content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import importlib
def get_func(path):
"""
Возвращает объект функции по ее пути. Например 'onesocial_django.utils.default_validate'.
"""
module_name, func_name = path.rsplit('.', maxsplit=1)
module = importlib.import_module(module_name)
func = getattr(module, func_name)
return func | c10b26e98b422f0b0239c055456af5ae13159999 | 666,886 |
def _eff_2_nom(effective_rate, piy):
"""Convert an effective rate to a nominal rate.
:effective_rate: effective rate to be changed
:piy: number of periods in a year for the effective rate
"""
return effective_rate * piy | 06663b1a49934e308bd44efe6055d416dcb4d59e | 666,887 |
def is_fasta_label(x):
"""Checks if x looks like a FASTA label line."""
return x.startswith(">") | 43f45397dfb10d67d2bc8517ab07c2fb09067f06 | 666,888 |
def _truncate_ids(unit_ids):
"""Drop the last character of each unit ID and return the result as a set.
pulp-admin hard-wraps search results. This can result in wonky output::
Metadata:
Digest: sha256:3e2261c673a3e5284252cf182c5706154471e6548e1b0eb9082c4c
c
An incorrec... | 24e499c3d106a865305c4a242e107af2ccc97210 | 666,889 |
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
J = set(J)
i = 0
for items in S:
if items in J:
i = i + 1
return i | d7ab3ac6fffbec9345f622acde9eb8bbc773090e | 666,890 |
def keep_firstn(lst, n):
"""Keep only the first n elems in a list."""
if len(lst) <= n:
return lst
else:
return lst[:n] | 02035b28223d07857173b337fa142816e0a4bb17 | 666,891 |
import torch
def combine_obj_pixels(obj_pix, obj_dim):
"""Combine obj-split pixels into a single image.
Args:
obj_pix: B, ..., Nobj, ..., C, H, W
obj_dim: The dimension to reduce over -- which corresponds to objs
Returns
B, ..., ..., C, H, W
"""
if obj_pix is None:
... | c0a47d2cf11609b7a905de9d88eb048cabb30216 | 666,892 |
def _svg_convert_size(size):
"""
Convert svg size to the px version
:param size: String with the size
"""
# https://www.w3.org/TR/SVG/coords.html#Units
conversion_table = {
"pt": 1.25,
"pc": 15,
"mm": 3.543307,
"cm": 35.43307,
"in": 90
}
if len(si... | 6c3a1e70c4bc2b342bf6f09e6e9f9f5a6b890d30 | 666,893 |
import argparse
def parse_args():
"""Parses arguments from command-line."""
parser = argparse.ArgumentParser()
parser.add_argument('--raw', help='Whether to use Raw Zucchini.',
action='store_true')
parser.add_argument('old_file', help='Old file to generate/apply patch.')
parser.add_arg... | 644e21fedc1269b4d9bbbd6e322d4c73a7708eb9 | 666,894 |
def show_img_data(path: str) -> bytes:
"""Read image.
Args:
path (str): path to the file
Returns:
bytes:
"""
file = open(path, "rb")
image = file.read()
return image | 6e2c16674874e38c59d152226a2e8b1acc749991 | 666,895 |
def calculate_confidence(freqent_itemset,next_itemset,support_data,min_confidence,rule_list):
"""
Arguments:
frequent_itemsets: a list of frequent_itemset
next_itemset : a list of next iteration
support_data: a list of itemsets support data
min_confidence: a minimum confidence th... | 8844c71d902615ce067236c2a1e4b987a85a4bb8 | 666,896 |
def dna2vec(dna):
"""
converts the digits to the dna alphabet and returns dna string
"""
str = []
for i in range(len(dna)):
if dna[i] == 'A':
str.append(0)
elif dna[i] == 'C':
str.append(1)
elif dna[i] == 'G':
str.append(2)
else:
... | e796569e4a3c8d1293b43cdc9c7687379a54b11b | 666,897 |
def phase1(l, sum):
"""
instead of jumping from start to end, since this is an ordered list
we place a pointer to the beginning of the list and another one to the end
then, if the sum of both numbers is higher than "sum" we decrease the higher index by one
if the sum is lower than "sum" we increase ... | 71aa12ba37dd323e4745f45d4704771916959cdf | 666,898 |
import re
def parse_ticket_links(raw_links):
# type: (str) -> list
"""
Parses the link IDs from the ticket link response
An example to an expected 'raw_links' is:
"RT/4.4.4 200 Ok
id: ticket/68315/links
Members: some-url.com/ticket/65461,
some-url.com/ticket/65462,
... | 4e5fe0bb6a6521f341cfd7556280373884af47af | 666,899 |
def _isolate_results(soup):
"""
Scrape directions header, route summary, and route details"
"""
summary = soup.find(lambda tag: tag.name == "table" and
"TripPlanDetailsTable" in tag.attrs.get("class",
set()))
de... | c220cc8b747c87460b6874aadb052bc845f498ed | 666,900 |
def default_list_sample_mode():
""" By default we do not sample from lists backed types """
return False | b50d45860c1c98665c646631f847bad8e5679830 | 666,902 |
def calculate_dbot_score(score: int) -> int:
"""Transforms cyber risk score (reputation) from SOCRadar API to DBot Score and using threshold.
Args:
score: Cyber risk score (reputation) from SOCRadar API
Returns:
Score representation in DBot
"""
return_score = 0
# Malicious
... | 3bea0dee5376dc72e7303d652a4ffb1eba70386e | 666,903 |
def handle_no_result_exception(error):
"""Return a custom not found error message and status code"""
return {'message': error.message}, error.status_code | 19f9a9eb921d555bd0aaab02bc37b93d7fc25ae5 | 666,904 |
import random
def getRandomWaitTimeMillis():
"""
Generate a random wait time between member refresh operations.
"""
return random.randint(20000, 60000) | b542b0cb71143c3dcc9534ec5ed05b46f05b569b | 666,905 |
import os
def get_default_result_path():
"""
"""
path = os.path.join(os.getcwd(), 'result')
if not os.path.exists(path):
os.mkdir(path)
return path | 6f44036072425f542bbd857a4cf1922d5183b789 | 666,907 |
def tolerance_tests_to_report(test_list_instance):
"""return tolerance tests to be reported for this test_list_instance"""
return test_list_instance.tolerance_tests() | 1398add29a3c09702b4f581878c03895124cc871 | 666,908 |
def parse_like_term(term):
"""
Parse search term into (operation, term) tuple. Recognizes operators
in the beginning of the search term.
* = case insensitive (can precede other operators)
^ = starts with
= = exact
:param term:
Search term
"""
cas... | 9980d54125f1e11930526700951772fdfcddc44d | 666,909 |
from typing import Optional
from typing import List
import subprocess
def _get_output_of_command(command: str) -> Optional[List[str]]:
"""
Runs a command and returns its output.
:param str command: The command to run.
:return: The output or None
:rtype: :py:class:`str`
"""
try:
re... | e5ae7f7685400beb17c9135584e80467c247856a | 666,910 |
def func(num):
"""定义内部函数并返回"""
def firstInnerFunc():
return "这是第一个内部函数"
def secondInnerFunc():
return "这是第二个内部函数"
if num == 1:
return firstInnerFunc
else:
return secondInnerFunc | c293bf18f978f31cb30a3e462f6ae0c6bd80248f | 666,911 |
import re
def _get_first_sentence(s):
"""
Get the first sentence from a string and remove any carriage
returns.
"""
x = re.match(".*?\S\.\s", s)
if x is not None:
s = x.group(0)
return s.replace('\n', ' ') | d95d52e003e9b9560d1a8b9d0b081bb2fcbc1e7f | 666,912 |
def get_binding_data_vars(ds, coord, as_names=False):
"""Get the data_vars that have this coordinate
Parameters
----------
ds: xarray.Dataset
coord_name: str
Return
------
list
List of data_var names
"""
if not isinstance(coord, str):
coord = coord.name
out ... | 8d6a7aef3af0b01028b315efa4995eae31c46e0a | 666,913 |
import json
def db2vg(meta_file):
"""transfer corrupted-not-removed db indices (108077) to vg indexes"""
dbidx2vgidx = {}
image_meta = json.load(open(meta_file))
for i, item in enumerate(image_meta):
dbidx2vgidx[i] = item['image_id']
vgidx2dbidx = {dbidx2vgidx[i]: i for i in dbidx2vgidx}
... | eca384f3e7a20531a3bb302ea8846119394816f3 | 666,914 |
import calendar
def leap_years_between(year1: int, year2: int) -> int:
""" determine how many leap years there will be between the years year1 and year2 inclusive
>>> leap_years_between(2018,2020)
1
>>> leap_years_between(2017,2022)
1
>>> leap_years_between(2000,2020)
6
"""
retur... | a608e8013b0d534e5490b1681e0549ece76505f0 | 666,916 |
import asyncio
async def async_wrapper(functions, *args):
"""Gather async functions."""
return await asyncio.gather(*[a(*args) for a in functions]) | f61eed4666333a6b5775d24e8e6946be914a984e | 666,917 |
import sys
def safe_unicode(s):
"""Encodes and decodes string based on user's STDOUT.
Encodes string to ``utf-8`` and then decodes it based
on the user's STDOUT's encoding, replacing erros in the process.
Args:
s (:obj:`str`): a string.
Returns:
:obj:`str`
"""
return s.... | 722d3e4f4042ef817ca3a6309aa95215ef6a42a5 | 666,918 |
def demande_nombre(question, minimum, maximum):
"""Pose un question jusqu'à ce que le joueur réponde par un nombre entier dans la fourchette
La fourchette est [minimum, maximum), c'est à dire que la borne inférieure
fait partie de la fourchette, mais pas la borne supérieure."""
# Une boucle infinie don... | 6e2c1e478fde3685a0a967db5048effb00da7fb8 | 666,919 |
def __getdelta ( transfers ,
z,
omegabh2 ,
omegach2 ,
omeganuh2 ,
H0 ):
"""
"""
h = H0/100.
Omegab = omegabh2 / h / h
Omegac = omegach2 / h / h
Omegan = omeganuh2 / h / h
rhob = Omegab* (1. + z )**3.0
rhocdm = Omegac* (1. + z)**3.0
rhonm = Omegan * (1. + z) **3.0
return 0 | 9bad3cf17eb502d5e4f7f48fdd8a8edf45c9fe39 | 666,920 |
def clamp(x, _min, _max):
"""Clamp a value between a minimum and a maximum"""
return min(_max, max(_min, x)) | fe9979a329cb130ebc9ecb7b812882770c962652 | 666,921 |
def cytoscape_element_from_client(client):
"""Generates a cytoscape element from a Client proto.
Args:
client: A Client proto.
Returns:
A cytoscape element dictionary with values derived from the proto.
"""
client_element = {
"data": {
"id": client.name,
... | 871c48223abb08f10108d59167f110d8ae9a3183 | 666,922 |
def get_location_string(location):
"""
Get coordinates as a string compatible with the Ruter API
"""
if location:
return f"(x={location[0]},y={location[1]})"
else:
return None | 12f0cb39c8c59d6329b661dc51672864316dadba | 666,923 |
import os
def find_files(suffix, path):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
Args:
suff... | b2bb86af2472c3cd9a9c61fc65dde1698ce4a227 | 666,924 |
def kv_parser(inp):
"""
Converts a url-encoded string to a dictionary object.
"""
return {obj[0]:obj[1]
for obj in (obj.split('=') for obj in inp.split('&'))
if len(obj) == 2} | 49ea6721c31e5db0367a3e822b4309fd91f459c1 | 666,925 |
def postorder_optimised(preorder: list, length: int) -> list:
"""
Use a static index pre_index to iterate over the list items one by one
when the loop returns, store the root item in list.
Time Complexity: O(n)
Space Complexity: O(n)
"""
min_val, max_val, pre_index = -1000_000, 1000_000, 0
... | f729fc2f4b0aa3816841850426a74581c8ca6b8c | 666,926 |
def PM_ds_initialized_3d(PM_ds_initialized_3d_full):
"""MPI Perfect-model-framework initialized maps xr.Dataset of subselected North
Atlantic."""
return PM_ds_initialized_3d_full.sel(x=slice(120, 130), y=slice(50, 60)) | 3cba0a2198592bfd3346e51e996442865cea1a92 | 666,927 |
import string
import random
def rndstr(size=16):
"""
Returns a string of random ascii characters or digits
:param size: The length of the string
:return: string
"""
_basech = string.ascii_letters + string.digits
return "".join([random.choice(_basech) for _ in range(size)]) | af168eeaa354d7acf2443774d5764f00cffeb780 | 666,929 |
import re
def clean_html(raw_html):
"""
Utility function for replace HTML tags from string.
"""
ltgt = re.compile('<.*?>')
whitespace = re.compile('\s+')
clean_text = whitespace.sub(" ", ltgt.sub("", raw_html)).replace("\n", " ")
return clean_text | ed3dca2eacd3adca321ab7480a72540cdd546e57 | 666,930 |
import json
def load_json(file_name_template, record_id):
"""Helper function to return JSON data saved to an external file.
file_name_template -- Template for building file name. Expected to contain a
string substitution element whose value is specified by the record_id parameter.
e.g. 'json/s... | 8feddf064343dee51dd9f952c77a32d9d904c2b3 | 666,931 |
def score(value, mu, musquared):
"""
Helper function for use in assigning negative prizes (when mu > 0)
"""
if mu <= 0:
raise ValueError('User variable mu is not greater than zero.')
if value == 1:
return 0
else:
newvalue = -float(value) #-math.log(float(value),2)
... | 9408df5b3120d5f34ee8ffb46931bf6fbab84686 | 666,932 |
import requests
def get_tag_list_from_docker_hub(repo, **kwargs):
"""Retrieves the list of tags from a docker repository on Docker Hub."""
docker_token_url = "https://auth.docker.io/token"
docker_token_url += "?service=registry.docker.io&scope=repository:{}:pull"
def get_token_from_docker_hub(repo, *... | 3a5b6baef1bc5452de6a0bdc352fa3ce282db7c1 | 666,933 |
def groupfinder(userid, request):
"""Fetch principals from permission backend for the specified `userid`.
This is plugged by default using the ``multiauth.groupfinder`` setting.
"""
backend = getattr(request.registry, 'permission', None)
# Permission backend not configured. Ignore.
if not backe... | 8e1d2344e2307359e988e8a77b5fa421759376eb | 666,934 |
from typing import List
from typing import Tuple
def filter_multiple_pronunications(
lexicon: List[Tuple[str, List[str]]]
) -> List[Tuple[str, List[str]]]:
"""Remove multiple pronunciations of words from a lexicon.
If a word has more than one pronunciation in the lexicon, only
the first one is kept, ... | faa106c3b16e7efbcd49471714260cb734f72385 | 666,935 |
import re
def replace_code_command(filestr):
"""Replace \code{...} by \Verb!...! or \textttt{...}."""
# Remove one newline (two implies far too long inline verbatim)
pattern = re.compile(r'\\code\{([^\n}]*?)\n(.*?)\}', re.DOTALL)
# (this pattern does not handle \code{...} with internal } AND \n!)
... | a4cd8301399d6e2c9628437bf896e5e068fa6606 | 666,936 |
import copy
def get_category_obj(data, category_name):
"""Extract obj with `name` == `category_name` from `data`."""
cats = copy.copy(data)
while(cats):
cat = cats.pop()
if cat['name'] == category_name:
return cat
if 'children' in cat:
cats.extend(cat['child... | 82782dba9ae9374abc5e3f510ba53f9e03e14a62 | 666,937 |
def _get_attr_args_and_kwargs_from_ax_call_item(ax_call_item):
"""
:param ax_call_item:
:return:
"""
if isinstance(ax_call_item, dict):
attr = ax_call_item['attr']
args = ax_call_item.pop('args', ())
kwargs = ax_call_item.pop('kwargs', {})
else:
attr = ax_call_it... | 37663eea5d3312f8d34c8a7fc1571c3aa7e41528 | 666,938 |
def _dedup_dim_dicts(dim_dicts):
""" Internal helper function to take a list of dimension dictionaries
and remove the dupes. What remains should be one dictionary per rank
(for this dimension of the process grid).
"""
# Workaround to make the dictionary's contents hashable.
for d in dim_dicts:
... | 002eb892c2400424f7d0d2d52a0d063eda38cd12 | 666,939 |
def is_valid_time_response(response):
"""
Returns true if a time response is valid.
str -> bool
"""
try:
return float(response) >= 0
except ValueError:
return False | b7afa38374db609b5c86e3892e83570a11c69cdd | 666,940 |
import re
def _sanitize_name(name: str) -> str:
"""Sanitizes name to comply with IR naming convention.
The sanitized name contains only lower case alphanumeric characters and
dashes.
"""
return re.sub('-+', '-', re.sub('[^-0-9a-z]+', '-',
name.lower())).lstrip('-').rstrip(... | a245350bfdf5422c8caf88f7484f2a2fbb65a90b | 666,941 |
def get_distance(p1, p2):
"""Distance entre les points p1 et p2, dans le plan horizontal,
sans prendre en compte le y qui est la verticale.
"""
if p1 and p2:
if None not in p1 and None not in p2:
d = ((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)**0.5
return int(d)
return... | f5420d7e362e238729943a6e4dbf24273b6114ce | 666,942 |
def skip_comments(lines):
"""Filter out lines starting with a #."""
return (line for line in lines if not line.startswith('#')) | c91426a14adcd8dcc8aa8564523d3c9650fd77d4 | 666,943 |
def format_number(num):
"""
Formats a one or two digit integer to fit in four spaces.
Returns a string of the formatted number string.
"""
result = " " + str(num) + " "
if num < 10:
result = result + " "
return result | 7aad542a65e7c661fc0769e43d701a3764b7f8f3 | 666,944 |
def extract_spec_norm_kwargs(kwargs):
"""Extracts spectral normalization configs from a given kwarg."""
return dict(
iteration=kwargs.pop("iteration", 1),
norm_multiplier=kwargs.pop("norm_multiplier", .99)) | 3262d4d9152a3a12e8f24580620e0c344f71d951 | 666,945 |
def parse_in(line):
"""Parse an incoming IRC message."""
prefix = ''
trailing = []
if not line:
print("Bad IRC message: ", line)
return None
if line[0] == ':':
prefix, line = line[1:].split(' ', 1)
if line.find(' :') != -1:
line, trailing = line.split(' :', 1)
... | 649d9dab68239e8819c7e40fc46804e73993f498 | 666,946 |
def loudness_normalize(sources_list, gain_list):
"""Normalize sources loudness."""
# Create the list of normalized sources
normalized_list = []
for i, source in enumerate(sources_list):
normalized_list.append(source * gain_list[i])
return normalized_list | 7bc674e0e74753d9775d7d526345861373960ac8 | 666,947 |
import re
def remove_major_minor_suffix(scripts):
"""Checks if executables already contain a "-MAJOR.MINOR" suffix. """
minor_major_regex = re.compile(r"-\d.?\d?$")
return [x for x in scripts if not minor_major_regex.search(x)] | 64c307deba8d9d6c1e02f2e96a0c428ffef9b4df | 666,948 |
def e_noroeste(arg):
"""
e_noroeste: direcao --> logico
e_noroeste(arg) tem o valor verdadeiro se arg for o elemento 'NW' e falso
caso contrario.
"""
return arg == 'NW' | c20e216c43b7861a43d47efa7e6b41ef184f4ea4 | 666,949 |
import argparse
def make_parser(description=__doc__):
"""
Makes a parser using the module :mod:`argparse.ArgumentParser`
:param description: the parser description
:type description: str
:rtype: argparse.ArgumentParser
:return: ArgumentParser instance
"""
parser = argparse.ArgumentPa... | a3cab167f47effdac433b50c56491e92cfd3e77a | 666,950 |
import numpy as np
def ellipse_principal_axes(u,v):
"""
Calculates principal semi-axes and orientation angle of an ellipse
given input vector components (u, v).
Code adapted from Andrew Poje's MATLAB routine.
Parameters
----------
u : float
x-component of input vector.
v : fl... | 6c6795c7de05eeaeee92c6a675a90c21192a6a94 | 666,951 |
def name_blob(mosaic_info, item_info):
"""
Generate the name for a data file in Azure Blob Storage.
This follows the pattern {kind}/{mosaic-id}/{item-id}/data.tif where
kind is either analytic or visual.
"""
prefix = "analytic" if "analytic" in mosaic_info["name"] else "visual"
return f"{pr... | 4dd17ec49eae5db887fcf30c0696f1233c825fb7 | 666,952 |
def optional(**kwargs) -> dict:
"""Given a dictionary, this filters out all values that are ``None``.
Useful for routes where certain parameters are optional.
"""
return {
key: value for key, value in kwargs.items()
if value is not None
} | db34838108b88397f9ed2cd231a4b148b0d488bf | 666,953 |
def mt_publishPost(postid, username, password):
"""
lies that it publishes the thing, mostly for compatibility
porpoises...
"""
return True | 427fdca621f9468959f69e0092b3e0b22a20439d | 666,954 |
def drop_engine_after(prev_engine):
"""
Removes an engine from the singly-linked list of engines.
Args:
prev_engine (projectq.cengines.BasicEngine):
The engine just before the engine to drop.
Returns:
Engine: The dropped engine.
"""
dropped_engine = prev_engine.next_... | 9369fea7cdb35a446a6016967157f66a6f8e9513 | 666,955 |
def _get_material_sets(cell_sets):
"""Get the cell sets that are materials."""
material_names = []
material_cells = []
if cell_sets:
set_names = list(cell_sets.keys())
for set_name in set_names:
if "MATERIAL" in set_name.upper():
material_names.append(set_name... | abd17165dd62b38f6ccae5aadf4bfee2cced11fa | 666,957 |
def unit_name(unit):
"""
Return name of unit (must of course match unit_t in opendps/uui.h)
"""
if unit == 0:
return "unitless" # none
if unit == 1:
return "A" # ampere
if unit == 2:
return "V" # volt
if unit == 3:
return "W" # watt
if unit == 4:
... | 7600e6b3e6b1f5f3d4ab845c1be1f7a36ad27b54 | 666,958 |
def has_property(name):
"""Simple function property decorator"""
def wrap(func):
"""Wrapper function"""
setattr(func, name, True)
return func
return wrap | a0d988b9a3ead5651c08ae9994697a3eb3de7fdc | 666,959 |
def headers(token=None):
"""
Creates a dict of headers with JSON content-type and token, if supplied.
:param token: access token for account
:return: dictionary of headers
"""
data = {'Content-Type': 'application/json'}
if token:
data['Token'] = token
return data | 425f0137b50999dfd38a1a6b28628bb8d762a402 | 666,960 |
import os
def expand_path(p: str) -> str:
"""Expand $HOME in a path and normalise slashes."""
p = os.path.expanduser(p)
p = os.path.normpath(p)
return p | 0fe32b8d6435a84f7c6701e2dd884aeba26805d6 | 666,961 |
def bmatrix(arr):
"""
Converts a numpy array (matrix) to a LaTeX bmatrix
Args:
arr: Array
Returns:
LaTeX bmatrix as a string
Raises:
ValueError: If the array has more than two dimensions
"""
if len(arr.shape) > 2:
raise ValueError('bmatrix can at most displa... | 5382c8c623f7e4e2114949c254b8516c3fb798b3 | 666,962 |
def update_gd_parameters(parameters, gradients, alpha=0.01):
"""
subtracting the gradient from the parameters for gradient descent
:param parameters: containing all the parameters for all the layers
:param gradients: containing all the gradients for all the layers
:param alpha: learning rate
:re... | 86355789fe849dcc33d062b8a30b12c9b3725e1e | 666,963 |
import argparse
def create_argument_parser():
"""
Create the parameters for the script
"""
parser = argparse.ArgumentParser(
description="Create a QField datasets from PostGIS database.",
epilog="Example usage: python postgis2qfield.py -d yourdatabase -H localhost - p 5432 "
... | 2f1190caa590411768c548b70cfbce3fbbd92419 | 666,965 |
def get_cookie(self, name, default=False):
"""Gets the value of the cookie with the given name,else default."""
if name in self.request.cookies:
return self.request.cookies[name]
return default | 0831ec3c42433bdb10261a6fa0a71f239866c0d1 | 666,966 |
def XML_calib(calib_data: list, cf: int = 1):
"""Transforms a calibration array of floats into a .xml formatation.
Args:
calib_data (list): list of the calibration data for the microphone.
Returns:
str: string of calibration data in a .xml format.
"""
new_pos = '<pos\tName="Point {... | cb72fd6b6b2b1d5384e271363f9e13ed39c7ba06 | 666,967 |
def make_boolean_schedule(*, start, offset=0, **kwargs):
"""has value of start as long as iteration<offset, flips start afterwards.
always on (no negative iterations): start=False, offset=0. (flip immediately)
"""
start = bool(start)
return lambda it: ((offset<=it) ^ start) | ddf15c575cb2432a5958c24c4c8f73180a8d9882 | 666,968 |
def quadratic_cutoff(r_cut: float, ri: float, ci: float):
"""A quadratic cutoff that goes to zero smoothly at the cutoff boundary.
Args:
r_cut (float): Cutoff value (in angstrom).
ri (float): Interatomic distance.
ci (float): Cartesian coordinate divided by the distance.
Returns:
... | c7e58dda5738a335659ec9f044d0fa41032d801e | 666,969 |
def compute_chi_squared(data):
"""
Calculate Chi-Squared value for a given byte array.
Keyword arguments:
data -- data bytes
"""
if len(data) == 0:
return 0
expected = float(len(data)) / 256.
observed = [0] * 256
for b in data:
observed[b] += 1
chi_squared = 0
... | 8ef7dfe25d88ff8d412fd6201e6dd7a9972b639b | 666,970 |
import requests
def get_number_of_records(parameters):
"""
:param parameters: Dictionary with parameters of query to Zenodo API (dict)
:return: Number of records retrieved from the query (int)
"""
response_hits = requests.get('https://zenodo.org/api/records/', params=parameters)
hits = respons... | 6fd13e13526c5bf4d4c035fdf08ec4d4c575659a | 666,971 |
import token
import requests
def get_payment_details(trans_id: str) -> dict:
"""
Takes the transaction_id from the request and returns the status info in json.
It transaction_id is different from the transaction_ref so it should be grabbed from the request in the redirect url
"""
url = f"https://a... | 340ebf60f82c24663c134a1d5d6e45f762764bf6 | 666,972 |
import platform
def host_bits():
"""
The bits (64 or 32) for the host machine on which we are running.
:returns: bits
:rtype: integer
"""
# Note: platform.architecture() extracts the bits from the Python executable,
# which is not we want here (we might be running 32bit Python on a 64bit... | 5dc95ee80e2b44fd97217a2dd245d28fe4e85e64 | 666,973 |
def _trim_to_bounds(corners, image_shape):
"""
corners: plain tuple representation of the rect in (top, right, bottom, left) order
"""
return max(corners[0], 0), min(corners[1], image_shape[1]), min(corners[2], image_shape[0]), max(corners[3], 0) | 253b2fcabd6a79b81de2c1405088a9af3959e030 | 666,974 |
def include_bootstrap():
""" include static files """
return None | 6215793d257fe10132d0aa09bb7f74750779bb1a | 666,976 |
def edge_label(shape):
"""Returns texts of graph's edges."""
if len(shape) == 0:
return ''
if shape[0] is None:
label = '?'
else:
label = '%i' % shape[0]
for s in shape[1:]:
if s is None:
label += '×?'
else:
label += u'×%i' % s
return label | bc649c30a63480da44a960fa4bebd4e09ff5b4a8 | 666,977 |
def _deep_map(func, *args):
"""Like map, but recursively enters iterables
Ex:
>>> _deep_map(lambda a, b: a + b,
(1, 2, (3, (4,), 5)),
(10, 20, (30, (40,), 50)))
[11, 22, [33, [44], 55]]
"""
try:
return [_deep_map(func, *z) for z in z... | 709679408cfeca47e25d975974b3b219945a2f59 | 666,978 |
def get_review_request_id(regex, commit_message):
"""Returns the review request ID referenced in the commit message.
We assume there is at most one review request associated with each commit.
If a matching review request cannot be found, we return 0.
"""
match = regex.search(commit_message)
ret... | a16866334259e50670f1af3cba3ff9e1b549a918 | 666,979 |
import re
def get_version_parts(version, for_sorting=False):
"""Returns a list containing the components of the version string
as numeric values. This function can be used for numeric sorting
of version strings such as '2.6.0-rc1' and '2.4.0' when the
'for_sorting' parameter is specified as true."""
... | 0528bb020ecb940763d39f6f141894fe2458721a | 666,980 |
import argparse
def get_arguments(argv):
"""
Get arguments using ArgumentParser
:param argv:
:return args:
"""
parser = argparse.ArgumentParser(description='CSV, XLS, XLSX data set migration to MySQL database')
parser.add_argument('-t', '--type', help='The dataset type. Spreadsheet or csv'... | 958f28e1dbb9109dba589186b02b847f09658ca3 | 666,981 |
import numpy
def parallactic_angle(hour_angle, declination, latitude):
"""
Return parallactic angle in degrees for a given observing condition.
Inputs in degrees. Hour angle is positive if west of the meridian.
The parallactic angle returned is the direction to the zenith measured north
... | 313c9ef3908b4fb16c4ee81929d5282729b56dbe | 666,982 |
def _compressed_suffix(compression):
"""Returns a suitable suffix (including leading dot, eg ".bz2") for
the selected compression method."""
if compression is True: # select best compression -- but is xz always the best?
return ".xz"
elif compression in ("xz", "bz2", "gz"): # valid compression i... | 5584928e335456969c59a85fe98c29a04ece1e33 | 666,983 |
import heapq
def solve(p, q):
"""
Build a suffix tree of the joined strings and return the shortest
(non-empty) substring of p that does not appear in q
"""
class Node():
def __init__(self, parent, rank, mode, offsets):
self.parent = parent
self.rank = rank
... | fbc306aeded5ba7ee688710fb664a7ee6dafa805 | 666,984 |
def work(task):
"""Just execute task."""
return task.execute() | 7a5dfed832b12c0f9c736d226e63373af672a9f5 | 666,985 |
def sort_by(comparator, list):
"""Sorts the list according to the supplied function"""
return sorted(list, key=comparator) | 3b50ddd1bf5e16b513cc9376cf5ee7363682fd40 | 666,987 |
def ramp(duration, initial, final):
"""Defines a linear ramp.
f(t) = (final - initial)*t/duration + initial
Args:
duration (float): Duration of ramp
initial (float): Starting value of ramp
final (float): Ending value of ramp
Returns:
func: Function that takes a single ... | 707a01542f90eea66ed4158f759cfd0a6b931d7a | 666,988 |
import csv
def csv_to_list(filename):
""" creates a list of the contents of the csv
"""
out = []
with open(filename, newline = '') as f: #open csv file containing names
reader = csv.reader(f) #read the file
for row in reader: #loop over rows of the file
out += row #add co... | 698ffe07a10ef64fb83bcd0d1e0477cca5fc0441 | 666,990 |
def setTeamBranchUsage(err=''):
""" Prints the Usage() statement for this method """
m = '%s\n' %err
m += ' This script set the status of a Team Branch within Salesforce.\n'
m += ' Use one of the forms below to meet your needs.\n'
m += ' \n'
m += ' Set the team branch status to "Team Bra... | 185e05292c42c204ab6c7a84980c3eaa587d4835 | 666,991 |
def may_raise(f):
"""
Return the set of exceptions that a callable may raise.
Returns {:class:`Exception`} if the callable has made no more
precise declaration.
"""
try:
return set(getattr(f, '_raises__xc_raises'))
except:
return set((Exception,)) | 8415cf7752c5ac31e48d1d75332b6ee715abcdf0 | 666,992 |
def _get_item_types(cls):
"""
Получение явно объявленных (не унаследованных) типов элементов коллекции
из её класса.
"""
attname = "_{}__item_types".format(cls.__name__)
return getattr(cls, attname, None) | 13962c6aab67fb7bb9b519628857b49acdd1cf0d | 666,993 |
import math
def make_elliptic_cylinder_shell_density_func(neuronal_ids,
regions,
neurons,
width_scale,
spans,
... | ef16fa83ad288af69db3cfcc169be147facce6ff | 666,994 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.