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 read_buf(self):
"""Read database file""" |
with open(self.filepath, 'rb') as handler:
try:
buf = handler.read()
# There should be a header at least
if len(buf) < 124:
raise KPError('Unexpected file size. It should be more or'
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close(self):
"""This method closes the database correctly.""" |
if self.filepath is not None:
if path.isfile(self.filepath+'.lock'):
remove(self.filepath+'.lock')
self.filepath = None
self.read_only = False
self.lock()
return True
else:
raise KPError('Can\'t close a 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 lock(self):
"""This method locks the database.""" |
self.password = None
self.keyfile = None
self.groups[:] = []
self.entries[:] = []
self._group_order[:] = []
self._entry_order[:] = []
self.root_group = v1Group()
self._num_groups = 1
self._num_entries = 0
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 unlock(self, password = None, keyfile = None, buf = None):
"""Unlock the database. masterkey is needed. """ |
if ((password is None or password == "") and (keyfile is None or
keyfile == "")):
raise KPError("A password/keyfile is needed")
elif ((type(password) is not str and password is not None) or
(type(keyfile) is not str and keyfile is not None)):
raise KP... |
<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_group(self, group = None):
"""This method removes a group. The group needed to remove the group. group must be a v1Group. """ |
if group is None:
raise KPError("Need group to remove a group")
elif type(group) is not v1Group:
raise KPError("group must be v1Group")
children = []
entries = []
if group in self.groups:
# Save all children and entries to
# dele... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move_group(self, group = None, parent = None):
"""Append group to a new parent. group and parent must be v1Group-instances. """ |
if group is None or type(group) is not v1Group:
raise KPError("A valid group must be given.")
elif parent is not None and type(parent) is not v1Group:
raise KPError("parent must be a v1Group.")
elif group is parent:
raise KPError("group and parent must not b... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move_group_in_parent(self, group = None, index = None):
"""Move group to another position in group's parent. index must be a valid index of group.parent.grou... |
if group is None or index is None:
raise KPError("group and index must be set")
elif type(group) is not v1Group or type(index) is not int:
raise KPError("group must be a v1Group-instance and index "
"must be an integer.")
elif group 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 _move_group_helper(self, group):
"""A helper to move the chidren of a group.""" |
for i in group.children:
self.groups.remove(i)
i.level = group.level + 1
self.groups.insert(self.groups.index(group) + 1, i)
if i.children:
self._move_group_helper(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 create_entry(self, group = None, title = "", image = 1, url = "", username = "", password = "", comment = "", y = 2999, mon = 12, d = 28, h = 23, min_ = 59, s... |
if (type(title) is not str or
type(image) is not int or image < 0 or
type(url) is not str or
type(username) is not str or
type(password) is not str or
type(comment) is not str or
type(y) is not int or
type(mon) 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 remove_entry(self, entry = None):
"""This method can remove entries. The v1Entry-object entry is needed. """ |
if entry is None or type(entry) is not v1Entry:
raise KPError("Need an entry.")
elif entry in self.entries:
entry.group.entries.remove(entry)
self.entries.remove(entry)
self._num_entries -= 1
return True
else:
rais... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move_entry(self, entry = None, group = None):
"""Move an entry to another group. A v1Group group and a v1Entry entry are needed. """ |
if entry is None or group is None or type(entry) is not v1Entry or \
type(group) is not v1Group:
raise KPError("Need an entry and a group.")
elif entry not in self.entries:
raise KPError("No entry found.")
elif group in self.groups:
entry.group.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 move_entry_in_group(self, entry = None, index = None):
"""Move entry to another position inside a group. An entry and a valid index to insert the entry in th... |
if entry is None or index is None or type(entry) is not v1Entry \
or type(index) is not int:
raise KPError("Need an entry and an index.")
elif index < 0 or index > len(entry.group.entries)-1:
raise KPError("Index is not valid.")
elif entry not in self.entrie... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _transform_key(self, masterkey):
"""This method creates the key to decrypt the database""" |
aes = AES.new(self._transf_randomseed, AES.MODE_ECB)
# Encrypt the created hash
for _ in range(self._key_transf_rounds):
masterkey = aes.encrypt(masterkey)
# Finally, hash it again...
sha_obj = SHA256.new()
sha_obj.update(masterkey)
masterkey = sha... |
<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_filekey(self):
"""This method creates a key from a keyfile.""" |
if not os.path.exists(self.keyfile):
raise KPError('Keyfile not exists.')
try:
with open(self.keyfile, 'rb') as handler:
handler.seek(0, os.SEEK_END)
size = handler.tell()
handler.seek(0, os.SEEK_SET)
if size == 3... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _cbc_decrypt(self, final_key, crypted_content):
"""This method decrypts the database""" |
# Just decrypt the content with the created key
aes = AES.new(final_key, AES.MODE_CBC, self._enc_iv)
decrypted_content = aes.decrypt(crypted_content)
padding = decrypted_content[-1]
if sys.version > '3':
padding = decrypted_content[-1]
else:
padd... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _cbc_encrypt(self, content, final_key):
"""This method encrypts the content.""" |
aes = AES.new(final_key, AES.MODE_CBC, self._enc_iv)
padding = (16 - len(content) % AES.block_size)
for _ in range(padding):
content += chr(padding).encode()
temp = bytes(content)
return aes.encrypt(temp) |
<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_group_field(self, group, levels, field_type, field_size, decrypted_content):
"""This method handles the different fields of a group""" |
if field_type == 0x0000:
# Ignored (commentar block)
pass
elif field_type == 0x0001:
group.id_ = struct.unpack('<I', decrypted_content[:4])[0]
elif field_type == 0x0002:
try:
group.title = struct.unpack('<{0}s'.format(field_size-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 _read_entry_field(self, entry, field_type, field_size, decrypted_content):
"""This method handles the different fields of an entry""" |
if field_type == 0x0000:
# Ignored
pass
elif field_type == 0x0001:
entry.uuid = decrypted_content[:16]
elif field_type == 0x0002:
entry.group_id = struct.unpack('<I', decrypted_content[:4])[0]
elif field_type == 0x0003:
entry.... |
<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_date(self, decrypted_content):
"""This method is used to decode the packed dates of entries""" |
# Just copied from original KeePassX source
date_field = struct.unpack('<5B', decrypted_content[:5])
dw1 = date_field[0]
dw2 = date_field[1]
dw3 = date_field[2]
dw4 = date_field[3]
dw5 = date_field[4]
y = (dw1 << 6) | (dw2 >> 2)
mon = ((... |
<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_date(self, date):
"""This method is used to encode dates""" |
# Just copied from original KeePassX source
y, mon, d, h, min_, s = date.timetuple()[:6]
dw1 = 0x0000FFFF & ((y>>6) & 0x0000003F)
dw2 = 0x0000FFFF & ((y & 0x0000003F)<<2 | ((mon>>2) & 0x00000003))
dw3 = 0x0000FFFF & (((mon & 0x0000003)<<6) | ((d & 0x0000001F)<<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 _create_group_tree(self, levels):
"""This method creates a group tree""" |
if levels[0] != 0:
raise KPError("Invalid group tree")
for i in range(len(self.groups)):
if(levels[i] == 0):
self.groups[i].parent = self.root_group
self.groups[i].index = len(self.root_group.children)
self.root_group.chi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _save_group_field(self, field_type, group):
"""This method packs a group field""" |
if field_type == 0x0000:
# Ignored (commentar block)
pass
elif field_type == 0x0001:
if group.id_ is not None:
return (4, struct.pack('<I', group.id_))
elif field_type == 0x0002:
if group.title is not 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 _save_entry_field(self, field_type, entry):
"""This group packs a entry field""" |
if field_type == 0x0000:
# Ignored
pass
elif field_type == 0x0001:
if entry.uuid is not None:
return (16, entry.uuid)
elif field_type == 0x0002:
if entry.group_id is not None:
return (4, struct.pack('<I', entry.gro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getsecret(self, section, option, **kwargs):
"""Get a secret from Custodia """ |
# keyword-only arguments, vars and fallback are directly passed through
raw = kwargs.get('raw', False)
value = self.get(section, option, **kwargs)
if raw:
return value
return self.custodia_client.get_secret(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 _load_plugin_class(menu, name):
"""Load Custodia plugin Entry points are preferred over dotted import path. """ |
group = 'custodia.{}'.format(menu)
eps = list(pkg_resources.iter_entry_points(group, name))
if len(eps) > 1:
raise ValueError(
"Multiple entry points for {} {}: {}".format(menu, name, eps))
elif len(eps) == 1:
# backwards compatibility with old setuptools
ep = eps[0]... |
<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_plugins(config, cfgparser):
"""Load and initialize plugins """ |
# set umask before any plugin gets a chance to create a file
os.umask(config['umask'])
for s in cfgparser.sections():
if s in {'ENV', 'global'}:
# ENV section is only used for interpolation
continue
if s.startswith('/'):
menu = 'consumers'
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 get(self, po):
"""Lookup value for a PluginOption instance Args: po: PluginOption Returns: converted value """ |
name = po.name
typ = po.typ
default = po.default
handler = getattr(self, '_get_{}'.format(typ), None)
if handler is None:
raise ValueError(typ)
self.seen.add(name)
# pylint: disable=not-callable
if not self.parser.has_option(self.section, na... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(self, msg, name):
"""Parses a simple message :param msg: the json-decoded value :param name: the requested name :raises UnknownMessageType: if the type... |
# On requests we imply 'simple' if there is no input message
if msg is None:
return
if not isinstance(msg, string_types):
raise InvalidMessage("The 'value' attribute is not a string")
self.name = name
self.payload = msg
self.msg_type = 'simple' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def krb5_unparse_principal_name(name):
"""Split a Kerberos principal name into parts Returns: * ('host', hostname, realm) for a host principal * (servicename, ho... |
prefix, realm = name.split(u'@')
if u'/' in prefix:
service, host = prefix.rsplit(u'/', 1)
return service, host, realm
else:
return None, prefix, realm |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(self, msg, name):
"""Parses the message. We check that the message is properly formatted. :param msg: a json-encoded value containing a JWS or JWE+JWS ... |
try:
jtok = JWT(jwt=msg)
except Exception as e:
raise InvalidMessage('Failed to parse message: %s' % str(e))
try:
token = jtok.token
if isinstance(token, JWE):
token.decrypt(self.kkstore.server_keys[KEY_USAGE_ENC])
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instance_name(string):
"""Check for valid instance name """ |
invalid = ':/@'
if set(string).intersection(invalid):
msg = 'Invalid instance name {}'.format(string)
raise argparse.ArgumentTypeError(msg)
return 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 copy_magic_into_pyc(input_pyc, output_pyc, src_version, dest_version):
"""Bytecodes are the same except the magic number, so just change that""" |
(version, timestamp, magic_int,
co, is_pypy, source_size) = load_module(input_pyc)
assert version == float(src_version), (
"Need Python %s bytecode; got bytecode for version %s" %
(src_version, version))
magic_int = magic2int(magics[dest_version])
write_bytecode_file(output_pyc, co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transform_26_27(inst, new_inst, i, n, offset, instructions, new_asm):
"""Change JUMP_IF_FALSE and JUMP_IF_TRUE to POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE""" |
if inst.opname in ('JUMP_IF_FALSE', 'JUMP_IF_TRUE'):
i += 1
assert i < n
assert instructions[i].opname == 'POP_TOP'
new_inst.offset = offset
new_inst.opname = (
'POP_JUMP_IF_FALSE' if inst.opname == 'JUMP_IF_FALSE' else 'POP_JUMP_IF_TRUE'
)
new_as... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transform_32_33(inst, new_inst, i, n, offset, instructions, new_asm):
"""MAKEFUNCTION adds another const. probably MAKECLASS as well """ |
add_size = xdis.op_size(new_inst.opcode, opcode_33)
if inst.opname in ('MAKE_FUNCTION','MAKE_CLOSURE'):
# Previous instruction should be a load const which
# contains the name of the function to call
prev_inst = instructions[i-1]
assert prev_inst.opname == 'LOAD_CONST'
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 transform_33_32(inst, new_inst, i, n, offset, instructions, new_asm):
"""MAKE_FUNCTION, and MAKE_CLOSURE have an additional LOAD_CONST of a name that are not... |
add_size = xdis.op_size(new_inst.opcode, opcode_33)
if inst.opname in ('MAKE_FUNCTION','MAKE_CLOSURE'):
# Previous instruction should be a load const which
# contains the name of the function to call
prev_inst = instructions[i-1]
assert prev_inst.opname == 'LOAD_CONST'
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 main(conversion_type, input_pyc, output_pyc):
"""Convert Python bytecode from one version to another. INPUT_PYC contains the input bytecode path name OUTPUT_... |
shortname = osp.basename(input_pyc)
if shortname.endswith('.pyc'):
shortname = shortname[:-4]
src_version = conversion_to_version(conversion_type, is_dest=False)
dest_version = conversion_to_version(conversion_type, is_dest=True)
if output_pyc is None:
output_pyc = "%s-%s.pyc" % (s... |
<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, str=None, fpath=None):
"""generates fingerprints of the input. Either provide `str` to compute fingerprint directly from your string or `fpath... |
self.prepare_storage()
self.str = self.load_file(fpath) if fpath else self.sanitize(str)
self.validate_config()
self.generate_kgrams()
self.hash_kgrams()
self.generate_fingerprints()
return self.fingerprints |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(pyc_file, asm_path):
""" Create Python bytecode from a Python assembly file. ASM_PATH gives the input Python assembly file. We suggest ending the file i... |
if os.stat(asm_path).st_size == 0:
print("Size of assembly file %s is zero" % asm_path)
sys.exit(1)
asm = asm_file(asm_path)
if not pyc_file and asm_path.endswith('.pyasm'):
pyc_file = asm_path[:-len('.pyasm')] + '.pyc'
write_pycfile(pyc_file, asm) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expire(self, secs):
""" Adds the standard 'exp' field, used to prevent replay attacks. Adds the 'exp' field to the payload. When a request is made, the field... |
self.add_field('exp',
lambda req: int(time.time() + secs)) |
<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, request):
""" Generate a payload for the given request. """ |
payload = {}
for field, gen in self._generators.items():
value = None
if callable(gen):
value = gen(request)
else:
value = gen
if value:
payload[field] = value
return payload |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def url2fs(url):
""" encode a URL to be safe as a filename """ |
uri, extension = posixpath.splitext(url)
return safe64.dir(uri) + extension |
<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_merc_projection(srs):
""" Return true if the map projection matches that used by VEarth, Google, OSM, etc. Is currently necessary for zoom-level shorthand... |
if srs.lower() == '+init=epsg:900913':
return True
# observed
srs = dict([p.split('=') for p in srs.split() if '=' in p])
# expected
# note, common optional modifiers like +no_defs, +over, and +wkt
# are not pairs and should not prevent matching
gym = '+proj=merc +a=6378137 +b... |
<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_declarations(map_el, dirs, scale=1, user_styles=[]):
""" Given a Map element and directories object, remove and return a complete list of style decla... |
styles = []
#
# First, look at all the stylesheets defined in the map itself.
#
for stylesheet in map_el.findall('Stylesheet'):
map_el.remove(stylesheet)
content, mss_href = fetch_embedded_or_remote_src(stylesheet, dirs)
if content:
styles.append((... |
<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_applicable_selector(selector, filter):
""" Given a Selector and Filter, return True if the Selector is compatible with the given Filter, and False if they... |
for test in selector.allTests():
if not test.isCompatible(filter.tests):
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 get_polygon_rules(declarations):
""" Given a Map element, a Layer element, and a list of declarations, create a new Style element with a PolygonSymbolizer, a... |
property_map = {'polygon-fill': 'fill', 'polygon-opacity': 'fill-opacity',
'polygon-gamma': 'gamma',
'polygon-meta-output': 'meta-output', 'polygon-meta-writer': 'meta-writer'}
property_names = property_map.keys()
# a place to put rules
rules = []
... |
<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_raster_rules(declarations):
""" Given a Map element, a Layer element, and a list of declarations, create a new Style element with a RasterSymbolizer, add... |
property_map = {'raster-opacity': 'opacity',
'raster-mode': 'mode',
'raster-scaling': 'scaling'
}
property_names = property_map.keys()
# a place to put rules
rules = []
for (filter, values) in filtered_property_declarations(declarations... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def locally_cache_remote_file(href, dir):
""" Locally cache a remote resource using a predictable file name and awareness of modification date. Assume that files... |
scheme, host, remote_path, params, query, fragment = urlparse(href)
assert scheme in ('http','https'), 'Scheme must be either http or https, not "%s" (for %s)' % (scheme,href)
head, ext = posixpath.splitext(posixpath.basename(remote_path))
head = sub(r'[^\w\-_]', '', head)
hash = md5(href).he... |
<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_process_symbolizer_image_file(file_href, dirs):
""" Given an image file href and a set of directories, modify the image file name so it's correct with r... |
# support latest mapnik features of auto-detection
# of image sizes and jpeg reading support...
# http://trac.mapnik.org/ticket/508
mapnik_auto_image_support = (MAPNIK_VERSION >= 701)
mapnik_requires_absolute_paths = (MAPNIK_VERSION < 601)
file_href = urljoin(dirs.source.rstrip('/')+'/', file_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def localize_shapefile(shp_href, dirs):
""" Given a shapefile href and a set of directories, modify the shapefile name so it's correct with respect to the output... |
# support latest mapnik features of auto-detection
# of image sizes and jpeg reading support...
# http://trac.mapnik.org/ticket/508
mapnik_requires_absolute_paths = (MAPNIK_VERSION < 601)
shp_href = urljoin(dirs.source.rstrip('/')+'/', shp_href)
scheme, host, path, p, q, f = urlparse(shp_href... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def localize_file_datasource(file_href, dirs):
""" Handle localizing file-based datasources other than shapefiles. This will only work for single-file based type... |
# support latest mapnik features of auto-detection
# of image sizes and jpeg reading support...
# http://trac.mapnik.org/ticket/508
mapnik_requires_absolute_paths = (MAPNIK_VERSION < 601)
file_href = urljoin(dirs.source.rstrip('/')+'/', file_href)
scheme, n, path, p, q, f = urlparse(file_href... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def midpoint(self):
""" Return a point guranteed to fall within this range, hopefully near the middle. """ |
minpoint = self.leftedge
if self.leftop is gt:
minpoint += 1
maxpoint = self.rightedge
if self.rightop is lt:
maxpoint -= 1
if minpoint is None:
return maxpoint
elif maxpoint is None:
return minpoint
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def isOpen(self):
""" Return true if this range has any room in it. """ |
if self.leftedge and self.rightedge and self.leftedge > self.rightedge:
return False
if self.leftedge == self.rightedge:
if self.leftop is gt or self.rightop is lt:
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 toFilter(self, property):
""" Convert this range to a Filter with a tests having a given property. """ |
if self.leftedge == self.rightedge and self.leftop is ge and self.rightop is le:
# equivalent to ==
return Filter(style.SelectorAttributeTest(property, '=', self.leftedge))
try:
return Filter(style.SelectorAttributeTest(property, opstr[self.leftop], self.leftedg... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def isOpen(self):
""" Return true if this filter is not trivially false, i.e. self-contradictory. """ |
equals = {}
nequals = {}
for test in self.tests:
if test.op == '=':
if equals.has_key(test.property) and test.value != equals[test.property]:
# we've already stated that this arg must equal something else
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 minusExtras(self):
""" Return a new Filter that's equal to this one, without extra terms that don't add meaning. """ |
assert self.isOpen()
trimmed = self.clone()
equals = {}
for test in trimmed.tests:
if test.op == '=':
equals[test.property] = test.value
extras = []
for (i, test) in enumerate(trimmed.tests):
if test.op... |
<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_preference(hdf5_file, preference):
"""Assign the value 'preference' to the diagonal entries of the matrix of similarities stored in the HDF5 data structu... |
Worker.hdf5_lock.acquire()
with tables.open_file(hdf5_file, 'r+') as fileh:
S = fileh.root.aff_prop_group.similarities
diag_ind = np.diag_indices(S.nrows)
S[diag_ind] = preference
Worker.hdf5_lock.release() |
<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_fluctuations(hdf5_file, N_columns, N_processes):
"""This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hd... |
random_state = np.random.RandomState(0)
slice_queue = multiprocessing.JoinableQueue()
pid_list = []
for i in range(N_processes):
worker = Fluctuations_worker(hdf5_file,
'/aff_prop_group/similarities', random_state,
N_columns, slice_queue... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_responsibilities(hdf5_file, N_columns, damping, N_processes):
"""Organize the computation and update of the responsibility matrix for Affinity Propag... |
slice_queue = multiprocessing.JoinableQueue()
pid_list = []
for i in range(N_processes):
worker = Responsibilities_worker(hdf5_file, '/aff_prop_group',
N_columns, damping, slice_queue)
worker.daemon = True
worker.start()
pid_list.append(worker.pid)
... |
<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_numpy_array(multiprocessing_array, shape, dtype):
"""Convert a share multiprocessing array to a numpy array. No data copying involved. """ |
return np.frombuffer(multiprocessing_array.get_obj(),
dtype = dtype).reshape(shape) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_rows_sum(hdf5_file, path, N_columns, N_processes, method = 'Process'):
"""Parallel computation of the sums across the rows of two-dimensional array a... |
assert isinstance(method, str), "parameter 'method' must consist in a string of characters"
assert method in ('Ordinary', 'Pool'), "parameter 'method' must be set to either of 'Ordinary' or 'Pool'"
if method == 'Ordinary':
rows_sum = np.zeros(N_columns, dtype = float)
... |
<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_convergence(hdf5_file, iteration, convergence_iter, max_iter):
"""If the estimated number of clusters has not changed for 'convergence_iter' consecutiv... |
Worker.hdf5_lock.acquire()
with tables.open_file(hdf5_file, 'r+') as fileh:
A = fileh.root.aff_prop_group.availabilities
R = fileh.root.aff_prop_group.responsibilities
P = fileh.root.aff_prop_group.parallel_updates
N = A.nrows
diag_ind = np.diag_indices(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 cluster_labels_A(hdf5_file, c, lock, I, rows_slice):
"""One of the task to be performed by a pool of subprocesses, as the first step in identifying the clust... |
with Worker.hdf5_lock:
with tables.open_file(hdf5_file, 'r+') as fileh:
S = fileh.root.aff_prop_group.similarities
s = S[rows_slice, ...]
s = np.argmax(s[:, I], axis = 1)
with lock:
c[rows_slice] = s[:]
del s |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cluster_labels_B(hdf5_file, s_reduced, lock, I, ii, iix, rows_slice):
"""Second task to be performed by a pool of subprocesses before the cluster labels and ... |
with Worker.hdf5_lock:
with tables.open_file(hdf5_file, 'r+') as fileh:
S = fileh.root.aff_prop_group.similarities
s = S[rows_slice, ...]
s = s[:, ii]
s = s[iix[rows_slice]]
with lock:
s_reduced += s[:].sum(axis = 0)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def output_clusters(labels, cluster_centers_indices):
"""Write in tab-separated files the vectors of cluster identities and of indices of cluster centers. """ |
here = os.getcwd()
try:
output_directory = os.path.join(here, 'concurrent_AP_output')
os.makedirs(output_directory)
except OSError:
if not os.path.isdir(output_directory):
print("ERROR: concurrent_AP: output_clusters: cannot create a directory "
... |
<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_coin_snapshot(fsym, tsym):
""" Get blockchain information, aggregated data as well as data for the individual exchanges available for the specified cu... |
# load data
url = build_url('coinsnapshot', fsym=fsym, tsym=tsym)
data = load_data(url)['Data']
return 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 matches(self, tag, id, classes):
""" Given an id and a list of classes, return True if this selector would match. """ |
element = self.elements[0]
unmatched_ids = [name[1:] for name in element.names if name.startswith('#')]
unmatched_classes = [name[1:] for name in element.names if name.startswith('.')]
unmatched_tags = [name for name in element.names if name is not '*' and not name.startswith('#') and 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 scaledBy(self, scale):
""" Return a new Selector with scale denominators scaled by a number. """ |
scaled = deepcopy(self)
for test in scaled.elements[0].tests:
if type(test.value) in (int, float):
if test.property == 'scale-denominator':
test.value /= scale
elif test.property == 'zoom':
test.value += log(scale)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scaledBy(self, scale):
""" Return a new Value scaled by a given number for ints and floats. """ |
scaled = deepcopy(self)
if type(scaled.value) in (int, float):
scaled.value *= scale
elif isinstance(scaled.value, numbers):
scaled.value.values = tuple(v * scale for v in scaled.value.values)
return scaled |
<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_mining_contracts():
""" Get all the mining contracts information available. Returns: This function returns two major dictionaries. The first one con... |
# load data
url = build_url('miningcontracts')
data = load_data(url)
coin_data = data['CoinData']
mining_data = data['MiningData']
return coin_data, mining_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 get_mining_equipment():
"""Get all the mining equipment information available. Returns: This function returns two major dictionaries. The first one conta... |
# load data
url = build_url('miningequipment')
data = load_data(url)
coin_data = data['CoinData']
mining_data = data['MiningData']
return coin_data, mining_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 main(src_file, dest_file, **kwargs):
""" Given an input layers file and a directory, print the compiled XML file to stdout and save any encountered external ... |
mmap = mapnik.Map(1, 1)
# allow [zoom] filters to work
mmap.srs = '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null'
load_kwargs = dict([(k, v) for (k, v) in kwargs.items() if k in ('cache_dir', 'scale', 'verbose', 'datasources_cfg', 'user_styles')... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chunk(url):
""" create filesystem-safe places for url-keyed data to be stored """ |
chunks = lambda l, n: [l[x: x+n] for x in xrange(0, len(l), n)]
url_64 = base64.urlsafe_b64encode(url)
return chunks(url_64, 255) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(filename):
""" Given an input file containing nothing but styles, print out an unrolled list of declarations in cascade order. """ |
input = open(filename, 'r').read()
declarations = cascadenik.stylesheet_declarations(input, is_merc=True)
for dec in declarations:
print dec.selector,
print '{',
print dec.property.name+':',
if cascadenik.style.properties[dec.property.name] in (cascadenik.style... |
<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_gps(value):
"""Validate GPS value.""" |
try:
latitude, longitude, altitude = value.split(',')
vol.Coerce(float)(latitude)
vol.Coerce(float)(longitude)
vol.Coerce(float)(altitude)
except (TypeError, ValueError, vol.Invalid):
raise vol.Invalid(
'GPS value should be of format "latitude,longitude,altit... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _connect(self):
"""Connect to socket. This should be run in a new thread.""" |
while self.protocol:
_LOGGER.info('Trying to connect to %s', self.server_address)
try:
sock = socket.create_connection(
self.server_address, self.reconnect_timeout)
except socket.timeout:
_LOGGER.error(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _connect(self):
"""Connect to the socket.""" |
try:
while True:
_LOGGER.info('Trying to connect to %s', self.server_address)
try:
yield from asyncio.wait_for(
self.loop.create_connection(
lambda: self.protocol, *self.server_address),
... |
<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):
"""Transport thread loop.""" |
# pylint: disable=broad-except
self.protocol = self.protocol_factory()
try:
self.protocol.connection_made(self)
except Exception as exc:
self.alive = False
self.protocol.connection_lost(exc)
self._connection_made.set()
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 register(self, name):
"""Return decorator to register item with a specific name.""" |
def decorator(func):
"""Register decorated function."""
self[name] = func
return func
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 _handle_subscription(self, topics):
"""Handle subscription of topics.""" |
if not isinstance(topics, list):
topics = [topics]
for topic in topics:
topic_levels = topic.split('/')
try:
qos = int(topic_levels[-2])
except ValueError:
qos = 0
try:
_LOGGER.debug('Subscribing... |
<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_topics(self):
"""Set up initial subscription of mysensors topics.""" |
_LOGGER.info('Setting up initial MQTT topic subscription')
init_topics = [
'{}/+/+/0/+/+'.format(self._in_prefix),
'{}/+/+/3/+/+'.format(self._in_prefix),
]
self._handle_subscription(init_topics)
if not self.persistence:
return
topics ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_mqtt_to_message(self, topic, payload, qos):
"""Parse a MQTT topic and payload. Return a mysensors command string. """ |
topic_levels = topic.split('/')
topic_levels = not_prefix = topic_levels[-5:]
prefix_end_idx = topic.find('/'.join(not_prefix)) - 1
prefix = topic[:prefix_end_idx]
if prefix != self._in_prefix:
return None
if qos and qos > 0:
ack = '1'
els... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_message_to_mqtt(self, data):
"""Parse a mysensors command string. Return a MQTT topic, payload and qos-level as a tuple. """ |
msg = Message(data, self)
payload = str(msg.payload)
msg.payload = ''
# prefix/node/child/type/ack/subtype : payload
return ('{}/{}'.format(self._out_prefix, msg.encode('/'))[:-2],
payload, msg.ack) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_presentation(self, msg):
"""Process a MQTT presentation message.""" |
ret_msg = handle_presentation(msg)
if msg.child_id == 255 or ret_msg is None:
return
# this is a presentation of a child sensor
topics = [
'{}/{}/{}/{}/+/+'.format(
self._in_prefix, str(msg.node_id), str(msg.child_id),
msg_type)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def recv(self, topic, payload, qos):
"""Receive a MQTT message. Call this method when a message is received from the MQTT broker. """ |
data = self._parse_mqtt_to_message(topic, payload, qos)
if data is None:
return
_LOGGER.debug('Receiving %s', data)
self.add_job(self.logic, 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 send(self, message):
"""Publish a command string to the gateway via MQTT.""" |
if not message:
return
topic, payload, qos = self._parse_message_to_mqtt(message)
try:
_LOGGER.debug('Publishing %s', message.strip())
self._pub_callback(topic, payload, qos, self._retain)
except Exception as exception: # pylint: disable=broad-except... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def contribute_to_class(self, cls, name, virtual_only=False):
""" Cast to the correct value every """ |
super(RegexField, self).contribute_to_class(cls, name, virtual_only)
setattr(cls, name, CastOnAssignDescriptor(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 run_validators(self, value):
""" Make sure value is a string so it can run through django validators """ |
value = self.to_python(value)
value = self.value_to_string(value)
return super(RegexField, self).run_validators(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 validate_hex(value):
"""Validate that value has hex format.""" |
try:
binascii.unhexlify(value)
except Exception:
raise vol.Invalid(
'{} is not of hex format'.format(value))
return 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 validate_v_rgb(value):
"""Validate a V_RGB value.""" |
if len(value) != 6:
raise vol.Invalid(
'{} is not six characters long'.format(value))
return validate_hex(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 validate_v_rgbw(value):
"""Validate a V_RGBW value.""" |
if len(value) != 8:
raise vol.Invalid(
'{} is not eight characters long'.format(value))
return validate_hex(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 copy(self, **kwargs):
"""Copy a message, optionally replace attributes with kwargs.""" |
msg = Message(self.encode(), self.gateway)
for key, val in kwargs.items():
setattr(msg, key, val)
return 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 modify(self, **kwargs):
"""Modify and return message, replace attributes with kwargs.""" |
for key, val in kwargs.items():
setattr(self, key, val)
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 decode(self, data, delimiter=';'):
"""Decode a message from command string.""" |
try:
list_data = data.rstrip().split(delimiter)
self.payload = list_data.pop()
(self.node_id,
self.child_id,
self.type,
self.ack,
self.sub_type) = [int(f) for f in list_data]
except ValueError:
_LOGGER.w... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode(self, delimiter=';'):
"""Encode a command string from message.""" |
try:
return delimiter.join([str(f) for f in [
self.node_id,
self.child_id,
int(self.type),
self.ack,
int(self.sub_type),
self.payload,
]]) + '\n'
except ValueError:
_LOGGE... |
<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(self, protocol_version):
"""Validate message.""" |
const = get_const(protocol_version)
valid_node_ids = vol.All(vol.Coerce(int), vol.Range(
min=0, max=BROADCAST_ID, msg='Not valid node_id: {}'.format(
self.node_id)))
valid_child_ids = vol.All(vol.Coerce(int), vol.Range(
min=0, max=SYSTEM_CHILD_ID, msg='No... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _save_pickle(self, filename):
"""Save sensors to pickle file.""" |
with open(filename, 'wb') as file_handle:
pickle.dump(self._sensors, file_handle, pickle.HIGHEST_PROTOCOL)
file_handle.flush()
os.fsync(file_handle.fileno()) |
<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_pickle(self, filename):
"""Load sensors from pickle file.""" |
with open(filename, 'rb') as file_handle:
self._sensors.update(pickle.load(file_handle)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _save_json(self, filename):
"""Save sensors to json file.""" |
with open(filename, 'w') as file_handle:
json.dump(self._sensors, file_handle, cls=MySensorsJSONEncoder,
indent=4)
file_handle.flush()
os.fsync(file_handle.fileno()) |
<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_json(self, filename):
"""Load sensors from json file.""" |
with open(filename, 'r') as file_handle:
self._sensors.update(json.load(
file_handle, cls=MySensorsJSONDecoder)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_sensors(self):
"""Save sensors to file.""" |
if not self.need_save:
return
fname = os.path.realpath(self.persistence_file)
exists = os.path.isfile(fname)
dirname = os.path.dirname(fname)
if (not os.access(dirname, os.W_OK) or exists and
not os.access(fname, os.W_OK)):
_LOGGER.error('... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.