code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def main(argv=None):
"""Entry point for the `simpl` command."""
#
# `simpl server`
#
logging.basicConfig(level=logging.INFO)
server_func = functools.partial(server.main, argv=argv)
server_parser = server.attach_parser(default_subparser())
server_parser.set_defaults(_func=server_func)
... | Entry point for the `simpl` command. |
def _patch_prebuild(cls):
"""Patch a setuptools command to depend on `prebuild`"""
orig_run = cls.run
def new_run(self):
self.run_command("prebuild")
orig_run(self)
cls.run = new_run | Patch a setuptools command to depend on `prebuild` |
def _dcm_to_q(self, dcm):
"""
Create q from dcm
Reference:
- Shoemake, Quaternions,
http://www.cs.ucr.edu/~vbz/resources/quatut.pdf
:param dcm: 3x3 dcm array
returns: quaternion array
"""
assert(dcm.shape == (3, 3))
q = np.zeros(4)... | Create q from dcm
Reference:
- Shoemake, Quaternions,
http://www.cs.ucr.edu/~vbz/resources/quatut.pdf
:param dcm: 3x3 dcm array
returns: quaternion array |
def error(message, *args, **kwargs):
"""
write a message to stderr
"""
if 'end' in kwargs:
end = kwargs['end']
else:
end = '\n'
if len(args) == 0:
sys.stderr.write(message)
else:
sys.stderr.write(message % args)
sys.stderr.write(end)
sys.stderr.flush... | write a message to stderr |
def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the encoding of the LongInteger from the input stream.
Args:
istream (stream): A buffer containing the encoded bytes of a
LongInteger. Usually a BytearrayStream object. Required.
k... | Read the encoding of the LongInteger from the input stream.
Args:
istream (stream): A buffer containing the encoded bytes of a
LongInteger. Usually a BytearrayStream object. Required.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version wi... |
def do_repl(self):
"""REPL for rTorrent XMLRPC commands."""
from prompt_toolkit import prompt
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.contrib.completers import WordCompleter
self.op... | REPL for rTorrent XMLRPC commands. |
def add_virtual_columns_proper_motion_gal2eq(self, long_in="ra", lat_in="dec", pm_long="pm_l", pm_lat="pm_b", pm_long_out="pm_ra", pm_lat_out="pm_dec",
name_prefix="__proper_motion_gal2eq",
right_ascension_galactic_pole=192.85,
... | Transform/rotate proper motions from galactic to equatorial coordinates.
Inverse of :py:`add_virtual_columns_proper_motion_eq2gal` |
def run_cli(
executable,
mets_url=None,
resolver=None,
workspace=None,
page_id=None,
log_level=None,
input_file_grp=None,
output_file_grp=None,
parameter=None,
working_dir=None,
):
"""
Create a workspace for mets_url and run MP CLI ... | Create a workspace for mets_url and run MP CLI through it |
def transformByDistance(wV, subModel, alphabetSize=4):
"""
transform wV by given substitution matrix
"""
nc = [0.0]*alphabetSize
for i in xrange(0, alphabetSize):
j = wV[i]
k = subModel[i]
for l in xrange(0, alphabetSize):
nc[l] += j * k[l]
return nc | transform wV by given substitution matrix |
def array_to_image(
arr, mask=None, img_format="png", color_map=None, **creation_options
):
"""
Translate numpy ndarray to image buffer using GDAL.
Usage
-----
tile, mask = rio_tiler.utils.tile_read(......)
with open('test.jpg', 'wb') as f:
f.write(array_to_image(tile, mask, img_for... | Translate numpy ndarray to image buffer using GDAL.
Usage
-----
tile, mask = rio_tiler.utils.tile_read(......)
with open('test.jpg', 'wb') as f:
f.write(array_to_image(tile, mask, img_format="jpeg"))
Attributes
----------
arr : numpy ndarray
Image array to encode.
mask:... |
def _Import(self, t):
""" Handle "import xyz.foo".
"""
self._fill("import ")
for i, (name,asname) in enumerate(t.names):
if i != 0:
self._write(", ")
self._write(name)
if asname is not None:
self._write(" as "+a... | Handle "import xyz.foo". |
def stop_apppool(name):
'''
Stop an IIS application pool.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the App Pool to stop.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.stop_apppool name='MyTe... | Stop an IIS application pool.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the App Pool to stop.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.stop_apppool name='MyTestPool' |
def register(cls, associations, backend, style_aliases={}):
"""
Register the supplied dictionary of associations between
elements and plotting classes to the specified backend.
"""
if backend not in cls.registry:
cls.registry[backend] = {}
cls.registry[backend... | Register the supplied dictionary of associations between
elements and plotting classes to the specified backend. |
def spev(t_int, C, deg, x, cov_C=None, M_spline=False, I_spline=False, n=0):
"""Evaluate a B-, M- or I-spline with the specified internal knots, order and coefficients.
`deg` boundary knots are appended at both sides of the domain.
The zeroth order basis functions are modified to ensure continuity... | Evaluate a B-, M- or I-spline with the specified internal knots, order and coefficients.
`deg` boundary knots are appended at both sides of the domain.
The zeroth order basis functions are modified to ensure continuity at the
right-hand boundary.
Note that the I-splines include the :math:... |
def _find_lib_path():
"""Find mxnet library."""
curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
amalgamation_lib_path = os.path.join(curr_path, '../../lib/libmxnet_predict.so')
if os.path.exists(amalgamation_lib_path) and os.path.isfile(amalgamation_lib_path):
lib_path... | Find mxnet library. |
def _fromiter(it, dtype, count, progress, log):
"""Utility function to load an array from an iterator."""
if progress > 0:
it = _iter_withprogress(it, progress, log)
if count is not None:
a = np.fromiter(it, dtype=dtype, count=count)
else:
a = np.fromiter(it, dtype=dtype)
ret... | Utility function to load an array from an iterator. |
def enrich_sentences_with_NLP(self, all_sentences):
"""
Enrich a list of fonduer Sentence objects with NLP features. We merge
and process the text of all Sentences for higher efficiency.
:param all_sentences: List of fonduer Sentence objects for one document
:return:
"""... | Enrich a list of fonduer Sentence objects with NLP features. We merge
and process the text of all Sentences for higher efficiency.
:param all_sentences: List of fonduer Sentence objects for one document
:return: |
def emit(
self,
record):
"""emit
Emit handler for queue-ing message for
the helper thread to send to Splunk on the ``self.sleep_interval``
:param record: LogRecord to send to Splunk
https://docs.python.org/3/library/logging.html
""... | emit
Emit handler for queue-ing message for
the helper thread to send to Splunk on the ``self.sleep_interval``
:param record: LogRecord to send to Splunk
https://docs.python.org/3/library/logging.html |
def preprocessFastqs(fastqFNs, seqFNPrefix, offsetFN, abtFN, areUniform, logger):
'''
This function does the grunt work behind string extraction for fastq files
@param fastqFNs - a list of .fq filenames for parsing
@param seqFNPrefix - this is always of the form '<DIR>/seqs.npy'
@param offsetFN - th... | This function does the grunt work behind string extraction for fastq files
@param fastqFNs - a list of .fq filenames for parsing
@param seqFNPrefix - this is always of the form '<DIR>/seqs.npy'
@param offsetFN - this is always of the form '<DIR>/offsets.npy'
@param abtFN - this is always of the form '<D... |
def parse_url(url):
"""Parse a Elk connection string """
scheme, dest = url.split('://')
host = None
ssl_context = None
if scheme == 'elk':
host, port = dest.split(':') if ':' in dest else (dest, 2101)
elif scheme == 'elks':
host, port = dest.split(':') if ':' in dest else (dest,... | Parse a Elk connection string |
def site_url(self, url):
"""URL setter and validator for site_url property.
Parameters:
url (str): URL of on Moebooru/Danbooru based sites.
Raises:
PybooruError: When URL scheme or URL are invalid.
"""
# Regular expression to URL validate
regex =... | URL setter and validator for site_url property.
Parameters:
url (str): URL of on Moebooru/Danbooru based sites.
Raises:
PybooruError: When URL scheme or URL are invalid. |
def get_version(extension, workflow_file):
'''Determines the version of a .py, .wdl, or .cwl file.'''
if extension == 'py' and two_seven_compatible(workflow_file):
return '2.7'
elif extension == 'cwl':
return yaml.load(open(workflow_file))['cwlVersion']
else: # Must be a wdl file.
... | Determines the version of a .py, .wdl, or .cwl file. |
def main():
"""main."""
config = context.config
config.set_main_option("sqlalchemy.url", config.get_main_option('url'))
run_migrations_online(config) | main. |
def fetch_ticker(self) -> Ticker:
"""Fetch the market ticker."""
return self._fetch('ticker', self.market.code)(self._ticker)() | Fetch the market ticker. |
def expand_to_one_hot(data,expand = True,use_alternative=False):
header_dict = {'ALCABUS':0,'PRIRCAT':1,'TMSRVC':2,'SEX1':3,'RACE':4,'RELTYP':5,'age_1st_arrest':6,'DRUGAB':7,'Class':8,'RLAGE':9,'NFRCTNS':10}
new_data = []
for entry in data:
temp = {}
if expand == True:
if entry[header_dict["SEX1"]] ... | with open("brandon_testing/test_"+str(time.clock())+".csv","w") as f:
writer = csv.writer(f,delimiter=",")
for row in fin:
writer.writerow(row) |
def create_game(
self,
map_name,
bot_difficulty=sc_pb.VeryEasy,
bot_race=sc_common.Random,
bot_first=False):
"""Create a game, one remote agent vs the specified bot.
Args:
map_name: The map to use.
bot_difficulty: The difficulty of the bot to play against.
bot_ra... | Create a game, one remote agent vs the specified bot.
Args:
map_name: The map to use.
bot_difficulty: The difficulty of the bot to play against.
bot_race: The race for the bot.
bot_first: Whether the bot should be player 1 (else is player 2). |
def dict_copy(func):
"copy dict args, to avoid modifying caller's copy"
def proxy(*args, **kwargs):
new_args = []
new_kwargs = {}
for var in kwargs:
if isinstance(kwargs[var], dict):
new_kwargs[var] = dict(kwargs[var])
else:
new_kwa... | copy dict args, to avoid modifying caller's copy |
def get_json_result(results, n=10):
"""Return the top `n` results as a JSON list.
>>> results = [{'probability': 0.65,
... 'whatever': 'bar'},
... {'probability': 0.21,
... 'whatever': 'bar'},
... {'probability': 0.05,
... 'whatever':... | Return the top `n` results as a JSON list.
>>> results = [{'probability': 0.65,
... 'whatever': 'bar'},
... {'probability': 0.21,
... 'whatever': 'bar'},
... {'probability': 0.05,
... 'whatever': 'bar'},]
>>> get_json_result(results, ... |
async def readline(self) -> bytes:
"""
Reads one line
>>> # Keeps waiting for a linefeed incase there is none in the buffer
>>> await test.readline()
:returns: bytes forming a line
"""
while True:
line = self._serial_instance.readline()
i... | Reads one line
>>> # Keeps waiting for a linefeed incase there is none in the buffer
>>> await test.readline()
:returns: bytes forming a line |
def _normalize_tabular_data(tabular_data, headers):
"""Transform a supported data type to a list of lists, and a list of headers.
Supported tabular data types:
* list-of-lists or another iterable of iterables
* list of named tuples (usually used with headers="keys")
* 2D NumPy arrays
* NumP... | Transform a supported data type to a list of lists, and a list of headers.
Supported tabular data types:
* list-of-lists or another iterable of iterables
* list of named tuples (usually used with headers="keys")
* 2D NumPy arrays
* NumPy record arrays (usually used with headers="keys")
* d... |
def set_frequency(self, host, sem=None, interval=None):
"""Set frequency for host with sem and interval."""
# single sem or global sem
sem = sem or self.sem
interval = self.interval if interval is None else interval
frequency = Frequency(sem, interval, host)
frequencies =... | Set frequency for host with sem and interval. |
def unblock_pin(ctx, puk, new_pin):
"""
Unblock the PIN.
Reset the PIN using the PUK code.
"""
controller = ctx.obj['controller']
if not puk:
puk = click.prompt(
'Enter PUK', default='', show_default=False,
hide_input=True, err=True)
if not new_pin:
n... | Unblock the PIN.
Reset the PIN using the PUK code. |
def __get_html(self, body=None):
"""
Returns the html content with given body tag content.
:param body: Body tag content.
:type body: unicode
:return: Html.
:rtype: unicode
"""
output = []
output.append("<html>")
output.append("<head>")
... | Returns the html content with given body tag content.
:param body: Body tag content.
:type body: unicode
:return: Html.
:rtype: unicode |
def commitAndCloseEditor(self):
"""Commit and close editor"""
editor = self.sender()
# Avoid a segfault with PyQt5. Variable value won't be changed
# but at least Spyder won't crash. It seems generated by a bug in sip.
try:
self.commitData.emit(editor)
... | Commit and close editor |
def _dictlist_to_lists(dl, *keys):
''' convert a list of dictionaries to a dictionary of lists
>>> dl = [{'a': 'test', 'b': 3}, {'a': 'zaz', 'b': 444},
{'a': 'wow', 'b': 300}]
>>> _dictlist_to_lists(dl)
(['test', 'zaz', 'wow'], [3, 444, 300])
'''
lists = []
for k in keys:
... | convert a list of dictionaries to a dictionary of lists
>>> dl = [{'a': 'test', 'b': 3}, {'a': 'zaz', 'b': 444},
{'a': 'wow', 'b': 300}]
>>> _dictlist_to_lists(dl)
(['test', 'zaz', 'wow'], [3, 444, 300]) |
def union_overlapping(intervals):
"""Union any overlapping intervals in the given set."""
disjoint_intervals = []
for interval in intervals:
if disjoint_intervals and disjoint_intervals[-1].overlaps(interval):
disjoint_intervals[-1] = disjoint_intervals[-1].union(interval)
else:... | Union any overlapping intervals in the given set. |
def tqdm(self, desc, total, leave, initial=0):
"""
Extension point. Override to provide custom options to tqdm_notebook initializer.
:param desc: Description string
:param total: Total number of updates
:param leave: Leave progress bar when done
:return: new progress bar
... | Extension point. Override to provide custom options to tqdm_notebook initializer.
:param desc: Description string
:param total: Total number of updates
:param leave: Leave progress bar when done
:return: new progress bar
:param initial: Initial counter state |
def _variable_inputs(self, op):
""" Return which inputs of this operation are variable (i.e. depend on the model inputs).
"""
if op.name not in self._vinputs:
self._vinputs[op.name] = np.array([t.op in self.between_ops or t in self.model_inputs for t in op.inputs])
return sel... | Return which inputs of this operation are variable (i.e. depend on the model inputs). |
def move(self, x, y):
"""
Move the drawing cursor to the specified position.
:param x: The column (x coord) for the location to check.
:param y: The line (y coord) for the location to check.
"""
self._x = int(round(x * 2, 0))
self._y = int(round(y * 2, 0)) | Move the drawing cursor to the specified position.
:param x: The column (x coord) for the location to check.
:param y: The line (y coord) for the location to check. |
def prepare_inventory(self):
"""
Prepares the inventory default under ``private_data_dir`` if it's not overridden by the constructor.
"""
if self.inventory is None:
self.inventory = os.path.join(self.private_data_dir, "inventory") | Prepares the inventory default under ``private_data_dir`` if it's not overridden by the constructor. |
def _get_game_number(cls, gid_path):
"""
Game Number
:param gid_path: game logs directory path
:return: game number(int)
"""
game_number = str(gid_path[len(gid_path)-2:len(gid_path)-1])
if game_number.isdigit():
return int(game_number)
else:
... | Game Number
:param gid_path: game logs directory path
:return: game number(int) |
def get_context(request, context=None):
"""Returns common context data for network topology views."""
if context is None:
context = {}
network_config = getattr(settings, 'OPENSTACK_NEUTRON_NETWORK', {})
context['launch_instance_allowed'] = policy.check(
(("compute", "os_compute_api:ser... | Returns common context data for network topology views. |
def shutdown(self):
"""close socket, immediately."""
if self.sock:
self.sock.close()
self.sock = None
self.connected = False | close socket, immediately. |
def get_writer_factory_for(self, name, *, format=None):
"""
Returns a callable to build a writer for the provided filename, eventually forcing a format.
:param name: filename
:param format: format
:return: type
"""
return self.get_factory_for(WRITER, name, format... | Returns a callable to build a writer for the provided filename, eventually forcing a format.
:param name: filename
:param format: format
:return: type |
def pvpc_procesa_datos_dia(_, response, verbose=True):
"""Procesa la información JSON descargada y forma el dataframe de los datos de un día."""
try:
d_data = response['PVPC']
df = _process_json_pvpc_hourly_data(pd.DataFrame(d_data))
return df, 0
except Exception as e:
if ver... | Procesa la información JSON descargada y forma el dataframe de los datos de un día. |
def dumpLines(self):
"""
For debugging dump all line and their content
"""
for i, line in enumerate(self.lines):
logger.debug("Line %d:", i)
logger.debug(line.dumpFragments()) | For debugging dump all line and their content |
def check_exists(self):
'''
Check if resource exists, update self.exists, returns
Returns:
None: sets self.exists
'''
response = self.repo.api.http_request('HEAD', self.uri)
self.status_code = response.status_code
# resource exists
if self.status_code == 200:
self.exists = True
# resource no ... | Check if resource exists, update self.exists, returns
Returns:
None: sets self.exists |
def acknowledge_time(self):
"""
Processor time when the alarm was acknowledged.
:type: :class:`~datetime.datetime`
"""
if (self.is_acknowledged and
self._proto.acknowledgeInfo.HasField('acknowledgeTime')):
return parse_isostring(self._proto.acknowledg... | Processor time when the alarm was acknowledged.
:type: :class:`~datetime.datetime` |
def long_click(self, duration=2.0):
"""
Perform the long click action on the UI element(s) represented by the UI proxy. If this UI proxy represents a
set of UI elements, the first one in the set is clicked and the anchor point of the UI element is used as the
default one. Similar to cl... | Perform the long click action on the UI element(s) represented by the UI proxy. If this UI proxy represents a
set of UI elements, the first one in the set is clicked and the anchor point of the UI element is used as the
default one. Similar to click but press the screen for the given time interval and... |
def quantize_weights(full_precision_model,
nbits,
quantization_mode="linear",
sample_data=None,
**kwargs):
"""
Utility function to convert a full precision (float) MLModel to a
nbit quantized MLModel (float16).
:param f... | Utility function to convert a full precision (float) MLModel to a
nbit quantized MLModel (float16).
:param full_precision_model: MLModel
Model which will be converted to half precision. Currently conversion
for only neural network models is supported. If a pipeline model is
passed in th... |
def exclude_matches(self, matches):
"""Filter any matches that match an exclude pattern.
:param matches: a list of possible completions
"""
for match in matches:
for exclude_pattern in self.exclude_patterns:
if re.match(exclude_pattern, match) is not None:
... | Filter any matches that match an exclude pattern.
:param matches: a list of possible completions |
def max(self):
"""Maximum, ignorning nans."""
if "max" not in self.attrs.keys():
def f(dataset, s):
return np.nanmax(dataset[s])
self.attrs["max"] = np.nanmax(list(self.chunkwise(f).values()))
return self.attrs["max"] | Maximum, ignorning nans. |
def sample(self, size=1):
""" Sample rigid transform random variables.
Parameters
----------
size : int
number of sample to take
Returns
-------
:obj:`list` of :obj:`RigidTransform`
sampled rigid transformations
"""
... | Sample rigid transform random variables.
Parameters
----------
size : int
number of sample to take
Returns
-------
:obj:`list` of :obj:`RigidTransform`
sampled rigid transformations |
def subalignment(alnfle, subtype, alntype="fasta"):
"""
Subset synonymous or fourfold degenerate sites from an alignment
input should be a codon alignment
"""
aln = AlignIO.read(alnfle, alntype)
alnlen = aln.get_alignment_length()
nseq = len(aln)
subaln = None
subalnfile = alnfle.rs... | Subset synonymous or fourfold degenerate sites from an alignment
input should be a codon alignment |
def _get_unit_factor(cls, unit):
"""
Returns the unit factor depending on the unit constant
:param int unit: the unit of the factor requested
:returns: a function to convert the raw sensor value to the given unit
:rtype: lambda function
:raises Unsu... | Returns the unit factor depending on the unit constant
:param int unit: the unit of the factor requested
:returns: a function to convert the raw sensor value to the given unit
:rtype: lambda function
:raises UnsupportedUnitError: if the unit is not supported |
def certificate_issuer_id(self, certificate_issuer_id):
"""
Sets the certificate_issuer_id of this CreateCertificateIssuerConfig.
The ID of the certificate issuer.
:param certificate_issuer_id: The certificate_issuer_id of this CreateCertificateIssuerConfig.
:type: str
... | Sets the certificate_issuer_id of this CreateCertificateIssuerConfig.
The ID of the certificate issuer.
:param certificate_issuer_id: The certificate_issuer_id of this CreateCertificateIssuerConfig.
:type: str |
def count_replica(self, partition):
"""Return count of replicas of given partition."""
return sum(1 for b in partition.replicas if b in self.brokers) | Return count of replicas of given partition. |
def frac_vol_floc_initial(ConcAluminum, ConcClay, coag, material):
"""Return the volume fraction of flocs initially present, accounting for both suspended particles and coagulant precipitates.
:param ConcAluminum: Concentration of aluminum in solution
:type ConcAluminum: float
:param ConcClay: Concentr... | Return the volume fraction of flocs initially present, accounting for both suspended particles and coagulant precipitates.
:param ConcAluminum: Concentration of aluminum in solution
:type ConcAluminum: float
:param ConcClay: Concentration of particle in suspension
:type ConcClay: float
:param coag:... |
def _wrap_result(self, func):
""" Wrap result in Parser instance """
def wrapper(*args):
result = func(*args)
if hasattr(result, '__iter__') and not isinstance(result, etree._Element):
return [self._wrap_element(element) for element in result]
else:
... | Wrap result in Parser instance |
def has_length(self, value, q, strict=False):
"""if value has a length of q"""
value = stringify(value)
if value is not None:
if len(value) == q:
return
self.shout('Value %r not matching length %r', strict, value, q) | if value has a length of q |
def _parse_keys(row, line_num):
""" Perform some sanity checks on they keys
Each key in the row should not be named None cause
(that's an overrun). A key named `type` MUST be
present on the row & have a string value.
:param row: dict
:param line_num: int
"""
... | Perform some sanity checks on they keys
Each key in the row should not be named None cause
(that's an overrun). A key named `type` MUST be
present on the row & have a string value.
:param row: dict
:param line_num: int |
def add_post_process(self, name, post_process, description=""):
"""add a post-process
Parameters
----------
name : str
name of the post-traitment
post_process : callback (function of a class with a __call__ method
or a streamz.Stream)... | add a post-process
Parameters
----------
name : str
name of the post-traitment
post_process : callback (function of a class with a __call__ method
or a streamz.Stream).
this callback have to accept the simulation state as paramete... |
def group_get(auth=None, **kwargs):
'''
Get a single group
CLI Example:
.. code-block:: bash
salt '*' keystoneng.group_get name=group1
salt '*' keystoneng.group_get name=group2 domain_id=b62e76fbeeff4e8fb77073f591cf211e
salt '*' keystoneng.group_get name=0e4febc2a5ab4f2c8f374b... | Get a single group
CLI Example:
.. code-block:: bash
salt '*' keystoneng.group_get name=group1
salt '*' keystoneng.group_get name=group2 domain_id=b62e76fbeeff4e8fb77073f591cf211e
salt '*' keystoneng.group_get name=0e4febc2a5ab4f2c8f374b054162506d |
def __add_flag (rule_or_module, variable_name, condition, values):
""" Adds a new flag setting with the specified values.
Does no checking.
"""
assert isinstance(rule_or_module, basestring)
assert isinstance(variable_name, basestring)
assert is_iterable_typed(condition, property_set.Property... | Adds a new flag setting with the specified values.
Does no checking. |
def do_down(self, arg):
"""d(own) [count]
Move the current frame count (default one) levels down in the
stack trace (to a newer frame).
"""
if self.curindex + 1 == len(self.stack):
self.error('Newest frame')
return
try:
count = int(arg ... | d(own) [count]
Move the current frame count (default one) levels down in the
stack trace (to a newer frame). |
def FromBinary(cls, record_data, record_count=1):
"""Create an UpdateRecord subclass from binary record data.
This should be called with a binary record blob (NOT including the
record type header) and it will decode it into a ReflashTileRecord.
Args:
record_data (bytearray)... | Create an UpdateRecord subclass from binary record data.
This should be called with a binary record blob (NOT including the
record type header) and it will decode it into a ReflashTileRecord.
Args:
record_data (bytearray): The raw record data that we wish to parse
i... |
def check_bearer_validity(self, token: dict, connect_mtd) -> dict:
"""Check API Bearer token validity.
Isogeo ID delivers authentication bearers which are valid during
a certain time. So this method checks the validity of the token
with a 30 mn anticipation limit, and renews it if neces... | Check API Bearer token validity.
Isogeo ID delivers authentication bearers which are valid during
a certain time. So this method checks the validity of the token
with a 30 mn anticipation limit, and renews it if necessary.
See: http://tools.ietf.org/html/rfc6750#section-2
FI: 2... |
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailin... | Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block. |
def is_usable(host, port, timeout=3):
"""测试代理是否可用
params
----------
host ip地址
port 端口号
timeout 默认值为3,通过设置这个参数可以过滤掉一些速度慢的代理
example
----------
is_usable('222.180.24.13', '808', timeout=3)
"""
try:
proxies = {
'http': 'http://%s:%s' % (h... | 测试代理是否可用
params
----------
host ip地址
port 端口号
timeout 默认值为3,通过设置这个参数可以过滤掉一些速度慢的代理
example
----------
is_usable('222.180.24.13', '808', timeout=3) |
def dollars_to_cents(s, allow_negative=False):
"""
Given a string or integer representing dollars, return an integer of
equivalent cents, in an input-resilient way.
This works by stripping any non-numeric characters before attempting to
cast the value.
Examples::
>>> dollars_to_ce... | Given a string or integer representing dollars, return an integer of
equivalent cents, in an input-resilient way.
This works by stripping any non-numeric characters before attempting to
cast the value.
Examples::
>>> dollars_to_cents('$1')
100
>>> dollars_to_cents('1')
... |
def get_credits_by_section_and_regid(section, regid):
"""
Returns a uw_sws.models.Registration object
for the section and regid passed in.
"""
deprecation("Use get_credits_by_reg_url")
# note trailing comma in URL, it's required for the optional dup_code param
url = "{}{},{},{},{},{},{},.jso... | Returns a uw_sws.models.Registration object
for the section and regid passed in. |
def access_func(self, id_, lineno, scope=None, default_type=None):
"""
Since ZX BASIC allows access to undeclared functions, we must allow
and *implicitly* declare them if they are not declared already.
This function just checks if the id_ exists and returns its entry if so.
Othe... | Since ZX BASIC allows access to undeclared functions, we must allow
and *implicitly* declare them if they are not declared already.
This function just checks if the id_ exists and returns its entry if so.
Otherwise, creates an implicit declared variable entry and returns it. |
def append(self, cert):
"""
Appends a cert to the path. This should be a cert issued by the last
cert in the path.
:param cert:
An asn1crypto.x509.Certificate object
:return:
The current ValidationPath object, for chaining
"""
if not isi... | Appends a cert to the path. This should be a cert issued by the last
cert in the path.
:param cert:
An asn1crypto.x509.Certificate object
:return:
The current ValidationPath object, for chaining |
def process_user_input(self):
"""
Gets the next single character and decides what to do with it
"""
user_input = self.get_input()
try:
num = int(user_input)
except Exception:
return
if 0 < num < len(self.items) + 1:
self.curren... | Gets the next single character and decides what to do with it |
def truncate(text, length=50, ellipsis='...'):
"""
Returns a truncated version of the inputted text.
:param text | <str>
length | <int>
ellipsis | <str>
:return <str>
"""
text = nativestring(text)
return text[:length] + (text[length:] and ellipsis) | Returns a truncated version of the inputted text.
:param text | <str>
length | <int>
ellipsis | <str>
:return <str> |
def minimum_pitch(self):
""" Returns the minimal pitch between two neighboring nodes of the mesh in each direction.
:return: Minimal pitch in each direction.
"""
pitch = self.pitch
minimal_pitch = []
for p in pitch:
minimal_pitch.append(min(p))
retu... | Returns the minimal pitch between two neighboring nodes of the mesh in each direction.
:return: Minimal pitch in each direction. |
def date_time(self, tzinfo=None, end_datetime=None):
"""
Get a datetime object for a date between January 1, 1970 and now
:param tzinfo: timezone, instance of datetime.tzinfo subclass
:example DateTime('2005-08-16 20:39:21')
:return datetime
"""
# NOTE: On windows... | Get a datetime object for a date between January 1, 1970 and now
:param tzinfo: timezone, instance of datetime.tzinfo subclass
:example DateTime('2005-08-16 20:39:21')
:return datetime |
def advance(self, length):
"""Advance the cursor in data buffer 'length' bytes."""
new_position = self._position + length
if new_position < 0 or new_position > len(self._data):
raise Exception('Invalid advance amount (%s) for cursor. '
'Position=%s' % (le... | Advance the cursor in data buffer 'length' bytes. |
def send_command_return_multilines(self, obj, command, *arguments):
""" Send command and wait for multiple lines output. """
index_command = obj._build_index_command(command, *arguments)
return self.chassis_list[obj.chassis].sendQuery(index_command, True) | Send command and wait for multiple lines output. |
def run_symmetrized_readout(self, program: Program, trials: int) -> np.ndarray:
"""
Run a quil program in such a way that the readout error is made collectively symmetric
This means the probability of a bitstring ``b`` being mistaken for a bitstring ``c`` is
the same as the probability ... | Run a quil program in such a way that the readout error is made collectively symmetric
This means the probability of a bitstring ``b`` being mistaken for a bitstring ``c`` is
the same as the probability of ``not(b)`` being mistaken for ``not(c)``
A more general symmetrization would guarantee t... |
def extract_ranges(index_list, range_size_limit=32):
"""Extract consecutive ranges and singles from index_list.
Args:
index_list: List of monotone increasing non-negative integers.
range_size_limit: Largest size range to return. If a larger
consecutive range exists it will be returned as multiple
... | Extract consecutive ranges and singles from index_list.
Args:
index_list: List of monotone increasing non-negative integers.
range_size_limit: Largest size range to return. If a larger
consecutive range exists it will be returned as multiple
ranges.
Returns:
ranges, singles where ranges is... |
def arrow_(self, xloc, yloc, text, orientation="v", arrowstyle='->'):
"""
Returns an arrow for a chart. Params: the text, xloc and yloc are
coordinates to position the arrow. Orientation is the way to display
the arrow: possible values are ``[<, ^, >, v]``. Arrow style is the
graphic style of the arrow:
po... | Returns an arrow for a chart. Params: the text, xloc and yloc are
coordinates to position the arrow. Orientation is the way to display
the arrow: possible values are ``[<, ^, >, v]``. Arrow style is the
graphic style of the arrow:
possible values: ``[-, ->, -[, -|>, <->, <|-|>]`` |
def delete(self, loc):
"""
Delete given loc(-s) from block in-place.
"""
self.values = np.delete(self.values, loc, 0)
self.mgr_locs = self.mgr_locs.delete(loc) | Delete given loc(-s) from block in-place. |
def create_audio_mp3_profile(apps, schema_editor):
""" Create audio_mp3 profile """
Profile = apps.get_model('edxval', 'Profile')
Profile.objects.get_or_create(profile_name=AUDIO_MP3_PROFILE) | Create audio_mp3 profile |
def _make_association(self, clk=None, rst=None) -> None:
"""
Associate this object with specified clk/rst
"""
if clk is not None:
assert self._associatedClk is None
self._associatedClk = clk
if rst is not None:
assert self._associatedRst is No... | Associate this object with specified clk/rst |
def _write(self, data):
"""
Writes string data out to Scratch
"""
total_sent = 0
length = len(data)
while total_sent < length:
try:
sent = self.socket.send(data[total_sent:])
except socket.error as (err, msg):
self.c... | Writes string data out to Scratch |
def update(cls, cluster_id_label, cluster_info):
"""
Update the cluster with id/label `cluster_id_label` using information provided in
`cluster_info`.
"""
conn = Qubole.agent(version="v2")
return conn.put(cls.element_path(cluster_id_label), data=cluster_info) | Update the cluster with id/label `cluster_id_label` using information provided in
`cluster_info`. |
def get_path_matching(name):
"""Get path matching a name.
Parameters
----------
name : string
Name to search for.
Returns
-------
string
Full filepath.
"""
# first try looking in the user folder
p = os.path.join(os.path.expanduser("~"), name)
# then try expa... | Get path matching a name.
Parameters
----------
name : string
Name to search for.
Returns
-------
string
Full filepath. |
def _pypi_head_package(dependency):
"""Hit pypi with a http HEAD to check if pkg_name exists."""
if dependency.specs:
_, version = dependency.specs[0]
url = BASE_PYPI_URL_WITH_VERSION.format(name=dependency.project_name, version=version)
else:
url = BASE_PYPI_URL.format(name=dependen... | Hit pypi with a http HEAD to check if pkg_name exists. |
def download(self, path, file):
"""Download remote file to disk."""
resp = self._sendRequest("GET", path)
if resp.status_code == 200:
with open(file, "wb") as f:
f.write(resp.content)
else:
raise YaDiskException(resp.status_code, resp.content) | Download remote file to disk. |
def _build_index(self):
"""Itera todos los datasets, distribucioens y fields indexandolos."""
datasets_index = {}
distributions_index = {}
fields_index = {}
# recorre todos los datasets
for dataset_index, dataset in enumerate(self.datasets):
if "identifier" ... | Itera todos los datasets, distribucioens y fields indexandolos. |
def get_ajax(self, request, *args, **kwargs):
""" Called when accessed via AJAX on the request method specified by the Datatable. """
response_data = self.get_json_response_object(self._datatable)
response = HttpResponse(self.serialize_to_json(response_data),
con... | Called when accessed via AJAX on the request method specified by the Datatable. |
def create_network(self):
"""Create a new network by reading the configuration file."""
class_ = getattr(networks, self.network_class)
return class_(max_size=self.quorum) | Create a new network by reading the configuration file. |
def __r1_hungarian(self, word, vowels, digraphs):
"""
Return the region R1 that is used by the Hungarian stemmer.
If the word begins with a vowel, R1 is defined as the region
after the first consonant or digraph (= two letters stand for
one phoneme) in the word. If the word begi... | Return the region R1 that is used by the Hungarian stemmer.
If the word begins with a vowel, R1 is defined as the region
after the first consonant or digraph (= two letters stand for
one phoneme) in the word. If the word begins with a consonant,
it is defined as the region after the fir... |
def delete(self, photo, **kwds):
"""
Endpoint: /photo/<id>/delete.json
Deletes a photo.
Returns True if successful.
Raises a TroveboxError if not.
"""
return self._client.post("/photo/%s/delete.json" %
self._extract_id(photo),
... | Endpoint: /photo/<id>/delete.json
Deletes a photo.
Returns True if successful.
Raises a TroveboxError if not. |
def extern_project_multi(self, context_handle, val, field_str_ptr, field_str_len):
"""Given a Key for `obj`, and a field name, project the field as a list of Keys."""
c = self._ffi.from_handle(context_handle)
obj = c.from_value(val[0])
field_name = self.to_py_str(field_str_ptr, field_str_len)
retur... | Given a Key for `obj`, and a field name, project the field as a list of Keys. |
def to_excel(self,
workbook=None,
worksheet=None,
xl_app=None,
clear=True,
rename=True,
resize_columns=True):
"""
Writes worksheet to an Excel Worksheet COM object.
Requires :py:module:`pywin32`... | Writes worksheet to an Excel Worksheet COM object.
Requires :py:module:`pywin32` to be installed.
:param workbook: xltable.Workbook this sheet belongs to.
:param worksheet: Excel COM Worksheet instance to write to.
:param xl_app: Excel COM Excel Application to write to.
:param b... |
def content(self):
"""Function returns the body of the as2 payload as a bytes object"""
if not self.payload:
return ''
if self.payload.is_multipart():
message_bytes = mime_to_bytes(
self.payload, 0).replace(b'\n', b'\r\n')
boundary = b'--' + ... | Function returns the body of the as2 payload as a bytes object |
def parse(out):
'''
Extract json from out.
Parameter
out: Type string. The data returned by the
ssh command.
'''
jsonret = []
in_json = False
for ln_ in out.split('\n'):
if '{' in ln_:
in_json = True
if in_json:
jsonret.append(ln_)
... | Extract json from out.
Parameter
out: Type string. The data returned by the
ssh command. |
def filtered_context(context):
"""Filters a context
This will return a new context with only the resources that
are actually available for use. Uses tags and command line
options to make determination."""
ctx = Context(context.opt)
for resource in context.resources():
if resource.child:... | Filters a context
This will return a new context with only the resources that
are actually available for use. Uses tags and command line
options to make determination. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.