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 _construct_columns(self, column_map):
''' a helper method for constructing the column objects for a table object '''
from sqlalchemy import Column, String, Boolean, Integer, Float, Binary
column_args = []
for key, value in column_map.items():
recor... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _reconstruct_record(self, record_object):
''' a helper method for reconstructing record fields from record object '''
record_details = {}
current_details = record_details
for key, value in self.model.keyMap.items():
record_key = key[1:]
if re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _compare_columns(self, new_columns, old_columns):
''' a helper method for generating differences between column properties '''
# print(new_columns)
# print(old_columns)
add_columns = {}
remove_columns = {}
rename_columns = {}
retype_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _construct_inserts(self, record, new_columns, rename_columns, retype_columns, resize_columns):
''' a helper method for constructing the insert kwargs for a record '''
insert_kwargs = {}
for key, value in new_columns.items():
# retrieve value for key (or from old key 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 generate(self, gender=None, part=None, snake_case=False, weighted=False):
"""Generate a Queb name. :param str gender: Gender of name to generate, one of 'mal... |
if weighted:
get_random_name = self._get_weighted_random_name
else:
get_random_name = self._get_random_name
if gender == 'male':
first_names = self._male_names
elif gender == 'female':
first_names = self._female_names
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_name_file(self, filename):
"""Read a name file from the data directory :param filename: Name of the file to read. :return: A list of name entries. """ |
file_path = os.path.join(self._DATA_DIR, filename)
with open(file_path) as f:
names = json.load(f)
return names |
<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_names(self):
"""Get the list of first names. :return: A list of first name entries. """ |
names = self._read_name_file('names.json')
names = self._compute_weights(names)
return names |
<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_surnames(self):
"""Get the list of surnames. :return: A list of surname entries. """ |
names = self._read_name_file('surnames.json')
names = self._compute_weights(names)
return names |
<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_random_name(name_list):
"""Get a random name from a given list. The choice of the name is fully random. :param name_list: The list of names from which t... |
length = len(name_list)
index = random.randrange(length)
return name_list[index]['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 _get_weighted_random_name(name_list):
"""Get a random name from a given list, according to its frequency. The choice of the name is random, but weighted in p... |
total_weight = name_list[-1]['weight_high']
random_weight = random.randrange(total_weight + 1)
left = 0
right = len(name_list) - 1
while left <= right:
index = (left + right) // 2
entry = name_list[index]
if random_weight > entry['weight_hi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _format_name(self, name, surname, snake_case=False):
"""Format a first name and a surname into a cohesive string. Note that either name or surname can be emp... |
if not name or not surname:
sep = ''
elif snake_case:
sep = '_'
else:
sep = ' '
if snake_case:
name = self._snakify_name(name)
surname = self._snakify_name(surname)
disp_name = '{}{}{}'.format(name, sep, surname)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _snakify_name(self, name):
"""Snakify a name string. In this context, "to snakify" means to strip a name of all diacritics, convert it to lower case, and rep... |
name = self._strip_diacritics(name)
name = name.lower()
name = name.replace(' ', '-')
return 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 cmp_val_salt_hash(val, salt, str_hash):
""" Given a string, salt, & hash validate the string The salt & val will be concatented as in gen_salt_and hash() & c... |
computed_hash = hashlib.sha256(val + salt).hexdigest()
return computed_hash == str_hash |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gen_salt_and_hash(val=None):
""" Generate a salt & hash If no string is provided then a random string will be used to hash & referred to as `val`. The salt w... |
if not val:
val = random_str()
str_salt = random_str()
str_hash = hashlib.sha256(val + str_salt).hexdigest()
return str_salt, str_hash |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def str_to_bool(val):
""" Return a boolean if the string value represents one :param val: str :return: bool :raise: ValueError """ |
if isinstance(val, bool):
return val
elif val.lower() == 'true':
return True
elif val.lower() == 'false':
return False
else:
raise ValueError |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def str_to_dt(val):
""" Return a datetime object if the string value represents one Epoch integer or an ISO 8601 compatible string is supported. :param val: str ... |
if isinstance(val, dt):
return val
try:
if val.isdigit():
return dt.utcfromtimestamp(float(val))
else:
return dt.strptime(val, '%Y-%m-%dT%H:%M:%S.%f')
except (AttributeError, TypeError):
raise ValueError |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _format_and_write(self, level, correlation_id, error, message, *args, **kwargs):
""" Formats the log message and writes it to the logger destination. :param ... |
if message != None and len(message) > 0 and len(kwargs) > 0:
message = message.format(*args, **kwargs)
self._write(level, correlation_id, error, message) |
<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(self, level, correlation_id, error, message, *args, **kwargs):
""" Logs a message at specified log level. :param level: a log level. :param correlation_i... |
self._format_and_write(level, correlation_id, error, message, 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 error(self, correlation_id, error, message, *args, **kwargs):
""" Logs recoverable application error. :param correlation_id: (optional) transaction id to tra... |
self._format_and_write(LogLevel.Error, correlation_id, error, message, 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 warn(self, correlation_id, message, *args, **kwargs):
""" Logs a warning that may or may not have a negative impact. :param correlation_id: (optional) transa... |
self._format_and_write(LogLevel.Warn, correlation_id, None, message, 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 info(self, correlation_id, message, *args, **kwargs):
""" Logs an important information message :param correlation_id: (optional) transaction id to trace exe... |
self._format_and_write(LogLevel.Info, correlation_id, None, message, 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 debug(self, correlation_id, message, *args, **kwargs):
""" Logs a high-level debug information for troubleshooting. :param correlation_id: (optional) transac... |
self._format_and_write(LogLevel.Debug, correlation_id, None, message, 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 trace(self, correlation_id, message, *args, **kwargs):
""" Logs a low-level debug information for troubleshooting. :param correlation_id: (optional) transact... |
self._format_and_write(LogLevel.Trace, correlation_id, None, message, 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 check_ipv6(ip_str):
""" Return True if is a valid IP v6 """ |
try:
socket.inet_pton(socket.AF_INET6, ip_str)
except socket.error:
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 check_ipv4(ip_str):
""" Return True if is a valid IP v4 """ |
try:
socket.inet_pton(socket.AF_INET, ip_str)
except AttributeError:
try:
socket.inet_aton(ip_str)
except socket.error:
return False
return ip_str.count('.') == 3
except socket.error:
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 gen_str_to_sign(self, req):
"""Generate string to sign using giving prepared request""" |
url = urlsplit(req.url)
bucket_name = url.netloc.split(".", 1)[0]
logger.debug(req.headers.items())
ucloud_headers = [
(k, v.strip())
for k, v in sorted(req.headers.lower_items())
if k.startswith("x-ucloud-")
]
canonicalized_headers =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fill_all_headers(self, req):
"""Set content-type, content-md5, date to the request.""" |
url = urlsplit(req.url)
content_type, __ = mimetypes.guess_type(url.path)
if content_type is None:
content_type = self.DEFAULT_TYPE
logger.warn("can not determine mime-type for {0}".format(url.path))
if self._expires is None:
# sign with url, no cont... |
<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_old_options(cli, image):
""" Returns Dockerfile values for CMD and Entrypoint """ |
return {
'cmd': dockerapi.inspect_config(cli, image, 'Cmd'),
'entrypoint': dockerapi.inspect_config(cli, image, 'Entrypoint'),
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restore_image_options(cli, image, options):
""" Restores CMD and ENTRYPOINT values of the image This is needed because we force the overwrite of ENTRYPOINT a... |
dockerfile = io.StringIO()
dockerfile.write(u'FROM {image}\nCMD {cmd}'.format(
image=image, cmd=json.dumps(options['cmd'])))
if options['entrypoint']:
dockerfile.write(
'\nENTRYPOINT {}'.format(json.dumps(options['entrypoint'])))
cli.build(tag=image, fileobj=dockerfile) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_code_in_container(cli, image, code, mount, entrypoint):
""" Run `code` in a container, returning its ID """ |
kwargs = {
'image': image,
}
if entrypoint:
kwargs['entrypoint'] = '/bin/bash'
kwargs['command'] = '-c {}'.format(quote(code))
else:
kwargs['command'] = '/bin/bash -c {}'.format(quote(code))
if mount:
binds = []
volumes = []
for m in mount:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def read(src):
'Event generator from u2 stream.'
parser, buff_agg = Parser(), ''
while True:
buff = parser.read(src)
if not buff: break # EOF
buff_agg += buff
while True:
buff_agg, ev = parser.process(buff_agg)
if ev is None: break
yield ev |
<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_and_check_settings(base_settings, file_name=None, section=None, base_path=None, strategy_type=INIJSONStrategy, disable=None, prompt=None, quiet=None):
"... |
environ_config = get_config_from_environ()
disable = environ_config['disable'] if disable is None else disable
prompt = environ_config['prompt'] if prompt is None else prompt
quiet = environ_config['quiet'] if quiet is None else quiet
if disable:
return {}
if file_name is 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 fetch_challenge(http_header):
""" apparently keywords Basic and Digest are not being checked anywhere and decisions are being made based on authorization con... |
m = fetch_challenge.wwwauth_header_re.match(http_header)
if m is None:
raise RuntimeError, 'expecting "WWW-Authenticate header [Basic,Digest]"'
d = dict(challenge=m.groups()[0])
m = fetch_challenge.auth_param_re.search(http_header)
while m is not None:
k,v = http_header[m.start():m.end()].split(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open_url(self, url):
""" Open's URL with apiToken in the headers """ |
try:
c = pycurl.Curl()
c.setopt(pycurl.FAILONERROR, True)
c.setopt(pycurl.URL, "%s/api/v0/%s" % (self.url, url))
c.setopt(pycurl.HTTPHEADER, ["User-Agent: %s" % self.userAgent,
"apiToken: %s" % self.apiToken])
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _loadConfiguration(self):
""" Load module configuration files. :return: <void> """ |
configPath = os.path.join(self.path, "config")
if not os.path.isdir(configPath):
return
config = Config(configPath)
Config.mergeDictionaries(config.getData(), self.application.config) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _loadModels(self):
""" Load module models. :return: <void> """ |
modelsPath = os.path.join(self.path, "model")
if not os.path.isdir(modelsPath):
return
for modelFile in os.listdir(modelsPath):
modelName = modelFile.replace(".py", "")
modelPath = os.path.join(
self.path, "model", modelFile
)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _loadServices(self):
""" Load module services. :return: <void> """ |
servicesPath = os.path.join(self.path, "service")
if not os.path.isdir(servicesPath):
return
self._scanDirectoryForServices(servicesPath) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _loadService(self, servicePath):
""" Check if an application service can be found at the specified path. If found, instantiate it and add it to the applicati... |
serviceName = ntpath.basename(servicePath).replace(".py", "")
# importing service
serviceSpec = importlib.util.spec_from_file_location(
serviceName,
servicePath
)
service = importlib.util.module_from_spec(serviceSpec)
serviceSpec.loader.exec_modu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post(self, request, key):
"""Create new email address that will wait for validation""" |
email = request.POST.get('email')
user_id = request.POST.get('user')
if not email:
return http.HttpResponseBadRequest()
try:
EmailAddressValidation.objects.create(address=email,
user_id=user_id)
except I... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def multi_iter(iterable, count=2):
"""Return `count` independent, thread-safe iterators for `iterable`""" |
# no need to special-case re-usable, container-like iterables
if not isinstance(
iterable,
(
list, tuple, set,
FutureChainResults,
collections.Sequence, collections.Set, collections.Mapping, collections.MappingView
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def realise(self):
""" Realise the future if possible If the future has not been realised yet, do so in the current thread. This will block execution until the f... |
if self._mutex.acquire(False):
# realise the future in this thread
try:
if self._result is not None:
return True
call, args, kwargs = self._instruction
try:
result = call(*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 result(self):
""" The result from realising the future If the result is not available, block until done. :return: result of the future :raises: any exception... |
if self._result is None:
self.await_result()
chunks, exception = self._result
if exception is None:
return chunks
raise exception |
<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_warcinfo(self):
'''
Returns WARCINFO record from the archieve as a single string including
WARC header. Expects the record to be in the beginning of the archieve,
otherwise it will be not found.
'''
if self.searched_for_warcinfo:
return self.warcinfo
prev_line = None
in_warcinfo_rec... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def init_state(self):
''' Sets the initial state of the state machine. '''
self.in_warc_response = False
self.in_http_response = False
self.in_payload = 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 _keys_from_label(self, label):
'''Convert a label into a kvl key.
'''
k1 = (label.content_id1, label.content_id2,
label.annotator_id, time_complement(label.epoch_ticks))
k2 = (label.content_id2, label.content_id1,
label.annotator_id, time_complement(label.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _value_from_label(self, label):
'''Convert a label into a kvl value.
'''
unser_val = (label.rel_strength.value, label.meta)
return cbor.dumps(unser_val) |
<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, cid1, cid2, annotator_id):
'''Retrieve a relation label from the store.
'''
t = (cid1, cid2, annotator_id)
for k, v in self.kvl.scan(self.TABLE, (t, t)):
return self._label_from_kvlayer(k, v) |
<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_related(self, content_id, min_strength=None):
'''Get positive relation labels for ``cid``.
If ``min_strength`` is set, will restrict results to labels
with a ``rel_strength`` greater or equal to the provided
``RelationStrength`` value. Note: ``min_strength`` should be of
... |
<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_related_ids(self, content_id, min_strength=None):
'''Get identifiers for related identifiers.
'''
related_labels = self.get_related(content_id,
min_strength=min_strength)
related_idents = set()
for label in related_labels:
... |
<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_relationships_for_idents(self, cid, idents):
'''Get relationships between ``idents`` and a ``cid``.
Returns a dictionary mapping the identifiers in ``idents``
to either None, if no relationship label is found between
the identifier and ``cid``, or a RelationshipType classifying
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_field(param, fields):
""" Ensure the sortable field exists on the model """ |
if param.field not in fields:
raise InvalidQueryParams(**{
'detail': 'The sort query param value of "%s" is '
'invalid. That field does not exist on the '
'resource being requested.' % param.raw_field,
'links': LINK,
'paramete... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_no_rels(param, rels):
""" Ensure the sortable field is not on a relationship """ |
if param.field in rels:
raise InvalidQueryParams(**{
'detail': 'The sort query param value of "%s" is not '
'supported. Sorting on relationships is not '
'currently supported' % param.raw_field,
'links': LINK,
'parameter': PAR... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init(req, model):
""" Determine the sorting preference by query parameter Return an array of Sortable objects. """ |
rels = model.relationships
fields = model.all_fields
params = req.get_param_as_list('sort') or [goldman.config.SORT]
params = [Sortable(param.lower()) for param in params]
for param in params:
_validate_no_rels(param, rels)
_validate_field(param, fields)
return params |
<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_site(self, url, headers, cookies, timeout, driver_args, driver_kwargs):
""" Try and return page content in the requested format using requests """ |
try:
# Headers and cookies are combined to the ones stored in the requests session
# Ones passed in here will override the ones in the session if they are the same key
response = self.driver.get(url,
*driver_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 _new_controller(self, addr, port):
""" Get an uid for your controller. :param addr: Address of the controller :param port: Port of the controller :type addr:... |
for uid, controller in self.controllers.items():
if controller[0] == addr:
# duplicate address. sending the uid again
#print('/uid/{} => {}:{}'.format(uid, addr, port))
self.sock.sendto('/uid/{}'.format(uid).encode('utf-8'), (addr, port))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _del_controller(self, uid):
""" Remove controller from internal list and tell the game. :param uid: Unique id of the controller :type uid: str """ |
try:
self.controllers.pop(uid)
e = Event(uid, E_DISCONNECT)
self.queue.put_nowait(e)
except KeyError:
# There is no such controller, ignore the command
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 _ping(self, uid, addr, port):
""" Just say hello so that pymlgame knows that your controller is still alive. Unused controllers will be deleted after a while... |
try:
self.controllers[uid][0] = addr
self.controllers[uid][1] = port
self.controllers[uid][3] = time.time()
e = Event(uid, E_PING)
self.queue.put_nowait(e)
except KeyError:
# There is no such controller, ignore the command
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _update_states(self, uid, states):
""" Got states of all buttons from a controller. Now check if something changed and create events if neccesary. :param uid... |
#TODO: use try and catch all exceptions
# test if uid exists
if self.controllers[uid]:
# test if states have correct lenght
if len(states) == 14:
old_states = self.controllers[uid][2]
if old_states != states:
for key in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _got_message(self, uid, text):
""" The controller has send us a message. :param uid: Unique id of the controller :param text: Text to display :type uid: str ... |
#TODO: use try
e = Event(uid, E_MESSAGE, text)
self.queue.put_nowait(e)
self.controllers[uid][2] = time.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 send(self, uid, event, payload=None):
""" Send an event to a connected controller. Use pymlgame event type and correct payload. To send a message to the cont... |
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
if uid in self.controllers.keys():
addr = self.controllers[uid][0]
port = self.controllers[uid][1]
if event == E_MESSAGE:
#print('/message/{} => {}:{}'.format(payload, addr, port))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
""" Listen for controllers. """ |
while True:
data, sender = self.sock.recvfrom(1024)
addr = sender[0]
msg = data.decode('utf-8')
if msg.startswith('/controller/'):
try:
uid = msg.split('/')[2]
if uid == 'new':
port =... |
<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_obj_frm_str(obj_str, **kwargs):
""" Returns a python object from a python object string args: obj_str: python object path expamle "rdfframework.connectio... |
obj_str = obj_str.format(**kwargs)
args = []
kwargs = {}
params = []
# parse the call portion of the string
if "(" in obj_str:
call_args = obj_str[obj_str.find("("):]
obj_str = obj_str[:obj_str.find("(")]
call_args = call_args[1:-1]
if call_args:
call... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pyfile_path(path):
""" converst a file path argment to the is path within the framework args: path: filepath to the python file """ |
if "/" in path:
parts = path.split("/")
join_term = "/"
elif "\\" in path:
parts =path.split("\\")
join_term = "\\"
parts.reverse()
base = parts[:parts.index('rdfframework')]
base.reverse()
return join_term.join(base) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def nz(value, none_value, strict=True):
''' This function is named after an old VBA function. It returns a default
value if the passed in value is None. If strict is False it will
treat an empty string as None as well.
example:
x = None
nz(x,"hello")
--> "hello"
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def make_set(value):
''' Takes a value and turns it into a set
!!!! This is important because set(string) will parse a string to
individual characters vs. adding the string as an element of
the set i.e.
x = 'setvalue'
set(x) = {'t', 'a', 'e', 'v', 'u', 's', 'l'}
make_set(x) = {'... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_triple(sub, pred, obj):
"""Takes a subject predicate and object and joins them with a space in between Args: sub -- Subject pred -- Predicate obj -- Ob... |
return "{s} {p} {o} .".format(s=sub, p=pred, o=obj) |
<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_null(obj):
''' reads through a list or set and strips any null values'''
if isinstance(obj, set):
try:
obj.remove(None)
except:
pass
elif isinstance(obj, list):
for item in obj:
if not is_not_null(item):
obj.remove(item)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def delete_key_pattern(obj, regx_pattern):
''' takes a dictionary object and a regular expression pattern and removes
all keys that match the pattern.
args:
obj: dictionay object to search trhough
regx_pattern: string without beginning and ending / '''
if isinstance(obj, list):
... |
<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_dict_key(data, key):
''' will serach a mulitdemensional dictionary for a key name and return a
value list of matching results '''
if isinstance(data, Mapping):
if key in data:
yield data[key]
for key_data in data.values():
for found in get_dict_key(key_da... |
<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_attr(item, name, default=None):
''' similar to getattr and get but will test for class or dict '''
try:
val = item[name]
except (KeyError, TypeError):
try:
val = getattr(item, name)
except AttributeError:
val = default
return val |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get2(item, key, if_none=None, strict=True):
''' similar to dict.get functionality but None value will return then
if_none value
args:
item: dictionary to search
key: the dictionary key
if_none: the value to return if None is passed in
strict: if False an empty string... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def initialized(func):
""" decorator for testing if a class has been initialized prior to calling any attribute """ |
def wrapper(self, *args, **kwargs):
""" internal wrapper function """
if not self.__is_initialized__:
return EmptyDot()
return func(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 find(self, value):
""" returns a dictionary of items based on the a lowercase search args: value: the value to search by """ |
value = str(value).lower()
rtn_dict = RegistryDictionary()
for key, item in self.items():
if value in key.lower():
rtn_dict[key] = item
return rtn_dict |
<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, prop):
""" get the value off the passed in dot notation args: prop: a string of the property to retreive "a.b.c" ~ dictionary['a']['b']['c'] """ |
prop_parts = prop.split(".")
val = None
for part in prop_parts:
if val is None:
val = self.obj.get(part)
else:
val = val.get(part)
return val |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set(self, prop, value):
""" sets the dot notated property to the passed in value args: prop: a string of the property to retreive "a.b.c" ~ dictionary['a']['... |
prop_parts = prop.split(".")
if self.copy_dict:
new_dict = copy.deepcopy(self.obj)
else:
new_dict = self.obj
pointer = None
parts_length = len(prop_parts) - 1
for i, part in enumerate(prop_parts):
if pointer is None and i == parts_len... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dict(self):
""" converts the class to a dictionary object """ |
return_obj = {}
for attr in dir(self):
if not attr.startswith('__') and attr not in self.__reserved:
if isinstance(getattr(self, attr), list):
return_val = []
for item in getattr(self, attr):
if isinstance(item,... |
<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_anchor_href(markup):
""" Given HTML markup, return a list of hrefs for each anchor tag. """ |
soup = BeautifulSoup(markup, 'lxml')
return ['%s' % link.get('href') for link in soup.find_all('a')] |
<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_anchor_contents(markup):
""" Given HTML markup, return a list of href inner html for each anchor tag. """ |
soup = BeautifulSoup(markup, 'lxml')
return ['%s' % link.contents[0] for link in soup.find_all('a')] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def names_from_exp(exp):
"Return a list of AttrX and NameX from the expression."
def match(exp):
return isinstance(exp, (sqparse2.NameX, sqparse2.AttrX))
paths = treepath.sub_slots(exp, match, match=True, recurse_into_matches=False)
return [exp[path] for path in paths] |
<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_tarball(self, tarball, package):
"""Add a tarball, possibly creating the directory if needed.""" |
if tarball is None:
logger.error(
"No tarball found for %s: probably a renamed project?",
package)
return
target_dir = os.path.join(self.root_directory, package)
if not os.path.exists(target_dir):
os.mkdir(target_dir)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ls(self):
""" List the objects in the current namespace, in alphabetical order. """ |
width = max([len(x) for x in self.namespace.keys()])
for key, value in sorted(self.namespace.items()):
if key == "_":
continue
info = ""
if (isinstance(value, dict) or
isinstance(value, list) or key == "services"):
info... |
<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_unicode(text, charset=None):
"""Convert input to an `unicode` object. For a `str` object, we'll first try to decode the bytes using the given `charset` en... |
if isinstance(text, str):
try:
return unicode(text, charset or 'utf-8')
except UnicodeDecodeError:
return unicode(text, 'latin1')
elif isinstance(text, Exception):
if os.name == 'nt' and \
isinstance(text, (OSError, IOError)): # pragma: no cover
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exception_to_unicode(e, traceback=False):
"""Convert an `Exception` to an `unicode` object. In addition to `to_unicode`, this representation of the exception... |
message = '%s: %s' % (e.__class__.__name__, to_unicode(e))
if traceback:
from docido_sdk.toolbox import get_last_traceback
traceback_only = get_last_traceback().split('\n')[:-2]
message = '\n%s\n%s' % (to_unicode('\n'.join(traceback_only)), message)
return message |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def levenshtein(s, t):
""" Compute the Levenshtein distance between 2 strings, which is the minimum number of operations required to perform on a string to get a... |
''' From Wikipedia article; Iterative with two matrix rows. '''
if s == t:
return 0
elif len(s) == 0:
return len(t)
elif len(t) == 0:
return len(s)
v0 = [None] * (len(t) + 1)
v1 = [None] * (len(t) + 1)
for i in range(len(v0)):
v0[i] = i
for i in range(len... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_help(self, line):
"""Displays help information.""" |
print ""
print "Perfdump CLI provides a handful of simple ways to query your"
print "performance data."
print ""
print "The simplest queries are of the form:"
print ""
print "\t[slowest|fastest] [tests|setups]"
print ""
print "For example:"
... |
<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_allposts(self):
''' Return all posts in blog sorted by date
'''
result = self.client.posts(self.blog, offset = 0, limit = 1)
try:
total_posts = result['total_posts']
except:
raise phasetumblr_errors.TumblrBlogException(result['meta']['msg'])
delta = (total_posts / 10) + 1
all_posts = []
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def n_to_pf(L, n, R):
"""Returns the packing fraction for a number of non-intersecting spheres. Parameters L: float array, shape (d,) System lengths. n: integer ... |
dim = L.shape[0]
return (n * sphere_volume(R=R, n=dim)) / np.product(L) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pf_to_n(L, pf, R):
"""Returns the number of non-intersecting spheres required to achieve as close to a given packing fraction as possible, along with the act... |
dim = L.shape[0]
n = int(round(pf * np.product(L) / sphere_volume(R, dim)))
pf_actual = n_to_pf(L, n, R)
return n, pf_actual |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pack_simple(R, L, pf=None, n=None, rng=None, periodic=False):
"""Pack a number of non-intersecting spheres into a system. Can specify packing by number of sp... |
if rng is None:
rng = np.random
if pf is not None:
if pf == 0.0:
return np.array([]), R
# If packing fraction is specified, find required number of spheres
# and the actual packing fraction this will produce
n, pf_actual = pf_to_n(L, pf, R)
elif n is not ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pack(R, L, pf=None, n=None, rng=None, periodic=False, beta_max=1e4, dL_max=0.02, dr_max=0.02):
"""Pack a number of non-intersecting spheres into a periodic s... |
if pf is not None:
if pf == 0.0:
return np.array([]), R
# If packing fraction is specified, find required number of spheres
# and the actual packing fraction this will produce
n, pf_actual = pf_to_n(L, pf, R)
elif n is not None:
if n == 0:
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 relpath_for(self, path):
"""Find the relative path from here from the parent_dir""" |
if self.parent_dir in (".", ""):
return path
if path == self.parent_dir:
return ""
dirname = os.path.dirname(path) or "."
basename = os.path.basename(path)
cached = self.relpath_cache.get(dirname, empty)
if cached is empty:
cached =... |
<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(self):
""" Find all the files we want to find commit times for, and any extra files under symlinks. Then find the commit times for those files and retur... |
mtimes = {}
git = Repo(self.root_folder)
all_files = git.all_files()
use_files = set(self.find_files_for_use(all_files))
# the git index won't find the files under a symlink :(
# And we include files under a symlink as seperate copies of the files
# So we still... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def commit_times_for(self, git, use_files):
""" Return commit times for the use_files specified. We will use a cache of commit times if self.with_cache is Truthy... |
# Use real_relpath if it exists (SymlinkdPath) and default to just the path
# This is because we _want_ to compare the commits to the _real paths_
# As git only cares about the symlink itself, rather than files under it
# We also want to make sure that the symlink targets are included i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extra_symlinked_files(self, potential_symlinks):
""" Find any symlinkd folders and yield SymlinkdPath objects for each file that is found under the symlink. ... |
for key in list(potential_symlinks):
location = os.path.join(self.root_folder, key.path)
real_location = os.path.realpath(location)
if os.path.islink(location) and os.path.isdir(real_location):
for root, dirs, files in os.walk(real_location, followlinks=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 find_files_for_use(self, all_files):
""" Given a list of all the files to consider, only yield Path objects for those we care about, given our filters """ |
for path in all_files:
# Find the path relative to the parent dir
relpath = self.relpath_for(path)
# Don't care about the ./
if relpath.startswith("./"):
relpath = relpath[2:]
# Only care about paths that aren't filtered
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_filtered(self, relpath):
"""Say whether this relpath is filtered out""" |
# Only include files under the parent_dir
if relpath.startswith("../"):
return True
# Ignore files that we don't want timestamps from
if self.timestamps_for is not None and type(self.timestamps_for) is list:
match = False
for line in self.timestamps_... |
<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_args_and_defaults(args, defaults):
"""Return a list of 2-tuples - the argument name and its default value or a special value that indicates there is no ... |
defaults = defaults or []
args_and_defaults = [(argument, default) for (argument, default)
in zip_longest(args[::-1], defaults[::-1],
fillvalue=NoDefault)]
return args_and_defaults[::-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 _prepare_doc(func, args, delimiter_chars):
"""From the function docstring get the arg parse description and arguments help message. If there is no docstring ... |
_LOG.debug("Preparing doc for '%s'", func.__name__)
if not func.__doc__:
return _get_default_help_message(func, args)
description = []
args_help = {}
fill_description = True
arg_name = None
arg_doc_regex = re.compile("\b*(?P<arg_name>\w+)\s*%s\s*(?P<help_msg>.+)" %
... |
<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_default_help_message(func, args, description=None, args_help=None):
"""Create a default description for the parser and help message for the agurments if... |
if description is None:
description = "Argument parsing for %s" % func.__name__
args_help = args_help or {}
# If an argument is missing a help message we create a simple one
for argument in [arg_name for arg_name in args
if arg_name not in args_help]:
args_help[argu... |
<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_arg_parser(func, types, args_and_defaults, delimiter_chars):
"""Return an ArgumentParser for the given function. Arguments are defined from the function... |
_LOG.debug("Creating ArgumentParser for '%s'", func.__name__)
(description, arg_help) = _prepare_doc(
func, [x for (x, _) in args_and_defaults], delimiter_chars)
parser = argparse.ArgumentParser(description=description)
for ((arg, default), arg_type) in zip_longest(args_and_defaults, types):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.