Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
358,500 | def update(self):
update_mask_pb = field_mask_pb2.FieldMask()
if self.display_name is not None:
update_mask_pb.paths.append("display_name")
if self.type_ is not None:
update_mask_pb.paths.append("type")
if self.labels is not None:
update_mask_... | Updates an instance within a project.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_update_instance]
:end-before: [END bigtable_update_instance]
.. note::
Updates any or all of the following values:
``display_name``... |
358,501 | def times(self, func, *args):
n = self.obj
i = 0
while n is not 0:
n -= 1
func(i)
i += 1
return self._wrap(func) | Run a function **n** times. |
358,502 | def getConfig(self):
config = {}
config["name"] = self.city
config["intervals"] = self.__intervals
config["last_date"] = self.__lastDay
config["excludedUsers"] = []
config["excludedLocations"] = []
for e in self.__excludedUsers:
config["exclu... | Return the configuration of the city.
:return: configuration of the city.
:rtype: dict. |
358,503 | def getParameter(self, name, index=-1):
if name == "patternCount":
return self._knn._numPatterns
elif name == "patternMatrix":
return self._getPatternMatrix()
elif name == "k":
return self._knn.k
elif name == "distanceNorm":
return self._knn.distanceNorm
elif name == "di... | Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getParameter`. |
358,504 | def locate_key(self, key):
left = bisect.bisect_left(self, key)
right = bisect.bisect_right(self, key)
diff = right - left
if diff == 0:
raise KeyError(key)
elif diff == 1:
return left
else:
return slice(left, right) | Get index location for the requested key.
Parameters
----------
key : object
Value to locate.
Returns
-------
loc : int or slice
Location of `key` (will be slice if there are duplicate entries).
Examples
--------
>>> imp... |
358,505 | def check_status(status, expected, path, headers=None,
resp_headers=None, body=None, extras=None):
if status in expected:
return
msg = (
%
(expected, status, path, headers, resp_headers, body, extras))
if status == httplib.UNAUTH... | Check HTTP response status is expected.
Args:
status: HTTP response status. int.
expected: a list of expected statuses. A list of ints.
path: filename or a path prefix.
headers: HTTP request headers.
resp_headers: HTTP response headers.
body: HTTP response body.
extras: extra info to be l... |
358,506 | def compat_serializer_attr(serializer, obj):
if DRFVLIST[0] == 3 and DRFVLIST[1] == 1:
for i in serializer.instance:
if i.id == obj.id:
return i
else:
return obj | Required only for DRF 3.1, which does not make dynamically added attribute available in obj in serializer.
This is a quick solution but works without breajing anything. |
358,507 | def ensure_one_opt_multi_ifo(opt, parser, ifo, opt_list):
the_one = None
for name in opt_list:
attr = name[2:].replace(, )
try:
if getattr(opt, attr)[ifo] is None:
raise KeyError
except KeyError:
pass
else:
if the_one is N... | Check that one and only one in the opt_list is defined in opt
Parameters
----------
opt : object
Result of option parsing
parser : object
OptionParser instance.
opt_list : list of strings |
358,508 | def sumvalues(self, q=0):
if q == 0:
return self._totalf
else:
return -np.partition(-self._freq_list, q)[:q].sum() | Sum of top q passowrd frequencies |
358,509 | def restart(self, wait=True, timeout=None, wait_polling_interval=None):
self.stop(timeout=timeout)
self.start(wait, timeout=timeout, wait_polling_interval=wait_polling_interval) | Restart b2g, waiting for the adb connection to become stable.
:param timeout: Maximum time to wait for restart.
:param wait_polling_interval: Interval at which to poll for device readiness. |
358,510 | def update_frequency(shell_ctx):
frequency_path = os.path.join(shell_ctx.config.get_config_dir(), shell_ctx.config.get_frequency())
if os.path.exists(frequency_path):
with open(frequency_path, ) as freq:
try:
frequency = json.load(freq)
except ValueError:
... | updates the frequency from files |
358,511 | def get_translated_file(fapi, file_uri, locale, retrieval_type, include_original_strings, use_cache, cache_dir=None):
file_data = None
cache_name = str(file_uri)+"."+str(locale)+"."+str(retrieval_type)+"."+str(include_original_strings)
cache_file = os.path.join(cache_dir, sha1(cache_name)) if cache_dir... | Returns a translated file from smartling |
358,512 | def second_order_score(y, mean, scale, shape, skewness):
return ((y-mean)/float(scale*np.abs(y-mean))) / (-(np.power(y-mean,2) - np.power(np.abs(mean-y),2))/(scale*np.power(np.abs(mean-y),3))) | GAS Laplace Update term potentially using second-order information - native Python function
Parameters
----------
y : float
datapoint for the time series
mean : float
location parameter for the Laplace distribution
scale : float
scale parame... |
358,513 | def _nextOn(self, request):
retval = None
nextDt, event = self.__localAfterOrPostponedTo(timezone.localtime(),
dt.time.min)
if nextDt is not None:
timeFrom = nextDt.time() if event.time_from is not None else None
... | Formatted date/time of when this event (including any postponements)
will next be on |
358,514 | def AND(cpu, dest, src):
if src.size == 64 and src.type == and dest.size == 64:
arg1 = Operators.SEXTEND(src.read(), 32, 64)
else:
arg1 = src.read()
res = dest.write(dest.read() & arg1)
cpu._calculate_logic_flags(dest.size, res... | Logical AND.
Performs a bitwise AND operation on the destination (first) and source
(second) operands and stores the result in the destination operand location.
Each bit of the result is set to 1 if both corresponding bits of the first and
second operands are 1; otherwise, it is set to ... |
358,515 | def save(self, directory, parameters=):
def _save_power_flow_results(target_dir):
if self.pfa_v_mag_pu is not None:
os.makedirs(target_dir, exist_ok=True)
self.pfa_v_mag_pu.to_csv(
os.path.join(target_dir... | Saves results to disk.
Depending on which results are selected and if they exist, the
following directories and files are created:
* `powerflow_results` directory
* `voltages_pu.csv`
See :py:attr:`~pfa_v_mag_pu` for more information.
* `currents.csv`
... |
358,516 | def find_resources(self, rsrc_type, sort=None, yield_pages=False, **kwargs):
return rsrc_type.find(self, sort=sort, yield_pages=yield_pages, **kwargs) | Find instances of `rsrc_type` that match the filter in `**kwargs` |
358,517 | def discriminator(self, imgs, y):
yv = y
y = tf.reshape(y, [-1, 1, 1, 10])
with argscope(Conv2D, kernel_size=5, strides=1):
l = (LinearWrap(imgs)
.ConcatWith(tf.tile(y, [1, 28, 28, 1]), 3)
.Conv2D(, 11)
.tf.nn.leaky_relu()
... | return a (b, 1) logits |
358,518 | def get_agent_data(self, queues=None, edge=None, edge_type=None, return_header=False):
queues = _get_queues(self.g, queues, edge, edge_type)
data = {}
for qid in queues:
for agent_id, dat in self.edge2queue[qid].data.items():
datum = np.zeros((len(dat), 6))
... | Gets data from queues and organizes it by agent.
If none of the parameters are given then data from every
:class:`.QueueServer` is retrieved.
Parameters
----------
queues : int or *array_like* (optional)
The edge index (or an iterable of edge indices) identifying
... |
358,519 | def set_icon(self, icon_url):
log = logging.getLogger(self.cls_logger + )
if not isinstance(icon_url, basestring):
msg =
log.error(msg)
raise ValueError(msg)
self.payload[] = icon_url
log.debug(.format(u=icon_url)) | Sets the icon_url for the message
:param icon_url: (str) Icon URL
:return: None |
358,520 | def detach_securitygroup_components(self, group_id, component_ids):
return self.security_group.detachNetworkComponents(component_ids,
id=group_id) | Detaches network components from a security group.
:param int group_id: The ID of the security group
:param list component_ids: The IDs of the network components to detach |
358,521 | def path():
try:
directory = os.environ["DID_DIR"]
except KeyError:
directory = CONFIG
filename = "config"
matched = re.search("--confi?g?[ =](\S+)", " ".join(sys.argv))
if matched:
filename = matched.groups()[0]
... | Detect config file path |
358,522 | def exp(x, context=None):
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_exp,
(BigFloat._implicit_convert(x),),
context,
) | Return the exponential of x. |
358,523 | def _normalized_mutual_info_score(reference_indices, estimated_indices):
ref_classes = np.unique(reference_indices)
est_classes = np.unique(estimated_indices)
if (ref_classes.shape[0] == est_classes.shape[0] == 1 or
ref_classes.shape[0] == est_classes.shape[0] == 0):
retur... | Compute the mutual information between two sequence labelings, adjusted for
chance.
Parameters
----------
reference_indices : np.ndarray
Array of reference indices
estimated_indices : np.ndarray
Array of estimated indices
Returns
-------
nmi : float <= 1.0
Norm... |
358,524 | def _get_ipv4_from_binary(self, bin_addr):
return socket.inet_ntop(socket.AF_INET, struct.pack("!L", bin_addr)) | Converts binary address to Ipv4 format. |
358,525 | def encrypt(cls, private_key, password, kdf=None, iterations=None):
address5ce9454909639d2d17a3f753ce7d93fa0b9ab12ecryptocipheraes-128-ctrcipherparamsiv0b7845a5c3597d3d378bde9b7c7319b7ciphertexta494f1feb3c854e99c1ff01e6aaa17d43c0752009073503b908457dc8de5d2a5kdfscryptkdfparamsdklennprsalt13c4a48123affaa29189e909... | Creates a dictionary with an encrypted version of your private key.
To import this keyfile into Ethereum clients like geth and parity:
encode this dictionary with :func:`json.dumps` and save it to disk where your
client keeps key files.
:param private_key: The raw private key
:t... |
358,526 | def _log_task(self, task):
if not task.duration:
return
self._setup_dir(task.base_dir)
stats_dir = self._sdir(task.base_dir)
duration = task.duration
while duration > 0:
date = (datetime.datetime.now() -
datetime... | Logs task record to file.
`task`
``Task`` instance. |
358,527 | def Update(self, filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
if self.stack:
self.previous_stack_top = self.stack[-1]
else:
self.previous_stack_top = None
self.UpdatePreprocessor(line)
if self.stack:
inne... | Update nesting state with current line.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. |
358,528 | def _read_ancestry(file):
df = pd.read_csv(
file,
comment="
header=0,
sep="\t",
na_values=0,
names=["rsid", "chrom", "pos", "allele1", "allele2"],
index_col=0,
dtype={"chrom": object},
)
... | Read and parse Ancestry.com file.
http://www.ancestry.com
Parameters
----------
file : str
path to file
Returns
-------
pandas.DataFrame
individual's genetic data normalized for use with `lineage`
str
name of data sou... |
358,529 | def add_node(self, node):
if _debug: Network._debug("add_node %r", node)
self.nodes.append(node)
node.lan = self
if not node.name:
node.name = % (self.name, node.address) | Add a node to this network, let the node know which network it's on. |
358,530 | def _apply_default_values(catalog, default_values):
for field, default_value in iteritems(default_values):
class_metadata = field.split("_")[0]
field_json_path = field.split("_")[1:]
if class_metadata == "catalog":
_set_default_value(catalog, field_json_path, defa... | Aplica valores default a los campos de un catálogo.
Si el campo está vacío, aplica el default. Si tiene un valor, deja el valor
que estaba. Sólo soporta defaults para las siguientes clases:
catalog
dataset
distribution
field
Args:
catalog (dict): Un catálogo.
... |
358,531 | def _osx_skype_status(status, message):
uid = os.getuid()
for proc in psutil.process_iter():
try:
if proc.uids.real == uid and proc.name == :
skype_running = True
break
except (psutil.AccessDenied, psutil.NoSuchProcess):
pass
... | Updates status and message for Skype IM application on Mac OSX.
`status`
Status type.
`message`
Status message. |
358,532 | def full(self, filetype, **kwargs):
if in kwargs:
return kwargs.get()
assert filetype in self.templates, (
.format(filetype))
template = self.templates[filetype]
... | Return the full name of a given type of file.
Parameters
----------
filetype : str
File type parameter.
Returns
-------
full : str
The full path to the file. |
358,533 | def member_del(self, member_id, reconfig=True):
server_id = self._servers.host_to_server_id(
self.member_id_to_host(member_id))
if reconfig and member_id in [member[] for member in self.members()]:
config = self.config
config[].pop(member_id)
self... | remove member from replica set
Args:
member_id - member index
reconfig - is need reconfig replica
return True if operation success otherwise False |
358,534 | def get_src_builders(self, env):
memo_key = id(env)
try:
memo_dict = self._memo[]
except KeyError:
memo_dict = {}
self._memo[] = memo_dict
else:
try:
return memo_dict[memo_key]
except KeyError:
... | Returns the list of source Builders for this Builder.
This exists mainly to look up Builders referenced as
strings in the 'BUILDER' variable of the construction
environment and cache the result. |
358,535 | def compose(self, mapping):
items = [f.compose(mapping) for f in self._items]
return self.__class__(items, self.shape, self.ftype) | Apply the ``compose`` method to all functions.
Returns a new farray. |
358,536 | def _canceller_for(self, elts, event):
def canceller():
try:
self._event_deque.remove(event)
self._in_deque.remove(elts)
return True
except ValueError:
return False
return canceller | Obtains a cancellation function that removes elts.
The returned cancellation function returns ``True`` if all elements
was removed successfully from the _in_deque, and false if it was not. |
358,537 | def handle_eclipses(self, expose_horizon=False, **kwargs):
eclipse_method = kwargs.get(, self.eclipse_method)
horizon_method = kwargs.get(, self.horizon_method)
possible_eclipse = False
if len(self.bodies) == 1:
if self.bodies[0].__class_... | Detect the triangles at the horizon and the eclipsed triangles, handling
any necessary subdivision.
:parameter str eclipse_method: name of the algorithm to use to detect
the horizon or eclipses (defaults to the value set by computeoptions)
:parameter str subdiv_alg: name of the algo... |
358,538 | def srp1(*args, **kargs):
ans, _ = srp(*args, **kargs)
if len(ans) > 0:
return ans[0][1]
else:
return None | Send and receive packets at layer 2 and return only the first answer |
358,539 | def sample_zip(items_list, num_samples, allow_overflow=False, per_bin=1):
samples_list = [[] for _ in range(num_samples)]
samples_iter = zip_longest(*items_list)
sx = 0
for ix, samples_ in zip(range(num_samples), samples_iter):
samples = filter_Nones(samples_)
samples_list... | Helper for sampling
Given a list of lists, samples one item for each list and bins them into
num_samples bins. If all sublists are of equal size this is equivilent to a
zip, but otherewise consecutive bins will have monotonically less
elemements
# Doctest doesn't work with assertionerror
#util... |
358,540 | def parse_client_table(redis_client):
NIL_CLIENT_ID = ray.ObjectID.nil().binary()
message = redis_client.execute_command("RAY.TABLE_LOOKUP",
ray.gcs_utils.TablePrefix.CLIENT,
"", NIL_CLIENT_ID)
if message i... | Read the client table.
Args:
redis_client: A client to the primary Redis shard.
Returns:
A list of information about the nodes in the cluster. |
358,541 | def split_words(sentence, modify=True, keep_shorts=False):
if (sentence == "*"):
yield sentence
return
if modify:
sentence = sentence.lower()
sentence = strip_accents(sentence)
words = FORCED_SPLIT_KEYWORDS_REGEX.split(sentence)
if keep_shorts:
word_it... | Extract and yield the keywords from the sentence:
- Drop keywords that are too short (keep_shorts=False)
- Drop the accents (modify=True)
- Make everything lower case (modify=True)
- Try to separate the words as much as possible (using 2 list of
separators, one being more complete than the others) |
358,542 | def infiles(fnames, progress, leave=True):
if progress:
if fnames:
fnames = tqdm(fnames, desc=, unit=,
bar_format=BAR_FORMAT,
leave=leave, dynamic_ncols=True)
else:
progress = False
yield fnames
if progress:
... | Get input file paths.
Parameters
----------
fnames : `list` of `str`
File paths.
progress : `bool`
Show progress bar.
leave : `bool`, optional
Leave progress bar (default: True).
Returns
-------
`generator` of `str`
Input file paths. |
358,543 | def delete(self):
if self.abstract:
raise AbstractDocumentException()
self._api.delete_document(self.id)
self._id = None
return True | Remove the document and all of its bundles from ProvStore.
.. warning::
Cannot be undone. |
358,544 | def make_rundir(path):
try:
if not os.path.exists(path):
os.makedirs(path)
prev_rundirs = glob(os.path.join(path, "[0-9]*"))
current_rundir = os.path.join(path, )
if prev_rundirs:
x = sorted([int(os.path.basename(x)) for x in prev_rundirs]... | When a path has not been specified, make the run directory.
Creates a rundir with the following hierarchy:
./runinfo <- Home of all run directories
|----000
|----001 <- Directories for each run
| ....
|----NNN
Kwargs:
- path (str): String path to a speci... |
358,545 | def create_shared_noise(count):
seed = 123
noise = np.random.RandomState(seed).randn(count).astype(np.float32)
return noise | Create a large array of noise to be shared by all workers. |
358,546 | def get_note_names(self):
res = []
for n in self.notes:
if n.name not in res:
res.append(n.name)
return res | Return a list with all the note names in the current container.
Every name will only be mentioned once. |
358,547 | def regionprops_3D(im):
r
print(*60)
print()
results = regionprops(im, coordinates=)
for i in tqdm(range(len(results))):
mask = results[i].image
mask_padded = sp.pad(mask, pad_width=1, mode=)
temp = spim.distance_transform_edt(mask_padded)
dt = extract_subsection(tem... | r"""
Calculates various metrics for each labeled region in a 3D image.
The ``regionsprops`` method in **skimage** is very thorough for 2D images,
but is a bit limited when it comes to 3D images, so this function aims
to fill this gap.
Parameters
----------
im : array_like
An imagin... |
358,548 | def load(self, response):
self._response = response
if self.next_location(raw=True):
self._num_redirects += 1 | Load the response and increment the counter.
Args:
response (:class:`.http.request.Response`): The response from
a previous request. |
358,549 | def find_biomass_precursors(model, reaction):
id_of_main_compartment = helpers.find_compartment_id_in_model(model, )
gam_reactants = set()
try:
gam_reactants.update([
helpers.find_met_in_model(
model, "MNXM3", id_of_main_compartment)[0]])
except RuntimeError:
... | Return a list of all biomass precursors excluding ATP and H2O.
Parameters
----------
reaction : cobra.core.reaction.Reaction
The biomass reaction of the model under investigation.
model : cobra.Model
The metabolic model under investigation.
Returns
-------
list
Meta... |
358,550 | def _build_search(structured_query):
arguments = {}
text_terms = [term for ttype, term in structured_query.terms
if ttype == ]
text_terms_wo_stopwords = [term for term in text_terms
if term.lower() not in STOPWORDS]
conditions = {: , : , ... | Construct search statment for db execution.
Produces the search statement and argument dictionary to be executed
by the DBAPI v2 execute method.
For example, ``cursor.execute(*_build_search(query, weights))``
:param query: containing terms, filters, and sorts.
:type query: Query
:param weights... |
358,551 | def make_tmp_dir(suffix="", prefix="tmp", dir=None):
if dir is None:
return tempfile.mkdtemp(suffix, prefix, dir)
else:
while True:
rand_term = random.randint(1, 9999)
tmp_dir = os.path.join(dir, "%s%d%s" % (prefix, rand_term, suffix))
if tf.gfile.Exists(tmp_dir):
continue
... | Make a temporary directory. |
358,552 | def forwards(self, orm):
"Write your forwards methods here."
for category in orm[].objects.all():
category.is_published = True
category.save() | Write your forwards methods here. |
358,553 | def syllabify(self):
ind = []
i = 0
while i < len(self.word) - 1:
if self.word[i] in SHORT_VOWELS + LONG_VOWELS:
nucleus =
while self.word[i] in SHORT_VOWELS + LONG_VOWELS and i < len(self.word) - 1:
... | Syllabifier module for Middle High German
The algorithm works by applying the MOP(Maximal Onset Principle)
on open syllables. For closed syllables, the legal partitions
are checked and applied. The word is always returned in lowercase.
Examples:
>>> Word('entslâfen').syllab... |
358,554 | def create(self, name, cidr, **kwargs):
return self.driver.create(name, cidr, **kwargs) | This function will create a user network.
Within OpenStack, it will create a network and a subnet
Within AWS, it will create a VPC and a subnet
:param name: string
:param cidr: string E.x: "10.0.0.0/24"
:param kwargs: dict
:return: dict |
358,555 | def create_minimal_scaleio_cluster(self, mdmPassword, liaPassword):
nodeUsername =
nodePassword =
node1 = ScaleIO_... | Using IM this method create a 3-node ScaleIO cluster with 2xMDM, 1xTB, 3x SDS (using /dev/sdb), 3x SDC |
358,556 | def hittime(cls, timestamp=None, age=None, milliseconds=None):
if isinstance(timestamp, (int, float)):
return int(Time.milliseconds_offset(Time.from_unix(timestamp, milliseconds=milliseconds)))
if isinstance(timestamp, datetime.datetime):
return int(Time.milliseconds_off... | Returns an integer represeting the milliseconds offset for a given hit (relative to now) |
358,557 | def encrypt(text, _key, salt=None):
if is_text(text):
encoding =
data = bytearray(text.encode("utf8"))
elif is_binary(text):
encoding = None
if PY2:
data = bytearray(text)
else:
data = text
if _key is None:
Log.error("Expecting ... | RETURN {"salt":s, "length":l, "data":d} -> JSON -> UTF8 |
358,558 | def cycle_data(self, verbose=False, result_cycle=None, result_size=None, result_edges=None,changelog=True):
cycle_names = [s[] for s in self.settings[]]
accepted_steps = set(s[] for s in self.settings[] if s[] == StatusTypes.accepted)
completed_steps = set(s[] for s in self.settings[] ... | Get data from JIRA for cycle/flow times and story points size change.
Build a numerically indexed data frame with the following 'fixed'
columns: `key`, 'url', 'issue_type', `summary`, `status`, and
`resolution` from JIRA, as well as the value of any fields set in
the `fields` dict in `s... |
358,559 | def _GetConfigValue(self, config_parser, section_name, value_name):
try:
return config_parser.get(section_name, value_name)
except configparser.NoOptionError:
return None | Retrieves a value from the config parser.
Args:
config_parser (ConfigParser): configuration parser.
section_name (str): name of the section that contains the value.
value_name (str): name of the value.
Returns:
object: configuration value or None if the value does not exists. |
358,560 | def wins(self, year):
schedule = self.schedule(year)
if schedule.empty:
return np.nan
return schedule.query().is_win.sum() | Returns the # of regular season wins a team in a year.
:year: The year for the season in question.
:returns: The number of regular season wins. |
358,561 | def get_profile_data(self, raw_token):
try:
response = self.request(, self.profile_url, token=raw_token)
response.raise_for_status()
except RequestException as e:
logger.error(.format(e))
return None
else:
return response.json(... | Fetch user profile information. |
358,562 | def encode(raw):
return raw \
.replace(bytes([SLIP_ESC]), bytes([SLIP_ESC, SLIP_ESC_ESC])) \
.replace(bytes([SLIP_END]), bytes([SLIP_ESC, SLIP_ESC_END])) | Encode SLIP message. |
358,563 | def _push_writer(self):
buf = util.FastEncodingBuffer()
self._buffer_stack.append(buf)
return buf.write | push a capturing buffer onto this Context and return
the new writer function. |
358,564 | def from_dict(cls, tx, skip_schema_validation=True):
operation = tx.get(, Transaction.CREATE) if isinstance(tx, dict) else Transaction.CREATE
cls = Transaction.resolve_class(operation)
if not skip_schema_validation:
cls.validate_id(tx)
cls.validate_schema(tx)
... | Transforms a Python dictionary to a Transaction object.
Args:
tx_body (dict): The Transaction to be transformed.
Returns:
:class:`~bigchaindb.common.transaction.Transaction` |
358,565 | def feature_info(self):
if self._feature_info is not None:
return self._feature_info
assert self._hparams is not None
hp = self.get_hparams()
if self.has_inputs:
in_id = hp.input_space_id
out_id = hp.target_space_id
features = collections.defaultdict(FeatureInfo)
for feat... | Retrieve dict<feature name, FeatureInfo>.
Must first call Problem.get_hparams or Problem.dataset to have the problem's
internal hparams already constructed.
Returns:
dict<feature name, FeatureInfo> |
358,566 | def incremental_value(self, slip_moment, mmax, mag_value, bbar, dbar):
delta_m = mmax - mag_value
a_3 = self._get_a3(bbar, dbar, slip_moment, mmax)
return a_3 * bbar * (np.exp(bbar * delta_m) - 1.0) * (delta_m > 0.0) | Returns the incremental rate with Mmax = Mag_value |
358,567 | def CountHuntFlows(self,
hunt_id,
filter_condition=db.HuntFlowsCondition.UNSET,
cursor=None):
hunt_id_int = db_utils.HuntIDToInt(hunt_id)
query = ("SELECT COUNT(*) FROM flows "
"FORCE INDEX(flows_by_hunt) "
"WHERE par... | Counts hunt flows matching given conditions. |
358,568 | def generate_pipeline_code(pipeline_tree, operators):
steps = _process_operator(pipeline_tree, operators)
pipeline_text = "make_pipeline(\n{STEPS}\n)".format(STEPS=_indent(",\n".join(steps), 4))
return pipeline_text | Generate code specific to the construction of the sklearn Pipeline.
Parameters
----------
pipeline_tree: list
List of operators in the current optimized pipeline
Returns
-------
Source code for the sklearn pipeline |
358,569 | def _get_delay(self, userdelay, frameslist):
delay = userdelay or getattr(frameslist, , None)
delay = (delay or self.default_delay) - self.nice_delay
if delay < 0:
delay = 0
return delay | Get the appropriate delay value to use, trying in this order:
userdelay
frameslist.delay
default_delay
The user can override the frameslist's delay by specifiying a
value, and if neither are given the default is used. |
358,570 | def execute(self):
r = self._s.execute()
r._faceted_search = self
return r | Execute the search and return the response. |
358,571 | def wheelEvent(self, ev, axis=None):
state = None
if ev.modifiers() == QtCore.Qt.ControlModifier:
state = self.mouseEnabled()
self.setMouseEnabled(not state[0], not state[1])
if self._zeroWheel:
ev.pos = lambda : self.mapViewToScene(QtCore.QP... | Reacts to mouse wheel movement, custom behaviour switches zoom
axis when ctrl is pressed, and sets the locus of zoom, if zeroWheel
is set. |
358,572 | def apply_motion_tracks(self, tracks, accuracy=0.004):
if not tracks:
raise ValueError(.format(repr(tracks)))
tb = MotionTrackBatch(tracks)
return self.agent.input.applyMotionEvents(tb.discretize(accuracy)) | Similar to click but press the screen for the given time interval and then release
Args:
tracks (:py:obj:`list`): list of :py:class:`poco.utils.track.MotionTrack` object
accuracy (:py:obj:`float`): motion accuracy for each motion steps in normalized coordinate metrics. |
358,573 | def has_axis(self, axis):
if self.type != EventType.POINTER_AXIS:
raise AttributeError(_wrong_meth.format(self.type))
return self._libinput.libinput_event_pointer_has_axis(
self._handle, axis) | Check if the event has a valid value for the given axis.
If this method returns True for an axis and :meth:`get_axis_value`
returns a value of 0, the event is a scroll stop event.
For pointer events that are not of type
:attr:`~libinput.constant.EventType.POINTER_AXIS`, this method raises
:exc:`AttributeErr... |
358,574 | def GetValueByName(self, name):
pyregf_value = self._pyregf_key.get_value_by_name(name)
if not pyregf_value:
return None
return REGFWinRegistryValue(pyregf_value) | Retrieves a value by name.
Value names are not unique and pyregf provides first match for the value.
Args:
name (str): name of the value or an empty string for the default value.
Returns:
WinRegistryValue: Windows Registry value if a corresponding value was
found or None if not. |
358,575 | def visit_slice(self, node):
lower = node.lower.accept(self) if node.lower else ""
upper = node.upper.accept(self) if node.upper else ""
step = node.step.accept(self) if node.step else ""
if step:
return "%s:%s:%s" % (lower, upper, step)
return "%s:%s" % (low... | return an astroid.Slice node as string |
358,576 | def is_invalid_params_py3(func, *args, **kwargs):
signature = inspect.signature(func)
parameters = signature.parameters
unexpected = set(kwargs.keys()) - set(parameters.keys())
if len(unexpected) > 0:
return True
params = [
parameter for name, parameter in parameters.items()
... | Use inspect.signature instead of inspect.getargspec or
inspect.getfullargspec (based on inspect.signature itself) as it provides
more information about function parameters.
.. versionadded: 1.11.2 |
358,577 | def calculate_concordance(graph: BELGraph, key: str, cutoff: Optional[float] = None,
use_ambiguous: bool = False) -> float:
correct, incorrect, ambiguous, _ = calculate_concordance_helper(graph, key, cutoff=cutoff)
try:
return correct / (correct + incorrect + (ambiguous i... | Calculates network-wide concordance.
Assumes data already annotated with given key
:param graph: A BEL graph
:param key: The node data dictionary key storing the logFC
:param cutoff: The optional logFC cutoff for significance
:param use_ambiguous: Compare to ambiguous edges as well |
358,578 | def get_instance(self, payload):
return VariableInstance(
self._version,
payload,
service_sid=self._solution[],
environment_sid=self._solution[],
) | Build an instance of VariableInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.serverless.v1.service.environment.variable.VariableInstance
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance |
358,579 | def _create_authority_file(self, file_path):
parent_dir = os.path.dirname(os.path.realpath(file_path))
if not os.path.exists(parent_dir):
os.makedirs(parent_dir)
blank = self._create_blank_authority()
with open(file_path, ) as authority_... | Create a new LSID authority file at the indicated location
:param file_path: location of LSID authority file |
358,580 | def image_information_response(self):
dr = degraded_request(self.identifier)
if (dr):
self.logger.info("image_information: degraded %s -> %s" %
(self.identifier, dr))
self.degraded = self.identifier
self.identifier = dr
el... | Parse image information request and create response. |
358,581 | def wait_for_service_endpoint(service_name, timeout_sec=120):
master_count = len(get_all_masters())
return time_wait(lambda: service_available_predicate(service_name),
timeout_seconds=timeout_sec,
required_consecutive_success_count=master_count) | Checks the service url if available it returns true, on expiration
it returns false |
358,582 | def get_config_directory(override_files=False):
if override_files:
possible_dirs = [override_files]
else:
xdg_config_home = os.environ.get() or \
os.path.expanduser()
possible_dirs = [os.path.join(xdg_config_home, "supernova.d/"),
os.path.expand... | Looks for the most specific configuration directory possible, in order to
load individual configuration files. |
358,583 | def page_not_found(request, template_name=):
response = render_in_page(request, template_name)
if response:
return response
template = Template(
)
body = template.render(RequestContext(
request, {: request.path}))
return http.HttpResponseNotFound(body, content... | Default 404 handler.
Templates: :template:`404.html`
Context:
request_path
The path of the requested URL (e.g., '/app/pages/bad_page/') |
358,584 | def status(self):
result = set()
for line in self._execute()[1].splitlines():
if line[0] == :
result.add((FileStatus.Added, line[2:].strip()))
elif line[0] == :
result.add((FileStatus.Removed, line[2:].strip()))
return result | See :py:meth:`~stash.repository.Repository.status`. |
358,585 | def wait_for_fresh_games(self, poll_interval=15.0):
wait_until_game = self.read_wait_cell()
if not wait_until_game:
return
latest_game = self.latest_game_number
last_latest = latest_game
while latest_game < wait_until_game:
utils.dbg(
... | Block caller until required new games have been played.
Args:
poll_interval: number of seconds to wait between checks
If the cell `table_state=metadata:wait_for_game_number` exists,
then block the caller, checking every `poll_interval` seconds,
until `table_state=metadata:ga... |
358,586 | def extract(self, obj, bypass_ref=False):
return self.pointer.extract(obj, bypass_ref) | Extract subelement from obj, according to pointer.
It assums that document is the object.
:param obj: the object source
:param bypass_ref: disable JSON Reference errors |
358,587 | def read_until(self, s, echo=None):
s_len = len(s)
buf = self.read(s_len, echo)
while buf[-s_len:] != s:
buf += self.read(1, echo)
return buf | Read until a certain string is encountered..
Args:
s(bytes): The string to wait for.
echo(bool): Whether to write the read data to stdout.
Returns:
bytes: The data up to and including *s*.
Raises:
EOFError: If the channel was closed. |
358,588 | def get_appliance_by_name(self, appliance_name):
appliances = self.get_appliances()
if appliances:
for appliance in appliances:
if appliance[] == appliance_name:
return appliance
return None | Gets the particular Image Streamer resource based on its name.
Args:
appliance_name:
The Image Streamer resource name.
Returns:
dict: Image Streamer resource. |
358,589 | def parse_create(prs, conn):
prs_create = prs.add_parser(
, help=)
set_option(prs_create, )
conn_options(prs_create, conn)
prs_create.set_defaults(func=create) | Create record.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information |
358,590 | def req_string(self, model):
if model not in self.models:
model = self.models
if self.min_ykver and self.max_ykver:
return "%s %d.%d..%d.%d" % (model, \
self.min_ykver[0], self.min_ykver[1], \
... | Return string describing model and version requirement. |
358,591 | def geotiff_tags(self):
if not self.is_geotiff:
return None
tags = self.tags
gkd = tags[].value
if gkd[0] != 1:
log.warning()
return {}
result = {
: gkd[0],
: gkd[1],
: gkd[2],
... | Return consolidated metadata from GeoTIFF tags as dict. |
358,592 | def hash_vector(self, v, querying=False):
bucket_keys = []
if querying:
for lshash in self.child_hashes:
for bucket_key in lshash.hash_vector(v, querying):
prefixed_key = lshash.hash_name++bucket_key
... | Hashes the vector and returns the bucket key as string. |
358,593 | def plot(self, **plot_kwargs: Any) -> None:
fig = plt.figure()
plt.plot(self._rabi_angles, self._excited_state_probs, ,
figure=fig, **plot_kwargs)
plt.xlabel(r"Rabi Angle (Radian)", figure=fig)
plt.ylabel(, figure=fig)
fig.show() | Plots excited state probability vs the Rabi angle (angle of rotation
around the x-axis).
Args:
**plot_kwargs: Arguments to be passed to matplotlib.pyplot.plot. |
358,594 | def intersection(self):
if self.moc is None:
raise CommandError()
filename = self.params.pop()
self.moc = self.moc.intersection(MOC(filename=filename)) | Compute the intersection with the given MOC.
This command takes the name of a MOC file and forms the intersection
of the running MOC with that file.
::
pymoctool a.fits --intersection b.fits --output intersection.fits |
358,595 | def mock_import(do_not_mock=None, **mock_kwargs):
do_not_mock = _to_list(do_not_mock)
def try_import(module_name, *args, **kwargs):
try:
return _builtins_import(module_name, *args, **kwargs)
except:
if any((_match(module_name, prefix) for prefix in do_not_mock)... | Mocks import statements by ignoring ImportErrors
and replacing the missing module with a Mock.
:param str|unicode|list[str|unicode] do_not_mock: names of modules
that should exists, and an ImportError could be raised for.
:param mock_kwargs: kwargs for MagicMock object.
:return: patch object |
358,596 | def s3_upload(self, keyname, absolute_path):
mimetype = mimetypes.guess_type(absolute_path)
options = {: mimetype[0]}
if mimetype[0] is not None and mimetype[0].startswith():
upload = open(absolute_path, )
options[] =
key_parts = keyname.split()
... | Upload a file to s3 |
358,597 | def cleanup_codra_edus(self):
for leafpos in self.tree.treepositions():
edu_str = self.tree[leafpos]
edu_str = EDU_START_RE.sub("", edu_str)
edu_str = TRIPLE_ESCAPE_RE.sub(, edu_str)
edu_str = EDU_END_RE.sub("", edu_str)
self.tree[leafpos] =... | Remove leading/trailing '_!' from CODRA EDUs and unescape its double quotes. |
358,598 | def render_text(self, request, instance, context):
render_template = self.get_render_template(request, instance, email_format=)
if not render_template:
base_url = request.build_absolute_uri()
html = self.render_html(request, instance, context)
re... | Custom rendering function for HTML output |
358,599 | def get_profile(self, img_type, coordinate, num_points):
lon0, lon1, lat0, lat1 = coordinate
X, Y, Z = self.get_arrays(img_type)
y0, x0 = np.argmin(np.abs(X[0, :] - lon0)
), np.argmin(np.abs(Y[:, 0] - lat0))
y1, x1 = np.argmin(np.abs(X[0, :] - lon1)
... | Extract a profile from (lat1,lon1) to (lat2,lon2)
Args:
img_type (str): Either lola or wac.
coordinate (float,float,float,flaot): A tupple
``(lon0,lon1,lat0,lat1)`` with:
- lon0: First point longitude
- lat0: First point latitude
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.