content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def recursive_dict_evaluate(d):
"""
Recursively run :func:`eval` on each element of the provided
dictionary.
A raw read of a configuration file with `ConfigObj` results in a
dictionary that contains strings or lists of strings. However, when
assigning the values for the various ParSets, the `f... | c5eb463aaa95d2bcfd37d71d5e1f5e091331bfd6 | 44,670 |
def firmware_version(ip_address):
"""
Returns the firmware version
"""
return str(snmp_get(FIRMWARE_VERSION_OID, ip_address)) | b16b11e3606da1fbe6475c7c3e66c146a04481fe | 44,671 |
def adjugate(matrix : Matrix) -> float:
"""It transposes a given Matrix,"""
array = [item[:] for item in matrix.rawMatrix()]
arrays = [[] for item in matrix.collsAll()]
for row in array:
i = 0
for num in row:
arrays[i].append(num)
i+=1
return Matrix(arrays) | 6d7438420abe9a5d85d45db7440f6169e4cfdccf | 44,672 |
import string
def shorten(message):
"""Convert message into a shorter form"""
if message == 'On time':
return '0'
number = message.translate(None, string.ascii_letters).strip()
sign = '+' if 'late' in message else '-'
return '{}{}'.format(sign, number) | 3fc8392e9ec61fa46fd9db6ed69ee4ac62a5f4b0 | 44,673 |
def index():
"""Serve index page."""
default_application_json = post('test', 'group/project', {})
rendered = flask.render_template('index.html.j2', application_json=default_application_json)
return rendered | 7b37cbb72d242d386a53986f6b25ab39cea0e238 | 44,674 |
def get_ground_truth(data, keypoints, warped_keypoints, shape, correctness_thresh, inv):
"""
Compute the ground truth keypoints matchings from image to image' where image' in the result
of warping image with H_matrix.
"""
#keypoints = np.stack([keypoints[0], keypoints[1]], axis=-1)
# Warp the ... | d1f93ad572ffd0177e689473c70ab3e1d9e05107 | 44,675 |
def bsonjs_dump(doc, file, mode=bsonjs.LEGACY):
"""Provide same API as json_util.dumps"""
return bsonjs.dump(to_bson(doc), file, mode=mode) | cd1116b91d6f6d01b207b848b094c880df86392e | 44,676 |
def get_create_table_field_data(field_data):
"""
Generates the field wise query segments needed to create a table.
:param field_data: List of dicts with each dict having keys 'name', 'type' and, optionally, 'modifiers'
:return: none
"""
field_query_list = []
for field in field_data:
... | 92ef0a4c60d54212e90cc3ac110964565bbfd1be | 44,677 |
def hough_lines(img, ρ, θ, threshold, min_line_len, max_line_gap):
"""
`img` should be the output of a Canny transform.
Returns the hough lines.
"""
lines = cv2.HoughLinesP(img, ρ, θ, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)
return lines | 0fb36b815ba9edd98822362a9b458cbcbf29f6a7 | 44,679 |
def url2pathname(pathname):
"""OS-specific conversion from a relative URL of the 'file' scheme
to a file system path; not recommended for general use."""
tp = urllib.splittype(pathname)[0]
if tp and tp != 'file':
raise RuntimeError, 'Cannot convert non-local URL to pathname'
if pathname[:3] ... | 1a948f456ce94769ac8f98a94322270d56855357 | 44,680 |
def _shellquote(s):
"""Return a shell-escaped version of the string *s*.
Args:
s (str): String to shell quote.
Returns:
str: The shell-quoted string.
"""
if not s:
return "''"
if _find_unsafe(s) is None:
return s
# use single quotes, and put single quotes... | 68e8c6dfa846a887591d6eeea55052e436429acd | 44,681 |
def cancel_order(order_id):
"""method to get and edit an order by the user"""
if request.method == "PUT":
data = request.get_json()
response = validate_parcel_data(data)
if response == "valid":
sender_name = data['sender_name']
descr = data['descr']
se... | 9d61dc7cfe4e308a642a4b13ebfb3d586112245b | 44,682 |
def determine_timestamp(item):
"""Determine the timestamp of the given item
Args:
item: [dict] Specifies an resource instance created by an API
"""
# There is no standard for this.
# The following are common to some APIs.
for key in ['creationTimestamp', 'timeCreated']:
if key in item:
return i... | e590b8e2efa9a791b96ba64d1bd73601ba34d317 | 44,683 |
def EmptyActivation():
"""EmptyActivation() object"""
return Activation(handle=_interpreter.interpreter_EmptyActivation()) | 5be18f1815c577e3efe6c624a6078114f3827698 | 44,684 |
def checkbox_to_boolean(list_checkbox_params, dict_all_params):
""" Takes a list of strings that are to be processed as checkboxes on a post parameter,
(checkboxes supply some arbitrary value in a post if they are checked, and no value at all if
they are not checked.), and a dict of parameters and their val... | fe57b02ae6593a0426364cba0c2b41f1362d2968 | 44,685 |
def distribution_data(history,mutant_id,i,all_types=False):
"""
generates neighbour data for mutants (or all cells if all_types is True)
cells are labelled by their ancestor. all cells with ancestor=mutant_id are type 1, all other cells type 0.
returns list of dicts with keys: tissueid, time, n, k, ... | 31f8b07108a6283713277f8ecf90df14c2f0e003 | 44,686 |
def likes(names):
"""Take string of names and let you know who likes 'it'."""
if len(names) == 0:
return "no one likes this"
elif len(names) == 1:
return "{} likes this".format(names[0])
elif len(names) > 3:
return "{}, {} and {} others like this".format(names[0], names[1],
... | 0d4f3d4275b2d92c503228fc6002ce0ae01acb6a | 44,687 |
def josa_en(word):
"""add josa either '은' or '는' at the end of this word"""
word = word.strip()
if not is_hangul(word): raise NotHangulException('')
last_letter = word[-1]
josa = u'은' if has_jongsung(last_letter) else u'는'
return word + josa | 6831b3bf62b8162a31712fc88d19a73632094ff0 | 44,689 |
import yaml
def get_runtime_env(yml_filename):
"""Reads input YAML filename and returns a dictionary in which each key
is a category name of runtime environment and the corresponding value
is an object that includes version information of packages listed in
that category.
"""
runtime_env = di... | b9f060605d84aeff799a3abad1601dae1f2b89b5 | 44,690 |
def matrix_power(M, n):
"""
Raise a square matrix to the (integer) power n.
Parameters
----------
M : Tensor variable
n : Python int
"""
result = 1
for i in xrange(n):
result = theano.dot(result, M)
return result | 7f998b3613160371be79a57753311a236ab7b3ff | 44,691 |
import torch
def camera_rays(camK, W=None, H=None, c2w=None, graphics_coordinate=True,
center=False):
"""shoot viewing rays from camera parameters.
Args:
camK: Tensor of shape `[3,3]`, the intrinsic matrix.
W: Integer, if set None, then `W` is calculated as `2*cx`.
H: I... | c572283305dccc243de1bd956d11b7fd2ff42726 | 44,692 |
def basic_project_data():
"""
Provide a basic collection of Sample-independent data.
:return dict[str, object]: Mapping from Project section name to
value or collection of values.
"""
return {
METADATA_KEY: {
NAME_TABLE_ATTR: "anns.csv",
OUTDIR_KEY: "outdir",... | 2988e94efe4e210ca7fe12f094077c8f72c0a61a | 44,693 |
def get_data(filename, args):
"""
@ input
filename: ex. kr00001973962b1p-4
@ output
image, coordinates, labels
"""
xmlfile = filename
jpgfile = filename.replace(".xml",".jpg")
doc = ET.parse(xmlfile)
root = doc.getroot()
object_dict = {}
for x in root.findall('... | 8f6d4488b60e559ccae579cf6baf1c9f75d3907e | 44,694 |
import re
def photos(context, group):
"""
Render one or more photos defined in the spreadsheet.
"""
photoset = [photo for photo in context['COPY']['photos'] if photo['group'] == group]
whitespace_regex = re.compile(r'\s+') # Remove whitespace for Markdown embedding
fragments = []
for row i... | 22f792ece3a44e6643a50e4465c81de9f07b6971 | 44,695 |
def sky_noise_jy_autos(lsts, freqs, autovis, omega_p, integration_time, channel_width=None, Trx=0.0):
"""Make a noise realization for a given auto-visibility level and beam.
This is a simple replacement for ``hera_sim.noise.sky_noise_jy``.
Parameters
----------
lsts : array_like
LSTs at wh... | dd00615de1a63cea9c30960f77c01082cd957f07 | 44,698 |
def shortestDist(S1, S2):
"""Returns the distance between the time series S1 and S2.
S1 and S2 have size N x ... x 3
Assumes linear interpolation between points but no assumption about the
velocity between grid points (hence the shortest distance is between segments is returned)
return array of size... | c330af8b03661523174a5a310d49a2642af2a95f | 44,699 |
from odc.io.text import parse_slice
from typing import List
def parse_all_tasks(
inputs: List[str], all_possible_tasks: List[TileIdx_txy]
) -> List[TileIdx_txy]:
"""
Select a subset of all possible tasks given user input on cli.
Every input task can be one of:
<int> -- 0 based ... | a7b428764b8d894c8c51a838864e4643bb9e77a8 | 44,700 |
import gzip
import numpy
def extract_labels(f, one_hot=False, num_classes=10):
"""Extract the labels into a 1D uint8 numpy array [index].
Args:
f: A file object that can be passed into a gzip reader.
one_hot: Does one hot encoding for the result.
num_classes: Number of classes for the one hot encoding... | 89984977f7dff0e3ccce82395295b4bd1fa0a209 | 44,702 |
def head(filename, numlines=200):
"""Route: head the contents of a file given the numlines"""
return process_file(tailer.head, filename, int(numlines)) | 549a85a8ccc663f5a48f97d4b6601b12a74cd833 | 44,703 |
def get_rpm_properties(input_file: str):
"""
Summary:
processes the structured name of the rpm file to get the
arch, release, version, and name
Parameters:
input_file (str): the file
Returns:
dictionary containing arch, release, version, and name
"""
#get prope... | 291171913e80ede385a464c525fc44e87aeaf41b | 44,704 |
def get_sig_symbol(corr_p_val, ctrl=False, percentile=False, sensitivity=None,
side=1, tails=2, p_thresh=0.05):
"""
get_sig_symbol(corr_p_val)
Return significance symbol.
Required args:
- corr_p_val (float):
corrected p-value (e.g., corrected for multiple compa... | bb7ea437252979f46ff435493a927cec8cfef1e8 | 44,705 |
def equalize_hist_rgb(rgb_img: np.ndarray) -> np.ndarray:
"""
Equalize the histogram of a RGB image.
:param rgb_img: RGB image
:return: equalized RGB image
"""
ycrcb_img = cv2.cvtColor(rgb_img, cv2.COLOR_RGB2YCrCb) # convert from RGB color-space to YCrCb
ycrcb_img[:, :, 0] = cv2.equalizeHi... | 05dbd9927beca59db290fbc6620174c4ce41ae16 | 44,706 |
def get_artists_in_genre(incl_genres, lydir: str=LYRICDIR):
"""
creates and displays a list of all artists for genres selected via incl_genres parm.
selects all genres if incl_genres is left blank or if 'all' is passed as str or list
:param incl_genres:
:param lydir: folder for lyric files
:retu... | 0f6ada98b7f639565536ffd5f57227ca38255be5 | 44,708 |
def authenticate():
"""Sends a 401 response that enables basic auth"""
return (
jsonify({"description": "Incorrect Credentials"}),
401,
{'WWW-Authenticate': 'Basic realm="Credentials Required"'}) | 6ce6133062ec68d32343da1cc9a574166235ab39 | 44,709 |
def update_batch_flow():
"""
手动置批处理节点为完成状态
"""
form = BusinessBatchFlowForm()
if form.validate_on_submit():
db_info = EnvironMapping.query.filter_by(tms_ip=form.test_env.data).first()
engine = OracleEngine('BATCH', db_info=db_info)
engine.update_business_batch_flow(form.trad... | 945d2490dfc8378f5baa3004f1e621c26952fbc3 | 44,710 |
def spherical_to_cartesian(spherical: np.ndarray) -> np.ndarray:
"""Returns the cartesian form of the spherical vector.
spherical_vector can be a numpy array where rows are spherical vectors
(or a single vector)"""
cartesian = np.empty_like(spherical, dtype=float)
cartesian[..., 0] = spheri... | 8e8703e798d5a5c32b5866ededd1d20c45d01e6a | 44,711 |
def max_flow_rule(mod, l, tmp):
"""
**Constraint Name**: TxSimple_Max_Flow_Constraint
**Enforced Over**: TX_SIMPLE_OPR_TMPS_W_MAX_CONSTRAINT
Transmitted power should not exceed the defined maximum flow in
each operational timepoint.
"""
var = mod.tx_simple_max_flow_mw[l, tmp]
if var == ... | 4448aca8c59392d2977b79dd24c3c2dd19ea823b | 44,712 |
def blink() -> str:
"""Returns 'bright/blink text' ANSI-command string."""
return _format_rich_text(TextAttributes.blink) | 6a46732d3f6d62bb40bd42f798583acfc06b236c | 44,713 |
def CachedPropertyParamRegistry(): # noqa: N802
"""Registry with cached property and a keyword parameter."""
class CachedPropertyParamRegistry:
registry = Registry('kwparam', cached_property=True)
return CachedPropertyParamRegistry | b1dcdee8012051765d5eb76bde3d0647dcc51efa | 44,714 |
def map_to_representative(state,
lp_metric,
representative_states,
n_representatives,
min_dist,
scaling,
accept_new_repr):
"""
Map state to representative s... | 168b919939b6135747d2484637a62f0a04eb8b32 | 44,715 |
def withRequest(f):
"""
Decorator to cause the request to be passed as the first argument
to the method.
If an I{xmlrpc_} method is wrapped with C{withRequest}, the
request object is passed as the first argument to that method.
For example::
@withRequest
def xmlrpc_echo(self, r... | f7fd8da601300aef722eb6706d111a54383648c0 | 44,716 |
def get_functional_enrichment(enrichment_file, go, remove_parents=False, only_biological_processes=False, only_slim=False, logodds_cutoff=0):
"""
Read functional enrichment file.
If there are multiple functional enrichment analyses it takes the comment as the key and returns
a dictionary con... | 3d47831a946d73050032ee11f518f1f401fb8a99 | 44,717 |
def analysis_line_linearity(target_list, measure_list_mm, boundary_index_list, linearity_list):
"""
analysis line boundary/center linearity
"""
boundary_max_linearity = [0, [0, 0]]
center_max_linearity = [0, [0, 0]]
for i in range(len(linearity_list)):
for j in range(len(linearity_list... | ecaf54467529b8d36f2af25c65c557520bf59711 | 44,718 |
def has_pipeline(model):
"""
Tells if a model contains a pipeline.
"""
return any(map(lambda x: isinstance(x[1], Pipeline),
enumerate_model_names(model))) | d7d559035548f2feb8302ed1a17da74029135be6 | 44,719 |
def add_permission(lambda_client, function_name, statement_id, action, principal, source_arn, source_account=None):
"""https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lambda.html#Lambda.Client.add_permission"""
kwargs = {
"FunctionName": function_name,
"StatementId": ... | 964fefb61c1e304bd80e446b662f6f23c85d2361 | 44,720 |
def dither_spikes(spiketrain, dither, n_surrogates=1, decimals=None,
edges=True, refractory_period=None):
"""
Generates surrogates of a spike train by spike dithering.
The surrogates are obtained by uniformly dithering times around the
original position. The dithering is performed ind... | 51bc68e7b3034b20eac474edf9e5b172d005a39d | 44,721 |
def dist():
"""Calculate advantage/disadvantage probability distributions."""
pa = np.zeros(20)
pd = np.zeros(20)
for k in range(20):
for i in range(20):
for j in range(20):
if max(i, j) >= k:
pa[k] += 1.0
if min(i, j) >= k:
... | d3d611a8457341e959c831a653acb00e44495471 | 44,722 |
def modelconfigurationsetups_id_delete(id, user=None): # noqa: E501
"""Delete an existing ModelConfigurationSetup
Delete an existing ModelConfigurationSetup (more information in https://w3id.org/okn/o/sdm#ModelConfigurationSetup) # noqa: E501
:param id: The ID of the ModelConfigurationSetup to be retriev... | adad372562d30d561027722f9ad7e8b15a40960c | 44,723 |
def parse_sacct(sacct_stream):
"""Parse out information from sacct status output."""
rows = (line.split() for line in sacct_stream)
# filter rows that begin with a SLURM job id
relevant_rows = (row for row in rows if row[0].isdigit())
jobs = [convert_job(row) for row in relevant_rows]
return job... | 4c549d56fd67b6d12ad5262780bd7a5744d9b7a2 | 44,724 |
def create(profile, name, subnets, tags=None):
"""Create a DB subnet group.
Args:
profile
A profile to connect to AWS with.
name
The name you want to give to the group.
subnets
A list of subnet IDs to put in the group.
tags
A l... | b02ce4e748387ced2e6fda87732a226eb8bbfc51 | 44,725 |
def format_output(template_string):
"""
Formats the value according to template_string using django's Template.
Example::
@allow_tags
@format_output('{{ value|urlize }}')
def object_url(self, obj):
return obj.url
"""
tpl = Template(template_string)
def dec... | 51f4d697f63737c2d0253562da68df0ab2d110df | 44,726 |
import torch
def calc_init_centroid(images, num_spixels_width, num_spixels_height):
"""
calculate initial superpixels
Args:
images: torch.Tensor
A Tensor of shape (B, C, H, W)
num_spixels_width: int
A number of superpixels in each column
num_spixels_height:... | cfa87a57d4cb6b194da4ae6316433adefb8cfbe1 | 44,727 |
import unicodedata
def slugify_camel_iso(old_string: str) -> str:
"""Slugify a string with camel case, underscores and ISO date/time formats.
>>> slugify_camel_iso("some name Here 2017_12_30")
'Some_Name_Here_2017-12-30'
>>> slugify_camel_iso("DONT_PAY_this-bill-10-05-2015")
'Dont_Pay_This_Bill_2... | 61c016606b83483ac25b407d53e6fd82fb1344dd | 44,728 |
import torch
def showSegModelInference(model, img_path, display=True):
"""
@func img_path -> 3 np arrays of results
label assign refer
https://github.com/mcordts/cityscapesScripts/blob/master/cityscapesscripts/helpers/labels.py
"""
img = Image.open(img_path)
img_p = np.array(img)
img_... | 10fee68c5aa58bb35c1b924cb7922c9809e39cc8 | 44,729 |
from typing import Union
from pathlib import Path
import yaml
def load_yaml(path: Union[str, Path], pure: bool = False) -> dict:
"""config.yaml file loader.
This function converts the config.yaml file to `dict` object.
Args:
path: .yaml configuration filepath
pure: If True, just load the .... | a0ed543d6f8c4372a51c8da25154fbe17eef64bb | 44,730 |
from datetime import date
def get_current_year():
"""
return: the current year.
"""
return date.today().isocalendar()[0] | 0ba2fd73f596fd40c290dcda5b18bdcc1afa5c62 | 44,731 |
def seed(request):
"""
Sets the seed for in numpy.random.
Return the seed value, so it can be used by plots as part of the
label.
"""
seed = request.param
np.random.seed(seed)
return seed | 9322cb00268f010f43c772fbb15a8b2d3ec8aef0 | 44,732 |
def denoise_timeseries(timeseries_data, fsampling, fmin=2, fmax=45):
"""Filters timeseries_data with a band pass filter designed with cutoff frequencies [fmin, fmax]
Args:
timeseries_data (dict): [N x t time series data, with N brain regions for source localized data or
... | 823a2da076b1ed10c8db0bf0ea1ae64006cdf2d7 | 44,734 |
from typing import List
def get_def_port(ports: List[int], default: int) -> int:
"""Returns default or first unused in system and in run configs port."""
port = default
if len(ports) > 0:
ports.sort()
port = ports[-1] + 1
while is_open_port(port):
port += 1
return port | 10ddb81bba45147bbac0cc8589f768f3cad87e2f | 44,735 |
def _prepare_lookup(keywords_file=None, stopwords_file=None, ngram_size=None, lemmatize=False,
stemmer=None):
# pylint: disable=too-many-arguments
"""Prepare resources for keywords lookup.
:param keywords_file: keywords file to be used
:param stopwords_file: stopwords file to be use... | 35bcc430571243a6cde197cee581ec2533ead400 | 44,736 |
def statistics(r, b=None, rf=None, freq=12):
"""
Generate the portfolio return matrix from the monthly P&L including the following:
Total return:
Annual Return:
Volatility
Sharpe Ratio
Percentage Positive Month/Day
MDD
Skewness
Kurtosis
If b is... | dbd9d8cceee1cd99198b0e4ae1d5e7aee5d98d6f | 44,737 |
import torch
def weightedDLTmatrix(Ps,weight):
"""
Input: Ps = [1,1,N,5 (X,Y,Z,x,y) ], Weights = [1,N]
P_world-3Dpoint (N,[X,Y,Z]) p_img-2Dpoint (N,[x,y]) Weight (N,)
OutpuT: weighted DLT matrix A^T*W*A
"""
# DLT matrix
N = Ps.shape[2]
A = torch.zeros([2*N,12])
W = ... | b71e546d459ee1bb57f68278edef852c466cd4e6 | 44,738 |
def game(request, event_id):
"""Game view.
If the request type is POST and the user is logged in, save the user score
and redirect the user to the profile page. Otherwise, display the game.
Arguments:
request - Django object containing request information.
event_id - ID of event to use.
R... | 8eef02a88a12e9c61f721eb698195b8bb9493b7a | 44,741 |
def hello():
"""Return a friendly HTTP greeting."""
return 'Deep Neural Network (DNN) heart failure prediction' | 7f30a185fccbabe9d1f06fbff34e51492239a2f9 | 44,742 |
def generate_shard_prune_playbook(migration):
"""Create a playbook for deleting unused files.
:returns: List of nodes that have files to remove
"""
full_plan = {plan.db_name: plan for plan in migration.shard_plan}
_, deletable_files_by_node = get_node_files(migration.source_couch_config, full_plan)
... | 24585de78337884c2ae19651f8b86cdf795c4676 | 44,743 |
import json
import csv
def num_of_rows(infile):
""" Compute the number of rows.
Args:
file: Infile file.
Returns:
The number of rows.
"""
numrows = 0
if metadata['format'] == JSON:
with open(infile, 'r') as fp:
numrows = len(json.load(fp)) # Use len() func... | dd7842e4273492e7a3d09e8b71b0a04523e8f259 | 44,745 |
import random
def uoc_hill_genkey(size):
"""
Hill Key Generation
:size: matrix size
:return: size x size matrix containing the key
"""
matrix = []
L = []
# Relleno una lista con tantos valores aleatorios como elementos a rellenar en la matriz determinada por size (size * size)
... | fe71dd71646ce229b7e690cacd7b747e5e536293 | 44,746 |
def study_demo(request):
"""
Redirect to a list to study (the first public one).
"""
lis = TranslationsList.objects.filter(public = True).order_by('pk')
if not lis:
return notification(request, 'There is no public list to study, sorry...')
return redirect(reverse('study_list_ask', kwargs = {'pk': lis[0].pk, 's... | 90efbf9face70ef1de6511be841d310ebfc5516c | 44,747 |
import socket
def api_config():
"""Build api endpoint for config data."""
read_config(config_file, srv_config)
resp = make_response(jsonify(srv_config))
resp.headers['Server-IP'] = socket.gethostbyname(localhost)
return resp | 254c8ce2820e3b9aef952b8ee48b0bd7b0aaed9f | 44,748 |
import re
import logging
def is_youtube_video(link):
"""Identify youtube video's."""
content = urllib2.unquote(link).decode('utf8')
# shortened YT url
result = re.search('http://youtu.be', content, flags=re.IGNORECASE)
if result is None:
result = re.search('www.youtube.com', content, flags... | 7f34d14929d366f318b4a750c9321a979ac08547 | 44,749 |
from typing import Union
from typing import Dict
from typing import Any
import typing
def ColorPicker(
concise: bool = False,
description: str = "",
description_tooltip: str = None,
disabled: bool = False,
layout: Union[Dict[str, Any], Element[ipywidgets.widgets.widget_layout.Layout]] = {},
st... | 6e4d3b63985aa1557a2e42927593ab2b282f5657 | 44,750 |
def sample_parameters_binary(boundaries):
"""
sample parameter values from the boundary conditions for binary encoding
Parameters
----------
'boundaries' (pandas df): boundary conditions for model parameters'ncpu' (int): number of cpu's to be used for computation, -1 is all cpu available o... | cf695fa985e0c4519ed191d4ffd45d551ae3c598 | 44,751 |
def deepmerge(a, b):
"""
Merge dict structures and return the result.
>>> a = {'first': {'all_rows': {'pass': 'dog', 'number': '1'}}}
>>> b = {'first': {'all_rows': {'fail': 'cat', 'number': '5'}}}
>>> import pprint; pprint.pprint(deepmerge(a, b))
{'first': {'all_rows': {'fail': 'cat', 'number'... | 5d6f27d6bff8643e37398b4c3c31a0340585b88d | 44,752 |
def _element_to_string(element):
"""Get a string that can be used to recognize the element.
If the element has an id, use it as it will uniquely identify the element.
Otherwise, fall back to the text. If it has no text, to the value.
Fallback to outerHTML as a last resort.
"""
element_id = ele... | ead981fe505cab8836dac19bdd2ff7c79d36e1bc | 44,753 |
import logging
def on_session_ended(session_ended_request, session):
""" Called when the user ends the session.
Is not called when the skill returns should_end_session=true
"""
logging.info("on_session_ended requestId=" + session_ended_request['requestId'] +
", sessionId=" + session['s... | 95e057baa90728881ca6cf0622bc652b05da4c77 | 44,756 |
def clean_data(text):
"""Fixes broken symbols in poems.
:param text: Broken text that has to be fixed
:return: Text with correct UTF8 symbols"""
corrections = {
'ó': 'ó',
'ż': 'ż',
'Ä™': 'ę',
'Å‚': 'ł',
'Å›': 'ś',
'ć': 'ć',
'Ä…': 'ą',
'... | ec847f50bc074f8f9ff081c55afccf3311037cd0 | 44,757 |
from django.db.models import Model
def model_instance_diff(old, new, serializer_mapping=None):
"""
Calculate the differences between two model instances. One of the instances may be None (i.e., a newly
created model or deleted model). This will cause all fields with a value to have changed (from None).
... | 2c2e79abed39ceebfb7c4b1b1d19fa71957704f3 | 44,758 |
import pandas
def _dataframe_reduce_columns_codegen_head(func_name, func_params, series_params, df):
"""
Example func_text for func_name='head' columns=('float', 'string'):
def _df_head_impl(df, n=5):
data_0 = df._data[0][0]
series_0 = pandas.Series(data_0)
result_0 = ser... | 72a2cef21cfa593992f4cce21ca2af6a400b9ff7 | 44,759 |
def translate_rev_to_sha(llvm_config: LLVMConfig, rev: Rev) -> str:
"""Translates a Rev to a SHA.
Raises a ValueError if the given Rev doesn't exist in the given config.
"""
branch, number = rev
if branch == 'master':
if number < base_llvm_revision:
return translate_prebase_rev_to_sha(llvm_config,... | 147825802c531ba49c10a4e3fde1dfaccfffcad5 | 44,760 |
def get_env_config_path():
"""return ocio config path from the environment
"""
blender_config_path = envconfig().get_blender_ocio_config()
ociopath = envconfig().getenv('OCIO', blender_config_path)
return ociopath | c4ddfdb8e0358d4b98e708a271d8413b508b4f9d | 44,761 |
import uuid
def uuid4():
"""
Generates uuid4's exactly like Python's uuid.uuid4() function.
When ``fix_random_seed()`` is called, it will instead generate deterministic IDs.
"""
if _lhotse_uuid is not None:
return _lhotse_uuid()
return uuid.uuid4() | 3a102c945d2d315bc9c3fb68d3cdaeb932769929 | 44,762 |
import logging
from pathlib import Path
import csv
def generate_DDs(experiment_dir, asdp_dir, track_fpaths, dd_config):
""" Create and save a diversity descriptor for a HELM experiment
Parameters
----------
experiment_dir: str
Path to experiment directory
asdp_dir: str
Path to ASD... | a57af9e8cd2cb442c4cc432ed602bccc390cef6e | 44,763 |
def prominent_points_new(x,y, features=["min","max","turnL","turnR","edgeL","edgeR","samples"], d2Lim=0, d3Lim=0, d4Lim=0):
"""
generate an ordered list of dict with prominent points entries
each entry carries several infos
{
type:min,max, ...
index: the index
... | 11517c30f1e4b82eeddef0970fdbc80d06dbe348 | 44,764 |
def avatar_url(user, size=50, gravatar_only=False):
"""
A template tag that receives a user and size and return
the appropriate avatar url for that user.
Example usage: {% avatar_url request.user 50 %}
"""
if (
not gravatar_only
and hasattr(user, "wagtail_userprofile")
a... | f90d7f070f540f8ff13aa7217d4ef6648b055958 | 44,765 |
def patch_location(r2, finfo, bb, from_addr, targets):
"""Generates patches for the basic block. Starts at the end and goes back
as many bytes as needed.
Returns patches as [(address, patch_bytes, r2 patch argument, r2 patch cmd"""
dbg = False
if dbg:
print('patch_location(_, {}, {:x}, {}'.f... | aedfa2d3f036ba632275cda2702c1e2272df7cb0 | 44,766 |
def smart_quote(url):
"""
Like urllib.parse.quote, but quote non-ascii words only.
Example ::
smart_quote("http://whouz.com") # http://whouz.com
smart_quote("喵.com") # %E5%96%B5.com
"""
l = [s if s in UNQUOTE else quote(s) for s in url]
return ''.join(l) | cb56fe02cb68c1d626df12763b2773c00c0cdaac | 44,767 |
from typing import Type
def get_pydantic_field(field_name: str, model: Type["Model"]) -> "ModelField":
"""
Extracts field type and if it's required from Model model_fields by passed
field_name. Returns a pydantic field with type of field_name field type.
:param field_name: field name to fetch from Mo... | deec984a9e5d89687bee77bd3733dc4261a403bc | 44,770 |
def spin_down_rate(tq, R, M, period, dt):
"""
Calculate the new rotation period given a torque and a timestep.
the rate of increasing rotation period for a given torque.
torque = dL/dt
dL = torque * dt
dt: timestep (seconds)
"""
dL = tq * dt
Omega = 2*np.pi/period
I = R**2 * M
... | cd0e0eb2d10f1bb8f3fd3940df1da05c5cfb8fbd | 44,771 |
from typing import Iterable
from typing import Dict
from typing import Any
import collections
from typing import List
import torch
def average_checkpoints(inputs: Iterable[str]) -> Dict[str, Any]:
"""Loads checkpoints from inputs and returns a model with averaged weights.
Args:
inputs: An iterable of s... | c58f4479fd10119fd28326c654ce0fce534c910c | 44,772 |
def pdf_pipeline(file: UploadFile = File(None)):
""" Parses the file and returns various analytics about the pdf
Parameters
----------
file: File
A File stream
Returns
-------
JSON
Returns a JSON where the key can be a section in the document with value as the text of the d... | 3ed9453a3bb18d489d9b01f3ccc720006c4f6ad4 | 44,774 |
def makepath_hybrid(model,T,h,ode_method,sample_rate):
""" Compute paths of model. """
voxel = 0.
path = np.zeros((Nt,len(model.systemState)))
path[0][:] = model.getstate(0)
clock = np.zeros(Nt)
for e in model.events:
e.sethybridtype()
e.updaterate()
# for hybrid paths use c... | f2f29f9a0d957d092cf8b471070416c9c6d4463d | 44,775 |
import ast
def eval_literal_value(value: str) -> ty.Any:
"""Evaluate a string to a literal value
:param value: Value to evaluate
:type value: str
:return: Literal value the string is evaluated to
:rtype: ty.Any
"""
try:
return ast.literal_eval(value)
except (SyntaxError, Value... | f5060d709587cfbd17804c7fee39ae62e4c88ec5 | 44,776 |
def _load_off_stream(file) -> dict:
"""
Load the data from a stream of an .off file.
Example .off file format:
off
8 6 1927 { number of vertices, faces, and (not used) edges }
# comment { comments with # sign }
0 0 0 { start of vertex... | 302b51377a0fb396e9a9cb08a80aa9eed56ccfc8 | 44,777 |
def get_distinct_attr() -> (WORD, WORD, WORD, WORD):
"""Returns a tuple with 4 values: foreground color, foreground intensity,
background color, and background intensity"""
attr = get_text_attr()
return (
attr & FOREGROUND_GREY,
attr & FOREGROUND_INTENSITY,
attr & BACKGROUND_GREY... | b5172d5b1e12f9d8bfa602514459a68bd6b005a7 | 44,778 |
def _full_simulation(exp, y0, pulse_sim_desc, pulse_de_model, solver_options=None):
"""
Set up full simulation, i.e. combining different (ideally modular) computational
resources into one function.
"""
solver_options = PulseSimOptions() if solver_options is None else solver_options
psi, ode_t ... | 0ec3fce6b3e0522697dadbaa634e3c81f82303b8 | 44,779 |
from typing import Dict
def get_headers(token_scope: str = TIMER_SERVICE_SCOPE) -> Dict[str, str]:
"""
Assemble any needed headers that should go in all requests to the timer API, such
as the access token.
"""
token = get_access_token_for_scope(token_scope)
if not token:
raise ValueErr... | 76e547ced14f1f37a7dc6287132e42db6cd9a3a4 | 44,780 |
import string
def unrank(n, sequence=string.ascii_lowercase):
"""Unrank n from sequence in colexicographical order.
>>> [''.join(unrank(i)) for i in range(8)]
['', 'a', 'b', 'ab', 'c', 'ac', 'bc', 'abc']
>>> unrank(299009)
['a', 'm', 'p', 's']
"""
return list(map(sequence.__getitem__, in... | 6deca92730cb7147d8e857fec4f8575580bb3142 | 44,781 |
import pkgutil
import json
def waste_schema():
"""Provides schema validation to tests"""
schema_file_contents = pkgutil.get_data("atomic6ghg.schemas", "waste.json")
schema = json.loads(schema_file_contents)
v = Draft7Validator(schema=schema)
return v | 211eda76983c6e4e51c5f6bd1cbf40efb284ea0f | 44,782 |
def min_threshold_dist_from_shapefile(shapefile, radius=None, p=2):
"""
Kernel weights with adaptive bandwidths.
Parameters
----------
shapefile : string
shapefile name with shp suffix.
radius : float
If supplied arc_distances will be calculated
... | 700322eb1e4bc11fefd56e571c7123fc1b5dadbf | 44,783 |
def datetimetodatetime64(t):
"""
Convert a vector of datetime64 to datetime objects
"""
#return np.array([np.datetime64(tt) for tt in t]).astype('datetime64[us]')
return np.array([np.datetime64(tt) for tt in t]).astype('<M8[ns]') | d201df8bfbed9cb61b7e2093c42fe00b39123031 | 44,784 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.