Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
382,700 | def run(self, **kwargs):
logger.info()
try:
with open(app_settings.IP_ASSEMBLER_IP_CHANGED_FILE, ) as f:
content_list = f.readlines()
if len(content_list) == 0:
ip_count_old = -1
else:
... | Does the magic! |
382,701 | def info_post_request(self, node, info):
for agent in node.neighbors():
node.transmit(what=info, to_whom=agent) | Run when a request to create an info is complete. |
382,702 | def _parse_args():
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=_CliFormatter)
parser.add_argument(, , action=,
help=)
fb_group = parser.add_argument_group()
fb_group.add_argument(
, , help=(
))
... | Parse and return command line arguments. |
382,703 | def collect_segment_partitions(self):
from collections import defaultdict
partitions = defaultdict(set)
for p in self.dataset.partitions:
if p.type == p.TYPE.SEGMENT:
name = p.identity.name
name.segment = None
... | Return a dict of segments partitions, keyed on the name of the parent partition |
382,704 | def submit(self, spec):
spec = ApplicationSpec._from_any(spec)
resp = self._call(, spec.to_protobuf())
return resp.id | Submit a new skein application.
Parameters
----------
spec : ApplicationSpec, str, or dict
A description of the application to run. Can be an
``ApplicationSpec`` object, a path to a yaml/json file, or a
dictionary description of an application specification.
... |
382,705 | def find_lexer_class_for_filename(_fn, code=None):
matches = []
fn = basename(_fn)
for modname, name, _, filenames, _ in itervalues(LEXERS):
for filename in filenames:
if _fn_matches(fn, filename):
if name not in _lexer_cache:
_load_lexers(modname... | Get a lexer for a filename.
If multiple lexers match the filename pattern, use ``analyse_text()`` to
figure out which one is more appropriate.
Returns None if not found. |
382,706 | def create_object_if_not_exists(self, alias, name=None, *args, **kwargs):
if name is None:
raise ValueError("Method requires an object `name`.")
obj_creator = functools.partial(self.create_object,
alias,
name=name,
... | Constructs the type with the given alias using the given args and kwargs.
NB: aliases may be the alias' object type itself if that type is known.
:API: public
:param alias: Either the type alias or the type itself.
:type alias: string|type
:param *args: These pass through to the underlying callab... |
382,707 | def _send_msg(self, header, payload):
if self.verbose:
print(, repr(header))
print(, repr(payload))
assert header.payload == len(payload)
try:
sent = self.socket.send(header + payload)
except IOError as err:
raise ConnError(*err.a... | send message to server |
382,708 | def get_dev_details(ip_address, auth, url):
get_dev_details_url = "/imcrs/plat/res/device?resPrivilegeFilter=false&ip=" + \
str(ip_address) + "&start=0&size=1000&orderBy=id&desc=false&total=false"
f_url = url + get_dev_details_url
r = requests.get(f_url, auth=auth, h... | Takes string input of IP address to issue RESTUL call to HP IMC\n
:param ip_address: string object of dotted decimal notation of IPv4 address
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.a... |
382,709 | def delete_user(self, username, params=None):
if username in SKIP_IN_PATH:
raise ValueError("Empty value passed for a required argument .")
return self.transport.perform_request(
"DELETE", _make_path("_security", "user", username), params=params
) | `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-delete-user.html>`_
:arg username: username
:arg refresh: If `true` (the default) then refresh the affected shards
to make this operation visible to search, if `wait_for` then wait
for a refresh to ma... |
382,710 | def parse(self, paramfile):
with open(paramfile, ) as f:
for line in f.readlines():
line_clean = line.rstrip().split()[0]
if line_clean and in line:
attribute, value = line_clean.split()
try:
... | Read parameter file and set parameter values.
File should have python-like syntax. Full file name needed. |
382,711 | def write(url, content, **args):
relay = urlparse.urlparse(args.pop(, ))
try:
smtplib_SMTPS = functools.partial(smtplib.SMTP_SSL,
keyfile=args.pop(, None),
certfile=args.pop(, None))
except AttributeError:
... | Put an object into a ftp URL. |
382,712 | def tap_and_hold(self, xcoord, ycoord):
self._actions.append(lambda: self._driver.execute(
Command.TOUCH_DOWN, {
: int(xcoord),
: int(ycoord)}))
return self | Touch down at given coordinates.
:Args:
- xcoord: X Coordinate to touch down.
- ycoord: Y Coordinate to touch down. |
382,713 | def reddening(self,extval):
T = 10.0**(-0.4*extval*self.obscuration)
ans = ExtinctionSpectralElement(wave=self.wave,
waveunits=self.waveunits,
throughput=T,
name=%(self.name, ... | Compute the reddening for the given extinction.
.. math::
A(V) = R(V) \\; \\times \\; E(B-V)
\\textnormal{THRU} = 10^{-0.4 \\; A(V)}
.. note::
``self.litref`` is passed into ``ans.citation``.
Parameters
----------
extval : float
... |
382,714 | def _generate_author_query(self, author_name):
name_variations = [name_variation.lower()
for name_variation
in generate_minimal_name_variations(author_name)]
if author_name_contains_fullnames(author_name):
... | Generates a query handling specifically authors.
Notes:
The match query is generic enough to return many results. Then, using the filter clause we truncate these
so that we imitate legacy's behaviour on returning more "exact" results. E.g. Searching for `Smith, John`
shouldn... |
382,715 | def bitop_or(self, dest, key, *keys):
return self.execute(b, b, dest, key, *keys) | Perform bitwise OR operations between strings. |
382,716 | def remove_sample(self, md5):
record = self.database[self.sample_collection].find_one({: md5})
if not record:
return
print % (record[], record[]/1024.0/1024.0)
self.database[self.sample_collection].remove({: record[]})
self.gridfs_handle.... | Delete a specific sample |
382,717 | def deleteMapTable(self, name, session):
duplicate_map_tables = session.query(MapTable).filter(MapTable.mapTableFile == self).filter(MapTable.name == name).all()
for duplicate_map_table in duplicate_map_tables:
if duplicate_map_table.indexMap:
session.delete(duplica... | Remove duplicate map table if it exists |
382,718 | def expect_keyword(parser, value):
token = parser.token
if token.kind == TokenKind.NAME and token.value == value:
advance(parser)
return token
raise GraphQLSyntaxError(
parser.source,
token.start,
u.format(value, get_token_desc(token)),
) | If the next token is a keyword with the given value, return that
token after advancing the parser. Otherwise, do not change the parser
state and return False. |
382,719 | def update_service_definitions(self, service_definitions):
content = self._serialize.body(service_definitions, )
self._send(http_method=,
location_id=,
version=,
content=content) | UpdateServiceDefinitions.
[Preview API]
:param :class:`<VssJsonCollectionWrapper> <azure.devops.v5_0.location.models.VssJsonCollectionWrapper>` service_definitions: |
382,720 | def has_nvme_ssd(system_obj):
storage_value = False
storage_resource = _get_attribute_value_of(system_obj, )
if storage_resource is not None:
storage_value = _get_attribute_value_of(
storage_resource, , default=False)
return storage_value | Gets if the system has any drive as NVMe SSD drive
:param system_obj: The HPESystem object.
:returns True if system has SSD drives and protocol is NVMe. |
382,721 | def _helper(result,
graph,
number_edges_remaining: int,
node_blacklist: Set[BaseEntity],
invert_degrees: Optional[bool] = None,
):
original_node_count = graph.number_of_nodes()
log.debug(, number_edges_remaining)
for _ in range(number_edges_r... | Help build a random graph.
:type result: networkx.Graph
:type graph: networkx.Graph |
382,722 | def search(self, args):
kwargs = {}
for a in args:
k, v = a.split()
kwargs[k] = v
return self._paged_api_call(self.flickr.photos_search, kwargs) | Executes a search
flickr:(credsfile),search,(arg1)=(val1),(arg2)=(val2)... |
382,723 | def process_csxml_file(self, filename, interval=None, lazy=False):
if interval is None:
interval = (None, None)
tmp_fname = tempfile.mktemp(os.path.basename(filename))
fix_character_encoding(filename, tmp_fname)
self.__f = open(tmp_fname, )
self._gen = self... | Processes a filehandle to MedScan csxml input into INDRA
statements.
The CSXML format consists of a top-level `<batch>` root element
containing a series of `<doc>` (document) elements, in turn containing
`<sec>` (section) elements, and in turn containing `<sent>` (sentence)
elem... |
382,724 | def report_error(self, line_number, offset, text, check):
if options.quiet == 1 and not self.file_errors:
message(self.filename)
self.file_errors += 1
code = text[:4]
options.counters[code] = options.counters.get(code, 0) + 1
options.messages[code] = text[5:]... | Report an error, according to options. |
382,725 | def _prep_ssh(
self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type=,
kwarg=None,
**kwargs):
opts = copy.deepcopy(self.opts)
opts.update(kwargs)
if timeout:
opts[] = timeout
arg... | Prepare the arguments |
382,726 | def gradient(self):
r
functional = self
class KLGradient(Operator):
def __init__(self):
super(KLGradient, self).__init__(
functional.domain, functional.domain, linear=False)
def _call(self, x):
... | r"""Gradient of the KL functional.
The gradient of `KullbackLeibler` with ``prior`` :math:`g` is given
as
.. math::
\nabla F(x) = 1 - \frac{g}{x}.
The gradient is not defined in points where one or more components
are non-positive. |
382,727 | def __software_to_pkg_id(self, publisher, name, is_component, is_32bit):
if publisher:
pub_lc = publisher.replace(, ).lower()
else:
pub_lc =
if name:
name_lc = name.replace(, ).lower()
else:
... | Determine the Package ID of a software/component using the
software/component ``publisher``, ``name``, whether its a software or a
component, and if its 32bit or 64bit archiecture.
Args:
publisher (str): Publisher of the software/component.
name (str): Name of the softwa... |
382,728 | def remove_range(self, start, end):
return self._sl.remove_range(
start, end, callback=lambda sc, value: self._dict.pop(value)) | Remove a range by score. |
382,729 | def disassemble(qobj):
run_config = qobj.config.to_dict()
user_qobj_header = qobj.header.to_dict()
circuits = _experiments_to_circuits(qobj)
return circuits, run_config, user_qobj_header | Dissasemble a qobj and return the circuits, run_config, and user header
Args:
qobj (Qobj): The input qobj object to dissasemble
Returns:
circuits (list): A list of quantum circuits
run_config (dict): The dist of the run config
user_qobj_header (dict): The dict of any user header... |
382,730 | def t_INDENTIFIER(t):
r
if t.value in reserved:
t.type = t.value.upper()
if t.value in reservedMap:
t.value = reservedMap[t.value]
elif t.value in strStatment:
t.type =
return t | r'(\$?[_a-zA-Z][_a-zA-Z0-9]*)|(__[A-Z_]+__) |
382,731 | def updateAnomalyLikelihoods(anomalyScores,
params,
verbosity=0):
if verbosity > 3:
print("In updateAnomalyLikelihoods.")
print("Number of anomaly scores:", len(anomalyScores))
print("First 20:", anomalyScores[0:min(20, len(anomalyScores))])
... | Compute updated probabilities for anomalyScores using the given params.
:param anomalyScores: a list of records. Each record is a list with the
following three elements: [timestamp, value, score]
Example::
[datetime.datetime(2013, 8, 10, 2... |
382,732 | def select_many(self, *args):
s = apply_query_operators(self.storage, args)
if isinstance(s, QuerySet):
return s
else:
return QuerySet(s) | Select several instances from the instance pool. Query operators such as
where_eq(), order_by() or filter functions may be passed as optional
arguments. |
382,733 | def generate_kmers(seq, k=4):
if isinstance(seq, basestring):
for i in range(len(seq) - k + 1):
yield seq[i:i + k]
elif isinstance(seq, (int, float, Decimal)):
for s in generate_kmers(str(seq)):
yield s
else:
for s in seq:
yield generate_kmers... | Return a generator of all the unique substrings (k-mer or q-gram strings) within a sequence/string
Not effiicent for large k and long strings.
Doesn't form substrings that are shorter than k, only exactly k-mers
Used for algorithms like UniqTag for genome unique identifier locality sensitive hashing.
... |
382,734 | def get_locations(self, url):
if not is_valid_url(url):
raise InvalidURLError(.format(url))
try:
response = self.session.head(url)
except (ConnectionError, InvalidSchema, Timeout):
raise StopIteration
try:
generator = self.session.... | Get valid location header values from responses.
:param url: a URL address. If a HEAD request sent to it
fails because the address has invalid schema, times out
or there is a connection error, the generator yields nothing.
:returns: valid redirection addresses. If a request for
... |
382,735 | def std(self):
std_expr = grizzly_impl.groupby_std(
[self.column],
[self.column_type],
self.grouping_columns,
self.grouping_column_types
)
unzipped_columns = grizzly_impl.unzip_columns(
std_expr,
self.grouping_colum... | Standard deviation
Note that is by default normalizd by n - 1
# TODO, what does pandas do for multiple grouping columns?
# Currently we are just going to use one grouping column |
382,736 | def evaluate_and_log_bleu(estimator, bleu_writer, bleu_source, bleu_ref):
subtokenizer = tokenizer.Subtokenizer(
os.path.join(FLAGS.data_dir, FLAGS.vocab_file))
uncased_score, cased_score = translate_and_compute_bleu(
estimator, subtokenizer, bleu_source, bleu_ref)
print("Bleu score (uncased):", ... | Calculate and record the BLEU score. |
382,737 | def add_project_name_or_id_arg(arg_parser, required=True, help_text_suffix="manage"):
project_name_or_id = arg_parser.add_mutually_exclusive_group(required=required)
name_help_text = "Name of the project to {}.".format(help_text_suffix)
add_project_name_arg(project_name_or_id, required=False, help_text... | Adds project name or project id argument. These two are mutually exclusive.
:param arg_parser:
:param required:
:param help_text:
:return: |
382,738 | def _parse_jetconfig(self):
conf = env(, None)
if not conf:
return
import urlparse
auth = None
port = None
conf = conf.split().pop()
entry = urlparse.urlparse(conf)
scheme = entry.scheme
host = entry.netloc or entry.path | Undocumented cross-compatability functionality with jetconfig
(https://github.com/shakefu/jetconfig) that is very sloppy. |
382,739 | def clear_samples(self):
self._lastclear = self.niterations
self._itercounter = 0
self._sampler.reset() | Clears the chain and blobs from memory. |
382,740 | def jitter_run(res, rstate=None, approx=False):
if rstate is None:
rstate = np.random
nsamps, samples_n = _get_nsamps_samples_n(res)
logl = res.logl
nunif = len(nlive_start)
for i in range(nunif):
nstart = nlive_start[i]
bound = bounds[i]... | Probes **statistical uncertainties** on a nested sampling run by
explicitly generating a *realization* of the prior volume associated
with each sample (dead point). Companion function to :meth:`resample_run`
and :meth:`simulate_run`.
Parameters
----------
res : :class:`~dynesty.results.Results`... |
382,741 | def create_vpc(self):
self.create_stack(
self.vpc_name,
,
parameters=define_parameters(
VpcBlock="10.42.0.0/16",
Subnet01Block="10.42.1.0/24",
Subnet02Block="10.42.2.0/24",
Subnet03Block="10.42.3.0/24"
... | Create a virtual private cloud on Amazon's Web services configured
for deploying JupyterHubs. |
382,742 | def resizeEvent(self, event):
self.resized.emit()
return super(MetadataConverterDialog, self).resizeEvent(event) | Emit custom signal when the window is re-sized.
:param event: The re-sized event.
:type event: QResizeEvent |
382,743 | def _tp__get_typed_properties(self):
try:
return tuple(getattr(self, p) for p in self._tp__typed_properties)
except AttributeError:
raise NotImplementedError | Return a tuple of typed attrs that can be used for comparisons.
Raises:
NotImplementedError: Raised if this class was mixed into a class
that was not created by _AnnotatedObjectMeta. |
382,744 | def save(evt, designer):
"Basic save functionality: just replaces the gui code"
ok = gui.confirm("Save the changes?", "GUI2PY Designer",
cancel=True, default=True)
if ok:
wx_obj = evt.GetEventObject()
w = wx_obj.obj
try:
if DEBUG: print "saving... | Basic save functionality: just replaces the gui code |
382,745 | def get_items(self, container_id, scope=None, item_path=None, metadata=None, format=None, download_file_name=None, include_download_tickets=None, is_shallow=None):
route_values = {}
if container_id is not None:
route_values[] = self._serialize.url(, container_id, )
query_par... | GetItems.
[Preview API]
:param long container_id:
:param str scope:
:param str item_path:
:param bool metadata:
:param str format:
:param str download_file_name:
:param bool include_download_tickets:
:param bool is_shallow:
:rtype: [FileCon... |
382,746 | def pip_command_output(pip_args):
import sys
import pip
from io import StringIO
old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()
pip.main(pip_args)
output = mystdout.getvalue()
mystdout.truncate(0)
sys.stdout = old_stdout
return output | Get output (as a string) from pip command
:param pip_args: list o pip switches to pass
:return: string with results |
382,747 | def strip_praw_submission(cls, sub):
reddit_link = re.compile(
r)
author = getattr(sub, , )
name = getattr(author, , )
flair = getattr(sub, , )
data = {}
data[] = sub
data[] =
data[] = sub.title
data[] = sub.selftext
... | Parse through a submission and return a dict with data ready to be
displayed through the terminal.
Definitions:
permalink - URL to the reddit page with submission comments.
url_full - URL that the submission points to.
url - URL that will be displayed on the subreddi... |
382,748 | def replace(self, year=None, week=None):
return self.__class__(self.year if year is None else year,
self.week if week is None else week) | Return a Week with either the year or week attribute value replaced |
382,749 | def shadow_calc(data):
up_shadow = abs(data.high - (max(data.open, data.close)))
down_shadow = abs(data.low - (min(data.open, data.close)))
entity = abs(data.open - data.close)
towards = True if data.open < data.close else False
print( * 15)
print(.format(up_shadow))
print(.format(down... | 计算上下影线
Arguments:
data {DataStruct.slice} -- 输入的是一个行情切片
Returns:
up_shadow {float} -- 上影线
down_shdow {float} -- 下影线
entity {float} -- 实体部分
date {str} -- 时间
code {str} -- 代码 |
382,750 | def not_(self, value, name=):
if isinstance(value.type, types.VectorType):
rhs = values.Constant(value.type, (-1,) * value.type.count)
else:
rhs = values.Constant(value.type, -1)
return self.xor(value, rhs, name=name) | Bitwise integer complement:
name = ~value |
382,751 | def _load(self, url, verbose):
msg = u"_load url: %s" % url
self._last_query_str = url
log.debug(msg)
if verbose:
print msg
response = self.__api__.request(url)
return response | Execute a request against the Salesking API to fetch the items
:param url: url to fetch
:return response
:raises SaleskingException with the corresponding http errors |
382,752 | def value_ranges(self, value_ranges):
intfloat
self._value_ranges = value_ranges
self._logger.log(, .format(
value_ranges
)) | Set the types, min/max values for tunable parameters
Args:
value_ranges (list): each element defines a tunable variable in
the form "(type ('int' or 'float'), (min_val, max_val))";
initial, random values for each bee will between "min_val" and
"max_va... |
382,753 | def stretch_cv(x,sr,sc,interpolation=cv2.INTER_AREA):
if sr==0 and sc==0: return x
r,c,*_ = x.shape
x = cv2.resize(x, None, fx=sr+1, fy=sc+1, interpolation=interpolation)
nr,nc,*_ = x.shape
cr = (nr-r)//2; cc = (nc-c)//2
return x[cr:r+cr, cc:c+cc] | Stretches image x horizontally by sr+1, and vertically by sc+1 while retaining the original image size and proportion. |
382,754 | def setConnStringForWindows():
global _dbConnectString
from peek_platform.file_config.PeekFileConfigABC import PeekFileConfigABC
from peek_platform.file_config.PeekFileConfigSqlAlchemyMixin import \
PeekFileConfigSqlAlchemyMixin
from peek_platform import PeekPlatformConfig
class _Worke... | Set Conn String for Windiws
Windows has a different way of forking processes, which causes the
@worker_process_init.connect signal not to work in "CeleryDbConnInit" |
382,755 | def list_jobs(self, argument_filters=None):
.functionmust_containdebugdebug.id.function.name.dt.interval.month.day.weekday.hour.minute.second.start_date.end_date.id.function.name.dtstartend.interval.month.day.weekday.hour.minute.second
title = % self.__class__.__name__
if argument... | a method to list jobs in the scheduler
:param argument_filters: list of query criteria dictionaries for class argument keys
:return: list of jobs (which satisfy the filters)
NOTE: query criteria architecture
each item in the argument filters list must be a dictionary
... |
382,756 | def recover_devices(cls):
if "_devices" in globals():
return
global _devices
confs_dir = os.path.abspath(os.path.normpath(cfg.CONF.dhcp_confs))
for netid in os.listdir(confs_dir):
conf_dir = os.path.join(confs_dir, netid)
intf_filename = os.... | Track devices.
Creates global dict to track device names across driver invocations
and populates based on current devices configured on the system. |
382,757 | def get_profile(A):
"Fail-soft profile getter; if no profile is present assume none and quietly ignore."
try:
with open(os.path.expanduser(A.profile)) as I:
profile = json.load(I)
return profile
except:
return {} | Fail-soft profile getter; if no profile is present assume none and quietly ignore. |
382,758 | def badge_label(self, badge):
kind = badge.kind if isinstance(badge, Badge) else badge
return self.__badges__[kind] | Display the badge label for a given kind |
382,759 | def _upload(auth_http, project_id, bucket_name, file_path, object_name, acl):
with open(file_path, ) as f:
data = f.read()
content_type, content_encoding = mimetypes.guess_type(file_path)
headers = {
: project_id,
: API_VERSION,
: acl,
: % len(data)
}
i... | Uploads a file to Google Cloud Storage.
Args:
auth_http: An authorized httplib2.Http instance.
project_id: The project to upload to.
bucket_name: The bucket to upload to.
file_path: Path to the file to upload.
object_name: The name within the bucket to upload to.
acl... |
382,760 | def expand_tpm(tpm):
unconstrained = np.ones([2] * (tpm.ndim - 1) + [tpm.shape[-1]])
return tpm * unconstrained | Broadcast a state-by-node TPM so that singleton dimensions are expanded
over the full network. |
382,761 | def _finalize_step(self):
t = time.time()
if self._callback is not None:
self._callback(self.age)
t2 = time.time()
self._step_processing_time += t2 - t
self._log(logging.INFO, "Step {} run in: {:.3f}s ({:.3f}s of "
"actual processing time us... | Finalize simulation step after all agents have acted for the current
step. |
382,762 | def apply_gemm(scope, input_name, output_name, container, operator_name=None, alpha=1.0, beta=1.0,
transA=0, transB=0):
name = _create_name_or_use_existing_one(scope, , operator_name)
attrs = {: alpha, : beta, : transA, : transB}
if container.target_opset < 5:
attrs[] = 1
... | Applies operator `gemm <https://github.com/onnx/onnx/blob/master/docs/Operators.md#gemm>`. |
382,763 | def terminate_process(self, idf):
try:
p = self.q.pop(idf)
p.terminate()
return p
except:
return None | Terminate a process by id |
382,764 | def qsnorm(p):
d = p
if d < 0. or d > 1.:
print()
sys.exit()
x = 0.
if (d - 0.5) > 0:
d = 1. - d
if (d - 0.5) < 0:
t2 = -2. * np.log(d)
t = np.sqrt(t2)
x = t - old_div((2.515517 + .802853 * t + .010328 * t2),
(1. + 1.432788... | rational approximation for x where q(x)=d, q being the cumulative
normal distribution function. taken from Abramowitz & Stegun p. 933
|error(x)| < 4.5*10**-4 |
382,765 | def CountFlowOutputPluginLogEntries(self,
client_id,
flow_id,
output_plugin_id,
with_type=None):
return len(
self.ReadFlowOutputPluginLogEntries(
... | Returns number of flow output plugin log entries of a given flow. |
382,766 | def _is_valid_duration(self, inpt, metadata):
from dlkit.abstract_osid.calendaring.primitives import Duration as abc_duration
if isinstance(inpt, abc_duration):
return True
else:
return False | Checks if input is a valid Duration |
382,767 | def md5(self, raw_output=False):
res = hashlib.md5(str(self.generator.random.random()).encode())
if raw_output:
return res.digest()
return res.hexdigest() | Calculates the md5 hash of a given string
:example 'cfcd208495d565ef66e7dff9f98764da' |
382,768 | def get_mcu_definition(self, project_file):
project_file = join(getcwd(), project_file)
uvproj_dic = xmltodict.parse(file(project_file), dict_constructor=dict)
mcu = MCU_TEMPLATE
try:
mcu[] = {
: {
: {
... | Parse project file to get mcu definition |
382,769 | def get_all_chats(self):
chats = self.wapi_functions.getAllChats()
if chats:
return [factory_chat(chat, self) for chat in chats]
else:
return [] | Fetches all chats
:return: List of chats
:rtype: list[Chat] |
382,770 | def notices(self):
return [self._db.notices.pop()[8:].strip() for x in range(len(self._db.notices))] | pops and returns all notices
http://initd.org/psycopg/docs/connection.html#connection.notices |
382,771 | def get_config_directory():
from .commands.stacker import Stacker
command = Stacker()
namespace = command.parse_args()
return os.path.dirname(namespace.config.name) | Return the directory the config file is located in.
This enables us to use relative paths in config values. |
382,772 | def simple_generate_batch(cls, create, size, **kwargs):
strategy = enums.CREATE_STRATEGY if create else enums.BUILD_STRATEGY
return cls.generate_batch(strategy, size, **kwargs) | Generate a batch of instances.
These instances will be either 'built' or 'created'.
Args:
size (int): the number of instances to generate
create (bool): whether to 'build' or 'create' the instances.
Returns:
object list: the generated instances |
382,773 | def Nu_Mokry(Re, Pr, rho_w=None, rho_b=None):
r
Nu = 0.0061*Re**0.904*Pr**0.684
if rho_w and rho_b:
Nu *= (rho_w/rho_b)**0.564
return Nu | r'''Calculates internal convection Nusselt number for turbulent vertical
upward flow in a pipe under supercritical conditions according to [1]_,
and reviewed in [2]_.
.. math::
Nu_b = 0.0061 Re_b^{0.904} \bar{Pr}_b^{0.684}
\left(\frac{\rho_w}{\rho_b}\right)^{0.564}
... |
382,774 | def sample(self, nsims=1000):
if self.latent_variables.estimation_method not in [, ]:
raise Exception("No latent variables estimated!")
else:
lv_draws = self.draw_latent_variables(nsims=nsims)
sigmas = [self._model(lv_draws[:,i])[0] for i in range(nsims)... | Samples from the posterior predictive distribution
Parameters
----------
nsims : int (default : 1000)
How many draws from the posterior predictive distribution
Returns
----------
- np.ndarray of draws from the data |
382,775 | def ASRS(self, params):
try:
Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_COMMA_SEPARATED, params)
except iarm.exceptions.ParsingError:
Rb, Rc = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params)
Ra =... | ASRS [Ra,] Ra, Rc
ASRS [Ra,] Rb, #imm5_counting
Arithmetic shift right Rb by Rc or imm5_counting and store the result in Ra
imm5 counting is [1, 32]
In the register shift, the first two operands must be the same register
Ra, Rb, and Rc must be low registers
If Ra is omit... |
382,776 | def compile(self):
from ..engines import get_default_engine
engine = get_default_engine(self)
return engine.compile(self) | Compile this expression into an ODPS SQL
:return: compiled DAG
:rtype: str |
382,777 | def how_long(length=4, choices=len(words), speed=1000 * 1000 * 1000 * 1000,
optimism=2):
return ((choices ** length) / (speed * optimism)) | How long might it take to guess a password?
@param length: the number of words that we're going to choose.
@type length: L{int}
@param choice: the number of words we might choose between.
@type choice: L{int}
@param speed: the speed of our hypothetical password guesser, in guesses
per sec... |
382,778 | def get_as_string(self, key):
value = self.get(key)
return StringConverter.to_string(value) | Converts map element into a string or returns "" if conversion is not possible.
:param key: an index of element to get.
:return: string value ot the element or "" if conversion is not supported. |
382,779 | def missing_particle(separation=0.0, radius=RADIUS, SNR=20):
s = init.create_two_particle_state(imsize=6*radius+4, axis=, sigma=1.0/SNR,
delta=separation, radius=radius, stateargs={: True}, psfargs={: 1e-6})
s.obj.typ[1] = 0.
s.reset()
return s, s.obj.pos.copy() | create a two particle state and compare it to featuring using a single particle guess |
382,780 | def get_group_member_profile(self, group_id, user_id, timeout=None):
response = self._get(
.format(group_id=group_id, user_id=user_id),
timeout=timeout
)
return Profile.new_from_json_dict(response.json) | Call get group member profile API.
https://devdocs.line.me/en/#get-group-room-member-profile
Gets the user profile of a member of a group that
the bot is in. This can be the user ID of a user who has
not added the bot as a friend or has blocked the bot.
:param str group_id: Gr... |
382,781 | def locate(self, pattern):
top_matches = self.top.locate(pattern)
bottom_matches = self.bottom.locate(pattern)
return [top_matches, bottom_matches] | Find sequences matching a pattern. For a circular sequence, the
search extends over the origin.
:param pattern: str or NucleicAcidSequence for which to find matches.
:type pattern: str or coral.DNA
:returns: A list of top and bottom strand indices of matches.
:rtype: list of lis... |
382,782 | def _hmmalign(self, input_path, directions, pipeline,
forward_reads_output_path, reverse_reads_output_path):
if pipeline == PIPELINE_AA:
reverse_direction_reads_present=False
else:
reverse_direction_reads_present=False in directions.values()
wi... | Align reads to the aln_hmm. Receives unaligned sequences and
aligns them.
Parameters
----------
input_path : str
Filename of unaligned hits to be aligned
directions : dict
dictionary containing read names as keys, and complement
as the entry (... |
382,783 | def get_stp_mst_detail_output_msti_instance_id(self, **kwargs):
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
... | Auto Generated Code |
382,784 | def get_bounds(self, bin_num):
min_value = pow(2.0, float(bin_num) / 2.0) * self.min_value
max_value = pow(2.0, float(bin_num + 1.0) / 2.0) * self.min_value
return self.Bounds(min_value, max_value) | Get the bonds of a bin, given its index `bin_num`.
:returns: a `Bounds` namedtuple with properties min and max
respectively. |
382,785 | def sphgen(self, force_rerun=False):
log.debug(.format(self.id))
if not self.dms_path:
return ValueError()
sph = op.join(self.dock_dir, .format(self.id))
insph = op.join(self.dock_dir, )
if ssbio.utils.force_rerun(flag=force_rerun, outfile=sph):
... | Create sphere representation (sph file) of receptor from the surface representation
Args:
force_rerun (bool): If method should be rerun even if output file exists |
382,786 | def generate_config_parser(config, include_all=False):
config_parser = SafeConfigParser(allow_no_value=True)
for section_name, option_name in _get_included_schema_sections_options(config, include_all):
if not config_parser.has_section(section_name):
config_parser.add_section(sect... | Generates a config parser from a configuration dictionary.
The dictionary contains the merged informations of the schema and,
optionally, of a source configuration file. Values of the source
configuration file will be stored in the *value* field of an option. |
382,787 | def filter_tess_lcdict(lcdict,
filterqualityflags=True,
nanfilter=,
timestoignore=None,
quiet=False):
sappdcsap,pdct caught by the quality
flags.
Returns
-------
lcdict
Returns an `lcdict` (this... | This filters the provided TESS `lcdict`, removing nans and bad
observations.
By default, this function removes points in the TESS LC that have ANY
quality flags set.
Parameters
----------
lcdict : lcdict
An `lcdict` produced by `consolidate_tess_fitslc` or
`read_tess_fitslc`.
... |
382,788 | def status_pipeline(conf, args):
host = conf.config[][args.host_instance]
url = api.build_pipeline_url(build_instance_url(host))
auth = tuple([conf.creds[][args.host_instance][], conf.creds[][args.host_instance][]])
verify_ssl = host.get(, True)
status_result = api.pipeline_status(url, args.pi... | Stop a pipeline. |
382,789 | async def set_lock(self, resource, lock_identifier):
start_time = time.time()
lock_timeout = self.lock_timeout
successes = await asyncio.gather(*[
i.set_lock(resource, lock_identifier, lock_timeout) for
i in self.instances
], return_exceptions=True)
... | Tries to set the lock to all the redis instances
:param resource: The resource string name to lock
:param lock_identifier: The id of the lock. A unique string
:return float: The elapsed time that took to lock the instances
in seconds
:raises: LockError if the lock has not be... |
382,790 | def requires_authentication(func):
def _auth(self, *args, **kwargs):
if not self._authenticated:
raise NotAuthenticatedException(
.format(func.__name__)
+ )
else:
... | Function decorator that throws an exception if the user
is not authenticated, and executes the function normally
if the user is authenticated. |
382,791 | def linear_connection(plist, lane):
logger.debug(
"Establishing linear connection with processes: {}".format(plist))
res = []
previous = None
for p in plist:
if not previous:
previous = p
continue
res.append({
"input": {
... | Connects a linear list of processes into a list of dictionaries
Parameters
----------
plist : list
List with process names. This list should contain at least two entries.
lane : int
Corresponding lane of the processes
Returns
-------
res : list
List of dictionaries ... |
382,792 | def open_url(url, httpuser=None, httppassword=None, method=None):
if os.getenv() == :
log.debug()
try:
sslctx = ssl.create_default_context()
except Exception as e:
log.error( % e)
raise Stop(
)
sslctx.... | Open a URL using an opener that will simulate a browser user-agent
url: The URL
httpuser, httppassword: HTTP authentication credentials (either both or
neither must be provided)
method: The HTTP method
Caller is reponsible for calling close() on the returned object |
382,793 | def update_field(self, elements):
changed = False
if isinstance(elements, list):
if self.is_any or self.is_none:
self.add_many(elements)
changed = True
else:
_elements = element_resolver(elements, do_raise=False)
... | Update the field with a list of provided values but only if the values
are different. Return a boolean indicating whether a change was made
indicating whether `save` should be called. If the field is currently
set to any or none, then no comparison is made and field is updated.
... |
382,794 | def dispatch(self, frame):
t need the rest of
the stack.
'
if frame.type() == HeartbeatFrame.type():
self.send_heartbeat()
elif frame.type() == MethodFrame.type():
if frame.class_id == 10:
cb = self._method_map.get(frame.method_id)
... | Override the default dispatch since we don't need the rest of
the stack. |
382,795 | def infer_batch(self, dataloader):
sum_losses = 0
len_losses = 0
for input_data, input_label in dataloader:
data = gluon.utils.split_and_load(input_data, self.ctx, even_split=False)
label = gluon.utils.split_and_load(input_label, self.ctx, even_split=False)
... | Description : inference for LipNet |
382,796 | def get_js(self):
js_file = os.path.join(self.theme_dir, , )
if not os.path.exists(js_file):
js_file = os.path.join(THEMES_DIR, , , )
if not os.path.exists(js_file):
raise IOError(u"Cannot find slides.js in default theme")
with codecs.open(js_fi... | Fetches and returns javascript file path or contents, depending if
we want a standalone presentation or not. |
382,797 | def getnamedargs(*args, **kwargs):
adict = {}
for arg in args:
if isinstance(arg, dict):
adict.update(arg)
adict.update(kwargs)
return adict | allows you to pass a dict and named args
so you can pass ({'a':5, 'b':3}, c=8) and get
dict(a=5, b=3, c=8) |
382,798 | def EndEdit(self, row, col, grid, oldVal=None):
self._tc.Unbind(wx.EVT_KEY_UP)
self.ApplyEdit(row, col, grid)
del self._col
del self._row
del self._grid | End editing the cell. This function must check if the current
value of the editing control is valid and different from the
original value (available as oldval in its string form.) If
it has not changed then simply return None, otherwise return
the value in its string form.
*Mus... |
382,799 | def copy_(name,
source,
force=False,
makedirs=False,
preserve=False,
user=None,
group=None,
mode=None,
subdir=False,
**kwargs):
t exist create them
preserve
.. versionadded:: 2015.5.0
Set ``preserve: True... | If the file defined by the ``source`` option exists on the minion, copy it
to the named path. The file will not be overwritten if it already exists,
unless the ``force`` option is set to ``True``.
.. note::
This state only copies files from one location on a minion to another
location on th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.