Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
370,800 | def remove_files(filename):
pattern = os.path.splitext(filename)[0] +
for f in glob.iglob(pattern):
os.remove(f) | Delete all files with same root as fileName,
i.e. regardless of suffix, such as ESRI shapefile |
370,801 | def named_objs(objlist, namesdict=None):
objs = OrderedDict()
if namesdict is not None:
objtoname = {hashable(v): k for k, v in namesdict.items()}
for obj in objlist:
if namesdict is not None and hashable(obj) in objtoname:
k = objtoname[hashable(obj)]
elif hasattr... | Given a list of objects, returns a dictionary mapping from
string name for the object to the object itself. Accepts
an optional name,obj dictionary, which will override any other
name if that item is present in the dictionary. |
370,802 | def connectPeer(self, peer):
return self.conns.connectCached(endpoint.Q2QEndpoint(self.svc,
self.addr,
peer,
PROTOCOL_NA... | Establish a SIGMA connection to the given peer.
@param peer: a Q2QAddress of a peer which has a file that I want
@return: a Deferred which fires a SigmaProtocol. |
370,803 | def do_patch(endpoint, body, access_token):
headers = {"content-type": "application/json", "Authorization": + access_token}
headers[] = get_user_agent()
return requests.patch(endpoint, data=body, headers=headers) | Do an HTTP PATCH request and return JSON.
Args:
endpoint (str): Azure Resource Manager management endpoint.
body (str): JSON body of information to patch.
access_token (str): A valid Azure authentication token.
Returns:
HTTP response. JSON body. |
370,804 | def add_translation(sender):
signals.post_save.connect(_save_translations, sender=sender)
sender.add_to_class("get_fieldtranslations", _get_fieldtranslations)
sender.add_to_class("load_translations", _load_translations)
sender.add_to_class("set_translation_fields", _set_dict_translations)
sender.... | Adds the actions to a class. |
370,805 | def generate_random_person(self, n):
assert self.all_male_first_names is not None
assert self.all_female_first_names is not None
assert self.all_last_names is not None
for i in range(n):
sex = if random.random() > 0.5 else
dob = random_date(sel... | Generator that yields details on a person with plausible name, sex and age.
:yields: Generated data for one person
tuple - (id: int, name: str('First Last'), birthdate: str('DD/MM/YYYY'), sex: str('M' | 'F') ) |
370,806 | def execute_after_scenario_steps(self, context):
if not self.feature_error and not self.scenario_error:
self.__execute_steps_by_action(context, ACTIONS_AFTER_SCENARIO)
if self.reset_error_status():
context.scenario.reset()
context.dyn_env.fail_first... | actions after each scenario
:param context: It’s a clever place where you and behave can store information to share around, automatically managed by behave. |
370,807 | def get_context_override(self, request):
context_override = super(EmulateUserModelMixin, self).get_context_override(request)
try:
if request.user.is_staff:
user = self.UserModel.objects.get(pk=request.session[])
context_override.update(user=user)
... | Override the request object with an emulated user. |
370,808 | def search_users(self, username_keyword, limit=10):
params = {"q": username_keyword, "limit": limit}
response = self.get("/users/search", params=params)
return [GogsUser.from_json(user_json) for user_json in response.json()["data"]] | Searches for users whose username matches ``username_keyword``, and returns
a list of matched users.
:param str username_keyword: keyword to search with
:param int limit: maximum number of returned users
:return: a list of matched users
:rtype: List[GogsUser]
:raises Net... |
370,809 | def get(self, word, default=nil):
node = self.__get_node(word)
output = nil
if node:
output = node.output
if output is nil:
if default is nil:
raise KeyError("no key " % word)
else:
return default
else:
return output | Retrieves output value associated with word.
If there is no word returns default value,
and if default is not given rises KeyError. |
370,810 | def list(self, limit=None, marker=None, name=None, visibility=None,
member_status=None, owner=None, tag=None, status=None,
size_min=None, size_max=None, sort_key=None, sort_dir=None,
return_raw=False):
uri = "/%s" % self.uri_base
qs = utils.dict_to_qs(dict(li... | Returns a list of resource objects. Pagination is supported through the
optional 'marker' and 'limit' parameters. Filtering the returned value
is possible by specifying values for any of the other parameters. |
370,811 | def _promote_and_split(s):
subst, attr, mode = s
subst0, subst1, _mode = subst
assert isinstance(_mode, NullScript)
return m(m(m(subst0)) ,m(m(subst1), attr) ,m(mode)) | E:F:.O:M:.t.- => E:.-F:.O:M:.-t.-‘
E:F:.M:M:.l.- => E:.-F:.M:M:.-l.-‘ |
370,812 | def _run_with_kvm(self, qemu_path, options):
if sys.platform.startswith("linux") and self.manager.config.get_section_config("Qemu").getboolean("enable_kvm", True) \
and "-no-kvm" not in options:
if os.path.basename(qemu_path) not in ["qemu-system-x86_64", "qem... | Check if we could run qemu with KVM
:param qemu_path: Path to qemu
:param options: String of qemu user options
:returns: Boolean True if we need to enable KVM |
370,813 | def w3_tx(self):
safe_contract = get_safe_contract(self.w3, address=self.safe_address)
return safe_contract.functions.execTransaction(
self.to,
self.value,
self.data,
self.operation,
self.safe_tx_gas,
self.data_gas,
... | :return: Web3 contract tx prepared for `call`, `transact` or `buildTransaction` |
370,814 | def is_descendant_of_bank(self, id_, bank_id):
if self._catalog_session is not None:
return self._catalog_session.is_descendant_of_catalog(id_=id_, catalog_id=bank_id)
return self._hierarchy_session.is_descendant(id_=id_, descendant_id=bank_id) | Tests if an ``Id`` is a descendant of a bank.
arg: id (osid.id.Id): an ``Id``
arg: bank_id (osid.id.Id): the ``Id`` of a bank
return: (boolean) - ``true`` if the ``id`` is a descendant of
the ``bank_id,`` ``false`` otherwise
raise: NotFound - ``bank_id`` not foun... |
370,815 | def _fetch_data(self):
if (self.inputs.surface_target == "fsnative" or
self.inputs.volume_target != "MNI152NLin2009cAsym"):
raise NotImplementedError
annotation_files = sorted(glob(os.path.join(self.inputs.subjects_dir,
... | Converts inputspec to files |
370,816 | def search_individuals(self, dataset_id, name=None):
request = protocol.SearchIndividualsRequest()
request.dataset_id = dataset_id
request.name = pb.string(name)
request.page_size = pb.int(self._page_size)
return self._run_search_request(
request, "individual... | Returns an iterator over the Individuals fulfilling the specified
conditions.
:param str dataset_id: The dataset to search within.
:param str name: Only Individuals matching the specified name will
be returned.
:return: An iterator over the :class:`ga4gh.protocol.Biosample`
... |
370,817 | def _normalize_purge_unknown(mapping, schema):
for field in tuple(mapping):
if field not in schema:
del mapping[field]
return mapping | {'type': 'boolean'} |
370,818 | def crates(self, from_page=1):
path = urijoin(CRATES_API_URL, CATEGORY_CRATES)
raw_crates = self.__fetch_items(path, from_page)
return raw_crates | Get crates in alphabetical order |
370,819 | def _configure_detail_level(cls, detail_level):
if isinstance(detail_level, six.string_types):
if detail_level not in LOG_DETAIL_LEVELS:
raise ValueError(
_format("Invalid log detail level string: {0!A}; must be "
"one... | Validate the `detail_level` parameter and return it.
This accepts a string or integer for `detail_level`. |
370,820 | def build_news(ctx, draft=False, yes=False):
report.info(ctx, "docs.build-news", "building changelog from news fragments")
build_command = f"towncrier --version {ctx.metadata[]}"
if draft:
report.warn(
ctx,
"docs.build-news",
"building changelog as draft (re... | Build towncrier newsfragments. |
370,821 | def process_results(self):
self.stage += 1
config_ids = list(filter(lambda cid: self.data[cid].status == , self.data.keys()))
if (self.stage >= len(self.num_configs)):
self.finish_up()
return
budgets = [self.data[cid].budget for cid in config_ids]
if len(set(budgets)) > 1:
raise RuntimeErr... | function that is called when a stage is completed and
needs to be analyzed befor further computations.
The code here implements the original SH algorithms by
advancing the k-best (lowest loss) configurations at the current
budget. k is defined by the num_configs list (see __init__)
and the current stage valu... |
370,822 | def mtf_image_transformer_tiny_spatial1d():
hparams = mtf_image_transformer_tiny()
hparams.num_decoder_layers = 6
hparams.filter_size = 128
hparams.block_height = 8
hparams.block_width = 8
hparams.attention_type = "local1d_spatial"
hparams.mesh_shape = ""
hparams.layout = ""
return hparams | Small single parameters. |
370,823 | def get_volumes(container_map, config, default_volume_paths, include_named):
def _bind_volume_path(vol):
if isinstance(vol, HostVolume):
return resolve_value(vol.path)
v_path = resolve_value(default_volume_paths.get(vol.name))
if v_path:
return v_path
rai... | Generates volume paths for the ``volumes`` argument during container creation.
:param container_map: Container map.
:type container_map: dockermap.map.config.main.ContainerMap
:param config: Container configuration.
:type config: dockermap.map.config.container.ContainerConfiguration
:param default_... |
370,824 | def run(self, context=None, options=None):
template = (
"var callback = arguments[arguments.length - 1];"
+ "axe.run(%s).then(results => callback(results))"
)
args = ""
if context is not None:
args += "%r" % context
... | Run axe against the current page.
:param context: which page part(s) to analyze and/or what to exclude.
:param options: dictionary of aXe options. |
370,825 | def extract_scopes(self, request):
payload = self.extract_payload(request)
if not payload:
return None
scopes_attribute = self.config.scopes_name()
return payload.get(scopes_attribute, None) | Extract scopes from a request object. |
370,826 | def cast_to_list(position):
@wrapt.decorator
def wrapper(function, instance, args, kwargs):
if not isinstance(args[position], list):
args = list(args)
args[position] = [args[position]]
args = tuple(args)
return function(*args, **kwargs)
return wrapper | Cast the positional argument at given position into a list if not already a list. |
370,827 | def find_link(self, target_node):
try:
return next(l for l in self.link_list if l.target == target_node)
except StopIteration:
return None | Find the link that points to ``target_node`` if it exists.
If no link in ``self`` points to ``target_node``, return None
Args:
target_node (Node): The node to look for in ``self.link_list``
Returns:
Link: An existing link pointing to ``target_node`` if found
... |
370,828 | def get_job_definition(self, identifier):
env = self.get_job_definition_by_arn(identifier)
if env is None:
env = self.get_job_definition_by_name(identifier)
return env | Get job defintiion by name or ARN
:param identifier: Name or ARN
:type identifier: str
:return: Job definition or None
:rtype: JobDefinition or None |
370,829 | def get_all_instance_profiles(path_prefix=, region=None, key=None,
keyid=None, profile=None):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
marker = False
profiles = []
while marker is not None:
marker = marker if marker else None
... | Get and return all IAM instance profiles, starting at the optional path.
.. versionadded:: 2016.11.0
CLI Example:
salt-call boto_iam.get_all_instance_profiles |
370,830 | def connection(self) -> Iterator[amqp.Connection]:
TCP_USER_TIMEOUT = 18
socket_settings = {TCP_USER_TIMEOUT: self.config.TCP_USER_TIMEOUT}
if sys.platform.startswith():
del socket_settings[TCP_USER_TIMEOUT]
conn = amqp.Connection(
host="%s:%s" % (sel... | Returns a new connection as a context manager. |
370,831 | def get_connection(connection=, engine_name=None, connection_type=, **args):
engine_name = engine_name or __default_engine__
if in connection:
d = {
:connection,
:args,
:connection_type,
}
return engine_manager.add(engine_name, d).en... | Creating an NamedEngine or just return existed engine instance
if '://' include in connection parameter, it'll create new engine object
otherwise return existed engine isntance |
370,832 | def categorical_partition_data(data):
series = pd.Series(data)
value_counts = series.value_counts(dropna=True)
null_indexes = series.isnull()
nonnull_count = (null_indexes == False).sum()
weights = value_counts.values / nonnull_count
return {
"values": value_counts.inde... | Convenience method for creating weights from categorical data.
Args:
data (list-like): The data from which to construct the estimate.
Returns:
A new partition object::
{
"partition": (list) The categorical values present in the data
"weights": (list... |
370,833 | def find_one_and_replace(self, filter, replacement,
projection=None, sort=None, upsert=False,
return_document=ReturnDocument.BEFORE, **kwargs):
common.validate_ok_for_replace(replacement)
kwargs[] = replacement
return self.__find... | Finds a single document and replaces it, returning either the
original or the replaced document.
The :meth:`find_one_and_replace` method differs from
:meth:`find_one_and_update` by replacing the document matched by
*filter*, rather than modifying the existing document.
>>> fo... |
370,834 | def smart_scrubf(df,col_name,error_rate = 0):
scrubbed = ""
while True:
valcounts = df[col_name].str[:len(scrubbed)+1].value_counts()
if not len(valcounts):
break
if not valcounts[0] >= (1-error_rate) * _utils.rows(df):
break
scrubbed=valcounts.index[... | Scrubs from the front of an 'object' column in a DataFrame
until the scrub would semantically alter the contents of the column. If only a
subset of the elements in the column are scrubbed, then a boolean array indicating which
elements have been scrubbed is appended to the dataframe. Returns the string tha... |
370,835 | def log_url (self, url_data):
self.writeln(u"insert into %(table)s(urlname,"
"parentname,baseref,valid,result,warning,info,url,line,col,"
"name,checktime,dltime,size,cached,level,modified) values ("
"%(base_url)s,"
"%(url_parent)s,"
... | Store url check info into the database. |
370,836 | def graftm_package_is_protein(graftm_package):
is_protein_package
found = None
with open(graftm_package.alignment_hmm_path()) as f:
r = f.read().split("\n")
for line in r:
if line==:
found = False
break
elif line==:
... | Return true if this package is an Amino Acid alignment package, otherwise
False i.e. it is a nucleotide package. In general it is best to use
'is_protein_package' instead. |
370,837 | def parse(self, line):
if not line:
raise KatcpSyntaxError("Empty message received.")
type_char = line[0]
if type_char not in self.TYPE_SYMBOL_LOOKUP:
raise KatcpSyntaxError("Bad type character %r." % (type_char,))
mtype = self.TYPE_SYMBOL_LOOK... | Parse a line, return a Message.
Parameters
----------
line : str
The line to parse (should not contain the terminating newline
or carriage return).
Returns
-------
msg : Message object
The resulting Message. |
370,838 | def _create_record(self, rtype, name, content):
if not self._list_records(rtype, name, content):
self._update_records([{}], {
: rtype,
: self._relative_name(name),
: content,
: self._get_lexicon_option(),
})
... | Create record. If it already exists, do nothing. |
370,839 | def get_group_details(self, group):
result = {}
try:
lgroup = self._get_group(group.name)
lgroup = preload(lgroup, database=self._database)
except ObjectDoesNotExist:
return result
for i, j in lgroup.items():
if j is not None:
... | Get the group details. |
370,840 | def lock_time(logfile):
print("Processing log %s" % filename)
mlog = mavutil.mavlink_connection(filename)
locked = False
start_time = 0.0
total_time = 0.0
t = None
m = mlog.recv_match(type=[,], condition=args.condition)
if m is None:
return 0
unlock_time = time.mktime(... | work out gps lock times for a log file |
370,841 | def get_service_types(self):
resp = self._get_resource_root().get(self._path() + )
return resp[ApiList.LIST_KEY] | Get all service types supported by this cluster.
@return: A list of service types (strings) |
370,842 | def cmd(send, msg, args):
implements = [, , , , , , , ]
methods = [, ]
if not msg:
channel = args[] if args[] != else args[][][]
with args[].data_lock:
users = list(args[].channels[channel].users())
slap =
send(slap % (choice(users), choice(methods), choice... | Slap somebody.
Syntax: {command} <nick> [for <reason>] |
370,843 | def split_bin_edges(edges, npts=2):
if npts < 2:
return edges
x = (edges[:-1, None] +
(edges[1:, None] - edges[:-1, None]) *
np.linspace(0.0, 1.0, npts + 1)[None, :])
return np.unique(np.ravel(x)) | Subdivide an array of bins by splitting each bin into ``npts``
subintervals.
Parameters
----------
edges : `~numpy.ndarray`
Bin edge array.
npts : int
Number of intervals into which each bin will be subdivided.
Returns
-------
edges : `~numpy.ndarray`
Subdivide... |
370,844 | def getkeys(table):
keys = []
if table == "ER_expedition":
pass
if table == "ER_citations":
keys.append("er_citation_name")
keys.append("long_authors")
keys.append("year")
keys.append("title")
keys.append("citation_type")
keys.append("doi")
... | customize by commenting out unwanted keys |
370,845 | def save(self, obj):
if isinstance(obj, self.np.ndarray) and not obj.dtype.hasobject:
if obj.shape == ():
obj_c_contiguous = obj.flatten()
elif obj.flags.c_contiguous:
obj_c_contiguous = ... | Subclass the save method, to hash ndarray subclass, rather
than pickling them. Off course, this is a total abuse of
the Pickler class. |
370,846 | def sync_repo(self, repo_name=None, envs=[], query=):
juicer.utils.Log.log_debug(
"Sync Repo %s In: %s" % (repo_name, ",".join(envs)))
data = {
: {
: ,
:
},
}
for env in envs:
url = "%s%s-... | Sync repository in specified environments |
370,847 | def save_plot(self, filename, img_format="eps", ylim=None, units="thz"):
plt = self.get_plot(ylim=ylim, units=units)
plt.savefig(filename, format=img_format)
plt.close() | Save matplotlib plot to a file.
Args:
filename: Filename to write to.
img_format: Image format to use. Defaults to EPS.
ylim: Specifies the y-axis limits.
units: units for the frequencies. Accepted values thz, ev, mev, ha, cm-1, cm^-1. |
370,848 | def set_tlsext_use_srtp(self, profiles):
if not isinstance(profiles, bytes):
raise TypeError("profiles must be a byte string.")
_openssl_assert(
_lib.SSL_CTX_set_tlsext_use_srtp(self._context, profiles) == 0
) | Enable support for negotiating SRTP keying material.
:param bytes profiles: A colon delimited list of protection profile
names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``.
:return: None |
370,849 | def _index_action(self, payload):
record = Record.get_record(payload[])
index, doc_type = self.record_to_index(record)
return {
: ,
: index,
: doc_type,
: str(record.id),
: record.revision_id,
: self._version_type,... | Bulk index action.
:param payload: Decoded message body.
:returns: Dictionary defining an Elasticsearch bulk 'index' action. |
370,850 | def findFile(input):
if not input:
return no
_fdir, _fname = os.path.split(osfn(input))
if _fdir == :
_fdir = os.curdir
try:
flist = os.listdir(_fdir)
except OSError:
return no
_root, _extn = parseFilename(_fname)
found = no
... | Search a directory for full filename with optional path. |
370,851 | def breakdown_tt2000(tt2000, to_np=None):
if (isinstance(tt2000, int) or isinstance(tt2000, np.int64)):
new_tt2000 = [tt2000]
elif (isinstance(tt2000, list) or isinstance(tt2000, tuple) or
isinstance(tt2000, np.ndarray)):
new_tt2000 = tt2000
else:... | Breaks down the epoch(s) into UTC components.
For CDF_EPOCH:
they are 7 date/time components: year, month, day,
hour, minute, second, and millisecond
For CDF_EPOCH16:
they are 10 date/time components: year, month, day,
hour, minute, second... |
370,852 | def diy(expression_data,
regressor_type,
regressor_kwargs,
gene_names=None,
tf_names=,
client_or_address=,
early_stop_window_length=EARLY_STOP_WINDOW_LENGTH,
limit=None,
seed=None,
verbose=False):
if verbose:
print()
client, s... | :param expression_data: one of:
* a pandas DataFrame (rows=observations, columns=genes)
* a dense 2D numpy.ndarray
* a sparse scipy.sparse.csc_matrix
:param regressor_type: string. One of: 'RF', 'GBM', 'ET'. Case insensitive.
:param regressor_kwargs: a dictionary of key-value pa... |
370,853 | def set_coords(self, value):
self.__coords = value
for image in self.images:
image.coords = value | Set all the images contained in the animation to the specified value. |
370,854 | def _parse_qual(self, data):
list = []
headers = data.split()
name = headers[0].strip()
name = re.split(, name, flags=re.I)
units = None
if len(name) > 1:
units = name[1].strip()
name = name[0].strip()
if len(headers) < 2:
... | Parse qual attribute of the old HEPData format
example qual:
*qual: RE : P P --> Z0 Z0 X
:param data: data to be parsed
:type data: str |
370,855 | def get_rank_based_enrichment(
self,
ranked_genes: List[str],
pval_thresh: float = 0.05,
X_frac: float = 0.25,
X_min: int = 5,
L: int = None,
adjust_pval_thresh: bool = True,
escore_pval_thresh: float = None,
exa... | Test for gene set enrichment at the top of a ranked list of genes.
This function uses the XL-mHG test to identify enriched gene sets.
This function also calculates XL-mHG E-scores for the enriched gene
sets, using ``escore_pval_thresh`` as the p-value threshold "psi".
Parameters
... |
370,856 | async def create_rev_reg(self, rr_id: str, rr_size: int = None) -> None:
LOGGER.debug(, rr_id, rr_size)
if not self.wallet.handle:
LOGGER.debug(, self.name)
raise WalletState(.format(self.name))
if not ok_rev_reg_id(rr_id):
LOGGER.debug(, rr_id)
... | Create revocation registry artifacts and new tails file (with association to
corresponding revocation registry identifier via symbolic link name)
for input revocation registry identifier. Symbolic link presence signals completion.
If revocation registry builder operates in a process external to ... |
370,857 | def search(self, search, **kwargs):
kwargs[] = True
if kwargs.get():
return self.search_with_http_info(search, **kwargs)
else:
(data) = self.search_with_http_info(search, **kwargs)
return data | Search for Repository Configurations based on internal or external url, ignoring the protocol and \".git\" suffix. The matching is done using LIKE.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be in... |
370,858 | def convert_str_to_datetime(df, *, column: str, format: str):
df[column] = pd.to_datetime(df[column], format=format)
return df | Convert string column into datetime column
---
### Parameters
*mandatory :*
- `column` (*str*): name of the column to format
- `format` (*str*): current format of the values (see [available formats](
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior)) |
370,859 | def _RegisterProcess(self, process):
if process is None:
raise ValueError()
if process.pid in self._processes_per_pid:
raise KeyError(
.format(
process.name, process.pid))
self._processes_per_pid[process.pid] = process | Registers a process with the engine.
Args:
process (MultiProcessBaseProcess): process.
Raises:
KeyError: if the process is already registered with the engine.
ValueError: if the process is missing. |
370,860 | def from_plane(cls, plane):
return cls(
origin=plane.origin.toTuple(),
xDir=plane.xDir.toTuple(),
normal=plane.zDir.toTuple(),
) | :param plane: cadquery plane instance to base coordinate system on
:type plane: :class:`cadquery.Plane`
:return: duplicate of the given plane, in this class
:rtype: :class:`CoordSystem`
usage example:
.. doctest::
>>> import cadquery
>>> from cqparts.ut... |
370,861 | def check_rollout(edits_service, package_name, days):
edit = edits_service.insert(body={}, packageName=package_name).execute()
response = edits_service.tracks().get(editId=edit[], track=, packageName=package_name).execute()
releases = response[]
for release in releases:
if release[] == :
... | Check if package_name has a release on staged rollout for too long |
370,862 | def _require_host_parameter(args, to):
if not args.host:
sys.stderr.write("--host is required parameter to --%s\n" % to)
sys.exit(1) | Make sure, that user specified --host argument. |
370,863 | def addup_fluxes(self):
fluxes = self.sequences.fluxes
for flux in fluxes.numerics:
sum_ = getattr(fluxes.fastaccess, % flux.name)
sum_ += flux
if flux.NDIM == 0:
setattr(fluxes.fastaccess, % flux.name, sum_) | Add up the sum of the fluxes calculated so far.
>>> from hydpy.models.test_v1 import *
>>> parameterstep()
>>> fluxes.fastaccess._q_sum = 1.0
>>> fluxes.q(2.0)
>>> model.addup_fluxes()
>>> fluxes.fastaccess._q_sum
3.0 |
370,864 | def gen_nf_quick_check(output, ascii_props=False, append=False, prefix=""):
categories = []
nf = {}
all_chars = ALL_ASCII if ascii_props else ALL_CHARS
file_name = os.path.join(HOME, , UNIVERSION, )
with codecs.open(file_name, , ) as uf:
for line in uf:
if not line.startswi... | Generate quick check properties. |
370,865 | def _get_changes(cls, diff_dict):
changes_strings = []
for p in sorted(diff_dict.keys()):
if sorted(diff_dict[p].keys()) == [, ]:
old_value = diff_dict[p][]
if diff_dict[p][] == cls.NONE_VALUE:
old_value =
... | Returns a list of string message with the differences in a diff dict.
Each inner difference is tabulated two space deeper |
370,866 | def _check_load_parameters(self, **kwargs):
if in kwargs:
msg = " is not allowed as a load parameter. Vcmp " \
"guests are accessed by name."
raise DisallowedReadParameter(msg)
super(Guest, self)._check_load_parameters(**kwargs) | Override method for one in resource.py to check partition
The partition cannot be included as a parameter to load a guest.
Raise an exception if a consumer gives the partition parameter.
:raises: DisallowedReadParameter |
370,867 | def key_rule(self, regex, verifier):
if regex is not None:
regex = re.compile(regex)
self._additional_key_rules.append((regex, verifier)) | Add a rule with a pattern that should apply to all keys.
Any key not explicitly listed in an add_required or add_optional rule
must match ONE OF the rules given in a call to key_rule().
So these rules are all OR'ed together.
In this case you should pass a raw string specifying a regex ... |
370,868 | def get_word_before_cursor(self, WORD=False):
if self.text_before_cursor[-1:].isspace():
return
else:
return self.text_before_cursor[self.find_start_of_previous_word(WORD=WORD):] | Give the word before the cursor.
If we have whitespace before the cursor this returns an empty string. |
370,869 | def _container_start_handler_factory(ion_type, before_yield=lambda c, ctx: None):
assert ion_type.is_container
@coroutine
def container_start_handler(c, ctx):
before_yield(c, ctx)
yield
yield ctx.event_transition(IonEvent, IonEventType.CONTAINER_START, ion_type, value=None)
... | Generates handlers for tokens that begin with container start characters.
Args:
ion_type (IonType): The type of this container.
before_yield (Optional[callable]): Called at initialization. Accepts the first character's ordinal and the
current context; performs any necessary initializati... |
370,870 | def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \
-> Generator[Any, None, None]:
return (row[0] for row in genrows(cursor, arraysize)) | Generate the first value in each row.
Args:
cursor: the cursor
arraysize: split fetches into chunks of this many records
Yields:
the first value of each row |
370,871 | def create_values(self, value_names):
output = {}
for value_name in value_names:
output[value_name] = read_settings(self.widget, value_name)
return output | Read original values from the settings or the defaults.
Parameters
----------
value_names : list of str
list of value names to read
Returns
-------
dict
dictionary with the value names as keys |
370,872 | def update_clock(self, dt):
dt = dt.astimezone(self.tzinfo)
fmt = "%H:%M"
if self.show_seconds:
fmt = "%H:%M:%S"
self.time_txt.text = dt.strftime(fmt)
suppl_text = "{0} {1}".format(dt.strftime("%Y-%m-%d"), self.timezone)
self.suppl_txt.text = suppl_... | This method is called by the ClockApp whenever the timer fires
to update the clock. `dt` is a timezone-aware datetime object. |
370,873 | def _elements_to_dict(data, position, obj_end, opts, subdocument=None):
if type(opts.document_class) == tuple:
result = opts.document_class[0](**opts.document_class[1]) if not subdocument else dict()
else:
result = opts.document_class() if not subdocument else dict()
end = obj_end - 1
... | Decode a BSON document. |
370,874 | def shutdown(self, hub=True, targets=, block=False):
if self.controller:
logger.debug("IPP:Shutdown sequence: Attempting controller kill")
self.controller.close()
logger.debug("Done with executor shutdown")
... | Shutdown the executor, including all workers and controllers.
The interface documentation for IPP is `here <http://ipyparallel.readthedocs.io/en/latest/api/ipyparallel.html#ipyparallel.Client.shutdown>`_
Kwargs:
- hub (Bool): Whether the hub should be shutdown, Default:True,
- ... |
370,875 | def connection(self):
connection = self._get_connection()
if connection:
return connection
else:
message = "GTF database needs to be created"
if self.install_string:
message += ", run: %s" % self.install_string
raise ValueE... | Get a connection to the database or raise an exception |
370,876 | def commit(*args):
parser = argparse.ArgumentParser(prog="%s %s" % (__package__, commit.__name__), description=commit.__doc__)
parser.add_argument(, help="file(s) to commit", nargs="*", default=[])
args = parser.parse_args(args)
config = FragmentsConfig()
for s, curr_path in _iterate_over_fil... | Commit changes to the fragments repository, limited to FILENAME(s) if specified. |
370,877 | def receive(self, path, diffTo, diffFrom):
diff = self.toObj.diff(diffTo, diffFrom)
self._open(self.butterStore.receive(diff, [path, ])) | Receive a btrfs diff. |
370,878 | def handle(self, *args, **options):
if mon is None:
sys.stderr.write(MISSING)
else:
mon.run(**options) | Handle the management command. |
370,879 | def home(request):
try:
DBSession.query(User).first()
except DBAPIError:
return Response(
conn_err_msg,
content_type="text/plain",
status_int=500,
)
return {"project": "pyramid_tut"} | Try to connect to database, and list available examples. |
370,880 | def _parse_quniform(self, param_value):
if param_value[2] < 2:
raise RuntimeError("The number of values sampled (q) should be at least 2")
low, high, count = param_value[0], param_value[1], param_value[2]
interval = (high - low) / (count - 1)
return [float(low + inte... | parse type of quniform parameter and return a list |
370,881 | def ellipse(n=1000, adaptive=False):
u = N.linspace(0,2*N.pi,n)
return N.array([N.cos(u),N.sin(u)]).T | Get a parameterized set of vectors defining
ellipse for a major and minor axis length.
Resulting vector bundle has major axes
along axes given. |
370,882 | def _store_post(self, stored_entry, entry=None):
if stored_entry.published is None:
stored_entry.published = self._get_dummy_datetime()
if stored_entry.updated is None:
stored_entry.updated = self._get_dummy_datetime()
stored_entry.save... | This method formats entry returned by _get_data() and puts to DB
create textDesc, title, and MIME |
370,883 | def _empty_notification(self):
sess = cherrypy.session
username = sess.get(SESSION_KEY, None)
if username in self.notifications:
ret = self.notifications[username]
else:
ret = []
self.notifications[username] = []
return ret | empty and return list of message notification |
370,884 | def _load_neighbors_from_external_source(self) -> None:
graph: SpotifyArtistGraph = self._graph
items: List[NameExternalIDPair] = graph.client.similar_artists(self.external_id)
limit: int = graph.neighbor_count if graph.neighbor_count > 0 else self._NEIGHBORS_TO_LOAD
if len(ite... | Loads the neighbors of the node from the igraph `Graph` instance that is
wrapped by the graph that has this node. |
370,885 | def cut(self, start=0, end=-1, index=False):
s_index, e_index = time_indices(self.npts, self.dt, start, end, index)
self._values = np.array(self.values[s_index:e_index]) | The method cuts the time series to reduce its length.
:param start: int or float, optional, New start point
:param end: int or float, optional, New end point
:param index: bool, optional, if False then start and end are considered values in time. |
370,886 | def update(self, muted=values.unset, hold=values.unset, hold_url=values.unset,
hold_method=values.unset, announce_url=values.unset,
announce_method=values.unset, wait_url=values.unset,
wait_method=values.unset, beep_on_exit=values.unset,
end_conference_on_exit... | Update the ParticipantInstance
:param bool muted: Whether the participant should be muted
:param bool hold: Whether the participant should be on hold
:param unicode hold_url: The URL we call using the `hold_method` for music that plays when the participant is on hold
:param unicode hol... |
370,887 | def _entropy(self):
if any(self._dist_fn_args):
raise ValueError(
)
return sum(joint_distribution_lib.maybe_check_wont_broadcast(
(d().entropy() for d in self._dist_fn_wrapped),
self.validate_args)) | Shannon entropy in nats. |
370,888 | def most_seen_creators_by_works(work_kind=None, role_name=None, num=10):
return Creator.objects.by_works(kind=work_kind, role_name=role_name)[:num] | Returns a QuerySet of the Creators that are associated with the most Works. |
370,889 | def maps_get_default_rules_output_rules_timebase(self, **kwargs):
config = ET.Element("config")
maps_get_default_rules = ET.Element("maps_get_default_rules")
config = maps_get_default_rules
output = ET.SubElement(maps_get_default_rules, "output")
rules = ET.SubElement(ou... | Auto Generated Code |
370,890 | def get_turbine_data_from_oedb(turbine_type, fetch_curve, overwrite=False):
r
filename = os.path.join(os.path.dirname(__file__), ,
)
if os.path.isfile(filename) and not overwrite:
logging.debug("Turbine data is fetched from {}".format(filename))
with pd.HDFSt... | r"""
Fetches data for one wind turbine type from the OpenEnergy Database (oedb).
If turbine data exists in local repository it is loaded from this file. The
file is created when turbine data was loaded from oedb in
:py:func:`~.load_turbine_data_from_oedb`. Use this function with
`overwrite=True` to... |
370,891 | def is_writable(path):
try:
testfile = tempfile.TemporaryFile(dir=path)
testfile.close()
except OSError as e:
if e.errno == errno.EACCES:
return False
return True | Check if path has write access |
370,892 | def add(A, b, offset=0):
return _diag_ufunc(A, b, offset, np.add) | Add b to the view of A in place (!).
Returns modified A.
Broadcasting is allowed, thus b can be scalar.
if offset is not zero, make sure b is of right shape!
:param ndarray A: 2 dimensional array
:param ndarray-like b: either one dimensional or scalar
:param int offset: same as in view.
:r... |
370,893 | def cmd(command):
env()
ipmi = cij.env_to_dict(PREFIX, EXPORTED + REQUIRED)
command = "ipmitool -U %s -P %s -H %s -p %s %s" % (
ipmi["USER"], ipmi["PASS"], ipmi["HOST"], ipmi["PORT"], command)
cij.info("ipmi.command: %s" % command)
return cij.util.execute(command, shell=True, echo=T... | Send IPMI 'command' via ipmitool |
370,894 | def _apply_data_mask(self, data):
data = self._format_data(data)
masked_data, pixels_affected = [], 0
data_mask = self._configuration.get("masks", {}).get("data", [])
for spectrum in data:
masked_spectrum = spectrum.copy()
for start, end in data_mask:
... | Apply pre-defined masks to the data. |
370,895 | def token_distance(t1, t2, initial_match_penalization):
if isinstance(t1, NameInitial) or isinstance(t2, NameInitial):
if t1.token == t2.token:
return 0
if t1 == t2:
return initial_match_penalization
return 1.0
return _normalized_edit_dist(t1.token, t2.token) | Calculates the edit distance between two tokens. |
370,896 | def _parse(self, stream):
builddata = json.load(stream)
log.debug()
if not in builddata:
log.warn()
return
for tdata in builddata[]:
target = address.new(target=tdata.pop(),
repo=self.target.rep... | Parse a JSON BUILD file.
Args:
builddata: dictionary of buildfile data
reponame: name of the repo that it came from
path: directory path within the repo |
370,897 | def _parse_tile_url(tile_url):
props = tile_url.rsplit(, 7)
return .join(props[1:4]), .join(props[4:7]), int(props[7]) | Extracts tile name, data and AWS index from tile URL
:param tile_url: Location of tile at AWS
:type: tile_url: str
:return: Tuple in a form (tile_name, date, aws_index)
:rtype: (str, str, int) |
370,898 | def apply(
self, value, locale, currency=None, currency_digits=True,
decimal_quantization=True):
if not isinstance(value, decimal.Decimal):
value = decimal.Decimal(str(value))
value = value.scaleb(self.scale)
is_negative = int(value.is_sign... | Renders into a string a number following the defined pattern.
Forced decimal quantization is active by default so we'll produce a
number string that is strictly following CLDR pattern definitions. |
370,899 | def name(self):
if self._name is None:
location = getattr(self.path_spec, , None)
if location is not None:
self._name = self._file_system.BasenamePath(location)
else:
volume_index = apfs_helper.APFSContainerPathSpecGetVolumeIndex(
self.path_spec)
if volume_... | str: name of the file entry, which does not include the full path. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.