content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def rad2deg(value):
"""Convert radians to degrees."""
return value * 180 / pi | 1b38d51ab3fc0a0aa9b0d7363bc8e0b263c19a9b | 3,601,100 |
from bs4 import BeautifulSoup
def get_url_brsrm(isin):
"""
Return Brsrm URL
"""
base_url = common.decode_rot('uggcf://jjj.obhefbenzn.pbz')
search_path = common.decode_rot('/erpurepur/nwnk?dhrel=')
content = cache.get(base_url+search_path+isin)
if not content:
return None
soup =... | f368dbdb4fda575d9dadc54d1491f3aa2407cd69 | 3,601,101 |
def affine_relu_backward(dout, cache):
"""
Backward pass for the affine-relu convenience layer
"""
fc_cache, relu_cache = cache
da = layers.relu_backward(dout, relu_cache)
dx, dw, db = layers.affine_backward(da, fc_cache)
# da = relu_backward(dout, relu_cache)
# dx, dw, db = affine_backw... | a7d299f7319309160531fc91de5c3c60db255ab4 | 3,601,102 |
import math
def _brug_profile_geometry(row, direction="RICHTING", lijn_lengte="WS_LENGTEBRUG", rotate_degree=0, default_width=1,
default_dir=0):
"""
Convert bridge point to line
direction in degrees"""
dir = math.radians(row[direction] + rotate_degree) if not pd.isnull(row[d... | 010fa33b91f55db1a55d78d09dcfa09cd8db9d7f | 3,601,103 |
def GetInvalidTypeErrors(type_names, metrics):
"""Check that all of the metrics have valid types.
Args:
type_names: The set of valid type names.
metrics: A list of rappor metric description objects.
Returns:
A list of errors about metrics with invalid_types.
"""
invalid_types = [m for m in metri... | 27af3804cb4a857d044ad365cdfee090a0d1ab56 | 3,601,104 |
def build_backbone(cfg):
"""
For Generalized_RCNN
"""
assert cfg.MODEL.BACKBONE.CONV_BODY in registry.BACKBONES, \
"cfg.MODEL.BACKBONE.CONV_BODY: {} are not registered in registry".format(
cfg.MODEL.BACKBONE.CONV_BODY
)
return registry.BACKBONES[cfg.MODEL.BACKBONE.CONV_BO... | 7755a43e26e6d5d1e3c1f6fd5ad39f29d9ed66a7 | 3,601,105 |
def tokenize_name_from_patterns(name, patterns=None, token_name="", **kwargs):
"""tokenize a string from certain patterns"""
pattern_res = search_pattern_and_cutout(name, patterns=patterns)
info_res = {}
for n, res in enumerate([i for i in pattern_res if i[-1]]):
# name = replace_and_strip(name... | cde9246d4e9782362c7d7c636be65a602ee29482 | 3,601,106 |
import textwrap
def _NormalizeDescription(description):
"""Normalizes description text.
Args:
description: str, The text to be normalized.
Returns:
str, The normalized text.
"""
if callable(description):
description = description()
if description:
description = textwrap.dedent(descriptio... | ecadc627c34d5de544a03a45850bb034f0678446 | 3,601,107 |
def login_required(f):
"""Redirect to login page if user not logged in"""
@wraps(f)
def decorated_function(*args, **kwargs):
if not session.get('logged_in'):
flash('Login required', 'error')
return redirect(url_for('login', next=request.url))
return f(*args, **kwargs)... | 2132d610a8e84d1a3febfcfa7873a66fd11e31ba | 3,601,108 |
def get_hrp_allocation(cov, tickers):
"""Compute top-down HRP weights"""
weights = pd.Series(1, index=tickers)
clusters = [tickers] # initialize one cluster with all assets
while len(clusters) > 0:
# run bisectional search:
clusters = [c[start:stop] for c in clusters
... | f369cccec9791250653d34a6171a48b87874ffb4 | 3,601,109 |
def schedule_menu_help():
"""Меню подсказок"""
kb = InlineKeyboardMarkup()
audience_help = InlBtn(text="🚪", callback_data="audience_help")
teacher_help = InlBtn(text="👴", callback_data="teacher_help")
kb.row(audience_help, teacher_help)
return kb | 857217e0798eb2730b56c1973677844e689f84dc | 3,601,110 |
import os
import tempfile
def auth_irods_user(user, password, scheme='PAM'):
"""
Attempts to authenticate the given user in the local zone
using the iinit command and the desired scheme (with the
default being PAM authentication).
Returns True if the user was successfully authenticated,
False... | 35426ad9aa5c1459fce01f4cf99e28c46cc0c3be | 3,601,111 |
def patch_extraction(Xb, yb, sizePatches=128, Npatches=1):
"""
3D patch extraction
"""
batch_size, rows, columns, slices, channels = Xb.shape
X_patches = np.empty((batch_size*Npatches, sizePatches, sizePatches, sizePatches, channels))
y_patches = np.empty((batch_size*Npatches, sizePatches, ... | 62c9b95b8258902de2a5334e41b5f0b197100f17 | 3,601,112 |
def get_events(content, vm_name):
"""
Get List of events for VM
:param content:
:param vm_name:
:return: List of events
"""
vm = get_obj(content, [vim.VirtualMachine], vm_name)
event_filter = vim.event.EventFilterSpec()
filter_spec_entity = vim.event.EventFilterSpec.ByEntity()
fi... | 1530cc8f36ec788777918b6607bd75b7906815ec | 3,601,113 |
from typing import Optional
from typing import Union
from typing import List
def mv_col_handling(
data: pd.DataFrame,
target: Optional[Union[str, pd.Series, List]] = None,
mv_threshold: float = 0.1,
corr_thresh_features: float = 0.5,
corr_thresh_target: float = 0.3,
return_details: bool = Fals... | f6ba007f25bb40fedeb4ee5e37c1c3acaf2f2261 | 3,601,114 |
def get_vix():
"""Fetch vix from Interactive Brokers and append to history'''
:return: Dataframe
"""
ibw = IbWrapper()
ib = ibw.ib
vix = Index('VIX')
cds = ib.reqContractDetails(vix)
# contracts = [cd.contract for cd in cds]
bars = ib.reqHistoricalData(cds[0].contract,
... | f88a48d86746d05e440889dc4517fb83966d0121 | 3,601,115 |
import json
from pathlib import Path
def parse_json(filepath=None):
"""Parse the json file.
:param filepath: the path name of the file to parse
:type filepath: str|Path
:return: AppConfig
:raises KeyError: if log section not exists
"""
if filepath is None:
# set default config ... | f69330dd1177c2222186e81f9ad39abe28a16d7a | 3,601,116 |
import heapq
def astar(maze, start, end, allow_diagonal_movement=False):
"""
Returns a list of tuples as a path from the given start to the given end in the given maze
"""
start_node = Node(None, start)
start_node.g = start_node.h = start_node.f = 0
end_node = Node(None, end)
end_node.g = ... | bc4e9a81f4a02ea3899c59a1be1d67a0281c2d2c | 3,601,117 |
import os
def tune_http():
"""
:return:
"""
# check if the post request has the file part
if 'file' not in request.files or request.files['file'].filename == '':
flash('No file choosed :/', category="error")
return redirect(request.url) # Return to HTML page [GET]
file = requ... | 1c48a3cd02c0429cfeaf4e20ef384965c5e5b2ab | 3,601,118 |
import math
def jd_to_date(jd):
"""
Convert Julian Day to date.
Algorithm from 'Practical Astronomy with your Calculator or Spreadsheet',
4th ed., Duffet-Smith and Zwart, 2011.
Parameters
----------
jd : float
Julian Day
Returns
-------
year : int
Year a... | 1b766ff5fd62f8d74817ee8a6fc056798babaa77 | 3,601,119 |
from pathlib import Path
import json
from typing import OrderedDict
def read_json(file_name: str):
"""
Function that reads a json file
Parameters
----------
file_name: str
The json file path
Returns
-------
OrderedDict
The json file's contents
"""
file_name =... | 2d487309bcc4b14c208c02d48e8f7d5994eea88b | 3,601,120 |
def regular2regular(
data,
ilons,
ilats,
olons,
olats,
distances=None,
inds=None,
how="nn",
k=10,
radius_of_influence=100000,
n_jobs=2,
):
"""
Interpolates from regular to regular grid.
It's a wraper around `fesom2regular` that creates an object that
mimic fes... | d1ce6e4d31b143233bd7fb07cb8ce137d249a579 | 3,601,121 |
def km_centroids(pts, assign, k):
"""Implements the centroid-update step of the k-means algorithm.
Given a set of points, ``pts``, of shape ``(npts, ndim)``, and an
assignment of each point to a region, ``assign``, and the number
of means, ``k``, returns an array of shape ``(k, ndim)`` giving
the ce... | 6606ad267fbaf0fd1b015120f0053828933c755e | 3,601,122 |
def recover_wallet(
word1: str, word2: str,
word3: str, word4: str,
word5: str, word6: str,
word7: str, word8: str,
word9: str, word10: str,
word11: str, word12: str
):
""" Recover Wallet private and publick key from 12 seeds words """
seeds = [
word1, word2, word3, word4,
... | b4a70cccad5de4a5868da10bca1113739180420f | 3,601,123 |
import json
def encrypt(d, master_key):
"""
Encrypt a dictionary with a master key.
Args:
d (dict): the dictionary to encrypt.
master_key (str): the master key.
Returns:
str: the encrypted dictionary as a hex string.
"""
key = generate_key(master_key)
fernet = Fer... | 0096443d4f6280f918af2400fd2713d8cd7037ab | 3,601,124 |
from datetime import datetime
import os
def get_image_path(directory: str) -> str:
"""
Get Image Path
Generates the path of the next image to save.
"""
now = datetime.datetime.now()
return os.path.join(directory, f'{now.date().isoformat()}', f'{now.time().strftime("%H:%M:%S")}.jpg') | 1f3e27a8a3ef70e1df23eeabbdb6daa3e0d1e48a | 3,601,125 |
def get_lhd_maximin_points(var_lower, var_upper, integer_vars,
sample_size, num_trials=50):
"""Compute a latin hypercube design with maximin distance.
Compute an array of points in the given box, where n is the
dimension of the space. The selected points are picked according
... | aa766f907acc79e5d718bbb876a353ab449fc2e5 | 3,601,126 |
import textwrap
def indent(multiline_str: str, indented=4):
"""
Converts a multiline string to an indented string
Args:
multiline_str: string to be converted
indented: number of space used for indentation
Returns: Indented string
"""
return textwrap.indent(multiline_str, " " ... | 9fd5f2310ade00071a57731040435428cff88557 | 3,601,127 |
def parse_dhcp_logs(from_date, macaddr):
"""Parse dhcpd logs, extract last ipaddr from DHCPACK if found
"""
macaddr = macaddr.lower()
entries = tsclient.fetch_dhcp_logs(from_date)
return entries.get(macaddr, None) | 0da376edc6c0a205a33b804c24bc80d1f105150e | 3,601,128 |
def automaticProcess(volume, pathToImages, grayThreshold, minSize, maxSize, useSubgroups, offset):
"""Deprecated. This functionality is nolonger maintained."""
# todo: make openImageStack return a volume rather than setting a global variable
#openImageStack(pathToImages)
blobs = findBlobs(volume, grayT... | 576acd1527e623fd43c623e78cd5b7e8870972a2 | 3,601,129 |
def _iteration_report_pb_to_subnetwork_reports(iteration_report_pb):
"""Converts IterationReport proto to a `MaterializedReport` list."""
def _proto_map_to_dict(proto, field_name):
"""Converts map field of a proto to a dict.
Args:
proto: the proto to read from.
field_name: name of the map fiel... | 49a5bc3966110318088447832ebe8609cd9ba635 | 3,601,130 |
def eval_root_children(node, evi):
"""
Evaluates the PC rooted at `node` at evidence `evi`.
This function only applies to the root of a PC.
"""
n_threads = nb.config.NUMBA_DEFAULT_NUM_THREADS
sizes = np.full(n_threads, node.nchildren // n_threads, dtype=np.int32)
sizes[:node.nchildre... | 01d5b2043927fc3ee5b640f22244997c545b2ef4 | 3,601,131 |
def validate_name(name, flash_errors=True):
"""Validates a name. Flashes errors if flash_errors is True."""
# Allow letters, spaces, hyphens, and apostrophes.
# First and last characters must be letters.
if not name_regex.match(name):
if flash_errors:
flask.flash("'{0}' is not a vali... | 4456e5d91ae0f148d10cf0a7ddee3e9aa554e581 | 3,601,132 |
def upload_user_pic(pic_name, user_id, type):
"""[summary]
Uploads users picture path to database
Args:
pic_name ([String]): [name of pic]
user_id ([String]): [user id]
type ([String]): [admin or user]
Returns:
[String]: [1 if success, 0 if failed]
"""
try:
... | 2f04038a9b48427bcb14d1e00fdafacf9130fbd6 | 3,601,133 |
def availability_zone_get(context, id_or_name):
"""Get availability zone by name or id."""
return IMPL.availability_zone_get(context, id_or_name) | 009b2b6338f7aae7415ca0171e82bca882255198 | 3,601,134 |
def is_stereo_compatible(tra, sgr1, sgr2):
""" is this transformation compatible with the reactant/product stereo
assignments?
"""
cgr1 = without_stereo_parities(sgr1)
cgr2 = without_stereo_parities(sgr2)
atm_key_dct = full_isomorphism(apply(tra, cgr1), cgr2)
# determine the stereo centers ... | 89c79dca8b87cd0a7f341bd56f4b2b77f956cc4b | 3,601,135 |
def pil_to_numpy(x_pil):
"""
:param x_pil: PIL.Image object
:return: Normalized numpy array of shape (channels, height, width)
"""
# Channels are the third dim of a PIL.Image,
# but we want to be able to index it by channel first,
# so we use np.rollaxis to get an array of shape (3, h, w)
... | be2b0d4dbe8d15c0154bb6d2428e8e66435df1c4 | 3,601,136 |
def upload(path, public, file_type=None): # could also call it import
"""
Upload a file or workflow to Galaxy.
Currently, gxwf attempts to upload any file with a .ga extension as a workflow, and all others as datasets.
"""
return upload_commands.upload(path, public, file_type) | 58a7dc3d02178f5e8830efd8647b00551a3c08ae | 3,601,137 |
import scipy.sparse as sp
from time import time
def fit_scan( scan, # input scan
lmk_3d, # input scan landmarks
model, # model
lmk_face_idx, lmk_b_coords, # landmark embedding
weights, ... | 7cd463260608bfb2b3e65de12743caf8371e6e2e | 3,601,138 |
import html
def add_dash(server):
"""
It creates a Dash app that plots a line chart of life expectancy from gapminder dataset
with 2 widgets : rangeslider for years and dropdown for sub-region filter
:param server: The Flask app object
:return: A Dash server
"""
app = Dash(server=serv... | 8f68b887ee5dceacf2403cb2b1efd7bf5e45eb0d | 3,601,139 |
from typing import Concatenate
def create_model(params: dict):
"""Generates a merged ANN and RNN model for hyperparameter training using Optuna
Args:
params (dict): contains Optuna-defined hyperparameter ranges
Returns:
keras model: a compiled model
"""
ACTIVATION = config["RNN_... | e72e0aa0ff2fc3861ab4871876b287c899be7662 | 3,601,140 |
def get_current_positions():
"""Get current positions returns a dataframe with columns:
Date Purchased,
Purchase Price,
Quantity Held,
Ex-dividend date
Current Price,
Symbol
"""
positions = api.list_positions()
target_columns = ['avg_entry_price', 'current... | 36f4529881bc9f86dc9a335435ec67cb87f5acaf | 3,601,141 |
def parse_arguments():
"""
Parse all command line arguments.
Returns:
segments - full file path to segment file
tumor - full file path to tumor bam
normal - full file path to normal bam
fasta - full file path to correct FASTA file
exons - full file path to bed file of all exons
directory - target direct... | 5cf2e5c94712a92b69a1ff722123fae8dcecbb06 | 3,601,142 |
def trapezoid_smooth(spectrum, width):
"""
Smoothing based on a `astropy.convolution.Trapezoid1DKernel` kernel.
Parameters
----------
spectrum : `~specutils.Spectrum1D`
The `~specutils.Spectrum1D` object to which the smoothing will be
applied.
width : number
The width of... | 2ac6a72e780edc6a1620682e21eea37280b1d636 | 3,601,143 |
def test_module_object_function_override():
"""Test that if a the PythonistaModuleAdapter has an overridden function
that function returns as expected when called."""
def open(self, url):
return url
PythonistaModuleAdapter.open = open
webbrowser = PythonistaModuleAdapter('webbrowser')
... | 26058f9807ecee5d385b08486bcaa8dfe61feba3 | 3,601,144 |
import numpy
def uft_d_active_integrals(sys, ea, eb, foa, fva, fob, fvb,
iocca, ivira, ioccb, ivirb, dveca, dvecb):
"""Return derivatives of unrestricted one and two-electron integrals
with small occupations excluded."""
# get FT Fock matrix
fa, fb = sys.u_fock_tot()
fa... | 98967cdd33cf19eb033d171ed590f771fc3be356 | 3,601,145 |
def list_pattern_features(client, patter_name, type_=None, file_=None):
"""List features in a Creo Pattern.
Args:
client (obj):
creopyson Client.
patter_name (str):
Pattern name.
`type_` (str, optional):
Feature type patter (wildcards allowed: True).
... | d1923ccdb178a211ecd896c325170a5e247557aa | 3,601,146 |
def cost_of_model_fit(stimulus_params, pair_a, pair_b, judgment_counts, params):
"""
Stimulus_params is the independent variable. LL is the dependent variable.
:param stimulus_params: nonzero coordinates of each of the stimuli stretched into one vector
:param pair_a: pair 1 of stimuli from trial
:pa... | 6920874f642231a4de3bfee565957db3eb940415 | 3,601,147 |
def rate_snippet(request, snippet_id):
"""
Allows a user to rate a Snippet.
Context::
None, returns a redirect back to the Snippet.
Template::
None, returns a redirect back to the Snippet.
"""
snippet = get_object_or_404(Snippet, pk=snippet_id)
if not Rati... | 74bc2044e2881725f954d96ea114aed8c6b17288 | 3,601,148 |
def returnBeta(*args):
"""
Return a beta distributed random variables with given parameters
"""
return [np.random.beta(args[0],args[1],1)] | 986853d4be7c95c6ee5164cd5490c38fd345e297 | 3,601,149 |
def get_binary_mask(x):
"""
Return binary mask from numpy array
:param x: numpy array
:return: binary mask from numpy array
"""
x[x >= 0.5] = 1.
x[x < 0.5] = 0.
return x | d63a2cff4d8398c52ea97fff720d78a8d6df66b5 | 3,601,150 |
def match_polygons(prediction_df, annotation_df):
"""
Match polygons (shapely objects) based on area of overlap
"""
'''
1) Find overlap among polygons efficiently
2) Calulate a cost matrix of overlap, with rows as itcs and columns as predictions
3) Hungarian matching for pairing
4) Cal... | 0e2253525161ac236e5154974d3ba7a82d2090a6 | 3,601,151 |
def append_query_params(original_url, **kwargs):
"""
Add additional query string arguments to the given url.
Example call:
new_url = append_query_params(
original_url, error='this is an error',
another_arg='this is another argument')
"""
scheme, netloc, path, query_s... | 2850549307204bcc48a8e773e2d1eadc5e261c94 | 3,601,152 |
def __createGraphStructure(argument, references, graphs, arguments):
""" Using the 'references' of this 'argument', create a graph-like
structure and make it part of the graphs in 'graphs'. The other
'arguments' from the config-subtree of the "dynamic"-tag are provided
to locate the referenced arguments. """
... | 51951bce08070627a251817a6c7c2c7738c0fc61 | 3,601,153 |
import os
def update_repo(config):
"""
Update (pull) the Git repo
"""
projectname = config[0]
triggerconfig = config[1]
repo_url = triggerconfig['repo']
repo_parent = settings.REPOS_CACHE_DIR
if 'repoparent' in triggerconfig and triggerconfig['repoparent']:
repo_parent = trigg... | c70bd911d3474a8f891784ce0722f771fb6c5e57 | 3,601,154 |
def emg_filter_highpass(x, order = 4, sRate = 200., lowcut = 10.):
""" Forward-backward high-pass filtering (IIR butterworth filter) """
nyq = 0.5 * sRate
low = lowcut/nyq
b, a = butter(order, low, btype = 'high', analog=False)
return filtfilt(b=b, a=a, x=x, axis=0, method = 'pad', padtype = 'od... | 2d5d89941765d52ad4cbcc76be016b6340525c9c | 3,601,155 |
import random
def process_image(path, steering_angle, augment, shape=(100,100)):
"""Process and augment an image."""
image = load_img(path, target_size=shape)
if augment and random.random() < 0.5:
image = random_darken(image) # before numpy'd
image = img_to_array(image)
if ... | 3c0e8896f92d9c4d0966412f3785b6762d1c66aa | 3,601,156 |
import html
def create_deck(df: pd.DataFrame, city: str) -> html.Div:
"""
Create a deck of tweets
:param df: dataframe to get tweets of
:param city: string of city to filter on
:return: list of child elements
"""
if city is not None:
df = df[df['city'] == city]
list_items = []... | c913edb138f638bf3bdb9bd9acc48ebd93c1784b | 3,601,157 |
import string
def readSurface( name ):
"""Read the files 'name'.vertices and 'name'.triangles and returns
lists of 6-floats for vertices x,y,z,nx,ny,nz and a list of 3-ints
for triangles"""
f = open( name+'.vertices' )
vdata = f.readlines()
f.close()
vdata = map( string.split, vdata ... | 360cc8c6a61acdab44ac15ffb21979600441c1ca | 3,601,158 |
import json
def get_labels_and_manifest(schema_content, args):
"""Get schema content and labels from cli argument or automated creation."""
if args.schema_path:
labels = json.loads(schema_content)['schemas']['named_entity']['tags']
else:
labels = DEFAULT_LABELS if not args.entity_types els... | d0928ad07cedc0658d623cd66c60436bfc17266f | 3,601,159 |
from typing import List
def create_outputfiles(payload: List[DojoSchema.ModelOutputFile]):
"""
Create an `outputfile` for a model. Each `outputfile` represents a single file that is created upon each model
execution. Here we store key metadata about the `outputfile` which enables us to find it within the ... | 25ba09a197e7613a9bcd8289e0b8f76f7cafbf5a | 3,601,160 |
from typing import Any
def check_value_base_type(t: BaseType, value: Any):
"""Validate that value conforms with the BaseType and return the canonicalized value if so
Raises InvalidValueError if the value is invalid
"""
t = canonicalize_base_type(t)
if isinstance(t, type):
if isinstance(va... | 3f1a17e13aecac7719ca3bd1bb8eba2ca7f05047 | 3,601,161 |
import torch
def load_data(path="./cora/", dataset="cora"):
"""读取引文网络数据cora"""
print('Loading {} dataset...'.format(dataset))
idx_features_labels = np.genfromtxt("{}{}.content".format(path, dataset),
dtype=np.dtype(str)) # 使用numpy读取.txt文件
features = sp.csr_matri... | 86cfb27406d8dbed33c10e461606c191fee48aa0 | 3,601,162 |
def t_statistic(mean1, mean2, n1, n2, svar1, svar2):
"""
Compute the t-statistic for the given estimates
"""
# Complete this funtion
a=svar1
b=svar2
c=a/n1
d=b/n2
e= 1/sqrt(c+d)
t_stat = e*(mean1-mean2)
return t_stat | 92435680aee41d5a6973ba6edc240bc808aecda9 | 3,601,163 |
def move_left(place: Coord) -> Coord:
"""Move left from place."""
x_place, y_place = place
return (x_place - 1, y_place) | b07939e7d9bcb77a2020eb862c65a7359731e9b2 | 3,601,164 |
def find_closest_star(root, star, depth=0):
"""
For one star, recursively finds closest match in entire k-d tree-ized catalog.
Returns element of kd tree
Parameters
----------
Root: element of kd tree
Star: element of kd tree
"""
if root is None:
return None
coord = dep... | dd9ee9c361c9e1a4b2d196097616f30836ac65aa | 3,601,165 |
def is_possible_move(direction, you, snake_heads, occupied, height, width, spacing=1):
"""
:param direction: up down left or right
:type direction: str
:param you: all blocks our body is occupying
:type you: list of dict
:param occupied: all blocks all snakes are occupying
:type occupied:... | 01909f9daecd01fd21b13c5a24bc0081ce50b7c9 | 3,601,166 |
def make_dot(x, model):
"""Produces Graphviz representation of PyTorch autograd graph.
Notes:
* Blue nodes are the Variables that require grad.
* Orange nodes are input tensors.
* Green nodes are output tensors.
* Darkpink nodes are backward operations.
Args:
x (tor... | 51c4139645d5f00bd814d356f1c763ace3250712 | 3,601,167 |
def get_intervals(xi,yi,grid):
""" This function computes the length of intersection of the line parametrized by the sample
observations X and Y with the grid (i.e. returns all the lengths of the line-segments generated
by passing a line through the grid)
"""
start = grid.start
end = grid.end
... | 2e0b59fe66abd1588536c45a88974f801d98b71d | 3,601,168 |
import sqlite3
def create_subject(subject, metadata=None):
"""Formally adds the given subject into the binder. It will be added into the database and automate
the creation of the template needed for the subject.
:param subject: The subject to be added.
:type subject: str
:param db: The database ... | 05bc970786a01b804ba2ce2728fa1ad4b7825f2e | 3,601,169 |
import time
def corporation_system_oneday(mongohandle, corporation_id, system):
"""find by corp and system - one day"""
allkills = mongohandle.allkills
system = int(system)
timeframe = 24 * 60 * 60
gmtminus = time.mktime(time.gmtime()) - timeframe
cursor = allkills.find({"corporation_id": corp... | fcedbb5853f5f9278450a5a7518c46ad37075136 | 3,601,170 |
from typing import List
def run_lsm_from_final_norm_state(config: Config) -> List[Step]:
"""
Run the LSM over the entire historical period, and retain the state files
for each iteration. Discard the results.
"""
# Set the yearmon in final state from climate norms run to be the first
# forcing... | f9fca4aacfa4f9c70249bcf4f0322ab39083da42 | 3,601,171 |
def gin_ensure_key(token):
"""
Confirms whether the public key 'gin-proc' is installed
on user's GIN account or not.
"""
for key in gin_get_keys(token):
if key['title'] == PRIV_KEY:
return True | 0e7f91ab38d16e49cf1102555a1e58027835dc2f | 3,601,172 |
def MakeModeratedEffect(data,i = 0, j = 1, effect = 0):
"""Summary line.
Extended description of function.
Parameters
----------
arg1 : int
Description of arg1
arg2 : str
Description of arg2
Returns
-------
bool
Description of return value
Examples
... | add8b8490f9df5d235067ba26993885e7762685b | 3,601,173 |
import copy
def copy_trade(trade):
"""
Make a modifiable copy of a Trade object for use in split_trades.
"""
new_trade = Trade(
trade.trade_type,
copy.copy(trade.price),
copy.copy(trade.fee),
copy.copy(trade.volume),
trade.exchange_trade_id,
None,
)
... | 6b127f49904e3eddb440c0aca44d51c3317c3f09 | 3,601,174 |
def valid_permlink(permlink, allow_empty=False):
"""Returns validated permlink or throws Assert."""
assert isinstance(permlink, str), "permlink must be string: %s" % permlink
if not (allow_empty and permlink == ''):
assert permlink and len(permlink) <= 256, "invalid permlink"
return permlink | ec5094ed8ac938b85c423218527d92b89ba3f1f3 | 3,601,175 |
def watershed_ift(input, markers, structure = None, output = None):
"""Apply watershed from markers using a iterative forest transform
algorithm.
Negative markers are considered background markers which are
processed after the other markers. A structuring element defining
the connectivity of the ob... | 713088daa1023744c0a2c249b59d81fcf4ac9548 | 3,601,176 |
def get_answer(offer, user):
"""Returns an user answer for the given offer"""
if not user.is_authenticated:
return None
return offer.answers.filter(user=user).first() | e89da7d11e6e8a01deb8177d3af9c693267fe09a | 3,601,177 |
from typing import List
def to_vecs_from_matrices_with_sparsity(
c_sys: CompositeSystem, matrices: List[np.ndarray]
) -> np.ndarray:
"""converts matrices to vecs.
this function uses the scipy.sparse module.
Parameters
----------
c_sys : CompositeSystem
CompositeSystem of this povm.
... | 278f1db6fa16f8575d683ce5027832998ecb3d89 | 3,601,178 |
def folder_navigation_top(request, item_container):
""" Eigenschaften des Ordners aendern """
class dms_itemForm ( forms.Form ) :
name = forms.CharField(max_length=60,
widget=forms.TextInput(attrs={'size':60}) )
navigation = forms.CharField(required=False,
... | 2f2b821a7cb6c0b962d4c9ca6a5b492991928b06 | 3,601,179 |
def simple_cdf(x_vals, num_summed, algorithm=0):
"""Analytic expression for the cdf of a sum of
num_summed random variables distributed according
to an algorithm.
Parameters
----------
x_vals : list
List of x values for which we will return a cdf.
num_summed : type
Number of... | c8ce1da482a04ac1bac9f6cf0bde608a05385ff1 | 3,601,180 |
from typing import Tuple
def distance_filter(contour, point: Tuple[int, int], min_dist: float = 0, max_dist: float = 50):
"""
Filters out contours that their center is not close enough
to the given (x, y) point in the image
:param contour: the contour to be filtered (numpy.ndarray)
:param point: ... | 8788ec042b9a549202ecc7df648e9dd75587c25f | 3,601,181 |
import os
def getMusZs(directory=""):
"""
Searches directory specified and returns a list of redshifts for GadgetMUSIC
snapshots.
Assumes file names are of format GadgetMUSIC-NewMDCLUSTER_0001.z0.000...
Directory must only contain files with names of this format.
Parameters
----------
... | 8834b8dbae8e07056fd68fe974476d54be64487a | 3,601,182 |
def main():
"""Main routine, when called as a script."""
global _CONN
# Parse command line args
optparser = optparse.OptionParser(
usage='%prog HOSTNAME [-u USER -p PASS] [-n NAMESPACE] [--no-ssl]')
# Username and password
optparser.add_option('-u', '--user', dest='user',
... | 32c515cf543ebe1594705be71527a3bda806e1e7 | 3,601,183 |
def do_tasks(request, uid):
"""Execute tasks of a wizard"""
task = request.session.get('wiz_' + uid + '_class')
if not task:
raise Http404
return
if task not in wizs:
raise Http404
return
if not request.session['wiz_' + uid + '_ctask']:
raise Http404
... | cc06d5750074b6fbe0b145a0c4b6f9a22b668050 | 3,601,184 |
async def oppio_client_supervisor(opp, aiohttp_client, oppio_stubs):
"""Return an authenticated HTTP client."""
access_token = opp.auth.async_create_access_token(oppio_stubs)
return await aiohttp_client(
opp.http.app,
headers={"Authorization": f"Bearer {access_token}"},
) | ccc821b17490e8c9163a813d8b9aab03f1467713 | 3,601,185 |
def get_charts(current_date):
"""
Grabs the charts entries for the given date
:return list of chart entries
"""
print u"{0:s}".format(current_date.strftime("%d.%m.%Y"))
date_in_milliseconds = time.mktime(current_date.timetuple()) * 1000
url = EP % date_in_milliseconds
html = common.re... | f766843347044f45fa427a37137cc8eacedf084a | 3,601,186 |
import os
import json
def load_gt(file_name):
"""load ground truth data, if existent"""
file_path = os.path.join(os.path.realpath('.'), 'mock', file_name + '.gt.json')
if os.path.exists( file_path ):
with open(file_path, 'r') as file:
# load file
processed_table = json.loa... | bec3389d0316f3965fed874aa6668a2a44e27d8d | 3,601,187 |
from ocflib.account.search import user_exists
def email_for_user(username, check_exists=True):
"""Return email for a user.
Currently, just appends @ocf.berkeley.edu, but could eventually do
something more complicated.
"""
if check_exists:
if not user_exists(username):
raise Va... | 8ad77fd07c0f2b8f9f85e6cbe5dbb243dd7053ab | 3,601,188 |
from typing import Tuple
from typing import Iterable
def resize(array: np.ndarray,
shape: Tuple[int, ...],
reflect_axes: Iterable[int] = ()) -> np.ndarray:
"""Resize an array with the local mean / bilinear scaling.
Works for both upsampling and downsampling in a fashion equivalent to
... | 5e6953faf3560783dfd26ac395ef584c6a2e24f1 | 3,601,189 |
from typing import Union
def cmd_concept_list(mixcli: MixCli, **kwargs: Union[str, bool]):
"""
Default function when MixCli concept list command is called.
:param mixcli: a MixCli instance
:param kwargs: keyword arguments from command-line arguments
:return: None
"""
proj_id = kwargs['pro... | dea85ea37172948d9f09927aa27fb7c51cb42bdf | 3,601,190 |
import logging
import os
def get_path_contents(folder_path):
"""
Get the entire contents of a path. Returns both files and folders at this path, and does not return
filenames contained within sub-folders at this path.
:param folder_path: a string containing a valid path to a computer directory
:r... | bcae9d348e236ebdd3716e1397cbf23eecb9e883 | 3,601,191 |
def leiaDinheiro(msg):
"""
-> Função que verifica se um preço digitado é valido
:param msg: recebe a menssagem pedindo um preço
:return: retorna o preço válido
"""
while True:
preco = input(msg).strip().replace(',', '.')
if preco.isalpha() or preco == "":
print(f'\033... | 9712bf74c29f0ac62d6f2326794d0537cc885b5c | 3,601,192 |
from aiida.cmdline.utils.templates import env
import re
import click
def edit_pre_post(pre=None, post=None, summary=None):
"""
use click to call up an editor to write or edit pre / post
execution scripts for both codes and computers
"""
template = env.get_template('prepost.bash.tpl')
summary =... | 5e4ea8e2fa4ea4cda74ae71825e7bfab8c2482ed | 3,601,193 |
def search_port(dvs, portgroupkey):
"""
Find port by port group key
"""
search_portkey = []
criteria = vim.dvs.PortCriteria()
criteria.connected = False
criteria.inside = True
criteria.portgroupKey = portgroupkey
ports = dvs.FetchDVPorts(criteria)
for port in ports:
searc... | de5244d60f77e74a56b40314ba57d0148e3e02ad | 3,601,194 |
def delete_user(user_id):
"""Delete the named user from the system
Mark the given user as deleted. The user isn't actually deleted,
but marked as such to maintain the audit trail. After deletion,
all other operations on said user are prohibited.
---
tags:
- User
operationId: delete... | 45fbc70a60c70f19ce5e2a4de6998b7be740c275 | 3,601,195 |
from typing import OrderedDict
def get_attributes(ncobj, verbose=None, normalise=True):
"""
Copy the global and variable attributes from a netCDF object to an
OrderedDict. This is a little like 'ncdump -h' (without the formatting).
Global attributes are keyed in the OrderedDict by the attribute name.... | 311e76f5f8b675a11fe3b897b2375feb3952636d | 3,601,196 |
def process_dsn(dsn):
"""
Take a standard DSN-dict and return the args and
kwargs that will be passed to the psycopg2 Connection
constructor.
"""
args = ['host=%s dbname=%s user=%s password=%s' % (dsn['host'], dsn['db'], dsn['user'], dsn['passwd'])]
del dsn['host']
del dsn['db']
del dsn['user']
del dsn['passw... | c73b641cd4e28c5824db6d37d3aec2786c7461ff | 3,601,197 |
import sys
def Unchecked():
"""Verify if the command "Unchecked" is present. In this case it means the action was just unchecked from RoboDK (applicable to checkable actions only)."""
if len(sys.argv) >= 2:
if "Unchecked" in sys.argv[1:]:
return True
return False | 70e288eb5a662f0aca9ebf6f4429b3b8510ea307 | 3,601,198 |
import collections
def parse_useful_string():
"""Return a changed defaultdict
"""
useful_lines = product_checkout_useful_string().split(sep='\n')
changed_files = collections.defaultdict(list)
for line in useful_lines:
if line == '':
continue
pairs = line.split('\t')
... | a556466141ee0a285fc87fa3e9c100903c2372cd | 3,601,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.