content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def reformate_path(path):
"""On certain editors (e.g. Spyder on Windows) a copy-paste of the path from the explorer includes a 'file:///'
attribute before the real path. This function removes this extra piece
Args:
path: original path
Returns:
Reformatted path
"""
_path = path.... | a488402957e233454749a55b92a0f4ce0526ebe9 | 663,884 |
def initial_fixation_duration(interest_area, fixation_sequence):
"""
Given an interest area and fixation sequence, return the duration of the
initial fixation on that interest area.
"""
for fixation in fixation_sequence.iter_without_discards():
if fixation in interest_area:
retur... | 3fef15047500b8be8175a28d838feb10cd571f80 | 663,886 |
def graph2google(graph):
""" Connectivity graph to Google Page Rank
:param graph: igraph formatted graph
:return:
"""
eigvectcent = graph.pagerank(weights=graph.es["weight"])
return eigvectcent | d718d058b9d083e5db26f1e55ab3c727fc0981b8 | 663,888 |
import numpy
def normalize_in_range(mylist, min_value, max_value):
"""
Rescales all the values of an array to be in the range (min_value, max_value).
@param mylist: The array to normalize.
@param min_value: Minimum value we want to have in the list.
@param max_value: Maximum value in the range.
... | ad3aa94734ba0981257e3d8757130f469435c567 | 663,889 |
def none_are_none(*args) -> bool:
"""
Return True if no args are None.
"""
return not any([arg is None for arg in args]) | 0264cf2abd4bb0fbcc4aff8f6f4a1c44512d844b | 663,890 |
def entities_equal(entity_1, entity_2, check_key=True):
"""Return a bool on whether two input entities are the same."""
if check_key:
return entity_1.key == entity_2.key
return entity_1.to_dict() == entity_2.to_dict() | 50a3d4378eb1653497c062537979057b27532e77 | 663,891 |
def parsePyMus(text):
"""Read data from a PyMus string."""
textlines = text.split("\n")
name = textlines[0].replace("NAME=","").replace("\n","")
beatlength = int(textlines[1].replace("BEATLENGTH=","").replace("\n",""))
lines = []
readlines = textlines[2:]
for i in range(0, len(readlines)):
... | 46f70b8a7d8057879ec146f03c1d4f9ac5bef6fa | 663,892 |
def get_word_lengths(s):
"""
Returns a list of integers representing
the word lengths in string s.
"""
return [len(w) for w in s.split()] | 54d6a646ddc27606cb9dd8324a614e5e7df00857 | 663,893 |
def doc_brief(brief):
"""format brief for doc-string"""
return " {0}\n".format(brief) | 24576b056014fe0712489361d61ae8409b1f09f2 | 663,894 |
def broadcast_rank(source, target):
"""Broadcasts source to match target's rank following Numpy semantics."""
return source.reshape((1,) * (target.ndim - source.ndim) + source.shape) | f4cf5a1e899599db06e5807fc17c08d1f68e2bd4 | 663,895 |
import inspect
def self(method, self, *args, **kwargs):
"""`@self` method decorator to return self object"""
if not inspect.isroutine(method):
err = "@self decorator for methods only, got %s" % method
raise TypeError(err)
margs = [self] + list(args)
r = method(*margs, **kwargs)
if ... | 46a3099e4128fdf963c7098e9c942bc6f1a7a467 | 663,896 |
def longest_substring_with_k_distinct(s, k):
"""Find the length of the longest substr with less than or equal to
k distinct characters.
Time: O(n)
Space: O(k)
>>> longest_substring_with_k_distinct("araaci", 2)
4
>>> longest_substring_with_k_distinct("araaci", 1)
2
>>> longest_subs... | 341e73fad56cfa9a22176c54baa6a3140ed96bb1 | 663,897 |
def function():
"""subpackage.function"""
return "subpackage.function" | c1d13f5e14dcdc8c83c1c162247a5f328c5a947a | 663,898 |
def GetName(FCFCS):
""" Return the S-57 long-name of the FCFCS """
return FCFCS[3] | 0480cf3cc33b54abb5296ac7c8168a4fd33fa5ba | 663,899 |
def find_max(arr, l, r):
"""查找范围内的最大值"""
if l == r:
return arr[l]
else:
if arr[l] < find_max(arr, l+1, r):
return find_max(arr, l+1, r)
else:
return arr[l] | 7afba3e33406383655d9c2f97d67a180ebce4c7b | 663,900 |
def dummies2int(cBin):
"""
Conversion of Binary Classes to Integers Classes
:param cBin: [1 0 0] ==> 1
(numpy array) [0 0 1] ==> 3
[0 1 0] ==> 2
:return: [1,3,2]
"""
c = []
for i in cBin.tolist():
c.append(i.index(1) + 1)
return c | d619f3d11f4efaafe0a4e1ab27645dc8bed731ad | 663,901 |
def instruments():
"""
Dict to convert instrument to bitwise flag
.. warning::
Modifying any of the following is a *bad* idea. Adding is ok
Returns
-------
instr_dict : dict
"""
instr_dict = {}
#
instr_dict['LRISr'] = 2**0
instr_dict['LRISb'] = 2**1
instr_dic... | 930b33d21f21324f83fd4568d06e2535b84d2adf | 663,902 |
import math
def angle_diff(a1, a2):
"""Computes signed angle diff in rad."""
d = a1 - a2
return (d + math.pi) % 2*math.pi - math.pi | ae7c98629c670f38b2a3577099609ff2ca9b5014 | 663,903 |
import re
def default_style_html_str(html_str):
"""Return a string that contains the \"Kindle Clippings.txt file\" converted to HTML with a default embedded CSS style."""
html_str = re.sub("<h1>", "<div class=\"frontpage\"><h1>", html_str)
html_str = re.sub("</h1>", "</h1>\n<div class=\"generator\"><p>Gen... | f3cb7e8626c21c567ce39c73c70a745cf523db57 | 663,904 |
def sec2hms(seconds):
""" return seconds as (hh,mm,ss)"""
hr = int(seconds)
mn = int((seconds*3600 - hr*3600)/60)
sec = seconds*3600 - hr*3600 - mn*60
return [hr, mn, sec] | 38cb365cd49d69c81e331c3ecfef41e4907400c0 | 663,905 |
import argparse
def get_argparser():
"""Build the argparse instance."""
parser = argparse.ArgumentParser(
description="Update from upstream releases.",
formatter_class=argparse.RawTextHelpFormatter,
)
parser.add_argument(
"--registry",
default=None,
type=str,
... | 926e88336f920b56c5a79255c42b5121839737f9 | 663,906 |
def spread():
"""Calculate the range between the minimum and maximum values. (spread = max - min).
:return: Returns function for use in pd.DataFrame.agg() calls.
"""
def _spread(x):
_min = x.min()
_max = x.max()
return _max - _min
_spread.__name__ = "range"
... | 7231282effabcfda8c361b93ac505671a930f8af | 663,907 |
def global_roach_state_from_rnc(rnc):
"""
Return a dictionary containing roach state information from the given ReadoutNetCDF instance that is common to all
measurements in the file.
:param rnc: a ReadoutNetCDF instance.
:return: a dict containing state information.
"""
state = {'boffile': ... | 35e65537cf5b01f1e9274d14e7bada0cec43cad4 | 663,908 |
from typing import Dict
from typing import List
import csv
def read_temp_csv_data(filepath_temp: str) -> Dict[str, Dict[int, List[float]]]:
"""Return a mapping from the state to a mapping of the year to yearly data in the format
[average temperature, precipitation, wildfire counts].
Currently, the values... | 4342eb9b1ed392cd8ee94dfa400a194948fef3a4 | 663,909 |
def getNodePresetExcludePaths():
"""getNodePresetExcludePaths() -> string list
Gets a list of all paths that are excluded from the search for node presets.
@return: List of paths."""
return ['',] | 710e372d79b3a68890652c1ba73762cc91d85c5c | 663,910 |
def replay_args(parser, show_all_task_softmax=True):
"""This is a helper function of function :func:`parse_cmd_arguments` to add
an argument group for options regarding Generative Replay.
Args:
parser (argparse.ArgumentParser): The argument parser to which the
group should be added.
... | ecc69b700a0221a9be7400d203f6dab2a7745bdd | 663,911 |
def get_trait_names(clinvar_json: dict) -> list:
"""
Given a dictionary for a ClinVar record parse the strings for the trait name of each trait in
the record, prioritising trait names which are specified as being "Preferred". Return a list of
there strings.
:param clinvar_json: A dict object contai... | 4728b182dc9fc5bfea9db440d279774f16f4eddd | 663,912 |
def remove_nones(X):
""" Removes all Nones from a list and replaces them by zero """
return [[[0. if v is 'None' else v for v in d] for d in data] for data in X] | 9c57e72146044934d08cf2b5282c6636a9c27710 | 663,913 |
def get_noun_r(words_li,pos_li,dpd_li,n_i,v_i):
"""
获取一个给定了index的名词的修饰关系
"""
elaborate=''
s=''
after=words_li[n_i+1]
if '的'==after:
j=n_i+2
else:
j=n_i+1
#给定名词修饰其后的名词
while pos_li[j]=='n':
elaborate+=words_li[j]
j+=1
if '的'==after:
i... | 0407df41a38d71cd2735d19f1caf839fb401c3c5 | 663,914 |
def init_label_dict(num_classes):
"""
init label dict. this dict will be used to save TP,FP,FN
:param num_classes:
:return: label_dict: a dict. {label_index:(0,0,0)}
"""
label_dict={}
for i in range(num_classes):
label_dict[i]=(0,0,0)
return label_dict | 7681e02aecadfc05a81599a0f6cb0f95a92c7a62 | 663,915 |
def convert_string_AE2BE(string, AE_to_BE):
"""convert a text from American English to British English
Parameters
----------
string: str
text to convert
Returns
-------
str
new text in British English
"""
string_new = " ".join([AE_to_BE[w] if w in AE_to_BE.keys() e... | b032b007ad59ef653733e01b3c7b43de5d2a956a | 663,916 |
def order_dict(_dict: dict, reverse: bool=True) -> dict:
"""
Takes a dictionary and returns it ordered.
:param _dict: :class:`dict`
:param reverse: :class:`bool`
:return: :class:`dict`
"""
temp_dict = {}
unordered_list = [(k, v) for k, v in _dict.items()]
ordered_list = sorted(unor... | 5e32efefff3f70e86eec21470cc179ff95707897 | 663,917 |
import re
def replace_string( text, old_string, new_string ):
"""
Check that `old_string` is in `text`, and replace it by `new_string`
(`old_string` and `new_string` use regex syntax)
"""
# Check that the target line is present
if re.findall(old_string, text) == []:
raise RuntimeError(... | 93811fe03ac720baab12b3bd0733a8b05cf6b3a0 | 663,918 |
def list_api_vs(client, resource_group_name, service_name):
"""Lists a collection of API Version Sets in the specified service instance."""
return client.api_version_set.list_by_service(resource_group_name, service_name) | c12a895195a0122afa53649c2cb351e118916a62 | 663,919 |
def has_won(board):
"""
returns 0 if game is unwon.
returns player number of winning player if game is won.
"""
#Check the rows
if board[0][0] == board[0][1] and board[0][2] == board[0][0] and not board[0][0] == 0:
return board[0][0]
elif board[1][0] == board[1][1] and board[... | 3d3e784ba4b91922ae910463d99c8567aecc3e66 | 663,920 |
def startswith(text, starts):
"""Simple wrapper for str.startswith"""
if isinstance(text, str):
return text.startswith(starts)
return False | 3bfc1637fdc3fc4e2fdc40badafbecbc140991b1 | 663,921 |
def merge_roles(mop):
"""Merge multiple roles."""
new_list = []
for m in mop:
if m in new_list:
keep_this = new_list[new_list.index(m)]
if not isinstance(keep_this.currentRole, list):
keep_this.currentRole = [keep_this.currentRole]
keep_this.curren... | 050f6f6e31779d543a84a1764be92539d4805017 | 663,922 |
def compare_acl(acl1, acl2):
"""
Compares two ACLs by comparing the role, action and allow setting for every ACE.
:param acl1: First ACL
:type acl1: dict with role, action as key and allow as value
:param acl2: Second ACL
:type acl2: dict with role, action as key and allow as value
:return:... | 4e38bb1a0dabe58401898a804bc5d3054861df97 | 663,923 |
def _reference_expect_copies(chrom, ploidy, is_sample_female, is_reference_male):
"""Determine the number copies of a chromosome expected and in reference.
For sex chromosomes, these values may not be the same ploidy as the
autosomes. The "reference" number is the chromosome's ploidy in the
CNVkit refe... | 115ab67a370bc640d39470be419053f4322b4f50 | 663,924 |
def indent(lines, column):
"""
Insert spaces to shift this string right by the column count
"""
columns = " " * column
output_string = ""
if (not isinstance(lines, list)):
lines = lines.splitlines()
for line in lines:
output_string += columns + line + "\n"
return outpu... | 9701d5a501ffd8af4072d1d00e0c679bd9e83ff0 | 663,925 |
def distancia(a, b):
"""
a, b: são listas, tuples, etc com dois elementos no mínimo
retorna distância Euclidiana entre "pontos" a e b
"""
return ((a[0] - b[0])**2 - (a[1] + b[1])**2)**0.5 | 78c3adeb948bf28e787581050423826abc0bf8ff | 663,926 |
def binary_map_gt(rast1, rast2):
"""
returns a binary map from the ground truth with two dates
"""
# loading the rasters
gt1 = rast1[0,:,:]
gt2 = rast2[0,:,:]
## getting the change map
# getting the nodata matrix
data_index = gt1 != 0
nodata2 = gt2 == 0
data_in... | 0a65f99bb0c3a54544cc21f2960065b39e7b0f0e | 663,927 |
import tempfile
def getBuildDir():
"""
get build directory path in sandbox.
"""
return tempfile.gettempdir() | 0f93bf8e16d7798ff91bd57fd04ce815548c4b82 | 663,928 |
def learning_rate_schedule(base_lr, epoch, total_epochs):
"""LR schedule"""
alpha = epoch / total_epochs
if alpha <= 0.5:
factor = 1.0
elif alpha <= 0.9:
factor = 1.0 - (alpha - 0.5) / 0.4 * 0.99
else:
factor = 0.01
return factor * base_lr | 12437424b845d618ac407882eef3bbac9e1ef377 | 663,929 |
import math
def score_feature_vector(feature_vector, probs, cnt_bins, restrict_features):
"""
For a feature vector, computes its log transformed likelihood ratio with respect to the model.
That is, every feature value in the feature vector is evaluated and log of the likelihood ratio is added
to the t... | d09078afef15dfc35470a73eb10e4a445cc8e781 | 663,931 |
def removekey(d, key):
"""This functions returns a copy of a dictionnary with a removed key
Parameters: d (dict): dictionnary
key: the key that must be deleted
Returns: copy of dictionnary d without the key
"""
r = dict(d)
del r[key]
return r | 45eeb1e56a38e065aeb2dba58acc098152ea0425 | 663,932 |
def modularity(comm):
"""
comm: community
"""
return comm.modularity | 5265d80ace73cdac78399b22a4cf9a54b5c7a75d | 663,933 |
def formatDiff(diff):
"""Takes a svn diff and marks it up with elements for styling purposes
Returns a formatted diff
"""
diff = diff.splitlines()
diffList = []
def formatLine(line):
format = "<samp class=\"%s\">%s</samp>"
formattingTypes = {"+": "addition", "-": "deletion", "@... | 4003d49dcbe734dbd03edf50bd2cd0e72171a0a9 | 663,934 |
def parse_cp_counter_output(data):
"""Parse file print_counter data must be a single string, as returned by file.read() (notice the difference
with parse_text_output!) On output, a dictionary with parsed values."""
parsed_data = {}
cardname = 'LAST_SUCCESSFUL_PRINTOUT'
tagname = 'STEP'
numbers =... | de03ca8d573ea15a88d6b5887aa410fceac232b8 | 663,935 |
def get_dataset_info(dataset_type):
"""define dataset_name and its dataroot"""
root = ''
if dataset_type == 'LEVIR_CD':
root = 'path-to-LEVIR_CD-dataroot'
# add more dataset ...
else:
raise TypeError("not define the %s" % dataset_type)
return root | d9fea426ba8b3277d774e1dee7fef3c132a3f5c3 | 663,936 |
def get_default(dct, key, default=None, fn=None):
"""Get a value from a dict and transform if not the default."""
value = dct.get(key, default)
if fn is not None and value != default:
return fn(value)
return value | d65f2c578d3de4e2e917c32b342b580fbdfff817 | 663,937 |
import re
def identity_card_match(id_number):
"""
身份证号码验证
:param id_number:
:return: Boolean
"""
if type(id_number) is int:
id_number = str(id_number)
if type(id_number) is str:
try:
int(id_number[:17])
except ValueError:
return False
re... | e048cf1a23ac2922be981bcdf1885d7c11cf0f06 | 663,938 |
import re
def get_class_name(a_string):
"""Convert a name string to format: ThisIsAnUnusualName.
Take a space delimited string, return a class name such as ThisIsAnUnusualName
Here we use this function for instance name. Thus it allows to start with a number
"""
joint_name = a_string.title().repla... | f1f0e146cdd2f35029eef0ed3b2e944c89082f1f | 663,939 |
def _get_num_contracts(contracts_list, param_name):
"""
Return the number of simple/default contracts.
Simple contracts are the ones which raise a RuntimeError with message
'Argument `*[argument_name]*` is not valid'
"""
msg = "Argument `*[argument_name]*` is not valid"
return sum(
... | 4ef03e50d2d4c6fd1881c94dacd8e9db166d7d8a | 663,940 |
def get_duplicate_indices(words):
"""Given a list of words, loop through the words and check for each
word if it occurs more than once.
If so return the index of its first ocurrence.
For example in the following list 'is' and 'it'
occurr more than once, and they are at indices 0 and 1 so you would
... | 0ea94957d5ff8ae9cd7488ea9b4adcf33020ec2c | 663,941 |
from typing import List
import random
def replace_mlm_tokens(
tokens: List[int],
vocab_len: int,
mask_id: int = 103,
masked_tokens_percentage: float = 0.15,
unmasked_label_id: int = -100,
):
"""Applies masking to the given sequence with numeric indices and returns the manipulated sequence + la... | 621ea4f1652827e83bea0e8c89236c95997b33fb | 663,943 |
import time
def utc_offset(time_struct=None):
"""
Returns the time offset from UTC accounting for DST
Keyword Arguments:
time_struct {time.struct_time} -- the struct time for which to
return the UTC offset.
If Non... | f7b52f3fd292ac773d107f8143ffc7ab8be57499 | 663,944 |
def csr_residual(v_t, b_t, weights):
"""get the residual of a vector after subtracting other vectors
:param v_t: csr matrix with one row
:param b_t: csr matrix with possibly many rows
:param weights: coefficients for each row in mat in vertical csr_matrix
:return: a csr matrix with one row, the v-s... | 0199ef4026183053a2afe12371dcbbac919482db | 663,945 |
import requests
from bs4 import BeautifulSoup
def getBoxscoreURLsFromPlayer(playerId):
"""
Put in a player id and get all boxscores for that player.
- can be updated to specify after which date.
"""
r = requests.get('https://www.pro-football-reference.com/players/'+ playerId[0] + '/' + p... | 7c083e65f292211fe3389d78206e9a2ec6c309fc | 663,946 |
def read_wien2k_G_vectors(filename):
"""
Read the Wien2K G-vectors and return
the vectors
- G1
- G2
- G3
In Wien2K the G-vectors are stored in a file with the extension
.outputkgen, and are listed under
G1 G2 G3
so we need to be looking for lines that start with that content.
... | 4a8388a11cb992520c946b2b5b7468824767e9ba | 663,947 |
def add2(matrix1,matrix2):
""" Add corresponding numbers in 2D matrix """
combined = []
for row1,row2 in zip(matrix1,matrix2):
tmp = [sum(column) for column in zip(row1,row2)]
combined.append(tmp)
return combined
# Alternativley:
# nest the list comprehension for a one line ... | 53660ae20171d2b91f9ad472bd4572b4c8bf991a | 663,948 |
def porosity_happel(row):
"""
:param row:
:return:
"""
gam = (1 - row.porosity) ** (1 / 3)
numerator = 2 * (1 - gam ** 5)
denominator = 2 - 3 * gam + 3 * gam ** 5 - 2 * gam ** 6
return numerator / denominator | 9b24c7c7741abf27ef5067142a5900d6b370f10a | 663,949 |
def adapt_value(value):
""" Convert sql field name to application field
"""
if isinstance(value, int):
return str(value)
if value == "null":
value = ""
if value is None:
value = ""
return value | e9f406074f282bb2db912f4c0ec6346d4096047a | 663,950 |
def nomalize_image(image):
"""Nomalize image from [0,255] to "[-1, 1]"""
image = image / 255.0
image = 2 * (image - 0.5)
return image | eb07880036567cdaa44b78531face24dd697745d | 663,952 |
def wavelength(frequency, speed=343.2):
"""Calculate the wavelength l of frequency f given the speed (of sound)"""
l = speed/frequency
return l | 6e72b642bdb2f6426c4527d413a551d2d82a3ca6 | 663,954 |
import uuid
def unique_dataset_name(prefix: str = "selenium-dataset"):
""" Return a universally-unique dataset name """
return f'{prefix}-{uuid.uuid4().hex[:8]}' | a048d843dc12d5193f068a4a793e3b8fe188d108 | 663,955 |
def make_ignore_f(start_line):
"""Make an ignore function that ignores bad gg lines"""
def ignore(line):
"""Return false if line is bad"""
return not line or ['',''] == line or [start_line,''] == line
return ignore | d81dee049adeca826c26126bca27fd92f4876afe | 663,956 |
import json
def pj(jdb):
"""Dumps pretty JSON"""
return json.dumps(jdb,sort_keys=True,indent=4) | 7235ef14a5a55cee58a5cde72bc65b4b56c66755 | 663,958 |
import os
def exists(path: str) -> bool:
"""Check if a file exists."""
return os.path.exists(path) | 39b7afceb81fd3842517daaf2d0bf948ecb2e75e | 663,959 |
def render(context, obj, args):
"""
Try to render an attribute from an object. It will first look for a function called 'render_<attr_name>' on the
view, If this doesnt exist it will look for an attribute with the attribute name, if this doesnt exist it will
fallback to the default value supplied or Non... | 2018260db69da36ab0e013fc6244dbdda888d66b | 663,960 |
import os
import toml
def load_system(source_dir):
"""
Load the build system from a source dir (pyproject.toml).
"""
pyproject = os.path.join(source_dir, 'pyproject.toml')
with open(pyproject) as f:
pyproject_data = toml.load(f)
return pyproject_data['build-system'] | 7812dbb72cae0c861fb3b0b1ac1286881dcbe7ff | 663,961 |
def _to_number(val):
"""
Convert to a numeric data type, but only if possible (do not throw error).
>>> _to_number('5.4')
5.4
>>> _to_number(5.4)
5.4
>>> _to_number('-6')
-6
>>> _to_number('R2D2')
'R2D2'
"""
try:
if val.is_integer(): # passed as int in float for... | e848f9832778bf6463889b20894681947a0716ba | 663,962 |
import hashlib
def md5(text):
"""Returns the md5 hash of a string."""
hash = hashlib.md5()
hash.update(text)
return hash.hexdigest() | 91a583ed19bfd36b80e157d30e62c9ce7cf50a44 | 663,963 |
import six
def binary_decode(data, encoding='utf-8'):
"""Converts a binary type into a text type using given encoding.
Does nothing if data is already unicode string.
"""
if isinstance(data, six.binary_type):
return data.decode(encoding)
elif isinstance(data, six.text_type):
retur... | 352ed50fc531380ec4045c6a18e0dafaf0734a71 | 663,964 |
def get_hub_name_from_instance(hub):
"""Get the string name the eventlet uses to refer to hub
:param hub: An eventlet hub
"""
return hub.__class__.__module__.rsplit('.',1)[-1] | e5919c16e57899eb6c2a9a878fc55d0e7a7fb61c | 663,965 |
def divides(d: int, n: int) -> bool:
"""Return whether d divides n."""
if d == 0:
return n == 0
else:
return n % d == 0 | ad575e50364976c29443b4306bdb0daa375ad7b1 | 663,966 |
def get_raw_field_descr_from_header(file_handler):
"""
Get the raw field descriptors of the GNSS Logger log. These field descriptors
will be later used to identify the data.
This method advances the file pointer past the line where the raw fields
are described
"""
for line in file_handler:... | eb85ec44fe781fcaffbe0a942ca750a82c599d75 | 663,967 |
from functools import reduce
def bitList32ToList4(lst):
"""Convert a 32-bit list into a 4-byte list"""
def bitListToInt(lst):
return reduce(lambda x,y:(x<<1)+y,lst)
lst2 = []
for i in range(0,len(lst),8):
lst2.append(bitListToInt(lst[i:i+8]))
return list([0]*(4-len(lst2))... | dcf128642151effcb574c695e226ee8bc47a8aec | 663,968 |
def _inject_filters(app, filters):
"""Inject a set of filters into a Flask app.
Args:
app (object): The Flask application.
filters (dict): A dictionary of name and functions.
Returns:
app (object): The Flask application.
"""
for name, func in filters.iteritems():
ap... | e953608b8e4641f23f3a5babfb9f4d3256cf3eea | 663,969 |
import torch
def tensor_normalize(tensor, mean, std):
"""
Normalize a given tensor by subtracting the mean and dividing the std.
Args:
tensor (tensor): tensor to normalize.
mean (tensor or list): mean value to subtract.
std (tensor or list): std to divide.
"""
if tensor.dty... | a1cc8c7d261dcdea5b54ced5708bcc63139f7896 | 663,970 |
def scan_trunk():
""" scan trunk directory name
"""
return 'SCANS' | faac531d7da4cddc75dcaf2f973c08938a6d0682 | 663,971 |
def find_split_words(pattern, content):
"""
Args:
pattern (): regex pattern
content (str): document text
Returns:
"""
return pattern.findall(content) | dbacdc48c82551c2b3cff57adb9c5cbbc915206f | 663,972 |
def circarea ():
"""This function calculates the area of a circle"""
radius = float(input("Enter the radius of circle: "))
p = 3.14
area = p * (radius**2)
return area | f41a5c9d08152c1a457fc22004b54636ddfd9180 | 663,973 |
def str_to_bool(value):
"""
False and 'False' => False
otherwise => True
"""
return bool(value) and value.lower() != 'false' | 9555183c436ab7882a7339b342a0714d3708c020 | 663,974 |
import tempfile
import os
def mkdtemp():
"""Unique temporary directory."""
dirname = tempfile.mkdtemp(prefix='how_', suffix='_tmp')
created = os.path.exists(dirname)
os.rmdir(dirname)
return created and "directory {}".format(dirname) | 2d5e9b89b78bb642f04188fb7b86fed7a63ad235 | 663,975 |
def parse_filename(fname):
"""
Parse an SAO .hf5 filename for date and source
"""
parts = fname[7:-8].split('.')
UNIXtime = float('.'.join(parts[:2]))
sourcename = '.'.join(parts[2:])
return UNIXtime, sourcename | 5bd7b1cf1d44fb92db647cecc557a2d63221548e | 663,976 |
def secant_method(tol, f, x0):
"""
Solve for x where f(x)=0, given starting x0 and tolerance.
Arguments
----------
tol: tolerance as percentage of final result. If two subsequent x values are with tol percent, the function will return.
f: a function of a single variable
x0: a starting value... | 6c465f68084365661f409616b55a4d88f2da573f | 663,977 |
from typing import List
from typing import Tuple
def divideWorkByChrom(workRegionSets: List[List[Tuple[str, int, int]]]) -> List[List[Tuple[str, int, List[Tuple[str, int, int]]]]]:
""" Groups and annotates work sets (generated by divideWork) by chromosome.
Input: [
[("chr1", 1, 3,), ("chr1", 4, 6)], # work set 0... | 56182b517774ca586e8e7f869675ee4b3d1f0136 | 663,978 |
def checkOperatorPrecedence(a,b):
"""
0 if a's precedence is more than b operator
1 otherwise
"""
check={}
check['(']=1
check['*']=2
check['/']=2
check['-']=3
check['+']=3
if check[a] <= check[b]:
return 1
else:
return 0 | 0b63f1e66f6ae3818e8c67cd63a1a52acc7cc5ee | 663,979 |
def foo_two_params(bar='hello', baz='world'):
"""Joins two strings with a space between them.
**This function has a no deprecation decorator.**
Parameters
----------
bar : str
The first word to join.
baz : str
The second word to join.
"""
return bar + ' ' + baz | f6efc13229f677f287343755445d3c06d4cd7844 | 663,980 |
def get_unique_attribute_objects(graph, uniq_attrs):
"""Fetches objects from given scene graph with unique attributes.
Args:
graph: Scene graph constructed from the dialog generated so far
uniq_attrs: List of unique attributes to get attributes
Returns:
obj_ids: List of object ids with the unique at... | 1170f79039ae5efb0d7a16e65f9e1d46a84cdfb1 | 663,981 |
from typing import Union
from typing import Optional
def cast_to_num(value: Union[float, int, str]) -> Optional[Union[float, int]]:
"""Casts a value to an int/float
>>> cast_to_num('5')
5
>>> cast_to_num('5.2')
5.2
>>> cast_to_num(10)
10
>>> cast_to_num(10.1)
10.1
>>> cast_to_... | dc42d7f98be8c9edb27b1a2ccc2beb3246283498 | 663,982 |
def output_value(jsons, key):
"""
通过参数key,在jsons中进行匹配并输出该key对应的value
:param jsons: 需要解析的json串
:param key: 需要查找的key
:return:
"""
key_value = ""
if isinstance(jsons, dict):
for json_result in jsons.values():
if key in jsons.keys():
key_value = jsons.get(... | 8b92ac236b69b2a94f77c044856508258d70ac79 | 663,983 |
def coerce_event_abi_types_for_decoding(input_types):
"""
Event logs use the `sha3(value)` for inputs of type `bytes` or `string`.
Because of this we need to modify the types so that we can decode the log
entries using the correct types.
"""
return [
'bytes32' if arg_type in {'bytes', 's... | ab4e4a732cb6a243d891a385a69c55032911018b | 663,985 |
def deltaT_boil(t_boil, t_cond):
"""
Calculates the temperature difference of boiler.
Parameters
----------
t_boil : float
The boiling temperature of liquid, [С]
t_cond : float
The condensation temperature of steam, [C]
Returns
-------
deltaT_boil : float
The ... | 9539609b696ceaf03d8fffac704bfc28d6679c89 | 663,986 |
def full_classname(cls):
"""Return full class name with modules"""
return cls.__module__ + "." + cls.__name__ | eb8ba6bbf17d2ad2f0333540b0e3e043ea292b4e | 663,987 |
import torch
def min_mse(output, target):
"""
selects one closest cell and computes the loss
the target is the set of velocity target candidates,
find the closest in them.
output: torch.tensor e.g. (128, 2000)
target: torch.tensor e.g. (128, 30, 2000)
"""
with torch.no_grad():
... | ed97340917a7ea58cf7b705397c80091dfe9c071 | 663,988 |
import random
def pick_event(event_intervals):
"""
Returns a randomly selected index of an event from a list of intervals
proportional to the events' probabilities
:param event_intervals: list of event intervals
"""
i_event = 0
cumul_intervals = []
cumul_interval = 0.0
for interva... | 40856e66a272ce9a86b49b647bd85148cfd33703 | 663,989 |
async def read_status():
"""Check if server is running."""
return {'message': 'Server is running'} | 512daadea1a60248af41104d9d5340a9fa44340f | 663,991 |
from functools import reduce
def versionToInt(version):
"""
Converts a WebODM version string (major.minor.build) to a integer value
for comparison
>>> versionToInt("1.2.3")
100203
>>> versionToInt("1")
100000
>>> versionToInt("1.2.3.4")
100203
>>> versionToInt("wrong")
-1
... | cd847ca28cf6c3aa10d8d96137c1264c496baf31 | 663,992 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.