text_prompt
stringlengths 157
13.1k
| code_prompt
stringlengths 7
19.8k
⌀ |
---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build(self, **variables):
"""Formats the locator with specified parameters""" |
return Locator(self.by, self.locator.format(**variables), self.description) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 webdriverwrapper: WebDriverWrapper to receive cookies @param handle_sub_domain: If True, will check driver url and change cookies with subdomains of that domain to match the current driver domain in order to avoid cross-domain cookie errors @rtype: None @return: None """ |
driver_hostname = urlparse(webdriverwrapper.current_url()).netloc
for cookie in requestdriver.session.cookies:
# Check if there will be a cross-domain violation and handle if necessary
cookiedomain = cookie.domain
if handle_sub_domain:
if is_subdomain(cookiedomain, driver_hostname):
# Cookies of requestdriver are subdomain cookies of webdriver; make them the base domain
cookiedomain = driver_hostname
try:
webdriverwrapper.add_cookie({
'name': cookie.name,
'value': cookie.value,
'domain': cookiedomain,
'path': cookie.path
})
except WebDriverException, e:
raise WebDriverException(
msg='Cannot set cookie "{name}" with domain "{domain}" on url "{url}" {override}: {message}'.format(
name=cookie.name,
domain=cookiedomain,
url=webdriverwrapper.current_url(),
override='(Note that subdomain override is set!)' if handle_sub_domain else '',
message=e.message),
screen=e.screen,
stacktrace=e.stacktrace
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 receive cookies @rtype: None @return: None """ |
for cookie in webdriverwrapper.get_cookies():
# Wedbriver uses "expiry"; requests uses "expires", adjust for this
expires = cookie.pop('expiry', {'expiry': None})
cookie.update({'expires': expires})
requestdriver.session.cookies.set(**cookie) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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'.format(datetime.datetime.now().isoformat('_'), words.random_word()))
log_file = open(log_path, 'w')
log('Firefox log file: {}'.format(log_path))
binary = FirefoxBinary(log_file=log_file)
return binary |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 errors on this page: {}'.format(logs)
failure_message = failure_message.replace('{', '{{').replace('}', '}}') # Escape braces for error message
driver.assertion.assert_false(
logs,
failure_message=failure_message
)
except (urllib2.URLError, socket.error, WebDriverException):
# The session has ended, don't check the logs
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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=self.request
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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, self.get_context(), request=self.request
)
return ''.join(subject.splitlines()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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`` object, as the variable ``site``. * Any additional variables added by context processors (this will be a ``RequestContext``). """ |
if not self.is_valid():
raise ValueError(
"Cannot generate Context from invalid contact form"
)
return dict(self.cleaned_data, site=get_current_site(self.request)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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")
shopify.Session.setup(api_key=settings.SHOPIFY_APP_API_KEY, secret=settings.SHOPIFY_APP_API_SECRET) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)
# Never want to be able to log on externally.
# Authentication will be taken care of by Shopify OAuth.
user.set_unusable_password()
user.save(using=self._db)
return user |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 parameters and add new parameters.
qs_args = urllib.parse.parse_qs(url_parts[4])
qs_args.update(query_parameters)
# Sort parameters to ensure consistent order.
sorted_qs_args = OrderedDict()
for k in sorted(qs_args.keys()):
sorted_qs_args[k] = qs_args[k]
# Encode the new parameters and return the updated URL.
new_qs = urllib.parse.urlencode(sorted_qs_args, True)
return urllib.parse.urlunparse(list(url_parts[0:4]) + [new_qs] + list(url_parts[5:])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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'] = channel_name
self.logger.info("Connection: Sending event - %s" % event)
try:
self.socket.send(json.dumps(event))
except Exception as e:
self.logger.error("Failed send event: %s" % e) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. """ |
if self.connection:
if event_name.startswith("client-"):
if self.name.startswith("private-") or self.name.startswith("presence-"):
self.connection.send_event(event_name, data, channel_name=self.name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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}
if auth is None:
if channel_name.startswith('presence-'):
data['auth'] = self._generate_presence_token(channel_name)
data['channel_data'] = json.dumps(self.user_data)
elif channel_name.startswith('private-'):
data['auth'] = self._generate_auth_token(channel_name)
else:
data['auth'] = auth
self.connection.send_event('pusher:subscribe', data)
self.channels[channel_name] = Channel(channel_name, self.connection)
return self.channels[channel_name] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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': channel_name,
}
)
del self.channels[channel_name] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.channels:
self.channels[channel_name]._handle_event(event_name, data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 = hmac.new(self.secret_as_bytes, subject.encode('utf-8'), hashlib.sha256)
auth_key = "{}:{}".format(self.key, h.hexdigest())
return auth_key |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 = hmac.new(self.secret_as_bytes, subject.encode('utf-8'), hashlib.sha256)
auth_key = "{}:{}".format(self.key, h.hexdigest())
return auth_key |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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(' | ')
singular, plural = singular.strip(), plural.strip()
else:
# This means there is no plural
singular, plural = element.strip(), ''
result[1] = ''
if singular:
result[0] = singular.split(' ')[0].split('/')
if plural:
result[1] = plural.split(' ')[0].split('/')
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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:
# This means there is no plural
return ['']
return [None] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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.content)
f.close()
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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.search('meervoud: (\w+)', element, re.U):
# It's a noun with a plural form
result[1] = ['de']
else:
# It's a noun without a plural form
result[1] = ['']
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 ', '').strip() for x in results]
return results
else:
# There is no plural form
return ['']
return [None] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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:
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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:
scrapers[language] = [scraper] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 = ['download', 'isdownloaded', 'getelements']
methods = [method for method in dir(scraper) if method not in blacklist and not method.startswith('_') and callable(getattr(scraper, method))]
for method in methods:
if discovered[language].has_key(method):
discovered[language][method].append(scraper)
else:
discovered[language][method] = [scraper]
debug('%d scrapers with %d methods (overall) registered for \'%s\'.' % (len(scrapers[language]), len(discovered[language].keys()), language)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 ' + method + '() is not implemented so far.') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 for value, count in Counter(list2tuple(list(elements))).most_common()])
return merged |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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[i])
return cleanelements |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def download(self):
''' Downloads HTML from url. '''
self.page = requests.get(self.url)
self.tree = html.fromstring(self.page.text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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] = ['']
else:
# If a plural form exists, there is only one possibility
result[1] = ['die']
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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|/]+)>', element, re.U)[0].split('/')
if re.search(', -(\w+)>', element, re.U):
# Suffix is provided
suffix = re.findall(', -(\w+)>', element, re.U)[0]
return [self.word + suffix]
if element.endswith('->'):
# Plural is the same as singular
return [self.word]
return [None] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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|medium|large|xlarge'
if not kwargs.has_key('filetype'):
kwargs['filetype'] = 'jpg'
info = {'q' : word, 'hl' : language, 'start' : str(kwargs['start']), 'as_filetype' : kwargs['filetype'], 'imgsz' : kwargs['isize'], 'imgtype' : kwargs['itype'], 'rsz' : '8', 'safe' : 'active'}
query = '&'.join([x[0] + '=' + x[1] for x in info.items()])
url = 'https://ajax.googleapis.com/ajax/services/search/images?v=1.0&' + query
debug('Loading ' + unicode(url) + '...')
page = requests.get(url)
data = json.loads(page.text)
images = []
if data and data.has_key('responseData') and data['responseData']:
items = data['responseData']['results']
if items:
images += [item['url'] for item in items]
if len(images) < int(n):
kwargs['start'] += 8
images += google(language, word, n, *args, **kwargs)
return images[:int(n)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 p.iterfind('font'):
text = self._normalize(font.text_content())
next = font.getnext()
text += ' ' + self._normalize(next.text_content())
while True:
next = next.getnext()
if next.tag != 'span':
break
text += '/' + self._normalize(next.text_content())
conjugation.append(text)
return conjugation |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def register(cache):
''' Registers a cache. '''
global caches
name = cache().name
if not caches.has_key(name):
caches[name] = cache |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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,))
cache = caches[item](*args, **kwargs)
if not cache.status():
warning('%s could not be loaded. Is the backend running (%s:%d)?' % (item, cache.server, cache.port))
continue
# This means that the cache backend was set up successfully
break
else:
debug('Cache backend %s is not registered. Are all requirements satisfied?' % (item,))
elif caches.has_key(identifier):
debug('Enabling cache %s...' % (identifier,))
previouscache = cache
cache = caches[identifier](*args, **kwargs)
if not cache.status():
warning('%s could not be loaded. Is the backend running (%s:%d)?' % (identifier, cache.server, cache.port))
cache = previouscache
else:
debug('Cache backend %s is not registered. Are all requirements satisfied?' % (identifier,)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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()
if exists(uid):
debug('Item \'%s\' is cached (%s).' % (uid, cache))
return get(uid)
else:
debug('Item \'%s\' is not cached (%s).' % (uid, cache))
result = f(*args, **kwargs)
debug('Caching result \'%s\' as \'%s\' (%s)...' % (result, uid, cache))
debug('Extra data: ' + (str(extradata) or 'None'))
put(uid, result, extradata)
return result
return wrapper
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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):
method = f.func_name
try:
if isinstance(language, (list, tuple)):
_lltk = __import__('lltk.' + language[0], globals(), locals(), [method], -1)
else:
_lltk = __import__('lltk.' + language, globals(), locals(), [method], -1)
except ImportError:
from lltk.exceptions import LanguageNotSupported
raise LanguageNotSupported('The language ' + language + ' is not supported so far.')
if hasattr(_lltk, method):
function = getattr(_lltk, method)
if callable(function):
return function(word, *args, **kwargs)
# No custom method implemented, yet.
raise NotImplementedError('Method lltk.' + language + '.' + method +'() not implemented, yet.')
return loader |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 changes after the cluster has been used for the first time are unlikely to make sense. """ |
if host_id is None:
raise RuntimeError('Host ID is required')
elif not isinstance(host_id, (int, long)):
raise ValueError('The host ID has to be an integer')
host_id = int(host_id)
with self._lock:
if host_id in self.hosts:
raise TypeError('Two hosts share the same host id (%r)' %
(host_id,))
self.hosts[host_id] = HostInfo(host_id=host_id, host=host,
port=port, db=db,
unix_socket_path=unix_socket_path,
password=password, ssl=ssl,
ssl_options=ssl_options)
self._hosts_age += 1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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:
pool.disconnect()
self._hosts_age += 1
return rv |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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:`BaseRouter`. """ |
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 self._lock:
router = self.router_cls(self, **(self.router_options or {}))
self._router = (router, ref_age)
return router |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 manually. """ |
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:
raise LookupError('Host %r does not exist' % (host_id,))
rv = self._pools.get(host_id)
if rv is not None:
return rv
with self._lock:
rv = self._pools.get(host_id)
if rv is None:
opts = dict(self.pool_options or ())
opts['db'] = host_info.db
opts['password'] = host_info.password
if host_info.unix_socket_path is not None:
opts['path'] = host_info.unix_socket_path
opts['connection_class'] = UnixDomainSocketConnection
if host_info.ssl:
raise TypeError('SSL is not supported for unix '
'domain sockets.')
else:
opts['host'] = host_info.host
opts['port'] = host_info.port
if host_info.ssl:
if SSLConnection is None:
raise TypeError('This version of py-redis does '
'not support SSL connections.')
opts['connection_class'] = SSLConnection
opts.update(('ssl_' + k, v) for k, v in
(host_info.ssl_options or {}).iteritems())
rv = self.pool_cls(**opts)
self._pools[host_id] = rv
return rv |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 place. In the context manager the client available is a :class:`MappingClient`. Example usage:: results = {} with cluster.map() as client: for key in keys_to_fetch: results[key] = client.get(key) for key, promise in results.iteritems():
print '%s => %s' % (key, promise.value) """ |
return self.get_routing_client(auto_batch).map(
timeout=timeout, max_concurrency=max_concurrency) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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`. Example usage:: with cluster.fanout(hosts='all') as client: client.flushdb() """ |
return self.get_routing_client(auto_batch).fanout(
hosts=hosts, timeout=timeout, max_concurrency=max_concurrency) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 command_name not in AUTO_BATCH_COMMANDS:
if pending_batch:
yield merge_batch(*pending_batch)
pending_batch = None
yield command_name, args, options, promise
continue
assert not options, 'batch commands cannot merge options'
if pending_batch and pending_batch[0] == command_name:
pending_batch[1].append((args, promise))
else:
if pending_batch:
yield merge_batch(*pending_batch)
pending_batch = (command_name, [(args, promise)])
if pending_batch:
yield merge_batch(*pending_batch) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_buffer(self):
"""Utility function that sends the buffer into the provided socket. The buffer itself will slowly clear out and is modified in place. """ |
buf = self._send_buf
sock = self.connection._sock
try:
timeout = sock.gettimeout()
sock.setblocking(False)
try:
for idx, item in enumerate(buf):
sent = 0
while 1:
try:
sent = sock.send(item)
except IOError as e:
if e.errno == errno.EAGAIN:
continue
elif e.errno == errno.EWOULDBLOCK:
break
raise
self.sent_something = True
break
if sent < len(item):
buf[:idx + 1] = [item[sent:]]
break
else:
del buf[:]
finally:
sock.settimeout(timeout)
except IOError as e:
self.connection.disconnect()
if isinstance(e, socket.timeout):
raise TimeoutError('Timeout writing to socket (host %s)'
% self.host_id)
raise ConnectionError('Error while writing to socket (host %s): %s'
% (self.host_id, e)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)
unsent_commands = self.commands
if unsent_commands:
self.commands = []
if self.auto_batch:
unsent_commands = auto_batch_commands(unsent_commands)
buf = []
for command_name, args, options, promise in unsent_commands:
buf.append((command_name,) + tuple(args))
self.pending_responses.append((command_name, options, promise))
cmds = self.connection.pack_commands(buf)
self._send_buf.extend(cmds)
if not self._send_buf:
return True
self.send_buffer()
return not self._send_buf |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 requests outstanding. You need '
'to wait for pending requests to be sent '
'first.')
pending = self.pending_responses
self.pending_responses = []
for command_name, options, promise in pending:
value = client.parse_response(
self.connection, command_name, **options)
promise.resolve(value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_command_buffer(self, host_id, command_name):
"""Returns the command buffer for the given command and arguments.""" |
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:
self.join(timeout=1.0)
def connect():
return self.connection_pool.get_connection(
command_name, shard_hint=host_id)
buf = CommandBuffer(host_id, connect, self.auto_batch)
self._cb_poll.register(host_id, buf)
return buf |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _release_command_buffer(self, command_buffer):
"""This is called by the command buffer when it closes.""" |
if command_buffer.closed:
return
self._cb_poll.unregister(command_buffer.host_id)
self.connection_pool.release(command_buffer.connection)
command_buffer.connection = None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)
if remaining is not None:
remaining -= (time.time() - now)
for command_buffer, event in rv:
# This command buffer still has pending requests which
# means we have to send them out first before we can read
# all the data from it.
if command_buffer.has_pending_requests:
if event == 'close':
self._try_reconnect(command_buffer)
elif event == 'write':
self._send_or_reconnect(command_buffer)
# The general assumption is that all response is available
# or this might block. On reading we do not use async
# receiving. This generally works because latency in the
# network is low and redis is super quick in sending. It
# does not make a lot of sense to complicate things here.
elif event in ('read', 'close'):
try:
command_buffer.wait_for_responses(self)
finally:
self._release_command_buffer(command_buffer)
if self._cb_poll and timeout is not None:
raise TimeoutError('Did not receive all data in time.') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def target(self, hosts):
"""Temporarily retarget the client for one call. This is useful when having to deal with a subset of hosts for one call. """ |
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)
rv._cb_poll = self._cb_poll
rv.__is_retargeted = True
return rv |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def target_key(self, key):
"""Temporarily retarget the client for one call to route specifically to the one host that the given key routes to. In that case the result on the promise is just the one host's value instead of a dictionary. .. versionadded:: 1.3 """ |
router = self.connection_pool.cluster.get_router()
host_id = router.get_host_for_key(key)
rv = self.target([host_id])
rv.__resolve_singular_result = True
return rv |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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(hosts, connection_pool=self.connection_pool,
max_concurrency=max_concurrency,
auto_batch=auto_batch) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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`. Example usage:: results = {} with cluster.map() as client: for key in keys_to_fetch: results[key] = client.get(key) for key, promise in results.iteritems():
print '%s => %s' % (key, promise.value) """ |
return MapManager(self.get_mapping_client(max_concurrency, auto_batch),
timeout=timeout) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolved(value):
"""Creates a promise object resolved with a certain value.""" |
p = Promise()
p._state = 'resolved'
p.value = value
return p |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rejected(reason):
"""Creates a promise object rejected with a certain value.""" |
p = Promise()
p._state = 'rejected'
p.reason = reason
return p |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve(self, value):
"""Resolves the promise with the given 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 != 'pending':
raise RuntimeError('Promise is no longer pending.')
self.value = value
self._state = 'resolved'
callbacks = self._callbacks
self._callbacks = None
for callback in callbacks:
callback(value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reject(self, reason):
"""Rejects the promise with the given reason.""" |
if self._state != 'pending':
raise RuntimeError('Promise is no longer pending.')
self.reason = reason
self._state = 'rejected'
errbacks = self._errbacks
self._errbacks = None
for errback in errbacks:
errback(reason) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def done(self, on_success=None, on_failure=None):
"""Attaches some callbacks to the promise and returns the promise.""" |
if on_success is not None:
if self._state == 'pending':
self._callbacks.append(on_success)
elif self._state == 'resolved':
on_success(self.value)
if on_failure is not None:
if self._state == 'pending':
self._errbacks.append(on_failure)
elif self._state == 'rejected':
on_failure(self.reason)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_key(self, command, args):
"""Returns the key a command operates on.""" |
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 '
'result.' % command)
if 'movablekeys' in spec['flags']:
raise UnroutableCommand('The keys for "%r" are movable and '
'as such cannot be routed to a single '
'host.')
keys = extract_keys(args, spec['key_spec'])
if len(keys) == 1:
return keys[0]
elif not keys:
raise UnroutableCommand(
'The command "%r" does not operate on a key which means '
'that no suitable host could be determined. Consider '
'using a fanout instead.')
raise UnroutableCommand(
'The command "%r" operates on multiple keys (%d passed) which is '
'something that is not supported.' % (command, len(keys))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_host_for_command(self, command, args):
"""Returns the host this command should be executed against.""" |
return self.get_host_for_key(self.get_key(command, args)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _rebuild_circle(self):
"""Updates the hash ring.""" |
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(node, 1)
ks = math.floor((40 * len(self._nodes) * weight) / total_weight)
for i in xrange(0, int(ks)):
k = md5_bytes('%s-%s-salt' % (node, i))
for l in xrange(0, 4):
key = ((k[3 + l * 4] << 24) | (k[2 + l * 4] << 16) |
(k[1 + l * 4] << 8) | k[l * 4])
self._hashring[key] = node
self._sorted_keys.append(key)
self._sorted_keys.sort() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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]] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def check_error(result, func, cargs):
"Error checking proper value returns"
if result != 0:
msg = 'Error in "%s": %s' % (func.__name__, get_errors(result) )
raise RTreeError(msg)
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 > 0:
minutes = -minutes
else:
seconds = -seconds
return (degrees,minutes,seconds) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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
break
if not is_annotated:
raise core.RTreeError("unable to parse '%s' to decimal degrees" % dms)
is_negative = False
if is_annotated:
dms_upper = dms.upper()
if 'W' in dms_upper or 'S' in dms_upper:
is_negative = True
else:
if dms < 0:
is_negative = True
if is_annotated:
bletters = letters.encode(encoding='utf-8')
bdms = dms.encode(encoding = 'utf-8')
dms = bdms.translate(None, bletters).decode('ascii')
# bletters = bytes(letters, encoding='utf-8')
# bdms = bytes(dms, encoding='utf-8')
# dms = bdms.translate(None, bletters).decode('ascii')
# dms = dms.translate(None, letters) # Python 2.x version
pieces = dms.split(".")
D = 0.0
M = 0.0
S = 0.0
divisor = 3600.0
if len(pieces) == 1:
S = dms[-2:]
M = dms[-4:-2]
D = dms[:-4]
else:
S = '{0:s}.{1:s}'.format (pieces[0][-2:], pieces[1])
M = pieces[0][-4:-2]
D = pieces[0][:-4]
DD = float(D) + float(M)/60.0 + float(S)/divisor
if is_negative:
DD = DD * -1.0
return DD |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_fobj(fname, mode='w+'):
"""Obtain a proper file object. Parameters fname : string, file object, file descriptor If a string or file descriptor, then we create a file object. If *fname* is a file object, then we do nothing and ignore the specified *mode* parameter. mode : str The mode of the file to be opened. Returns ------- fobj : file object The file object. close : bool If *fname* was a string, then *close* will be *True* to signify that the file object should be closed after writing to it. Otherwise, *close* will be *False* signifying that the user, in essence, created the file object already and that subsequent operations should not close it. """ |
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
close = False
else:
# assume it is a file descriptor
fobj = os.fdopen(fname, mode)
close = False
return fobj, close |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def graph_from_dot_file(path):
"""Load graph as defined by a DOT file. The file is assumed to be in DOT format. It will be loaded, parsed and a Dot class will be returned, representing the graph. """ |
fd = open(path, 'rb')
data = fd.read()
fd.close()
return graph_from_dot_data(data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def graph_from_edges(edge_list, node_prefix='', directed=False):
"""Creates a basic graph out of an edge list. The edge list has to be a list of tuples representing the nodes connected by the edge. The values can be anything: bool, int, float, str. If the graph is undirected by default, it is only calculated from one of the symmetric halves of the matrix. """ |
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=graph_type)
for src, dst in edge_list:
src = with_prefix(src)
dst = with_prefix(dst)
graph.add_edge(Edge(src, dst))
return graph |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. """ |
node_orig = 1
if directed:
graph = Dot(graph_type='digraph')
else:
graph = Dot(graph_type='graph')
for row in matrix:
if not directed:
skip = matrix.index(row)
r = row[skip:]
else:
skip = 0
r = row
node_dest = skip + 1
for e in r:
if e:
graph.add_edge(
Edge(
node_prefix + node_orig,
node_prefix + node_dest))
node_dest += 1
node_orig += 1
return graph |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. """ |
if directed:
graph = Dot(graph_type='digraph')
else:
graph = Dot(graph_type='graph')
for row in matrix:
nodes = []
c = 1
for node in row:
if node:
nodes.append(c * node)
c += 1
nodes.sort()
if len(nodes) == 2:
graph.add_edge(
Edge(
node_prefix + abs(nodes[0]),
node_prefix + nodes[1]))
if not directed:
graph.set_simplify(True)
return graph |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __find_executables(path):
"""Used by find_graphviz path - single directory as a string If any of the executables are found, it will return a dictionary containing the program names as keys and their paths as values. Otherwise returns None """ |
success = False
progs = {
"dot": "",
"twopi": "",
"neato": "",
"circo": "",
"fdp": "",
"sfdp": "",
}
was_quoted = False
path = path.strip()
if path.startswith('"') and path.endswith('"'):
path = path[1:-1]
was_quoted = True
if not os.path.isdir(path):
return None
for prg in progs:
if progs[prg]:
continue
prg_path = os.path.join(path, prg)
prg_exe_path = prg_path + ".exe"
if os.path.exists(prg_path):
if was_quoted:
prg_path = "\"{}\"".format(prg_path)
progs[prg] = prg_path
success = True
elif os.path.exists(prg_exe_path):
if was_quoted:
prg_exe_path = "\"{}\"".format(prg_exe_path)
progs[prg] = prg_exe_path
success = True
if success:
return progs
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 PATH environment variable. Thirdly: Default install location (Windows only) It will look for 'dot', 'twopi' and 'neato' in the default install location under the "Program Files" directory. It will return a dictionary containing the program names as keys and their paths as values. If this fails, it returns None. """ |
# Method 1 (Windows only)
if os.sys.platform == 'win32':
HKEY_LOCAL_MACHINE = 0x80000002
KEY_QUERY_VALUE = 0x0001
RegOpenKeyEx = None
RegQueryValueEx = None
RegCloseKey = None
try:
import win32api
RegOpenKeyEx = win32api.RegOpenKeyEx
RegQueryValueEx = win32api.RegQueryValueEx
RegCloseKey = win32api.RegCloseKey
except ImportError:
# Print a messaged suggesting they install these?
pass
try:
import ctypes
def RegOpenKeyEx(key, subkey, opt, sam):
result = ctypes.c_uint(0)
ctypes.windll.advapi32.RegOpenKeyExA(key, subkey, opt, sam,
ctypes.byref(result))
return result.value
def RegQueryValueEx(hkey, valuename):
data_type = ctypes.c_uint(0)
data_len = ctypes.c_uint(1024)
data = ctypes.create_string_buffer(1024)
# this has a return value, which we should probably check
ctypes.windll.advapi32.RegQueryValueExA(
hkey, valuename, 0, ctypes.byref(data_type),
data, ctypes.byref(data_len))
return data.value
RegCloseKey = ctypes.windll.advapi32.RegCloseKey
except ImportError:
# Print a messaged suggesting they install these?
pass
if RegOpenKeyEx is not None:
# Get the GraphViz install path from the registry
hkey = None
potentialKeys = [
"SOFTWARE\\ATT\\Graphviz",
"SOFTWARE\\AT&T Research Labs\\Graphviz"]
for potentialKey in potentialKeys:
try:
hkey = RegOpenKeyEx(
HKEY_LOCAL_MACHINE,
potentialKey, 0, KEY_QUERY_VALUE)
if hkey is not None:
path = RegQueryValueEx(hkey, "InstallPath")
RegCloseKey(hkey)
# The regitry variable might exist, left by
# old installations but with no value, in those cases
# we keep searching...
if not path:
continue
# Now append the "bin" subdirectory:
path = os.path.join(path, "bin")
progs = __find_executables(path)
if progs is not None:
return progs
except Exception:
pass
else:
break
# Method 2 (Linux, Windows etc)
if 'PATH' in os.environ:
for path in os.environ['PATH'].split(os.pathsep):
progs = __find_executables(path)
if progs is not None:
return progs
# Method 3 (Windows only)
if os.sys.platform == 'win32':
# Try and work out the equivalent of "C:\Program Files" on this
# machine (might be on drive D:, or in a different language)
if 'PROGRAMFILES' in os.environ:
# Note, we could also use the win32api to get this
# information, but win32api may not be installed.
path = os.path.join(os.environ['PROGRAMFILES'], 'ATT',
'GraphViz', 'bin')
else:
# Just in case, try the default...
path = r"C:\Program Files\att\Graphviz\bin"
progs = __find_executables(path)
if progs is not None:
return progs
for path in (
'/usr/bin', '/usr/local/bin',
'/opt/local/bin',
'/opt/bin', '/sw/bin', '/usr/share',
'/Applications/Graphviz.app/Contents/MacOS/'):
progs = __find_executables(path)
if progs is not None:
return progs
# Failed to find GraphViz
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_node_list(self):
"""Get the list of Node instances. This method returns the list of Node instances composing the graph. """ |
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])
return node_objs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_d)
for obj_d
in obj_dict_list])
return edge_objs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.obj_dict['strict']:
graph.append('strict ')
if self.obj_dict['name'] == '':
if ('show_keyword' in self.obj_dict and
self.obj_dict['show_keyword']):
graph.append('subgraph {\n')
else:
graph.append('{\n')
else:
graph.append('%s %s {\n' % (self.obj_dict['type'],
self.obj_dict['name']))
for attr, value in sorted(self.obj_dict['attributes'].items(),
key=itemgetter(0)):
if value is not None:
graph.append('%s=%s' % (attr, quote_if_necessary(value)))
else:
graph.append(attr)
graph.append(';\n')
edges_done = set()
edge_obj_dicts = list()
for e in self.obj_dict['edges'].values():
edge_obj_dicts.extend(e)
if edge_obj_dicts:
edge_src_set, edge_dst_set = list(
zip(*[obj['points'] for obj in edge_obj_dicts]))
edge_src_set, edge_dst_set = set(edge_src_set), set(edge_dst_set)
else:
edge_src_set, edge_dst_set = set(), set()
node_obj_dicts = list()
for e in self.obj_dict['nodes'].values():
node_obj_dicts.extend(e)
sgraph_obj_dicts = list()
for sg in self.obj_dict['subgraphs'].values():
sgraph_obj_dicts.extend(sg)
obj_list = sorted([
(obj['sequence'], obj)
for obj
in (edge_obj_dicts + node_obj_dicts + sgraph_obj_dicts)])
for _idx, obj in obj_list:
if obj['type'] == 'node':
node = Node(obj_dict=obj)
if self.obj_dict.get('suppress_disconnected', False):
if (node.get_name() not in edge_src_set and
node.get_name() not in edge_dst_set):
continue
graph.append(node.to_string() + '\n')
elif obj['type'] == 'edge':
edge = Edge(obj_dict=obj)
if self.obj_dict.get('simplify', False) and edge in edges_done:
continue
graph.append(edge.to_string() + '\n')
edges_done.add(edge)
else:
sgraph = Subgraph(obj_dict=obj)
graph.append(sgraph.to_string() + '\n')
graph.append('}\n')
return ''.join(graph) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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' can also be an open file-like object, such as a StringIO instance. The format 'raw' is used to dump the string representation of the Dot object, without further processing. The output can be processed by any of graphviz tools, defined in 'prog', which defaults to 'dot' Returns True or False according to the success of the write operation. There's also the preferred possibility of using: write_'format'(path, prog='program') which are automatically defined for all the supported formats. """ |
if prog is None:
prog = self.prog
fobj, close = get_fobj(path, 'w+b')
try:
if format == 'raw':
data = self.to_string()
if isinstance(data, basestring):
if not isinstance(data, unicode):
try:
data = unicode(data, 'utf-8')
except Exception:
pass
try:
charset = self.get_charset()
if not PY3 or not charset:
charset = 'utf-8'
data = data.encode(charset)
except Exception:
if PY3:
data = data.encode('utf-8')
pass
fobj.write(data)
else:
fobj.write(self.create(prog, format))
finally:
if close:
fobj.close()
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_crumbs(self):
""" Get crumbs for navigation links. Returns: tuple: concatenated list of crumbs using these crumbs and the crumbs of the parent classes through ``__mro__``. """ |
crumbs = []
for cls in reversed(type(self).__mro__[1:]):
crumbs.extend(getattr(cls, 'crumbs', ()))
crumbs.extend(list(self.crumbs))
return tuple(crumbs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, request, *args, **kwargs):
""" Django view get function. Add items of extra_context, crumbs and grid to context. Args: request ():
Django's request object. *args ():
request args. **kwargs ():
request kwargs. Returns: response: render to response with context. """ |
context = self.get_context_data(**kwargs)
context.update(self.extra_context)
context['crumbs'] = self.get_crumbs()
context['title'] = self.title
context['suit'] = 'suit' in settings.INSTALLED_APPS
if context.get('dashboard_grid', None) is None and self.grid:
context['dashboard_grid'] = self.grid
return self.render_to_response(context) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 matched. time_interval (int):
the interval of refreshment in milliseconds. Returns: Widget: the "real-timed" widget. """ |
if not hasattr(widget, 'get_updated_content'):
raise AttributeError('Widget %s must implement get_updated_content '
'method.' % widget)
elif not callable(widget.get_updated_content):
raise ValueError('get_updated_content in widget %s is not callable'
% widget)
if url_name is None:
if getattr(widget, 'url_name', None) is not None:
url_name = widget.url_name
else:
url_name = widget.__class__.__name__
if url_name in [w.url_name for w in REALTIME_WIDGETS]:
raise ValueError('URL name %s is already used by another '
'real time widget.' % url_name)
if url_regex is None:
if getattr(widget, 'url_regex', None) is not None:
url_regex = widget.url_regex
else:
url_regex = sha256(url_name.encode('utf-8'))
url_regex = url_regex.hexdigest()[:32]
url_regex = 'realtime/' + url_regex
if url_regex in [w.url_regex for w in REALTIME_WIDGETS]:
raise ValueError('URL regex %s is already used by another '
'real time widget.' % url_regex)
if time_interval is None:
if getattr(widget, 'time_interval', None) is not None:
time_interval = widget.time_interval
else:
time_interval = app_settings.default_time_interval
from django.views.generic import View
from braces.views import AjaxResponseMixin, JSONResponseMixin
# pylama:ignore=C0111,R0201
class PartialResponse(JSONResponseMixin, AjaxResponseMixin, View):
def get_data(self):
return widget.get_updated_content()
def get(self, request, *args, **kwargs):
return self.get_ajax(request, *args, **kwargs)
def get_ajax(self, request, *args, **kwargs):
return self.render_json_response(self.get_data())
PartialResponse.url_name = url_name
PartialResponse.url_regex = url_regex
PartialResponse.time_interval = time_interval
REALTIME_WIDGETS.append(PartialResponse)
if not hasattr(widget, 'url_name'):
widget.url_name = url_name
if not hasattr(widget, 'url_regex'):
widget.url_regex = url_regex
if not hasattr(widget, 'time_interval'):
widget.time_interval = time_interval
return widget |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_realtime_urls(admin_view_func=lambda x: x):
""" Get the URL for real-time widgets. Args: admin_view_func (callable):
an admin_view method from an AdminSite instance. By default: identity. Returns: list: the list of the real-time URLs as django's ``url()``. """ |
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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_time(self):
""" Make sure our Honeypot time is consistent, and not too far off from the actual time. """ |
poll = self.config['timecheck']['poll']
ntp_poll = self.config['timecheck']['ntp_pool']
while True:
clnt = ntplib.NTPClient()
try:
response = clnt.request(ntp_poll, version=3)
diff = response.offset
if abs(diff) >= 15:
logger.error('Timings found to be far off, shutting down drone ({0})'.format(diff))
sys.exit(1)
else:
logger.debug('Polled ntp server and found that drone has {0} seconds offset.'.format(diff))
except (ntplib.NTPException, _socket.error) as ex:
logger.warning('Error while polling ntp server: {0}'.format(ex))
gevent.sleep(poll * 60 * 60) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.