content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def asses_completeness(language_code: str, sw: ServiceWorker = Depends(get_sw)):
"""
make a completion test for language: check fe,be, domains and entries
@param language_code:
@param sw:
@return:
"""
if language_code not in sw.messages.get_added_languages():
raise ApplicationExcepti... | 9de6a9130ec34e47782679ac63d80707de5b98ce | 3,650,574 |
def create_intrinsic_node_class(cls):
"""
Create dynamic sub class
"""
class intrinsic_class(cls):
"""Node class created based on the input class"""
def is_valid(self):
raise TemplateAttributeError('intrisnic class shouldn\'t be directly used')
intrinsic_class.__name__ =... | ddcb0ba5f36981288fd9748f1f533f02f1eb1604 | 3,650,575 |
def segment_fish(image):
"""Attempts to segment the clown fish out of the provided image."""
hsv_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
light_orange = (1, 190, 200)
dark_orange = (18, 255, 255)
mask = cv2.inRange(hsv_image, light_orange, dark_orange)
light_white = (0, 0, 200)
dark_wh... | c9ee166f12e9c344143f677939a82dd1a00a5fb5 | 3,650,577 |
def enable_faster_encoder(self, need_build=True, use_fp16=False):
"""
Compiles fusion encoder operator intergrated FasterTransformer using the
method of JIT(Just-In-Time) and replaces the `forward` function of
`paddle.nn.TransformerEncoder` and `paddle.nn.TransformerEncoderLayer`
objects inherited f... | 4da1f669cefd291df4bc790dfc68fcbe5ce93f86 | 3,650,579 |
def func(*x):
""" Compute the function to minimise.
Vector reshaped for more readability.
"""
res = 0
x = np.array(x)
x = x.reshape((n, 2))
for i in range(n):
for j in range(i+1, n):
(x1, y1), (x2, y2) = x[i, :], x[j, :]
delta = (x2 - x1)**2 + (y2 - y1)**2 - ... | 775d4330ca77e04662f1920dd2160631deb30430 | 3,650,580 |
import torch
def transform_target(target, classes=None):
"""
Accepts target value either single dimensional torch.Tensor or (int, float)
:param target:
:param classes:
:return:
"""
if isinstance(target, torch.Tensor):
if target.ndim == 1:
target = target.item() if tar... | 5e1423b4beac4385fa4f328bfdfeed2859c28f7b | 3,650,581 |
from typing import List
from typing import Tuple
def merge_all_regions(out_path: str, id_regions: List[Tuple[int, File]]) -> Tuple[int, int, File]:
"""
Recursively merge a list of region files.
"""
if len(id_regions) == 1:
# Base case 1.
[(sample_id, region_file)] = id_regions
... | d9ebbdfec49b6e5702e4c16476a20440185e39ef | 3,650,582 |
def check_for_collision(sprite1: arcade.Sprite,
sprite2: arcade.Sprite) -> bool:
"""Check for collision between two sprites.
Used instead of Arcade's default implementation as we need a hack to
return False if there is just a one pixel overlap, if it's not
multiplayer...
"""... | 679de76d880c2e2e9ac34e0d87cc5cdd0211daa9 | 3,650,584 |
def modify_color(hsbk, **kwargs):
"""
Helper function to make new colors from an existing color by modifying it.
:param hsbk: The base color
:param hue: The new Hue value (optional)
:param saturation: The new Saturation value (optional)
:param brightness: The new Brightness value (optional)
... | ecc5118873aaf0e4f63bad512ea61d2eae0f7ead | 3,650,585 |
def train_val_test_split(df, train_p=0.8, val_p=0.1, state=1, shuffle=True):
"""Wrapper to split data into train, validation, and test sets.
Parameters
-----------
df: pd.DataFrame, np.ndarray
Dataframe containing features (X) and labels (y).
train_p: float
Percent of data to assign... | 67b50b172f94ee65981ab124f03e192c7631c49c | 3,650,586 |
def add_logs_to_table_heads(max_logs):
"""Adds log headers to table data depending on the maximum number of logs from trees within the stand"""
master = []
for i in range(2, max_logs + 1):
for name in ['Length', 'Grade', 'Defect']:
master.append(f'Log {i} {name}')
if i < max_logs... | 5db494650901bfbb114135da9596b9b453d47568 | 3,650,587 |
def stations_at_risk(stations, level):
"""Returns a list of tuples, (station, risk_level) for all stations with risk above level"""
level = risk_level(level)
stations = [(i, station_flood_risk(i)) for i in stations]
return [i for i in stations if risk_level(i[1]) >= level] | c18ef9af1ac02633f2daed9b88dfe6d72e83481a | 3,650,588 |
def unproxy(proxy):
"""Return a new copy of the original function of method behind a proxy.
The result behaves like the original function in that calling it
does not trigger compilation nor execution of any compiled code."""
if isinstance(proxy, types.FunctionType):
return _psyco.unproxycode(proxy.func_... | 7fad2339a8e012fd95117b73b79a371d4488e439 | 3,650,590 |
from typing import Optional
def get_measured_attribute(data_model, metric_type: str, source_type: str) -> Optional[str]:
"""Return the attribute of the entities of a source that are measured in the context of a metric.
For example, when using Jira as source for user story points, the points of user stories (... | f15379e528b135ca5d9d36f50f06cb95a145b477 | 3,650,591 |
def getIntArg(arg, optional=False):
"""
Similar to "getArg" but return the integer value of the arg.
Args:
arg (str): arg to get
optional (bool): argument to get
Returns:
int: arg value
"""
return(int(getArg(arg, optional))) | a30e39b5a90bd6df996bdd8a43faf787aed7128f | 3,650,593 |
from typing import Iterable
def get_in_with_default(keys: Iterable, default):
"""`get_in` function, returning `default` if a key is not there.
>>> get_in_with_default(["a", "b", 1], 0)({"a": {"b": [0, 1, 2]}})
1
>>> get_in_with_default(["a", "c", 1], 0)({"a": {"b": [0, 1, 2]}})
0
"""
gett... | dbb5a9753bad224245ffea884e33802930bb8ded | 3,650,594 |
def conv_HSV2BGR(hsv_img):
"""HSV画像をBGR画像に変換します。
Arguments:
hsv_img {numpy.ndarray} -- HSV画像(3ch)
Returns:
numpy.ndarray -- BGR画像(3ch)
"""
V = hsv_img[:, :, 2]
C = hsv_img[:, :, 1]
H_p = hsv_img[:, :, 0] / 60
X = C * (1 - np.abs(H_p % 2 - 1))
Z = np.zeros_like(C)
... | f748c88e9f4b2a3da2ee7d7703b0d3c9615e564b | 3,650,595 |
import torch
def remap(tensor, map_x, map_y, align_corners=False):
"""
Applies a generic geometrical transformation to a tensor.
"""
if not tensor.shape[-2:] == map_x.shape[-2:] == map_y.shape[-2:]:
raise ValueError("Inputs last two dimensions must match.")
batch_size, _, height, wid... | ff88d66b6692548979e45d2a00f6905e2d973c2a | 3,650,596 |
def AutoRegression(df_input,
target_column,
time_column,
epochs_to_forecast=1,
epochs_to_test=1,
hyper_params_ar={}):
"""
This function performs regression using feature augmentation and then training XGB with Crossval... | 704daf914897b7a43971b22d721ec0f1bb919d3e | 3,650,597 |
def VMACD(prices, timeperiod1=12, timeperiod2=26, timeperiod3=9):
"""
39. VMACD量指数平滑异同移动平均线
(Vol Moving Average Convergence and Divergence,VMACD)
说明:
量平滑异同移动平均线(VMACD)用于衡量量能的发展趋势,属于量能引趋向指标。
MACD称为指数平滑异同平均线。分析的数学公式都是一样的,只是分析的物理量不同。
VMACD对成交量VOL进行分析计算,而MACD对收盘价CLOSE进行分析计算。
计算方法:
SHORT=... | 5de5f372cb7ef6762b82f30d16465469b2cb6afc | 3,650,598 |
from . import graphics
def merge_all_mods(list_of_mods, gfx=None):
"""Merges the specified list of mods, starting with graphics if set to
pre-merge (or if a pack is specified explicitly).
Params:
list_of_mods
a list of the names of mods to merge
gfx
a graphics pack... | c0b6ed6df7116a0abcb0c2674c8bddabd4a52f82 | 3,650,600 |
def pearson_r_p_value(a, b, dim):
"""
2-tailed p-value associated with pearson's correlation coefficient.
Parameters
----------
a : Dataset, DataArray, GroupBy, Variable, numpy/dask arrays or scalars
Mix of labeled and/or unlabeled arrays to which to apply the function.
b : Dataset, Dat... | d9236eaf1d7315fd61eba35bdd4cdc4f27cb9890 | 3,650,601 |
from datetime import datetime
import time
def get_ceilometer_usages(date, connection_string):
"""
Function which talks with openstack
"""
today = datetime.datetime.combine(date, datetime.datetime.min.time())
yesterday = today - datetime.timedelta(days=1)
engine = create_engine(connection_stri... | b05e7f2024ebf2e2eb23a914da71b834debb66cc | 3,650,602 |
def fit_kij(kij_bounds, eos, mix, datavle=None, datalle=None, datavlle=None,
weights_vle=[1., 1.], weights_lle=[1., 1.],
weights_vlle=[1., 1., 1., 1.], minimize_options={}):
"""
fit_kij: attemps to fit kij to VLE, LLE, VLLE
Parameters
----------
kij_bounds : tuple
bo... | 0f2e05a64599b49f70b327e8a69a66647b4c344f | 3,650,603 |
def calc_ac_score(labels_true, labels_pred):
"""calculate unsupervised accuracy score
Parameters
----------
labels_true: labels from ground truth
labels_pred: labels form clustering
Return
-------
ac: accuracy score
"""
nclass = len(np.unique(labels_true))
labels_size =... | 39ca30d3cdcf683dda04d429146775cffd7c0134 | 3,650,606 |
def wave_ode_gamma_neq0(t, X, *f_args):
"""
Right hand side of the wave equation ODE when gamma > 0
"""
C = f_args[0]
D = f_args[1]
CD = C*D
x, y, z = X
return np.array([-(1./(1.+y) + CD)*x + C*(1+D*CD)*(z-y), x, CD*(z-y)]) | 4b2f5f7b5b4e1c932e0758e9be10fcbc5d9fbbb7 | 3,650,607 |
from typing import Dict
def run_workflow(
config: Dict,
form_data: ImmutableMultiDict,
*args,
**kwargs
) -> Dict:
"""Executes workflow and save info to database; returns unique run id."""
# Validate data and prepare run environment
form_data_dict = __immutable_multi_dict_to_nested_dict(
... | bfa732ceaef6fbd6865e015b9c28da68932fa2db | 3,650,608 |
from typing import List
def insertion_stack(nums: List[int]) -> List[int]:
""" A helper function that sort the data in an ascending order
Args:
nums: The original data
Returns:
a sorted list in ascending order
"""
left = []
right = []
for num in nums:
while left and le... | 045e28d763ece3dac9e1f60d50a0d51c43b75664 | 3,650,609 |
def svn_wc_get_pristine_contents(*args):
"""svn_wc_get_pristine_contents(char const * path, apr_pool_t result_pool, apr_pool_t scratch_pool) -> svn_error_t"""
return _wc.svn_wc_get_pristine_contents(*args) | 5a26e358bbd2a4341bdb1c572f98d419f676a725 | 3,650,610 |
def create_cache_key(func, key_dict=None, self=None):
"""Get a cache namespace and key used by the beaker_cache decorator.
Example::
from tg import cache
from tg.caching import create_cache_key
namespace, key = create_cache_key(MyController.some_method)
cache.get_cache(namespace... | 461fc998a7345d646fdaa61fd36f91c3c250d331 | 3,650,614 |
def longest_common_substring(s, t):
"""
Find the longest common substring between the given two strings
:param s: source string
:type s: str
:param t: target string
:type t: str
:return: the length of the longest common substring
:rtype: int
"""
if s == '' or t == '':
r... | 66aef17a117c6cc96205664f4c603594ca496092 | 3,650,615 |
def correct_predictions(output_probabilities, targets):
"""
Compute the number of predictions that match some target classes in the
output of a model.
Args:
output_probabilities: A tensor of probabilities for different output
classes.
targets: The indices of the actual targe... | 1bff085d95da7b37bb2232b6ac03b034e2bdb6b9 | 3,650,616 |
def resolve_all(anno, task):
"""Resolve all pending annotations."""
return (x for x in (_first_match(anno, task), _first_match_any(anno)) if x) | ca127999972644ad25741bc48c78d67aaa4adeec | 3,650,617 |
import socket
def get_free_port():
""" Find and returns free port number. """
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.bind(("", 0))
free_port = soc.getsockname()[1]
soc.close()
return free_port | d1a514a47a906c946fa3a8cb4312e71bc4f7570e | 3,650,618 |
def get_diff_list(small_list, big_list):
"""
Get the difference set of the two list.
:param small_list: The small data list.
:param big_list: The bigger data list.
:return: diff_list: The difference set list of the two list.
"""
# big_list有而small_list没有的元素
diff_list = list(set(big_list).... | f92d20e6edd1f11ca6436a3ada4a6ba71da37457 | 3,650,619 |
def blend_weight_arrays(n_weightsA, n_weightsB, value=1.0, weights_pp=None):
"""
Blend two 2d weight arrays with a global mult factor, and per point weight values.
The incoming weights_pp should be a 1d array, as it's reshaped for the number of influences.
Args:
n_weightsA (np.array): Weight ar... | f5167730773718952f48a67970d62a197bd92944 | 3,650,620 |
def weight_kabsch_dist(x1, x2, weights):
"""
Compute the Mahalabonis distance between positions x1 and x2 given Kabsch weights (inverse variance)
x1 (required) : float64 array with dimensions (n_atoms,3) of one molecular configuration
x2 (required) : float64 a... | e03c86875873af3b890fc3cfa799f037c808196e | 3,650,621 |
def calc_color_rarity(color_frequencies: dict) -> float:
"""
Return rarity value normalized to 64.
Value ascending from 0 (most rare) to 64 (most common).
"""
percentages = calc_pixel_percentages(color_frequencies)
weighted_rarity = [PERCENTAGES_NORMALIZED.get(k) * v * 64 for k,v in percentages.... | 54dd3dde36dc02101b5536630e79d3d39fe18aa8 | 3,650,622 |
def exp_map(x, r, tangent_point=None):
"""
Let \(\mathcal{M}\) be a CCM of radius `r`, and \(T_{p}\mathcal{M}\) the
tangent plane of the CCM at point \(p\) (`tangent_point`).
This function maps a point `x` on the tangent plane to the CCM, using the
Riemannian exponential map.
:param x: np.array,... | 2544e6f6054c602d5eae438b405b55dc995d190a | 3,650,623 |
def _get_data_column_label_in_name(item_name):
"""
:param item_name: Name of a group or dataset
:return: Data column label or ``None``
:rtype: str on None
"""
# /1.1/measurement/mca_0 should not be interpreted as the label of a
# data column (let's hope no-one ever uses mca_0 as a label)
... | 58a50f9b28a8dd3c30eb609bbf61eeaf1b821238 | 3,650,625 |
def _auto_backward(loss,
startup_program=None,
parameter_list=None,
no_grad_set=None,
callbacks=None,
distop_context=None):
"""
modification is inplaced
"""
act_no_grad_set = _get_no_grad_set(loss, no_grad_set... | f7c08e9677768faf125ccc2a273016312004c225 | 3,650,626 |
import re
def strip_from_ansi_esc_sequences(text):
"""
find ANSI escape sequences in text and remove them
:param text: str
:return: list, should be passed to ListBox
"""
# esc[ + values + control character
# h, l, p commands are complicated, let's ignore them
seq_regex = r"\x1b\[[0-9;... | 8597654defffbdde33b844a34e95bf7893a36855 | 3,650,627 |
def _concat_columns(args: list):
"""Dispatch function to concatenate DataFrames with axis=1"""
if len(args) == 1:
return args[0]
else:
_lib = cudf if HAS_GPU and isinstance(args[0], cudf.DataFrame) else pd
return _lib.concat(
[a.reset_index(drop=True) for a in args],
... | e60a3d5120e50dbd2d1be5632042e702e5780bc6 | 3,650,628 |
import re
def applyRegexToList(list, regex, separator=' '):
"""Apply a list of regex to list and return result"""
if type(regex) != type(list):
regex = [regex]
regexList = [re.compile(r) for r in regex]
for r in regexList:
list = [l for l in list if r.match(l)]
list = [l.split(separator) for l in... | eee1edebf361f9516e7b40ba793b0d13ea3070f3 | 3,650,629 |
def GetFileName(path: str) -> str:
"""Get the name of the file from the path
:type path: str
:rtype: str
"""
return splitext(basename(path))[0] | 4aa3a8b75a1ed926c173f9d978504ca2ed653e20 | 3,650,631 |
import re
from functools import reduce
def collapse(individual_refs):
"""Collapse references like [C1,C2,C3,C7,C10,C11,C12,C13] into 'C1-C3, C7, C10-C13'.
Args:
individual_refs (string): Uncollapsed references.
Returns:
string: Collapsed references.
"""
parts = []
for ref in... | f4225586d30960cae74123806b8d44ff6f007584 | 3,650,632 |
def generate_fig_univariate_categorical(
df_all: pd.DataFrame,
col: str,
hue: str,
nb_cat_max: int = 7,
) -> plt.Figure:
"""
Returns a matplotlib figure containing the distribution of a categorical feature.
If the feature is categorical and contains too many categories, the ... | 9e6f9b8739b1907f67c864ceaf177f9f1007d35b | 3,650,634 |
def pt_sharp(x, Ps, Ts, window_half, method='diff'):
"""
Calculate the sharpness of extrema
Parameters
----------
x : array-like 1d
voltage time series
Ps : array-like 1d
time points of oscillatory peaks
Ts : array-like 1d
time points of oscillatory troughs
w... | 6d06b9343c71115fc660a298569794933267bd51 | 3,650,635 |
from datetime import datetime
def convert_date(string, report_date, bad_dates_rep, bad_dates_for):
"""
Converts date string in format dd/mm/yyyy
to format dd-Mmm-yyyy
"""
x = string.split('/')
try:
date = datetime.datetime(int(x[2]),int(x[1]),int(x[0]))
date_str = date.strftime... | f84db7bc2edc070a4c6b9c475458081701bca1eb | 3,650,637 |
def render_raw(request, paste, data):
"""Renders RAW content."""
return HttpResponse(paste.content, content_type="text/plain") | 2ec6fdb719e831988a4384e3690d2bec0faad405 | 3,650,638 |
def node_avg():
"""get the avg of the node stats"""
node_raw = ["average", 0, 0, 0]
for node in node_stats():
node_raw[1] += float(node[1])
node_raw[2] += float(node[2])
node_raw[3] += float(node[3])
num = len(node_stats())
node_avg = ["average",
"{:.2f}".format(... | 985e1f848945d8952ec224a0dd56a02e84b2ea57 | 3,650,639 |
from typing import Union
def decrypt_vault_password(key: bytes, password: Union[str, bytes]) -> Union[str, bool]:
"""Decrypt and return the given vault password.
:param key: The key to be used during the decryption
:param password: The password to decrypt
"""
if isinstance(password, str):
... | 3311b6dc7a9fba4152545ff3ca89881e9ceebb94 | 3,650,640 |
from typing import Optional
def get_gv_rng_if_none(rng: Optional[rnd.Generator]) -> rnd.Generator:
"""get gym-gridverse module rng if input is None"""
return get_gv_rng() if rng is None else rng | 008bf9d22fb6c9f07816e62c2174c60839a5353f | 3,650,642 |
def fill_name(f):
"""
Attempts to generate an unique id and a parent from a BioPython SeqRecord.
Mutates the feature dictionary passed in as parameter.
"""
global UNIQUE
# Get the type
ftype = f['type']
# Get gene name
gene_name = first(f, "gene")
# Will attempt to fill in the... | d2351eb509d72b6b2ef34b7c0b01c339acd52677 | 3,650,643 |
def run_single_softmax_experiment(beta, alpha):
"""Run experiment with agent using softmax update rule."""
print('Running a contextual bandit experiment')
cb = ContextualBandit()
ca = ContextualAgent(cb, beta=beta, alpha=alpha)
trials = 360
for _ in range(trials):
ca.run()
df = Data... | 953c07ae1cdc25782f24206a0ce02bf4fc15202b | 3,650,644 |
def available(name):
"""
Returns ``True`` if the specified service is available, otherwise returns
``False``.
We look up the name with the svcs command to get back the FMRI
This allows users to use simpler service names
CLI Example:
.. code-block:: bash
salt '*' service.available... | 371980f44a348faf83ab32b9d50583fc8e9bae41 | 3,650,645 |
def coincidence_rate(text):
""" Return the coincidence rate of the given text
Args:
text (string): the text to get measured
Returns:
the coincidence rate
"""
ko = 0
# measure the frequency of each letter in the cipher text
for letter in _VOCAB:
count = text.count(letter)
ko = ko + (count *... | ca1ca3d8b746ea40ba07af1cb96a194bf14c1d98 | 3,650,646 |
import numpy
def convert_bytes_to_ints(in_bytes, num):
"""Convert a byte array into an integer array. The number of bytes forming an integer
is defined by num
:param in_bytes: the input bytes
:param num: the number of bytes per int
:return the integer array"""
dt = numpy.dtype('>i' + str(num)... | 38b97fb9d5ecc5b55caf7c9409e4ab4a406a21d7 | 3,650,647 |
def search_spec(spec, search_key, recurse_key):
"""
Recursively scans spec structure and returns a list of values
keyed with 'search_key' or and empty list. Assumes values
are either list or str.
"""
value = []
if search_key in spec and spec[search_key]:
if isinstance(spec[search_ke... | 9d89aacc200e205b0e6cbe49592abfd37158836a | 3,650,648 |
import test
def before_class(home=None, **kwargs):
"""Like @test but indicates this should run before other class methods.
All of the arguments sent to @test work with this decorator as well.
"""
kwargs.update({'run_before_class':True})
return test(home=home, **kwargs) | 3b36e448ec76a2c513a1f87dd29b8027b0693780 | 3,650,649 |
import math
def hellinger_distance_poisson_variants(a_means, b_means, n_samples, sample_distances):
"""
a - The coverage vec for a variant over n_samples
b - The coverage vec for a variant over n_samples
returns average hellinger distance of multiple poisson distributions
"""
# generate dist... | 555365ea295ef2ff1e18e5c26b6b56b1c939035a | 3,650,651 |
def min_threshold(x, thresh, fallback):
"""Returns x or `fallback` if it doesn't meet the threshold. Note, if you want to turn a hyper "off" below,
set it to "outside the threshold", rather than 0.
"""
return x if (x and x > thresh) else fallback | e92c17aafb8a7c102152d9f31d0a317b285a0ae6 | 3,650,652 |
def get_command(command, meta):
"""Construct the command."""
bits = []
# command to run
bits.append(command)
# connection params
bits.extend(connect_bits(meta))
# database name
if command == 'mysqladmin':
# these commands shouldn't take a database name
return bits
if ... | 0c80072fa70e7943bb7693ad5eb2d24d7078b1cc | 3,650,653 |
def get_common_count(list1, list2):
"""
Get count of common between two lists
:param list1: list
:param list2: list
:return: number
"""
return len(list(set(list1).intersection(list2))) | c149b49e36e81237b775b0de0f19153b5bcf2f99 | 3,650,654 |
def text_present(nbwidget, text="Test"):
"""Check if a text is present in the notebook."""
if WEBENGINE:
def callback(data):
global html
html = data
nbwidget.dom.toHtml(callback)
try:
return text in html
except NameError:
return Fal... | f61f90c6fbbe5251c4839cc3ef82ed1298640345 | 3,650,655 |
def multiFilm(layers, det, e0=20.0, withPoisson=True, nTraj=defaultNumTraj, dose=defaultDose, sf=defaultCharFluor, bf=defaultBremFluor, xtraParams=defaultXtraParams):
"""multiFilm(layers, det, e0=20.0, withPoisson=True, nTraj=defaultNumTraj, dose=defaultDose, sf=defaultCharFluor, bf=defaultBremFluor, xtraParams={})... | ae586a6860ece7e21f46e221398a462619d16acd | 3,650,656 |
def value_iteration(R, P, gamma, epsilon=1e-6):
"""
Value iteration for discounted problems.
Parameters
----------
R : numpy.ndarray
array of shape (S, A) contaning the rewards, where S is the number
of states and A is the number of actions
P : numpy.ndarray
array of sha... | 4f8286d7519577f77f86b239c14e948eed513a6a | 3,650,657 |
def mock_api_response(response_config={}):
"""Create a mock response from the Github API."""
headers = {
'ETag': 'W/"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"',
'Cache-Control': 'public, max-age=60, s-maxage=60',
'Content-Type': 'application/json; charset=utf-8'
}
api_response = MagicMoc... | f79af84cb51ffa063c1db2b70dce99ae61da871a | 3,650,658 |
import tqdm
import json
def load_jsonl(file_path):
""" Load file.jsonl ."""
data_list = []
with open(file_path, mode='r', encoding='utf-8') as fi:
for idx, line in enumerate(tqdm(fi)):
jsonl = json.loads(line)
data_list.append(jsonl)
return data_list | 58bd0dbfa59d08036aa83e62aab47acd2c40ba6e | 3,650,661 |
from io import StringIO
from datetime import datetime
def aurora_forecast():
"""
Get the latest Aurora Forecast from http://swpc.noaa.gov.
Returns
-------
img : numpy array
The pixels of the image in a numpy array.
img_proj : cartopy CRS
The rectangular coordinate system of th... | 04ee88aee75f7ac86063c9a57f4e5155378f9085 | 3,650,662 |
def get_number_trips(grouped_counts):
"""
Gets the frequency of number of trips the customers make
Args:
grouped_counts (Pandas.DataFrame): The grouped dataframe returned from
a get_trips method call
Returns:
Pandas.DataFrame: the dataframe co... | 4045f10e95fe597e626883c586cc832aa34157c3 | 3,650,663 |
import re
def process_text(text, max_features=200, stopwords=None):
"""Splits a long text into words, eliminates the stopwords and returns
(words, counts) which is necessary for make_wordcloud().
Parameters
----------
text : string
The text to be processed.
max_features : number ... | 531c8eea539136701289eea5cd462476ba7fefac | 3,650,664 |
def update_graph_map(n):
"""Update the graph rail network mapbox map.
Returns:
go.Figure: Scattermapbox of rail network graph
"""
return get_graph_map() | 826b12616e9c08b05cecef8d44017a1599ed8f98 | 3,650,665 |
def get_party_leads_sql_string_for_state(party_id, state_id):
"""
:type party_id: integer
"""
str = """ select
lr.candidate_id,
c.fullname as winning_candidate,
lr.constituency_id,
cons.name as constituency,
lr.party_id,
lr.max_votes,
(lr.max_votes-sr.votes) ... | de1e200cf8651626fff04c2011b3ada12b8b08a7 | 3,650,666 |
import requests
import json
import math
import time
def goods_images(goods_url):
"""
获得商品晒图
Parameters:
goods_url - str 商品链接
Returns:
image_urls - list 图片链接
"""
image_urls = []
productId = goods_url.split('/')[-1].split('.')[0]
# 评论url
comment_url = 'https://sclub.jd.com/comment/productPageComments.acti... | 8ed59e295ebd08788f0083be9941ecd8b09f1d84 | 3,650,667 |
def delete_index_list(base_list, index_list):
"""
根据index_list删除base_list中指定元素
:param base_list:
:param index_list:
:return:
"""
if base_list and index_list:
return [base_list[i] for i in range(len(base_list)) if (i not in index_list)] | 0dd8960d0efc168df42cabb92147f078da362e5e | 3,650,668 |
def not_found():
"""Page not found."""
return make_response(
render_template("404.html"),
404
) | 3bc56677f760937f1767e0465e4dbd0a11eb41d0 | 3,650,669 |
def _traverseAgg(e, visitor=lambda n, v: None):
"""
Traverse a parse-tree, visit each node
if visit functions return a value, replace current node
"""
res = []
if isinstance(e, (list, ParseResults, tuple)):
res = [_traverseAgg(x, visitor) for x in e]
elif isinstance(e, CompValue)... | c436dbb548c6a1b7bc6ddc8ea8770cb953e76a72 | 3,650,670 |
def roll(image, delta):
"""Roll an image sideways
(A more detailed explanation goes here.)
"""
xsize, ysize = image.size
delta = delta % xsize
if delta == 0:
print("the delta was 0!")
return image
part1 = image.crop((0, 0, delta, ysize))
part2 = image.crop((delta... | b9ccd9659eedfefa5002f064a23c768d36dfdc0a | 3,650,671 |
def make_long_format(path_list, args):
"""Output list of strings in informative line-by-line format like ls -l
Args:
path_list (list of (str, zipfile.Zipinfo)): tuples, one per file
component of zipfile, with relative file path and zipinfo
args (argparse.Namespace): user arguments to... | 68a30c16409c98e92a31b21a911cbca7ca9ef7c4 | 3,650,672 |
import unicodedata
import re
def is_name_a_title(name, content):
"""Determine whether the name property represents an explicit title.
Typically when parsing an h-entry, we check whether p-name ==
e-content (value). If they are non-equal, then p-name likely
represents a title.
However, occasional... | 2a8d3191920fba0d92670a3d520bfdf6836dbe69 | 3,650,673 |
from datetime import datetime
import traceback
def insertTweet(details, insertDuplicates=True):
""" Adds tweet to database
@param details {Dict} contains tweet details
@param insertDuplicates {Boolean} optional, if true it
will insert even if alread... | e11aba2fecd3d2e0a8f21f25ea1f920512949bdc | 3,650,674 |
from typing import OrderedDict
def return_embeddings(embedding: str, vocabulary_size: int, embedding_dim: int,
worddicts: OrderedDict) -> np.ndarray:
"""Create array of word embeddings."""
word_embeddings = np.zeros((vocabulary_size, dim_word))
with open(embedding, 'r') as f:
... | 86379e2cc9c343733464bea207dc3f41b4dd7601 | 3,650,676 |
import sympy
def symLink(twist, dist, angle, offset):
"""
Transform matrix of this link with DH parameters.
(Use symbols)
"""
twist = twist * sympy.pi / 180
T1 = sympy.Matrix([
[1, 0, 0, dist],
[0, sympy.cos(twist), -sympy.sin(twist), 0],
[0, sympy.sin(twist), sympy.co... | a6e2ac09866f2b54ffb33da681ba9d19e74e57f0 | 3,650,677 |
import aiohttp
from typing import Tuple
from typing import Dict
from typing import Any
from typing import Sequence
async def _parse_action_body(service: UpnpServerService, request: aiohttp.web.Request) -> Tuple[str, Dict[str, Any]]:
"""Parse action body."""
# Parse call.
soap = request.headers.get("SOAPAc... | d5f390d956d726ffca0d37891815b8ccf488a826 | 3,650,678 |
import json
def get_tc_json():
"""Get the json for this testcase."""
try:
with open(GLOBAL_INPUT_JSON_PATH) as json_file:
tc = json.load(json_file)
except Exception:
return_error('Could not custom_validator_input.json')
return tc | de19278f5edb415d40e383d2ad08dfc6e968cb81 | 3,650,679 |
def dualgauss(x, x1, x2, w1, w2, a1, a2, c=0):
"""
Sum of two Gaussian distributions. For curve fitting.
Parameters
----------
x: np.array
Axis
x1: float
Center of 1st Gaussian curve
x2: float
Center of 2nd Gaussian curve
w1: float
... | d60d63ad0776aa6d5babfe5e963503f18dca0c3e | 3,650,680 |
def pdg_format3( value , error1 , error2 , error3 , latex = False , mode = 'total' ) :
"""Round value/error accoridng to PDG prescription and format it for print
@see http://pdg.lbl.gov/2010/reviews/rpp2010-rev-rpp-intro.pdf
@see section 5.3 of doi:10.1088/0954-3899/33/1/001
Quote:
The b... | 9d75007e19d60caac14a2a830800e7db215c0de6 | 3,650,681 |
from datetime import datetime
def getChinaHoliday(t):
"""找出距离输入日期最近的中国节日,输出距离的天数"""
date_time = datetime.datetime.strptime(t, '%d %B %Y')
y = date_time.year
# 中国阳历节日
sh = [
(y, 1, 1), # 元旦
(y, 4, 5), # 清明
(y, 5, 1), # 五一劳动节
(y, 10, 1) # 国庆节
... | bc9520f56135d86cf196bfe30bde0ea645377f45 | 3,650,682 |
def parse_mimetype(mimetype):
"""Parses a MIME type into its components.
:param str mimetype: MIME type
:returns: 4 element tuple for MIME type, subtype, suffix and parameters
:rtype: tuple
Example:
>>> parse_mimetype('text/html; charset=utf-8')
('text', 'html', '', {'charset': 'utf-8'})... | a9abfde73528e6f76cca633efe3d4c881dccef82 | 3,650,683 |
def terraform_state_bucket(config):
"""Get the bucket name to be used for the remote Terraform state
Args:
config (dict): The loaded config from the 'conf/' directory
Returns:
string: The bucket name to be used for the remote Terraform state
"""
# If a bucket name is specified for ... | 443ae393896d180f3e419db7a6b7e346dca0655c | 3,650,684 |
def get_binary_matrix(gene_expr, libraries):
"""
Get binary matrix with genes as rows and pathways as columns.
If a gene is found in a given pathway, it is given a value of
1. Else, 0. Only the list of genes in common between that found
in the gene set libraries and the current dataset are used.
... | 53f39909efc1dfb083cba734a01f77d181f4c36c | 3,650,685 |
def get_tip_downvotes(tips_id):
"""
GET function for retrieving all User objects that have downvoted a tip
"""
tip = Tips.objects.get(id=tips_id)
tips_downvotes = (tip.to_mongo())["downvotes"]
tips_downvotes_list = [
User.objects.get(id=str(user)).to_mongo() for user in tips_downvotes
... | b528be2bd74169a4baff14ecb473ef12d8554be9 | 3,650,686 |
from typing import List
from typing import Dict
def get_placements(
big_graph: nx.Graph, small_graph: nx.Graph, max_placements=100_000
) -> List[Dict]:
"""Get 'placements' mapping small_graph nodes onto those of `big_graph`.
This function considers monomorphisms with a restriction: we restrict only to un... | fad71c888639ba29c0b0d2d61ddeff2a2c1d8653 | 3,650,687 |
import inspect
import six
def _filter_baseanalysis_kwargs(function, kwargs):
"""
create two dictionaries with kwargs separated for function and AnalysisBase
Parameters
----------
function : callable
function to be called
kwargs : dict
keyword argument dictionary
Returns
... | a674c640618ebba3d2c29fec0458773344c84be6 | 3,650,690 |
def torch_to_flax(torch_params, get_flax_keys):
"""Convert PyTorch parameters to nested dictionaries"""
def add_to_params(params_dict, nested_keys, param, is_conv=False):
if len(nested_keys) == 1:
key, = nested_keys
params_dict[key] = np.transpose(param, (2, 3, 1, 0)) if is_conv else np.transpose(p... | fd87617e3e0db491ff313218883961a1c2aa9d0f | 3,650,691 |
from typing import Union
from pathlib import Path
from typing import Optional
def subset_shape(
ds: Union[xarray.DataArray, xarray.Dataset],
shape: Union[str, Path, gpd.GeoDataFrame],
raster_crs: Optional[Union[str, int]] = None,
shape_crs: Optional[Union[str, int]] = None,
buffer: Optional[Union[... | 2d751cd4a9300645cb9bc7b1b353dc29da388f96 | 3,650,692 |
def plot_record_static(
record,
save=True,
scale=1000,
select_kw={},
x_prop='wavenumber',
**kwargs
):
"""Figure of Static data from a record.
High level function.
record: Record to get data from
save: Boolean, Save figure
scale: Scale y axis.
sel... | 4a25068f7df9450870af81fb2507f6262db61b42 | 3,650,693 |
def logmelspectrogram(wave: np.ndarray, conf: ConfMelspec) -> np.ndarray:
"""Convert a waveform to a scaled mel-frequency log-amplitude spectrogram.
Args:
wave::ndarray[Time,] - waveform
conf - Configuration
Returns::(Time, Mel_freq) - mel-frequency log(Bel)-amplitude spectrogram
"""
... | d4849092495b097b8efb292826eb020c8775157c | 3,650,694 |
def get_trainer_config(env_config, train_policies, num_workers=9, framework="tf2"):
"""Build configuration for 1 run."""
# trainer config
config = {
"env": env_name, "env_config": env_config, "num_workers": num_workers,
# "multiagent": {"policy_mapping_fn": lambda x: x, "policies": policies... | 4452d0e037b4bc49a5b027d4f0f6dd2993eceac2 | 3,650,695 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.