content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def wkt_to_proj4(wkt):
"""Converts a well-known text string to a pyproj.Proj object"""
srs = osgeo.osr.SpatialReference()
srs.ImportFromWkt(wkt)
return pyproj.Proj(str(srs.ExportToProj4())) | 17796040f4bac614d520591a5b41396cfca5a514 | 3,627,100 |
def runtime_expand1(bindings, filename, tree):
"""Macro-expand an AST value `tree` at run time, once. Run-time part of `expand1r`.
`bindings` and `filename` are as in `mcpyrate.core.BaseMacroExpander`.
Convenient for experimenting with quoted code in the REPL.
"""
expander = MacroExpander(bindings... | f1d22f6e4dd494d6febdd2088fa9a70b05e534b4 | 3,627,101 |
def elasticnet(exprDF, lMirUser = None, lGeneUser = None, n_core = 2):
"""
Function to calculate the ElasticNet correlation coefficient
of each pair of miRNA-mRNA, return a matrix of correlation coefficients
with columns are miRNAs and rows are mRNAs.
Args:
exprDF df Concat Dataframe ... | 8255b549743c65777574e6847b449f0badb121bf | 3,627,102 |
def get_batch_unpack(args): # arguments dictionary
""" Pass through function for unpacking get_batch arguments.
Args:
args: Arguments dictionary
Returns:
Return value of get_batch.
"""
# unpack args values and call get_batch
return get_batch(tensors=args['tensors'],
... | 2a47792afcf95575d1b70138faffbb55eca1a622 | 3,627,103 |
import six
def simple_unlimited_args(one, two='hi', *args):
"""Expected simple_unlimited_args __doc__"""
return "simple_unlimited_args - Expected result: %s" % (', '.join(six.text_type(arg) for arg in [one, two] + list(args))) | 63cbd2d532cb638af8ff3964e1148e1bcabf632d | 3,627,104 |
def _random_subset(seq, m, rng):
"""
Return m unique elements from seq.
This differs from random.sample which can return repeated
elements if seq holds repeated elements.
Taken from networkx.generators.random_graphs
"""
targets = set()
while len(targets) < m:
x = rng.choice(seq... | 64a174d55a64b73eb55f3f795156733911a54802 | 3,627,105 |
def rnn_forward(x, nb_units, nb_layers, rnn_type, name, drop_rate=0., i=0, activation='tanh', return_sequences=False):
"""Multi-RNN layers.
Parameters
----------
nb_units: int, the dimensionality of the output space for
recurrent neural network.
nb_layers: int, the number of the layers for ... | dd1e3b8f6c76bc67687219748bc98668c1edc046 | 3,627,106 |
def lambda_handler(*kwargs):
""" Lambda handler for usercount
:param event: Lambda event
:param context: Lambda context
"""
print kwargs[0].get('account')
function_name = kwargs[1].function_name
account = kwargs[0].get('account')
results = get_user_count(function_name, account)
body ... | 1b1d2a00a98a00a0197cf59154d35baa9111b193 | 3,627,107 |
import sys
def notebook_is_active() -> bool:
"""Return if script is executing in a IPython notebook (e.g. Jupyter notebook)"""
for x in sys.modules:
if x.lower() == 'ipykernel':
return True
return False | 200962d831c75d636b310aafa0c8cc4e664e0b4a | 3,627,108 |
def lstm_cond_layer(tparams, state_below, options, prefix='lstm',
mask=None, init_memory=None, init_state=None,
trng=None, use_noise=None,
**kwargs):
"""
Computation graph for the conditional LSTM.
"""
nsteps = state_below.shape[0]
n_sample... | ddb443a6bdbe2f25a231f5df660036b682bc337f | 3,627,109 |
from typing import Generator
def get_frame_tree() -> Generator[dict, dict, FrameTree]:
"""Returns present frame tree structure.
Returns
-------
frameTree: FrameTree
Present frame tree structure.
"""
response = yield {"method": "Page.getFrameTree", "params": {}}
return FrameTre... | 9a79281fbd6a9b469c8f7ef7746fe6a3e7b5156c | 3,627,110 |
def lddmm_transform_points(
points,
deform_to="template",
# lddmm_register output (lddmm_dict).
affine_phi=None,
phi_inv_affine_inv=None,
template_resolution=1,
target_resolution=1,
**unused_kwargs,
):
"""
Apply the transform, or position_field, to an array of points to transform... | c63b032f25fa9b0bd50b7072fdb59d76ed68c170 | 3,627,111 |
def check_sanitization(mol):
"""
Given a rdkit.Chem.rdchem.Mol this script will sanitize the molecule.
It will be done using a series of try/except statements so that if it fails it will return a None
rather than causing the outer script to fail.
Nitrogen Fixing step occurs here to correct for a co... | 5014508cbde6ea1a89beeca106f0adeae1422817 | 3,627,112 |
import argparse
def build_parser():
"""Parser to grab and store command line arguments"""
MINIMUM = 200000
SAVEPATH = "data/raw/"
parser = argparse.ArgumentParser()
parser.add_argument(
"subreddit", help="Specify the subreddit to scrape from")
parser.add_argument("-m", "--minimum",
... | d4f3eb484423416d3cb83ad64784747a8f453d98 | 3,627,113 |
from typing import Union
import re
def extract_msg(log: str, replica_name: str) -> Union[str, None]:
"""
Extracts a message from a single log
Parameters
----------
log
full log string
replica_name
identity name of replica
Returns
-------
msg
message sent f... | da17f008af059d70cc4cc969bc03aa34ed846e0f | 3,627,114 |
def tf_dmdm_fid(rho, sigma):
"""Trace fidelity between two density matrices."""
# TODO needs fixing
rhosqrt = tf.linalg.sqrtm(rho)
return tf.linalg.trace(
tf.linalg.sqrtm(tf.matmul(tf.matmul(rhosqrt, sigma), rhosqrt))
) | 057b01193412ee863cb431fd6b270492fd575125 | 3,627,115 |
def LF_report_is_short_demo(x):
"""
Checks if report is short.
"""
return NORMAL if len(x.text) < 280 else ABSTAIN | 525fdbdf910c21d28824a4bf371dec069e9a7abb | 3,627,116 |
from typing import Optional
def binarize_swf(
scores: SlidingWindowFeature,
onset: float = 0.5,
offset: float = 0.5,
initial_state: Optional[bool] = None,
):
"""(Batch) hysteresis thresholding
Parameters
----------
scores : SlidingWindowFeature
(num_chunks, num_frames, num_cla... | 3e578608501887943e0918b13fc6dcc10585685e | 3,627,117 |
import sys
def invlogit(x, eps=sys.float_info.epsilon):
"""The inverse of the logit function, 1 / (1 + exp(-x))."""
return (1.0 - 2.0 * eps) / (1.0 + tt.exp(-x)) + eps | bbdf200fa8e79d97aae4cd71e727eb75489e7242 | 3,627,118 |
import torch
import time
def train_pytorch_ch7(optimizer_fn, optimizer_hyperparams, features, labels,
batch_size=10, num_epochs=2):
"""
The training function of chapter7, but this is the pytorch library version
Parameters
----------
optimizer_fn : [function]
the opti... | 4b60531b47fc58df0c61bd36cdb77ac8a137ba76 | 3,627,119 |
def ProcessOptionInfileParameters(ParamsOptionName, ParamsOptionValue, InfileName = None, OutfileName = None):
"""Process parameters for reading input files and return a map containing
processed parameter names and values.
Arguments:
ParamsOptionName (str): Command line input parameters option ... | ece155282aef5c7ba365ce54c529998590146043 | 3,627,120 |
import logging
def user_annotation_for_application() -> UserInputClass:
"""
Make info from user annotation
1. Original File
2. VM Runtime configuration
3. Target Goal
3. Function service with parameters
"""
# Fist make dataclass and save default values
user_input_class = UserInput... | a4473128a86253ea8bddc533a84bdf893e49853a | 3,627,121 |
def brier_score(y_true, y_pred):
"""Brier score
Computes the Brier score between the true labels and the estimated
probabilities. This corresponds to the Mean Squared Error between the
estimations and the true labels.
Parameters
----------
y_true : label indicator matrix (n_samples, n_clas... | 06a457db29de6e5943900000ea5395cbffac2ab5 | 3,627,122 |
from typing import Tuple
def computeD1D2(current: float, volatility: float, ttm: float, strike: float,
rf: float) -> Tuple[float, float]:
"""Helper function to compute the risk-adjusted priors of exercising the
option contract, and keeping the underlying asset. This is used in the
computat... | 76dc53df4bde1c2974749bf10f007ba3c8e748ff | 3,627,123 |
def control_event(data_byte1, data_byte2=0, channel=1):
"""Return a MIDI control event with the given data bytes."""
data_byte1 = muser.utils.key_check(data_byte1, CONTROL_BYTES, 'upper')
return (STATUS_BYTES['CONTROL'] + channel - 1, data_byte1, data_byte2) | 5195d1236f1cd4441281777ab1a50591b3b9fbe0 | 3,627,124 |
def create_noise_mask(mean, variance, threshold=25):
"""Creates a binary data mask based on quartile
thresholds from two mean and variance arrays.
Parameters
----------
mean : numpy array
Array containing pixel mean values.
variance : numpy array
Array containing pixel variance... | 40dc9907e0a65a28cdf81a3b76e11754d15257fe | 3,627,125 |
def initialCondition1D(u, a):
"""
use this function only if initial condition != 0 is needed ?????
"""
nx = u.size
ul = np.zeros(nx)
ul[1:nx-1] = u[1:nx-1]+0.5*a[1:nx-1]**2*(u[2:]-2*u[1:nx-1]+u[0:nx-2])
return ul | 8047a95fe733867e4dcf1c30acdb130fdc4ff9f6 | 3,627,126 |
def learnability_objective_function(throughput, delay):
"""Objective function used in https://cs.stanford.edu/~keithw/www/Learnability-SIGCOMM2014.pdf
throughput: Mbps
delay: ms
"""
score = np.log(throughput) - np.log(delay)
# print(throughput, delay, score)
score = score.replace([np.inf, -n... | 9646af095668bf0c449f2ec05319c1cc35d59d39 | 3,627,127 |
def partition_graph(graph, partitions):
"""
Create a new graph based on `graph`, where nodes are aggregated based on
`partitions`, similar to :func:`~networkx.algorithms.minors.quotient_graph`,
except that it only accepts pre-made partitions, and edges are not given
a 'weight' attribute. Much fast t... | 98aae7e3c3354a04b30c005c6e0183676f983234 | 3,627,128 |
import logging
def __misc_badbarcode():
"""DEPRECATED: setting badbarcode boolean. Use /misc/itemattr instead.
Gets or Sets the barcode-okayness of a SKU.
This will return the barcode state of a SKU in a GET message, and will set the barcode state of a SKU in a POST message.
:param int sku: The... | dcc02a80348cc327e3705c8392724eecc6243610 | 3,627,129 |
def lzip(*args):
"""
this function emulates the python2 behavior of zip (saving parentheses in py3)
"""
return list(zip(*args)) | 92aa6dea9d4058e68764b24eb63737a2ec59a835 | 3,627,130 |
def sanitize_url(url: str) -> str:
"""
This function strips to the protocol, e.g., http, from urls.
This ensures that URLs can be compared, even with different protocols, for example, if both http and https are used.
"""
prefixes = ["https", "http", "ftp"]
for prefix in prefixes:
if url... | 9c61a9844cfd6f96e158a9f663357a7a3056abf0 | 3,627,131 |
from typing import Dict
from typing import Union
def trimming_parameters(
library_type: LibraryType,
trimming_min_length: int
) -> Dict[str, Union[str, int]]:
"""
Derive trimming parameters based on the library type, and minimum allowed trim length.
:param library_type: The LibraryType (e... | 9eb891eb685a0163c7df0d3d8946606ad54ea11d | 3,627,132 |
def make_nn(output_size, hidden_sizes):
"""
Creates a fully connected neural network.
Params:
output_size: output dimensionality
hidden_sizes: list of hidden layer sizes. List length is the number of hidden layers.
"""
NNLayers = [tf.keras.layers.Dense(h, activation=tf.nn.relu,... | 66945e649f8dba407e72fb9790eb2f23d052d6fb | 3,627,133 |
def image_to_world(bbox, size):
"""Function generator to create functions for converting from image coordinates to world coordinates"""
px_per_unit = (float(size[0])/bbox.width, float(size[1]/bbox.height))
return lambda x,y: (x/px_per_unit[0] + bbox.xmin, (size[1]-y)/px_per_unit[1] + bbox.ymin) | 35fcfbf8e76e0ec627da9bf32a797afdae11fe17 | 3,627,134 |
def error_func(A, b, x, x_star, fold=50):
"""Calculate errors ||Ax_1-b||-||Ax_star-b||, where x1 \in x.
Param:
A: n*d np.ndarray, coefficient in ||Ax-b||
b: n*1 np.ndarray, coefficient in ||Ax-b||
x: tuple, (x_linBoost, x_inverse, x_cholesky)
x_star: d*1 np.ndarray, x* by lstsq()... | 59a6aae4566fcb8406b5e495727550790f9958ff | 3,627,135 |
def git_reset_all():
"""Function that unstages all files in repo for commit.
Returns
-------
out : str
Output string from stdout if success, stderr if failure
err : int
Error code if failure, 0 otherwise.
"""
command = 'git reset HEAD'
name = 'git_reset_all'
return ... | 6b3aea4d7cde04cbe5b81ccc58c2dc2bf2f6d1bc | 3,627,136 |
def find_kern_timing(df_trace):
"""
find the h2d start and end for the current stream
"""
kern_begin = 0
kern_end = 0
for index, row in df_trace.iterrows():
if row['api_type'] == 'kern':
kern_begin = row.start
kern_end = row.end
break;
return kern... | 2e121e7a9f7ae19f7f9588b0105f282c59f125ba | 3,627,137 |
def Get(SyslogSource, WorkspaceID):
"""
Get the syslog conf for specified workspace from the machine
"""
if conf_path == oms_syslog_ng_conf_path:
NewSource = ReadSyslogNGConf(SyslogSource, WorkspaceID)
else:
NewSource = ReadSyslogConf(SyslogSource, WorkspaceID)
for d in NewSourc... | e8b6613e821336644cdfe9c4091e914f9ec1c8ac | 3,627,138 |
def partie_reelle(c : Complexe) -> float:
"""Renvoie la partie réelle du nombre complexe c.
"""
re, _ = c
return re | 555ded6a3814002a7ddc1c74467a9002a2bb341d | 3,627,139 |
def get_client_folder_id(drive_service):
"""
Returns the client folder to take the backups
TODO fetch client name
"""
client_name = frappe.db.get_value("ConsoleERP Settings", filters="*", fieldname="client_name")
if not client_name:
print("Client Name not set")
return None
print("Client Name: %s" % client... | 237793089ed98d92630d25fa9fbe859f6dad7214 | 3,627,140 |
from bs4 import BeautifulSoup
import re
def get_event_data(url: str) -> dict:
"""connpassイベントページより追加情報を取得する。
Parameters
----------
url : str
connpassイベントのurl。
Returns
-------
event_dict : dict[str, Any]
イベント情報dict。
"""
try:
html = urlopen(url)
... | bbb95eba99c57c07c4067f47cf47d69f6260d45b | 3,627,141 |
def overlap_branches(targetbranch: dict, sourcebranch: dict) -> dict:
"""
Overlaps to dictionaries with each other. This method does apply changes
to the given dictionary instances.
Examples:
>>> overlap_branches(
... {"a": 1, "b": {"de": "ep"}},
... {"b": {"de": {"eper"... | a11b54b72d4a7d79d0bfaa13ed6c351dd84ce45f | 3,627,142 |
def get_dependencies(node, skip_sources=False):
"""Return a list of dependencies for node."""
if skip_sources:
return [
get_path(src_file(child))
for child in filter_ninja_nodes(node.children())
if child not in node.sources
]
return [get_path(src_file(chil... | 2f5589f99e240b1e0c3dfed1106275e6725eae2e | 3,627,143 |
def depolarizing_channel_3q(q, p, system, ancillae):
"""Returns a QuantumCircuit implementing depolarizing channel on q[system]
Args:
q (QuantumRegister): the register to use for the circuit
p (float): the probability for the channel between 0 and 1
system (int): index of the system qub... | 154e129dd6865dccff0a172df43f52df11df0004 | 3,627,144 |
def resample_30s(annot):
"""resample_30s: to resample annot dataframe when durations are multiple
of 30s
Parameters:
-----------
annot : pandas dataframe
the dataframe of annotations
Returns:
--------
annot : pandas dataframe
the resampled dataframe of annotations
"... | 761ba6d624f7911873f3a980925c81ef6d0266dc | 3,627,145 |
def jamoToHang(jamo: str):
"""자소 단위(초, 중, 종성)를 한글로 결합하는 모듈입니다.
@status `Accepted` \\
@params `"ㅇㅏㄴㄴㅕㅇㅎㅏ_ㅅㅔ_ㅇㅛ_"` \\
@returns `"안녕하세요"` """
result, index = "", 0
while index < len(jamo):
try:
initial = chosung.index(jamo[index]) * 21 * 28
midial = jungsung.i... | 875d189f8547b637a13eb7b7eeba584044fbe484 | 3,627,146 |
def calc_Vs30(profile, option_for_profile_shallower_than_30m=1, verbose=False):
"""
Calculate Vs30 from the given Vs profile, where Vs30 is the reciprocal of
the weighted average travel time from Z meters deep to the ground surface.
Parameters
----------
profile : numpy.ndarray
Vs profi... | 3d66287836eec960b494617cb652478327ab0067 | 3,627,147 |
import torch
from typing import Optional
from typing import Dict
from typing import Any
def prepare_model(
model: torch.nn.Module,
move_to_device: bool = True,
wrap_ddp: bool = True,
ddp_kwargs: Optional[Dict[str, Any]] = None,
) -> torch.nn.Module:
"""Prepares the model for distributed execution.... | 28b1b9f3140c4782e3e6eb9fd1345c3bdec7b88f | 3,627,148 |
def make_legend_labels(dskeys=[], tbkeys=[], sckeys=[], bmkeys=[], plkeys=[],
dskey=None, tbkey=None, sckey=None, bmkey=None, plkey=None):
"""
@param dskeys : all datafile or examiner keys
@param tbkeys : all table keys
@param sckeys : all subchannel keys
@param bmkeys : all beam keys
@pa... | a8b17916f896b7d8526c5ab7ae3cf4a7435627e2 | 3,627,149 |
import csv
import sys
def import_summary_tsv_data(file):
"""
Import the data from a summary_qc.tsv file
"""
_qc = dict()
with open(file, 'r') as ifh:
reader = csv.DictReader(ifh, delimiter='\t')
for item in reader:
if item['sample'] not in _qc:
_qc.updat... | 8c4ca80ed15bcd59ff773320d26579d248b61b7a | 3,627,150 |
def get_parameter_change(old_params, new_params, ord='inf'):
"""Measure the change in parameters.
Parameters
----------
old_params : list
The old parameters as a list of ndarrays, typically from
session.run(var_list)
new_params : list
The old parameters as a list of ndarrays... | dc2f15c53b1c65acdfb60d25fd70f9c21f046b70 | 3,627,151 |
def get_image_dir():
"""Return the `image_dir` set in the current context."""
return get_data_context().image_dir | 44557bc421ba14212c089970dcc7f33978ac83fe | 3,627,152 |
import collections
def get_interface_config_vlan():
"""
Return the interface configuration parameters for all IP static
addressing.
"""
parameters = collections.OrderedDict()
parameters['VLAN'] = 'yes'
return parameters | 61ef6affba231af19e4030c54bfcaaaa15a6438f | 3,627,153 |
def get_browser(sport, debug=False):
"""
Use selenium and chromedriver to do our website getting.
Might as well go all the way.
:param debug: whether to set the browser to debug mode
:param headless: go headless
:return:
"""
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--use... | 2c0e975f63c8b6e2c61f9be18a76c86b0503d8b1 | 3,627,154 |
def parsear_ruta(linea):
"""
Lee una linea del archivo de rutas, separa los campos, y devuelve un objeto Ruta armado apropiadamente.
Si hay un error al aplicar split, y hay menos campos de los esperados, devuelve None.
Si algun valor no tiene el formato apropiado (documentado en la clase) devuelve None.
Si la ciud... | 934122d266fa799e79812613cbb539bd8ebd501d | 3,627,155 |
def split_channel_groups(data,meta):
"""
With respect to the sensor site, a different number of channels is given.
In both sites the first 160 channels contain the meg data.
params:
-------
data: array w/ shape (160+type2channels+type3channels,time_samples)
meta:
returns:
... | 399bd66b6aa7681ac67db73c6c68aae1b5f7ba72 | 3,627,156 |
from .core import read_byte_data
def _read_header_byte_data(header_structure):
""" Reads the byte data from the data file for a PDS4 Header.
Determines, from the structure's meta data, the relevant start and stop bytes in the data file prior to
reading.
Parameters
----------
header_structure... | 7115d8ecdb4ef511fd0a7b0d74e0f8484673aaf7 | 3,627,157 |
import numbers
def check_random_state(seed):
"""Turn seed into a np.random.RandomState instance
Parameters
----------
seed : None | int | instance of RandomState
If seed is None, return the RandomState singleton used by np.random.
If seed is an int, return a new RandomState instance s... | dbb76ad1094b2d4cb2acb7d0fb7d59290ed6fd78 | 3,627,158 |
import os
import json
def repolist(orgname, refresh=True):
"""Return list of repos for a GitHub organization.
If refresh=False, we use the cached data in /data/repos{orgname}.json and
don't retrieve the repo data from GitHub API.
Returns tuples of (reponame, size). Note that this is the size returne... | 5e3d3dacbf2ed3f638f068e9c7f2bd32e143b9e5 | 3,627,159 |
def normalize_string(value):
""" Normalize a string value. """
if isinstance(value, bytes):
value = value.decode()
if isinstance(value, str):
return value.strip()
raise ValueError("Cannot convert {} to string".format(value)) | 86d8134f8f83384d83da45ed6cb82841301e2e52 | 3,627,160 |
def _is_test_env(env_config: tox.config.TestenvConfig) -> bool:
"""Check if it is a test environment.
Tox creates environments for provisioning (`.tox`) and for isolated build
(`.packaging`) in addition to the usual test environments. And in hooks
such as `tox_testenv_create` it is not clear if the env... | bf2d9ebdc3e8d3428a5bbc0d27abd0ecc10ca6be | 3,627,161 |
def latest_version():
"""Return the latest version of Windows git available for download."""
soup = get_soup('https://git-scm.com/download/win')
if soup:
tag = soup.find('a', string='Click here to download manually')
if tag:
return downloadable_version(tag.attrs['href'])
retu... | 35563a0da6eb42e619609dd8d646a7bd5033b5da | 3,627,162 |
from datetime import datetime
def get_interval_date_list_by_freq_code(start_date, end_date, freq_code):
"""
:param freq_code: D, W, M
"""
end_date_list = get_end_date_list_by_freq_code(start_date, end_date, freq_code)
start_date = start_date
interval_date_list = []
for end_date in end_da... | 34ce484294f62ef6e7f0726e73f0c502f2c56f01 | 3,627,163 |
from distutils.version import StrictVersion
from distutils.spawn import find_executable
import re
import os
def get_versions():
""" Try to find out the versions of gcc and ld.
If not possible it returns None for it.
"""
gcc_exe = find_executable('gcc')
if gcc_exe:
out = os.popen(gcc_e... | 3774f0fe270733512b3a6c1cb3e361a1cb90a362 | 3,627,164 |
def _rotate_move(move, axis, n=1):
"""Rotate a move clockwise about an axis
The axis of rotation should correspond to a primitive rotation operation of
a cube Face.
"""
if n == 0:
return move
table = {
Face.U: {
'U': 'U',
'D': 'D',
'U\'': ... | 12554560bc9f2b65c101ace74b179cb252bdb62b | 3,627,165 |
def mapAddress(name):
"""Given a register name, return the address of that register.
Passes integers through unaffected.
"""
if type(name) == type(''):
return globals()['RCPOD_REG_' + name.upper()]
return name | 21f2f9a085d259d5fd46b258cc3ee0298fdda158 | 3,627,166 |
def list_index(ls, indices):
"""numpy-style creation of new list based on a list of elements and another
list of indices
Parameters
----------
ls: list
List of elements
indices: list
List of indices
Returns
-------
list
"""
return [ls[i] for i in indices] | 7e5e35674f48208ae3e0befbf05b2a2e608bcdf0 | 3,627,167 |
def create_seed_population(cities, howmany):
"""Create a seed file with tours generated by the nearest-neighbour
algorithm.
"""
attr = OrderedIndividual.get_attributes()
attr['osi.num_genes'] = len(cities) - 1
tours = generate_nntours(cities, howmany)
pop = []
for i in range(len(tours))... | 1b5338f687c0780b85c6788fe9891a10c9ee9633 | 3,627,168 |
import io
import re
def copyright_present(f):
"""
Check if file already has copyright header.
Args:
f - Path to file
"""
with io.open(f, "r", encoding="utf-8") as fh:
return re.search('Copyright', fh.read()) | afbffde0ab51984dab40d296f8ad9ca29829aef1 | 3,627,169 |
import math
def calc_LFC(in_file_2, bin_list):
"""
Mods the count to L2FC in each bin
"""
#for itereating through the bin list
bin_no=0
header_line = True
with open(in_file_2, 'r') as f:
for bin_count in f:
if header_line:
header_line = False
... | 379035fa4972c956d9734b958f3e81a3792c96d6 | 3,627,170 |
def parse_value(named_reg_value):
"""
Convert the value returned from EnumValue to a (name, value) tuple using the value classes.
"""
name, value, value_type = named_reg_value
value_class = REG_VALUE_TYPE_MAP[value_type]
return name, value_class(value) | 9e77edad1cee75973ea06c0cb2bfe6ec217abc2e | 3,627,171 |
def construct_model_vector(df, n):
"""
Convert a dataframe to an array of numpy vectors which are of the form
[(1-hot encoding of position), (game stats for n games leading up to this
one for a given player)]. If there are p positions and s stats this
vector will be of dimension p + s * n.
... | 019c5072a536e6910b2ef2a3ec9ae3682d949f10 | 3,627,172 |
import os
def poscar_parser_file_object():
"""Load POSCAR file using a file object.
"""
testdir = os.path.dirname(__file__)
poscarfile = testdir + '/POSCAR'
poscar = None
with open(poscarfile) as file_handler:
poscar = Poscar(file_handler=file_handler)
return poscar | b642bbbedefa33fd612c65e49a9aa9e63caa7754 | 3,627,173 |
import yaml
def parse_json(file_handle):
"""Parse a repeats file in the .json format
Args:
file_handle(iterable(str))
Returns:
repeat_info(dict)
"""
repeat_info = {}
try:
raw_info = yaml.safe_load(file_handle)
except yaml.YAMLError as err:
raise SyntaxErro... | 889c99594c7d92dd278caefc2af2e71fdfb0354b | 3,627,174 |
def get_value(obj, expr):
"""
Extracts value from object or expression.
"""
if isinstance(expr, F):
expr = getattr(obj, expr.name)
elif hasattr(expr, 'value'):
expr = expr.value
return expr | 9413f762e6ed19895bbbfda8da5f258bba387c80 | 3,627,175 |
from inspect import ismethod
from typing import Iterable
def _get_common_evented_attributes(
layers: Iterable[Layer],
exclude: set[str] = {'thumbnail', 'status', 'name', 'data'},
with_private=False,
) -> set[str]:
"""Get the set of common, non-private evented attributes in ``layers``.
Not all lay... | 33ce31cd98659f295f45e33788cfa69510ddb640 | 3,627,176 |
def farthest_from_point(point, point_set):
"""
find the farthest point in point_set from point and return its coordinate and its distance squared to point_set
"""
record = []
for i in point_set:
distance = euclidean_distance_square(point, i)
record.append([i, distance])
# create ... | a2105d7e96e6289f9d67aff08d3fc1934fa05a0b | 3,627,177 |
import subprocess
import time
def start_app():
"""
ASSUMES AN EMULATOR HAS ALREADY BEEN STARTED.
Starts the calculator program, finds the pid, and instantiates a
TestMutator object.
"""
subprocess.call(["adb", "shell", "am start " + PACKAGE])
time.sleep(10)
bits = subproce... | 5be6e57a7401530b4751f8e77485762e70a2fe4c | 3,627,178 |
def get_subtypes():
"""Get all available subtypes"""
subtypes = []
for subtype in Subtype:
subtypes.append(subtype.value)
return subtypes | 61b858731812e1e8fe67c4a09d9bcde2cbe6c596 | 3,627,179 |
def clean_dict(dictionary: dict) -> dict:
"""Recursively removes `None` values from `dictionary`
Args:
dictionary (dict): subject dictionary
Returns:
dict: dictionary without None values
"""
for key, value in list(dictionary.items()):
if isinstance(value, dict):
... | 3968b6d354116cca299a01bf2c61d7b2d9610da9 | 3,627,180 |
def create_emoticon_stream(table, n_hours=None):
"""Creates a twitter stream object that will insert queries into
object and will terminate in n_hours
Parameters:
-----------
table: connection to mongodb table
n_hours: number of hours to run before termination, default = None
Returns:
... | 62b1eb58a81d0ce7d2e752368c3b7a969b87736d | 3,627,181 |
def tag_tranfsers(df):
"""Tag txns with description indicating tranfser payment."""
df = df.copy()
tfr_strings = [' ft', ' trf', 'xfer', 'transfer']
exclude = ['fee', 'interest']
mask = (df.transaction_description.str.contains('|'.join(tfr_strings))
& ~df.transaction_description.str.cont... | 4fdfd775ec423418370776c34fac809a513f91b5 | 3,627,182 |
from typing import Optional
from typing import Tuple
from typing import List
from typing import Dict
def calc_box(
df: dd.DataFrame,
bins: int,
ngroups: int = 10,
largest: bool = True,
dtype: Optional[DTypeDef] = None,
) -> Tuple[pd.DataFrame, List[str], List[float], Optional[Dict[str, int]]]:
... | 2ad140d7897c1a12c72a4084837fde01667b0eda | 3,627,183 |
def remove_dead_exceptions(graph):
"""Exceptions can be removed if they are unreachable"""
def issubclassofmember(cls, seq):
for member in seq:
if member and issubclass(cls, member):
return True
return False
for block in list(graph.iterblocks()):
if not b... | fc0c810eef726f0979678e3003051c99775a981d | 3,627,184 |
def borda_matrix(lTuple):
"""
Function to use the Borda count election
to integrate the rankings from different miRNA
coefficients.
Args:
lTuple list List of tuples with the correlation matrix, an the
name of the analysis (df,"value_name")
Returns:
... | 405ff7c469b9fc4026de899ab7a46e959c2280cc | 3,627,185 |
import sys
def plotHeatmap(fcsDF, x, y, vI=sentinel, bins=300, scale='linear', xscale='linear', yscale='linear', thresh=1000, aspect='auto', **kwargs):
"""
Core plotting function of AliGater. Mainly intended to be called internally, but may be called directly.
Only plots. No gating functionalities.
... | 3051f0840568be8bba6c5884385dec881e91055d | 3,627,186 |
def _ImportModuleHookBySuffix(name, package=None):
"""Callback when a module is imported through importlib.import_module."""
_IncrementNestLevel()
try:
# Really import modules.
module = _real_import_module(name, package)
finally:
if name.startswith('.'):
if package:
name = _ResolveRel... | 1d9b11cec308e1a74c2aaac138c5cb3edefce62b | 3,627,187 |
import copy
def from_fake(dbc_db,
signals_properties,
file_hash_blf=("00000000000000000000000000000000"
"00000000000000000000000000000000"),
file_hash_mat=("00000000000000000000000000000000"
"00000000000000000000000000... | c7fb3f188893f6f52f9624c6a051a060bb189fad | 3,627,188 |
def frozen(request: HttpRequest):
""" Заглушка для редиректа со страниц с замороженным функционалом """
context = {'title': _('Frozen feature')}
return render(request, template_name='core/frozen.html', context=context) | bb745cb5af702af074423f048e29a60664b7dda4 | 3,627,189 |
import os
def find_root_path(resource_name, extension):
""" Find root path, given name and extension
(example: "/home/pi/Media")
This will return the *first* instance of the file
Arguments:
resource_name -- name of file without the extension
extension -- ending of file (ex: ".json")
... | 6bdd2a0c7e1ed8ea57cc41806773d70f8dcf096b | 3,627,190 |
def zero_intensity_flag(row, name_group):
"""Check if the mean intensity of certain group of samples is zero. If zero, then
the metabolite is not existed in that material.
# Arguments:
row: certain row of peak table (pandas dataframe).
name_group: name of the group.
# Returns:
... | f71b9906032c61988ff3eeccd57fb228d1049526 | 3,627,191 |
def ComputeCountryTimeSeriesWaterChange(country_id, feature = None, zoom = 1):
"""Returns a series of water change over time for the country."""
collection = ee.ImageCollection('JRC/GSW1_0/YearlyHistory')
collection = collection.select('waterClass')
scale = REDUCTION_SCALE_METERS
if feature is None:
fea... | 57c20c4b02b66afe6ba8d05ce15f1a4259818a91 | 3,627,192 |
import os
def get_abspath(filepath):
"""helper function to facilitate absolute test file access"""
return os.path.join(TESTDATA_DIR, filepath) | 29faad6a1c4b554793e6bd3a9ffddacfcc394afd | 3,627,193 |
import os
def get_wiki_img():
"""
Returns a path to local image.
"""
this = os.path.dirname(__file__)
img = os.path.join(this, "wiki.png")
if not os.path.exists(img):
raise FileNotFoundError("Unable to find '{}'.".format(img))
return img | ef522391665830019f7b48f545291d81b528bd45 | 3,627,194 |
import time
def get_largest_component(G, strongly=False):
"""
Return the largest weakly or strongly connected component from a directed
graph.
Parameters
----------
G : networkx multidigraph
strongly : bool
if True, return the largest strongly instead of weakly connected
c... | 67fe084033c54babc2ee5301ad97a9d00bab77d9 | 3,627,195 |
import importlib
import os
def get_git_versions(repos, get_dirty_status=False, verbose=0):
""" Returns the repository head guid and dirty status and package version number if installed via pip.
The version is only returned if the repo is installed as pip package without edit mode.
NOTE: currently ... | 78ee6dabffe8ca49c338827be6ca37b6a3956a48 | 3,627,196 |
def _argmin(t: 'Tensor', axis=None, isnew: bool = True) -> 'Tensor':
"""
Also see:
--------
:param t:
:param axis:
:param isnew:
:return:
"""
data = t.data.argmin(axis = axis)
requires_grad = t.requires_grad
if isnew:
requires_grad = False
if requires_grad:
... | 19dd2e9ed604f4296f08381d5b80affb9472fc2c | 3,627,197 |
def new_measure_get_activity_activity(data: dict) -> MeasureGetActivityActivity:
"""Create GetActivityActivity from json."""
timezone = timezone_or_raise(data.get("timezone"))
return MeasureGetActivityActivity(
date=arrow_or_raise(data.get("date")).replace(tzinfo=timezone),
timezone=timezon... | dc77b0bc1528a409064626fd2f9c1527058d37a2 | 3,627,198 |
import os
def establecer_destino_archivo_imagen(instance, filename):
"""
Establece la ruta de destino para el archivo de imagen cargado a la instancia.
"""
# Almacena el archivo en:
# 'app_reservas/contingencia/<id_imagen>'
ruta_archivos_ubicacion = 'app_reservas/contingencia/'
filename = ... | 13e233d113ac3232a6e76725b13ef2befcd47feb | 3,627,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.