content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def encode(numbers, GCE=GCE):
"""
do extended encoding on a list of numbers for the google chart api
>>> encode([1690, 90,1000])
'chd=e:aaBaPo'
"""
encoded = []
for number in numbers:
if number > 4095: raise ValueError('too large')
first, second = divmod(number, len(GCE))
... | 9a15134e0266a0dfc60b654b9da8d2a6169bee7f | 15,357 |
def compute_f_mat(mat_rat,user_count,movie_count):
"""
compute the f matrix
:param mat_rat: user`s rating matrix([user number,movie number]) where 1 means user likes the index movie.
:param user_count: statistics of moive numbers that user have watch.
:param movie_count: statistics of user numbers t... | ff13544c28dde9025630878aed0844f56453e08e | 15,358 |
import logging
import tqdm
def query_assemblies(organism, output, quiet=False):
"""from a taxid or a organism name, download all refseq assemblies
"""
logger = logging.getLogger(__name__)
assemblies = []
genomes = Entrez.read(Entrez.esearch(
"assembly",
term=f"{organism}[Organism... | 48b4f4946f4368865b2934f1ac30ce650a00b5d0 | 15,360 |
def main(params):
"""Loads the file containing the collation results from Wdiff.
Then, identifies various kinds of differences that can be observed.
Assembles this information for each difference between the two texts."""
print("\n== coleto: running text_analyze. ==")
difftext = get_difftext(params[... | 425aa27fb7ba1ee0b1aa23c2489e8431b4a57726 | 15,361 |
def matrix_horizontal_stack(matrices: list, _deepcopy: bool = True):
"""
stack matrices horizontally.
:param matrices: (list of Matrix)
:param _deepcopy: (bool)
:return: (Matrix)
"""
assert matrices
for _i in range(1, len(matrices)):
assert matrices[_i].basic_data_type() == matri... | 83419b0f77fc055145026b61ab8a0200172fcb62 | 15,362 |
def inds_to_invmap_as_array(inds: np.ndarray):
"""
Returns a mapping that maps global indices to local ones
as an array.
Parameters
----------
inds : numpy.ndarray
An array of global indices.
Returns
-------
numpy.ndarray
Mapping from global to local.
"""
re... | 25dc5fa9f1225cb9da64a513ebea3dff935c3c44 | 15,363 |
def ident_keys(item, cfg):
"""Returns the list of keys in item which gives its identity
:param item: dict with type information
:param cfg: config options
:returns: a list of fields for item that give it its identity
:rtype: list
"""
try:
return content.ident_keys(item)
except E... | e911ea9bb0dbccbdf4d0ab5cdfeb5742297ae9e8 | 15,365 |
def playlists_by_date(formatter, albums):
"""Returns a single playlist of favorite tracks from albums
sorted by decreasing review date.
"""
sorted_tracks = []
sorted_albums = sorted(albums, key=lambda x: x["date"], reverse=True)
for album in sorted_albums:
if album["picks"] is None:
... | 0448fd941c0219f6e854a15df62e4811c1cecf3e | 15,366 |
def merge_two_sorted_array(l1, l2):
"""
Time Complexity: O(n+m)
Space Complexity: O(n+m)
:param l1: List[int]
:param l2: List[int]
:return: List[int]
"""
if not l1:
return l2
if not l2:
return l1
merge_list = []
i1 = 0
i2 = 0
l1_len = len(l1) - 1
... | 2671d21707056741bbdc4e3590135e7e1be4c7e9 | 15,367 |
def regression_metrics(y_true,y_pred):
"""
param1: pandas.Series/pandas.DataFrame/numpy.darray
param2: pandas.Series/pandas.DataFrame/numpy.darray
return: dictionary
Function accept actual prediction labels from the dataset and predicted values from the model and utilizes this
two values/data... | 085bf6d9006443c752f5b665480fce4f24e5f850 | 15,368 |
def convert_from_quint8(arr):
"""
Dequantize a quint8 NumPy ndarray into a float one.
:param arr: Input ndarray.
"""
assert isinstance(arr, np.ndarray)
assert (
"mgb_dtype" in arr.dtype.metadata
and arr.dtype.metadata["mgb_dtype"]["name"] == "Quantized8Asymm"
), "arr should ... | 50143a309108bf68cb65b266e2aec84090eb30e6 | 15,369 |
def classpartial(*args, **kwargs):
"""Bind arguments to a class's __init__."""
cls, args = args[0], args[1:]
class Partial(cls):
__doc__ = cls.__doc__
def __new__(self):
return cls(*args, **kwargs)
Partial.__name__ = cls.__name__
return Partial | 7cdc96e314a2ce3c658ecb886922df4d7bda5b99 | 15,370 |
def alphabetize_concat(input_list):
"""
Takes a python list.
List can contain arbitrary objects with .__str__() method
(so string, int, float are all ok.)
Sorts them alphanumerically.
Returns a single string with result joined by underscores.
"""
array = np.array(input_list, dtype=st... | 4bac3712696fd776b96ca8501f696c505c05e699 | 15,372 |
def kick(state, ai, ac, af, cosmology=cosmo, dtype=np.float32, name="Kick",
**kwargs):
"""Kick the particles given the state
Parameters
----------
state: tensor
Input state tensor of shape (3, batch_size, npart, 3)
ai, ac, af: float
"""
with tf.name_scope(name):
state = tf.convert_to_te... | e7deeca9001fccc078f2f8ab7e51ac38d72a1125 | 15,373 |
def check_similarity(var1, var2, error):
"""
Check the simulatiry between two numbers, considering a error margin.
Parameters:
-----------
var1: float
var2: float
error: float
Returns:
-----------
similarity: boolean
"""
if((var1 <= (var2 + error)) and (v... | 305fd08cf4d8b1718d8560315ebf7bd03a4c7e2a | 15,374 |
def model_type_by_code(algorithm_code):
"""
Method which return algorithm type by algorithm code.
algorithm_code MUST contain any 'intable' type
:param algorithm_code: code of algorithm
:return: algorithm type name by algorithm code or None
"""
# invalid algorithm code case
if algorith... | bcd811e200855cc026134ce05b67add807e176ca | 15,375 |
def getCasing(word):
""" Returns the casing of a word"""
if len(word) == 0:
return 'other'
elif word.isdigit(): #Is a digit
return 'numeric'
elif word.islower(): #All lower case
return 'allLower'
elif word.isupper(): #All upper case
return 'allUpper'
elif word[0... | 2af70926c0cbbde6310abb573ccc3ee8260b86bd | 15,376 |
def normalize_angle(deg):
"""
Take an angle in degrees and return it as a value between 0 and 360
:param deg: float or int
:return: float or int, value between 0 and 360
"""
angle = deg
while angle > 360:
angle -= 360
while angle < 360:
angle += 360
return angle | cd4788819bbc8fce17ca7c7b1b320499a3893dee | 15,377 |
from datetime import datetime
from dateutil import tz
import math
def current_global_irradiance(site_properties, solar_properties, timestamp):
"""Calculate the clear-sky POA (plane of array) irradiance for a specific time (seconds timestamp)."""
dt = datetime.datetime.fromtimestamp(timestamp=timestamp, tz=tz.... | d8e180b9768d5cf6c3064a7d30a2e7d918307366 | 15,378 |
from datetime import datetime
def date_formatting(format_date, date_selected):
"""Date formatting management.
Arguments:
format_date {str} -- Date
date_selected {str} -- Date user input
Returns:
str -- formatted date
"""
if len(date_selected) == 19:
date_selected... | 48ff4cb59de3e8f75238420d8d211812148db34c | 15,379 |
def parse_activity_from_metadata(metadata):
"""Parse activity name from metadata
Args:
metadata: List of metadata from log file
Returns
Activity name from metadata"""
return _parse_type_metadata(metadata)[1] | c583d34a8cb0db8ddf26ff79d1a0885aab5c6af9 | 15,380 |
def mask_data_by_FeatureMask(eopatch, data_da, mask):
"""
Creates a copy of array and insert 0 where data is masked.
:param data_da: dataarray
:type data_da: xarray.DataArray
:return: dataaray
:rtype: xarray.DataArray
"""
mask = eopatch[FeatureType.MASK][mask]
if len(data_da... | 6639cc2cbf4956edbd637f07308fb33f00fcb8af | 15,381 |
def makeFields(prefix, n):
"""Generate a list of field names with this prefix up to n"""
return [prefix+str(n) for n in range(1,n+1)] | 435571557ef556b99c4729500f372cc5c9180052 | 15,382 |
def process_input_dir(input_dir):
"""
Find all image file paths in subdirs, convert to str and extract labels from subdir names
:param input_dir Path object for parent directory e.g. train
:returns: list of file paths as str, list of image labels as str
"""
file_paths = list(input_dir.rglob('*.... | 569d4539368888c91a12538156c611d311da03b6 | 15,383 |
def fak(n):
""" Berechnet die Fakultaet der ganzen Zahl n. """
erg = 1
for i in range(2, n+1):
erg *= i
return erg | 9df6f4fa912a25535369f4deb0a06baef8e6bdcc | 15,384 |
import re
def create_sequences_sonnets(sonnets):
"""
This creates sequences as done in Homework 6, by mapping each word
to an integer in order to create a series of sequences. This function
specifically makes entire sonnets into individual sequences
and returns the list of processed sonnets back t... | 56087140fe5ed8934b64a18567b4e9023ddc6f59 | 15,386 |
def l_to_rgb(img_l):
"""
Convert a numpy array (l channel) into an rgb image
:param img_l:
:return:
"""
lab = np.squeeze(255 * (img_l + 1) / 2)
return color.gray2rgb(lab) / 255 | 362a1ef926e780b311902c3637a5299afbce4c6a | 15,388 |
def blockchain_assert_absolute_time_exceeds(condition: ConditionWithArgs, timestamp):
"""
Checks if current time in millis exceeds the time specified in condition
"""
try:
expected_mili_time = int_from_bytes(condition.vars[0])
except ValueError:
return Err.INVALID_CONDITION
curr... | 7b3ce8801239a524b150c9191b49eb24575b3fbb | 15,389 |
def show_aip(mets_file):
"""Show a METS file"""
mets_instance = METS.query.filter_by(metsfile='%s' % (mets_file)).first()
level = mets_instance.level
original_files = mets_instance.metslist
dcmetadata = mets_instance.dcmetadata
divs = mets_instance.divs
filecount = mets_instance.originalfile... | 606dfd4dba45fe8dae918f795f27bfeddb0fcd70 | 15,390 |
def testCartesianEpehemeris(
ephemeris_actual,
ephemeris_desired,
position_tol=1*u.m,
velocity_tol=(1*u.mm/u.s),
magnitude=True,
raise_error=True
):
"""
Tests that the two sets of cartesian ephemeris are within the desired absolute tolerances
of each other... | 5ab38140ed7ff446f0f961e147e7d8af3e6c97e0 | 15,391 |
import requests
def get_longitude_latitude(city_info, station):
"""
利用高德地图查询对应的地铁站经纬度信息,下面的key需要自己去高德官网申请
https://lbs.amap.com/api/webservice/guide/api/georegeo
:param city_info: 具体城市的地铁,如:广州市地铁
:param station: 具体的地铁站名称,如:珠江新城站
:return: 经纬度
"""
addr = city_info + station
print('*要查... | 9b0132702e14af9dec1ce65724139af0188b14a0 | 15,392 |
def make_resource_object(resource_type, credentials_path):
"""Creates and configures the service object for operating on resources.
Args:
resource_type: [string] The Google API resource type to operate on.
credentials_path: [string] Path to credentials file, or none for default.
"""
try:
api_name, ... | 018cac83513b61c8bc99e06a07ded004685016b2 | 15,393 |
def AreBenchmarkResultsDifferent(result_dict_1, result_dict_2, test=MANN,
significance_level=0.05):
"""Runs the given test on the results of each metric in the benchmarks.
Checks if the dicts have been created from the same benchmark, i.e. if
metric names match (e.g. first_non_em... | d9e1eaa16c2329511dd3e1fc7e5cad63cab0c208 | 15,394 |
def _load_pascal_annotation(image_index):
"""
Load image and bounding boxes info from XML file in the PASCAL VOC
format.
"""
#image_index = _load_image_set_index()
classes = ('__background__', # always index 0
'aeroplane', 'bicycle', 'bird', 'boat',
... | e656d78003d17ca7b8dae204ed9ea2812e5871dc | 15,395 |
def create_global_var(shape,
value,
dtype,
persistable=False,
force_cpu=False,
name=None):
"""
This function creates a new tensor variable with value in the global block(block 0).
Parameters:
... | 0d64b4bd15c97b2f32058bfe298249c3e528ec16 | 15,396 |
def select(population, fitness_val):
"""
选择操作,用轮盘赌法进行选择
:param population: 种群基因型
:param fitness_val: 种群适应度
:return selected_pop: 选择后的种群
"""
f_sum = sum(fitness_val)
cumulative = []
for i in range(1, len(fitness_val)+1):
cumulative.append(sum(fitness_val[:i]) / f_sum)
... | dd3529eaf6ac35801c589152078e7fe1dd0ed9fe | 15,397 |
def _nan_helper(y, nan=False, inf=False, undef=None):
"""
Helper to handle indices and logical indices of NaNs, Infs or undefs.
Definition
----------
def _nan_helper(y, nan=False, inf=False, undef=None):
Input
-----
y 1d numpy array with possible missing values
Optional ... | 742433c2140f4827f11e79c691e3a16be124ef99 | 15,398 |
def unpacking(block_dets, *, repeat=False, **_kwargs):
"""
Identify name unpacking e.g. x, y = coord
"""
unpacked_els = block_dets.element.xpath(ASSIGN_UNPACKING_XPATH)
if not unpacked_els:
return None
title = layout("""\
### Name unpacking
""")
summary_bits = []
for unp... | 512238569efe4c17ef7afd3a26e2bc17a0f77cfb | 15,399 |
import tempfile
import gzip
def load_training_data():
"""Loads the Fashion-MNIST dataset.
Returns:
Tuple of Numpy arrays: `(x_train, y_train)`.
License:
The copyright for Fashion-MNIST is held by Zalando SE.
Fashion-MNIST is licensed under the [MIT license](
https://githu... | be2a5d84c8ef0cd1aa62564a3fd3882af49344ca | 15,400 |
def set_difference(tree, context, attribs):
"""A meta-feature that will produce the set difference of two boolean features
(will have keys set to 1 only for those features that occur in the first set but not in the
second).
@rtype: dict
@return: dictionary with keys for key occurring with the first... | 7887f619e601624843c6507e7b93442020ecf1ea | 15,401 |
def create_STATES(us_states_location):
"""
Create shapely files of states.
Args:
us_states_location (str): Directory location of states shapefiles.
Returns:
States data as cartopy feature for plotting.
"""
proj = ccrs.LambertConformal(central_latitude = 25,
... | fe2b48f465ee7e63bb4dfa91e2c9917eeeab082f | 15,402 |
def get_name_by_url(url):
"""Returns the name of a stock from the instrument url. Should be located at ``https://api.robinhood.com/instruments/<id>``
where <id> is the id of the stock.
:param url: The url of the stock as a string.
:type url: str
:returns: Returns the simple name of the stock. If th... | c90e453bb1576d8c93a3388ab2cfe0d9f63d550c | 15,403 |
def recursively_replace(original, replacements, include_original_keys=False):
"""Clones an iterable and recursively replaces specific values."""
# If this function would be called recursively, the parameters 'replacements' and 'include_original_keys' would have to be
# passed each time. Therefore, a h... | aee393b09c74eb6cb1417d017d7004ac69bb3543 | 15,404 |
from typing import get_origin
from typing import get_args
def destructure(hint: t.Any) -> t.Tuple[t.Any, t.Tuple[t.Any, ...]]:
"""Return type hint origin and args."""
return get_origin(hint), get_args(hint) | 451d1fd5a3277f882b9645dcdc78b2accc4d56a2 | 15,405 |
def f_x_pbe(x, kappa=0.804, mu=0.2195149727645171):
"""Evaluates PBE exchange enhancement factor.
10.1103/PhysRevLett.77.3865 Eq. 14.
F_X(x) = 1 + kappa ( 1 - 1 / (1 + mu s^2)/kappa )
kappa, mu = 0.804, 0.2195149727645171 (PBE values)
s = c x, c = 1 / (2 (3pi^2)^(1/3) )
Args:
x: Float numpy array with... | 9933a379b659b38082aa91d4498a399a43b2e20c | 15,406 |
def index():
"""
if no browser and no platform: it's a CLI request.
"""
if g.client['browser'] is None or g.client['platform'] is None:
string = "hello from API {} -- in CLI Mode"
msg = {'message': string.format(versions[0]),
'status': 'OK',
'mode': 200}
... | d497ce0cf12bbe914ab3147080c05a4441e9d39b | 15,407 |
def attention_resnet20(**kwargs):
"""Constructs a ResNet-20 model.
"""
model = CifarAttentionResNet(CifarAttentionBasicBlock, 3, **kwargs)
return model | e44061a9ad42ceea26aa263a5169ffec62857f90 | 15,409 |
import re
def get_basename(name):
""" [pm/cmds] オブジェクト名からベースネームを取得する """
fullpath = get_fullpath(name)
return re(r"^.*\|", "", fullpath) | a18cd5ac563dd37c53bdf6b0c1ea6a55efa7a221 | 15,410 |
from typing import Optional
def get_live_token(resource_uri: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetLiveTokenResult:
"""
The response to a live token query.
:param str resource_uri: The identifier of the resource.
"""
__args__ = dict(... | b82d799ff261994643c807f4d1b947ba591d6a14 | 15,411 |
def load_subspace_vectors(embd, subspace_words):
"""Loads all word vectors for the particular subspace in the list of words as a matrix
Arguments
embd : Dictonary of word-to-embedding for all words
subspace_words : List of words representing a particular subspace
Returns
subspace_e... | 5eb1db8be8801cf6b1fe294a6f2c93570e9a9fe1 | 15,412 |
from datetime import datetime
def _safe_filename(filename):
"""
Generates a safe filename that is unlikely to collide with existing
objects in Google Cloud Storage.
``filename.ext`` is transformed into ``filename-YYYY-MM-DD-HHMMSS.ext``
"""
filename = secure_filename(filename)
date = datet... | 63e55ccbf29505868efe702cd7c25cdfb0e6ad2f | 15,413 |
from typing import List
from typing import Tuple
def get_raw(contents: List[str]) -> Tuple[sections.Raw, List[str]]:
"""Parse the \\*RAW section"""
raw_dict, rest = get_section(contents, "raw")
remarks = raw_dict[REMARKS] if REMARKS in raw_dict else ""
raw_info = sections.Raw(
remarks=remarks,... | 005af62533c129d39b7af1524b00a48a9113adde | 15,414 |
import itertools
def transfers_from_stops(
stops,
stop_times,
transfer_type=2,
trips=False,
links_from_stop_times_kwargs={'max_shortcut': False, 'stop_id': 'stop_id'},
euclidean_kwargs={'latitude': 'stop_lat', 'longitude': 'stop_lon'},
seek_traffic_redundant_paths=True,
seek_transfer_r... | 9e9456440b3dc6cbdd367f9ea99f85559e3343cd | 15,415 |
from pypy.module.cpyext.tupleobject import PyTuple_GetItem
from pypy.module.cpyext.listobject import PyList_GetItem
def PySequence_ITEM(space, w_obj, i):
"""Return the ith element of o or NULL on failure. Macro form of
PySequence_GetItem() but without checking that
PySequence_Check(o)() is true and withou... | 8a3bb364d6d2e96681bb89b170b8517e09eb719c | 15,416 |
import codecs
import binascii
def decode_hex(data):
"""Decodes a hex encoded string into raw bytes."""
try:
return codecs.decode(data, 'hex_codec')
except binascii.Error:
raise TypeError() | 115e89d6f80a6fc535f44d92f610a6312edf6daf | 15,417 |
def crop_bbox_by_coords(bbox, crop_coords, crop_height, crop_width, rows, cols):
"""Crop a bounding box using the provided coordinates of bottom-left and top-right corners in pixels and the
required height and width of the crop.
"""
bbox = denormalize_bbox(bbox, rows, cols)
x_min, y_min, x_max, y_ma... | 2cd53c51f6a80034630a53a43678d22f1073e7f4 | 15,418 |
def computeDateGranularity(ldf):
"""
Given a ldf, inspects temporal column and finds out the granularity of dates.
Example
----------
['2018-01-01', '2019-01-02', '2018-01-03'] -> "day"
['2018-01-01', '2019-02-01', '2018-03-01'] -> "month"
['2018-01-01', '2019-01-01', '2020-01-01'] -> "year"
Parameters
-----... | e998a144b22c6e65599f1f6b5cc2ec893310e3cc | 15,419 |
from typing import Optional
from typing import Tuple
import sqlite3
def next_pending_location(user_id: int, current_coords: Optional[Tuple[int, int]] = None) -> Optional[Tuple[int, int]]:
"""
Retrieves the next pending stone's coordinates. If current_coords is not specified (or is not pending),
retrieves ... | fb26531819c19532d7dbf8152963245f07af8e7c | 15,420 |
import re
import keyword
def get_valid_identifier(prop, replacement_character='', allow_unicode=False):
"""Given a string property, generate a valid Python identifier
Parameters
----------
replacement_character: string, default ''
The character to replace invalid characters with.
allow_un... | a3eeb389b73540aba2041e877c2ff151e272ffdd | 15,421 |
from re import T
def temporal_padding(x, paddings=(1, 0), pad_value=0):
"""Pad the middle dimension of a 3D tensor
with `padding[0]` values left and `padding[1]` values right.
Modified from keras.backend.temporal_padding
https://github.com/fchollet/keras/blob/3bf913d/keras/backend/theano_b... | 8ccc828ac68cd98da4e7ec5f8253ae5385317d48 | 15,422 |
def get_orientation(y, num_classes=8, encoding='one_hot'):
"""
Args:
y: [B, T, H, W]
"""
# [H, 1]
idx_y = np.arange(y.shape[2]).reshape([-1, 1])
# [1, W]
idx_x = np.arange(y.shape[3]).reshape([1, -1])
# [H, W, 2]
idx_map = np.zeros([y.shape[2], y.shape[3], 2])
idx_map[:, ... | 501c57cf447865ec03229a3ba15125da3837eb8e | 15,424 |
def plot_tempo_curve(f_tempo, t_beat, ax=None, figsize=(8, 2), color='k', logscale=False,
xlabel='Time (beats)', ylabel='Temp (BPM)', xlim=None, ylim=None,
label='', measure_pos=[]):
"""Plot a tempo curve
Notebook: C3/C3S3_MusicAppTempoCurve.ipynb
Args:
f_... | fd8f084d5912b7b64929e7bc8a61bd4dfc8ae107 | 15,425 |
def not_pathology(data):
"""Return false if the node is a pathology.
:param dict data: A PyBEL data dictionary
:rtype: bool
"""
return data[FUNCTION] != PATHOLOGY | b420826265164445e8df470a4049d68839182d4b | 15,426 |
def remove_index_fastqs(fastqs,fastq_attrs=IlluminaFastqAttrs):
"""
Remove index (I1/I2) Fastqs from list
Arguments:
fastqs (list): list of paths to Fastq files
fastq_attrs (BaseFastqAttrs): class to use for
extracting attributes from Fastq names
(defaults to IlluminaFastqAttrs)... | fc62bd4ab28427ba51d8cd56d17576c89e2ed7ad | 15,427 |
from typing import Union
from typing import List
def max(name: "Union[str, List[Expr]]") -> "Expr":
"""
Get maximum value
"""
if isinstance(name, list):
def max_(acc: Series, val: Series) -> Series:
mask = acc < val
return acc.zip_with(mask, val)
return fold(l... | 3ca308e951801e4376483188249da2333aafc789 | 15,428 |
def initialize(Lx, Ly,
solutes, restart_folder,
field_to_subspace,
concentration_init, rad,
enable_NS, enable_EC,
dx,
surface_charge,
permittivity,
**namespace):
""" Create the initial state. """
... | 802affd7e56598cb4a22e37480313401254e263f | 15,429 |
def _get_sentry_sdk():
"""Creates raven.Client instance configured to work with cron jobs."""
# NOTE: this function uses settings and therefore it shouldn't be called
# at module level.
try:
sentry_sdk = __import__("sentry_sdk")
DjangoIntegration = __import__(
"sentry_s... | 8682004e68606bf8f67487ad541455179c50493c | 15,430 |
def get_memos():
"""
Returns all memos in the database, in a form that
can be inserted directly in the 'session' object.
"""
records = [ ]
for record in collection.find( { "type": "dated_memo" } ):
record['date'] = arrow.get(record['date']).isoformat()
del record['_id']
r... | d9f0f66db05d368d086b77669418652565ea8587 | 15,431 |
def psplit(df, idx, label):
"""
Split the participants with a positive label in df into two sets, similarly for participants with a negative label. Return two numpy arrays of participant ids, each array are the chosen id's to be removed from two dataframes to ensure no overlap of participants between the two se... | fa8652d8812c8f4fd94c7d2601b964b7aaced963 | 15,433 |
import numpy
def invU(U):
"""
Calculate inverse of U Cell.
"""
nr, nc = U.getCellsShape()
mshape = U.getMatrixShape()
assert (nr == nc), "U Cell must be square!"
nmat = nr
u_tmp = admmMath.copyCell(U)
u_inv = admmMath.Cells(nmat, nmat)
for i in range(nmat):
for j ... | 58765834bde6c93e419d3e2f6d8de25d1740c587 | 15,437 |
def liq_g(drvt,drvp,temp,pres):
"""Calculate liquid water Gibbs energy using F03.
Calculate the specific Gibbs free energy of liquid water or its
derivatives with respect to temperature and pressure using the
Feistel (2003) polynomial formulation.
:arg int drvt: Number of temperature deriv... | dfa3eef9d0b9228495b2d4d33a503c0e8c174c2a | 15,438 |
def extract_dates(obj):
"""extract ISO8601 dates from unpacked JSON"""
if isinstance(obj, dict):
new_obj = {} # don't clobber
for k,v in iteritems(obj):
new_obj[k] = extract_dates(v)
obj = new_obj
elif isinstance(obj, (list, tuple)):
obj = [ extract_dates(o) for o... | 1dd7dbda376755cd962c23d2149f41e8559cff12 | 15,441 |
def construct_covariates(states, model_spec):
"""Construct a matrix of all the covariates
that depend only on the state space.
Parameters
---------
states : np.ndarray
Array with shape (num_states, 8) containing period, years of schooling,
the lagged choice, the years of experience ... | 883395fc3561ea2fb774eb0ea6dfd866a3d2eed6 | 15,442 |
def check_oblique_montante(grille, x, y):
"""Alignements diagonaux montants (/) : allant du coin bas gauche au coin haut droit"""
symbole = grille.grid[y][x]
# Alignement diagonal montant de la forme XXX., le noeud (x,y) étant le plus bas et à gauche
if grille.is_far_from_top(y) and grille.is_far_from_r... | f1ca8d7b55117e3e03c5150a07fd483a1da0a4d5 | 15,444 |
def _rotate_the_grid(lon, lat, rot_1, rot_2, rot_3):
"""Rotate the horizontal grid at lon, lat, via rotation matrices rot_1/2/3
Parameters
----------
lon, lat : xarray DataArray
giving longitude, latitude in degrees of LLC horizontal grid
rot_1, rot_2, rot_3 : np.ndarray
rotation ma... | b6c81dcc8191c2843534f369269e5c9cd466d581 | 15,445 |
def dict_mapper(data):
"""Mapper from `TypeValueMap` to :class`dict`"""
out = {}
for k, v in data.items():
if v.type in (iceint.TypedValueType.TypeDoubleComplex,
iceint.TypedValueType.TypeFloatComplex):
out[k] = complex(v.value.real, v.value.imag)
elif v.typ... | b10ba4ed38d81cca3fc760d281a32d46d03d4223 | 15,446 |
def split_by_normal(cpy):
"""split curved faces into one face per triangle (aka split by
normal, planarize). in place"""
for name, faces in cpy.iteritems():
new_faces = []
for points, triangles in faces:
x = points[triangles, :]
normals = np.cross(x[:, 1]-x[:, 0], x[:... | 9a4c563465cc2deb5c2946f3e182fc9b71327081 | 15,449 |
def generate_index_distribution_from_blocks(numTrain, numTest, numValidation, params):
""" Generates a vector of indices to partition the data for training.
NO CHECKING IS DONE: it is assumed that the data could be partitioned
in the specified block quantities and that the block quantities describe ... | 7bb30a6f69a45d231cbb4a140d7527a270f22e27 | 15,450 |
def sct2e(sc, sclkdp):
"""sct2e(SpiceInt sc, SpiceDouble sclkdp)"""
return _cspyce0.sct2e(sc, sclkdp) | a32defabb20993b87c182121e209e62c190a46c8 | 15,451 |
import re
import json
def test_main(monkeypatch, test_dict: FullTestDict):
"""
- GIVEN a list of words
- WHEN the accent dict is generated
- THEN check all the jisho info is correct and complete
"""
word_list = convert_list_of_str_to_kaki(test_dict['input'])
sections = test_dict['jisho']['... | f32d75bc5219cf48eccffcd777dc0881e0299ae7 | 15,452 |
def get_tn(tp, fp, fn, _all):
"""
Args:
tp (Set[T]):
fp (Set[T]):
fn (Set[T]):
_all (Iterable[T]):
Returns:
Set[T]
"""
return set(_all) - tp - fp - fn | a9afa3a2f07c8b63a6d6911b9a54cf9f9df08600 | 15,454 |
def download_cow_head():
"""Download cow head dataset."""
return _download_and_read('cowHead.vtp') | 70dc6617d3b9d6a8f9fa4df90caf749d00a6d778 | 15,455 |
def select_tests(blocks, match_string_list, do_test):
"""Remove or keep tests from list in WarpX-tests.ini according to do_test variable"""
if do_test not in [True, False]:
raise ValueError("do_test must be True or False")
if (do_test == False):
for match_string in match_string_list:
... | f77a0b9e91ec34b85479a442008241c7da386beb | 15,456 |
def get_last_ds_for_site(session, idescr: ImportDescription, col: ImportColumn, siteid: int):
"""
Returns the newest dataset for a site with instrument, valuetype and level fitting to the ImportDescription's column
To be used by lab imports where a site is encoded into the sample name.
"""
q = sess... | 41040efe43c0189a3cc8b7288e47eccd752674a7 | 15,457 |
def get_cart_from_request(request, cart_queryset=Cart.objects.all()):
"""Get cart from database or return unsaved Cart
:type cart_queryset: saleor.cart.models.CartQueryset
:type request: django.http.HttpRequest
:rtype: Cart
"""
if request.user.is_authenticated():
cart = get_user_cart(req... | 5d9d7e3708db5db38f07aea9299ee0aacdecea22 | 15,458 |
def _is_ge(series, value):
""" Returns the index of rows from series where series >= value.
Parameters
----------
series : pandas.Series
The data to be queried
value : list-like
The values to be tested
Returns
-------
index : pandas.index
The index of series fo... | 98b8825753953b1b9bf7348d04d260b7514a7749 | 15,459 |
def preprocess_image(image, image_size, is_training=False, test_crop=True):
"""Preprocesses the given image.
Args:
image: `Tensor` representing an image of arbitrary size.
image_size: Size of output image.
is_training: `bool` for whether the preprocessing is for training.
test_crop: whether or not ... | 913f614798daaf7b752195c92e48890868666b57 | 15,460 |
async def wait_for_reaction(self, message):
""" Assert that ``message`` is reacted to with any reaction.
:param discord.Message message: The message to test with
:returns: The reaction object.
:rtype: discord.Reaction
:raises NoReactionError:
"""
def check_reaction(reaction, user):
... | 67890343d6b59923e8fd3e655252eddcde88323c | 15,461 |
def _multivariate_normal_log_likelihood(X, means=None, covariance=None):
"""Calculate log-likelihood assuming normally distributed data."""
X = check_array(X)
n_samples, n_features = X.shape
if means is None:
means = np.zeros_like(X)
else:
means = check_array(means)
asser... | d5144074f0a88c51a0c46f1b36eb8bdd95f9140e | 15,462 |
import tokenize
def lemmatize(text):
"""
tokenize and lemmatize english messages
Parameters
----------
text: str
text messages to be lemmatized
Returns
-------
list
list with lemmatized forms of words
"""
def get_wordnet_pos(treebank_tag):
if treebank_... | 0a744953ac014f2c0551cecb9c235fc405bf5aaa | 15,463 |
def prune_non_overlapping_boxes(boxes1, boxes2, min_overlap):
"""Prunes the boxes in boxes1 that overlap less than thresh with boxes2.
For each box in boxes1, we want its IOA to be more than min_overlap with
at least one of the boxes in boxes2. If it does not, we remove it.
Arguments:
boxes1: a... | 5e1a04022707364f1d1a8b14afbd356e781137b9 | 15,464 |
def get_namespace_from_node(node):
"""Get the namespace from the given node
Args:
node (str): name of the node
Returns:
namespace (str)
"""
parts = node.rsplit("|", 1)[-1].rsplit(":", 1)
return parts[0] if len(parts) > 1 else u":" | a2305719c0e72614f75309f1412ce71c9264b5df | 15,465 |
def PricingStart(builder):
"""This method is deprecated. Please switch to Start."""
return Start(builder) | d87eae22f74b5251261bb39aea93e46887f03725 | 15,466 |
def create_whimsy_value_at_clients(number_of_clients: int = 3):
"""Returns a Python value and federated type at clients."""
value = [float(x) for x in range(10, number_of_clients + 10)]
type_signature = computation_types.at_clients(tf.float32)
return value, type_signature | 87d1d110392bd83585fd19ba2e8a10a0c8507d30 | 15,468 |
def format_task_numbers_with_links(tasks):
"""Returns formatting for the tasks section of asana."""
project_id = data.get('asana-project', None)
def _task_format(task_id):
if project_id:
asana_url = tool.ToolApp.make_asana_url(project_id, task_id)
return "[#%d](%s)" % (task... | b6b7975cb45cdae0a146a67c0fab51ef0724aee2 | 15,469 |
def get_tick_indices(tickmode, numticks, coords):
"""
Ticks on the axis are a subset of the axis coordinates
This function returns the indices of y coordinates on which a tick should be displayed
:param tickmode: should be 'auto' (automatically generated) or 'all'
:param numticks: minimum number of ... | 72cf3fed39db3cabf672bff4b042c8685356f9ff | 15,470 |
def fpIsNormal(a, ctx=None):
"""Create a Z3 floating-point isNormal expression.
"""
return _mk_fp_unary_pred(Z3_mk_fpa_is_normal, a, ctx) | ee6e2cccf1ad0534929aa0632d271d37f58a232e | 15,471 |
import math
def siqs_find_next_poly(n, factor_base, i, g, B):
"""Compute the (i+1)-th polynomials for the Self-Initialising
Quadratic Sieve, given that g is the i-th polynomial.
"""
v = lowest_set_bit(i) + 1
z = -1 if math.ceil(i / (2 ** v)) % 2 == 1 else 1
b = (g.b + 2 * z * B[v - 1]) % g.a
... | d5529db62a194582aacd8769a56688cf6b42bbe1 | 15,473 |
def get_column(value):
"""Convert column number on command line to Python index."""
if value.startswith("c"):
# Ignore c prefix, e.g. "c1" for "1"
value = value[1:]
try:
col = int(value)
except:
stop_err("Expected an integer column number, not %r" % value)
if col < 1:... | 858f4128955c0af579d99dcd64be157b41c6dae3 | 15,474 |
def sdi(ts_split, mean=False, keys=None):
"""
Compute the Structural Decoupling Index (SDI).
i.e. the ratio between the norms of the "high" and the norm of the "low"
"graph-filtered" timeseries.
If the given dictionary does not contain the keywords "high" and "low",
the SDI is computed as the ... | 9ed09f72bc6902b5c007286e12f1ed72d904d4b8 | 15,475 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.