content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def travel_cost():
"""
Returns the yearly costs of travel, 22£ per week.
:return: The cost of travel.
"""
# There are 52 weeks in a year minus two for Christmas and Summer holidays.
return 22 * 50 | fa51fba03ab3db9deea7f3e075c392d4c8db6cef | 57,447 |
import string
import re
def tokenize_count(s: str) -> int:
"""
Tokenizes the given strings to count the number of words.
:param s:
:return: number of words
"""
s = s.translate(str.maketrans('', '', string.punctuation + "„“–"))
return len(re.split(r'\W+', s)) | c68822f313a2ffcab11edf0c0ce146d758cb8e3f | 57,448 |
def set_idle_override(isUserActive: bool, isScreenUnlocked: bool) -> dict:
"""Overrides the Idle state.
Parameters
----------
isUserActive: bool
Mock isUserActive
isScreenUnlocked: bool
Mock isScreenUnlocked
**Experimental**
"""
return {
"method": "Emula... | 21b51d27edef13f66818d8d72583745e6c3449e9 | 57,449 |
def cr_encode(index):
"""cr: Get a custom value."""
return MessageEncode(f"08cr{index + 1:02}00", "CR") | e24c245ab7bb51cb6b570274657d2726d3faeda4 | 57,450 |
def format_strings(*strings):
"""Take an arbitrary number of strings and format them nicely.
Returns the nicely formatted string.
"""
accum_string = ""
for str in strings:
accum_string = "{0} {1}\n".format(accum_string, str)
return accum_string | 7785cf052ed04ce3185035b0921e98bd0d952449 | 57,451 |
def get_lang_obj(name: str) -> AbstractLanguage:
""" Returns a new language object """
if name.lower() == "abap":
return Abap()
raise Exception("Unknown language: " + name) | 974f6da222a20056d7d71c36af6137c7b9f5ebde | 57,452 |
def plot_spectrum(wavelength, flux, fig=None, scale='log', legend=None, ylabel='Flux Density', xlabel='Wavelength [um]', width=1024, height=500, **kwargs):
"""
Plot a generic spectrum
Parameters
----------
wavelength: array-like
The 1D wavelength array
flux: array-like
The 1D co... | e9ebd77f64b1b18578e619f06ae24ffbc4f1257c | 57,453 |
def batch_intersection_union(output, target, nclass):
"""mIoU"""
# inputs are numpy array, output 4D, target 3D
mini = 1
maxi = nclass
nbins = nclass
predict = paddle.argmax(output, 1) + 1 # [N,H,W]
target = target.astype('float32') + 1 # [N,H,W]
predict = predict.astype('fl... | 347577626149ef17652080c00c4b44dfaa7023ee | 57,455 |
def calc_mean_std_population(df_merged, discard_file=None):
"""Calculate mean and STD of the traning datasets
"""
A_freq_cols = [col for col in df_merged.columns if 'A' in col]
C_freq_cols = [col for col in df_merged.columns if 'C' in col]
G_freq_cols = [col for col in df_merged.columns if 'G' in co... | 57a94d893234d011f05f08f42f7caef52a018cc0 | 57,456 |
def __preprocessor(text):
"""
Happens before tokenizer.
:param text: text
:return: text
"""
s = text.lower()
s = s.replace('\r', ' ').replace('\n', ' ').strip()
s = strip_punctuation(s)
return s | 1c62f9a9f4db478aa694dc6b90c697fe21b699c1 | 57,457 |
def renameApkPackage(smaliFolder = 'file/decompile/smali', manifest = 'file/decompile/AndroidManifest.xml', newPackageName="com.zzw.noName"):
"""
rename apk package name.
"""
manifest = file_operate.getFullPath(manifest)
ET.register_namespace('android', androidNS)
targetTree = ET.parse(manif... | 15791aeebf6c9c27626f8d0806d8397cb4e8776f | 57,458 |
def estimated_autocorrelation(x):
"""
http://stackoverflow.com/questions/14297012/estimate-autocorrelation-using-python
http://stackoverflow.com/q/14297012/190597
http://en.wikipedia.org/wiki/Autocorrelation#Estimation
"""
result = estimate_unnormalised_autocorrelation(x, x.mean())
variance... | 06744514ccdbcef2fe5ebc962773a0e4da9a345d | 57,459 |
def SceneLightShadowsStart(builder):
"""This method is deprecated. Please switch to Start."""
return Start(builder) | 81899f6c6b7decef9c02aa49c7112ad213537417 | 57,460 |
def get_location_recordings():
"""Retrieve show recordings for all locations"""
return locations.get_location_recordings(database_connection) | 940c88a448e6fa825594c46432cc553edfaf57f9 | 57,461 |
def _get_value(string, context):
"""
determines the true value of an input to a template tag. If the string is
quoted it's interpreted as a string. If not quoted then it's treated as a
variable and looked up against the context.
"""
if _is_quoted_string(string):
return string[1:-1]
r... | 0e0bf209ef24a5304e800db541d1943106636419 | 57,462 |
def modify_packet(packet):
"""
Modifies the DNS Resource Record `packet` ( the answer part)
to map our globally defined `dns_hosts` dictionary.
For instance, whenever we see a google.com answer, this function replaces
the real IP address (172.217.19.142) with fake IP address (192.168.0.6)
"""
... | 9401aeb5fe36b8782797616f7b863cdfe29e2ac0 | 57,463 |
def database_get_most_cited( publication_period: int=None, # Limit the considered pubs to only those published in these years
cited_in_period: str='5', #
cite_count: int=0, # Has to be cited more than this number of times, a large nbr speeds the... | e94f7ba7b4dd0d177008998b63fedc6a200394db | 57,465 |
def fitLinReg(x, y):
"""
Fit multiple linear regression model.
x: indep variable / predictors
y: dep variable to predict
"""
rkf = RepeatedKFold(n_splits=10, n_repeats=100, random_state=0)
regressor = LinearRegression()
regressor.fit(x, y)
pred = regressor.predict(x)
cv_results... | d6eadfee1899f8619279ed60dbcde4b80cdab983 | 57,466 |
def process_data(packet, start, msg):
"""
This funcion aims to dissect PacketIn and PacketOut data
It assumes it is
Ethernet [vlan] (BDDP|LLDP|ARP|IP) [TCP|UDP]
Args:
packet: class OFMessage
start: offset
msg:
Returns:
payload: array with all class... | 22dc9b2114cbb37f7b95908e1f566a127135e676 | 57,467 |
def block(inputs,
activation: str = "swish",
drop_rate: float = 0.,
name: str = "",
input_channel: int = 32,
output_channel: int = 16,
kernel_size: int = 3,
strides: int = 1,
expand_ratio: int = 1,
use_se: bool = True,
s... | 02c31a0f3b204b4f9c2a6f5bfdae31fd0f80b72a | 57,468 |
import time
def set_seed(seed=None):
"""Making the seed (for random values) variable if None"""
# Set the seed
if seed is None:
seed = int((time.time() * 10**6) % 4294967295)
try:
np.random.seed(seed)
except Exception as e:
print("!!! WARNING !!!: Seed was not set correct... | ea751bdf0548887dbbeb03f47b48f33a9ba22a41 | 57,469 |
def _get_http_client():
"""Uses project credentials in CLIENT_SECRET_FILE along with requested OAuth2
scopes for authorization, and caches API tokens in TOKEN_STORE_FILE.
"""
store = file.Storage(TOKEN_STORE_FILE)
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_... | 846dc2dfbe31c4a7d84ca267818be655376056db | 57,470 |
def rename_candidate_hugo(candidate, renamings):
"""Renames a candidate name according to a renaming map."""
candidate_split = candidate.split("_")
name_expr = candidate_split[0].split(".")
base_name = name_expr[0]
if base_name in renamings:
base_name = renamings[base_name]
name_expr[0] ... | dd0744bb725ddcb3cd6e9e520e32448ad7657495 | 57,472 |
def is_explicitly_rooted(path):
"""Return whether a relative path is explicitly rooted relative to the
cwd, rather than starting off immediately with a file or folder name.
It's nice to have paths start with "./" (or "../", "../../", etc.) so, if a
user is that explicit, we still find the path in the s... | bde26849889ac5c951160e441cdd0c3c60871ab1 | 57,474 |
def _description(title=None, exits=(), description=None, components=None):
"""
"""
return language.Description(
title=title, exits=exits, description=description,
components=components) | 27a5d6dc6a6947c156745fee2f93050c90ca140c | 57,475 |
from typing import List
def snip_out(file_str:str, start_key:str)->str:
"""From an anvil.yaml file, snips out only the string you want: the database description."""
good_string:List[str]=[]
save_this_one = False
for line in file_str.split('\n'):
if line.startswith(start_key):
good_... | 8e9ebde180fb5ff6faefcbd92629c75f260ce518 | 57,476 |
def eth_sign_sha3(data: bytes) -> bytes:
"""
eth_sign/recover compatible hasher
Prefixes data with "\x19Ethereum Signed Message:\n<len(data)>"
"""
prefix = b'\x19Ethereum Signed Message:\n'
if not data.startswith(prefix):
data = prefix + b'%d%s' % (len(data), data)
return sha3(data) | d69481f46e0e2ca8ba69eb512f2dfd6ca62b8d7c | 57,477 |
from typing import Any
import requests
def setup_api(
requests_mock: Any,
url_path: str = url_path(),
json_extras: dict = None,
headers_extras: dict = None,
matcher: Any = None,
) -> requests.Response:
"""Utility function for mocking API calls.
Args:
requests_mock: mock object for... | 4f07fd4bc727a754229917768eea09f221bc0a12 | 57,478 |
import platform
def get_terminal_size():
""" getTerminalSize()
- get width and height of console
- works on linux,os x,windows,cygwin(windows)
originally retrieved from:
http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python
"""
current_os = platform.system... | f6e7d5b9bdbb88b84da615a74a967e96546064c8 | 57,479 |
from typing import Any
from typing import Dict
def validate_long_url(_netid: str, client: ShrunkClient, long_url: str) -> Any:
"""``GET /api/validate_long_url/<b32:long_url>``
Validate a long URL. This endpoint is used for form validation in the frontend. Response format:
.. code-block:: json
{ ... | ae49f477f1e1dcd19ab108b23a5be7b06b818fbe | 57,480 |
def bls_series(series_id, **kwargs):
"""
Authenticated request to the BLS API to fetch timeseries data in JSON
form. You can pass a list of up to 25 series_ids to fetch multiple
series, or you can pass in a single series_id string to do a simple
request. You can also pass in parameters via the kwarg... | f7d5b254d3b296ebc339a4e0c96c54760df9a936 | 57,481 |
def crawl(ob,keys=None,parents=None,capture=None,bubble=None,param=None):
"""
Returns what was passed in as param, after crawling through the target
object's nested structure and firing callbacks at every node in both capture
and bubble directions.
Parameters:
ob
- target dict being crawled through
parents
... | 7b84a94df5907f2f941ea216340fd5e3ef0ef8b3 | 57,482 |
def colour_code_segmentation(image, label_values, array_type):
"""
Given a 1-channel array of class keys, colour code the segmentation results.
# Arguments
image: single channel array where each value represents the class key.
label_values
# Returns
Colour coded image for segmen... | e9a6e9d0bb705cc17e30899126ca3081369f3a99 | 57,483 |
def init_step(idx, cols):
"""Helper function to find init suffix
in a column
Parameters
----------
idx: int
Index of 'init' column in cols.
cols: list[str]
List of column names.
"""
for i in range(idx, len(cols)):
if cols[i] != 'init':
return 'init-' ... | ec056ef39c56ec9dbc534e70105d55aa9bbf7be5 | 57,484 |
def training_base_config(estimator, inputs=None, job_name=None, mini_batch_size=None):
"""Export Airflow base training config from an estimator
Args:
estimator (sagemaker.estimator.EstimatorBase):
The estimator to export training config from. Can be a BYO estimator,
Framework es... | b36b68efeafbf869d8f5de517bc0575492752b94 | 57,485 |
def se_bhmass_mgii_vo09_fwhm(mgii_fwhm, cont_lwav, cont_wav):
"""Calculate the single-epoch virial BH mass based on the MgII FWHM
and monochromatic continuum luminosity at 1350A, 2100A, 3000A, or 5100A.
This relationship is taken from Vestergaard & Osmer 2009, ApJ 641, 689
To determine the FWHM of the... | 9cd1d8a90e30fcbc9fa2b045242a573020aeff70 | 57,486 |
def get_plotly_fig():
"""Dummy Plotly Plot"""
return px.line(data_frame=get_dataframe(), x="quantity", y="price") | befcb64177b799977845bb98343cee0052ec18eb | 57,488 |
def next_nuc(seq, pos, n):
""" Returns the nucleotide that is n places from pos in seq. Skips gap symbols.
"""
i = pos + 1
while i < len(seq):
if seq[i] != '-':
n -= 1
if n == 0: break
i += 1
if i < len(seq) :
return seq[i]
else :
return 'N... | dbe3d204d3399167630cf83c74b0f1742d1c8367 | 57,489 |
def toolchains(request):
""" Return a Toolchains Instance """
res = Toolchains()
request.addfinalizer(res.clean)
return res | b973c31ab74deb5248ad6efe20992166049c96e3 | 57,490 |
def format_node(id, label):
"""
Return the formatted string to represent a node
"""
return NODE_PREFIX + id + label + NODE_SUFFIX | 02d70e31430ad79aff2d900a930e0f9ea0978977 | 57,491 |
def Axes_Replace_Split_Axes(fig, axes_remove, split_fraction, direction='vertical'):
"""
Add sevearl new axes in the place of the axes_remove
(the axes which will be replaced by new ones). This could be
used to set break axes.
Parameters
----------
axes_remove: the axes ... | cb6ac4ac6fde65c39989db3c719d6ad366e46227 | 57,493 |
import logging
def _tile_scalar_to_batch_size(tensor_dict, batch_size):
"""Tile scalar tensors in the dictionary to have batch dimension."""
# bool(tf.constant(1).shape) = True.
# this is inconsistent with python default length test. Disable pylint.
scalar_keys = [k for k, v in tensor_dict.items() if len(v.sh... | 3d0281a89358b7c20070498016f928800980c8cf | 57,494 |
def yices_bvconst_minus_one(n):
"""Set all bits to 1.
Error report:
if n = 0
code = POS_INT_REQUIRED
badval = n
if n > YICES_MAX_BVSIZE
code = MAX_BVSIZE_EXCEEDED
badval = n.
"""
# let yices deal with int32_t excesses
if n > MAX_INT32_SIZE:
n = MA... | 6fcd12b438399f3c27b6d02a1717a3ccc0c0ca49 | 57,495 |
def high_pass_filter(x_vals, y_vals, cutoff, inspectPlots=True):
"""
Replicate origin directy
http://www.originlab.com/doc/Origin-Help/Smooth-Algorithm
"rotate" the data set so it ends at 0,
enforcing a periodicity in the data. Otherwise
oscillatory artifacts result at the ends
This uses a ... | b531921a91ff2cc6553979e7c6a87da313e2b761 | 57,496 |
def get_lemma(word: str) -> str:
""" returns the lemma of a word (simplifies word as possible)"""
return wn.morphy(word) or word | faea8c50b0abb2e541a8f84dfdfc7af5dd62e6fb | 57,497 |
import numpy
def avg_3_op(array_1, array_2, array_3, nodata):
"""Average 3 arrays. Skip nodata."""
result = numpy.empty_like(array_1)
result[:] = nodata
valid_mask = (
~numpy.isclose(array_1, nodata) &
~numpy.isclose(array_2, nodata) &
~numpy.isclose(array_3, nodata))
resul... | 6e6a47b8e5e7cae065fa933275122d1f9cee7f88 | 57,498 |
import sh
import re
def vm_stat(field):
"""Wrapper around 'vm_stat' cmdline utility."""
out = sh('vm_stat')
for line in out.split('\n'):
if field in line:
break
else:
raise ValueError("line not found")
return int(re.search(r'\d+', line).group(0)) * PAGESIZE | 15c35d607cbd7a54fa721a58d02f4bf4e0b4d81a | 57,499 |
from typing import List
def match(rules: Rules, rule_id: str, message: str) -> List[int]:
"""Returns how many characters are possible to match in *message* starting from *rule_id*.
If none can be matched, returns the empty list, otherwise, returns a list of possibilities,
as there can be several alternat... | 4d1f278333bf3095a382015d9d0f062e655333bb | 57,500 |
import json
def parse_json(line: str) -> str:
"""
parse one line of json data, change the names of some fields and add the length of multivalued fields
:param line: a string containing document as json
:return: the modified data as string
"""
parsed = json.loads(line)
# rename authors to a... | 68f332e12fcd8600da1aa8f3f34d9b2aef01a6cb | 57,501 |
def sqs_receive(fila):
"""
recupera templates da lista
"""
sqs = boto3.resource('sqs', region_name=aws_region)
conn = sqs.get_queue_by_name(QueueName=fila)
messages = conn.receive_messages(MaxNumberOfMessages=10, AttributeNames=[
'All'], WaitTimeSeconds=1)
... | d4de36bc63a8d1d967f6a1927f1e9731fbff82eb | 57,503 |
def model_to_owl_str(model: BioPaxModel) -> str:
"""Return an OWL string serialized from a BioPaxModel object.
Parameters
----------
model :
The BioPaxModel to serialize into an OWL string.
Returns
-------
:
The OWL string for the model.
"""
return xml_to_str(model.... | b036c18a1b10a069c7dd36a1d11fbdc8da813727 | 57,504 |
import warnings
def ica(data, observations , n_components, n_runs , return_info = False , copy = False , plot_projection = None , fun = 'logcosh' , algorithm = 'fastica_par'
, normalize = True , reorientation = True , whiten = True , pca_solver = 'full', chunked = False , chunk_size = None , zero_center = True... | 8462c08ef207aa75d8c798b438f2366a63ccdf91 | 57,505 |
def _find_dumb_path(challbs, preferences):
"""Find challenge path without server hints.
Should be called if the combinations hint is not included by the
server. This function either returns a path containing all
challenges provided by the CA or raises an exception.
"""
path = []
for i, cha... | 9a07cbd00e8b21d98024ae314df0291da1d598f1 | 57,506 |
def _assign_odim_moments(ds, nch, sweep, **kwargs):
"""Assign radar moments to dataset.
Parameters
----------
nch : netCDF4.Dataset handle
source netCDF4 Dataset
ds : xarray dataset
destination dataset
sweep : str
netcdf group name
Keyword Arguments
------------... | 1eba8ddadc46c287e6daf078b4e9d09f54f69efc | 57,507 |
import collections
import itertools
import unittest
def _test_or_class_decorator(test_or_class, single_method_decorator):
"""Decorate a test or class with a decorator intended for one method.
If the test_or_class is a class:
This will apply the decorator to all test methods in the class.
If the te... | 13af4b3f68d6ece781e8e665b9bf8073970a9c1d | 57,508 |
import torch
import math
def tensor2img(tensor, out_type=np.uint8, min_max=(0, 1)):
"""Convert torch Tensors into image numpy arrays.
After clamping to (min, max), image values will be normalized to [0, 1].
For differnet tensor shapes, this function will have different behaviors:
1. 4D mini-bat... | db3e0b221e0634ff2c3635c6f25dcc8e6d7b3f9e | 57,509 |
def censor(data, width=30):
""" Censor values after leading edges in time.
This is used to insert a censored period in threshold crossings.
For instance, when you find a crossing in the signal, you don't
want the next 0.5-1 ms, you just want the first crossing.
**Arguments**:
*data*:
... | f943c3c556a8ec6c667e217080509255ce76cdc7 | 57,511 |
def get_folder_parameters(folder_ref: str, filename: str):
"""Extracts sample sizes from the managed folder
:param str filename: name of the json containing the experiment parameters
:raises: :class:`ValueError`: Missing folder or filename.
:returns: sample sizes
:rtype: tuple
"""
folder =... | 59df273c57ba67669c823766d4e1e1e8cc1b8198 | 57,512 |
from typing import Dict
import pandas
def query_postgresql_server(database_information: DatabaseInformation, sql_command: Text,
connection_arguments: Dict = None) -> pandas.Dataframe:
"""Query PostgreSQL database.
This function will create a PostgreSQL database connection.
Ar... | 5be87d0a8168d6671768f31d23c926237591ab5f | 57,514 |
def _mt_repr(self):
"""Print mutable tuple like dict."""
return '{{{0}}}'.format(', '.join('\'{0}\': {1!r}'.format(name, getattr(self, name)) for name in self._fields)) | bc01cb22d8263ce7df77e90214d587f0553627a7 | 57,515 |
def call_view(request, username):
"""Call page."""
interlocutor = get_object_or_404(User, username=username)
return render(
request,
"call.html",
{
"interlocutor": interlocutor,
},
) | 7037d0ad5564ebcc2931899190acedcf5a2e2b76 | 57,516 |
def add_args(parser):
"""
parser : argparse.ArgumentParser
return a parser added with args required by fit
"""
# Training settings
parser.add_argument('--model', type=str, default='lr', metavar='N',
help='neural network used in training')
parser.add_argument('--datas... | 794109eaf6da5cfc52c95ef6a8a69430b98fd17d | 57,517 |
def rescale_none(pop_counts, policy, budget=None):
"""
Rescales and allows for None in policy proportion factors.
Filters out the nones, and performs rescaling on the remaining numbers.
pop_counts: dict[pop_id] -> count
policy: dict[pop_id] -> proportion factor
"""
scales = [v for k, v in p... | 330bf93707d7ee8ecee10ebb9dade916eee7d510 | 57,518 |
def check_cors(f):
"""Wraps a request handler with CORS headers checking."""
@wraps(f)
def decorated(*args, **kwargs):
self = args[0]
request = args[1]
origin = request.getHeader('Origin')
if origin:
if '*' in self.cors_origins:
request.setHeader... | 2b6354dae6ecf16fb192f14d15b9b9a14d898661 | 57,519 |
def _stc_to_label(stc, src, smooth, subjects_dir=None):
"""Compute a label from the non-zero sources in an stc object.
Parameters
----------
stc : SourceEstimate
The source estimates.
src : SourceSpaces | str | None
The source space over which the source estimates are defined.
... | fd18809322a9974418ab59423ca35680e2aab709 | 57,520 |
from pathlib import Path
def delete_ingest_pipeline(ingestPipelineName: str = Path(
default='test-pipeline', example='test-pipeline')):
"""
Delete a previously saved ingest pipeline - based on the ingest pipeline name.
"""
return _id | d2f8b318049490ae4e7d6b9976edb3350ac93515 | 57,521 |
import re
def rgb2short(rgb):
""" Find the closest xterm-256 approximation to the given RGB value.
@param rgb: Hex code representing an RGB value, eg, 'abcdef'
@returns: String between 0 and 255, compatible with xterm.
>>> rgb2short('123456')
('23', '005f5f')
>>> rgb2short('ffffff')
('231'... | 4fe1600d6e95a921cc82bd00bbc899f24b42684e | 57,522 |
from operator import contains
def homo_inner_multi(N, m, minority_fraction, homophily, epsilon, labels, edges):
"""
samples edges according to barabasi + homophily but allows multi edges
this algorithm has strict runtime O(n + m)
"""
n_edges = 0
minority_size = int(minority_fraction * N)
m... | 37cf73ca583d0a81469b579158423a5c113d91e0 | 57,523 |
import scipy
def fit(model, trend, val='arate'):
"""Fit a 2 paramater model to a rate trend"""
try :
doffs = list(range(trend.num_rows))
params, pcov = scipy.optimize.curve_fit(model, doffs, trend[val])
return params, np.sqrt(np.diag(pcov))
except :
return [np.nan, np.nan],... | cad3f3b5ce93d15121df2d558317b442d30161e8 | 57,524 |
from typing import Tuple
from typing import Any
def parse_tuple(string: str) -> Tuple[Any, ...]:
"""Parse a tuple from a given string.
:param string: the string representation of a tuple
:type string: str
:raises ValueError: if the string cannot be interpreted as a tuple using :func:`ast.literal_eval... | b201cb1c5671ff7d873721e38ec7ad94f59a1680 | 57,526 |
def get_k_set_interval(vec: str, k: int, to_counter_plus_one: bool = False) -> tuple:
"""return tupl
Parameters
----------
vec : str
String of {0,1}*.
k : int
????????????????????
????????????????????
## to_counter_plus_one : bool
## If True, assume vec beggins i... | ac0dcfe0e9af6dae77942ba7beb682c9d52b57f0 | 57,528 |
import functools
import numpy
import unittest
def for_dtypes(dtypes, name="dtype"):
"""Decorator for parameterized dtype test.
Args:
dtypes(list of dtypes): dtypes to be tested.
name(str): Argument name to which specified dtypes are passed.
This decorator adds a keyword argument specif... | cb6784686cbf5adc034d0014e385a67e47d7f933 | 57,529 |
def remove_failed(data, failed):
"""
chr20 12th row, 1 based
chr21 1st row, 1 based
chr22 27th row, 1 based
"""
failed = np.array(failed)
data = np.array(data)
res = np.delete(data, failed, -1)
res = np.delete(res, failed, -2)
return res | 1406fb3fe5f5e5efbf135fd6c0cab299d7a81044 | 57,530 |
def play_and_train(env, agent, t_max=10**4):
"""
This function should
- run a full game, actions given by agent's e-greedy policy
- train agent using agent.update(...) whenever it is possible
- return total reward
"""
total_reward = 0.0
s = env.reset()
for t in range(t_max):
... | 0a4a5bf5f71a1c14946c30d39aa3a541f9a5c6fd | 57,531 |
def shap_neighbors(instance, x_init, contributions, mode):
"""
For an instance and corresponding neighbors, calculate various
metrics (described below) that are useful to evaluate local stability
Parameters
----------
instance : 2D array
Instance + neighbours with corresponding features... | e600a4d78a69e705e8162522ca6addf6cfd79937 | 57,532 |
import pandas as pd
def save_ldamodel_summary_to_excel(excel_file, topic_word_distrib, doc_topic_distrib, doc_labels, vocab,
top_n_topics=10, top_n_words=10, dtm=None,
rank_label_fmt=None, topic_labels=None):
"""
Save a summary derived from... | fe8fec0cbc8e2fe6e3923fb54015162181cc06ae | 57,533 |
def _do_transforms(graph_def, input_names, output_names, initializer_names,
transforms, saver_def=None, checkpoint_path=None):
"""Apply requested transforms to a GraphDef, including freezing.
This applies the Graph Transform Tool interleaved with graph freezing.
Args:
graph_def: A GraphDe... | 547ba9f3c7ecd95e4ce3e8c0acdf695f23f175b9 | 57,534 |
def UsersJSON():
""" This is a JSON endpoint which returns list of all registered users."""
session = DBSession()
users = session.query(User).all()
return jsonify(users=[u.serialize for u in users]) | 2412b54c30182e0388b7ba83be074d1e4d3464b7 | 57,535 |
def preprocess_default(pathname):
"""
Examples:
>>> preprocess_default("data/train_sample_0.csv")
"""
df = pd.read_csv(pathname)
df = preprocess_funcs.add_times2categorical(df)
df = preprocess_funcs.add_releaseyear(df)
df = preprocess_funcs.add_ages2categorical(df)
df = preproces... | 92702ac6e74af046e663bcbb453a8c92c73f6e15 | 57,536 |
def vertice_concatenate(pt1xstr, pt1zstr, pt1ystr, pt2xstr, pt2zstr, pt2ystr, pt3xstr, pt3zstr, pt3ystr, pt4xstr, pt4zstr, pt4ystr, pt5xstr, pt5zstr, pt5ystr, pt6xstr, pt6zstr, pt6ystr, pt7xstr, pt7zstr, pt7ystr, pt8xstr, pt8zstr, pt8ystr, pt9xstr, pt9zstr, pt9ystr, pt10xstr, pt10zstr, pt10ystr, pt11xstr, pt11zstr, pt1... | e12332d866b7b1e5acc7e9214f264d4b24e592c4 | 57,537 |
def U(W, cell=None):
"""Calculates operator `U` for the given wave functions.
Args:
W (numpy.ndarray): wave function sample points.
cell (pydft.geometry.Cell): describing the unit cell and sampling points.
"""
return np.dot(W.conjugate().T, O(W, cell)) | 846cf07f848875ebd0afddb66a3b018e0757812f | 57,538 |
def build_rescale_transform_slow(downscale_factor, image_shape, target_shape):
"""Rescale Transform.
This mimics the skimage.transform.resize function.
The resulting image is centered.
Args:
downscale_factor: float, >1
image_shape: tuple(rows, cols), input image shape
target_shape: tuple(row... | a009d89572ee6c5a686646a7c8c9df43395fc5d5 | 57,539 |
def load_h5(h5f):
"""
Load fiberbundles configurations from a hdf5 class
Parameters
----------
h5f : hdf5 class
h5-file or group object
Returns
-------
res : list(list(fiber)), fibers are (n,4)-arrays with (x,y,z,radii) for each fiber point
"""
fiber_bundles = []
f... | 47487b43ae375c5ade27c82ec083570ee9655e27 | 57,540 |
def fizz_buzzable(num):
"""
We're only interested in valid fizz buzz numbers.
"""
return num % 3 == 0 or num % 5 == 0 | 4eba37245525ead66f4f30370d9e3d97c05aca55 | 57,541 |
def hpo_sheets_chosen_create_uw_ams(
metric_choice, hpo_dictionary, datetimes, metric_dictionary):
"""
Function is used to triage how to create 'aggregate metrics'
for HPO sheets based on the kind of user input provided.
In cases where the 'aggregate metric' already exists in the
DataQualit... | 8856a012059fbec747862eda1f642a856deb1ce7 | 57,542 |
def sympy2pysmt(expression):
"""Converts a sympy formula representing a polynomial into a pysmt formula.
Args:
expression: The sympy formula to convert.
Returns:
FNode: The pysmt formula.
Raises:
WMIParsingException: If the method fails to parse the formula.
... | 24687efc367e1c8904b07e66f7f787b5282c1afd | 57,543 |
async def send_for_revision(internal_id: str, stages_ids: tp.List[str]) -> GenericResponse:
"""
Endpoint to sent current unit for revision by selected stages ids.
Empty copy of those stages will be created. Unit status will change to 'revision'.
"""
logger.info(f"Sending unit {internal_id} for revis... | e1a26f663fdec547d37d9c33a1fbc9b5410ba31d | 57,544 |
def MINUS_DM(data: xr.DataArray, timeperiod: int = 14):
"""
Minus Directional Movement (Momentum Indicators)
Inputs:
data: ['high', 'low']
Parameters:
timeperiod: 14
Outputs:
double series
"""
return multiple_series_call(talib.MINUS_DM, data, ds.TIME, ds.FIELD, [f.HIG... | 3d732ce535292af7e9031955edbad1d5c1312130 | 57,545 |
def parse_arxiv_url(url):
"""
examples is http://arxiv.org/abs/1512.08756v2
we want to extract the raw id and the version
"""
ix = url.rfind('/')
idversion = url[ix+1:] # extract just the id (and the version)
parts = idversion.split('v')
assert len(parts) == 2, 'error parsing url ' + url
return parts[... | 1eb44f9db2504cd569bea9ab91ca5b27f1ff1817 | 57,546 |
from typing import List
def load_file(file_path: str) -> List[str]:
"""
Just loader for file with lines
:param file_path: path to file
:return: list of lines of your data
"""
data: List[str] = list()
with open(file_path) as file_object:
for line in file_object:
data.a... | 9aadf5c0a90f5c65868862e4366276c448077944 | 57,547 |
def uniquify_tablewidgetitems(a):
""" Eliminates duplicate list entries in a list
of TableWidgetItems. It relies on the row property
being available for comparison.
"""
if (len(a) == 0):
tmp = []
else:
tmp = [a[0]]
# XXX: we need to compare row #s because
... | 942eb3fb5e172185fe7f857f5e6e5e523984b75c | 57,548 |
from Acquire.Client import Service as _Service
from Acquire.Client import LoginError
def _get_accounting_service(accounting_url=None):
"""Function to return the accounting service for the system
Args:
accounting_url (str, default=None): Accounting URL
Returns:
Service: Accounting servic... | d25e914adf75cf45755a053eea2006fe7975c3b6 | 57,549 |
def distance(s, t):
"""Returns the Levenshtein edit distance between two strings."""
m, n = len(s), len(t)
d = [range(n+1)]
d += [[i] for i in range(1,m+1)]
for i in range(0,m):
for j in range(0,n):
cost = 1
if s[i] == t[j]: cost = 0
d[i+1].append(min... | c7232ada6d66604430e9d6fe14bff18e3ede91bf | 57,550 |
def build_app_list(app_list):
"""Create response payload for app list."""
app_list = [
{"app_id": app_id, "title": app_name, "type": MEDIA_TYPE_APP}
for app_name, app_id in app_list.items()
]
return BrowseMedia(
media_class=MEDIA_CLASS_DIRECTORY,
media_content_id=None,
... | 7bd1a83da7ffaed68fd90ecefc28f0ca48e4de8e | 57,552 |
import random
def random_colors(*commands):
"""From tuple of commands, generate random but unique colors."""
colors = ["blue", "green", "red", "yellow", "magenta", "cyan", "white"]
num_colors = len(colors)
num_commands = len(commands)
if num_commands >= num_colors:
colors += colors
u... | 2f55ce480a8550d94b595b94017371e525b8a8b4 | 57,553 |
def greeting() -> str:
"""The standard greeting.
>>> assert greeting() == 'hello'
"""
return 'hello' | eba4ada1f6dd154dc8197bce0c0128fea3d7e31e | 57,554 |
def impute_dates(df, freq, dt_stop=None):
"""Fill missing dates in the timeseries dataframe.
Parameters
----------
dd : pd.DataFrame
freq : str
dt_stop : str or datetime, optional
The final date in the timeseries, it will be inferred if not specified.
Otherwise, dates will be im... | 01ab0c4aee61f23e10a220e603e05d794a5a5792 | 57,556 |
def get_num_antennas(ms):
"""Return number of antennas in a MS."""
tb.open(ms + '/ANTENNA', nomodify=True)
num_stations = tb.nrows()
tb.close()
return num_stations | ef815dd1c038c6f31686dfa0160edd42ad576be3 | 57,558 |
def compare_records(azara_record, rui_record):
"""
:param azara_record: tuple - a (treasure, coordinate) pair.
:param rui_record: tuple - a (location, coordinate, quadrant) trio.
:return: bool - True if coordinates match, False otherwise.
"""
return azara_record[1] == rui_record[1][0] + rui_re... | e0ee6ceddee0be3bcb5ce4fb283ba560c0998fe9 | 57,559 |
import random
def mutation_chromossome(chromossomes, mutation_function, mutation_rate):
"""
:param: chromossomes -
:param: mutation_function -
:param: mutation_rate -
:return: chromossomes -
"""
number_chromossomes_to_mutate = int(len(chromossomes) * mutation_rate)
ran... | 30a9a92724a91e70d10ba5c35fef0e1aef85300d | 57,560 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.