text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def clone_repo(self):
"""Clone a repository containing the dotfiles source."""
tempdir_path = tempfile.mkdtemp()
if self.args.git:
self.log.debug('Cloning git source repository from %s to %s',
self.source, tempdir_path)
self.sh('git clone', sel... | 0.004415 |
def update_payload(self, fields=None):
"""Rename ``system_ids`` to ``system_uuids``."""
payload = super(HostCollection, self).update_payload(fields)
if 'system_ids' in payload:
payload['system_uuids'] = payload.pop('system_ids')
return payload | 0.006969 |
def setNodeCount(self, nodeType, numNodes, preemptable=False, force=False):
"""
Attempt to grow or shrink the number of preemptable or non-preemptable worker nodes in
the cluster to the given value, or as close a value as possible, and, after performing
the necessary additions or removal... | 0.008276 |
def wait_for_transfer_job(self, job, expected_statuses=(GcpTransferOperationStatus.SUCCESS,), timeout=60):
"""
Waits until the job reaches the expected state.
:param job: Transfer job
See:
https://cloud.google.com/storage-transfer/docs/reference/rest/v1/transferJobs#Tran... | 0.004918 |
def decode_base64(data: str) -> bytes:
"""Decode base64, padding being optional.
:param data: Base64 data as an ASCII byte string
:returns: The decoded byte string.
"""
missing_padding = len(data) % 4
if missing_padding != 0:
data += "=" * (4 - missing_padding)
return base64.decodeb... | 0.00289 |
def get_job(db, job_id, username=None):
"""
If job_id is negative, return the last calculation of the current
user, otherwise returns the job_id unchanged.
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_id: a job ID (can be negative and can be nonexisting)
:param username: ... | 0.000966 |
def save(self):
"""
Reset the user's password if the provided information is valid.
"""
token = models.PasswordResetToken.objects.get(
key=self.validated_data["key"]
)
token.email.user.set_password(self.validated_data["password"])
token.email.user.sav... | 0.004866 |
def _clean_block(response_dict):
''' Pythonize a blockcypher API response '''
response_dict['received_time'] = parser.parse(response_dict['received_time'])
response_dict['time'] = parser.parse(response_dict['time'])
return response_dict | 0.007905 |
def login(email, password):
"""Login to Todoist.
:param email: A Todoist user's email address.
:type email: str
:param password: A Todoist user's password.
:type password: str
:return: The Todoist user.
:rtype: :class:`pytodoist.todoist.User`
>>> from pytodoist import todoist
>>> u... | 0.001942 |
def ssh_to_task(task) -> paramiko.SSHClient:
"""Create ssh connection to task's machine
returns Paramiko SSH client connected to host.
"""
username = task.ssh_username
hostname = task.public_ip
ssh_key_fn = get_keypair_fn()
print(f"ssh -i {ssh_key_fn} {username}@{hostname}")
pkey = paramiko.RSAKey.fr... | 0.021645 |
def measure_int_put(self, measure, value):
"""associates the measure of type Int with the given value"""
if value < 0:
# Should be an error in a later release.
logger.warning("Cannot record negative values")
self._measurement_map[measure] = value | 0.006803 |
def MoveTo(x: int, y: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
Simulate mouse move to point x, y from current cursor.
x: int.
y: int.
moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move faster.
waitTime: float.
"""
if moveSpeed <= 0:
... | 0.002079 |
def tag_pos_volume(line):
"""Tag POS volume number
POS is journal that has special volume numbers
e.g. PoS LAT2007 (2007) 369
"""
def tagger(match):
groups = match.groupdict()
try:
year = match.group('year')
except IndexError:
# Extract year from volu... | 0.00107 |
def tokenize_number(val, line):
"""Parse val correctly into int or float."""
try:
num = int(val)
typ = TokenType.int
except ValueError:
num = float(val)
typ = TokenType.float
return {'type': typ, 'value': num, 'line': line} | 0.003676 |
def _get_env(self, config):
""" Read environment variables based on the settings defined in
the defaults. These are expected to be upper-case versions of
the actual setting names, prefixed by ``SCRAPEKIT_``. """
for option, value in config.items():
env_name = 'SCRAPEKIT_%s' %... | 0.004505 |
def get_vnetwork_portgroups_output_vnetwork_pgs_vs_nn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_portgroups = ET.Element("get_vnetwork_portgroups")
config = get_vnetwork_portgroups
output = ET.SubElement(get_vnetwork_portgroups,... | 0.003472 |
def sparql_query(self, query, flush=None, limit=None):
"""
Run a Sparql query.
:param query: sparql query string
:rtype: list of dictionary
"""
return self.find_statements(query, language='sparql', type='tuples',
flush=flush, limit=limit) | 0.010033 |
def writeGenerator(self, gen):
"""
Iterates over a generator object and encodes all that is returned.
"""
n = getattr(gen, 'next')
while True:
try:
self.writeElement(n())
except StopIteration:
break | 0.00678 |
def in_period(period, dt=None):
"""
Determines if a datetime is within a certain time period. If the time
is omitted the current time will be used.
in_period return True is the datetime is within the time period, False if not.
If the expression is malformed a TimePeriod.InvalidFormat exception
... | 0.00084 |
def _RawData(self, data):
"""Convert data to common format.
Configuration options are normally grouped by the functional component which
define it (e.g. Logging.path is the path parameter for the logging
subsystem). However, sometimes it is more intuitive to write the config as a
flat string (e.g. ... | 0.006536 |
def by_name(name):
"""Return a device by name.
Args:
name (str): The name of the device to return.
Returns:
:class:`~.SoCo`: The first device encountered among all zone with the
given player name. If none are found `None` is returned.
"""
devices = discover(all_househol... | 0.002252 |
def WalkTree(top, getChildren: Callable = None, getFirstChild: Callable = None, getNextSibling: Callable = None, yieldCondition: Callable = None, includeTop: bool = False, maxDepth: int = 0xFFFFFFFF):
"""
Walk a tree not using recursive algorithm.
top: a tree node.
getChildren: function(treeNode) -> lis... | 0.002406 |
def get_upload_form(self):
"""Construct form for accepting file upload."""
return self.form_class(self.request.POST, self.request.FILES) | 0.013158 |
def tf_summary_to_dict(tf_summary_str_or_pb, namespace=""):
"""Convert a Tensorboard Summary to a dictionary
Accepts either a tensorflow.summary.Summary
or one encoded as a string.
"""
values = {}
if isinstance(tf_summary_str_or_pb, Summary):
summary_pb = tf_summary_str_or_pb
elif i... | 0.00097 |
def ifelse(arg, true_expr, false_expr):
"""
Shorthand for implementing ternary expressions
bool_expr.ifelse(0, 1)
e.g., in SQL: CASE WHEN bool_expr THEN 0 else 1 END
"""
# Result will be the result of promotion of true/false exprs. These
# might be conflicting types; same type resolution as... | 0.002198 |
def read(self, size=None):
""" Read `size` of bytes."""
if size is None:
return self.buf.read() + self.open_file.read()
contents = self.buf.read(size)
if len(contents) < size:
contents += self.open_file.read(size - len(contents))
return contents | 0.01083 |
def get_component_info(self, comp):
"""Return the information about sub-component specific to a particular data selection
Parameters
----------
comp : `binning.Component` object
Specifies the sub-component
Returns `ModelComponentInfo` object
"""
if ... | 0.006173 |
def main():
"""
1. Parse CLI arguments.
2. Patch the environment with Python and libraries paths. This relaunches Python!
3. Launch IPython if requested
4. Load Chimera. IPython can import it now!
5. Run any additional CLI arguments (-m, -c, -f), if needed
"""
patch_sys_version()
arg... | 0.003008 |
def filter(self):
"""
Get a filtered list of file imports
:return: A list of file imports, with only the id set (you need to
refresh them if you want all the attributes to be filled in)
:rtype: list of :class:`carto.file_import.FileImportJob`
:raise: CartoExcept... | 0.001647 |
def float_to_fix(signed, n_bits, n_frac):
"""**DEPRECATED** Return a function to convert a floating point value to a
fixed point value.
.. warning::
This function is deprecated in favour of :py:meth:`~.float_to_fp`.
For example, a function to convert a float to a signed fractional
represen... | 0.000386 |
def job_conf(self, job_id):
"""
A job configuration resource contains information about the job
configuration for this job.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
pa... | 0.007059 |
def switch(request, tenant_id, redirect_field_name=auth.REDIRECT_FIELD_NAME):
"""Switches an authenticated user from one project to another."""
LOG.debug('Switching to tenant %s for user "%s".',
tenant_id, request.user.username)
endpoint, __ = utils.fix_auth_url_version_prefix(request.user.en... | 0.000466 |
def _parse_stsd(self, atom, fileobj):
"""Sets channels, bits_per_sample, sample_rate and optionally bitrate.
Can raise MP4StreamInfoError.
"""
assert atom.name == b"stsd"
ok, data = atom.read(fileobj)
if not ok:
raise MP4StreamInfoError("Invalid stsd")
... | 0.001402 |
def results(context, history_log):
"""Process provided history log and results files."""
if context.obj is None:
context.obj = {}
context.obj['history_log'] = history_log
if context.invoked_subcommand is None:
context.invoke(show, item=1) | 0.00369 |
def _update_deferred(self, event):
"""
This does the actual work of updating channel metadata. This is called
by the update(), and runs this method in another thread.
"""
if isinstance(event, ChannelCreated):
i = event.channel[u'id']
event.channel[u'is_archived'] = event.channel[u'is_member'] = False
... | 0.02272 |
def makeBaudRatePacket(ID, rate):
"""
Set baud rate of servo.
in: rate - 0: 9600, 1:57600, 2:115200, 3:1Mbps
out: write packet
"""
if rate not in [0, 1, 2, 3]:
raise Exception('Packet.makeBaudRatePacket: wrong rate {}'.format(rate))
pkt = makeWritePacket(ID, xl320.XL320_BAUD_RATE, [rate])
return pkt | 0.032154 |
def detect_duplicate_repos(repos1, repos2):
"""Return duplicate repos dict if repo_dir same and vcs different.
:param repos1: list of repo expanded dicts
:type repos1: list of :py:dict
:param repos2: list of repo expanded dicts
:type repos2: list of :py:dict
:rtype: list of dicts or None
:r... | 0.002064 |
def remove_file(file_path):
"""Remove a file from the filesystem."""
if path.exists(file_path):
try:
rmtree(file_path)
except Exception:
print('Unable to remove temporary workdir {}'.format(file_path)) | 0.004016 |
def make_mashes(fastas, mash_file, threads, kmer = 21, force = False):
"""
Create mash files for multiple fasta files
Input:
fastas <list[str]> -- paths to fasta files
mash_file <str> -- path to output mash file
threads <int> -- # threads for parallelization
kmer <... | 0.007383 |
def _disallow_catching_UnicodeDecodeError(f):
"""
Patches a template modules to prevent catching UnicodeDecodeError.
Note that this has the effect of also making Template raise a
UnicodeDecodeError instead of a TemplateEncodingError if the template
string is not UTF-8 or unicode.
"""
patch_... | 0.001458 |
def get_preview_url(self, data_type='L1C'):
"""Returns url location of full resolution L1C preview
:return:
"""
if self.data_source is DataSource.SENTINEL2_L1C or self.safe_type is EsaSafeType.OLD_TYPE:
return self.get_url(AwsConstants.PREVIEW_JP2)
return self.get_qi_... | 0.008451 |
def regular_grid_1d_from_shape_pixel_scales_and_origin(shape, pixel_scales, origin=(0.0, 0.0)):
"""Compute the (y,x) arc second coordinates at the centre of every pixel of an array of shape (rows, columns).
Coordinates are defined from the top-left corner, such that the first pixel at location [0, 0] has negat... | 0.006959 |
def import_submodules(package, name=None, recursive=True):
"""Import all submodules of ``package``.
Parameters
----------
package : `module` or string
Package whose submodules to import.
name : string, optional
Override the package name with this value in the full
submodule ... | 0.000764 |
def encode(self, *values):
"""Builds a hash from the passed `values`.
:param values The values to transform into a hashid
>>> hashids = Hashids('arbitrary salt', 16, 'abcdefghijkl0123456')
>>> hashids.encode(1, 23, 456)
'1d6216i30h53elk3'
"""
if not (values and ... | 0.003929 |
def tz_from_geom(connection, geometry):
r"""Finding the timezone of a given point or polygon geometry, assuming
that the polygon is not crossing a border of a timezone. For a given point
or polygon geometry not located within the timezone dataset (e.g. sea) the
nearest timezone based on the bounding box... | 0.000709 |
def calibrate_percentile_ranks(allele, predictor, peptides=None):
"""
Private helper function.
"""
global GLOBAL_DATA
if peptides is None:
peptides = GLOBAL_DATA["calibration_peptides"]
predictor.calibrate_percentile_ranks(
peptides=peptides,
alleles=[allele])
return ... | 0.002532 |
def json_format(out, graph):
"""Outputs the graph in a machine readable JSON format."""
steps = {}
for step, deps in each_step(graph):
steps[step.name] = {}
steps[step.name]["deps"] = [dep.name for dep in deps]
json.dump({"steps": steps}, out, indent=4)
out.write("\n") | 0.003268 |
def get_instance(cls, state):
""":rtype: UserStorageHandler"""
if cls.instance is None:
cls.instance = UserStorageHandler(state)
return cls.instance | 0.01087 |
def send(
self, record, message, resource=None, labels=None, trace=None, span_id=None
):
"""Overrides Transport.send().
:type record: :class:`logging.LogRecord`
:param record: Python log record that the handler was called with.
:type message: str
:param message: The... | 0.003481 |
def parse_oxide(self):
"""
Determines if an oxide is a peroxide/superoxide/ozonide/normal oxide.
Returns:
oxide_type (str): Type of oxide
ozonide/peroxide/superoxide/hydroxide/None.
nbonds (int): Number of peroxide/superoxide/hydroxide bonds in
st... | 0.000704 |
def escape_LDAP(ldap_string):
# type: (str) -> str
# pylint: disable=C0103
"""
Escape a string to let it go in an LDAP filter
:param ldap_string: The string to escape
:return: The protected string
"""
if not ldap_string:
# No content
return ldap_string
# Protect esc... | 0.001116 |
def _write_method(schema):
"""Add a write method for named schema to a class.
"""
def method(
self,
filename=None,
schema=schema,
taxon_col='uid',
taxon_annotations=[],
node_col='uid',
node_annotations=[],
branch_lengths=True,
**kwargs)... | 0.002519 |
def profile_prior_model_dict(self):
"""
Returns
-------
profile_prior_model_dict: {str: PriorModel}
A dictionary mapping_matrix instance variable names to variable profiles.
"""
return {key: value for key, value in
filter(lambda t: isinstance(t... | 0.009569 |
def regions():
"""
Get all available regions for the RDS service.
:rtype: list
:return: A list of :class:`boto.rds.regioninfo.RDSRegionInfo`
"""
return [RDSRegionInfo(name='us-east-1',
endpoint='rds.us-east-1.amazonaws.com'),
RDSRegionInfo(name='eu-west-1',... | 0.001026 |
def is_valid_filename(filename, return_ext=False):
"""Check whether the argument is a filename."""
ext = Path(filename).suffixes
if len(ext) > 2:
logg.warn('Your filename has more than two extensions: {}.\n'
'Only considering the two last: {}.'.format(ext, ext[-2:]))
ext =... | 0.003472 |
def _list_records(self, rtype=None, name=None, content=None):
"""
list all records
:param str rtype: type of record
:param str name: name of record
:param mixed content: value of record
:return list: list of found records
:raises Exception: on error
"""
... | 0.001629 |
async def load_tuple(self, elem_type, params=None, elem=None, obj=None):
"""
Loads tuple of elements from the reader. Supports the tuple ref.
Returns loaded tuple.
:param elem_type:
:param params:
:param elem:
:param obj:
:return:
"""
if o... | 0.00251 |
def constrain(value, lower=-np.Inf, upper=np.Inf, allow_equal=False):
"""
Apply interval constraint on stochastic value.
"""
ok = flib.constrain(value, lower, upper, allow_equal)
if ok == 0:
raise ZeroProbability | 0.004149 |
def p_expression_subsetvar(self, p):
''' expression : expression SUBSET VAR
'''
_LOGGER.debug("expresion -> expresion SUBSET VAR")
if p[3] not in self._VAR_VALUES:
if self._autodefine_vars:
self._VAR_VALUES[p[3]] = TypedList([])
else:
... | 0.015203 |
def get_child(self):
"""
Find file or folder at the remote_path
:return: File|Folder
"""
path_parts = self.remote_path.split(os.sep)
return self._get_child_recurse(path_parts, self.node) | 0.008547 |
def get_columns(self, *, top=None, skip=None):
"""
Return the columns of this table
:param int top: specify n columns to retrieve
:param int skip: specify n columns to skip
"""
url = self.build_url(self._endpoints.get('get_columns'))
params = {}
if top is... | 0.003958 |
def populate_index(
version, circleci_build, appveyor_build, coveralls_build, travis_build
):
"""Populates ``docs/index.rst`` with release-specific data.
Args:
version (str): The current version.
circleci_build (Union[str, int]): The CircleCI build ID corresponding
to the releas... | 0.000991 |
def post_freeze_hook(self):
"""Post :meth:`dtoolcore.ProtoDataSet.freeze` cleanup actions.
This method is called at the end of the
:meth:`dtoolcore.ProtoDataSet.freeze` method.
In the :class:`dtoolcore.storage_broker.DiskStorageBroker` it removes
the temporary directory for sto... | 0.004115 |
def from_params(cls, params: List[Tuple[str, Params]] = None) -> "InitializerApplicator":
"""
Converts a Params object into an InitializerApplicator. The json should
be formatted as follows::
[
["parameter_regex_match1",
{
... | 0.008089 |
def _block_stack_repr(self, block_stack):
"""Get a string version of `block_stack`, for debugging."""
blocks = ", ".join(
["(%s, %r)" % (dis.opname[b[0]], b[1]) for b in block_stack]
)
return "[" + blocks + "]" | 0.007874 |
def _import_module(self, module_path):
"""Dynamically import a module returning a handle to it.
:param str module_path: The module path
:rtype: module
"""
LOGGER.debug('Importing %s', module_path)
try:
return __import__(module_path)
except ImportErro... | 0.004651 |
def __create_vector(self, *vec) -> Vector3:
"""
Converts a variety of vector types to a flatbuffer Vector3.
Supports Flatbuffers Vector3, cTypes Vector3, list/tuple of numbers, or passing x,y,z (z optional)
"""
import numbers
if len(vec) == 1:
if hasattr(vec[... | 0.005233 |
def error(message):
"""
Throw an error with the given message and immediately quit.
Args:
message(str): The message to display.
"""
fail = '\033[91m'
end = '\033[0m'
sys.exit(fail + "Error: {}".format(message) + end) | 0.003953 |
def SelectGlyph(aFont, message="Select a glyph:", title='FontParts'):
"""
Select a glyph for a given font.
Optionally a `message` and `title` can be provided.
::
from fontParts.ui import SelectGlyph
font = CurrentFont()
glyph = SelectGlyph(font)
print(glyph)
"""
... | 0.002519 |
def from_file(cls, filename, sr=22050):
""" Loads an audiofile, uses sr=22050 by default. """
y, sr = librosa.load(filename, sr=sr)
return cls(y, sr) | 0.011561 |
def is_git_directory_clean(path_to_repo: Path,
search_parent_dirs: bool = True,
check_untracked: bool = False) -> None:
"""
Check that the git working directory is in a clean state
and raise exceptions if not.
:path_to_repo: The path of the git repo
... | 0.004154 |
def assert_dict_equal(
first, second, key_msg_fmt="{msg}", value_msg_fmt="{msg}"
):
"""Fail unless first dictionary equals second.
The dictionaries are considered equal, if they both contain the same
keys, and their respective values are also equal.
>>> assert_dict_equal({"foo": 5}, {"foo": 5})
... | 0.000359 |
def operator(func=None, *, pipable=False):
"""Create a stream operator from an asynchronous generator
(or any function returning an asynchronous iterable).
Decorator usage::
@operator
async def random(offset=0., width=1.):
while True:
yield offset + width * rand... | 0.000197 |
def get_wsgi_requests(request):
'''
For the given batch request, extract the individual requests and create
WSGIRequest object for each.
'''
valid_http_methods = ["get", "post", "put", "patch", "delete", "head", "options", "connect", "trace"]
requests = json.loads(request.body)
if t... | 0.00451 |
def join_timeseries(base, overwrite, join_linear=None):
"""Join two sets of timeseries
Parameters
----------
base : :obj:`MAGICCData`, :obj:`pd.DataFrame`, filepath
Base timeseries to use. If a filepath, the data will first be loaded from disk.
overwrite : :obj:`MAGICCData`, :obj:`pd.DataF... | 0.005556 |
def _add_gateway_node(self, gw_type, routing_node_gateway, network=None):
"""
Add a gateway node to existing routing tree. Gateways are only added if
they do not already exist. If they do exist, check the destinations of
the existing gateway and add destinations that are not already ther... | 0.007173 |
def antenna_pattern(self, right_ascension, declination, polarization, t_gps):
"""Return the detector response.
Parameters
----------
right_ascension: float or numpy.ndarray
The right ascension of the source
declination: float or numpy.ndarray
The declinat... | 0.003628 |
def _get_mark_if_any(self):
"""Parse a mark section."""
line = self.next_line()
if line.startswith(b'mark :'):
return line[len(b'mark :'):]
else:
self.push_line(line)
return None | 0.00813 |
def compile_to_code(definition, handlers={}):
"""
Generates validation code for validating JSON schema passed in ``definition``.
Example:
.. code-block:: python
import fastjsonschema
code = fastjsonschema.compile_to_code({'type': 'string'})
with open('your_file.py', 'w') as f:... | 0.003409 |
def result(self):
""" Get the result for a job. This will block if the job is incomplete.
Returns:
The result for the Job.
Raises:
An exception if the Job resulted in an exception.
"""
self.wait()
if self._fatal_error:
raise self._fatal_error
return self._result | 0.006431 |
def po_to_unicode(po_obj):
"""
Turns a polib :class:`polib.PoFile` or a :class:`polib.PoEntry`
into a :class:`unicode` string.
:param po_obj: Either a :class:`polib.PoFile` or :class:`polib.PoEntry`.
:rtype: :class:`unicode` string.
"""
po_text = po_obj.__str__()
if type(po_text) !... | 0.012315 |
def add_parameter(self, name, value, meta=None):
"""Add a parameter to the parameter list.
:param name: New parameter's name.
:type name: str
:param value: New parameter's value.
:type value: float
:param meta: New parameter's meta property.
:type meta: dict
... | 0.006623 |
def plot_spatial_firing_rate(self,label_x='x',label_y='y',bins=None,resolution=1.0,geometry=None,weight_function=None,normalize_time=True,normalize_n=False,start_units_with_0=True,**kwargs):
"""
Plots a two dimensional representation of the firing rates.
Each spike is binned according to... | 0.025016 |
def spinner(
spinner_name=None,
start_text=None,
handler_map=None,
nospin=False,
write_to_stdout=True,
):
"""Get a spinner object or a dummy spinner to wrap a context.
:param str spinner_name: A spinner type e.g. "dots" or "bouncingBar" (default: {"bouncingBar"})
:param str start_text: ... | 0.002238 |
def manual(cls, node, tval, ns=None):
"""
Set the node's xsi:type attribute based on either I{value}'s or the
node text's class. Then adds the referenced prefix(s) to the node's
prefix mapping.
@param node: XML node.
@type node: L{sax.element.Element}
@param tval... | 0.002247 |
def _delay_call(self):
"""
Makes sure that web service calls are at least 0.2 seconds apart.
"""
now = time.time()
time_since_last = now - self.last_call_time
if time_since_last < DELAY_TIME:
time.sleep(DELAY_TIME - time_since_last)
self.last_ca... | 0.006006 |
def add_template_network_events(self, columns, vectors):
""" Add a vector indexed """
# initialize with zeros - since vectors can be None, look for the
# longest one that isn't
new_events = None
new_events = numpy.zeros(
max([len(v) for v in vectors if v is not None])... | 0.002491 |
def add_source(self, source):
"""
Adds source to observation, keeping sorted order (in separation)
"""
if not type(source)==Source:
raise TypeError('Can only add Source object.')
if len(self.sources)==0:
self.sources.append(source)
else:
... | 0.00708 |
def kn_to_n(kn, N_k = None, cleanup = False):
""" Convert KxN_max array to N array
Parameters
----------
u_kn: np.ndarray, float, shape=(KxN_max)
N_k (optional) : np.array
the N_k matrix from the previous formatting form
cleanup (optional) : bool
optional command to clean up, s... | 0.006452 |
def remove(self, path, recursive=True):
"""
Remove file or directory at location ``path``.
:param path: a path within the FileSystem to remove.
:type path: str
:param recursive: if the path is a directory, recursively remove the directory and
all of its... | 0.005226 |
def extender(path=None, cache=None):
"""A context that temporarily extends sys.path and reverts it after the
context is complete."""
old_path = sys.path[:]
extend(path, cache=None)
try:
yield
finally:
sys.path = old_path | 0.003788 |
def load_command_table(self, args): # pylint: disable=unused-argument
""" Load commands into the command table
:param args: List of the arguments from the command line
:type args: list
:return: The ordered command table
:rtype: collections.OrderedDict
"""
self.c... | 0.006682 |
def overview(game_id):
"""Gets the overview information for the game with matching id."""
output = {}
# get data
overview = mlbgame.data.get_overview(game_id)
# parse data
overview_root = etree.parse(overview).getroot()
try:
output = add_raw_box_score_attributes(output, game_id)
... | 0.000902 |
def render_aafigure(self, text, options):
"""
Render an ASCII art figure into the requested format output file.
"""
fname = get_basename(text, options)
fname = '%s.%s' % (get_basename(text, options), options['format'])
if True: #TODO: hasattr(self.builder, 'imgpath'):
# HTML
#TO... | 0.005963 |
def fileobj_name(fileobj):
"""
Returns:
text: A potential filename for a file object. Always a valid
path type, but might be empty or non-existent.
"""
value = getattr(fileobj, "name", u"")
if not isinstance(value, (text_type, bytes)):
value = text_type(value)
return... | 0.003067 |
def mouseMoveEvent(self, event):
"""
Drags the selection view for this widget.
:param event | <QMouseMoveEvent>
"""
w = event.pos().x() - self._region.x()
h = event.pos().y() - self._region.y()
self._region.setWidth(w)
self... | 0.011494 |
def _get_md_files(self):
"""Get all markdown files."""
all_f = _all_files_matching_ext(os.getcwd(), "md")
exclusions = [
"*.egg/*",
"*.eggs/*",
"*build/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)]) | 0.00627 |
def on_to_state_edited(self, renderer, path, new_state_identifier):
"""Connects the outcome with a transition to the newly set state
:param Gtk.CellRendererText renderer: The cell renderer that was edited
:param str path: The path string of the renderer
:param str new_state_identifier: ... | 0.005489 |
def component_acting_parent_tag(parent_tag, tag):
"""
Only intended for use in getting components, look for tag name of fig-group
and if so, find the first fig tag inside it as the acting parent tag
"""
if parent_tag.name == "fig-group":
if (len(tag.find_previous_siblings("fig")) > 0):
... | 0.001773 |
def permute(self, ordering: np.ndarray, axis: int) -> None:
"""
Permute the dataset along the indicated axis.
Args:
ordering (list of int): The desired order along the axis
axis (int): The axis along which to permute
Returns:
Nothing.
"""
if self._file.__contains__("tiles"):
del self._fi... | 0.031722 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.