output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Subscribe to a channel.
Explain what the following Python 3 code does def subscribe(self, channel_name, auth=None): data = {'channel': channel_name} if auth is None: if channel_name.startswith('presence-'): data['auth'] = self._generate_presence_token(channel_name) data['channel_data...
You are a Python code analyst, evaluating scripts for potential improvements.
Unsubscribe from a channel.
How would you explain what the following Python 3 function does def unsubscribe(self, channel_name): if channel_name in self.channels: self.connection.send_event( 'pusher:unsubscribe', { 'channel': channel_name, } ) del self...
As a Python code analyst, you investigate and solve complex coding mysteries
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.
Make a summary of the following Python 3 code def _connection_handler(self, event_name, data, channel_name): if channel_name in self.channels: self.channels[channel_name]._handle_event(event_name, data)
As a Python code composer, you craft elegant and concise scripts.
Generate a token for authentication with the given channel.
Given the following Python 3 function, write the documentation def _generate_auth_token(self, channel_name): subject = "{}:{}".format(self.connection.socket_id, channel_name) h = hmac.new(self.secret_as_bytes, subject.encode('utf-8'), hashlib.sha256) auth_key = "{}:{}".format(self.key, h.hexdige...
You are a Python code generator, capable of creating scripts from specifications.
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 = ...
Implement a Python 3 function for generating a presence token.
As a Python code analyst, you investigate and solve complex coding mysteries
Tries to decide about the part of speech.
Make a summary of the following Python 3 code 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 ...
As a Python code analyst, you investigate and solve complex coding mysteries
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(' | ')...
Implement a function in Python 3 to try to scrape the correct articles for singular and plural from uitmuntend. nl.
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Can you create a Python 3 function that tries to scrape the plural version from uitmuntend. nl.
As a python code expert, you are capable of creating scripts from specifications.
Downloads a file via HTTP.
Can you tell what is the following Python 3 function doing 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 ...
You are a Python code architect, reviewing and designing scalable and efficient code
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')
Write a Python 3 function for printing a message if warning mode is enabled.
You are a Python code generator, capable of creating scripts from specifications.
Decorator used to trace function calls for debugging purposes.
How would you explain what the following Python 3 function does 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)
You are a Python code generator, capable of creating scripts from specifications.
Tries to scrape the correct articles for singular and plural from vandale. nl.
Can you tell what is the following Python 3 function doing 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...
As a python code expert, you are capable of creating scripts from specifications.
Tries to scrape the plural version from vandale. nl.
Here you have a function in Python 3, explain what it does 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).g...
You are a Python code architect, reviewing and designing scalable and efficient code
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]
Implement a function in Python 3 to try to scrape the miniaturized version from vandale. nl.
As a Python code translator, you convert algorithms and pseudocode into Python.
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
Implement a Python 3 function for returning a sanitized string.
You are a Python code analyst, evaluating scripts for potential improvements.
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')): ...
Implement a function in Python 3 to attempt to decide about the part of speech.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a sanitized string.
Explain what the following Python 3 code does 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
As a Python code analyst, you investigate and solve complex coding mysteries
Tries to decide about the part of speech.
Given the following Python 3 function, write the documentation 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 ...
You are a Python code analyst, evaluating scripts for potential improvements.
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
Implement a Python 3 function for trying to scrape the gender for a given noun from leo. org.
As a Python code analyst, you investigate and solve complex coding mysteries
Finds out if a scraping result should be considered empty.
Can you tell what is the following Python 3 function doing 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:...
As a Python code composer, you craft elegant and concise scripts.
Returns a list of valid POS - tags for a given method.
Can you generate a brief explanation for the following Python 3 code 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, superlat...
As a Python code composer, you craft elegant and concise scripts.
Registers a scraper to make it available for the generic scraping interface.
Can you generate a brief explanation for the following Python 3 code 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...
As a Python code composer, you craft elegant and concise scripts.
Discovers all registered scrapers for the given language.
Can you generate the documentation for the following Python 3 function 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(): discov...
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
Create a Python 3 function for using custom scrapers and calls provided method.
As a Python code translator, you convert algorithms and pseudocode into Python.
Iterate over all available scrapers for a given method.
Given the following Python 3 function, write the documentation 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]: ...
You are a Python code analyst, evaluating scripts for potential improvements.
Merges all scraping results to a list sorted by frequency of occurrence.
Given the following Python 3 function, write the documentation 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 objec...
As a Python code analyst, you investigate and solve complex coding mysteries
Removes empty or incomplete answers.
How would you explain what the following Python 3 function does 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....
As a Python code analyst, you investigate and solve complex coding mysteries
def download(self): ''' Downloads HTML from url. ''' self.page = requests.get(self.url) self.tree = html.fromstring(self.page.text)
Can you implement a function in Python 3 that downloads HTML from url.
You are a Python code architect, reviewing and designing scalable and efficient code
Decorator used to make sure that there are elements prior to running the task.
Given the following Python 3 function, write the documentation 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) ...
As a python code expert, you are capable of creating scripts from specifications.
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
Write a Python 3 script to return the first element with required POS - tag.
You are a Python code analyst, evaluating scripts for potential improvements.
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
Create a Python 3 function to return a sanitized string.
As a Python code analyst, you investigate and solve complex coding mysteries
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: ...
Can you write a function in Python 3 where it attempts to decide about the part of speech.
As a Python code composer, you craft elegant and concise scripts.
Tries to scrape the correct articles for singular and plural from de. pons. eu.
Can you generate the documentation for the following Python 3 function 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()] i...
As a python code expert, you are capable of creating scripts from specifications.
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...
Write a Python 3 function for trying to scrape the plural version from pons. eu.
You are a Python code generator, capable of creating scripts from specifications.
Returns the articles that are used for a given noun.
Make a summary of the following Python 3 code 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 (['-'], ['-'])...
You are a Python code generator, capable of creating scripts from specifications.
Translate a word using Google Translate.
Can you tell what is the following Python 3 function doing 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: ...
You are a Python code generator, capable of creating scripts from specifications.
Returns a list of URLs to suitable audiosamples for a given word.
How would you explain what the following Python 3 function does 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 url...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a list of URLs to suitable images for a given word.
Given the following Python 3 function, write the documentation 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)
You are a Python code architect, reviewing and designing scalable and efficient code
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 = (...
Implement a Python 3 function for returning the articles for a given noun.
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
Create a Python 3 function to download suitable images for a given word from Google Images.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a sanitized string.
Here you have a function in Python 3, explain what it does def _normalize(self, string): ''' Returns a sanitized string. ''' string = string.replace(u'\xa0', '') string = string.strip() return string
As a Python code translator, you convert algorithms and pseudocode into Python.
Extracts data from conjugation table.
How would you explain what the following Python 3 function does 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()) = "' + ...
You are a Python code architect, reviewing and designing scalable and efficient code
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]
Implement a Python 3 function for returning a list of the conjugate tenses.
As a python code expert, you are capable of creating scripts from specifications.
Loads a configuration file.
Explain what the following Python 3 code does 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.loa...
As a python code expert, you are capable of creating scripts from specifications.
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()
Can you write a function in Python 3 where it saves the current configuration to a JSON file.
As a python code expert, you are capable of creating scripts from specifications.
Returns a list of suitable audiosamples for a given word from Forvo.
Explain what the following Python 3 code does 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 =...
As a Python code analyst, you investigate and solve complex coding mysteries
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
Implement a function in Python 3 to return a sanitized string.
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
Write a Python 3 script for attempting to decide about the part of speech.
As a Python code analyst, you investigate and solve complex coding mysteries
Decorator used to prepend the language as an argument.
Can you tell what is the following Python 3 function doing 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...
As a Python code composer, you craft elegant and concise scripts.
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...
How would you implement a function in Python 3 that returns a list of suitable textsamples for a given word using Tatoeba. org.
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
Can you create a Python 3 function that tries to scrape the correct gender for a given word from wordreference. com
As a Python code translator, you convert algorithms and pseudocode into Python.
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
Write a Python 3 function for converting ISO639 language identifier to the corresponding human readable language name.
As a Python code translator, you convert algorithms and pseudocode into Python.
Adds a new host to the cluster.
Can you generate the documentation for the following Python 3 function 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 ...
As a Python code composer, you craft elegant and concise scripts.
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...
Implement a function in Python 3 to remove a host from the client.
You are a Python code analyst, evaluating scripts for potential improvements.
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()
Implement a function in Python 3 to disconnect all connections from the internal pools.
As a Python code composer, you craft elegant and concise scripts.
Returns the router for the cluster.
Here you have a function in Python 3, explain what it does def get_router(self): cached_router = self._router ref_age = self._hosts_age if cached_router is not None: router, router_age = cached_router if router_age == ref_age: return router with ...
As a Python code composer, you craft elegant and concise scripts.
Returns the connection pool for the given host.
Can you generate the documentation for the following Python 3 function def get_pool_for_host(self, host_id): if isinstance(host_id, HostInfo): host_info = host_id host_id = host_info.host_id else: host_info = self.hosts.get(host_id) if host_info is None: ...
You are a Python code analyst, evaluating scripts for potential improvements.
Fanout to all hosts.
Make a summary of the following Python 3 code def all(self, timeout=None, max_concurrency=64, auto_batch=True): return self.fanout('all', timeout=timeout, max_concurrency=max_concurrency, auto_batch=auto_batch)
You are a Python code generator, capable of creating scripts from specifications.
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:: ...
Write a Python 3 function that can execute a sequence of commands on a Redis cluster and return a new mapping.
You are a Python code architect, reviewing and designing scalable and efficient code
Given a pipeline of commands this attempts to merge the commands into more efficient ones if that is possible.
Here you have a function in Python 3, explain what it does def auto_batch_commands(commands): pending_batch = None for command_name, args, options, promise in commands: # This command cannot be batched, return it as such. if command_name not in AUTO_BATCH_COMMANDS: if pending_batch:...
As a python code expert, you are capable of creating scripts from specifications.
def send_pending_requests(self): """Sends all pending requests into the connection. The default is to only send pending data that fits into the socket without blocking. This returns `True` if all data was sent or `False` if pending data is left over. """ assert_open(self...
Implement a function in Python 3 to send all pending requests into the socket.
You are a Python code analyst, evaluating scripts for potential improvements.
def wait_for_responses(self, client): """Waits for all responses to come back and resolves the eventual results. """ assert_open(self) if self.has_pending_requests: raise RuntimeError('Cannot wait for responses if there are ' 'pending r...
Create a Python 3 function for waiting for all responses to come back and resolves the eventual results.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns the command buffer for the given command and arguments.
Can you tell what is the following Python 3 function doing def _get_command_buffer(self, host_id, command_name): buf = self._cb_poll.get(host_id) if buf is not None: return buf if self._max_concurrency is not None: while len(self._cb_poll) >= self._max_concurrency: ...
As a Python code analyst, you investigate and solve complex coding mysteries
This is called by the command buffer when it closes.
Here you have a function in Python 3, explain what it does def _release_command_buffer(self, command_buffer): if command_buffer.closed: return self._cb_poll.unregister(command_buffer.host_id) self.connection_pool.release(command_buffer.connection) command_buffer.connection =...
As a Python code composer, you craft elegant and concise scripts.
def join(self, timeout=None): """Waits for all outstanding responses to come back or the timeout to be hit. """ remaining = timeout while self._cb_poll and (remaining is None or remaining > 0): now = time.time() rv = self._cb_poll.poll(remaining) ...
Create a Python 3 function to wait for all outstanding responses to come back or the timeout to be hit.
You are a Python code architect, reviewing and designing scalable and efficient code
Temporarily retarget the client for one call.
Here you have a function in Python 3, explain what it does def target(self, hosts): if self.__is_retargeted: raise TypeError('Cannot use target more than once.') rv = FanoutClient(hosts, connection_pool=self.connection_pool, max_concurrency=self._max_concurrency) ...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a thread unsafe mapping client.
How would you explain what the following Python 3 function does def get_mapping_client(self, max_concurrency=64, auto_batch=None): if auto_batch is None: auto_batch = self.auto_batch return MappingClient(connection_pool=self.connection_pool, max_concurrency=max_c...
You are a Python code analyst, evaluating scripts for potential improvements.
def get_fanout_client(self, hosts, max_concurrency=64, auto_batch=None): """Returns a thread unsafe fanout client. Returns an instance of :class:`FanoutClient`. """ if auto_batch is None: auto_batch = self.auto_batch return FanoutClient(host...
Write a Python 3 script for returning an instance of thread unsafe fanout client.
As a python code expert, you are capable of creating scripts from specifications.
def map(self, timeout=None, max_concurrency=64, auto_batch=None): """Returns a context manager for a map operation. This runs multiple queries in parallel and then joins in the end to collect all results. In the context manager the client available is a :class:`MappingClient`. ...
Create a Python 3 function for returning a context manager that runs a map operation.
As a python code expert, you are capable of creating scripts from specifications.
def fanout(self, hosts=None, timeout=None, max_concurrency=64, auto_batch=None): """Returns a context manager for a map operation that fans out to manually specified hosts instead of using the routing system. This can for instance be used to empty the database on all hosts. The ...
Implement a Python 3 function for returning a context manager that fans out to the specified hosts.
You are a Python code generator, capable of creating scripts from specifications.
Creates a promise object resolved with a certain value.
Can you generate the documentation for the following Python 3 function def resolved(value): p = Promise() p._state = 'resolved' p.value = value return p
You are a Python code architect, reviewing and designing scalable and efficient code
def rejected(reason): """Creates a promise object rejected with a certain value.""" p = Promise() p._state = 'rejected' p.reason = reason return p
Write a Python 3 script for creating a promise object rejected with a certain value.
You are a Python code architect, reviewing and designing scalable and efficient code
Resolves the promise with the given value.
Can you tell what is the following Python 3 function doing def resolve(self, value): if self is value: raise TypeError('Cannot resolve promise with itself.') if isinstance(value, Promise): value.done(self.resolve, self.reject) return if self._state != 'pendi...
You are a Python code generator, capable of creating scripts from specifications.
Rejects the promise with the given reason.
Can you generate the documentation for the following Python 3 function def reject(self, reason): if self._state != 'pending': raise RuntimeError('Promise is no longer pending.') self.reason = reason self._state = 'rejected' errbacks = self._errbacks self._errbacks = ...
As a Python code analyst, you investigate and solve complex coding mysteries
Attaches some callbacks to the promise and returns the promise.
How would you explain what the following Python 3 function does def done(self, on_success=None, on_failure=None): if on_success is not None: if self._state == 'pending': self._callbacks.append(on_success) elif self._state == 'resolved': on_success(self.val...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns the key a command operates on.
How would you explain what the following Python 3 function does def get_key(self, command, args): spec = COMMANDS.get(command.upper()) if spec is None: raise UnroutableCommand('The command "%r" is unknown to the ' 'router and cannot be handled as a ' ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the host this command should be executed against.
Here you have a function in Python 3, explain what it does def get_host_for_command(self, command, args): return self.get_host_for_key(self.get_key(command, args))
You are a Python code architect, reviewing and designing scalable and efficient code
Updates the hash ring with the new ones.
Explain what the following Python 3 code does def _rebuild_circle(self): self._hashring = {} self._sorted_keys = [] total_weight = 0 for node in self._nodes: total_weight += self._weights.get(node, 1) for node in self._nodes: weight = self._weights.get(no...
As a Python code composer, you craft elegant and concise scripts.
Return the node position for a given key or None.
Explain what the following Python 3 code does def _get_node_pos(self, key): if not self._hashring: return k = md5_bytes(key) key = (k[3] << 24) | (k[2] << 16) | (k[1] << 8) | k[0] nodes = self._sorted_keys pos = bisect(nodes, key) if pos == len(nodes): ...
As a Python code analyst, you investigate and solve complex coding mysteries
def remove_node(self, node): """Removes node from circle and rebuild it.""" try: self._nodes.remove(node) del self._weights[node] except (KeyError, ValueError): pass self._rebuild_circle()
Implement a function in Python 3 to remove node from circle and rebuild it.
You are a Python code architect, reviewing and designing scalable and efficient code
Adds a node to the circle and rebuilds it.
Can you tell what is the following Python 3 function doing def add_node(self, node, weight=1): self._nodes.add(node) self._weights[node] = weight self._rebuild_circle()
You are a Python code analyst, evaluating scripts for potential improvements.
def get_node(self, key): """Return node for a given key. Else return None.""" pos = self._get_node_pos(key) if pos is None: return None return self._hashring[self._sorted_keys[pos]]
Implement a Python 3 function for returning node for a given key. If no node exists return None.
As a python code expert, you are capable of creating scripts from specifications.
def ddtodms(self, dd): """Take in dd string and convert to dms""" negative = dd < 0 dd = abs(dd) minutes,seconds = divmod(dd*3600,60) degrees,minutes = divmod(minutes,60) if negative: if degrees > 0: degrees = -degrees elif minutes ...
Write a Python 3 function for taking in dd string and convert to dms
You are a Python code generator, capable of creating scripts from specifications.
def dmstodd(self, dms): """ convert dms to dd""" size = len(dms) letters = 'WENS' is_annotated = False try: float(dms) except ValueError: for letter in letters: if letter in dms.upper(): is_annotated = True ...
Create a Python 3 function for converting a string to dd
As a Python code translator, you convert algorithms and pseudocode into Python.
Obtain a proper file object.
Can you generate a brief explanation for the following Python 3 code def get_fobj(fname, mode='w+'): if is_string_like(fname): fobj = open(fname, mode) close = True elif hasattr(fname, 'write'): # fname is a file-like object, perhaps a StringIO (for example) fobj = fname ...
As a Python code analyst, you investigate and solve complex coding mysteries
Load a graph from a DOT file.
Here you have a function in Python 3, explain what it does def graph_from_dot_file(path): fd = open(path, 'rb') data = fd.read() fd.close() return graph_from_dot_data(data)
As a Python code analyst, you investigate and solve complex coding mysteries
Creates a basic graph out of an edge list.
Here you have a function in Python 3, explain what it does def graph_from_edges(edge_list, node_prefix='', directed=False): if edge_list is None: edge_list = [] graph_type = "digraph" if directed else "graph" with_prefix = functools.partial("{0}{1}".format, node_prefix) graph = Dot(graph_type=...
As a Python code composer, you craft elegant and concise scripts.
def graph_from_adjacency_matrix(matrix, node_prefix='', directed=False): """Creates a basic graph out of an adjacency matrix. The matrix has to be a list of rows of values representing an adjacency matrix. The values can be anything: bool, int, float, as long as they can evaluate to True or False. ...
How would you implement a function in Python 3 that creates a basic graph out of an adjacency matrix.
As a Python code composer, you craft elegant and concise scripts.
def graph_from_incidence_matrix(matrix, node_prefix='', directed=False): """Creates a basic graph out of an incidence matrix. The matrix has to be a list of rows of values representing an incidence matrix. The values can be anything: bool, int, float, as long as they can evaluate to True or False. ...
Write a Python 3 function for creating a basic graph out of an incidence matrix.
As a Python code translator, you convert algorithms and pseudocode into Python.
Used by find_graphviz path - single directory as a string
Explain what the following Python 3 code does def __find_executables(path): success = False progs = { "dot": "", "twopi": "", "neato": "", "circo": "", "fdp": "", "sfdp": "", } was_quoted = False path = path.strip() if path.startswith('"') and pa...
You are a Python code generator, capable of creating scripts from specifications.
def find_graphviz(): """Locate Graphviz's executables in the system. Tries three methods: First: Windows Registry (Windows only) This requires Mark Hammond's pywin32 is installed. Secondly: Search the path It will look for 'dot', 'twopi' and 'neato' in all the directories specified in the...
Write a Python 3 script for locating the Graphviz executables in the system.
As a Python code translator, you convert algorithms and pseudocode into Python.
Get the list of Node instances. This method returns the list of Node instances.
How would you explain what the following Python 3 function does def get_node_list(self): node_objs = list() for obj_dict_list in self.obj_dict['nodes'].values(): node_objs.extend([ Node(obj_dict=obj_d) for obj_d in obj_dict_list]) ret...
As a python code expert, you are capable of creating scripts from specifications.
def del_edge(self, src_or_list, dst=None, index=None): """Delete an edge from the graph. Given an edge's (source, destination) node names all matching edges(s) will be deleted if 'index' is not specified or set to None. If there are several matching edges and 'index' is ...
Implement a function in Python 3 to delete an edge from the graph.
As a Python code analyst, you investigate and solve complex coding mysteries
def get_edge_list(self): """Get the list of Edge instances. This method returns the list of Edge instances composing the graph. """ edge_objs = list() for obj_dict_list in self.obj_dict['edges'].values(): edge_objs.extend([ Edge(obj_dict=obj_...
Can you write a function in Python 3 where it gets the list of Edge instances. This method returns the list of Edge instances.
As a python code expert, you are capable of creating scripts from specifications.
def to_string(self): """Returns a string representation of the graph in dot language. It will return the graph and all its subelements in string from. """ graph = list() if self.obj_dict.get('strict', None) is not None: if self == self.get_parent_graph() and self.o...
Implement a function in Python 3 to return a string representation of the object in dot language.
As a Python code analyst, you investigate and solve complex coding mysteries
def write(self, path, prog=None, format='raw'): """Write graph to file in selected format. Given a filename 'path' it will open/create and truncate such file and write on it a representation of the graph defined by the dot object and in the format specified by 'format'. 'path' c...
How would you code a function in Python 3 to write the graph to file in specified format.
You are a Python code architect, reviewing and designing scalable and efficient code
Get crumbs for navigation links.
How would you explain what the following Python 3 function does def get_crumbs(self): crumbs = [] for cls in reversed(type(self).__mro__[1:]): crumbs.extend(getattr(cls, 'crumbs', ())) crumbs.extend(list(self.crumbs)) return tuple(crumbs)
You are a Python code generator, capable of creating scripts from specifications.
This function is called by the get view function. It returns a Django response with the context data.
How would you explain what the following Python 3 function does def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) context.update(self.extra_context) context['crumbs'] = self.get_crumbs() context['title'] = self.title context['suit'] = 'suit' in se...
As a Python code analyst, you investigate and solve complex coding mysteries
def realtime(widget, url_name=None, url_regex=None, time_interval=None): """ Return a widget as real-time. Args: widget (Widget): the widget to register and return as real-time. url_name (str): the URL name to call to get updated content. url_regex (regex): the URL regex to be match...
Implement a function in Python 3 to return a widget as real - time.
You are a Python code architect, reviewing and designing scalable and efficient code
Get the URL for real - time widgets.
Given the following Python 3 function, write the documentation def get_realtime_urls(admin_view_func=lambda x: x): from .widgets import REALTIME_WIDGETS return [url(w.url_regex, admin_view_func(w.as_view()), name=w.url_name) for w in REALTIME_WIDGETS]
You are a Python code generator, capable of creating scripts from specifications.