content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def getHiddenStatus(data):
"""
使用Gaussian HMM对数据进行建模,并得到预测值
"""
cols = ["r_5", "r_20", "a_5", "a_20"]
model = GaussianHMM(n_components=3, covariance_type="full", n_iter=1000,
random_state=2010)
model.fit(data[cols])
hiddenStatus = model.predict(data[cols])
return hiddenStatus | 4a613e426b8a4f16e02f535aebc2752d4a99ae25 | 3,640,524 |
def format_time(data, year):
"""Format any time variables in US.
Parameters
----------
data : pd.DataFrame
Data without time formatting.
year : int
The `year` of the wave being processed.
Returns
-------
data : pd.DataFrame
Data with time formatting.
"""
... | 858d7e48143a16e644d4f1241cd8918385dc7c5f | 3,640,525 |
def get_connection(sid):
"""
Attempts to connect to the given server and
returns a connection.
"""
server = get_server(sid)
try:
shell = spur.SshShell(
hostname=server["host"],
username=server["username"],
password=server["password"],
por... | 933aa768640455ed21b914c4cb432436a7225e4e | 3,640,526 |
from typing import List
def tail(filename: str, nlines: int = 20, bsz: int = 4096) -> List[str]:
"""
Pure python equivalent of the UNIX ``tail`` command. Simply pass a filename and the number of lines you want to load
from the end of the file, and a ``List[str]`` of lines (in forward order) will be return... | e5f94cdc349610189c85c82c66589c243063f5a6 | 3,640,528 |
def initialized(name, secret_shares=5, secret_threshold=3, pgp_keys=None,
keybase_users=None, unseal=True):
"""
Ensure that the vault instance has been initialized and run the
initialization if it has not.
:param name: The id used for the state definition
:param secret_shares: THe nu... | c2b88bb8875ded7c7274b0695a9de9fb287b0b57 | 3,640,529 |
def plot(plot, x, y, **kwargs):
"""
Adds series to plot. By default this is displayed as continuous line.
Refer to matplotlib.pyplot.plot() help for more info. X and y coordinates
are expected to be in user's data units.
Args:
plot: matplotlib.pyplot
Plot to which series sho... | 1e861243a87b61461fb49dcadf19ec9099fa5a1f | 3,640,530 |
def glyph_by_hershey_code(hershey_code):
"""
Returns the Hershey glyph corresponding to `hershey_code`.
"""
glyph = glyphs_by_hershey_code.get(hershey_code)
if glyph is None:
raise ValueError("No glyph for hershey code %d" % hershey_code)
return glyph | 54a8c9657466f2348e93667e8a638c3e44681adb | 3,640,531 |
def _get_prefab_from_address(address):
"""
Parses an address of the format ip[:port] and return return a prefab object connected to the remote node
"""
try:
if ':' in address:
ip, port = address.split(':')
port = int(port)
else:
ip, port = address, 22
... | 3520dcca249073433ece88a4d9b31e8c2d73eb86 | 3,640,532 |
def interval_to_errors(value, low_bound, hi_bound):
"""
Convert error intervals to errors
:param value: central value
:param low_bound: interval low bound
:param hi_bound: interval high bound
:return: (error minus, error plus)
"""
error_plus = hi_bound - value
error_minus = value ... | ffee403968ddf5fd976df79a90bdbb62474ede11 | 3,640,533 |
from typing import Any
from typing import cast
def log_enabled_arg(request: Any) -> bool:
"""Using different log messages.
Args:
request: special fixture that returns the fixture params
Returns:
The params values are returned one at a time
"""
return cast(bool, request.param) | 9ff97ab8f5cc8e3a0c548e613b75b5da050eb53d | 3,640,534 |
def expsign(sign, exp):
"""
optimization of sign ** exp
"""
if sign == 1:
return 1
assert sign == -1
return -1 if exp % 2 else 1 | d770aaa2a4d20c9530a213631047d1d0f9cca3f7 | 3,640,535 |
def convert_format(tensors, kind, target_kind):
"""Converts data from format 'kind' to one of the formats specified in 'target_kind'
This allows us to convert data to/from dataframe representations for operators that
only support certain reprentations
"""
# this is all much more difficult because o... | 8925d002395da05c6b5a7374a7288cc0511df1cb | 3,640,536 |
import urllib
import re
def template2path(template, params, ranges=None):
"""Converts a template and a dict of parameters to a path fragment.
Converts a template, such as /{name}/ and a dictionary of parameter
values to a URL path (string).
Parameter values that are used for buildig the path are con... | daf628ab6ef1a6fddb612c0f4c817085ac23ce2c | 3,640,537 |
from typing import Union
from typing import Dict
from typing import Any
def calculate_total_matched(
market_book: Union[Dict[str, Any], MarketBook]
) -> Union[int, float]:
"""
Calculate the total matched on this market from the amounts matched on each runner at each price point. Useful for historic data w... | 7bc3d4680e5507d1400e94ab30213c0cc6d817bb | 3,640,538 |
import re
def _newline_to_ret_token(instring):
"""Replaces newlines with the !RET token.
"""
return re.sub(r'\n', '!RET', instring) | 4fcf60025f79811e99151019a479da04f25ba47c | 3,640,540 |
def _ComputeLineCounts(old_lines, chunks):
"""Compute the length of the old and new sides of a diff.
Args:
old_lines: List of lines representing the original file.
chunks: List of chunks as returned by patching.ParsePatchToChunks().
Returns:
A tuple (old_len, new_len) representing len(old_lines) and... | ba99714016b69d87f260c8e7b8793468a2f7b04d | 3,640,541 |
def _read_int(file_handle, data_size):
"""
Read a signed integer of defined data_size from file.
:param file_handle: The file handle to read from at current position
:param data_size: The data size in bytes of the integer to read
:returns: The integer read and decoded
"""
return int.from_... | 4d2a7e82e9daa828c0e5b180250834f2fa9977d5 | 3,640,542 |
import numpy
def quaternion_to_matrix(quat):
"""OI
"""
qw = quat[0][0]
qx = quat[1][0]
qy = quat[2][0]
qz = quat[3][0]
rot = numpy.array([[1 - 2*qy*qy - 2*qz*qz, 2*qx*qy - 2*qz*qw, 2*qx*qz + 2*qy*qw],
[2*qx*qy + 2*qz*qw, 1 - 2*qx*qx - 2*qz*qz, 2*qy*qz - 2*qx*qw],
[2*qx*qz - 2*qy*qw, 2*... | 67f02ea97db1af4a763c3a97957f36de29da0157 | 3,640,543 |
def get_cart_from_request(request, create=False):
"""Returns Cart object for current user. If create option is True,
new cart will be saved to db"""
cookie_token = request.get_signed_cookie(
Cart.COOKIE_NAME, default=None)
if request.user.is_authenticated():
user = request.user
... | d22c2587a20c12bac1fe713d40ddf069bfc5f40e | 3,640,544 |
def make_concrete_rule(rule_no, zone_map, direction, zone, rule, concrete_port):
"""Take a rule and create a corresponding concrete rule."""
def make_rule(target_zone, port):
return ConcreteRule(source_rules=[rule], rule_no=rule_no, target_zone=target_zone,
direction=directi... | b7b1babc32c2d81193e62e90b5fd751ad8575ff1 | 3,640,545 |
from typing import List
def downcast(df: pd.DataFrame, signed_columns: List[str] = None) -> pd.DataFrame:
"""
Automatically check for signed/unsigned columns and downcast.
However, if a column can be signed while all the data in that column is unsigned, you don't want to downcast to
an unsigned column... | 2eb2494e5a59630c4e20d114aac076c971f287a6 | 3,640,546 |
from typing import Optional
def entity_type(entity: dict) -> Optional[str]:
"""
Safely get the NGSI type of the given entity.
The type, if present, is expected to be a string, so we convert it if it
isn't.
:param entity: the entity.
:return: the type string if there's an type, `None` otherwis... | e4d27b7499710951959cfef5c1191c6744bd02ce | 3,640,548 |
def read_private_key_data(bio):
"""
Read enough data from bio to fully read a private key.
(The data read is thrown away, though.)
This is required since the format does not contain the actual length
of the privately-serialized private key data. The knowledge of what
to read for each key type... | de1e38c49fe81449b90b14ccab0b2aaf7de121bc | 3,640,549 |
def list_check(lst):
"""Are all items in lst a list?
>>> list_check([[1], [2, 3]])
True
>>> list_check([[1], "nope"])
False
"""
t = [1 if isinstance(x, list) else 0 for x in lst]
return len(lst) == sum(t) | 9e2c55cb6e15f89ff2b73a78d5f15310d3cac672 | 3,640,550 |
from typing import Dict
def build_encoded_manifest_from_nested_directory(
data_directory_path: str,
) -> Dict[str, EncodedVideoInfo]:
"""
Creates a dictionary from video_id to EncodedVideoInfo for
encoded videos in the given directory.
Args:
data_directory_path (str): The folder to ls to ... | 2a908eb33b140e73d27bca02da449d09e4ac4c5d | 3,640,552 |
def derive_question(doc):
"""
Return a string that rephrases an action in the
doc in the form of a question.
'doc' is expected to be a spaCy doc.
"""
verb_chunk = find_verb_chunk(doc)
if not verb_chunk:
return None
subj = verb_chunk['subject'].text
obj = verb_chunk['object'].text
if verb_chunk['verb'].tag_ ... | 876e6733f8cf3d9accf3af1af89241ded4a02481 | 3,640,553 |
def recover_label(pred_variable, gold_variable, mask_variable, label_alphabet, word_recover, sentence_classification=False):
"""
input:
pred_variable (batch_size, sent_len): pred tag result
gold_variable (batch_size, sent_len): gold result variable
mask_variable (batch_si... | 7f3efef4a0e9041e329c8d1c0c5641bf0c79ff58 | 3,640,554 |
def RegenerateOverview(*args, **kwargs):
"""
RegenerateOverview(Band srcBand, Band overviewBand, char const * resampling="average", GDALProgressFunc callback=0,
void * callback_data=None) -> int
"""
return _gdal.RegenerateOverview(*args, **kwargs) | 8f05fcb7a12bf09d432b65b9cf049d2ff5cf23b1 | 3,640,555 |
import imp
def import_code(code, name):
""" code can be any object containing code -- string, file object, or
compiled code object. Returns a new module object initialized
by dynamically importing the given code. If the module has already
been imported - then it is returned and not import... | 309fb1e214225dcdf742bc5ea7d21cb502b05ae9 | 3,640,556 |
def two(data: np.ndarray) -> int:
"""
Use the binary numbers in your diagnostic report to calculate the oxygen generator rating and CO2 scrubber rating,
then multiply them together. What is the life support rating of the submarine? (Be sure to represent your answer in
decimal, not binary.)
"""
... | 723984bf673ab23697ccff69e0c7e2529cce2e81 | 3,640,557 |
import six
def get_lr_fit(sess, model, x_train, y_train, x_test, num_steps=100):
"""Fit a multi-class logistic regression classifier.
Args:
x_train: [N, D]. Training data.
y_train: [N]. Training label, integer classes.
x_test: [M, D]. Test data.
Returns:
y_pred: [M]. Integer class prediction of... | a60654d15e8f0f1c5e7ab11bc9c3e17f3440d286 | 3,640,558 |
import random
def make_block_trials(ntrials_block):
"""Creates a matrix of pseudo-random balanced trial parameters for a block of trials.
Parameters
----------
ntrials_block : int
Number of trials in the block.
Returns
-------
block : 2d array
Matrix of trial parameters (... | ed504af676a660befd3b548e9148e4a6cbc93183 | 3,640,559 |
def view_user(user_id: int):
"""Return the given user's history."""
return render_user(manager.get_user_by_id(user_id)) | 70b88f25b63697682650ae60591e4eee16253433 | 3,640,560 |
def first(c) -> col:
"""
In contrast to pyspark.sql.functions.first this function uses column name as alias
without prefixing it with the aggregation function name.
"""
if isinstance(c, str):
return F.first(c).alias(c)
columnName = c._jc.toString()
return F.first(c).alias(columnName... | 0b7b0bb0d3e2f56c400f3a026f39cb2459b0e54f | 3,640,561 |
def translate(root_list, use_bag_semantics=False):
"""
Translate a list of relational algebra trees into SQL statements.
:param root_list: a list of tree roots
:param use_bag_semantics: flag for using relational algebra bag semantics
:return: a list of SQL statements
"""
translator = (Trans... | b7a25d8af2e47ba134a6dbf490a0255391b330c1 | 3,640,562 |
import jsonschema
def replace_aliases(record):
"""
Replace all aliases associated with this DID / GUID
"""
# we set force=True so that if MIME type of request is not application/JSON,
# get_json will still throw a UserError.
aliases_json = flask.request.get_json(force=True)
try:
js... | a19335af1836f1899565b874640cdd0858247bcc | 3,640,563 |
def pos_tag(docs, language=None, tagger_instance=None, doc_meta_key=None):
"""
Apply Part-of-Speech (POS) tagging to list of documents `docs`. Either load a tagger based on supplied `language`
or use the tagger instance `tagger` which must have a method ``tag()``. A tagger can be loaded via
:func:`~tmto... | a990acc4caa33c7615c961593557b43ef6d5a6d0 | 3,640,564 |
def NOBE_GA_SH(G,K,topk):
"""detect SH spanners via NOBE-GA[1].
Parameters
----------
G : easygraph.Graph
An unweighted and undirected graph.
K : int
Embedding dimension k
topk : int
top - k structural hole spanners
Returns
-------
SHS : list
The t... | a1f3f8f041e4a89b9d09037479574c27505dd7fa | 3,640,565 |
import torch
def calculate_correct_answers(model, dataloader, epoch):
"""Calculate correct over total answers"""
forward_backward_func = get_forward_backward_func()
for m in model:
m.eval()
def loss_func(labels, output_tensor):
logits = output_tensor
loss_dict = {}
#... | 24e3196cd172719d16524b0bbd6c0848fec3c44e | 3,640,566 |
from typing import Dict
from typing import Tuple
from typing import Any
import re
def set_template_parameters(
template: Template, template_metadata: TemplateMetadata, input_parameters: Dict[str, str], interactive=False
):
"""Set and verify template parameters' values in the template_metadata."""
if inter... | fb14c28f754305e6907cff40086b2ffe55a55526 | 3,640,567 |
def calc_roll_pitch_yaw(yag, zag, yag_obs, zag_obs, sigma=None):
"""Calc S/C delta roll, pitch, and yaw for observed star positions relative to reference.
This function computes a S/C delta roll/pitch/yaw that transforms the
reference star positions yag/zag into the observed positions
yag_obs/zag_obs. ... | e1cf3c1377a3613b9ea1fc76e7c9eecac1a6e175 | 3,640,568 |
def make_query_abs(db, table, start_dt, end_dt, dscfg, mode, no_part=False, cols=None):
"""절대 시간으로 질의를 만듦.
Args:
db (str): DB명
table (str): table명
start_dt (date): 시작일
end_dt (date): 종료일
dscfg (ConfigParser): 데이터 스크립트 설정
mode: 쿼리 모드 ('count' - 행 수 구하기, 'preview' ... | 113049d37ceaf1cbf9b9149b1d3a4278dad96aa6 | 3,640,569 |
def validate_task_rel_proposal(header, propose, rel_address, state):
"""Validates that the User exists, the Task exists, and the User is not
in the Task's relationship specified by rel_address.
Args:
header (TransactionHeader): The transaction header.
propose (ProposeAddTask_____): The Task... | d9511f0cad43cbb7a2bc9c08b9f1d112d2d4bf7b | 3,640,571 |
import json
def all_cells_run(event_str: str, expected_count: int) -> bool:
"""Wait for an event signalling all cells have run.
`execution_count` should equal number of nonempty cells.
"""
try:
event = json.loads(event_str)
msg_type = event["msg_type"]
content = event["content... | c3e1bb23f38ffdd09d4cc2ea3326d40b7cf54034 | 3,640,572 |
from typing import Union
def to_forecasting(
timeseries: np.ndarray,
forecast: int = 1,
axis: Union[int, float] = 0,
test_size: int = None,
):
"""Split a timeseries for forecasting tasks.
Transform a timeseries :math:`X` into a series of
input values :math:`X_t` and a series of output val... | 7d77df1f52ee5a499b635dd9575ab08afaa7dda2 | 3,640,573 |
def build_task_environment() -> dm_env.Environment:
"""Returns the environment."""
# We first build the base task that contains the simulation model as well
# as all the initialization logic, the sensors and the effectors.
task, components = task_builder.build_task()
del components
env_builder = subtask_e... | 91618e066ef92a396ea2dc8f6ff36c9a98356e29 | 3,640,574 |
def searchInsert(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
try:
return nums.index(target)
except ValueError:
nums.append(target)
nums.sort()
return nums.index(target) | 56a719b1595502a773c108d26c597fb5ac0201bb | 3,640,575 |
def resource(author, tag) -> Resource:
"""Resource fixture"""
return Resource(
name="Sentiment Algorithm",
url="https://raw.githubusercontent.com/MarcSkovMadsen/awesome-streamlit/master/src/pages/gallery/contributions/marc_skov_madsen/sentiment_analyzer/sentiment_analyzer.py",
is_awesom... | b4eb6bd4c8409e83d0ebb75f0dc390ce7d669512 | 3,640,576 |
def model_softmax(input_data=None,
output_targets=None,
num_words=3000,
num_units=128,
num_layers=2,
num_tags=5,
batchsize=1,
train=True
):
"""
:param input_data:
... | a3991206b0cdae621e1095a1d1dc4493d600bc26 | 3,640,578 |
from typing import AnyStr
from typing import List
from typing import Dict
def get_metric_monthly_rating(metric: AnyStr,
tenant_id: AnyStr,
namespaces: List[AnyStr]) -> List[Dict]:
"""
Get the monthly price for a metric.
:metric (AnyStr) A string... | e73c56015a9320e9ce08b0f1375a7cea70dcc0f0 | 3,640,579 |
def masked_softmax_cross_entropy(preds, labels, mask):
"""Softmax cross-entropy loss with masking."""
loss = tf.nn.softmax_cross_entropy_with_logits(logits=preds, labels=labels)
mask = tf.cast(mask, dtype=tf.float32)
mask /= tf.reduce_mean(mask)
loss *= tf.transpose(mask)
return tf.reduce_mean(t... | f95f917ff4dd5835c84167f7bf3ea76a4cf6536b | 3,640,580 |
def u0(x):
"""
Initial Condition
Parameters
----------
x : array or float;
Real space
Returns
-------
array or float : Initial condition evaluated in the real space
"""
return sin(pi * x) | bd55cc7226a4d2ca941b8718d62025f6f2e157b6 | 3,640,581 |
import json
def jsonify(value):
"""
Convert a value into a JSON string that can be used for JSONB queries in
Postgres.
If a string happens to contain the character U+0000, which cannot be
represented in a PostgreSQL value, remove the escape sequence representing
that character, effectively st... | 7fff497b302822f8f79f0e68b2576c26458df99c | 3,640,582 |
def generate_dataset(type = 'nlp', test=1):
"""
Generates a dataset for the model.
"""
if type == 'nlp':
return generate_nlp_dataset(test=test)
elif type == 'non-nlp':
return generate_non_nlp_dataset() | 5e8998a6c9e10775367be3d6d4a722f3e24c6be1 | 3,640,584 |
def getAsciiFileExtension(proxyType):
"""
The file extension used for ASCII (non-compiled) proxy source files
for the proxies of specified type.
"""
return '.proxy' if proxyType == 'Proxymeshes' else '.mhclo' | cb2b27956b3066d58c7b39efb511b6335b7f2ad6 | 3,640,586 |
def dist(s1, s2):
"""Given two strings, return the Hamming distance (int)"""
return abs(len(s1) - len(s2)) + sum(
map(lambda p: 0 if p[0] == p[1] else 1, zip(s1.lower(), s2.lower()))) | ef7b3bf24e24a2e49f0c7acfd7bcb8f23fa9af2e | 3,640,587 |
import pickle
def read_bunch(path):
""" read bunch.
:param path:
:return:
"""
file = open(path, 'rb')
bunch = pickle.load(file)
file.close()
return bunch | aec87c93e20e44ddeeda6a8dfaf37a61e837c714 | 3,640,588 |
def cluster_analysis(L, cluster_alg, args, kwds):
"""Given an input graph (G), and whether the graph
Laplacian is to be normalized (True) or not (False) runs spectral clustering
as implemented in scikit-learn (empirically found to be less effective)
Returns Partitions (list of sets of ints)
"""
... | 83114156a0b5517d31e2b2c2ffb7fc0837098db8 | 3,640,589 |
def col_index_list(info, key, value):
"""Given a list of dicts 'info', return a list of indices corresponding to
columns in which info[key] == value. Use to build lists of default columns,
non-exportable columns, etc."""
index_list = list()
if info != None:
for i in range(0, len(info)):
... | af46b03c2fe5bce2ceb7305fd670ce1f0f52ae38 | 3,640,590 |
def sparse_softmax_cross_entropy(logits, labels, weights=1.0, scope=None):
"""Cross-entropy loss using `tf.nn.sparse_softmax_cross_entropy_with_logits`.
`weights` acts as a coefficient for the loss. If a scalar is provided,
then the loss is simply scaled by the given value. If `weights` is a
tensor of size [`b... | dcae4206bdcb147d5bdd4611170f12ba4e371d70 | 3,640,591 |
def retr_radihill(smax, masscomp, massstar):
"""
Return the Hill radius of a companion
Arguments
peri: orbital period
rsma: the sum of radii of the two bodies divided by the semi-major axis
cosi: cosine of the inclination
"""
radihill = smax * (masscomp / 3. / massstar)*... | 5010f66026db7e2544b85f70fd1449f732c024b4 | 3,640,593 |
def load_feature_file(in_feature):
"""Load the feature file into a pandas dataframe."""
f = pd.read_csv(feature_path + in_feature, index_col=0)
return f | 95bb40cc381dab3c29cf81c40d308104e9e4035b | 3,640,594 |
def add_observation_noise(obs, noises, stds, only_object_noise=False):
"""Add noise to observations
`noises`: Standard normal noise of same shape as `obs`
`stds`: Standard deviation per dimension of `obs` to scale noise with
"""
assert obs.shape == noises.shape
idxs_object_pos = SENSOR_INFO_PNP... | 926de82261b6cbd702e3f19f201f82c1a94ca72b | 3,640,595 |
import json
def test_domains(file_path="../../domains.json"):
"""
Reads a list of domains and see if they respond
"""
# Read file
with open(file_path, 'r') as domain_file:
domains_json = domain_file.read()
# Parse file
domains = json.loads(domains_json)
results = {}
for... | 69c6792ee86e90dfdf08a866d2d8e04022dde8c7 | 3,640,596 |
from typing import Dict
from typing import Any
def mix_dirichlet_noise(distribution: Dict[Any, float],
epsilon: float,
alpha: float) -> Dict[Any, float]:
"""Combine values in dictionary with Dirichlet noise. Samples
dirichlet_noise according to dirichlet_alpha i... | f779566b27107f86a92952470c949c69edb623be | 3,640,597 |
def get_video_ID(video_url: str) -> str:
"""Returns the video ID of a youtube video from a URL"""
try:
return parse_qs(urlparse(video_url).query)['v'][0]
except KeyError:
# The 'v' key isn't there, this could be a youtu.be link
return video_url.split("/")[3][:11] | c185a6c5a2c8a5bb4e2d6efd57f325023b030cda | 3,640,598 |
def profiling_csv(stage, phases, durations):
"""
Dumps the profiling information into a CSV format.
For example, with
stage: `x`
phases: ['a', 'b', 'c']
durations: [1.42, 2.0, 3.4445]
The output will be:
```
x,a,1.42
x,b,2.0
x,c,3.444
```
"""
as... | d40ee5601aa201904741870ce75c4b5bfde0f9bc | 3,640,599 |
def int_not_in_range(bounds, inclusive=False):
"""Creates property that must be an int outside bounds[0] and bounds[1].
Parameters:
bounds: Subscriptable with len()==2, where bounds[0] is the lower
bound and bounds[1] is the upper bound.
Requires bounds[1] > bounds[0].
... | 6890cd827fb741329c958a001e48013466414d11 | 3,640,600 |
from typing import Dict
from typing import List
def plot_concordance_pr(
pr_df: pd.DataFrame,
snv: bool,
colors: Dict[str, str] = None,
size_prop: str = None,
bins_to_label: List[int] = None,
) -> Column:
"""
Generates plots showing Precision/Recall curves for truth samples:
Two tabs:
... | 8ad9541605c8f9f274faba03de7e19766341a562 | 3,640,601 |
from enum import Enum
def typehint_metavar(typehint):
"""Generates a metavar for some types."""
metavar = None
if typehint == bool:
metavar = '{true,false}'
elif is_optional(typehint, bool):
metavar = '{true,false,null}'
elif _issubclass(typehint, Enum):
enum = typehint
... | 31b42c29dd970d561917420e789eea6a7bd84cfa | 3,640,602 |
from datetime import datetime
def generate_signed_url(filename):
"""
Generate a signed url to access publicly
"""
found_blob = find(filename)
expiration = datetime.now() + timedelta(hours=1)
return found_blob.generate_signed_url(expiration) | 917f78cfa12496baf655a8ea707143b4922f99c0 | 3,640,603 |
def delete_old_layer_versions(client, table, region, package, prefix):
"""
Loops through all layer versions found in DynamoDB and deletes layer version if it's <maximum_days_older> than
latest layer version.
The latest layer version is always kept
Because lambda functions are created at a maximum... | 291afac422a37cad59a8c2128776567b24c5a0c1 | 3,640,604 |
def _run_simulation(sim_desc):
"""Since _run_simulation() is always run in a separate process, its input
and output params must be pickle-friendly. Keep that in mind when
making changes.
This is what each worker executes.
Given a SimulationDescription object, calls the sequence & binning
code,... | 16cacdb3eaf1fadff8769ab6316eb06e89c226eb | 3,640,605 |
def view_filestorage_file(self, request):
""" Renders the given filestorage file in the browser. """
return getattr(request.app, self.storage).getsyspath(self.path) | ad65b83b9462c8b8efec7626d4751685df3aba8b | 3,640,606 |
def enum_choice_list(data):
""" Creates the argparse choices and type kwargs for a supplied enum type or list of strings """
# transform enum types, otherwise assume list of string choices
if not data:
return {}
try:
choices = [x.value for x in data]
except AttributeError:
c... | 4f91c76569a4b42e655ed198a5c4ec2e48d9e839 | 3,640,607 |
def chartset(request):
""" Conjunto de caracteres que determian la pagina
request: respuesta de la url"""
print "--------------- Obteniendo charset -------------------"
try:
charset = request.encoding
except AttributeError as error_atributo:
charset = "NA"
print "charset: " +... | 072ec863bd555706a64bab48d147afb24142fae4 | 3,640,608 |
import uuid
def generate_UUID():
"""
Generate a UUID and return it
"""
return str(uuid.uuid4()) | feab11861e366ddf60cdc74c12f77f6a6ece2fa3 | 3,640,609 |
def streaming_recall_at_thresholds(predictions, labels, thresholds,
ignore_mask=None, metrics_collections=None,
updates_collections=None, name=None):
"""Computes various recall values for different `thresholds` on `predictions`.
The `streaming_r... | 6cdaa7cf3b0d1c35204764fb78c4f9cefb09b577 | 3,640,610 |
def fib(n):
"""Returns the nth Fibonacci number."""
if n == 0:
return 1
elif n == 1:
return 1
else:
return fib(n - 1) + fib(n - 2) | 397d5714f45491dde68c13379fe2a6acafe55002 | 3,640,611 |
def template_review(context, mapping):
""":phabreview: Object describing the review for this changeset.
Has attributes `url` and `id`.
"""
ctx = context.resource(mapping, b'ctx')
m = _differentialrevisiondescre.search(ctx.description())
if m:
return templateutil.hybriddict({
... | f475cf717026329ecc3c1ed1ccaff89089423e50 | 3,640,614 |
def addRandomEdges(graph: nx.Graph, nEdges: int) -> tuple:
""" Adds random edges to a given graph """
nodes = list(graph.nodes)
n = len(nodes)
edges = []
for i in range(nEdges):
newEdge = False
while not newEdge:
i_u, i_v = np.random.randint(0, n-1), np.random.randint(0, ... | 004723ac17a431a266bae27c91316a66ced507f9 | 3,640,615 |
def get_s3_buckets_for_account(account, region='us-east-1'):
""" Get S3 buckets for a specific account.
:param account: AWS account
:param region: AWS region
"""
session = boto3.session.Session() # create session for Thread Safety
assume = rolesession.assume_crossact_audit_role(
session... | bc2a334bb6c358c43fb97336d3092c27372bd2d0 | 3,640,616 |
def get_users():
""" Alle Benutzer aus der Datenbank laden. """
session = get_cassandra_session()
future = session.execute_async("SELECT user_id, username, email FROM users")
try:
rows = future.result()
except Exception:
log.exeception()
users = []
for row in rows:
... | c6f7b49447dd187e188e9094af3443fe3e4ed218 | 3,640,618 |
def vgconv(xinput,yinput,fwhm, ppr=None):
"""convolution with a Gaussian in log lambda scale
for a constant resolving power
Parameters
----------
xinput: numpy float array
wavelengths
yinput: numpy array of floats
fluxes
fwhm: float
FWHM of the Gaussian (km/s)
ppr: float, optional
... | d4722c87881eca27bac45cd47f84269249591cd0 | 3,640,620 |
def attach_component_to_entity(entity_id, component_name):
# type: (azlmbr.entity.EntityId, str) -> azlmbr.entity.EntityComponentIdPair
"""
Adds the component if not added already.
:param entity_id: EntityId of the entity to attach the component to
:param component_name: name of the component
:r... | f2c29f18ede8eef7accaf19970d18b0a432801ed | 3,640,621 |
import yaml
from io import StringIO
def mix_to_dat(probspec,isStringIO=True):
"""
Reads a YAML mix file and generates all of the GMPL dat components associated with
the mix inputs.
Inputs:
ttspec - the tour type spec object created from the mix file
param_name - string name of paramte... | 972c1118c8d7af6dc8f9ff87908b1ca7184c880e | 3,640,623 |
from typing import Any
def get_setting(setting_name: str, default: Any=None) -> Any:
"""
Convenience wrapper to get the value of a setting.
"""
configuration = get_configuration()
if not configuration: # pragma: no cover
raise Exception('get_setting() called before configuration was initi... | 774ee06824a227ed66357cb46a5277c24ba11f09 | 3,640,624 |
def deceptivemultimodal(x: np.ndarray) -> float:
"""Infinitely many local optima, as we get closer to the optimum."""
assert len(x) >= 2
distance = np.sqrt(x[0]**2 + x[1]**2)
if distance == 0.:
return 0.
angle = np.arctan(x[0] / x[1]) if x[1] != 0. else np.pi / 2.
invdistance = int(1. / ... | c08ab425bbc9803fcea9695c46acee71c2455873 | 3,640,625 |
from aiida.orm import Dict
from aiida_quantumespresso.utils.resources import get_default_options
def generate_inputs_ph(fixture_sandbox, fixture_localhost, fixture_code, generate_remote_data, generate_kpoints_mesh):
"""Generate default inputs for a `PhCalculation."""
def _generate_inputs_ph():
"""Gen... | 4ab1f46ff08094fccd4197a19ab56c31dc1ac93c | 3,640,627 |
from urllib.parse import quote
def escape_url(raw):
"""
Escape urls to prevent code injection craziness. (Hopefully.)
"""
return quote(raw, safe="/#:") | 4eee23f244998d2d2f4abd892a867f2e27f502a2 | 3,640,628 |
def split_sample(labels):
"""
Split the 'Sample' column of a DataFrame into a list.
Parameters
----------
labels: DataFrame
The Dataframe should contain a 'Sample' column for splitting.
Returns
-------
DataFrame
Updated DataFrame has 'Sample' column with a list of strin... | 483f1b78e07a2156aa3e48ae6c1f5ce41f5e60fe | 3,640,629 |
def pmi_odds(pnx, pn, nnx, nn):
"""
Computes the PMI with odds
Args:
pnx (int): number of POSITIVE news with the term x
pn (int): number of POSITIVE news
nnx (int): number of NEGATIVE news with the term x
nn (int): number of NEGATIVE news
Ret... | 5d4786f477fb12051a5a56887a7a7573aeab0802 | 3,640,630 |
def berDecodeLength(m, offset=0):
"""
Return a tuple of (length, lengthLength).
m must be atleast one byte long.
"""
l = ber2int(m[offset + 0:offset + 1])
ll = 1
if l & 0x80:
ll = 1 + (l & 0x7F)
need(m, offset + ll)
l = ber2int(m[offset + 1:offset + ll], signed=0)
... | e93252966e370088274f62bd512d59062e7431b2 | 3,640,631 |
def hasAspect(obj1, obj2, aspList):
""" Returns if there is an aspect between objects
considering a list of possible aspect types.
"""
aspType = aspectType(obj1, obj2, aspList)
return aspType != const.NO_ASPECT | 71907043900d080f2254557fe0bd2420b9bf9ac3 | 3,640,632 |
def gen_decomposition(denovo_name, basis_names, weights, output_path, project, \
mtype, denovo_plots_dict, basis_plots_dict, reconstruction_plot_dict, \
reconstruction=False, statistics=None, sig_version=None, custom_text=None):
"""
Generate the correct plot based on mtype.
Parameters:
----------
denovo_name: ... | 9bb65728017a3f9f2a64ae94cb1ae7e15268c93b | 3,640,633 |
from unittest.mock import Mock
def org(gh):
"""Creates an Org instance and adds an spy attribute to check for calls"""
ret = Organization(gh, name=ORG_NAME)
ret._gh = Mock(wraps=ret._gh)
ret.spy = ret._gh
return ret | 017d044015ff60c91742ea2eb12e2cd7720328c6 | 3,640,634 |
def merge_regions(
out_path: str, sample1_id: int, regions1_file: File, sample2_id: int, regions2_file: File
) -> File:
"""
Merge two sorted region files into one.
"""
def iter_points(regions):
for start, end, depth in regions:
yield (start, "start", depth)
yield (en... | eeb4b8bf73df45ae9d6af39d0d8c9db04251da41 | 3,640,635 |
import hashlib
def get_text_hexdigest(data):
"""returns md5 hexadecimal checksum of string/unicode data
NOTE
----
The md5 sum of get_text_hexdigest can differ from get_file_hexdigest.
This will occur if the line ending character differs from being read in
'rb' versus 'r' modes.
"""
da... | 762115178406c0b49080b3076859a3d1c13ad356 | 3,640,636 |
import json
def recipe(recipe_id):
"""
Display the recipe on-page for each recipe id that was requested
"""
# Update the rating if it's an AJAX call
if request.method == "POST":
# check if user is login in order to proceed with rating
if not session:
return json.dumps({... | 60db178d071d1880410e4e752ec484c4b59b0f96 | 3,640,637 |
def api_program_ordering(request, program):
"""Returns program-wide RF-aware ordering (used after indicator deletion on program page)"""
try:
data = ProgramPageIndicatorUpdateSerializer.load_for_pk(program).data
except Program.DoesNotExist:
logger.warning('attempt to access program page orde... | d4966689b0ea65885456ad7b52cf5dfd845ac822 | 3,640,638 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.