code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def process_rpc(self, rpc):
"""Process input and output parts of `rpc`."""
p = "/nc:rpc/" + self.qname(rpc)
tmpl = self.xsl_template(p)
inp = rpc.search_one("input")
if inp is not None:
ct = self.xsl_calltemplate("rpc-input", tmpl)
self.xsl_withparam("nsid... | Process input and output parts of `rpc`. |
def file_link(self, instance):
'''
Renders the link to the student upload file.
'''
sfile = instance.file_upload
if not sfile:
return mark_safe('No file submitted by student.')
else:
return mark_safe('<a href="%s">%s</a><br/>(<a href="%s" targe... | Renders the link to the student upload file. |
def _validate_ctypes(self, from_obj, to_obj):
"""
Asserts that the content types for the given object are valid for this
relationship. If validation fails, ``AssertionError`` will be raised.
"""
if from_obj:
from_ctype = ContentType.objects.get_for_model(from_obj)
... | Asserts that the content types for the given object are valid for this
relationship. If validation fails, ``AssertionError`` will be raised. |
def add_media(dest, media):
"""
Optimized version of django.forms.Media.__add__() that doesn't create new objects.
"""
if django.VERSION >= (2, 2):
dest._css_lists += media._css_lists
dest._js_lists += media._js_lists
elif django.VERSION >= (2, 0):
combined = dest + media
... | Optimized version of django.forms.Media.__add__() that doesn't create new objects. |
def range(cls, collection, attribute, left, right, closed, index_id, skip=None, limit=None):
"""
This will find all documents within a given range. In order to execute a range query, a
skip-list index on the queried attribute must be present.
:param collection Collection ins... | This will find all documents within a given range. In order to execute a range query, a
skip-list index on the queried attribute must be present.
:param collection Collection instance
:param attribute The attribute path to check
:param left The lower bound
:p... |
def get_op_version(name):
'''
.. versionadded:: 2019.2.0
Returns the glusterfs volume op-version
name
Name of the glusterfs volume
CLI Example:
.. code-block:: bash
salt '*' glusterfs.get_op_version <volume>
'''
cmd = 'volume get {0} cluster.op-version'.format(name)... | .. versionadded:: 2019.2.0
Returns the glusterfs volume op-version
name
Name of the glusterfs volume
CLI Example:
.. code-block:: bash
salt '*' glusterfs.get_op_version <volume> |
def count_mapped_reads(self, file_name, paired_end):
"""
Mapped_reads are not in fastq format, so this one doesn't need to accommodate fastq,
and therefore, doesn't require a paired-end parameter because it only uses samtools view.
Therefore, it's ok that it has a default parameter, sinc... | Mapped_reads are not in fastq format, so this one doesn't need to accommodate fastq,
and therefore, doesn't require a paired-end parameter because it only uses samtools view.
Therefore, it's ok that it has a default parameter, since this is discarded.
:param str file_name: File for which to cou... |
def reshape(tt_array, shape, eps=1e-14, rl=1, rr=1):
''' Reshape of the TT-vector
[TT1]=TT_RESHAPE(TT,SZ) reshapes TT-vector or TT-matrix into another
with mode sizes SZ, accuracy 1e-14
[TT1]=TT_RESHAPE(TT,SZ,EPS) reshapes TT-vector/matrix into another with
mode sizes SZ and accuracy EP... | Reshape of the TT-vector
[TT1]=TT_RESHAPE(TT,SZ) reshapes TT-vector or TT-matrix into another
with mode sizes SZ, accuracy 1e-14
[TT1]=TT_RESHAPE(TT,SZ,EPS) reshapes TT-vector/matrix into another with
mode sizes SZ and accuracy EPS
[TT1]=TT_RESHAPE(TT,SZ,EPS, RL) reshapes TT-vector/... |
def get_instance(self, payload):
"""
Build an instance of TaskInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.autopilot.v1.assistant.task.TaskInstance
:rtype: twilio.rest.autopilot.v1.assistant.task.TaskInstance
"""
return TaskI... | Build an instance of TaskInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.autopilot.v1.assistant.task.TaskInstance
:rtype: twilio.rest.autopilot.v1.assistant.task.TaskInstance |
def init_app_context():
"""Initialize app context for Invenio 2.x."""
try:
from invenio.base.factory import create_app
app = create_app()
app.test_request_context('/').push()
app.preprocess_request()
except ImportError:
pass | Initialize app context for Invenio 2.x. |
def detect_encoding(filename, limit_byte_check=-1):
"""Return file encoding."""
try:
with open(filename, 'rb') as input_file:
encoding = _detect_encoding(input_file.readline)
# Check for correctness of encoding.
with open_with_encoding(filename, encoding) as input_fi... | Return file encoding. |
async def tuple(self, elem=None, elem_type=None, params=None):
"""
Loads/dumps tuple
:return:
"""
if hasattr(elem_type, 'blob_serialize'):
container = elem_type() if elem is None else elem
return await container.blob_serialize(self, elem=elem, elem_type=el... | Loads/dumps tuple
:return: |
def _end(ins):
""" Outputs the ending sequence
"""
global FLAG_end_emitted
output = _16bit_oper(ins.quad[1])
output.append('ld b, h')
output.append('ld c, l')
if FLAG_end_emitted:
return output + ['jp %s' % END_LABEL]
FLAG_end_emitted = True
output.append('%s:' % END_LABEL... | Outputs the ending sequence |
def _walk_directory(root_directory):
"""
Generates the paths of all files that are ancestors
of `root_directory`.
"""
paths = [os.path.join(root, name)
for root, dirs, files in os.walk(root_directory) # noqa
for name in files]
paths.sor... | Generates the paths of all files that are ancestors
of `root_directory`. |
def latex_to_img(tex):
"""Return a pygame image from a latex template."""
with tempfile.TemporaryDirectory() as tmpdirname:
with open(tmpdirname + r'\tex.tex', 'w') as f:
f.write(tex)
os.system(r"latex {0}\tex.tex -halt-on-error -interaction=batchmode -disable-in... | Return a pygame image from a latex template. |
def _get_model_instance(model_cls, data):
"""Convert dict into object of class of passed model.
:param class model_cls:
:param object data:
:rtype DomainModel:
"""
if not isinstance(data, (model_cls, dict)):
raise TypeError('{0} is not valid type, instance of... | Convert dict into object of class of passed model.
:param class model_cls:
:param object data:
:rtype DomainModel: |
def host(self, value=None):
"""
Return the host
:param string value: new host string
"""
if value is not None:
return URL._mutate(self, host=value)
return self._tuple.host | Return the host
:param string value: new host string |
def visit_Dict(self, node):
""" Define set type from all elements type (or empty_dict type). """
self.generic_visit(node)
if node.keys:
for key, value in zip(node.keys, node.values):
value_type = self.result[value]
self.combine(node, key,
... | Define set type from all elements type (or empty_dict type). |
def one_hot(cls, ij, sz):
"""
ij: postion
sz: size of matrix
"""
if isinstance(sz, int):
sz = (sz, sz)
if isinstance(ij, int):
ij = (ij, ij)
m = np.zeros(sz)
m[ij[0], ij[1]] = 1.0
return Matrix(m) | ij: postion
sz: size of matrix |
def vsubg(v1, v2, ndim):
"""
Compute the difference between two double precision
vectors of arbitrary dimension.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vsubg_c.html
:param v1: First vector (minuend).
:type v1: Array of floats
:param v2: Second vector (subtrahend).
:t... | Compute the difference between two double precision
vectors of arbitrary dimension.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vsubg_c.html
:param v1: First vector (minuend).
:type v1: Array of floats
:param v2: Second vector (subtrahend).
:type v2: Array of floats
:param nd... |
def send_raw_transaction(self, hextx, **kwargs):
""" Broadcasts a transaction over the NEO network and returns the result.
:param hextx: hexadecimal string that has been serialized
:type hextx: str
:return: result of the transaction
:rtype: bool
"""
return self.... | Broadcasts a transaction over the NEO network and returns the result.
:param hextx: hexadecimal string that has been serialized
:type hextx: str
:return: result of the transaction
:rtype: bool |
def sanitize_dict(input_dict):
r"""
Given a nested dictionary, ensures that all nested dicts are normal
Python dicts. This is necessary for pickling, or just converting
an 'auto-vivifying' dict to something that acts normal.
"""
plain_dict = dict()
for key in input_dict.keys():
valu... | r"""
Given a nested dictionary, ensures that all nested dicts are normal
Python dicts. This is necessary for pickling, or just converting
an 'auto-vivifying' dict to something that acts normal. |
def _split_regex(regex):
"""
Return an array of the URL split at each regex match like (?P<id>[\d]+)
Call with a regex of '^/foo/(?P<id>[\d]+)/bar/$' and you will receive ['/foo/', '/bar/']
"""
if regex[0] == '^':
regex = regex[1:]
if regex[-1] == '$':
regex = regex[0:-1]
res... | Return an array of the URL split at each regex match like (?P<id>[\d]+)
Call with a regex of '^/foo/(?P<id>[\d]+)/bar/$' and you will receive ['/foo/', '/bar/'] |
def dynacRepresentation(self):
"""
Return the Pynac representation of this Set4DAperture instance.
"""
details = [
self.voltage.val,
self.phase.val,
self.harmonicNum.val,
self.apertureRadius.val,
]
return ['BUNCHER', [detail... | Return the Pynac representation of this Set4DAperture instance. |
def padding_oracle_encrypt(oracle, plaintext, block_size=128, pool=None):
"""
Encrypt plaintext using an oracle function that returns ``True`` if the
provided ciphertext is correctly PKCS#7 padded after decryption. The
cipher needs to operate in CBC mode.
Args:
oracle(callable): The oracle ... | Encrypt plaintext using an oracle function that returns ``True`` if the
provided ciphertext is correctly PKCS#7 padded after decryption. The
cipher needs to operate in CBC mode.
Args:
oracle(callable): The oracle function. Will be called repeatedly with
a chunk of ciphertext.
pl... |
def plot_mag(fignum, datablock, s, num, units, norm):
"""
plots magnetization against (de)magnetizing temperature or field
Parameters
_________________
fignum : matplotlib figure number for plotting
datablock : nested list of [step, 0, 0, magnetization, 1,quality]
s : string for title
n... | plots magnetization against (de)magnetizing temperature or field
Parameters
_________________
fignum : matplotlib figure number for plotting
datablock : nested list of [step, 0, 0, magnetization, 1,quality]
s : string for title
num : matplotlib figure number, can set to 1
units : [T,K,U] fo... |
def load_json_fixture(fixture_path: str) -> Dict[str, Any]:
"""
Loads a fixture file, caching the most recent files it loaded.
"""
with open(fixture_path) as fixture_file:
file_fixtures = json.load(fixture_file)
return file_fixtures | Loads a fixture file, caching the most recent files it loaded. |
def execute_sql(
self,
sql,
params=None,
param_types=None,
query_mode=None,
partition=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
):
"""Perform an ``ExecuteStreamingSql`` API request.
... | Perform an ``ExecuteStreamingSql`` API request.
:type sql: str
:param sql: SQL query statement
:type params: dict, {str -> column value}
:param params: values for parameter replacement. Keys must match
the names used in ``sql``.
:type param_types: dict[... |
def unredirect_stdout(self):
"""Redirect stdout and stderr back to screen."""
if hasattr(self, 'hijacked_stdout') and hasattr(self, 'hijacked_stderr'):
sys.stdout = self.hijacked_stdout
sys.stderr = self.hijacked_stderr | Redirect stdout and stderr back to screen. |
def _push_new_state(self):
"""Push a new state into history.
This new state will be used to hold resolution results of the next
coming round.
"""
try:
base = self._states[-1]
except IndexError:
graph = DirectedGraph()
graph.add(None) ... | Push a new state into history.
This new state will be used to hold resolution results of the next
coming round. |
def available_metrics(self):
"""
List all available metrics that you can add to this machine
:returns: A list of dicts, each of which is a metric that you can add to a monitored machine
"""
req = self.request(self.mist_client.uri+"/clouds/"+self.cloud.id+"/machines/"+self.id+"/m... | List all available metrics that you can add to this machine
:returns: A list of dicts, each of which is a metric that you can add to a monitored machine |
def average(iterator):
"""Iterative mean."""
count = 0
total = 0
for num in iterator:
count += 1
total += num
return float(total)/count | Iterative mean. |
def to_df(self, variables=None, format='wide', sparse=True,
sampling_rate=None, include_sparse=True, include_dense=True,
**kwargs):
''' Merge columns into a single pandas DataFrame.
Args:
variables (list): Optional list of variable names to retain;
... | Merge columns into a single pandas DataFrame.
Args:
variables (list): Optional list of variable names to retain;
if None, all variables are written out.
format (str): Whether to return a DataFrame in 'wide' or 'long'
format. In 'wide' format, each row is ... |
def input_object(prompt_text, cast = None, default = None,
prompt_ext = ': ', castarg = [], castkwarg = {}):
"""Gets input from the command line and validates it.
prompt_text
A string. Used to prompt the user. Do not include a trailing
space.
prompt_ext
... | Gets input from the command line and validates it.
prompt_text
A string. Used to prompt the user. Do not include a trailing
space.
prompt_ext
Added on to the prompt at the end. At the moment this must not
include any control stuff because it is send directly to
... |
def commit_index(self, message):
"""
Commit the current index.
:param message: str
:return: str the generated commit sha
"""
tree_id = self.write_tree()
args = ['commit-tree', tree_id, '-p', self.ref_head]
# todo, this can end in a race-condition with ot... | Commit the current index.
:param message: str
:return: str the generated commit sha |
def _oval_string(self, p1, p2, p3, p4):
"""Return /AP string defining an oval within a 4-polygon provided as points
"""
def bezier(p, q, r):
f = "%f %f %f %f %f %f c\n"
return f % (p.x, p.y, q.x, q.y, r.x, r.y)
kappa = 0.55228474983 # magic number
... | Return /AP string defining an oval within a 4-polygon provided as points |
def validiate_webhook_signature(self, webhook, signature):
"""Validates a webhook signature from a webhook body + client secret
Parameters
webhook (string)
The request body of the webhook.
signature (string)
The webhook signature specified in X-Ub... | Validates a webhook signature from a webhook body + client secret
Parameters
webhook (string)
The request body of the webhook.
signature (string)
The webhook signature specified in X-Uber-Signature header. |
def prettyPrintPacket(pkt):
"""
not done
"""
s = 'packet ID: {} instr: {} len: {}'.format(pkt[4], pkt[7], int((pkt[6] << 8) + pkt[5]))
if len(s) > 10:
params = pkt[8:-2]
s += ' params: {}'.format(params)
return s | not done |
def Get(self,key):
"""Get alert by providing name, ID, or other unique key.
If key is not unique and finds multiple matches only the first
will be returned
"""
for alert in self.alerts:
if alert.id == key: return(alert)
elif alert.name == key: return(alert) | Get alert by providing name, ID, or other unique key.
If key is not unique and finds multiple matches only the first
will be returned |
def _render(self):
"""
Render the text.
Avoid using this fonction too many time as it is slow as it is low to render text and blit it.
"""
self._last_text = self.text
self._surface = self.font.render(self.text, True, self.color, self.bg_color)
rect = self._surf... | Render the text.
Avoid using this fonction too many time as it is slow as it is low to render text and blit it. |
def upload(request):
"""
Displays an upload form
Creates upload url and token from youtube api and uses them on the form
"""
# Get the optional parameters
title = request.GET.get("title", "%s's video on %s" % (
request.user.username, request.get_host()))
description = request.GET.get... | Displays an upload form
Creates upload url and token from youtube api and uses them on the form |
def namedb_get_name_preorder( db, preorder_hash, current_block ):
"""
Get a (singular) name preorder record outstanding at the given block, given the preorder hash.
NOTE: returns expired preorders.
Return the preorder record on success.
Return None if not found.
"""
select_query = "SEL... | Get a (singular) name preorder record outstanding at the given block, given the preorder hash.
NOTE: returns expired preorders.
Return the preorder record on success.
Return None if not found. |
def get_votes(self):
"""
Get all votes for this election.
"""
candidate_elections = CandidateElection.objects.filter(election=self)
votes = None
for ce in candidate_elections:
votes = votes | ce.votes.all()
return votes | Get all votes for this election. |
def save(self):
"""
Saves or updates the current tailored audience permission.
"""
if self.id:
method = 'put'
resource = self.RESOURCE.format(
account_id=self.account.id,
tailored_audience_id=self.tailored_audience_id,
... | Saves or updates the current tailored audience permission. |
def codemirror_html(self, config_name, varname, element_id):
"""
Render HTML for a CodeMirror instance.
Since a CodeMirror instance have to be attached to a HTML element, this
method requires a HTML element identifier with or without the ``#``
prefix, it depends from template in... | Render HTML for a CodeMirror instance.
Since a CodeMirror instance have to be attached to a HTML element, this
method requires a HTML element identifier with or without the ``#``
prefix, it depends from template in
``settings.CODEMIRROR_FIELD_INIT_JS`` (default one require to not
... |
def _filter_child_model_fields(cls, fields):
""" Keep only related model fields.
Example: Inherited models: A -> B -> C
B has one-to-many relationship to BMany.
after inspection BMany would have links to B and C. Keep only B. Parent
model A could not be used (It would not be in ... | Keep only related model fields.
Example: Inherited models: A -> B -> C
B has one-to-many relationship to BMany.
after inspection BMany would have links to B and C. Keep only B. Parent
model A could not be used (It would not be in fields)
:param list fields: model fields.
... |
def make_selector(value):
'''Create a selector callable from the supplied value.
Args:
value: If is a callable, then returned unchanged. If a string is used
then create an attribute selector. If in an integer is used then
create a key selector.
Returns:
A ... | Create a selector callable from the supplied value.
Args:
value: If is a callable, then returned unchanged. If a string is used
then create an attribute selector. If in an integer is used then
create a key selector.
Returns:
A callable selector based on the sup... |
def _log(self, monitors, iteration, label='', suffix=''):
'''Log the state of the optimizer on the console.
Parameters
----------
monitors : OrderedDict
A dictionary of monitor names mapped to values. These names and
values are what is being logged.
itera... | Log the state of the optimizer on the console.
Parameters
----------
monitors : OrderedDict
A dictionary of monitor names mapped to values. These names and
values are what is being logged.
iteration : int
Optimization iteration that we are logging.
... |
def load_text_file(self, filename, encoding="utf-8", tokenizer=None):
""" Load in a text file from which to generate a word frequency list
Args:
filename (str): The filepath to the text file to be loaded
encoding (str): The encoding of the text file
t... | Load in a text file from which to generate a word frequency list
Args:
filename (str): The filepath to the text file to be loaded
encoding (str): The encoding of the text file
tokenizer (function): The function to use to tokenize a string |
def frames(self, key=None, orig_order=False):
"""Returns a list of frames in this tag.
If KEY is None, returns all frames in the tag; otherwise returns all frames
whose frameid matches KEY.
If ORIG_ORDER is True, then the frames are returned in their original order.
Othe... | Returns a list of frames in this tag.
If KEY is None, returns all frames in the tag; otherwise returns all frames
whose frameid matches KEY.
If ORIG_ORDER is True, then the frames are returned in their original order.
Otherwise the frames are sorted in canonical order according ... |
def get_fmt_v4(data_type, size, channel_type=v4c.CHANNEL_TYPE_VALUE):
"""convert mdf version 4 channel data type to numpy dtype format string
Parameters
----------
data_type : int
mdf channel data type
size : int
data bit size
channel_type: int
mdf channel type
Retu... | convert mdf version 4 channel data type to numpy dtype format string
Parameters
----------
data_type : int
mdf channel data type
size : int
data bit size
channel_type: int
mdf channel type
Returns
-------
fmt : str
numpy compatible data type format strin... |
def crypt(word, salt=None, rounds=_ROUNDS_DEFAULT):
"""Return a string representing the one-way hash of a password, with a salt
prepended.
If ``salt`` is not specified or is ``None``, the strongest
available method will be selected and a salt generated. Otherwise,
``salt`` may be one of the ``crypt... | Return a string representing the one-way hash of a password, with a salt
prepended.
If ``salt`` is not specified or is ``None``, the strongest
available method will be selected and a salt generated. Otherwise,
``salt`` may be one of the ``crypt.METHOD_*`` values, or a string as
returned by ``crypt.... |
def match(self, environ):
''' Return a (target, url_agrs) tuple or raise HTTPError(404/405). '''
targets, urlargs = self._match_path(environ)
if not targets:
raise HTTPError(404, "Not found: " + repr(environ['PATH_INFO']))
method = environ['REQUEST_METHOD'].upper()
if... | Return a (target, url_agrs) tuple or raise HTTPError(404/405). |
def install_python_module(name):
""" instals a python module using pip """
with settings(hide('warnings', 'running', 'stdout', 'stderr'),
warn_only=False, capture=True):
run('pip --quiet install %s' % name) | instals a python module using pip |
def _get_plugin_stats(self, name):
'''
Used for getting stats for Plugin based stuff, like Kafka Monitor
and Redis Monitor
@param name: the main class stats name
@return: A formatted dict of stats
'''
the_dict = {}
keys = self.redis_conn.keys('stats:{n}:... | Used for getting stats for Plugin based stuff, like Kafka Monitor
and Redis Monitor
@param name: the main class stats name
@return: A formatted dict of stats |
def issue(self, CorpNum, MgtKey, Memo=None, UserID=None):
""" 발행
args
CorpNum : 팝빌회원 사업자번호
MgtKey : 원본 현금영수증 문서관리번호
Memo : 발행 메모
UserID : 팝빌회원 아이디
return
처리결과. consist of code and message
... | 발행
args
CorpNum : 팝빌회원 사업자번호
MgtKey : 원본 현금영수증 문서관리번호
Memo : 발행 메모
UserID : 팝빌회원 아이디
return
처리결과. consist of code and message
raise
PopbillException |
def account_weight(self, account):
"""
Returns the voting weight for **account**
:param account: Account to get voting weight for
:type account: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.account_weight(
... account="xrb_3e3j5tkog48pnny9dmfzj1r16p... | Returns the voting weight for **account**
:param account: Account to get voting weight for
:type account: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.account_weight(
... account="xrb_3e3j5tkog48pnny9dmfzj1r16pg8t1e76dz5tmac6iq689wyjfpi00000000"
... )
... |
def _add_log_handler(
handler, level=None, fmt=None, datefmt=None, propagate=None):
"""
Add a logging handler to Orca.
Parameters
----------
handler : logging.Handler subclass
level : int, optional
An optional logging level that will apply only to this stream
handler.
... | Add a logging handler to Orca.
Parameters
----------
handler : logging.Handler subclass
level : int, optional
An optional logging level that will apply only to this stream
handler.
fmt : str, optional
An optional format string that will be used for the log
messages.
... |
def extract_values(query):
"""
Extract values from insert or update query.
Supports bulk_create
"""
# pylint
if isinstance(query, subqueries.UpdateQuery):
row = query.values
return extract_values_inner(row, query)
if isinstance(query, subqueries.InsertQuery):
ret = []... | Extract values from insert or update query.
Supports bulk_create |
def graham(meshes, xs, ys, zs, expose_horizon=False):
"""
convex_graham
"""
distance_factor = 1.0 # TODO: make this an option (what does it even do)?
# first lets handle the horizon
visibilities, weights, horizon = only_horizon(meshes, xs, ys, zs)
# Order the bodies from front to back. ... | convex_graham |
def make_unix_filename(fname):
"""
:param fname: the basename of a file (e.g., xxx in /zzz/yyy/xxx).
:returns: a valid unix filename
:rtype: string
:raises: DXError if the filename is invalid on a Unix system
The problem being solved here is that *fname* is a python string, it
may contain c... | :param fname: the basename of a file (e.g., xxx in /zzz/yyy/xxx).
:returns: a valid unix filename
:rtype: string
:raises: DXError if the filename is invalid on a Unix system
The problem being solved here is that *fname* is a python string, it
may contain characters that are invalid for a file name.... |
def strip_illumina_suffix(self):
'''Removes any trailing /1 or /2 off the end of the name'''
if self.id.endswith('/1') or self.id.endswith('/2'):
self.id = self.id[:-2] | Removes any trailing /1 or /2 off the end of the name |
def _compile_tag_re(self):
"""
Compile regex strings from device_tag_re option and return list of compiled regex/tag pairs
"""
device_tag_list = []
for regex_str, tags in iteritems(self._device_tag_re):
try:
device_tag_list.append([re.compile(regex_str... | Compile regex strings from device_tag_re option and return list of compiled regex/tag pairs |
def _recv(self):
'''read some bytes into self.buf'''
from . import mavutil
start_time = time.time()
while time.time() < start_time + self.timeout:
m = self.mav.recv_match(condition='SERIAL_CONTROL.count!=0',
... | read some bytes into self.buf |
def getkeyword(self, keyword):
"""Get the value of a table keyword.
The value of a keyword can be a:
- scalar which is returned as a normal python scalar.
- an array which is returned as a numpy array.
- a reference to a table which is returned as a string containing its
... | Get the value of a table keyword.
The value of a keyword can be a:
- scalar which is returned as a normal python scalar.
- an array which is returned as a numpy array.
- a reference to a table which is returned as a string containing its
name prefixed by 'Table :'. It can be ... |
def object_download(self, bucket, key, start_offset=0, byte_count=None):
"""Reads the contents of an object as text.
Args:
bucket: the name of the bucket containing the object.
key: the key of the object to be read.
start_offset: the start offset of bytes to read.
byte_count: the number... | Reads the contents of an object as text.
Args:
bucket: the name of the bucket containing the object.
key: the key of the object to be read.
start_offset: the start offset of bytes to read.
byte_count: the number of bytes to read. If None, it reads to the end.
Returns:
The text con... |
def locus_of_gene_id(self, gene_id):
"""
Given a gene ID returns Locus with: chromosome, start, stop, strand
"""
return self.db.query_locus(
filter_column="gene_id",
filter_value=gene_id,
feature="gene") | Given a gene ID returns Locus with: chromosome, start, stop, strand |
def mangle(self, name, x):
"""
Mangle the name by hashing the I{name} and appending I{x}.
@return: the mangled name.
"""
h = abs(hash(name))
return '%s-%s' % (h, x) | Mangle the name by hashing the I{name} and appending I{x}.
@return: the mangled name. |
def Pipe(self, *sequence, **kwargs):
"""
`Pipe` runs any `phi.dsl.Expression`. Its highly inspired by Elixir's [|> (pipe)](https://hexdocs.pm/elixir/Kernel.html#%7C%3E/2) operator.
**Arguments**
* ***sequence**: any variable amount of expressions. All expressions inside of `sequence` will be composed together... | `Pipe` runs any `phi.dsl.Expression`. Its highly inspired by Elixir's [|> (pipe)](https://hexdocs.pm/elixir/Kernel.html#%7C%3E/2) operator.
**Arguments**
* ***sequence**: any variable amount of expressions. All expressions inside of `sequence` will be composed together using `phi.dsl.Expression.Seq`.
* ****kwargs**: ... |
def drawQuad(page, quad, color=None, fill=None, dashes=None,
width=1, roundCap=False, morph=None, overlay=True):
"""Draw a quadrilateral.
"""
img = page.newShape()
Q = img.drawQuad(Quad(quad))
img.finish(color=color, fill=fill, dashes=dashes, width=width,
roundCap=rou... | Draw a quadrilateral. |
def login_oauth2_user(valid, oauth):
"""Log in a user after having been verified."""
if valid:
oauth.user.login_via_oauth2 = True
_request_ctx_stack.top.user = oauth.user
identity_changed.send(current_app._get_current_object(),
identity=Identity(oauth.user.i... | Log in a user after having been verified. |
def fragments_fromstring(html, no_leading_text=False, base_url=None,
parser=None, **kw):
"""
Parses several HTML elements, returning a list of elements.
The first item in the list may be a string (though leading
whitespace is removed). If no_leading_text is true, then it will
... | Parses several HTML elements, returning a list of elements.
The first item in the list may be a string (though leading
whitespace is removed). If no_leading_text is true, then it will
be an error if there is leading text, and it will always be a list
of only elements.
base_url will set the docume... |
def save(markov, fname, args):
"""Save a generator.
Parameters
----------
markov : `markovchain.Markov`
Generator to save.
fname : `str`
Output file path.
args : `argparse.Namespace`
Command arguments.
"""
if isinstance(markov.storage, JsonStorage):
if fn... | Save a generator.
Parameters
----------
markov : `markovchain.Markov`
Generator to save.
fname : `str`
Output file path.
args : `argparse.Namespace`
Command arguments. |
def make_non_negative_axis(axis, rank):
"""Make (possibly negatively indexed) `axis` argument non-negative."""
axis = tf.convert_to_tensor(value=axis, name="axis")
rank = tf.convert_to_tensor(value=rank, name="rank")
axis_ = tf.get_static_value(axis)
rank_ = tf.get_static_value(rank)
# Static case.
if ax... | Make (possibly negatively indexed) `axis` argument non-negative. |
def random_string(**kwargs):
"""
By default generates a random string of 10 chars composed
of digits and ascii lowercase letters. String length and pool can
be override by using kwargs. Pool must be a list of strings
"""
n = kwargs.get('length', 10)
pool = kwargs.get('pool') or string.digits... | By default generates a random string of 10 chars composed
of digits and ascii lowercase letters. String length and pool can
be override by using kwargs. Pool must be a list of strings |
def golfclap(rest):
"Clap for something"
clapv = random.choice(phrases.clapvl)
adv = random.choice(phrases.advl)
adj = random.choice(phrases.adjl)
if rest:
clapee = rest.strip()
karma.Karma.store.change(clapee, 1)
return "/me claps %s for %s, %s %s." % (clapv, rest, adv, adj)
return "/me claps %s, %s %s." %... | Clap for something |
def currentRegion(self):
"""
Returns the current region based on the current cursor position.
:return <XDropZoneWidget>
"""
pos = QtGui.QCursor.pos()
pos = self.mapFromGlobal(pos)
for region in self.regions():
if region.testHovere... | Returns the current region based on the current cursor position.
:return <XDropZoneWidget> |
def busco_plot (self, lin):
""" Make the HighCharts HTML for the BUSCO plot for a particular lineage """
data = {}
for s_name in self.busco_data:
if self.busco_data[s_name].get('lineage_dataset') == lin:
data[s_name] = self.busco_data[s_name]
plot_keys = ['c... | Make the HighCharts HTML for the BUSCO plot for a particular lineage |
def get_qemu_version(qemu_path):
"""
Gets the Qemu version.
:param qemu_path: path to Qemu executable.
"""
if sys.platform.startswith("win"):
# Qemu on Windows doesn't return anything with parameter -version
# look for a version number in version.txt fil... | Gets the Qemu version.
:param qemu_path: path to Qemu executable. |
def parse(self):
"""Fully parses game summary report.
:returns: boolean success indicator
:rtype: bool """
r = super(GameSummRep, self).parse()
try:
self.parse_scoring_summary()
return r and False
except:
return False | Fully parses game summary report.
:returns: boolean success indicator
:rtype: bool |
def save(filename=ConfigPath):
"""Saves this module's changed attributes to INI configuration."""
default_values = defaults()
parser = configparser.RawConfigParser()
parser.optionxform = str # Force case-sensitivity on names
try:
save_types = basestring, int, float, tuple, list, dict, ... | Saves this module's changed attributes to INI configuration. |
def __complete_imports_and_aliases(
self, prefix: str, name_in_module: Optional[str] = None
) -> Iterable[str]:
"""Return an iterable of possible completions matching the given
prefix from the list of imports and aliased imports. If name_in_module
is given, further attempt to refine ... | Return an iterable of possible completions matching the given
prefix from the list of imports and aliased imports. If name_in_module
is given, further attempt to refine the list to matching names in that
namespace. |
def _updater_wrapper(updater):
"""A wrapper for the user-defined handle."""
def updater_handle(key, lhs_handle, rhs_handle, _):
""" ctypes function """
lhs = _ndarray_cls(NDArrayHandle(lhs_handle))
rhs = _ndarray_cls(NDArrayHandle(rhs_handle))
updater(key, lhs, rhs)
return up... | A wrapper for the user-defined handle. |
def _locked_refresh_doc_ids(self):
"""Assumes that the caller has the _index_lock !
"""
d = {}
for s in self._shards:
for k in s.doc_index.keys():
if k in d:
raise KeyError('doc "{i}" found in multiple repos'.format(i=k))
d[... | Assumes that the caller has the _index_lock ! |
def display(self,
ret,
indent,
out,
rows_key=None,
labels_key=None):
'''Display table(s).'''
rows = []
labels = None
if isinstance(ret, dict):
if not rows_key or (rows_key and rows_key in list(... | Display table(s). |
def _validate_danglers(self):
"""
Checks for rows that are not referenced in the the tables that should be linked
stops <> stop_times using stop_I
stop_times <> trips <> days, using trip_I
trips <> routes, using route_I
:return:
"""
for query, warning in ... | Checks for rows that are not referenced in the the tables that should be linked
stops <> stop_times using stop_I
stop_times <> trips <> days, using trip_I
trips <> routes, using route_I
:return: |
def get_network(model=None, std=0.005, disable_reinforce=False, random_glimpse=False):
"""
Get baseline model.
Parameters:
model - model path
Returns:
network
"""
network = NeuralClassifier(input_dim=28 * 28)
network.stack_layer(FirstGlimpseLayer(std=std, disable_reinforce=di... | Get baseline model.
Parameters:
model - model path
Returns:
network |
def remove_escapes(self):
"""Removes everything except number and letters from string
:return: All numbers and letters in string
"""
chars = []
i = 0
while i < len(self.string):
char = self.string[i]
if char == "\\":
i += 1
... | Removes everything except number and letters from string
:return: All numbers and letters in string |
def insert(self, context):
"""
Add Vagrant box to the calling user.
:param resort.engine.execution.Context context:
Current execution context.
"""
self.write([
"box",
"add",
"--name", context.resolve(self.__name),
self.__path(context)
]) | Add Vagrant box to the calling user.
:param resort.engine.execution.Context context:
Current execution context. |
def tokenize(text, custom_dict=None):
"""
Tokenize given Thai text string
Input
=====
text: str, Thai text string
custom_dict: str (or list), path to customized dictionary file
It allows the function not to tokenize given dictionary wrongly.
The file should contain custom words ... | Tokenize given Thai text string
Input
=====
text: str, Thai text string
custom_dict: str (or list), path to customized dictionary file
It allows the function not to tokenize given dictionary wrongly.
The file should contain custom words separated by line.
Alternatively, you can ... |
def _divide(divisor, remainder, quotient, remainders, base, precision=None):
"""
Given a divisor and dividend, continue until precision in is reached.
:param int divisor: the divisor
:param int remainder: the remainder
:param int base: the base
:param precision: maximum ... | Given a divisor and dividend, continue until precision in is reached.
:param int divisor: the divisor
:param int remainder: the remainder
:param int base: the base
:param precision: maximum number of fractional digits to compute
:type precision: int or NoneType
:returns... |
def request_access_token(self, code, redirect_uri=None):
'''
Return access token as a JsonDict: {"access_token":"your-access-token","expires":12345678,"uid":1234}, expires is represented using standard unix-epoch-time
'''
redirect = redirect_uri or self._redirect_uri
resp_text = ... | Return access token as a JsonDict: {"access_token":"your-access-token","expires":12345678,"uid":1234}, expires is represented using standard unix-epoch-time |
def synphot(self, wlen, flam):
"""`wlen` and `flam` give a tabulated model spectrum in wavelength and f_λ
units. We interpolate linearly over both the model and the bandpass
since they're both discretely sampled.
Note that quadratic interpolation is both much slower and can blow up
... | `wlen` and `flam` give a tabulated model spectrum in wavelength and f_λ
units. We interpolate linearly over both the model and the bandpass
since they're both discretely sampled.
Note that quadratic interpolation is both much slower and can blow up
fatally in some cases. The latter issu... |
def pyx2obj(pyxpath, objpath=None, interm_c_dir=None, cwd=None,
logger=None, full_module_name=None, only_update=False,
metadir=None, include_numpy=False, include_dirs=None,
cy_kwargs=None, gdb=False, cplus=None, **kwargs):
"""
Convenience function
If cwd is specified, py... | Convenience function
If cwd is specified, pyxpath and dst are taken to be relative
If only_update is set to `True` the modification time is checked
and compilation is only run if the source is newer than the
destination
Parameters
----------
pyxpath: path string
path to Cython sour... |
def format_all(format_string, env):
""" Format the input string using each possible combination of lists
in the provided environment. Returns a list of formated strings.
"""
prepared_env = parse_pattern(format_string, env, lambda x, y: [FormatWrapper(x, z) for z in y])
# Generate each possible ... | Format the input string using each possible combination of lists
in the provided environment. Returns a list of formated strings. |
def get_holiday_label(self, day):
"""Return the label of the holiday, if the date is a holiday"""
day = cleaned_date(day)
return {day: label for day, label in self.holidays(day.year)
}.get(day) | Return the label of the holiday, if the date is a holiday |
def genrows(cursor: Cursor, arraysize: int = 1000) \
-> Generator[List[Any], None, None]:
"""
Generate all rows from a cursor.
Args:
cursor: the cursor
arraysize: split fetches into chunks of this many records
Yields:
each row
"""
# http://code.activestate.com/r... | Generate all rows from a cursor.
Args:
cursor: the cursor
arraysize: split fetches into chunks of this many records
Yields:
each row |
def create_dataclass_loader(cls, registry, field_getters):
"""create a loader for a dataclass type"""
fields = cls.__dataclass_fields__
item_loaders = map(registry, map(attrgetter('type'), fields.values()))
getters = map(field_getters.__getitem__, fields)
loaders = list(starmap(compose, zip(item_loa... | create a loader for a dataclass type |
def set_log_format(self, log_type, log_format):
'''Configures log format
Arguments:
log_type (:obj:`str`): log type (error, debug or stream)
log_format (:obj:`str`): log format (ex:"Log: %(message)s | Log level:%(levelname)s |
Date:%(asctime)s',datefmt='%m/%d/%Y ... | Configures log format
Arguments:
log_type (:obj:`str`): log type (error, debug or stream)
log_format (:obj:`str`): log format (ex:"Log: %(message)s | Log level:%(levelname)s |
Date:%(asctime)s',datefmt='%m/%d/%Y %I:%M:%S") |
def get_type_len(self):
"""Retrieve the type and length for a data record."""
# Check types and set type/len
self.get_sql()
return self.type, self.len, self.len_decimal | Retrieve the type and length for a data record. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.