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 set_property(self, key, value):
"""Set a property on the document. Calling code should use this method to add and modify properties on the document instead of modifying ``properties`` directly. If ``key`` is ``"_links"`` or ``"_embedded"`` this method will silently fail. If there is no property with the name in ``key``, a new property is created with the name from ``key`` and the value from ``value``. If the document already has a property with that name, it's value is replaced with the value in ``value``. """ |
if key in self.RESERVED_ATTRIBUTE_NAMES:
return
self.o[key] = 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 delete_property(self, key):
"""Remove a property from the document. Calling code should use this method to remove properties on the document instead of modifying ``properties`` directly. If there is a property with the name in ``key``, it will be removed. Otherwise, a ``KeyError`` will be thrown. """ |
if key in self.RESERVED_ATTRIBUTE_NAMES:
raise KeyError(key)
del self.o[key] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def link(self, href, **kwargs):
"""Retuns a new link relative to this resource.""" |
return link.Link(dict(href=href, **kwargs), self.base_uri) |
<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_link(self, rel=None, href=lambda _: True):
"""Deletes links from the document. Calling code should use this method to remove links instead of modyfying ``links`` directly. The optional arguments, ``rel`` and ``href`` are used to select the links that will be deleted. If neither of the optional arguments are given, this method deletes every link in the document. If ``rel`` is given, only links for the matching link relationship type are deleted. If ``href`` is given, only links with a matching ``href`` are deleted. If both ``rel`` and ``href`` are given, only links with matching ``href`` for the matching link relationship type are delted. Arguments: - ``rel``: an optional string specifying the link relationship type of the links to be deleted. - ``href``: optionally, a string specifying the ``href`` of the links to be deleted, or a callable that returns true when its single argument is in the set of ``href``s to be deleted. """ |
if not LINKS_KEY in self.o:
return
links = self.o[LINKS_KEY]
if rel is None:
for rel in list(links.keys()):
self.delete_link(rel, href)
return
if callable(href):
href_filter = href
else:
href_filter = lambda x: x == href
links_for_rel = links.setdefault(rel, [])
if isinstance(links_for_rel, dict):
links_for_rel = [links_for_rel]
new_links_for_rel = []
for link in links_for_rel:
if not href_filter(link['href']):
new_links_for_rel.append(link)
if new_links_for_rel:
if len(new_links_for_rel) == 1:
new_links_for_rel = new_links_for_rel[0]
links[rel] = new_links_for_rel
else:
del links[rel]
if not self.o[LINKS_KEY]:
del self.o[LINKS_KEY] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_object(cls, o, base_uri=None, parent_curies=None, draft=AUTO):
"""Returns a new ``Document`` based on a JSON object or array. Arguments: - ``o``: a dictionary holding the deserializated JSON for the new ``Document``, or a ``list`` of such documents. - ``base_uri``: optional URL used as the basis when expanding relative URLs in the document. - ``parent_curies``: optional ``CurieCollection`` instance holding the CURIEs of the parent document in which the new document is to be embedded. Calling code should not normally provide this argument. - ``draft``: a ``Draft`` instance that selects the version of the spec to which the document should conform. Defaults to ``drafts.AUTO``. """ |
if isinstance(o, list):
return [cls.from_object(x, base_uri, parent_curies, draft)
for x in o]
return cls(o, base_uri, parent_curies, draft) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def empty(cls, base_uri=None, draft=AUTO):
"""Returns an empty ``Document``. Arguments: - ``base_uri``: optional URL used as the basis when expanding relative URLs in the document. - ``draft``: a ``Draft`` instance that selects the version of the spec to which the document should conform. Defaults to ``drafts.AUTO``. """ |
return cls.from_object({}, base_uri=base_uri, draft=draft) |
<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_embedded(self, rel=None, href=lambda _: True):
"""Removes an embedded resource from this document. Calling code should use this method to remove embedded resources instead of modifying ``embedded`` directly. The optional arguments, ``rel`` and ``href`` are used to select the embedded resources that will be removed. If neither of the optional arguments are given, this method removes every embedded resource from this document. If ``rel`` is given, only embedded resources for the matching link relationship type are removed. If ``href`` is given, only embedded resources with a ``self`` link matching ``href`` are deleted. If both ``rel`` and ``href`` are given, only embedded resources with matching ``self`` link for the matching link relationship type are removed. Arguments: - ``rel``: an optional string specifying the link relationship type of the embedded resources to be removed. - ``href``: optionally, a string specifying the ``href`` of the ``self`` links of the resources to be removed, or a callable that returns true when its single argument matches the ``href`` of the ``self`` link of one of the resources to be removed. """ |
if EMBEDDED_KEY not in self.o:
return
if rel is None:
for rel in list(self.o[EMBEDDED_KEY].keys()):
self.delete_embedded(rel, href)
return
if rel not in self.o[EMBEDDED_KEY]:
return
if callable(href):
url_filter = href
else:
url_filter = lambda x: x == href
rel_embeds = self.o[EMBEDDED_KEY][rel]
if isinstance(rel_embeds, dict):
del self.o[EMBEDDED_KEY][rel]
if not self.o[EMBEDDED_KEY]:
del self.o[EMBEDDED_KEY]
return
new_rel_embeds = []
for embedded in list(rel_embeds):
embedded_doc = Document(embedded, self.base_uri)
if not url_filter(embedded_doc.url()):
new_rel_embeds.append(embedded)
if not new_rel_embeds:
del self.o[EMBEDDED_KEY][rel]
elif len(new_rel_embeds) == 1:
self.o[EMBEDDED_KEY][rel] = new_rel_embeds[0]
else:
self.o[EMBEDDED_KEY][rel] = new_rel_embeds
if not self.o[EMBEDDED_KEY]:
del self.o[EMBEDDED_KEY] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def drop_curie(self, name):
"""Removes a CURIE. The CURIE link with the given name is removed from the document. """ |
curies = self.o[LINKS_KEY][self.draft.curies_rel]
if isinstance(curies, dict) and curies['name'] == name:
del self.o[LINKS_KEY][self.draft.curies_rel]
return
for i, curie in enumerate(curies):
if curie['name'] == name:
del curies[i]
break
continue |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mask_left(self, n_seq_bases, mask="S"):
""" Return a new cigar with cigar string where the first `n_seq_bases` are soft-masked unless they are already hard-masked. """ |
cigs = list(self.items())
new_cigs = []
c, cum_len = self.cigar, 0
for i, (l, op) in enumerate(cigs):
if op in Cigar.read_consuming_ops:
cum_len += l
if op == "H":
cum_len += l
new_cigs.append(cigs[i])
elif cum_len < n_seq_bases:
new_cigs.append(cigs[i])
else:
# the current cigar element is split by the masking.
right_extra = cum_len - n_seq_bases
new_cigs.append((l - right_extra, 'S'))
if right_extra != 0:
new_cigs.append((right_extra, cigs[i][1]))
if cum_len >= n_seq_bases: break
else:
pass
new_cigs[:i] = [(l, op if op in "HS" else "S") for l, op in
new_cigs[:i]]
new_cigs.extend(cigs[i + 1:])
return Cigar(Cigar.string_from_elements(new_cigs)).merge_like_ops() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mask_right(self, n_seq_bases, mask="S"):
""" Return a new cigar with cigar string where the last `n_seq_bases` are soft-masked unless they are already hard-masked. """ |
return Cigar(Cigar(self._reverse_cigar()).mask_left(n_seq_bases, mask)._reverse_cigar()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def runner(test_command, work_dir=None):
""" Internal test job runner context manager. Run the test_command in a subprocess and instantiates 2 FlushStreamThread, one for each standard stream (output/stdout and error/stderr). It yields the subprocess.Popen instance that was spawned to run the given test command in the given working directory. Leaving the context manager kills the process and joins the flushing threads. Use the ``process.wait`` method to avoid that. """ |
process = subprocess.Popen(test_command, bufsize=0, shell=True,
cwd=work_dir,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
with flush_stream_threads(process):
try:
yield process
finally:
if process.poll() is None:
process.terminate() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def kill(self, sig=signal.SIGTERM):
""" Terminate the test job. Kill the subprocess if it was spawned, abort the spawning process otherwise. This information can be collected afterwards by reading the self.killed and self.spawned flags. Also join the 3 related threads to the caller thread. This can be safely called from any thread. This method behaves as self.join() when the thread isn't alive, i.e., it doesn't raise an exception. The ``sig`` parameter should be either: * ``signal.SIGKILL`` (``9``), on Linux or OSX; * ``signal.SIGTERM`` (``15``), the default value. On Windows this one calls the ``TerminateProcess`` Win32 API function. """ |
while self.is_alive():
self.killed = True
time.sleep(POLLING_DELAY) # "Was a process spawned?" polling
if not self.spawned:
continue # Either self.run returns or runner yields
if self.process.poll() is None: # It's running
self.process.send_signal(sig)
try: # There's no os.WNOHANG in Windows
os.waitpid(self.process.pid, getattr(os, "WNOHANG", 1))
except OSError: # Ignore "No child processes" error
pass
break # We already either killed or finished it
self.join() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loader(schema, validator=CerberusValidator, update=None):
"""Create a load function based on schema dict and Validator class. :param schema: a Cerberus schema dict. :param validator: the validator class which must be a subclass of more.cerberus.CerberusValidator which is the default. :param update: will pass the update flag to the validator, when ``True`` the ``required`` rules will not be checked. By default it will be set for PUT and PATCH requests to ``True`` and for other requests to ``False``. You can plug this ``load`` function into a json view. Returns a ``load`` function that takes a request JSON body and uses the schema to validate it. This function raises :class:`more.cerberus.ValidationError` if validation is not successful. """ |
if not issubclass(validator, CerberusValidator):
raise TypeError(
"Validator must be a subclass of more.cerberus.CerberusValidator"
)
return partial(load, schema, validator, update) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render(self, rectangle, data):
"""Draws the signature mark. Note that this draws OUTSIDE the rectangle we're given. If cropping is involved, then this obviously won't work.""" |
size = (1.0 - 2.0*self.margin) * rectangle.h
offset = self.margin * rectangle.h
per_mark = 1.0 / float(self.total)
bottom = offset + size * float(self.index) * per_mark
top = bottom + per_mark * size
c = data['output']
with c:
c.translate(rectangle.x, rectangle.y)
c.draw_polygon(
0, top, -self.width, bottom, self.width, bottom,
fill=self.color
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def projected_inverse(L):
""" Supernodal multifrontal projected inverse. The routine computes the projected inverse .. math:: Y = P(L^{-T}L^{-1}) where :math:`L` is a Cholesky factor. On exit, the argument :math:`L` contains the projected inverse :math:`Y`. :param L: :py:class:`cspmatrix` (factor) """ |
assert isinstance(L, cspmatrix) and L.is_factor is True, "L must be a cspmatrix factor"
n = L.symb.n
snpost = L.symb.snpost
snptr = L.symb.snptr
chptr = L.symb.chptr
chidx = L.symb.chidx
relptr = L.symb.relptr
relidx = L.symb.relidx
blkptr = L.symb.blkptr
blkval = L.blkval
stack = []
for k in reversed(list(snpost)):
nn = snptr[k+1]-snptr[k] # |Nk|
na = relptr[k+1]-relptr[k] # |Ak|
nj = na + nn
# invert factor of D_{Nk,Nk}
lapack.trtri(blkval, offsetA = blkptr[k], ldA = nj, n = nn)
# zero-out strict upper triangular part of {Nj,Nj} block (just in case!)
for i in range(1,nn): blas.scal(0.0, blkval, offset = blkptr[k] + nj*i, n = i)
# compute inv(D_{Nk,Nk}) (store in 1,1 block of F)
F = matrix(0.0, (nj,nj))
blas.syrk(blkval, F, trans = 'T', offsetA = blkptr[k], ldA = nj, n = nn, k = nn)
# if supernode k is not a root node:
if na > 0:
# copy "update matrix" to 2,2 block of F
Vk = stack.pop()
lapack.lacpy(Vk, F, ldB = nj, offsetB = nn*nj+nn, m = na, n = na, uplo = 'L')
# compute S_{Ak,Nk} = -Vk*L_{Ak,Nk}; store in 2,1 block of F
blas.symm(Vk, blkval, F, m = na, n = nn, offsetB = blkptr[k]+nn,\
ldB = nj, offsetC = nn, ldC = nj, alpha = -1.0)
# compute S_nn = inv(D_{Nk,Nk}) - S_{Ak,Nk}'*L_{Ak,Nk}; store in 1,1 block of F
blas.gemm(F, blkval, F, transA = 'T', m = nn, n = nn, k = na,\
offsetA = nn, alpha = -1.0, beta = 1.0,\
offsetB = blkptr[k]+nn, ldB = nj)
# extract update matrices if supernode k has any children
for ii in range(chptr[k],chptr[k+1]):
i = chidx[ii]
stack.append(frontal_get_update(F, relidx, relptr, i))
# copy S_{Jk,Nk} (i.e., 1,1 and 2,1 blocks of F) to blkval
lapack.lacpy(F, blkval, m = nj, n = nn, offsetB = blkptr[k], ldB = nj, uplo = 'L')
L._is_factor = False
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 define_system_args(subparsers):
"""Append the parser arguments for the 'system' commands""" |
system_parser = subparsers.add_parser("system", help='Available commands: \'info\'')
system_subparsers = system_parser.add_subparsers(help='System commands')
# system info arguments
info_parser = system_subparsers.add_parser('info', help='Get system status information')
info_parser.add_argument('--src', required=True, dest='src', metavar='src',
help='The instance name of the target SDC (must match the name in sdc-hosts.yml)')
info_parser.set_defaults(func=info_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 get_user_info(user):
"""Get the user information """ |
user = api.get_user(user)
current = api.get_current_user()
if api.is_anonymous():
return {
"username": current.getUserName(),
"authenticated": False,
"roles": current.getRoles(),
"api_url": api.url_for("plone.jsonapi.routes.users", username="current"),
}
# nothing to do
if user is None:
logger.warn("No user found for {}".format(user))
return None
# plone user
pu = user.getUser()
info = {
"username": user.getUserName(),
"roles": user.getRoles(),
"groups": pu.getGroups(),
"authenticated": current == user,
"api_url": api.url_for("senaite.jsonapi.v1.users", username=user.getId()),
}
for k, v in api.get_user_properties(user).items():
if api.is_date(v):
v = api.to_iso_date(v)
if not api.is_json_serializable(v):
logger.warn("User property '{}' is not JSON serializable".format(k))
continue
info[k] = v
return 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 get(context, request, username=None):
"""Plone users route """ |
user_ids = []
# Don't allow anonymous users to query a user other than themselves
if api.is_anonymous():
username = "current"
# query all users if no username was given
if username is None:
user_ids = api.get_member_ids()
elif username == "current":
current_user = api.get_current_user()
user_ids = [current_user.getId()]
else:
user_ids = [username]
# Prepare batch
size = req.get_batch_size()
start = req.get_batch_start()
batch = api.make_batch(user_ids, size, start)
# get the user info for the user ids in the current batch
users = map(get_user_info, batch.get_batch())
return {
"pagesize": batch.get_pagesize(),
"next": batch.make_next_url(),
"previous": batch.make_prev_url(),
"page": batch.get_pagenumber(),
"pages": batch.get_numpages(),
"count": batch.get_sequence_length(),
"items": users,
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def perm(A, p):
""" Symmetric permutation of a symmetric sparse matrix. :param A: :py:class:`spmatrix` :param p: :py:class:`matrix` or :class:`list` of length `A.size[0]` """ |
assert isinstance(A,spmatrix), "argument must be a sparse matrix"
assert A.size[0] == A.size[1], "A must be a square matrix"
assert A.size[0] == len(p), "length of p must be equal to the order of A"
return A[p,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 enable_shuffle(self, value=None):
"""Enable shuffle mode """ |
if value is None:
value = not self.shuffled
spotifyconnect.Error.maybe_raise(lib.SpPlaybackEnableShuffle(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 enable_repeat(self, value=None):
"""Enable repeat mode """ |
if value is None:
value = not self.repeated
spotifyconnect.Error.maybe_raise(lib.SpPlaybackEnableRepeat(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 detect(self, obj):
"""Identifies the HAL draft level of a given JSON object.""" |
links = obj.get(LINKS_KEY, {})
for detector in [LATEST, DRAFT_3]:
if detector.draft.curies_rel in links:
return detector.detect(obj)
return LATEST.detect(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 to_list(thing):
""" converts an object to a list [1] [1, 2, 3] ['a', 'b', 'c'] [{'a': 1, 'b': 2}] [] ['a', 'b', 'c'] [''] [] ['[]'] ['a', 'b', 'c'] """ |
if thing is None:
return []
if isinstance(thing, set):
return list(thing)
if isinstance(thing, types.StringTypes):
if thing.startswith("["):
# handle a list inside a string coming from the batch navigation
return ast.literal_eval(thing)
if not (is_list(thing) or is_tuple(thing)):
return [thing]
return list(thing) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pluck(col, key, default=None):
""" Extracts a list of values from a collection of dictionaries ['moe', 'larry', 'curly'] It only works with collections Traceback (most recent call last):
RuntimeError: First argument must be a list or tuple """ |
if not (is_list(col) or is_tuple(col)):
fail("First argument must be a list or tuple")
def _block(dct):
if not is_dict(dct):
return []
return dct.get(key, default)
return map(_block, col) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rename(dct, mapping):
""" Rename the keys of a dictionary with the given mapping {'AAA': 1, 'BBB': 2} """ |
def _block(memo, key):
if key in dct:
memo[mapping[key]] = dct[key]
return memo
else:
return memo
return reduce(_block, mapping, omit(dct, *mapping.keys())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def alias(col, mapping):
""" Returns a collection of dictionaries with the keys renamed according to the mapping [{'edition': 1, 'isbn': 1}, {'edition': 2, 'isbn': 2}] [{'b': 1}] """ |
if not is_list(col):
col = [col]
def _block(dct):
return rename(dct, mapping)
return map(_block, col) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def first(thing, n=0):
""" get the first element of a list 1 [1, 2, 3] [1, 2, 3, 4, 5] {'key': 'value'} 'a' '' [''] '' False '' """ |
n = to_int(n)
if is_list(thing) or is_tuple(thing):
if len(thing) == 0:
return None
if n > 0:
return thing[0:n]
return thing[0]
return thing |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def discover(ignore_list=[], max_wait=30, loop=None):
"""List STB in the network.""" |
stbs = []
try:
async with timeout(max_wait, loop=loop):
def responses_callback(notify):
"""Queue notify messages."""
_LOGGER.debug("Found: %s", notify.ip_address)
stbs.append(notify.ip_address)
mr_protocol = await install_mediaroom_protocol(responses_callback=responses_callback)
await asyncio.sleep(max_wait)
except asyncio.TimeoutError:
mr_protocol.close()
_LOGGER.debug("discover() timeout!")
return list(set([stb for stb in stbs if stb not in ignore_list])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def send_cmd(self, cmd, loop=None):
"""Send remote command to STB.""" |
_LOGGER.info("Send cmd = %s", cmd)
if cmd not in COMMANDS and cmd not in range(0, 999):
_LOGGER.error("Unknown command")
raise PyMediaroomError("Unknown commands")
keys = []
if cmd in range(0, 999):
for character in str(cmd):
keys.append(COMMANDS["Number"+str(character)])
if len(keys) < 3:
keys.append(COMMANDS["OK"])
self.current_channel = cmd
else:
keys = [COMMANDS[cmd]]
try:
async with timeout(OPEN_CONTROL_TIMEOUT, loop=loop):
async with self.lock:
_LOGGER.debug("Connecting to %s:%s", self.stb_ip, REMOTE_CONTROL_PORT)
stb_recv, stb_send = await asyncio.open_connection(self.stb_ip,
REMOTE_CONTROL_PORT,
loop=loop)
await stb_recv.read(6)
_LOGGER.info("Connected to %s:%s", self.stb_ip, REMOTE_CONTROL_PORT)
for key in keys:
_LOGGER.debug("%s key=%s", cmd, key)
stb_send.write("key={}\n".format(key).encode('UTF-8'))
_ = await stb_recv.read(3)
await asyncio.sleep(0.300)
except asyncio.TimeoutError as error:
_LOGGER.warning(error)
raise PyMediaroomError("Timeout connecting to {}".format(self.stb_ip))
except ConnectionRefusedError as error:
_LOGGER.warning(error)
raise PyMediaroomError("Connection refused to {}".format(self.stb_ip)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def notify_callback(self, notify):
"""Process State from NOTIFY message.""" |
_LOGGER.debug(notify)
if notify.ip_address != self.stb_ip:
return
if notify.tune:
self._state = State.PLAYING_LIVE_TV
self.tune_src = notify.tune['@src']
try:
if notify.stopped:
self._state = State.STOPPED
elif notify.timeshift:
self._state = State.PLAYING_TIMESHIFT_TV
elif notify.recorded:
self._state = State.PLAYING_RECORDED_TV
except PyMediaroomError as e:
_LOGGER.debug("%s please report at https://github.com/dgomes/pymediaroom/issues", e)
else:
self._state = State.STANDBY
_LOGGER.debug("%s is %s", self.stb_ip, self._state)
return self._state |
<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):
""" Main thread function. """ |
if not hasattr(self, 'queue'):
raise RuntimeError("Audio queue is not intialized.")
chunk = None
channel = None
self.keep_listening = True
while self.keep_listening:
if chunk is None:
try:
frame = self.queue.get(timeout=queue_timeout)
chunk = pygame.sndarray.make_sound(frame)
except Empty:
continue
if channel is None:
channel = chunk.play()
else:
if not channel.get_queue():
channel.queue(chunk)
chunk = None
time.sleep(0.005)
if not channel is None and pygame.mixer.get_init():
channel.stop()
pygame.mixer.quit() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search(self, query):
"""search the catalog """ |
logger.info("Catalog query={}".format(query))
# Support to set the catalog as a request parameter
catalogs = _.to_list(req.get("catalog", None))
if catalogs:
return senaiteapi.search(query, catalog=catalogs)
# Delegate to the search API of Bika LIMS
return senaiteapi.search(query) |
<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_index(self, name):
"""get an index by name TODO: Combine indexes of relevant catalogs depending on the portal_type which is searched for. """ |
catalog = self.get_catalog()
index = catalog._catalog.getIndex(name)
logger.debug("get_index={} of catalog '{}' --> {}".format(
name, catalog.__name__, index))
return index |
<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_index_value(self, value, index):
"""Convert the value for a given index """ |
# ZPublisher records can be passed to the catalog as is.
if isinstance(value, HTTPRequest.record):
return value
if isinstance(index, basestring):
index = self.get_index(index)
if index.id == "portal_type":
return filter(lambda x: x, _.to_list(value))
if index.meta_type == "DateIndex":
return DateTime(value)
if index.meta_type == "BooleanIndex":
return bool(value)
if index.meta_type == "KeywordIndex":
return value.split(",")
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 make_query(self, **kw):
"""create a query suitable for the catalog """ |
query = kw.pop("query", {})
query.update(self.get_request_query())
query.update(self.get_custom_query())
query.update(self.get_keyword_query(**kw))
sort_on, sort_order = self.get_sort_spec()
if sort_on and "sort_on" not in query:
query.update({"sort_on": sort_on})
if sort_order and "sort_order" not in query:
query.update({"sort_order": sort_order})
logger.info("make_query:: query={} | catalog={}".format(
query, self.catalog))
return query |
<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_request_query(self):
"""Checks the request for known catalog indexes and converts the values to fit the type of the catalog index. :param catalog: The catalog to build the query for :type catalog: ZCatalog :returns: Catalog query :rtype: dict """ |
query = {}
# only known indexes get observed
indexes = self.catalog.get_indexes()
for index in indexes:
# Check if the request contains a parameter named like the index
value = req.get(index)
# No value found, continue
if value is None:
continue
# Convert the found value to format understandable by the index
index_value = self.catalog.to_index_value(value, index)
# Conversion returned None, continue
if index_value is None:
continue
# Append the found value to the query
query[index] = index_value
return query |
<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_custom_query(self):
"""Extracts custom query keys from the index. Parameters which get extracted from the request: `q`: Passes the value to the `SearchableText` `path`: Creates a path query `recent_created`: Creates a date query `recent_modified`: Creates a date query :param catalog: The catalog to build the query for :type catalog: ZCatalog :returns: Catalog query :rtype: dict """ |
query = {}
# searchable text queries
q = req.get_query()
if q:
query["SearchableText"] = q
# physical path queries
path = req.get_path()
if path:
query["path"] = {'query': path, 'depth': req.get_depth()}
# special handling for recent created/modified
recent_created = req.get_recent_created()
if recent_created:
date = api.calculate_delta_date(recent_created)
query["created"] = {'query': date, 'range': 'min'}
recent_modified = req.get_recent_modified()
if recent_modified:
date = api.calculate_delta_date(recent_modified)
query["modified"] = {'query': date, 'range': 'min'}
return query |
<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_keyword_query(self, **kw):
"""Generates a query from the given keywords. Only known indexes make it into the generated query. :returns: Catalog query :rtype: dict """ |
query = dict()
# Only known indexes get observed
indexes = self.catalog.get_indexes()
# Handle additional keyword parameters
for k, v in kw.iteritems():
# handle uid in keywords
if k.lower() == "uid":
k = "UID"
# handle portal_type in keywords
if k.lower() == "portal_type":
if v:
v = _.to_list(v)
if k not in indexes:
logger.warn("Skipping unknown keyword parameter '%s=%s'" % (k, v))
continue
if v is None:
logger.warn("Skip None value in kw parameter '%s=%s'" % (k, v))
continue
logger.debug("Adding '%s=%s' to query" % (k, v))
query[k] = v
return query |
<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_sort_spec(self):
"""Build sort specification """ |
all_indexes = self.catalog.get_indexes()
si = req.get_sort_on(allowed_indexes=all_indexes)
so = req.get_sort_order()
return si, so |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trsm(self,B,trans='N'):
r""" Solves a triangular system of equations with multiple righthand sides. Computes .. math:: B &:= L^{-1} B \text{ if trans is 'N'} B &:= L^{-T} B \text{ if trans is 'T'} """ |
if trans=='N':
cp.trsm(self._L0,B)
pftrsm(self._V,self._L,self._B,B,trans='N')
elif trans=='T':
pftrsm(self._V,self._L,self._B,B,trans='T')
cp.trsm(self._L0,B,trans='T')
elif type(trans) is str:
raise ValueError("trans must be 'N' or 'T'")
else:
raise TypeError("trans must be 'N' or 'T'")
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 render_to_reportlab_canvas(rl_canvas, papersize_tuple, layout):
"""Renders the given layout manager on a page of the given canvas.""" |
rl_canvas.setPageSize(papersize_tuple)
layout.render(
Rectangle(0, 0, *papersize_tuple),
dict(output=ReportlabOutput(rl_canvas))
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def http_basic(r, username, password):
"""Attaches HTTP Basic Authentication to the given Request object. Arguments should be considered non-positional. """ |
username = str(username)
password = str(password)
auth_s = b64encode('%s:%s' % (username, password))
r.headers['Authorization'] = ('Basic %s' % auth_s)
return r |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def http_digest(r, username, password):
"""Attaches HTTP Digest Authentication to the given Request object. Arguments should be considered non-positional. """ |
def handle_401(r):
"""Takes the given response and tries digest-auth, if needed."""
s_auth = r.headers.get('www-authenticate', '')
if 'digest' in s_auth.lower():
last_nonce = ''
nonce_count = 0
chal = parse_dict_header(s_auth.replace('Digest ', ''))
realm = chal['realm']
nonce = chal['nonce']
qop = chal.get('qop')
algorithm = chal.get('algorithm', 'MD5')
opaque = chal.get('opaque', None)
algorithm = algorithm.upper()
# lambdas assume digest modules are imported at the top level
if algorithm == 'MD5':
H = lambda x: hashlib.md5(x).hexdigest()
elif algorithm == 'SHA':
H = lambda x: hashlib.sha1(x).hexdigest()
# XXX MD5-sess
KD = lambda s, d: H("%s:%s" % (s, d))
if H is None:
return None
# XXX not implemented yet
entdig = None
p_parsed = urlparse(r.request.url)
path = p_parsed.path + p_parsed.query
A1 = "%s:%s:%s" % (username, realm, password)
A2 = "%s:%s" % (r.request.method, path)
if qop == 'auth':
if nonce == last_nonce:
nonce_count += 1
else:
nonce_count = 1
last_nonce = nonce
ncvalue = '%08x' % nonce_count
cnonce = (hashlib.sha1("%s:%s:%s:%s" % (
nonce_count, nonce, time.ctime(), randombytes(8)))
.hexdigest()[:16]
)
noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, H(A2))
respdig = KD(H(A1), noncebit)
elif qop is None:
respdig = KD(H(A1), "%s:%s" % (nonce, H(A2)))
else:
# XXX handle auth-int.
return None
# XXX should the partial digests be encoded too?
base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
'response="%s"' % (username, realm, nonce, path, respdig)
if opaque:
base += ', opaque="%s"' % opaque
if entdig:
base += ', digest="%s"' % entdig
base += ', algorithm="%s"' % algorithm
if qop:
base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)
r.request.headers['Authorization'] = 'Digest %s' % (base)
r.request.send(anyway=True)
_r = r.request.response
_r.history.append(r)
return _r
return r
r.hooks['response'] = handle_401
return r |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dispatch(t):
"""Given an auth tuple, return an expanded version.""" |
if not t:
return t
else:
t = list(t)
# Make sure they're passing in something.
assert len(t) >= 2
# If only two items are passed in, assume HTTPBasic.
if (len(t) == 2):
t.insert(0, 'basic')
# Allow built-in string referenced auths.
if isinstance(t[0], basestring):
if t[0] in ('basic', 'forced_basic'):
t[0] = http_basic
elif t[0] in ('digest',):
t[0] = http_digest
# Return a custom callable.
return (t[0], tuple(t[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 action(context, request, action=None, resource=None, uid=None):
"""Various HTTP POST actions """ |
# allow to set the method via the header
if action is None:
action = request.get_header("HTTP_X_HTTP_METHOD_OVERRIDE", "CREATE").lower()
# Fetch and call the action function of the API
func_name = "{}_items".format(action)
action_func = getattr(api, func_name, None)
if action_func is None:
api.fail(500, "API has no member named '{}'".format(func_name))
portal_type = api.resource_to_portal_type(resource)
items = action_func(portal_type=portal_type, uid=uid)
return {
"count": len(items),
"items": items,
"url": api.url_for("senaite.jsonapi.v1.action", action=action),
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_help_html():
"""Build the help HTML using the shared resources.""" |
remove_from_help = ["not-in-help", "copyright"]
if sys.platform in ["win32", "cygwin"]:
remove_from_help.extend(["osx", "linux"])
elif sys.platform == "darwin":
remove_from_help.extend(["linux", "windows", "linux-windows"])
else:
remove_from_help.extend(["osx", "windows"])
readme_part_gen = all_but_blocks(remove_from_help, README, newline=None)
rst_body = "\n".join(list(readme_part_gen) + CHANGES)
doctree = docutils.core.publish_doctree(rst_body)
visitor = Doctree2HtmlForWx(doctree)
doctree.walkabout(visitor) # Fills visitor.body and visitor.toc
return ( # wx.html.HtmlWindow only renders a HTML subset
u'<body bgcolor="{bg}" text="{fg}" link="{link}">'
u'<a name="0"><h1>{title}</h1></a>'
u"{sectionless}"
u"{toc}"
u"<p>This help was generated using selected information from the\n"
u"Dose <tt>README.rst</tt> and <tt>CHANGES.rst</tt> project files.</p>"
u'<p><a href="{url}">{url}</a></p><hr/>'
u"{body}</body>"
).format(bg=HELP_BG_COLOR, fg=HELP_FG_COLOR, link=HELP_LINK_COLOR,
title=HELP_TITLE, sectionless=u"".join(visitor.sectionless),
toc=u"".join(visitor.toc), url=__url__,
body=u"".join(visitor.body)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def help_box():
"""A simple HTML help dialog box using the distribution data files.""" |
style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER
dialog_box = wx.Dialog(None, wx.ID_ANY, HELP_TITLE,
style=style, size=(620, 450))
html_widget = HtmlHelp(dialog_box, wx.ID_ANY)
html_widget.page = build_help_html()
dialog_box.ShowModal()
dialog_box.Destroy() |
<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_frame(self, outdata, frames, timedata, status):
""" Callback function for the audio stream. Don't use directly. """ |
if not self.keep_listening:
raise sd.CallbackStop
try:
chunk = self.queue.get_nowait()
# Check if the chunk contains the expected number of frames
# The callback function raises a ValueError otherwise.
if chunk.shape[0] == frames:
outdata[:] = chunk
else:
outdata.fill(0)
except Empty:
outdata.fill(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 get_component_product(self, other):
"""Returns the component product of this vector and the given other vector.""" |
return Point(self.x * other.x, self.y * other.y) |
<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_normalized(self):
"""Returns a vector of unit length, unless it is the zero vector, in which case it is left as is.""" |
magnitude = self.get_magnitude()
if magnitude > 0:
magnitude = 1.0 / magnitude
return Point(self.x * magnitude, self.y * magnitude)
else:
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_rotated(self, angle):
"""Rotates this vector through the given anti-clockwise angle in radians.""" |
ca = math.cos(angle)
sa = math.sin(angle)
return Point(self.x*ca-self.y*sa, self.x*sa+self.y*ca) |
<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_magnitude(self):
"""Returns the magnitude of this vector.""" |
return math.sqrt(self.x*self.x + self.y*self.y) |
<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_magnitude_squared(self):
"""Returns the square of the magnitude of this vector.""" |
return self.x*self.x + self.y*self.y |
<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_scalar_product(self, other):
"""Returns the scalar product of this vector with the given other vector.""" |
return self.x*other.x+self.y*other.y |
<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_angle_between(self, other):
"""Returns the smallest angle between this vector and the given other vector.""" |
# The scalar product is the sum of the squares of the
# magnitude times the cosine of the angle - so normalizing the
# vectors first means the scalar product is just the cosine of
# the angle.
normself = self.get_normalized()
normother = other.get_normalized()
sp = normself.get_scalar_product(normother)
return math.acos(sp) |
<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_minimum(self, other):
"""Updates this vector so its components are the lower of its current components and those of the given other value.""" |
return Point(min(self.x, other.x), min(self.y, other.y)) |
<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_maximum(self, other):
"""Updates this vector so its components are the higher of its current components and those of the given other value.""" |
return Point(max(self.x, other.x), max(self.y, other.y)) |
<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(min_pt, max_pt):
"""Returns a random vector in the given range.""" |
result = Point(random.random(), random.random())
return result.get_component_product(max_pt - min_pt) + min_pt |
<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_data(self):
"""Returns the x, y, w, h, data as a tuple.""" |
return self.x, self.y, self.w, self.h |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _candidate_tempdir_list():
"""Generate a list of candidate temporary directories which _get_default_tempdir will try.""" |
dirlist = []
# First, try the environment.
for envname in 'TMPDIR', 'TEMP', 'TMP':
dirname = _os.getenv(envname)
if dirname: dirlist.append(dirname)
# Failing that, try OS-specific locations.
if _os.name == 'nt':
dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
else:
dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
# As a last resort, the current directory.
try:
dirlist.append(_os.getcwd())
except (AttributeError, OSError):
dirlist.append(_os.curdir)
return dirlist |
<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_tempdir():
"""Calculate the default directory to use for temporary files. This routine should be called exactly once. We determine whether or not a candidate temp dir is usable by trying to create and write to a file in that directory. If this is successful, the test file is deleted. To prevent denial of service, the name of the test file must be randomized.""" |
namer = _RandomNameSequence()
dirlist = _candidate_tempdir_list()
for dir in dirlist:
if dir != _os.curdir:
dir = _os.path.abspath(dir)
# Try only a few names per directory.
for seq in range(100):
name = next(namer)
filename = _os.path.join(dir, name)
try:
fd = _os.open(filename, _bin_openflags, 0o600)
try:
try:
with _io.open(fd, 'wb', closefd=False) as fp:
fp.write(b'blat')
finally:
_os.close(fd)
finally:
_os.unlink(filename)
return dir
except FileExistsError:
pass
except OSError:
break # no point trying more names in this directory
raise FileNotFoundError(_errno.ENOENT,
"No usable temporary directory found in %s" %
dirlist) |
<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_candidate_names():
"""Common setup sequence for all user-callable interfaces.""" |
global _name_sequence
if _name_sequence is None:
_once_lock.acquire()
try:
if _name_sequence is None:
_name_sequence = _RandomNameSequence()
finally:
_once_lock.release()
return _name_sequence |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _mkstemp_inner(dir, pre, suf, flags):
"""Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.""" |
names = _get_candidate_names()
for seq in range(TMP_MAX):
name = next(names)
file = _os.path.join(dir, pre + name + suf)
try:
fd = _os.open(file, flags, 0o600)
return (fd, _os.path.abspath(file))
except FileExistsError:
continue # try again
except PermissionError:
# This exception is thrown when a directory with the chosen name
# already exists on windows.
if _os.name == 'nt':
continue
else:
raise
raise FileExistsError(_errno.EEXIST,
"No usable temporary file name found") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gettempdir():
"""Accessor for tempfile.tempdir.""" |
global tempdir
if tempdir is None:
_once_lock.acquire()
try:
if tempdir is None:
tempdir = _get_default_tempdir()
finally:
_once_lock.release()
return tempdir |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mkdtemp(suffix="", prefix=template, dir=None):
"""User-callable function to create and return a unique temporary directory. The return value is the pathname of the directory. Arguments are as for mkstemp, except that the 'text' argument is not accepted. The directory is readable, writable, and searchable only by the creating user. Caller is responsible for deleting the directory when done with it. """ |
if dir is None:
dir = gettempdir()
names = _get_candidate_names()
for seq in range(TMP_MAX):
name = next(names)
file = _os.path.join(dir, prefix + name + suffix)
try:
_os.mkdir(file, 0o700)
return file
except FileExistsError:
continue # try again
raise FileExistsError(_errno.EEXIST,
"No usable temporary directory name found") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def syr2(X, u, v, alpha = 1.0, beta = 1.0, reordered=False):
r""" Computes the projected rank 2 update of a cspmatrix X .. math:: X := \alpha*P(u v^T + v u^T) + \beta X. """ |
assert X.is_factor is False, "cspmatrix factor object"
symb = X.symb
n = symb.n
snptr = symb.snptr
snode = symb.snode
blkval = X.blkval
blkptr = symb.blkptr
relptr = symb.relptr
snrowidx = symb.snrowidx
sncolptr = symb.sncolptr
if symb.p is not None and reordered is False:
up = u[symb.p]
vp = v[symb.p]
else:
up = u
vp = v
for k in range(symb.Nsn):
nn = snptr[k+1]-snptr[k]
na = relptr[k+1]-relptr[k]
nj = na + nn
for i in range(nn): blas.scal(beta, blkval, n = nj-i, offset = blkptr[k]+(nj+1)*i)
uk = up[snrowidx[sncolptr[k]:sncolptr[k+1]]]
vk = vp[snrowidx[sncolptr[k]:sncolptr[k+1]]]
blas.syr2(uk, vk, blkval, n = nn, offsetA = blkptr[k], ldA = nj, alpha = alpha)
blas.ger(uk, vk, blkval, m = na, n = nn, offsetx = nn, offsetA = blkptr[k]+nn, ldA = nj, alpha = alpha)
blas.ger(vk, uk, blkval, m = na, n = nn, offsetx = nn, offsetA = blkptr[k]+nn, ldA = nj, alpha = alpha)
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 _ensure_5args(func):
""" Conditionally wrap function to ensure 5 input arguments Parameters func: callable with four or five positional arguments Returns ------- callable which possibly ignores 0 or 1 positional arguments """ |
if func is None:
return None
self_arg = 1 if inspect.ismethod(func) else 0
if len(inspect.getargspec(func)[0]) == 5 + self_arg:
return func
if len(inspect.getargspec(func)[0]) == 4 + self_arg:
return lambda t, y, J, dfdt, fy=None: func(t, y, J, dfdt)
else:
raise ValueError("Incorrect numer of arguments") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shadow_normal_module(cls, mod_name=None):
""" Shadow a module with an instance of LazyModule :param mod_name: Name of the module to shadow. By default this is the module that is making the call into this method. This is not hard-coded as that module might be called '__main__' if it is executed via 'python -m' :returns: A fresh instance of :class:`LazyModule`. """ |
if mod_name is None:
frame = inspect.currentframe()
try:
mod_name = frame.f_back.f_locals['__name__']
finally:
del frame
orig_mod = sys.modules[mod_name]
lazy_mod = cls(orig_mod.__name__, orig_mod.__doc__, orig_mod)
for attr in dir(orig_mod):
setattr(lazy_mod, attr, getattr(orig_mod, attr))
sys.modules[mod_name] = lazy_mod
return lazy_mod |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lazily(self, name, callable, args):
""" Load something lazily """ |
self._lazy[name] = callable, args
self._all.add(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 immediate(self, name, value):
""" Load something immediately """ |
setattr(self, name, value)
self._all.add(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 parse_dimension(text):
""" Parses the given text into one dimension and returns its equivalent size in points. The numbers provided can be integer or decimal, but exponents are not supported. The units may be inches (", in, ins, inch, inchs, inches), millimeters (mm), points (pt, pts, point, points, or nothing), or centimeters (cm). Because this module is intended for use with paper-size dimensions, no larger or smaller units are currently supported. """ |
size, unit = _split_dimension(text)
factor = _unit_lookup[unit]
return size*factor |
<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_dimensions(text):
""" Parses a set of dimensions into tuple of values representing the sizes in points. The dimensions that this method supports are exactly as for parse_dimension. It supports multiple dimensions, separated by whitespace, comma, semicolon, hyphen, or the letter x. The units may follow each dimension (in which case they can be different in each case) or only after the last one. Because no-units also means points, if you have some dimensions in the middle of the set with units and some without, then those without will be interpreted as points: i.e. the 2 in "1in, 2, 3mm" will be treated as 2 points, where as the 1 and 2 in "1, 2, 3mm" will be treated as millimeters. """ |
components = _dimension_separator.split(text)
if len(components) == 0:
raise DimensionError("No dimensions found in string.")
# Split each component into size and units
pairs = []
units = 0
for component in components:
value, unit = _split_dimension(component)
pairs.append((value, unit))
if unit is not None: units += 1
# Work out what to do with empty units
if units == 1 and pairs[-1][1]:
# We need to infer the units
empty_unit = _unit_lookup[pairs[-1][1]]
else:
empty_unit = 1
# Compile and return the result
result = []
for value, unit in pairs:
if unit: result.append(value * _unit_lookup[unit])
else: result.append(value * empty_unit)
return tuple(result) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _split_dimension(text):
""" Returns the number and unit from the given piece of text as a pair. (1, 'pt') (1, 'pt') (1, 'pt') (1, 'pt') (1, 'pt') (3, None) (-12.43, 'mm') (-12.43, '"') """ |
match = _dimension_finder.match(text)
if not match:
raise DimensionError("Can't parse dimension '%s'." % text)
number = match.group(1)
unit = match.group(4)
if '.' in number:
return (float(number), unit)
else:
return (int(number), unit) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def queue(self, value):
""" Sets the audioqueue. Parameters value : queue.Queue The buffer from which audioframes are received. """ |
if not isinstance(value, Queue):
raise TypeError("queue is not a Queue object")
self._queue = value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_minimum_size(self, data):
"""Returns the minimum size of the managed element, as long as it is larger than any manually set minima.""" |
size = self.element.get_minimum_size(data)
return datatypes.Point(
max(size.x, self.min_width),
max(size.y, self.min_height)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render(self, rect, data):
"""Draws the managed element in the correct alignment.""" |
# We can't use our get minimum size, because that enforces
# the size limits.
size = self.element.get_minimum_size(data)
# Assume we're bottom left at our natural size.
x = rect.x
y = rect.y
w = size.x
h = size.y
extra_width = rect.w - w
extra_height = rect.h - h
if self.horizontal_align == AlignLM.ALIGN_CENTER:
x += extra_width * 0.5
elif self.horizontal_align == AlignLM.ALIGN_RIGHT:
x += extra_width
elif self.horizontal_align == AlignLM.GROW_X:
w = rect.w
if self.vertical_align == AlignLM.ALIGN_MIDDLE:
y += extra_height * 0.5
elif self.vertical_align == AlignLM.ALIGN_TOP:
y += extra_height
elif self.vertical_align == AlignLM.GROW_Y:
h = rect.h
self.element.render(datatypes.Rectangle(x, y, w, h), 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 create_copy_without_data(G):
"""Return a copy of the graph G with all the data removed""" |
H = nx.Graph()
for i in H.nodes_iter():
H.node[i] = {}
return H |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump(stuff, filename, verbose=True, protocol=3):
"""Store an object to file by pickling Parameters stuff : object to be pickled filename : path verbose : bool protocol : 1,2,3 (default = 3) Protocol used by Pickler, higher number means more recent version of Python is needed to read the pickle produced. Default is protocol=3, which only works with Python 3+ Return ------ path Path where pickled object was saved. """ |
filename = os.path.normcase(filename)
dir_path = os.path.dirname(filename)
if not os.path.exists(dir_path): os.makedirs(dir_path)
with open(filename, 'wb') as f:
p = pickle.Pickler(f, protocol=protocol)
p.dump(stuff)
if verbose:
print('Written {} items to pickled binary file: {}'.format(len(stuff), filename))
return filename |
<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(filename):
"""Retrieve a pickled object Parameter --------- filename : path Return ------ object Unpickled object """ |
filename = os.path.normcase(filename)
try:
with open(filename, 'rb') as f:
u = pickle.Unpickler(f)
return u.load()
except IOError:
raise LogOpeningError('No file found for %s' % filename, filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sign_envelope(envelope, key_file):
"""Sign the given soap request with the given key""" |
doc = etree.fromstring(envelope)
body = get_body(doc)
queue = SignQueue()
queue.push_and_mark(body)
security_node = ensure_security_header(doc, queue)
security_token_node = create_binary_security_token(key_file)
signature_node = Signature(
xmlsec.TransformExclC14N, xmlsec.TransformRsaSha1)
security_node.append(security_token_node)
security_node.append(signature_node)
queue.insert_references(signature_node)
key_info = create_key_info_node(security_token_node)
signature_node.append(key_info)
# Sign the generated xml
xmlsec.addIDs(doc, ['Id'])
dsigCtx = xmlsec.DSigCtx()
dsigCtx.signKey = xmlsec.Key.load(key_file, xmlsec.KeyDataFormatPem, None)
dsigCtx.sign(signature_node)
return etree.tostring(doc) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verify_envelope(reply, key_file):
"""Verify that the given soap request is signed with the certificate""" |
doc = etree.fromstring(reply)
node = doc.find(".//{%s}Signature" % xmlsec.DSigNs)
if node is None:
raise CertificationError("No signature node found")
dsigCtx = xmlsec.DSigCtx()
xmlsec.addIDs(doc, ['Id'])
signKey = xmlsec.Key.load(key_file, xmlsec.KeyDataFormatPem)
signKey.name = os.path.basename(key_file)
dsigCtx.signKey = signKey
try:
dsigCtx.verify(node)
except xmlsec.VerificationError:
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 create_key_info_node(security_token):
"""Create the KeyInfo node for WSSE. Note that this currently only supports BinarySecurityTokens Example of the generated XML: <ds:KeyInfo Id="KI-24C56C5B3448F4BE9D141094243396829"> <wsse:SecurityTokenReference wsse11:TokenType="{{ BINARY_TOKEN_TYPE }}"> <wsse:Reference URI="#X509-24C56C5B3448F4BE9D141094243396828" ValueType="{{ BINARY_TOKEN_TYPE }}"/> </wsse:SecurityTokenReference> </ds:KeyInfo> """ |
key_info = etree.Element(ns_id('KeyInfo', ns.dsns))
sec_token_ref = etree.SubElement(
key_info, ns_id('SecurityTokenReference', ns.wssens))
sec_token_ref.set(
ns_id('TokenType', ns.wssens), security_token.get('ValueType'))
reference = etree.SubElement(sec_token_ref, ns_id('Reference', ns.wssens))
reference.set('ValueType', security_token.get('ValueType'))
reference.set('URI', '#%s' % security_token.get(WSU_ID))
return key_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 create_binary_security_token(key_file):
"""Create the BinarySecurityToken node containing the x509 certificate. """ |
node = etree.Element(
ns_id('BinarySecurityToken', ns.wssens),
nsmap={ns.wssens[0]: ns.wssens[1]})
node.set(ns_id('Id', ns.wsuns), get_unique_id())
node.set('EncodingType', ns.wssns[1] + 'Base64Binary')
node.set('ValueType', BINARY_TOKEN_TYPE)
with open(key_file) as fh:
cert = crypto.load_certificate(crypto.FILETYPE_PEM, fh.read())
node.text = base64.b64encode(
crypto.dump_certificate(crypto.FILETYPE_ASN1, cert))
return node |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ensure_security_header(envelope, queue):
"""Insert a security XML node if it doesn't exist otherwise update it. """ |
(header,) = HEADER_XPATH(envelope)
security = SECURITY_XPATH(header)
if security:
for timestamp in TIMESTAMP_XPATH(security[0]):
queue.push_and_mark(timestamp)
return security[0]
else:
nsmap = {
'wsu': ns.wsuns[1],
'wsse': ns.wssens[1],
}
return _create_element(header, 'wsse:Security', nsmap) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def checkParametersInputFile(filename):
"""Check the do_x3dna output file and return list of parameters present in the file. """ |
fin = open(filename, 'r')
line = fin.readline()
line2 = fin.readline()
fin.close()
temp = re.split('\s+', line)
temp2 = re.split('\s+', line2)
if temp[0] == '#Minor':
return groovesParameters
if temp[0] == '#Shift':
return baseStepParameters
if temp[0] == '#X-disp':
return helicalBaseStepParameters
if temp[0] == '#Shear':
return basePairParameters
if temp[0] == '#Position':
return helicalAxisParameters
if temp2[0] == '#P':
return helicalRadiusParameters
if temp2[0] == '#alpha':
return backboneDihedrals |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setParametersFromFile(dna, filename, parameters=None, bp=None):
"""Read a specific parameter from the do_x3dna output file. It automatically load the input parameter from a file to dna object or HDF5 file. It automatically decides from input parameter, what will be format of input file. Parameters dna : :class:`DNA` Input :class:`DNA` instance. filename : str Input filename. This file should be output from do_x3dna. parameter : str, list, None Name of parameter. For details about accepted keywords, see ``parameter`` in the method :meth:`DNA.get_parameters`. Note that parameter that are calculated from do_x3dna cannot be used here. In case of `Ǹone`, parameters name will be automatically determine from the input file. bp : list List containing lower and higher limit of base-pair/step range. * This list should not contain more than two number. * First number should be less than second number. Example for base-pairs/steps 4 to 15: ``bp = [4,15] # step_range = True`` If ``None``, all base-pairs/steps will be considered. """ |
gotParameterList = False
param_type = None
# In case of none try to determine from file
if parameters is None:
parameters = checkParametersInputFile(filename)
if parameters is None:
raise AssertionError(" Cannot determine the parameters name from file {0}.".format(filename))
if isinstance(parameters, list) or isinstance(parameters, np.ndarray):
gotParameterList = True
parameter = list(parameters)
param_type = getParameterType(parameter[0])
else:
param_type = getParameterType(parameters)
if bp is None:
if param_type == 'bps':
bp = [dna.startBP, dna.num_step]
else:
bp = [dna.startBP, dna.num_bp]
if len(bp) == 1:
bp_range = False
else:
bp_range = True
if not gotParameterList:
tempParamName = parameters
inputParameter = [ parameters ]
else:
tempParamName = parameters[0]
inputParameter = parameter
sys.stdout.write('\nLoading parameters: {0}'.format(inputParameter))
success = False
if tempParamName in basePairParameters:
dna.set_base_pair_parameters(filename, bp, parameters=inputParameter, bp_range=bp_range)
success = True
if tempParamName in baseStepParameters:
dna.set_base_step_parameters(filename, bp, parameters=inputParameter, step_range=bp_range, helical=False)
success = True
if tempParamName in helicalBaseStepParameters:
dna.set_base_step_parameters(filename, bp, parameters=inputParameter, step_range=bp_range, helical=True)
success = True
if tempParamName in groovesParameters:
dna.set_major_minor_groove(filename, bp, parameters=inputParameter, step_range=bp_range)
success = True
if tempParamName in backboneDihedrals:
dna.set_backbone_dihedrals(filename, bp, parameters=inputParameter, bp_range=bp_range)
success = True
if tempParamName in helicalRadiusParameters:
dna.set_helical_radius(filename, bp, full=True, bp_range=bp_range)
success = True
if tempParamName in helicalAxisParameters:
if len(bp) == 1:
raise AssertionError("Axis cannot be read for a single base-step.\n Use a segment spanned over several basepairs.")
dna.set_helical_axis(filename, step_range=True, step=bp)
success = True
if not success:
raise ValueError ('Not able to load these parameters: {0}... '.format(parameter)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def frenet_serret(xyz):
''' Frenet-Serret Space Curve Invariants
Taken from "Diffusion Imaging in Python" `DiPy package<http://nipy.org/dipy/>`_
Calculates the 3 vector and 2 scalar invariants of a space curve defined by vectors r = (x,y,z). If z is omitted (i.e. the array xyz has shape (N,2), then the curve is only 2D (planar), but the equations are still valid.
Similar to http://www.mathworks.com/matlabcentral/fileexchange/11169
In the following equations the prime ($'$) indicates differentiation with respect to the parameter $s$ of a parametrised curve $\mathbf{r}(s)$.
- $\mathbf{T}=\mathbf{r'}/|\mathbf{r'}|\qquad$ (Tangent vector)}
- $\mathbf{N}=\mathbf{T'}/|\mathbf{T'}|\qquad$ (Normal vector)
- $\mathbf{B}=\mathbf{T}\times\mathbf{N}\qquad$ (Binormal vector)
- $\kappa=|\mathbf{T'}|\qquad$ (Curvature)
- $\mathrm{\tau}=-\mathbf{B'}\cdot\mathbf{N}$ (Torsion)
**Arguments:**
* xyz : array-like shape (N,3)
array representing x,y,z of N points in a track
**Returns:**
* T : array shape (N,3)
array representing the tangent of the curve xyz
* N : array shape (N,3)
array representing the normal of the curve xyz
* B : array shape (N,3)
array representing the binormal of the curve xyz
* k : array shape (N,1)
array representing the curvature of the curve xyz
* t : array shape (N,1)
array representing the torsion of the curve xyz
Examples:
Create a helix and calculate its tangent, normal, binormal, curvature and torsion
>>> from dipy.tracking import metrics as tm
>>> import numpy as np
>>> theta = 2*np.pi*np.linspace(0,2,100)
>>> x=np.cos(theta)
>>> y=np.sin(theta)
>>> z=theta/(2*np.pi)
>>> xyz=np.vstack((x,y,z)).T
>>> T,N,B,k,t=tm.frenet_serret(xyz)
'''
def magn(xyz, n=1):
''' magnitude of vector
'''
mag = np.sum(xyz**2, axis=1)**0.5
imag = np.where(mag == 0)
mag[imag] = np.finfo(float).eps
if n > 1:
return np.tile(mag, (n, 1)).T
return mag.reshape(len(mag), 1)
xyz = np.asarray(xyz)
n_pts = xyz.shape[0]
if n_pts == 0:
raise ValueError('xyz array cannot be empty')
dxyz = np.gradient(xyz)[0]
ddxyz = np.gradient(dxyz)[0]
# Tangent
T = np.divide(dxyz, magn(dxyz, 3))
# Derivative of Tangent
dT = np.gradient(T)[0]
# Normal
N = np.divide(dT, magn(dT, 3))
# Binormal
B = np.cross(T, N)
# Curvature
k = magn(np.cross(dxyz, ddxyz), 1) / (magn(dxyz, 1)**3)
# Torsion
#(In matlab was t=dot(-B,N,2))
t = np.sum(-B * N, axis=1)
# return T,N,B,k,t,dxyz,ddxyz,dT
return T, N, B, k, t |
<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_param_file(FileName, parameters, bp, bp_range, word=False, startBP=1):
""" Read parameters from do_x3dna file. It is the main function, which is used to read and extract the parameters values from the do_x3dna output files. Parameters FileName : str Parameter file produced from do_x3dna. parameters : list List of column indices that has to be extracted. indices here start with one. bp : 1D list or array base-pairs to analyze Example: :: bp = [6] # bp_range = False bp = [4,15] # bp_range = True bp = range(4,15) # bp_range = False bp = np.arange(4,15) # bp_range = False bp = [2,5,6,7,9,12,18] # bp_range = False bp_range : bool ``Default=True``: As shown above, if ``True``, bp is taken as a range otherwise list or numpy array. word : bool In some parameters, in place of value, ``'---'`` is present in the file. If parameter values contain this, use ``True``. startBP : int Number ID of first base-pair. Returns ------- data : 3D array Extracted parameters as a 3D array of shape (bp, parameters, time). time : 1D array Time of each frame """ |
sys.stdout.write("\nReading file : %s\n" % FileName)
sys.stdout.flush()
def get_frame_data(block, parameters, bp_idx):
block = np.array(block).T
temp_data = (block[parameters, :])[:, bp_idx].copy()
return temp_data
def get_time(line):
dummy, temp_time = line.split('=')
return float( temp_time )
infile = open(FileName, 'r')
data = []
time = []
frame_number = 0
bp_idx, param_idx = get_idx_of_bp_parameters(bp, parameters, bp_range, startBP=startBP)
block = []
for line in infile:
# Removing last new line character
line = line.rstrip('\n')
# Skipping blank/empty line
if not line.strip():
continue
# Getting Time tag and time => Starting of new frame
if(re.match('# Time', line) != None):
if((frame_number < 100) and (frame_number % 10 == 0)) or ((frame_number < 1000) and (frame_number % 100 == 0)) or ((frame_number < 10000) and (frame_number % 1000 == 0)) or ((frame_number < 100000) and (frame_number % 10000 == 0)) or ((frame_number < 1000000) and (frame_number % 100000 == 0)):
sys.stdout.write("\rReading frame %d" % frame_number)
sys.stdout.flush()
frame_number += 1
# if(frame_number==5000):
# break
# Getting time
time.append(get_time(line))
# Getting parameters/values for base-pairs
if(len(block) > 0):
data.append(get_frame_data(block, param_idx, bp_idx))
block = []
continue
# Skipping other lines starting with '#' tag
if(re.match('#', line) != None):
continue
if not word:
block.append(list(map(float, line.split())))
else:
temp = []
split_line = line.split()
for word in split_line:
if word != '---':
temp.append(float(word))
else:
temp.append(None)
block.append(temp)
# For last frame
data.append(get_frame_data(block, param_idx, bp_idx))
block = []
data_transpose = np.array(data).T
sys.stdout.write(
"\nFinished reading.... Total number of frame read = %d\n" % frame_number)
sys.stdout.flush()
return data_transpose, 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 _set_time(self, time):
""" Set time in both class and hdf5 file """ |
if len(self.time) == 0 :
self.time = np.array(time)
if self.h5 is not None:
self.h5.create_dataset('time', self.time.shape, dtype=self.time.dtype, data=self.time, compression="gzip", shuffle=True, scaleoffset=3)
else:
if(len(time) != len(self.time)):
raise AssertionError("\nTime or number of frame mismatch in input files.\n Exiting...\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 _set_mask(self, mask):
""" Set mask array in both class and hdf5 file """ |
self.mask = mask.copy()
if self.h5 is not None:
if 'mask' in self.h5:
self.h5.pop('mask')
self.h5.create_dataset('mask', mask.shape, dtype=self.mask.dtype, data=mask, compression="gzip", shuffle=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 set_helical_axis(self, filename, step_range=False, step=None):
""" To read and set local helical-axis positions from an input file. Parameters filename : str Input file, which is generated from do_x3dna. e.g. HelAxis_g.dat step_range : bool * ``step_range = True`` : read axis coordinates of base-steps for the given range of base-steps * ``step_range = False``: read axis coordinates of all base-steps step : list List containing lower and higher limit of base-steps range. * This option only works with ``step_range=True``. * This list should not contain more than two number. * First number should be less than second number. Example for base-step 4 to 15: ``step = [4,15] # step_range = True`` """ |
if (step_range):
if not isinstance(step, list):
raise AssertionError("type %s is not list" % type(step))
if (len(step) > 2):
print (
"ERROR: Range for helical axis should be list of two numbers, e.g. step=[1, 20] \n")
exit(1)
if (step_range) and (step == None):
raise ValueError(
"See, documentation for step and step_range usage!!!")
# Check if requested parameters found within input file
gotParametersInputFile = checkParametersInputFile(filename)
if gotParametersInputFile is None:
raise IOError(' Something wrong in input file {0}.\n Cannot read parameters.\n File should be an output from do_x3dna.'.format(filename))
for p in helicalAxisParameters:
if p not in gotParametersInputFile:
raise ValueError(' Helical axis not found in input file. \n This file contains following parameters: \n {0}'.format(gotParametersInputFile))
targetParameters = { 1:'helical x-axis', 2:'helical y-axis', 3:'helical z-axis' }
if (step_range):
if (len(step) != 2):
raise ValueError("See, documentation for step usage!!!")
if step[0] > step[1]:
raise ValueError("See, documentation for step usage!!!")
data, time = read_param_file(filename, [1, 2, 3], step, True, startBP=self.startBP)
else:
data, time = read_param_file(filename, [1, 2, 3], [1, self.num_step], True, startBP=self.startBP)
self._set_time(time)
if (step_range):
bp_idx, param_idx = get_idx_of_bp_parameters(step, [], True, startBP=self.startBP)
else:
bp_idx, param_idx = get_idx_of_bp_parameters([1, self.num_step], [], True, startBP=self.startBP)
for i in range(len(data)):
for j in range(len(data[i])):
bp_num = str( bp_idx[i]+self.startBP )
param = targetParameters[j+1]
self._set_data(data[i][j], 'bps', bp_num, param, scaleoffset=2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loop(self, value):
""" Indicates whether the playback should loop. Parameters value : bool True if playback should loop, False if not. """ |
if not type(value) == bool:
raise TypeError("can only be True or False")
self._loop = 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 reset(self):
""" Resets the player and discards loaded data. """ |
self.clip = None
self.loaded_file = None
self.fps = None
self.duration = None
self.status = UNINITIALIZED
self.clock.reset()
self.loop_count = 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_media(self, mediafile, play_audio=True):
""" Loads a media file to decode. If an audiostream is detected, its parameters will be stored in a dictionary in the variable `audioformat`. This contains the fields :nbytes: the number of bytes in the stream (2 is 16-bit sound). :nchannels: the channels (2 for stereo, 1 for mono) :fps: the frames per sec/sampling rate of the sound (e.g. 44100 KhZ). :buffersize: the audioframes per buffer. If play_audio was set to False, or the video does not have an audiotrack, `audioformat` will be None. Parameters mediafile : str The path to the media file to load. play_audio : bool, optional Indicates whether the audio of a movie should be played. Raises ------ IOError When the file could not be found or loaded. """ |
if not mediafile is None:
if os.path.isfile(mediafile):
self.clip = VideoFileClip(mediafile, audio=play_audio)
self.loaded_file = os.path.split(mediafile)[1]
## Timing variables
# Clip duration
self.duration = self.clip.duration
self.clock.max_duration = self.clip.duration
logger.debug("Video clip duration: {}s".format(self.duration))
# Frames per second of clip
self.fps = self.clip.fps
self.clock.fps = self.clip.fps
logger.debug("Video clip FPS: {}".format(self.fps))
if play_audio and self.clip.audio:
buffersize = int(self.frame_interval*self.clip.audio.fps)
self.audioformat = {
'nbytes': 2,
'nchannels': self.clip.audio.nchannels,
'fps': self.clip.audio.fps,
'buffersize': buffersize
}
logger.debug("Audio loaded: \n{}".format(self.audioformat))
logger.debug("Creating audio buffer of length: "
" {}".format(queue_length))
self.audioqueue = Queue(queue_length)
else:
self.audioformat = None
logger.debug('Loaded {0}'.format(mediafile))
self.status = READY
return True
else:
raise IOError("File not found: {0}".format(mediafile))
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 set_audiorenderer(self, renderer):
""" Sets the SoundRenderer object. This should take care of processing the audioframes set in audioqueue. Parameters renderer : soundrenderers.SoundRenderer A subclass of soundrenderers.SoundRenderer that takes care of the audio rendering. Raises ------ RuntimeError If no information about the audiostream is available. This could be because no video has been loaded yet, or because no embedded audiostream could be detected in the video, or play_sound was set to False. """ |
if not hasattr(self, 'audioqueue') or self.audioqueue is None:
raise RuntimeError("No video has been loaded, or no audiostream "
"was detected.")
if not isinstance(renderer, SoundRenderer):
raise TypeError("Invalid renderer object. Not a subclass of "
"SoundRenderer")
self.soundrenderer = renderer
self.soundrenderer.queue = self.audioqueue |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self):
""" Stops the video stream and resets the clock. """ |
logger.debug("Stopping playback")
# Stop the clock
self.clock.stop()
# Set plauyer status to ready
self.status = READY |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def seek(self, value):
""" Seek to the specified time. Parameters value : str or int The time to seek to. Can be any of the following formats: """ |
# Pause the stream
self.pause()
# Make sure the movie starts at 1s as 0s gives trouble.
self.clock.time = max(0.5, value)
logger.debug("Seeking to {} seconds; frame {}".format(self.clock.time,
self.clock.current_frame))
if self.audioformat:
self.__calculate_audio_frames()
# Resume the stream
self.pause() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __calculate_audio_frames(self):
""" Aligns audio with video. This should be called for instance after a seeking operation or resuming from a pause. """ |
if self.audioformat is None:
return
start_frame = self.clock.current_frame
totalsize = int(self.clip.audio.fps*self.clip.audio.duration)
self.audio_times = list(range(0, totalsize,
self.audioformat['buffersize'])) + [totalsize]
# Remove audio segments up to the starting frame
del(self.audio_times[0:start_frame]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __render(self):
""" Main render loop. Checks clock if new video and audio frames need to be rendered. If so, it passes the frames to functions that take care of rendering these frames. """ |
# Render first frame
self.__render_videoframe()
# Start videoclock with start of this thread
self.clock.start()
logger.debug("Started rendering loop.")
# Main rendering loop
while self.status in [PLAYING,PAUSED]:
current_frame_no = self.clock.current_frame
# Check if end of clip has been reached
if self.clock.time >= self.duration:
logger.debug("End of stream reached at {}".format(self.clock.time))
if self.loop:
logger.debug("Looping: restarting stream")
# Seek to the start
self.rewind()
self.loop_count += 1
else:
# End of stream has been reached
self.status = EOS
break
if self.last_frame_no != current_frame_no:
# A new frame is available. Get it from te stream
self.__render_videoframe()
self.last_frame_no = current_frame_no
# Sleeping is a good idea to give the other threads some breathing
# space to do their work.
time.sleep(0.005)
# Stop the clock.
self.clock.stop()
logger.debug("Rendering stopped.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __render_videoframe(self):
""" Retrieves a new videoframe from the stream. Sets the frame as the __current_video_frame and passes it on to __videorenderfunc() if it is set. """ |
new_videoframe = self.clip.get_frame(self.clock.time)
# Pass it to the callback function if this is set
if callable(self.__videorenderfunc):
self.__videorenderfunc(new_videoframe)
# Set current_frame to current frame (...)
self.__current_videoframe = new_videoframe |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.