Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
7,200 | def every_other(iterable):
items = iter(iterable)
while True:
try:
yield next(items)
next(items)
except StopIteration:
return | Yield every other item from the iterable
>>> ' '.join(every_other('abcdefg'))
'a c e g' |
7,201 | def _check_dn(self, dn, attr_value):
if dn is not None:
self._error()
if not is_dn(attr_value):
self._error(
% attr_value) | Check dn attribute for issues. |
7,202 | def devop_write(self, args, bustype):
usage = "Usage: devop write <spi|i2c> name bus address regstart count <bytes>"
if len(args) < 5:
print(usage)
return
name = args[0]
bus = int(args[1],base=0)
address = int(args[2],base=0)
reg = int(arg... | write to a device |
7,203 | def help(i):
o=i.get(,)
m=i.get(,)
if m==:
m=
h= +cfg[].replace(, m)+
h+=
h+=
for q in sorted(cfg[]):
s=q
desc=cfg[][q].get(,)
if desc!=: s+=+desc
h+=+s+
h+=
h+=
if m==:
for q in sorted(cfg[]):
if q not ... | Input: {
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
help - help text
} |
7,204 | def split(self, k):
if not 1 <= k <= self.num_rows - 1:
raise ValueError("Invalid value of k. k must be between 1 and the"
"number of rows - 1")
rows = np.random.permutation(self.num_rows)
first = self.take(rows[:k])
rest = self.take(ro... | Return a tuple of two tables where the first table contains
``k`` rows randomly sampled and the second contains the remaining rows.
Args:
``k`` (int): The number of rows randomly sampled into the first
table. ``k`` must be between 1 and ``num_rows - 1``.
Raises:
... |
7,205 | def forget_subject(sid):
s freesurfer module to forget about cached data for the
subject with subject id sid. The sid may be any sid that can be passed to the subject()
function.
This function is useful for batch-processing of subjects in a memory-limited environment; e.g.,
if you run out of me... | forget_subject(sid) causes neuropythy's freesurfer module to forget about cached data for the
subject with subject id sid. The sid may be any sid that can be passed to the subject()
function.
This function is useful for batch-processing of subjects in a memory-limited environment; e.g.,
if you run ... |
7,206 | def list_passwords(kwargs=None, call=None):
response = _query(, )
ret = {}
for item in response[]:
if in item:
server = item[][]
if server not in ret:
ret[server] = []
ret[server].append(item)
return ret | List all password on the account
.. versionadded:: 2015.8.0 |
7,207 | def parse_mmtf_header(infile):
infodict = {}
mmtf_decoder = mmtf.parse(infile)
infodict[] = mmtf_decoder.deposition_date
infodict[] = mmtf_decoder.release_date
try:
infodict[] = [x.decode() for x in mmtf_decoder.experimental_methods]
except AttributeError:
infodict[] = [x f... | Parse an MMTF file and return basic header-like information.
Args:
infile (str): Path to MMTF file
Returns:
dict: Dictionary of parsed header
Todo:
- Can this be sped up by not parsing the 3D coordinate info somehow?
- OR just store the sequences when this happens since it... |
7,208 | def integrate(self, outevent, inevent):
assert outevent not in self
for function in compat_itervalues(self.functions):
assert outevent not in function
assert inevent in function
for call in compat_itervalues(function.calls):
assert o... | Propagate function time ratio along the function calls.
Must be called after finding the cycles.
See also:
- http://citeseer.ist.psu.edu/graham82gprof.html |
7,209 | def raise_for_missing_name(self, line: str, position: int, namespace: str, name: str) -> None:
self.raise_for_missing_namespace(line, position, namespace, name)
if self.has_enumerated_namespace(namespace) and not self.has_enumerated_namespace_name(namespace, name):
raise MissingNam... | Raise an exception if the namespace is not defined or if it does not validate the given name. |
7,210 | def pause(self, remaining_pause_cycles):
url = urljoin(self._url, )
elem = ElementTreeBuilder.Element(self.nodename)
elem.append(Resource.element_for_value(,
remaining_pause_cycles))
body = ElementTree.tostring(elem, encoding=)
... | Pause a subscription |
7,211 | def rule_role(self, **kwargs):
config = ET.Element("config")
rule = ET.SubElement(config, "rule", xmlns="urn:brocade.com:mgmt:brocade-aaa")
index_key = ET.SubElement(rule, "index")
index_key.text = kwargs.pop()
role = ET.SubElement(rule, "role")
role.text = kwarg... | Auto Generated Code |
7,212 | def _read_bytes_from_non_framed_body(self, b):
_LOGGER.debug("starting non-framed body read")
bytes_to_read = self.body_length
_LOGGER.debug("%d bytes requested; reading %d bytes", b, bytes_to_read)
ciphertext = self.source_stream.read(bytes_to_read)
if len(se... | Reads the requested number of bytes from a streaming non-framed message body.
:param int b: Number of bytes to read
:returns: Decrypted bytes from source stream
:rtype: bytes |
7,213 | async def openurl(url, **opts):
if url.find() == -1:
newurl = alias(url)
if newurl is None:
raise s_exc.BadUrl(f)
url = newurl
info = s_urlhelp.chopurl(url)
info.update(opts)
host = info.get()
port = info.get()
auth = None
user = info.get()
if... | Open a URL to a remote telepath object.
Args:
url (str): A telepath URL.
**opts (dict): Telepath connect options.
Returns:
(synapse.telepath.Proxy): A telepath proxy object.
The telepath proxy may then be used for sync or async calls:
proxy = openurl(url)
value = ... |
7,214 | def getWorkflowDir(workflowID, configWorkDir=None):
workDir = configWorkDir or os.getenv() or tempfile.gettempdir()
if not os.path.exists(workDir):
raise RuntimeError("The directory specified by --workDir or TOIL_WORKDIR (%s) does not "
"exist." % work... | Returns a path to the directory where worker directories and the cache will be located
for this workflow.
:param str workflowID: Unique identifier for the workflow
:param str configWorkDir: Value passed to the program using the --workDir flag
:return: Path to the workflow directory
... |
7,215 | def _get_or_add_image(self, image_file):
image_part, rId = self.part.get_or_add_image_part(image_file)
desc, image_size = image_part.desc, image_part._px_size
return rId, desc, image_size | Return an (rId, description, image_size) 3-tuple identifying the
related image part containing *image_file* and describing the image. |
7,216 | def _solve(self):
while len(self._remove_constr) > 0:
self._remove_constr.pop().delete()
try:
self._prob.solve(lp.ObjectiveSense.Maximize)
except lp.SolverError as e:
raise_from(FluxBalanceError(.format(
e), result=self._pro... | Solve the problem with the current objective. |
7,217 | def extract_subsection(im, shape):
r
shape = sp.array(shape)
if shape[0] < 1:
shape = sp.array(im.shape) * shape
center = sp.array(im.shape) / 2
s_im = []
for dim in range(im.ndim):
r = shape[dim] / 2
lower_im = sp.amax((center[dim] - r, 0))
upper_im = sp.ami... | r"""
Extracts the middle section of a image
Parameters
----------
im : ND-array
Image from which to extract the subsection
shape : array_like
Can either specify the size of the extracted section or the fractional
size of the image to extact.
Returns
-------
ima... |
7,218 | def update_with_result(self, result):
assert isinstance(result, dict), "%s is not a dictionary" % result
for type in ("instance", "plugin"):
id = (result[type] or {}).get("id")
is_context = not id
if is_context:
item = self.instances[0]
... | Update item-model with result from host
State is sent from host after processing had taken place
and represents the events that took place; including
log messages and completion status.
Arguments:
result (dict): Dictionary following the Result schema |
7,219 | def restore_flattened_dict(i):
a={}
b=i[]
first=True
for x in b:
if first:
first=False
y=x[1:2]
if y==: a=[]
else: a={}
set_by_flat_key({:a, :x, :b[x]})
return {:0, : a} | Input: {
dict - flattened dict
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
dict - restored dict
} |
7,220 | def _store_variable(self, j, key, m, value):
if hasattr(value, ):
v = value.copy()
else:
v = value
self.history[j][key][m].append(v) | Store a copy of the variable in the history |
7,221 | def get_feature_info(feature):
dimensions = feature.findall()
for dim in dimensions:
if dim.attrib[] == :
rt = dim.text
elif dim.attrib[] == :
mz = dim.text
return {: float(rt), : float(mz),
: int(feature.find().text),
: float(feature.find... | Returns a dict with feature information |
7,222 | def get_gene_symbols(chrom, start, stop):
gene_symbols = query_gene_symbol(chrom, start, stop)
logger.debug("Found gene symbols: {0}".format(.join(gene_symbols)))
return gene_symbols | Get the gene symbols that a interval overlaps |
7,223 | def view_count_plus(slug):
entry = TabWiki.update(
view_count=TabWiki.view_count + 1,
).where(TabWiki.uid == slug)
entry.execute() | View count plus one. |
7,224 | def getInvestigators(self, tags = None, seperator = ";", _getTag = False):
if tags is None:
tags = []
elif isinstance(tags, str):
tags = [, tags]
else:
tags.append()
return super().getInvestigators(tags = tags, seperator = seperator, _getTag =... | Returns a list of the names of investigators. The optional arguments are ignored.
# Returns
`list [str]`
> A list of all the found investigator's names |
7,225 | def translate_char(source_char, carrier, reverse=False, encoding=False):
u
if not isinstance(source_char, unicode) and encoding:
source_char = source_char.decode(encoding, )
elif not isinstance(source_char, unicode):
raise AttributeError(u"`source_char` must be decoded to `unicode` or set `e... | u"""translate unicode emoji character to unicode carrier emoji character (or reverse)
Attributes:
source_char - emoji character. it must be unicode instance or have to set `encoding` attribute to decode
carrier - the target carrier
reverse - if you want to translate CARRIE... |
7,226 | def complete(self, stream):
assert not self.is_complete()
self._marker.addInputPort(outputPort=stream.oport)
self.stream.oport.schema = stream.oport.schema
self._pending_schema._set(self.stream.oport.schema)
... | Complete the pending stream.
Any connections made to :py:attr:`stream` are connected to `stream` once
this method returns.
Args:
stream(Stream): Stream that completes the connection. |
7,227 | def _get_default_namespace(self) -> Optional[Namespace]:
return self._get_query(Namespace).filter(Namespace.url == self._get_namespace_url()).one_or_none() | Get the reference BEL namespace if it exists. |
7,228 | def _check_inplace_setting(self, value):
if self._is_mixed_type:
if not self._is_numeric_mixed_type:
try:
if np.isnan(value):
return True
except Exception:
pass
... | check whether we allow in-place setting with this type of value |
7,229 | def update_transfer_job(self, job_name, body):
body = self._inject_project_id(body, BODY, PROJECT_ID)
return (
self.get_conn()
.transferJobs()
.patch(jobName=job_name, body=body)
.execute(num_retries=self.num_retries)
) | Updates a transfer job that runs periodically.
:param job_name: (Required) Name of the job to be updated
:type job_name: str
:param body: A request body, as described in
https://cloud.google.com/storage-transfer/docs/reference/rest/v1/transferJobs/patch#request-body
:type bo... |
7,230 | def add_output(self, address, value, unit=):
value_satoshi = self.from_unit_to_satoshi(value, unit)
if self.verbose:
print("Adding output of: %s satoshi (%.8f)" % (
value_satoshi, (value_satoshi / 1e8)
))
self.outs.append({
: address... | Add an output (a person who will receive funds via this tx).
If no unit is specified, satoshi is implied. |
7,231 | def _select_date_range(self, lines):
headers = []
num_lev = []
dates = []
for idx, line in enumerate(lines):
if line[0] == :
year, month, day, hour = map(int, line[13:26].split())
try:
da... | Identify lines containing headers within the range begin_date to end_date.
Parameters
-----
lines: list
list of lines from the IGRA2 data file. |
7,232 | def _build(self, name, **params):
log = self._getparam(, self._discard, **params)
rebuild = False
wparams = params.copy()
wparams[] = False
for path in list(self._watch.paths_open):
if path in self.modules:
continue
... | Rebuild operations by removing open modules that no longer need to be
watched, and adding new modules if they are not currently being watched.
This is done by comparing self.modules to watch_files.paths_open |
7,233 | def get_or_create_media(self, api_media):
return Media.objects.get_or_create(site_id=self.site_id,
wp_id=api_media["ID"],
defaults=self.api_object_data("media", api_media)) | Find or create a Media object given API data.
:param api_media: the API data for the Media
:return: a tuple of an Media instance and a boolean indicating whether the Media was created or not |
7,234 | def get_summary_stats(self, output_csv=None):
contig_size_list = []
self.summary_info["ncontigs"] = len(self.contigs)
for contig_id, sequence in self.contigs.items():
logger.debug("Processing contig: {}".format(contig_id))
contig_len = len(seque... | Generates a CSV report with summary statistics about the assembly
The calculated statistics are:
- Number of contigs
- Average contig size
- N50
- Total assembly length
- Average GC content
- Amount of missing data
Parameters
... |
7,235 | def create(cls, name, key_chain_entry):
key_chain_entry = key_chain_entry or []
json = {: name,
: key_chain_entry}
return ElementCreator(cls, json) | Create a key chain with list of keys
Key_chain_entry format is::
[{'key': 'xxxx', 'key_id': 1-255, 'send_key': True|False}]
:param str name: Name of key chain
:param list key_chain_entry: list of key chain entries
:raises CreateElementFailed: create failed with reason
... |
7,236 | def format(self, vertices):
index = .join(str(vertices[vn].index) for vn in self.vnames)
vcom = .join(self.vnames)
buf = io.StringIO()
buf.write(\
.format(
index,self.name, vcom))
buf.write()
for p in self.points:
... | Format instance to dump
vertices is dict of name to Vertex |
7,237 | def run_until_disconnected(self):
if self.loop.is_running():
return self._run_until_disconnected()
try:
return self.loop.run_until_complete(self.disconnected)
except KeyboardInterrupt:
pass
finally:
self.disconnect() | Runs the event loop until `disconnect` is called or if an error
while connecting/sending/receiving occurs in the background. In
the latter case, said error will ``raise`` so you have a chance
to ``except`` it on your own code.
If the loop is already running, this method returns a corout... |
7,238 | def docpie(doc, argv=None, help=True, version=None,
stdopt=True, attachopt=True, attachvalue=True,
helpstyle=,
auto2dashes=True, name=None, case_sensitive=False,
optionsfirst=False, appearedonly=False, namedoptions=False,
extra=None):
if case_sensitive:
... | Parse `argv` based on command-line interface described in `doc`.
`docpie` creates your command-line interface based on its
description that you pass as `doc`. Such description can contain
--options, <positional-argument>, commands, which could be
[optional], (required), (mutually | exclusive) or repeat... |
7,239 | def run_all(logdir, verbose=False):
run_box_to_gaussian(logdir, verbose=verbose)
run_sobel(logdir, verbose=verbose) | Run simulations on a reasonable set of parameters.
Arguments:
logdir: the directory into which to store all the runs' data
verbose: if true, print out each run's name as it begins |
7,240 | def arg_completions(
completion_text: str,
parent_function: str,
args: list,
arg_idx: int,
bel_spec: BELSpec,
bel_fmt: str,
species_id: str,
namespace: str,
size: int,
):
function_long = bel_spec["functions"]["to_long"].get(parent_function)
if not function_long:
... | Function argument completion
Only allow legal options for completion given function name, arguments and index of argument
to replace.
Args:
completion_text: text to use for completion - used for creating highlight
parent_function: BEL function containing these args
args: arguments ... |
7,241 | def post_step(self, ctxt, step, idx, result):
debugger = ExtensionDebugger()
for ext in self.exts:
with debugger(ext):
ext.post_step(ctxt, step, idx, result)
return result | Called after executing a step.
:param ctxt: An instance of ``timid.context.Context``.
:param step: An instance of ``timid.steps.Step`` describing
the step that was executed.
:param idx: The index of the step in the list of steps.
:param result: An instance of ``timi... |
7,242 | def add_intern_pattern(self, url=None):
try:
pat = self.get_intern_pattern(url=url)
if pat:
log.debug(LOG_CHECK, "Add intern pattern %r", pat)
self.aggregate.config[].append(get_link_pat(pat))
except UnicodeError as msg:
res = ... | Add intern URL regex to config. |
7,243 | def _from_dict(cls, _dict):
args = {}
if in _dict:
args[] = DocInfo._from_dict(_dict.get())
if in _dict:
args[] = _dict.get()
if in _dict:
args[] = _dict.get()
if in _dict:
args[] = [
Tables._from_dict(x... | Initialize a TableReturn object from a json dictionary. |
7,244 | def osx_clipboard_get():
p = subprocess.Popen([, , ],
stdout=subprocess.PIPE)
text, stderr = p.communicate()
text = text.replace(, )
return text | Get the clipboard's text on OS X. |
7,245 | def addbr(name):
fcntl.ioctl(ifconfig.sockfd, SIOCBRADDBR, name)
return Bridge(name) | Create new bridge with the given name |
7,246 | def print_roi(self, loglevel=logging.INFO):
self.logger.log(loglevel, + str(self.roi)) | Print information about the spectral and spatial properties
of the ROI (sources, diffuse components). |
7,247 | def disconnect_async(self, connection_id, callback):
try:
context = self.connections.get_context(connection_id)
except ArgumentError:
callback(connection_id, self.id, False, "Could not find connection information")
return
self.connections.begin_disc... | Asynchronously disconnect from a device that has previously been connected
Args:
connection_id (int): A unique identifier for this connection on the DeviceManager that owns this adapter.
callback (callable): A function called as callback(connection_id, adapter_id, success, failure_reaso... |
7,248 | def delete_rule(name=None,
localport=None,
protocol=None,
dir=None,
remoteip=None):
test*test8080tcpintest_remote_ip*test_remote_ip8000tcpin192.168.0.1*allow80*
cmd = [, , , , ]
if name:
cmd.append(.format(name))
if protocol:
... | .. versionadded:: 2015.8.0
Delete an existing firewall rule identified by name and optionally by ports,
protocols, direction, and remote IP.
Args:
name (str): The name of the rule to delete. If the name ``all`` is used
you must specify additional parameters.
localport (Option... |
7,249 | def cmd_zf(self, ch=None):
viewer = self.get_viewer(ch)
if viewer is None:
self.log("No current viewer/channel.")
return
viewer.zoom_fit()
cur_lvl = viewer.get_zoom()
self.log("zoom=%f" % (cur_lvl)) | zf ch=chname
Zoom the image for the given viewer/channel to fit the window. |
7,250 | def makediagram(edges):
graph = pydot.Dot(graph_type=)
nodes = edges2nodes(edges)
epnodes = [(node,
makeanode(node[0])) for node in nodes if nodetype(node)=="epnode"]
endnodes = [(node,
makeendnode(node[0])) for node in nodes if nodetype(node)=="EndNode"]
epbr = [(node, makeab... | make the diagram with the edges |
7,251 | def set_elements_text(parent_to_parse, element_path=None, text_values=None):
if text_values is None:
text_values = []
return _set_elements_property(parent_to_parse, element_path, _ELEM_TEXT, text_values) | Assigns an array of text values to each of the elements parsed from the parent. The
text values are assigned in the same order they are provided.
If there are less values then elements, the remaining elements are skipped; but if
there are more, new elements will be inserted for each with the remaining text ... |
7,252 | def _michael_b(m_l, m_r):
m_r = m_r ^ _rotate_left32(m_l, 17)
m_l = (m_l + m_r) % 2**32
m_r = m_r ^ _XSWAP(m_l)
m_l = (m_l + m_r) % 2**32
m_r = m_r ^ _rotate_left32(m_l, 3)
m_l = (m_l + m_r) % 2**32
m_r = m_r ^ _rotate_right32(m_l, 2)
m_l = (m_l + m_r) % 2**32
return m_l, m_r | Defined in 802.11i p.49 |
7,253 | def forward_kinematics(self, joints, full_kinematics=False):
frame_matrix = np.eye(4)
if full_kinematics:
frame_matrixes = []
if len(self.links) != len(joints):
raise ValueError("Your joints vector length is {} but you have {} links".format(len(joints), len(sel... | Returns the transformation matrix of the forward kinematics
Parameters
----------
joints: list
The list of the positions of each joint. Note : Inactive joints must be in the list.
full_kinematics: bool
Return the transformation matrices of each joint
Ret... |
7,254 | def volume(self):
mprop = vtk.vtkMassProperties()
mprop.SetInputData(self.tri_filter())
return mprop.GetVolume() | Mesh volume - will throw a VTK error/warning if not a closed surface
Returns
-------
volume : float
Total volume of the mesh. |
7,255 | def datum_to_value(self, instance, datum):
if datum is None:
return []
if not isinstance(datum, Sequence):
raise TypeError(
"datum must be a sequence, not %s" % type(datum).__name__)
bound = getattr(instance._origin, "FilesystemGroupDevic... | Convert a given MAAS-side datum to a Python-side value.
:param instance: The `Object` instance on which this field is
currently operating. This method should treat it as read-only, for
example to perform validation with regards to other fields.
:param datum: The MAAS-side datum ... |
7,256 | def get_unicodedata(version, output=HOME, no_zip=False):
target = os.path.join(output, , version)
zip_target = os.path.join(output, , % version)
if not os.path.exists(target) and os.path.exists(zip_target):
unzip_unicode(output, version)
download_unicodedata(version, output, no_zip... | Ensure we have Unicode data to generate Unicode tables. |
7,257 | def get_category_drilldown(parser, token):
bits = token.split_contents()
error_str = \
\
if len(bits) == 4:
if bits[2] != :
raise template.TemplateSyntaxError(error_str % {: bits[0]})
if bits[2] == :
varname = bits[3].strip("usi... | Retrieves the specified category, its ancestors and its immediate children
as an iterable.
Syntax::
{% get_category_drilldown "category name" [using "app.Model"] as varname %}
Example::
{% get_category_drilldown "/Grandparent/Parent" [using "app.Model"] as family %}
or ::
{... |
7,258 | def is_intersection(g, n):
return len(set(g.predecessors(n) + g.successors(n))) > 2 | Determine if a node is an intersection
graph: 1 -->-- 2 -->-- 3
>>> is_intersection(g, 2)
False
graph:
1 -- 2 -- 3
|
4
>>> is_intersection(g, 2)
True
Parameters
----------
g : networkx DiGraph
n : node id
Returns
-------
bool |
7,259 | def make_index_for(package, index_dir, verbose=True):
index_template =
item_template =
index_filename = os.path.join(index_dir, "index.html")
if not os.path.isdir(index_dir):
os.makedirs(index_dir)
parts = []
for pkg_filename in package.files:
pkg_name = os.path.basename(... | Create an 'index.html' for one package.
:param package: Package object to use.
:param index_dir: Where 'index.html' should be created. |
7,260 | def _check_query(self, query, style_cols=None):
try:
self.sql_client.send(
utils.minify_sql((
,
,
,
,
,
)).format(query=query,
comma=... | Checks if query from Layer or QueryLayer is valid |
7,261 | def create_ports(port, mpi, rank):
if port == "random" or port is None:
ports = {}
else:
port = int(port)
ports = {
"REQ": port + 0,
"PUSH": port + 1,
"SUB": port + 2
}
... | create a list of ports for the current rank |
7,262 | def add_request(self, request):
if request.name in self.requests:
raise ValueError(.format(request.name))
self.requests[request.name] = request
for method, url in request.urls:
if RE_URL_ARG.search(url):
request_r... | Add a request object |
7,263 | def from_text(text):
if text.isdigit():
value = int(text)
if value >= 0 and value <= 15:
return value
value = _by_text.get(text.upper())
if value is None:
raise UnknownOpcode
return value | Convert text into an opcode.
@param text: the textual opcode
@type text: string
@raises UnknownOpcode: the opcode is unknown
@rtype: int |
7,264 | def _init_index(root_dir, schema, index_name):
index_dir = os.path.join(root_dir, index_name)
try:
if not os.path.exists(index_dir):
os.makedirs(index_dir)
return create_in(index_dir, schema), index_dir
else:
return open_dir(index_dir), index_dir
exc... | Creates new index or opens existing.
Args:
root_dir (str): root dir where to find or create index.
schema (whoosh.fields.Schema): schema of the index to create or open.
index_name (str): name of the index.
Returns:
tuple ((whoosh.index.FileIndex, str)): first element is index, ... |
7,265 | def validate_subfolders(filedir, metadata):
if not os.path.isdir(filedir):
print("Error: " + filedir + " is not a directory")
return False
subfolders = os.listdir(filedir)
for subfolder in subfolders:
if subfolder not in metadata:
print("Error: folder " + subfolder +... | Check that all folders in the given directory have a corresponding
entry in the metadata file, and vice versa.
:param filedir: This field is the target directory from which to
match metadata
:param metadata: This field contains the metadata to be matched. |
7,266 | def match_aspect_to_viewport(self):
viewport = self.viewport
self.aspect = float(viewport.width) / viewport.height | Updates Camera.aspect to match the viewport's aspect ratio. |
7,267 | def get_user(self, user):
return self.service.get_user(
user, self.url_prefix, self.auth, self.session, self.session_send_opts) | Get user's data (first and last name, email, etc).
Args:
user (string): User name.
Returns:
(dictionary): User's data encoded in a dictionary.
Raises:
requests.HTTPError on failure. |
7,268 | def average_gradient(data, *kwargs):
return np.average(np.array(np.gradient(data))**2) | Compute average gradient norm of an image |
7,269 | def natsorted(seq, key=lambda x: x, number_type=float, signed=True, exp=True):
return sorted(seq, key=lambda x: natsort_key(key(x),
number_type=number_type,
signed=signed, exp=exp)) | \
Sorts a sequence naturally (alphabetically and numerically),
not lexicographically.
>>> a = ['num3', 'num5', 'num2']
>>> natsorted(a)
['num2', 'num3', 'num5']
>>> b = [('a', 'num3'), ('b', 'num5'), ('c', 'num2')]
>>> from operator import itemgetter
>>> natsorte... |
7,270 | def send_output_report(self, data):
assert( self.is_opened() )
if not ( isinstance(data, ctypes.Array) and \
issubclass(data._type_, c_ubyte) ):
raw_data_type = c_ubyte * len(data)
raw_data = raw_data_type()
for index in range(... | Send input/output/feature report ID = report_id, data should be a
c_ubyte object with included the required report data |
7,271 | def miraligner(args):
hairpin, mirna = _download_mirbase(args)
precursors = _read_precursor(args.hairpin, args.sps)
matures = _read_mature(args.mirna, args.sps)
gtf = _read_gtf(args.gtf)
out_dts = []
out_files = []
for bam_fn in args.files:
sample = op.splitext(op.basename(bam_f... | Realign BAM hits to miRBAse to get better accuracy and annotation |
7,272 | def do_powershell_complete(cli, prog_name):
commandline = os.environ[]
args = split_args(commandline)[1:]
quote = single_quote
incomplete =
if args and not commandline.endswith():
incomplete = args[-1]
args = args[:-1]
quote_pos = commandline.rfind(incomplete) - 1
... | Do the powershell completion
Parameters
----------
cli : click.Command
The main click Command of the program
prog_name : str
The program name on the command line
Returns
-------
bool
True if the completion was successful, False otherwise |
7,273 | def single_value(cls, value, shape, pixel_scale, origin=(0.0, 0.0)):
array = np.ones(shape) * value
return cls(array, pixel_scale, origin) | Creates an instance of Array and fills it with a single value
Parameters
----------
value: float
The value with which the array should be filled
shape: (int, int)
The shape of the array
pixel_scale: float
The scale of a pixel in arc seconds
... |
7,274 | def minimum_katcp_version(major, minor=0):
version_tuple = (major, minor)
def decorator(handler):
handler._minimum_katcp_version = version_tuple
return handler
return decorator | Decorator; exclude handler if server's protocol version is too low
Useful for including default handler implementations for KATCP features that
are only present in certain KATCP protocol versions
Examples
--------
>>> class MyDevice(DeviceServer):
... '''This device server will expose ?myr... |
7,275 | def focusd(task):
if registration.get_registered(event_hooks=True, root_access=True):
start_cmd_srv = (os.getuid() == 0)
else:
start_cmd_srv = False
_run = lambda: Focusd(task).run(start_cmd_srv)
daemonize(get_daemon_pidfile(task), task.task_dir, _run) | Forks the current process as a daemon to run a task.
`task`
``Task`` instance for the task to run. |
7,276 | def get_task(self, task=0, timeout=None, block=True):
return _NuMapTask(self, task=task, timeout=timeout, block=block) | Returns an iterator which results are limited to one **task**. The
default iterator the one which e.g. will be used in a for loop is the
iterator for the first task (task =0). The returned iterator is a
``_NuMapTask`` instance.
Compare::
for result_from_task_0 in ... |
7,277 | def getTotalw(self):
w = sum([field.w for field in self.fields])
return w | Returns the cumulative w for all the fields in the dataset |
7,278 | def is_training_modified(self):
last_modified = self.trainer.get_last_modified()
if last_modified > self.training_timestamp:
return True
else:
return False | Returns `True` if training data
was modified since last training.
Returns `False` otherwise,
or if using builtin training data. |
7,279 | def list(self, **params):
_, _, visit_outcomes = self.http_client.get("/visit_outcomes", params=params)
return visit_outcomes | Retrieve visit outcomes
Returns Visit Outcomes, according to the parameters provided
:calls: ``get /visit_outcomes``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of VisitOutcomes.
:r... |
7,280 | def addGlobalServices(self):
if self.options.get() and self.options.get():
_cache = self.getCacheService()
_cache.startService() | This is where we put service that we don't want to be duplicated on
worker subprocesses |
7,281 | def untranslateName(s):
s = s.replace(, )
s = s.replace(, )
if s[:2] == : s = s[2:]
s = s.replace(, )
return s | Undo Python conversion of CL parameter or variable name. |
7,282 | def make_matrix(version, reserve_regions=True, add_timing=True):
size = calc_matrix_size(version)
row = [0x2] * size
matrix = tuple([bytearray(row) for i in range(size)])
if reserve_regions:
if version > 6:
for i in range(6):
matrix[... | \
Creates a matrix of the provided `size` (w x h) initialized with the
(illegal) value 0x2.
The "timing pattern" is already added to the matrix and the version
and format areas are initialized with 0x0.
:param int version: The (Micro) QR Code version
:rtype: tuple of bytearrays |
7,283 | def Datetime(null=True, **kwargs):
return Property(
types=datetime.datetime,
convert=util.local_timezone,
load=dateutil.parser.parse,
null=null,
**kwargs
) | A datetime property. |
7,284 | def defaults(d1, d2):
d1 = d1.copy()
tolist = isinstance(d2, pd.DataFrame)
keys = (k for k in d2 if k not in d1)
for k in keys:
if tolist:
d1[k] = d2[k].tolist()
else:
d1[k] = d2[k]
return d1 | Update a copy of d1 with the contents of d2 that are
not in d1. d1 and d2 are dictionary like objects.
Parameters
----------
d1 : dict | dataframe
dict with the preferred values
d2 : dict | dataframe
dict with the default values
Returns
-------
out : dict | dataframe
... |
7,285 | def find_and_filter_sgf_files(base_dir, min_year=None, komi=None):
sgf_files = []
for dirpath, dirnames, filenames in os.walk(base_dir):
for filename in filenames:
if filename.endswith():
path = os.path.join(dirpath, filename)
sgf_files.append(path)
... | Finds all sgf files in base_dir with year >= min_year and komi |
7,286 | def Points(plist, r=5, c="gray", alpha=1):
def _colorPoints(plist, cols, r, alpha):
n = len(plist)
if n > len(cols):
colors.printc("~times Error: mismatch in colorPoints()", n, len(cols), c=1)
exit()
if n != len(cols):
colors.printc("~lightning Warni... | Build a point ``Actor`` for a list of points.
:param float r: point radius.
:param c: color name, number, or list of [R,G,B] colors of same length as plist.
:type c: int, str, list
:param float alpha: transparency in range [0,1].
.. hint:: |lorenz| |lorenz.py|_ |
7,287 | def vcs_upload():
if env.deploy_tool == "git":
remote_path = "ssh://%s@%s%s" % (env.user, env.host_string,
env.repo_path)
if not exists(env.repo_path):
run("mkdir -p %s" % env.repo_path)
with cd(env.repo_path):
run... | Uploads the project with the selected VCS tool. |
7,288 | def inFootprint(footprint,ra,dec):
if footprint is None:
return np.ones(len(ra),dtype=bool)
try:
if isinstance(footprint,str) and os.path.exists(footprint):
filename = footprint
footprint = read_map(filename)
nside = hp.npix2nsi... | Check if set of ra,dec combinations are in footprint.
Careful, input files must be in celestial coordinates.
filename : Either healpix map or mangle polygon file
ra,dec : Celestial coordinates
Returns:
inside : boolean array of coordinates in footprint |
7,289 | def values(self):
values = []
for __, data in self.items():
values.append(data)
return values | return a list of all state values |
7,290 | def remove(self, branch, turn, tick):
for parent, entitys in list(self.parents.items()):
for entity, keys in list(entitys.items()):
for key, branchs in list(keys.items()):
if branch in branchs:
branhc = branchs[branch]
... | Delete data on or after this tick
On the assumption that the future has been invalidated. |
7,291 | def hmget(self, *args):
if args and not any(arg in self._instancehash_fields for arg in args):
raise ValueError("Only InstanceHashField can be used here.")
return self._call_command(, args) | This command on the model allow getting many instancehash fields with only
one redis call. You must pass hash name to retrieve as arguments. |
7,292 | def add(self, data):
for host in data:
for key in data[host]:
if not data[host][key] == []:
self.add_item(host, key, data[host][key]) | Add a list of item into the container
:data: dict of items & value per hostname |
7,293 | def _validate_num_units(num_units, service_name, add_error):
if num_units is None:
return 0
try:
num_units = int(num_units)
except (TypeError, ValueError):
add_error(
.format(service_name))
return
if num_units < 0:
add_error(
... | Check that the given num_units is valid.
Use the given service name to describe possible errors.
Use the given add_error callable to register validation error.
If no errors are encountered, return the number of units as an integer.
Return None otherwise. |
7,294 | def color(self):
color = idc.GetColor(self.ea, idc.CIC_ITEM)
if color == 0xFFFFFFFF:
return None
return color | Line color in IDA View |
7,295 | def search(self, word, limit=30):
search = Search(PrefixQuery("word", word), sort={"count": "desc"})
for doc in self.connection.search(
search, indexes=[self.index], count=limit):
yield (doc["word"], doc["count"]) | Search for a word within the wordgatherer collection.
:param word: Word to search for.
:param limit: Maximum number of results to return. |
7,296 | def put(self, key, value):
key = self._service_key(key)
self._service_ops[](key, value) | Stores the object `value` named by `key` in `service`.
Args:
key: Key naming `value`.
value: the object to store. |
7,297 | def meanprecision(a):
s = a.sum()
m = a / s
return (m,s) | Mean and precision of Dirichlet distribution.
Parameters
----------
a : array
Parameters of Dirichlet distribution.
Returns
-------
mean : array
Numbers [0,1] of the means of the Dirichlet distribution.
precision : float
Precision or concentration parameter of the D... |
7,298 | def t_RP(self, t):
r
if t.value != and OPTIONS.bracket.value:
t.type =
return t | r'[])] |
7,299 | def initialize_layers(self, layers=None):
if layers is not None:
self.layers = layers
self.layers_ = Layers()
if isinstance(self.layers[0], Layer):
for out_layer in self.layers:
for i, layer in enumerate(get_all_layers(out_layer)):
... | Sets up the Lasagne layers
:param layers: The dictionary of layers, or a
:class:`lasagne.Layers` instance, describing the underlying
network
:return: the output layer of the underlying lasagne network.
:seealso: :ref:`layer-def` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.