Search is not available for this dataset
text
stringlengths
75
104k
def new_driver(browser_name, *args, **kwargs): """Instantiates a new WebDriver instance, determining class by environment variables """ if browser_name == FIREFOX: return webdriver.Firefox(*args, **kwargs) # elif options['local'] and options['browser_name'] == CHROME: ...
def build_follow_url(host=None, **params): """ Build a URL for the /follow page """ # template = '?{params}' config = ExampleConfig() template = '/follow?{params}' if not host: host = config.get('example_web_hostname') return ExampleUrlBuild...
def encode_collection(collection, encoding='utf-8'): """Encodes all the string keys and values in a collection with specified encoding""" if isinstance(collection, dict): return dict((encode_collection(key), encode_collection(value)) for key, value in collection.iteritems()) elif isinstance(collect...
def get_delimited_string_from_list(_list, delimiter=', ', wrap_values_with_char=None, wrap_strings_with_char=None): """Given a list, returns a string representation of that list with specified delimiter and optional string chars _list -- the list or tuple to stringify delimiter -- the the character to sepe...
def execute_script(self, string, args=None): """ Execute script passed in to function @type string: str @value string: Script to execute @type args: dict @value args: Dictionary representing command line args @rtype: int @rtype: ...
def execute_template(self, template_name, variables, args=None): """ Execute script from a template @type template_name: str @value template_name: Script template to implement @type args: dict @value args: Dictionary representing command line ...
def execute_template_and_return_result(self, template_name, variables, args=None): """ Execute script from a template and return result @type template_name: str @value template_name: Script template to implement @type variables: dict @value variables: D...
def build_js_from_template(self, template_file, variables): """ Build a JS script from a template and args @type template_file: str @param template_file: Script template to implement; can be the name of a built-in script or full filepath to a js file...
def build(template='/', host=None, scheme=None, port=None, **template_vars): """Builds a url with a string template and template variables; relative path if host is None, abs otherwise: template format: "/staticendpoint/{dynamic_endpoint}?{params}" """ # TODO: refactor to build_absol...
def poll(function, step=0.5, timeout=3, ignore_exceptions=(), exception_message='', message_builder=None, args=(), kwargs=None, ontimeout=()): """Calls the function until bool(return value) is truthy @param step: Wait time between each function call @param timeout: Max amount of time that will ela...
def build(self, **variables): """Formats the locator with specified parameters""" return Locator(self.by, self.locator.format(**variables), self.description)
def random_words_string(count=1, maxchars=None, sep=''): """Gets a """ nouns = sep.join([random_word() for x in xrange(0, count)]) if maxchars is not None and nouns > maxchars: nouns = nouns[0:maxchars-1] return nouns
def is_subdomain(domain, reference): """Tests if a hostname is a subdomain of a reference hostname e.g. www.domain.com is subdomain of reference @param domain: Domain to test if it is a subdomain @param reference: Reference "parent" domain """ index_of_reference = domain.find(reference) if ...
def dump_requestdriver_cookies_into_webdriver(requestdriver, webdriverwrapper, handle_sub_domain=True): """Adds all cookies in the RequestDriver session to Webdriver @type requestdriver: RequestDriver @param requestdriver: RequestDriver with cookies @type webdriverwrapper: WebDriverWrapper @param w...
def dump_webdriver_cookies_into_requestdriver(requestdriver, webdriverwrapper): """Adds all cookies in the Webdriver session to requestdriver @type requestdriver: RequestDriver @param requestdriver: RequestDriver with cookies @type webdriver: WebDriverWrapper @param webdriver: WebDriverWrapper to r...
def get_firefox_binary(): """Gets the firefox binary @rtype: FirefoxBinary """ browser_config = BrowserConfig() constants_config = ConstantsConfig() log_dir = os.path.join(constants_config.get('logs_dir'), 'firefox') create_directory(log_dir) log_path = os.path.join(log_dir, '{}_{}.log...
def _log_fail_callback(driver, *args, **kwargs): """Raises an assertion error if the page has severe console errors @param driver: ShapewaysDriver @return: None """ try: logs = driver.get_browser_log(levels=[BROWSER_LOG_LEVEL_SEVERE]) failure_message = 'There were severe console er...
def clone_and_update(self, **kwargs): """Clones the object and updates the clone with the args @param kwargs: Keyword arguments to set @return: The cloned copy with updated values """ cloned = self.clone() cloned.update(**kwargs) return cloned
def message(self): """ Render the body of the message to a string. """ template_name = self.template_name() if \ callable(self.template_name) \ else self.template_name return loader.render_to_string( template_name, self.get_context(), request=...
def subject(self): """ Render the subject of the message to a string. """ template_name = self.subject_template_name() if \ callable(self.subject_template_name) \ else self.subject_template_name subject = loader.render_to_string( template_name...
def get_context(self): """ Return the context used to render the templates for the email subject and body. By default, this context includes: * All of the validated values in the form, as variables of the same names as their fields. * The current ``Site`` obj...
def get_message_dict(self): """ Generate the various parts of the message and return them in a dictionary, suitable for passing directly as keyword arguments to ``django.core.mail.send_mail()``. By default, the following values are returned: * ``from_email`` * ...
def initialise_shopify_session(): """ Initialise the Shopify session with the Shopify App's API credentials. """ if not settings.SHOPIFY_APP_API_KEY or not settings.SHOPIFY_APP_API_SECRET: raise ImproperlyConfigured("SHOPIFY_APP_API_KEY and SHOPIFY_APP_API_SECRET must be set in settings") sh...
def anonymous_required(function=None, redirect_url=None): """ Decorator requiring the current user to be anonymous (not logged in). """ if not redirect_url: redirect_url = settings.LOGIN_REDIRECT_URL actual_decorator = user_passes_test( is_anonymous, login_url=redirect_url, ...
def login_required(f, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): """ Decorator that wraps django.contrib.auth.decorators.login_required, but supports extracting Shopify's authentication query parameters (`shop`, `timestamp`, `signature` and `hmac`) and passing them on to the login URL (instea...
def create_user(self, myshopify_domain, password=None): """ Creates and saves a ShopUser with the given domain and password. """ if not myshopify_domain: raise ValueError('ShopUsers must have a myshopify domain') user = self.model(myshopify_domain=myshopify_domain) ...
def add_query_parameters_to_url(url, query_parameters): """ Merge a dictionary of query parameters into the given URL. Ensures all parameters are sorted in dictionary order when returning the URL. """ # Parse the given URL into parts. url_parts = urllib.parse.urlparse(url) # Parse existing ...
def bind(self, event_name, callback, *args, **kwargs): """Bind an event to a callback :param event_name: The name of the event to bind to. :type event_name: str :param callback: The callback to notify of this event. """ self.event_callbacks[event_name].append((callback,...
def send_event(self, event_name, data, channel_name=None): """Send an event to the Pusher server. :param str event_name: :param Any data: :param str channel_name: """ event = {'event': event_name, 'data': data} if channel_name: event['channel'] = chan...
def trigger(self, event_name, data): """Trigger an event on this channel. Only available for private or presence channels :param event_name: The name of the event. Must begin with 'client-'' :type event_name: str :param data: The data to send with the event. """ ...
def subscribe(self, channel_name, auth=None): """Subscribe to a channel. :param str channel_name: The name of the channel to subscribe to. :param str auth: The token to use if authenticated externally. :rtype: pysher.Channel """ data = {'channel': channel_name} i...
def unsubscribe(self, channel_name): """Unsubscribe from a channel :param str channel_name: The name of the channel to unsubscribe from. """ if channel_name in self.channels: self.connection.send_event( 'pusher:unsubscribe', { 'channel': c...
def _connection_handler(self, event_name, data, channel_name): """Handle incoming data. :param str event_name: Name of the event. :param Any data: Data received. :param str channel_name: Name of the channel this event and data belongs to. """ if channel_name in self.chan...
def _reconnect_handler(self): """Handle a reconnect.""" for channel_name, channel in self.channels.items(): data = {'channel': channel_name} if channel.auth: data['auth'] = channel.auth self.connection.send_event('pusher:subscribe', data)
def _generate_auth_token(self, channel_name): """Generate a token for authentication with the given channel. :param str channel_name: Name of the channel to generate a signature for. :rtype: str """ subject = "{}:{}".format(self.connection.socket_id, channel_name) h = hm...
def _generate_presence_token(self, channel_name): """Generate a presence token. :param str channel_name: Name of the channel to generate a signature for. :rtype: str """ subject = "{}:{}:{}".format(self.connection.socket_id, channel_name, json.dumps(self.user_data)) h = ...
def pos(self, element = None): ''' Tries to decide about the part of speech. ''' tags = [] if element: if element.startswith(('de ', 'het ', 'het/de', 'de/het')) and not re.search('\[[\w|\s][\w|\s]+\]', element.split('\r\n')[0], re.U): tags.append('NN') if re.search('[\w|\s|/]+ \| [\w|\s|/]+ - [\w|\s|/...
def articles(self): ''' Tries to scrape the correct articles for singular and plural from uitmuntend.nl. ''' result = [None, None] element = self._first('NN') if element: element = element.split('\r\n')[0] if ' | ' in element: # This means there is a plural singular, plural = element.split(' | ')...
def plural(self): ''' Tries to scrape the plural version from uitmuntend.nl. ''' element = self._first('NN') if element: element = element.split('\r\n')[0] if ' | ' in element: # This means there is a plural singular, plural = element.split(' | ') return [plural.split(' ')[1]] else: # Th...
def download(url, filename, overwrite = False): ''' Downloads a file via HTTP. ''' from requests import get from os.path import exists debug('Downloading ' + unicode(url) + '...') data = get(url) if data.status_code == 200: if not exists(filename) or overwrite: f = open(filename, 'wb') f.write(data.cont...
def warning(message): ''' Prints a message if warning mode is enabled. ''' import lltk.config as config if config['warnings']: try: from termcolor import colored except ImportError: def colored(message, color): return message print colored('@LLTK-WARNING: ' + message, 'red')
def trace(f, *args, **kwargs): ''' Decorator used to trace function calls for debugging purposes. ''' print 'Calling %s() with args %s, %s ' % (f.__name__, args, kwargs) return f(*args,**kwargs)
def articles(self): ''' Tries to scrape the correct articles for singular and plural from vandale.nl. ''' result = [None, None] element = self._first('NN') if element: if re.search('(de|het/?de|het);', element, re.U): result[0] = re.findall('(de|het/?de|het);', element, re.U)[0].split('/') if re.sear...
def plural(self): ''' Tries to scrape the plural version from vandale.nl. ''' element = self._first('NN') if element: if re.search('meervoud: ([\w|\s|\'|\-|,]+)', element, re.U): results = re.search('meervoud: ([\w|\s|\'|\-|,]+)', element, re.U).groups()[0].split(', ') results = [x.replace('ook ', '')...
def miniaturize(self): ''' Tries to scrape the miniaturized version from vandale.nl. ''' element = self._first('NN') if element: if re.search('verkleinwoord: (\w+)', element, re.U): return re.findall('verkleinwoord: (\w+)', element, re.U) else: return [''] return [None]
def _normalize(self, string): ''' Returns a sanitized string. ''' string = super(VerbixDe, self)._normalize(string) string = string.replace('sie; Sie', 'sie') string = string.strip() return string
def pos(self): ''' Tries to decide about the part of speech. ''' tags = [] if self.tree.xpath('//div[@class="grad733100"]/h2[@class="inline"]//text()'): info = self.tree.xpath('//div[@class="grad733100"]/h2[@class="inline"]')[0].text_content() info = info.strip('I ') if info.startswith(('de', 'het')): ...
def _normalize(self, string): ''' Returns a sanitized string. ''' string = super(VerbixFr, self)._normalize(string) string = string.replace('il; elle', 'il/elle') string = string.replace('ils; elles', 'ils/elles') string = string.strip() return string
def pos(self, element = None): ''' Tries to decide about the part of speech. ''' tags = [] if element: if re.search('[\w|\s]+ [m|f]\.', element, re.U): tags.append('NN') if '[VERB]' in element: tags.append('VB') if 'adj.' in element and re.search('([\w|\s]+, [\w|\s]+)', element, re.U): tags....
def gender(self): ''' Tries to scrape the gender for a given noun from leo.org. ''' element = self._first('NN') if element: if re.search('([m|f|n)])\.', element, re.U): genus = re.findall('([m|f|n)])\.', element, re.U)[0] return genus
def isempty(result): ''' Finds out if a scraping result should be considered empty. ''' if isinstance(result, list): for element in result: if isinstance(element, list): if not isempty(element): return False else: if element is not None: return False else: if result is not None: retur...
def method2pos(method): ''' Returns a list of valid POS-tags for a given method. ''' if method in ('articles', 'plural', 'miniaturize', 'gender'): pos = ['NN'] elif method in ('conjugate',): pos = ['VB'] elif method in ('comparative, superlative'): pos = ['JJ'] else: pos = ['*'] return pos
def register(scraper): ''' Registers a scraper to make it available for the generic scraping interface. ''' global scrapers language = scraper('').language if not language: raise Exception('No language specified for your scraper.') if scrapers.has_key(language): scrapers[language].append(scraper) else: scr...
def discover(language): ''' Discovers all registered scrapers to be used for the generic scraping interface. ''' debug('Discovering scrapers for \'%s\'...' % (language,)) global scrapers, discovered for language in scrapers.iterkeys(): discovered[language] = {} for scraper in scrapers[language]: blacklist =...
def scrape(language, method, word, *args, **kwargs): ''' Uses custom scrapers and calls provided method. ''' scraper = Scrape(language, word) if hasattr(scraper, method): function = getattr(scraper, method) if callable(function): return function(*args, **kwargs) else: raise NotImplementedError('The method...
def iterscrapers(self, method, mode = None): ''' Iterates over all available scrapers. ''' global discovered if discovered.has_key(self.language) and discovered[self.language].has_key(method): for Scraper in discovered[self.language][method]: yield Scraper
def merge(self, elements): ''' Merges all scraping results to a list sorted by frequency of occurrence. ''' from collections import Counter from lltk.utils import list2tuple, tuple2list # The list2tuple conversion is necessary because mutable objects (e.g. lists) are not hashable merged = tuple2list([value f...
def clean(self, elements): ''' Removes empty or incomplete answers. ''' cleanelements = [] for i in xrange(len(elements)): if isempty(elements[i]): return [] next = elements[i] if isinstance(elements[i], (list, tuple)): next = self.clean(elements[i]) if next: cleanelements.append(elements...
def _needs_download(self, f): ''' Decorator used to make sure that the downloading happens prior to running the task. ''' @wraps(f) def wrapper(self, *args, **kwargs): if not self.isdownloaded(): self.download() return f(self, *args, **kwargs) return wrapper
def download(self): ''' Downloads HTML from url. ''' self.page = requests.get(self.url) self.tree = html.fromstring(self.page.text)
def _needs_elements(self, f): ''' Decorator used to make sure that there are elements prior to running the task. ''' @wraps(f) def wrapper(self, *args, **kwargs): if self.elements == None: self.getelements() return f(self, *args, **kwargs) return wrapper
def _first(self, tag): ''' Returns the first element with required POS-tag. ''' self.getelements() for element in self.elements: if tag in self.pos(element): return element return None
def _normalize(self, string): ''' Returns a sanitized string. ''' string = string.replace(u'\xb7', '') string = string.replace(u'\u0331', '') string = string.replace(u'\u0323', '') string = string.strip(' \n\rI.') return string
def pos(self, element = None): ''' Tries to decide about the part of speech. ''' tags = [] if element: if element.startswith(('der', 'die', 'das')): tags.append('NN') if ' VERB' in element: tags.append('VB') if ' ADJ' in element: tags.append('JJ') else: for element in self.elements: ...
def articles(self): ''' Tries to scrape the correct articles for singular and plural from de.pons.eu. ''' result = [None, None] element = self._first('NN') if element: result[0] = [element.split(' ')[0].replace('(die)', '').strip()] if 'kein Plur' in element: # There is no plural result[1] = ['']...
def plural(self): ''' Tries to scrape the plural version from pons.eu. ''' element = self._first('NN') if element: if 'kein Plur' in element: # There is no plural return [''] if re.search(', ([\w|\s|/]+)>', element, re.U): # Plural form is provided return re.findall(', ([\w|\s|/]+)>', eleme...
def reference(language, word): ''' Returns the articles (singular and plural) combined with singular and plural for a given noun. ''' sg, pl, art = word, '/'.join(plural(language, word) or ['-']), [[''], ['']] art[0], art[1] = articles(language, word) or (['-'], ['-']) result = ['%s %s' % ('/'.join(art[0]), sg), ...
def translate(src, dest, word): ''' Translates a word using Google Translate. ''' results = [] try: from textblob import TextBlob results.append(TextBlob(word).translate(from_lang = src, to = dest).string) except ImportError: pass if not results: return [None] return results
def audiosamples(language, word, key = ''): ''' Returns a list of URLs to suitable audiosamples for a given word. ''' from lltk.audiosamples import forvo, google urls = [] urls += forvo(language, word, key) urls += google(language, word) return urls
def images(language, word, n = 20, *args, **kwargs): ''' Returns a list of URLs to suitable images for a given word.''' from lltk.images import google return google(language, word, n, *args, **kwargs)
def articles(word): ''' Returns the articles (singular and plural) for a given noun. ''' from pattern.it import article result = [[None], [None]] genus = gender(word) or 'f' result[0] = [article(word, function = 'definite', gender = genus)] result[1] = [article(plural(word)[0], function = 'definite', gender = (...
def google(language, word, n = 8, *args, **kwargs): ''' Downloads suitable images for a given word from Google Images. ''' if not kwargs.has_key('start'): kwargs['start'] = 0 if not kwargs.has_key('itype'): kwargs['itype'] = 'photo|clipart|lineart' if not kwargs.has_key('isize'): kwargs['isize'] = 'small|med...
def _normalize(self, string): ''' Returns a sanitized string. ''' string = string.replace(u'\xa0', '') string = string.strip() return string
def _extract(self, identifier): ''' Extracts data from conjugation table. ''' conjugation = [] if self.tree.xpath('//p/b[normalize-space(text()) = "' + identifier.decode('utf-8') + '"]'): p = self.tree.xpath('//p/b[normalize-space(text()) = "' + identifier.decode('utf-8') + '"]')[0].getparent() for font in...
def conjugate(self, tense = 'present'): ''' Tries to conjugate a given verb using verbix.com.''' if self.tenses.has_key(tense): return self._extract(self.tenses[tense]) elif self.tenses.has_key(tense.title()): return self._extract(self.tenses[tense.title()]) return [None]
def load(self, filename, replace = False): ''' Loads a configuration file (JSON). ''' import os, json, re if os.path.exists(filename): f = open(filename, 'r') content = f.read() content = re.sub('[\t ]*?[#].*?\n', '', content) try: settings = json.loads(content) except ValueError: # This m...
def save(self, filename): ''' Saves the current configuration to file 'filename' (JSON). ''' import json f = open(filename, 'w') json.dump(self.settings, f, indent = 4) f.close()
def forvo(language, word, key): ''' Returns a list of suitable audiosamples for a given word from Forvo.com. ''' from requests import get url = 'http://apifree.forvo.com/action/word-pronunciations/format/json/word/%s/language/%s/key/%s/' % (word, language, key) urls = [] page = get(url) if page.status_code == ...
def _normalize(self, string): ''' Returns a sanitized string. ''' string = string.replace(u'\xb7', '') string = string.replace(u'\xa0', ' ') string = string.replace('selten: ', '') string = string.replace('Alte Rechtschreibung', '') string = string.strip() return string
def pos(self): ''' Tries to decide about the part of speech. ''' tags = [] if self.tree.xpath('//div[@id="mw-content-text"]//a[@title="Hilfe:Wortart"]/text()'): info = self.tree.xpath('//div[@id="mw-content-text"]//a[@title="Hilfe:Wortart"]/text()')[0] if info == 'Substantiv': tags.append('NN') if i...
def register(cache): ''' Registers a cache. ''' global caches name = cache().name if not caches.has_key(name): caches[name] = cache
def enable(identifier = None, *args, **kwargs): ''' Enables a specific cache for the current session. Remember that is has to be registered. ''' global cache if not identifier: for item in (config['default-caches'] + ['NoCache']): if caches.has_key(item): debug('Enabling default cache %s...' % (item,)) ...
def cached(key = None, extradata = {}): ''' Decorator used for caching. ''' def decorator(f): @wraps(f) def wrapper(*args, **kwargs): uid = key if not uid: from hashlib import md5 arguments = list(args) + [(a, kwargs[a]) for a in sorted(kwargs.keys())] uid = md5(str(arguments)).hexdigest() ...
def needsconnection(self, f): ''' Decorator used to make sure that the connection has been established. ''' @wraps(f) def wrapper(self, *args, **kwargs): if not self.connection: self.connect() return f(self, *args, **kwargs) return wrapper
def language(l): ''' Use this as a decorator (implicitly or explicitly). ''' # Usage: @language('en') or function = language('en')(function) def decorator(f): ''' Decorator used to prepend the language as an argument. ''' @wraps(f) def wrapper(*args, **kwargs): return f(l, *args, **kwargs) return wrapp...
def _load_language_or_die(f): ''' Decorator used to load a custom method for a given language. ''' # This decorator checks if there's a custom method for a given language. # If so, prefer the custom method, otherwise raise exception NotImplementedError. @wraps(f) def loader(language, word, *args, **kwargs): me...
def tatoeba(language, word, minlength = 10, maxlength = 100): ''' Returns a list of suitable textsamples for a given word using Tatoeba.org. ''' word, sentences = unicode(word), [] page = requests.get('http://tatoeba.org/deu/sentences/search?query=%s&from=%s&to=und' % (word, lltk.locale.iso639_1to3(language))) tre...
def gender(self): ''' Tries to scrape the correct gender for a given word from wordreference.com ''' elements = self.tree.xpath('//table[@class="WRD"]') if len(elements): elements = self.tree.xpath('//table[@class="WRD"]')[0] if len(elements): if '/iten/' in self.page.url: elements = elements.xpat...
def humanize(iso639): ''' Converts ISO639 language identifier to the corresponding (human readable) language name. ''' for i, element in enumerate(LANGUAGES): if element[1] == iso639 or element[2] == iso639: return element[0] return None
def add_host(self, host_id=None, host='localhost', port=6379, unix_socket_path=None, db=0, password=None, ssl=False, ssl_options=None): """Adds a new host to the cluster. This is only really useful for unittests as normally hosts are added through the constructor and ...
def remove_host(self, host_id): """Removes a host from the client. This only really useful for unittests. """ with self._lock: rv = self._hosts.pop(host_id, None) is not None pool = self._pools.pop(host_id, None) if pool is not None: p...
def disconnect_pools(self): """Disconnects all connections from the internal pools.""" with self._lock: for pool in self._pools.itervalues(): pool.disconnect() self._pools.clear()
def get_router(self): """Returns the router for the cluster. If the cluster reconfigures the router will be recreated. Usually you do not need to interface with the router yourself as the cluster's routing client does that automatically. This returns an instance of :class:`Bas...
def get_pool_for_host(self, host_id): """Returns the connection pool for the given host. This connection pool is used by the redis clients to make sure that it does not have to reconnect constantly. If you want to use a custom redis client you can pass this in as connection pool ...
def map(self, timeout=None, max_concurrency=64, auto_batch=True): """Shortcut context manager for getting a routing client, beginning a map operation and joining over the result. `max_concurrency` defines how many outstanding parallel queries can exist before an implicit join takes plac...
def fanout(self, hosts=None, timeout=None, max_concurrency=64, auto_batch=True): """Shortcut context manager for getting a routing client, beginning a fanout operation and joining over the result. In the context manager the client available is a :class:`FanoutClient`. Ex...
def all(self, timeout=None, max_concurrency=64, auto_batch=True): """Fanout to all hosts. Works otherwise exactly like :meth:`fanout`. Example:: with cluster.all() as client: client.flushdb() """ return self.fanout('all', timeout=timeout, ...
def execute_commands(self, mapping, *args, **kwargs): """Concurrently executes a sequence of commands on a Redis cluster that are associated with a routing key, returning a new mapping where values are a list of results that correspond to the command in the same position. For example:: ...
def auto_batch_commands(commands): """Given a pipeline of commands this attempts to merge the commands into more efficient ones if that is possible. """ pending_batch = None for command_name, args, options, promise in commands: # This command cannot be batched, return it as such. if...
def enqueue_command(self, command_name, args, options): """Enqueue a new command into this pipeline.""" assert_open(self) promise = Promise() self.commands.append((command_name, args, options, promise)) return promise