def main(): reload(sys) # reload unicode decoder sys.setdefaultencoding('utf-8') # use utf-8 (param, word) = alfred.args() cityCode = '100010000' # Beijing if word.isspace(): url = "http://m.nuomi.com/client/gethotkeyword?cityid=%s&limit=20&client=ios&version=3.2.0" % (cityCode) else: word = OnlyCharNum(word) url = "http://m.nuomi.com/client/searchsuggest?k=%s&cityid=%s" % (word, cityCode) req = urllib2.Request(url) response = urllib2.urlopen(req) data = json.loads(response.read()) results = [] if word.isspace(): if len(data['keywords']) == 0: results.append(alfred.Item({'uid': 0, 'arg': word}, word, '', 'icon.png')) else: for i in range(0, len(data['keywords'])): results.append(alfred.Item({'uid': i, 'arg': data['keywords'][i]['keyword']}, data['keywords'][i]['keyword'], '', 'icon.png')) else: if len(data['data']) == 0: results.append(alfred.Item({'uid': 0, 'arg': word}, word, '', 'icon.png')) else: for i in range(0, len(data['data'])): results.append(alfred.Item({'uid': i, 'arg': data['data'][i]['t']}, data['data'][i]['t'], '', 'icon.png')) xml = alfred.xml(results) # compiles the XML answer alfred.write(xml)
def main(): reload(sys) # reload unicode decoder sys.setdefaultencoding('utf-8') # use utf-8 (param, word) = alfred.args() cityCode = '100010000' # Beijing if word.isspace(): url = "http://m.nuomi.com/client/gethotkeyword?cityid=%s&limit=20&client=ios&version=3.2.0" % ( cityCode) else: word = OnlyCharNum(word) url = "http://m.nuomi.com/client/searchsuggest?k=%s&cityid=%s" % ( word, cityCode) req = urllib2.Request(url) response = urllib2.urlopen(req) data = json.loads(response.read()) results = [] if word.isspace(): if len(data['keywords']) == 0: results.append( alfred.Item({ 'uid': 0, 'arg': word }, word, '', 'icon.png')) else: for i in range(0, len(data['keywords'])): results.append( alfred.Item( { 'uid': i, 'arg': data['keywords'][i]['keyword'] }, data['keywords'][i]['keyword'], '', 'icon.png')) else: if len(data['data']) == 0: results.append( alfred.Item({ 'uid': 0, 'arg': word }, word, '', 'icon.png')) else: for i in range(0, len(data['data'])): results.append( alfred.Item({ 'uid': i, 'arg': data['data'][i]['t'] }, data['data'][i]['t'], '', 'icon.png')) xml = alfred.xml(results) # compiles the XML answer alfred.write(xml)
def run(self): """Parse arguments and perform appropriate action""" parser = self._make_parser() try: args = parser.parse_args(alfred.args()) if args.list_folders: self.do_list_folders() elif args.add_folder: self.do_add_folder(args.add_folder) elif args.delete_folder: self.do_delete_folder(args.delete_folder) else: self.do_search(args.query) except InvalidConfiguration: self.display_message('Invalid configuration.', 'Please delete the configuration file.', icon=ICON_ERROR) return 1
def main(): query = alfred.args() if query: query = query[0] r = requests.get('%s/api/autocomplete_repos?q=%s' % (CODE_URL, query)) results = r.json() items = [] for repo in results.get('repos', []): items.append( alfred.Item( { u'valid': u'yes', u'arg': "%s%s" % (CODE_URL, repo['url']), u'uid': u'repo' }, u'%s' % repo['name'], u'Hit ENTER to the project', u'icon.png')) xml = alfred.xml(items, maxresults=10) print(xml) return 0
def main(): query = alfred.args() if query: query = query[0] r = requests.get('%s/api/autocomplete_repos?q=%s' % (CODE_URL, query)) results = r.json() items = [] for repo in results.get('repos', []): items.append(alfred.Item({ u'valid': u'yes', u'arg': "%s%s" % (CODE_URL, repo['url']), u'uid': u'repo' }, u'%s' % repo['name'], u'Hit ENTER to the project', u'icon.png' )) xml = alfred.xml(items, maxresults=10) print(xml) return 0
def main(): logging.basicConfig(filename=logfile(), level=logging.DEBUG) try: args = alfred.args() command, options = (args[0:]) if len(args) > 1 else (args[0], None) command_switch = { 'list': lambda x: list_compatible(), 'update': lambda x: list_updates(), 'reset': lambda x: reset(), 'log': lambda x: openlog(), 'download-all': lambda x: download_all(), 'download': lambda w: download(w, direct=True) } if command in command_switch: command_switch[command](options) else: show_options() except Exception, e: print str(e) autolog(str(e))
def main(): args = alfred.args() log.debug('args : {}'.format(args)) # recipients = [] mt = MailTo() if len(args): emails = [s.strip() for s in args[0].split(u',') if s.strip()] url = mt.build_url(emails) else: url = u'mailto:' log.debug(u'args : {}'.format(args)) log.debug('URL : {}'.format(url)) appname, path, bundleid = mt.default_app command = ['open'] if bundleid is not None: command.append('-b') command.append(bundleid) command.append(url) log.debug('command : {}'.format(command)) retcode = check_call(command) return retcode
def display_message(message, subtitle=None): """ Inform them that something's wrong """ if message is None: # Display same message as the placeholder message = 'Search your Kippt bookmarks' xml = alfred.xml([ alfred.Item( title=message, subtitle=subtitle, attributes={ 'uid': alfred.uid(0), }, icon='icon.png', ) ]) # compiles the XML answer alfred.write(xml) # writes the XML back to Alfred exit() if __name__ == "__main__": try: username = alfred.args()[0] api_key = alfred.args()[1] if not username or not api_key: raise ValueError() query_str = alfred.args()[2] client = kippt.user(username, api_key) except (IndexError, ValueError): display_message('Please add your Kippt username & API key to ' 'the workflow script filter') process(query_str)
m = terms terms = index['terms'][m] if not isinstance(terms, (list, tuple)): terms = [terms] outterm = [] for t in terms: url = _URL + '/%s/%s.html?highlight=%s' % (v, fnames[t], m) outterm.append([url, clean_HTML(html, titles[t]), m]) outmatch.extend(sorted(outterm, key=lambda x: x[1])) return outmatch if __name__ == '__main__': args = alfred.args() # clean if len(args) == 1: # get python version from URL v = re.search('docs.python.org/(\d)/.*', args[0]).group(1) if clean_index(v): print 'Index rebuilt!' else: print 'No internet connexion found, index not rebuilt.' else: v, query = args results = [] # define a function using the local pydoc define = os.path.exists('define.txt') if define:
def main(): from docopt import docopt args = alfred.args() log.debug(u'alfred.args : {}'.format(args)) args = docopt(__usage__, args) log.debug(u'docopt.args : {}'.format(args)) # application actions if args.get(u'config'): # show configuration show_config() # email client elif args.get(u'client'): # choose client query = args.get(u'<query>') if not query: query = u'' query = query.strip() choose_client(query) elif args.get(u'setclient'): # set default mail client path = args.get(u'<path>') log.debug(u'setclient : {!r}'.format(path)) mt = MailTo() if not path: mt.default_app = None print(u'System Default') else: mt.default_app = path appname = mt.default_app[0] print(appname) # email format elif args.get(u'format'): # set email format choose_format() elif args.get(u'setformat'): # set default format fmt = args.get(u'<format>') log.debug(u'setformat : {!r}'.format(fmt)) mt = MailTo() # if not fmt: # mt.use_contact_name = True # print(u'Default Format (Name & Email Address)') if fmt == u'name': mt.use_contact_name = True print(u'Default Format (Name & Email Address)') elif fmt == u'email': mt.use_contact_name = False print(u'Email Address Only') # other options elif args.get(u'delcache'): # delete settings file deleted = False if os.path.exists(settings.settings_path): os.unlink(settings.settings_path) print('Deleted settings', file=sys.stderr) deleted = True if os.path.exists(CACHEPATH): os.unlink(CACHEPATH) print('Deleted cache', file=sys.stderr) deleted = True if not deleted: print('No cache to delete', file=sys.stderr) elif args.get(u'dellog'): # delete logfile if os.path.exists(settings.log_path): os.unlink(settings.log_path) print('Deleted log file', file=sys.stderr) elif args.get(u'logon'): # turn on logging mt = MailTo() mt.logging = True print('Turned logging on', file=sys.stderr) elif args.get(u'logoff'): # turn off logging mt = MailTo() mt.logging = False print('Turned logging off', file=sys.stderr) elif args.get(u'openlog'): # open logfile check_call([u'open', settings.log_path]) elif args.get(u'help'): # show help in Alfred show_help() elif args.get(u'openhelp'): # open help file in browser open_help_file() elif args.get(u'version'): # print version print(open(os.path.join(os.path.dirname(__file__), 'version')).read().strip()) return 0
(uid, title, url, faviconid) = result yield alfred.Item({u'uid': alfred.uid(uid), u'arg': url}, title, url, icon(db, faviconid)) def sql(query): keywords = u"""\ select distinct moz_places.id, moz_bookmarks.title, moz_places.url, moz_places.favicon_id from moz_places inner join moz_bookmarks on moz_places.id = moz_bookmarks.fk inner join moz_keywords on moz_bookmarks.keyword_id = moz_keywords.id where %s""" % where(query, [u'moz_keywords.keyword']) bookmarks = u"""\ select distinct moz_places.id, moz_bookmarks.title, moz_places.url, moz_places.favicon_id from moz_places inner join moz_bookmarks on moz_places.id = moz_bookmarks.fk where %s""" % where(query, [u'moz_bookmarks.title', u'moz_places.url']) history = u"""\ select distinct moz_places.id, moz_places.title, moz_places.url, moz_places.favicon_id from moz_places inner join moz_inputhistory on moz_places.id = moz_inputhistory.place_id where %s""" % where(query, [u'moz_inputhistory.input', u'moz_places.title', u'moz_places.url']) joinTemplate = u"""\ inner join %(table)s on moz_places.id = %(table)s.%(field)s """ return u'\nunion\n'.join([keywords, bookmarks, history]) def where(query, fields): return combine(u'or', ('%s regexp "%s"' % (field, '.*%s' % '.*'.join(re.escape(c) for c in query.split(' '))) for field in fields)) (profile, query) = alfred.args() db = sqlite3.connect(places(profile)) alfred.write(alfred.xml(results(db, query), maxresults=_MAX_RESULTS))
'arg': arg, }, title = title, subtitle = subtitle, icon = 'icon.png' )) # print(results) xml = alfred.xml(results) alfred.write(xml) # name = u'messi' # rating = 98 # status = u'pace' # name = alfred.args()[0] name = alfred.args()[0] rating = '' status = '' if len(alfred.args()) == 2: try: (fake_name, rating) = alfred.args() rating = int(rating) except ValueError: error(title=u"请按照 <球员> <分数> <属性>输入", subtitle="pace, shoot, pass, dri, def, phy", arg=None) exit() elif len(alfred.args()) == 3: try: (fake_name, rating, status) = alfred.args() rating = int(rating) except ValueError: error(title=u"请按照 <球员> <分数> <属性>输入", subtitle="pace, shoot, pass, dri, def, phy", arg=None)
import plistlib import alfred _MAX_RESULTS = 20 _CACHE_EXPIRY = 24 * 60 * 60 # in seconds _CACHE = alfred.work(True) def combine(operator, iterable): return u'(%s)' % (u' %s ' % operator).join(iterable) def results(path, query): match = set() for root, dirs, files in os.walk(path): for file in files: if file in match: continue if file.find(query) > -1: match.add(file) parts = file.split('.') parts.pop() title = '.'.join(parts) pl = plistlib.readPlist(root + file) url = pl.URL yield alfred.Item({u'arg': root + file}, title, url, os.getcwd() + "/icon.png") (path, query) = alfred.args() alfred.write(alfred.xml(results(path, query), maxresults=_MAX_RESULTS))
def main(): args = alfred.args() if len(args): q = args[0].lstrip(u', ').strip() else: q = u'' log.debug(u'args : {} q : {!r}'.format(args, q)) if q == u'': # Compose empty mail item = alfred.Item( {u'valid':u'yes', u'arg':u'', u'uid':u'compose'}, u'Write new email', u'Hit ENTER to compose a new mail or start typing to add recipients', icon=u'icon.png' ) xml = alfred.xml([item]) log.debug(xml) print(xml) return 0 # Split out existing valid and invalid recipients q = q.lower() existing = u'' addresses = [] invalid_addresses = [] if u',' in q: addresses = [s.strip() for s in q.split(u',')] if len(addresses): existing = [] for email in addresses[:-1]: if not valid_email(email): invalid_addresses.append(email) else: existing.append(email) if len(existing): existing = u', '.join(existing) + u', ' else: existing = u'' q = addresses[-1] log.debug(u'args : {}, existing : {} addresses : {} invalid_addresses : {} q : {!r}'.format(args, existing, addresses, invalid_addresses, q)) contacts = [] hits = [] items = [] if q != u'': # Find matching contacts email_to_name, name_to_email, groups = get_contacts() # startswith # group names for name, email in groups: if name.lower().startswith(q) and (name, email) not in hits: hits.append((name, email)) # contact names for name, emails in name_to_email: if name.lower().startswith(q): for email in emails: if (name, email) not in hits: hits.append((name, email)) # for email, name in email_to_name: # if name.lower().startswith(q): # hits.append((name, email)) # email addresses for email, name in email_to_name: if email.lower().startswith(q) and (name, email) not in hits: hits.append((name, email)) # search in # groups for name, email in groups: if q in name.lower() and (name, email) not in hits: hits.append((name, email)) # contact names for name, emails in name_to_email: if q in name.lower(): for email in emails: if (name, email) not in hits: hits.append((name, email)) # email addresses for email, name in email_to_name: if q in email.lower() and (name, email) not in hits: hits.append((name, email)) # show errors first for email in invalid_addresses: item = alfred.Item( {u'valid':u'no'}, u'{} is not a valid email address'.format(email), u'Try something else', icon=u'warning.png' ) items.append(item) # q does not match anything if not len(hits): if valid_email(q) or (q == u'' and existing != u''): recipients = (existing + q).rstrip(u', ') item = alfred.Item( {u'valid':u'yes', u'arg':recipients}, u'Write mail to {}'.format(recipients), u'Hit ENTER to compose a new message', icon=u'icon.png' ) items.append(item) elif q != u'' and q not in KEYWORDS: # show error and offer to mail existing recipients item = alfred.Item( {u'valid':u'no'}, u'{} is not a valid email address'.format(q), u'Try something else', icon=u'warning.png' ) items.append(item) if existing: recipients = existing.rstrip(u', ') item = alfred.Item( {u'valid':u'yes', u'arg':recipients}, u'Write mail to {}'.format(recipients), u'Hit ENTER to compose a new message', icon=u'icon.png' ) items.append(item) xml = alfred.xml(items) print(xml) return 0 # got some matches, show them for name, email in hits: if email in addresses: continue if u', ' in email: # is a group icon = u'group.png' else: icon = u'icon.png' recipients = existing + email + u', ' item = alfred.Item( {u'valid':u'yes', u'arg':recipients, u'uid':recipients, u'autocomplete':recipients}, name, email, icon=icon ) items.append(item) if not len(items): # all results are in existing recipients, compose message to nobody recipients = existing + email + u', ' item = alfred.Item( {u'valid':u'yes', u'arg':recipients, u'autocomplete':recipients}, u'Write mail to {}'.format(recipients), u'Hit ENTER to compose a new message', icon=u'icon.png' ) items.append(item) xml = alfred.xml(items, maxresults=MAX_RESULTS) print(xml) return 0
def prompt(title="<amount> <currency> in <other currency>", subtitle="i.e. 123 EUR in USD", arg=None): alfred.write( alfred.xml([alfred.Item(attributes={"uid": alfred.uid(0), "arg": arg}, title=title, subtitle=subtitle)]) ) try: import settings except ImportError: prompt(title="no settings.py file found", subtitle="Did you follow the installation instructions?") exit() try: (value, from_curr, to, to_curr) = alfred.args() # proper decoding and unescaping of command line arguments except ValueError: prompt() exit() from_curr = from_curr.upper() to_curr = to_curr.upper() value = float(value.replace(",", ".")) # all possible currency ids CURR_IDS = [ u"DZD", u"NAD", u"GHS", u"EGP", u"BGN",
alfred.write(alfred.xml(infos, maxresults=10)) return # No extension base_exts = [".com", ".cn", ".net", ".me"] advanced_exts = [".org", ".tv", ".cc"] final_exts = base_exts if query == "all": final_exts = base_exts+advanced_exts for ext in final_exts: domain = keyword+ext result = domainsearch(domain) show_result(infos, domain, result) alfred.write(alfred.xml(infos, maxresults=10)) (parameter, query) = alfred.args() keyword = parameter.strip().encode('utf-8') query = query.strip().encode('utf-8') alfred_search(keyword, query) # alfred_search("heyuhao.com", None)
port = int(infile.read()) search_results = gsearch.search(query, port) for result in search_results: title = result.get('title', '').decode('utf-8') href = result.get('href', '').decode('utf-8') alfred_results.append(alfred.Item( title=title, subtitle=href, attributes={ 'uid': alfred.uid(index), 'arg': title + ';' + href, }, quicklookurl=href, icon='icon.png', )) index += 1 return alfred_results if __name__ == '__main__': try: query_str = ''.join(alfred.args()) except: query_str = None process(query_str)
#!/usr/bin/python # -*- coding: utf-8 -*- import alfred import urllib (cmd, rawstring) = alfred.args() if cmd == "en": handled = urllib.quote(rawstring) icon = "703B65EB-7EA7-40D9-8860-4BA3D2CF48A9.png" elif cmd == "de": handled = urllib.unquote(rawstring) icon = "AA6E0037-6E59-499D-ABE1-8C5BC0BC48B4.png" else: handled = rawstring icon = "icon.png" results = [ alfred.Item( attributes={"uid": alfred.uid(0), "arg": handled}, title=handled, subtitle=u"Enter to copy to clipboard", icon=icon, ) ] xml = alfred.xml(results) alfred.write(xml)
search_results = google.search(query, port) for result in search_results: title = result.get('title', '').decode('utf-8') href = result.get('href', '').decode('utf-8') alfred_results.append( alfred.Item( title=title, subtitle=href, attributes={ 'uid': alfred.uid(index), 'arg': title + ';' + href, }, icon='icon.png', quicklookurl=href, )) index += 1 return alfred_results if __name__ == '__main__': try: query_str = ''.join(alfred.args()) except: query_str = None process(query_str)
# # [2013/03/20] import subprocess import re import sys import alfred # regular expression entrySpliterRe = re.compile("^\*|^!\s+",re.M) lineSpliterRe = re.compile("\n\s+", re.M) # command line iCalBuddyProg = "./iCalBuddy -tf '%H:%M' -b '*' " parameter = alfred.args() # proper decoding and unescaping of command line arguments if len(parameter) >= 1: param = parameter[0] else: param = 0 progList = [] try: param = int(param) progList.append([iCalBuddyProg + "eventsToday+%d" % int(param), 'ical.png']) progList.append([iCalBuddyProg + "tasksDueBefore:today+%d" % (int(param)+1), 'reminder.png']) except ValueError: progList.append([iCalBuddyProg + "undatedUncompletedTasks", 'reminder.png'])
# 1937-01-01T12:00:27 ("%Y-%m-%dT%H:%M:%S", ''), # 1996-12-19T16:39:57-0800 ("%Y-%m-%dT%H:%M:%S%z", ''), ] for format, description in formats: item_value = value.datetime.strftime(format) results.append(alfred.Item( title=str(item_value), subtitle=description, attributes={ 'uid': alfred.uid(index), 'arg': item_value, }, icon='icon.png', )) index += 1 return results if __name__ == "__main__": try: query_str = alfred.args()[0] if len(alfred.args()) > 1: tf = alfred.args()[1] else: tf = 'Asia/Shanghai' except IndexError: query_str = None process(query_str, tf)
import alfred import json import urllib lovefilm, query = alfred.args() url = u'http://www.lovefilm.{lovefilm}/ajax/autocomplete.html?term={query}&category=all_titles'.format( lovefilm=str(lovefilm), query=str(query)) prefix = u'http://www.lovefilm.{lovefilm}'.format(lovefilm=lovefilm) json_result = json.load(urllib.urlopen(url)) results = [] if len(json_result["items"]) == 0: results.append(alfred.Item( attributes= {'uid': 'nothing-found', 'arg': ''}, title=u'Nothing found', subtitle=u'Please try again!', icon=('icon.png'))) for item in json_result["items"]: results.append(alfred.Item( attributes= {'uid': item["name"], 'arg': prefix+item["url"]}, title=item["name"], subtitle=u'view movie on LOVEFiLM', icon=('icon.png'))) xml = alfred.xml(results) alfred.write(xml)
# -*- coding: utf-8 -*- try: import alfred import sys sys.path.append('lib') from lib.pushbullet import Pushbullet from lib.pushbullet.errors import InvalidKeyError from lib.requests.exceptions import ConnectionError except ImportError as e: print e sys.exit() args = alfred.args() if len(args) != 3: print 'Wrong number of parameters.' sys.exit() apiKey = args[0] deviceName = args[1] text = args[2] try: api = Pushbullet(apiKey) except InvalidKeyError: print 'API key is invalid.' sys.exit() except ConnectionError: print 'Failed connecting to pushbullet.' sys.exit()
# -*- coding: utf-8 -*- import os from zipfile import ZipFile import alfred ARCHIVE = u'Archive' def zip(files): path = os.path.dirname(os.path.commonprefix(files)) zipfile = os.path.join(path, u'%s.zip' % ARCHIVE) with ZipFile(zipfile, 'a') as z: for file in files: z.write(file, os.path.join(ARCHIVE, file.replace(path, u'', 1))) return zipfile files = alfred.args()[0].split('\t') try: zipfile = zip(files) except Exception as e: alfred.write('Could not create archive: %s' % e) else: alfred.write('Archive created (%d files): %s' % (len(files), zipfile))
# Sun, 19 May 2002 15:21:36 ("%a, %d %b %Y %H:%M:%S", ''), # 1937-01-01T12:00:27 ("%Y-%m-%dT%H:%M:%S", ''), # 1996-12-19T16:39:57-0800 ("%Y-%m-%dT%H:%M:%S%z", ''), ] for format, description in formats: item_value = value.datetime.strftime(format) results.append( alfred.Item( title=str(item_value), subtitle=description, attributes={ 'uid': alfred.uid(index), 'arg': item_value, }, icon='icon.png', )) index += 1 return results if __name__ == "__main__": try: query_str = alfred.args()[0] except IndexError: query_str = None process(query_str)
for alg in algs: c_digest = getDigest(filename, alg) if digest == c_digest: match = True addResult( alg.upper() + ' MATCH for \'' + ntpath.basename(filename) + '\'', '[' + c_digest + ']', 'icons/green.png') if not match: addResult('NO MATCH for \'' + ntpath.basename(filename) + '\'', 'file may be corrupted!', 'icons/red.png') def showAllDigests(filename): global algs for alg in algs: c_digest = getDigest(filename, alg) addResult(alg.upper() + ':' + c_digest, ' Hit Enter to Copy to Clipboard', 'icons/orange.png', c_digest) # main (filename, digest) = alfred.args() if digest == 'all': showAllDigests(filename) else: checkDigests(filename, digest) alfred.write(alfred.xml(results))
import alfred import urllib2 import json def prompt(title="<amount> <currency> in <other currency>", subtitle="i.e. 123 EUR in USD", arg=None): alfred.write(alfred.xml([alfred.Item(attributes={'uid': alfred.uid(0), 'arg': arg}, title=title, subtitle=subtitle)])) try: import settings except ImportError: prompt(title="no settings.py file found", subtitle="Did you follow the installation instructions?") exit() try: (value, from_curr, to, to_curr) = alfred.args() # proper decoding and unescaping of command line arguments except ValueError: prompt() exit() from_curr = from_curr.upper() to_curr = to_curr.upper() value = float(value.replace(',', '.')) # all possible currency ids CURR_IDS = [u'DZD', u'NAD', u'GHS', u'EGP', u'BGN', u'PAB', u'BOB', u'DKK', u'BWP', u'LBP', u'TZS', u'VND', u'AOA', u'KHR', u'MYR', u'KYD', u'LYD', u'UAH', u'JOD', u'AWG', u'SAR', u'EUR', u'HKD', u'CHF', u'GIP', u'BYR', u'ALL', u'MRO', u'HRK', u'DJF', u'SZL', u'THB', u'XAF', u'BND', u'ISK', u'UYU', u'NIO', u'LAK', u'SYP', u'MAD', u'MZN', u'PHP', u'ZAR', u'NPR', u'ZWL', u'NGN', u'CRC', u'AED', u'EEK', u'MWK', u'LKR', u'PKR', u'HUF', u'BMD', u'LSL', u'MNT', u'AMD', u'UGX', u'QAR', u'XDR', u'JMD', u'GEL', u'SHP', u'AFN', u'SBD', u'KPW', u'TRY', u'BDT', u'YER', u'HTG', u'XOF', u'MGA', u'ANG', u'LRD', u'RWF', u'NOK', u'MOP', u'INR', u'MXN', u'CZK', u'TJS', u'BTC', u'BTN', u'COP', u'TMT', u'MUR', u'IDR', u'HNL', u'XPF', u'FJD', u'ETB', u'PEN', u'BZD', u'ILS', u'DOP', u'TWD', u'MDL', u'BSD', u'SEK', u'ZMK', u'JEP', u'AUD', u'SRD', u'CUP', u'CLF', u'BBD', u'KMF', u'KRW', u'GMD', u'VEF', u'GTQ', u'CLP', u'ZMW', u'LTL', u'CDF', u'XCD', u'KZT', u'RUB', u'XAG', u'TTD', u'OMR', u'BRL', u'MMK', u'PLN', u'PYG', u'KES', u'SVC', u'MKD', u'GBP', u'AZN', u'TOP', u'MVR', u'VUV', u'GNF', u'WST', u'IQD', u'ERN', u'BAM', u'SCR', u'CAD', u'CVE', u'KWD', u'BIF', u'PGK', u'SOS', u'SGD', u'UZS', u'STD', u'IRR', u'CNY', u'SLL', u'TND', u'GYD', u'MTL', u'NZD', u'FKP', u'LVL', u'USD', u'KGS', u'ARS', u'RON', u'RSD', u'BHD', u'JPY', u'SDG', u'XAU'] no_curr = [] if from_curr not in CURR_IDS: no_curr.append(from_curr)
:param query_str: :return: """ try: oid = ObjectId(query_str) except InvalidId: oid = None return oid # def alfred_items_for_value(oid): # index = 0 # alfred_items = [ # alfred.Item(title=str(oid), subtitle='Original ObjectId', attributes={ # 'uid': alfred.uid(index), # 'arg': oid, # }, icon='icon.png') # ] # return alfred_items if __name__ == '__main__': try: arg = alfred.args()[0] except IndexError: arg = None process(arg)
attributes = {'valid':"no"}, icon=u"lunar.png" )) elif mode_type == mode.convert_lunar: isleap = targetdate.lunarleap and '(윤달)' or '' results.append(alfred.Item(title=targetdate.strftime('음력 %LY년 %Lm월 %Ld일') + isleap, subtitle=u"음력날짜는...", attributes = {'valid':"no"}, icon=u"lunar.png" )) results.append(alfred.Item(title=targetdate.strftime('양력 %Y년 %m월 %d일 %a'), subtitle=u"양력날짜는...", attributes = {'valid':"no"}, icon=u"solar.png")) elif mode_type == mode.error: results.append(alfred.Item(title=error_str, subtitle=u"오류 메시지", attributes = {'valid':"no"}, icon=u"icon.png")) print alfred.xml(results) if __name__ == '__main__': try: query = alfred.args()[0] except IndexError: query = "" process(query)
# -*- coding: utf-8 -*- import alfred inStr = alfred.args()[0] inNum = int(inStr, 2) outStr8 = str(oct(inNum)) outStr10 = str(inNum) outStr16 = str(hex(inNum)) results = [alfred.Item({u'uid':alfred.uid(1), u'arg':outStr8}, 'octal: '+outStr8, ''), alfred.Item({u'uid':alfred.uid(2), u'arg':outStr10}, 'decimal: '+outStr10, ''), alfred.Item({u'uid':alfred.uid(3), u'arg':outStr16}, 'hex: '+outStr16, '')] xml = alfred.xml(results) alfred.write(xml)
import subprocess import alfred def list_apps(arg): apps = subprocess.check_output("ios-deploy -B | sort", stderr=subprocess.STDOUT, shell=True) apps = apps.rstrip().split('\n') items = [] for app in apps: if arg is '' or app.startswith(arg): items.append(alfred.Item({'arg': app}, app, '')) alfred.write(alfred.xml(items)) if __name__ == '__main__': list_apps(alfred.args()[0])
def getDigest(filename, alg): digest = commands.getstatusoutput('openssl dgst -'+ alg +' ' + filename) return digest[1].split('= ')[1] def checkDigests(filename, digest): global algs match = False for alg in algs: c_digest = getDigest(filename, alg) if digest == c_digest: match = True addResult(alg.upper() + ' MATCH for \''+ ntpath.basename(filename) + '\'', '[' + c_digest + ']', 'icons/green.png') if not match: addResult('NO MATCH for \''+ ntpath.basename(filename) + '\'', 'file may be corrupted!', 'icons/red.png') def showAllDigests(filename): global algs for alg in algs: c_digest = getDigest(filename, alg) addResult(alg.upper() + ':' + c_digest, ' Hit Enter to Copy to Clipboard', 'icons/orange.png', c_digest) # main (filename, digest) = alfred.args() if digest == 'all': showAllDigests(filename) else: checkDigests(filename, digest) alfred.write(alfred.xml(results))
def main(action, query): # If the configuration file doesn't exist, create an empty one if not os.path.isfile(_CONFIG_FILE): create_config() alfred.write(alfred.xml(config_file_is_empty())) return try: config = get_config() if not config.sections() and action != 'add': # If the configuration file is empty, tell the user to add secrets to it alfred.write(alfred.xml(config_file_is_empty())) return except Exception as e: alfred.write(alfred.xml([alfred.Item({u'uid': alfred.uid(0), u'arg': '', u'ignore': 'yes'}, "~/.gauth: Invalid syntax", str(e).replace('\n', ' '), "error.png")])) sys.exit(1) if action == 'list' and not is_command(query): alfred.write(alfred.xml(list_accounts(config, query), maxresults=_MAX_RESULTS)) elif action == 'add': alfred.write(add_account(config, query)) if __name__ == "__main__": main(action=alfred.args()[0], query=alfred.args()[1])
def __init__(self): """ Setup """ # Read bundle info and config path self.bundle_id = plistlib.readPlist( os.path.abspath('./info.plist'))['bundleid'] self.placeholder = '' for x in plistlib.readPlist( os.path.abspath('./info.plist'))['objects']: if x['type'] == 'alfred.workflow.input.scriptfilter': self.placeholder = x['config']['title'] self.config_path = '%s/%s/' % ( os.path.expanduser(alfred_config_path).rstrip('/'), self.bundle_id, ) # Handle init if alfred.args()[0] == 'run_config': # Create config if doesn't exist and then open in textedit try: os.makedirs(self.config_path) except OSError: # Exists pass if not os.path.exists(self.config_path + config_filename): config_file = open(self.config_path + config_filename, 'w') # dump default config config_file.write(json.dumps(self.config, indent=4)) config_file.close() call(['open', '-a', 'TextEdit', self.config_path + config_filename]) else: # Read existing config config_file = None try: config_file = open(self.config_path + config_filename, 'r') config_data = json.loads(''.join(config_file.readlines())) except IOError: self.display_config_prompt() # Config file doesnt exist except ValueError: self.display_config_prompt('Invalid configuration', 'Config contains invalid JSON') finally: if config_file: config_file.close() try: self.read_config(config_data) except (ValueError, TypeError): self.display_config_prompt('Invalid configuration') # Get query query_str = alfred.args()[1].strip() # Run if query_str == "config": self.display_config_prompt() else: self.process(query_str)
'arg': f, 'autocomplete': f }, icon=u"icon.png") for f in appnames if query in f.lower() ] results.insert( 0, alfred.Item( title=u"Tidy up LaunchPad : tdl [appname]", subtitle= "Hide app icon from LaunchPad. It wouldn't delete App itself.", attributes={'valid': "no"}, icon=u"icon.png")) alfred.write(alfred.xml(results, maxresults=None)) def process(query): appnames = read_appnames() write_output(appnames, query=query) if __name__ == '__main__': try: query = alfred.args()[0].lower().strip() except IndexError: query = u"" process(query)
import json import os import re import urllib import alfred import pocket (action, query) = alfred.args() # proper decoding and unescaping of command line arguments def login(): code = pocket.getRequestCode() with open('code.json', 'w') as myFile: myFile.write(json.dumps(code)) results = [alfred.Item( attributes={'uid': alfred.uid(0), 'arg': code["code"]}, title='Login!', icon='icon.png', subtitle=u'Login with Pocket.com (you will be taken to pocket.com)' )] # a single Alfred result xml = alfred.xml(results) # compiles the XML answer alfred.write(xml) # writes the XML back to Alfred def post(): obj = applescript(query) pocket.post(obj) def applescript(argument): if argument == "isChrome":
result = domainsearch(keyword) show_result(infos, keyword, result) alfred.write(alfred.xml(infos, maxresults=10)) return # No extension base_exts = [".com", ".cn", ".net", ".me"] advanced_exts = [".org", ".tv", ".cc"] final_exts = base_exts if query == "all": final_exts = base_exts + advanced_exts for ext in final_exts: domain = keyword + ext result = domainsearch(domain) show_result(infos, domain, result) alfred.write(alfred.xml(infos, maxresults=10)) (parameter, query) = alfred.args() keyword = parameter.strip().encode('utf-8') query = query.strip().encode('utf-8') alfred_search(keyword, query) # alfred_search("heyuhao.com", None)
query, [u'moz_inputhistory.input', u'moz_places.title', u'moz_places.url']) browsing_history = u"""\ select distinct moz_places.id, moz_places.title, moz_places.url, moz_places.url_hash from moz_places inner join moz_historyvisits on moz_places.id = moz_historyvisits.place_id where %s and moz_places.title notnull""" % where( query, [u'moz_places.title', u'moz_places.url']) joinTemplate = u"""\ inner join %(table)s on moz_places.id = %(table)s.%(field)s """ return u'\nunion\n'.join( [keywords, bookmarks, input_history, browsing_history]) def where(query, fields): return combine( u'or', ('%s regexp "%s"' % (field, '.*%s' % '.*'.join(re.escape(c) for c in query.split(' '))) for field in fields)) (profile, query) = alfred.args() places_db = sqlite3.connect(places(profile)) favicons_db = sqlite3.connect(favicons(profile)) alfred.write( alfred.xml(results(places_db, favicons_db, query), maxresults=_MAX_RESULTS))
isleap = targetdate.lunarleap and '(윤달)' or '' results.append( alfred.Item(title=targetdate.strftime('음력 %LY년 %Lm월 %Ld일') + isleap, subtitle=u"음력날짜는...", attributes={'valid': "no"}, icon=u"lunar.png")) results.append( alfred.Item(title=targetdate.strftime('양력 %Y년 %m월 %d일 %a'), subtitle=u"양력날짜는...", attributes={'valid': "no"}, icon=u"solar.png")) elif mode_type == mode.error: results.append( alfred.Item(title=error_str, subtitle=u"오류 메시지", attributes={'valid': "no"}, icon=u"icon.png")) print alfred.xml(results) if __name__ == '__main__': try: query = alfred.args()[0] except IndexError: query = "" process(query)
# Date: June 12, 2013 # Author: Benjamin Gray # Purpose: Searches anki note fields and displays question and answer in alfred import alfred import sqlite3 import string MAX_RESULTS = 50 (pathToCollection, query) = alfred.args() # get the cards from the database db = sqlite3.connect(pathToCollection) q = "select flds, id from notes where flds like '%" + query + "%'" rs = db.execute(q) results = [] for r in rs: string = r[0] cid = unicode(r[1]) fields = string.split("\x1f") question = fields[0] answer = fields[1] # write results to item list results.append( alfred.Item(attributes={ 'uid': alfred.uid(0), 'arg': cid }, title=question,
#!/usr/bin/env python # encoding: utf-8 """ importbibtex.py Created by Andrew Ning on 2013-11-17. """ from common import importBibTeXIntoBibDesk import alfred bibtex = alfred.args()[0] importBibTeXIntoBibDesk(bibtex)
import json import os import re import urllib import alfred import pocket (action, query ) = alfred.args() # proper decoding and unescaping of command line arguments def login(): code = pocket.getRequestCode() with open('code.json', 'w') as myFile: myFile.write(json.dumps(code)) results = [ alfred.Item( attributes={ 'uid': alfred.uid(0), 'arg': code["code"] }, title='Login!', icon='icon.png', subtitle=u'Login with Pocket.com (you will be taken to pocket.com)' ) ] # a single Alfred result xml = alfred.xml(results) # compiles the XML answer alfred.write(xml) # writes the XML back to Alfred
#!/usr/bin/python #coding: utf-8 import os import alfred def results(arg, com): uid = 0 tasks = os.popen('./todo.sh ls' + com + ' ' + arg).read().splitlines() if com == 'prj': uid += 1 yield alfred.Item({'uid': alfred.uid(uid), 'arg': ''}, 'ALL Projects', 'Enter to display all ...', 'EBD226C2-1E22-4F65-BD43-556E6EF3C463.png') for task in tasks: uid += 1 task = task.rstrip() yield alfred.Item({'uid': alfred.uid(uid), 'arg': task}, task, 'Enter to display' + task, 'EBD226C2-1E22-4F65-BD43-556E6EF3C463.png') (query, com) = alfred.args() alfred.write(alfred.xml(results(query, com)))
# 19 May 2002 15:21:36 ("%d %b %Y %H:%M:%S", ''), # Sun, 19 May 2002 15:21:36 ("%a, %d %b %Y %H:%M:%S", ''), # 1937-01-01T12:00:27 ("%Y-%m-%dT%H:%M:%S", ''), # 1996-12-19T16:39:57-0800 ("%Y-%m-%dT%H:%M:%S%z", ''), ] for format, description in formats: item_value = value.datetime.strftime(format) results.append(alfred.Item( title=str(item_value), subtitle=description, attributes={ 'uid': alfred.uid(index), 'arg': item_value, }, icon='icon.png', )) index += 1 return results if __name__ == "__main__": try: query_str = alfred.args()[0] except IndexError: query_str = None process(query_str)
def __init__(self): """ Setup """ # Read bundle info and config path self.bundle_id = plistlib.readPlist( os.path.abspath('./info.plist'))['bundleid'] self.placeholder = '' for x in plistlib.readPlist( os.path.abspath('./info.plist'))['objects']: if x['type'] == 'alfred.workflow.input.scriptfilter': self.placeholder = x['config']['title'] self.config_path = '%s/%s/' % ( os.path.expanduser(alfred_config_path).rstrip('/'), self.bundle_id, ) # Handle init if alfred.args()[0] == 'run_config': # Create config if doesn't exist and then open in textedit try: os.makedirs(self.config_path) except OSError: # Exists pass if not os.path.exists(self.config_path + config_filename): config_file = open(self.config_path + config_filename, 'w') # dump default config config_file.write(json.dumps(self.config, indent=4)) config_file.close() call( ['open', '-a', 'TextEdit', self.config_path + config_filename]) else: # Read existing config config_file = None try: config_file = open(self.config_path + config_filename, 'r') config_data = json.loads(''.join(config_file.readlines())) except IOError: self.display_config_prompt() # Config file doesnt exist except ValueError: self.display_config_prompt('Invalid configuration', 'Config contains invalid JSON') finally: if config_file: config_file.close() try: self.read_config(config_data) except (ValueError, TypeError): self.display_config_prompt('Invalid configuration') # Get query query_str = alfred.args()[1].strip() # Run if query_str == "config": self.display_config_prompt() else: self.process(query_str)
# Date: June 12, 2013 # Author: Benjamin Gray # Purpose: Searches anki note fields and displays question and answer in alfred import alfred import sqlite3 import string MAX_RESULTS = 50 (pathToCollection, query) = alfred.args() # get the cards from the database db = sqlite3.connect(pathToCollection) q = "select flds, id from notes where flds like '%" + query + "%'" rs = db.execute(q) results = [] for r in rs: string = r[0] cid = unicode(r[1]) fields = string.split("\x1f") question = fields[0] answer = fields[1] # write results to item list results.append( alfred.Item( attributes= {'uid': alfred.uid(0), 'arg': cid}, title=question, subtitle=answer, icon='Anki.png' )) # a single Alfred result
return sorted(appnames) def write_output(appnames,query): results = [alfred.Item(title=f, subtitle="", attributes = {'arg':f, 'autocomplete':f}, icon=u"icon.png" ) for f in appnames if query in f.lower()] results.insert(0, alfred.Item(title=u"Tidy up LaunchPad : tdl [appname]", subtitle="Hide app icon from LaunchPad. It wouldn't delete App itself.", attributes = {'valid':"no"}, icon=u"icon.png" )) alfred.write(alfred.xml(results,maxresults=None)) def process(query): appnames = read_appnames() write_output(appnames, query=query) if __name__ == '__main__': try: query = alfred.args()[0].lower().strip() except IndexError: query = u"" process(query)