content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def nested_value(d, keys):
"""Access an element in nested dictioary `d` with path given by list of `keys`"""
for k in keys:
d = d[k]
return d | 0e42b078a4450422e08530ddb67066400d198b2d | 639,573 |
def to_hex(payload):
"""
Converts an int or long to hex but removes the "0x" at the start.
@rtype: str
@return: A string representing the number in hex without "0x".
"""
return hex(payload)[2:] | 08b28e4e2364fc3578a69c85478300a0549bccfb | 639,575 |
def GetRank(text, header):
"""
Get the rank under header.
Possible Headers: Tournament results, Match results
"""
headerStart = text.find(header)
found = text.find("Yomi AI", headerStart)
if found == -1:
raise Exception("MAJOR PARSING ERROR. Yomi AI text not found.")
en... | 159db975b9225ea25914ff2a39ca6d92757d5a5f | 639,576 |
import sys
import os
def path_for(name, script=__file__):
"""Build absolute paths to resources based on app path"""
if 'uwsgi' in sys.argv:
return os.path.join(os.path.abspath(os.path.join(os.path.dirname(script),'..')),name)
return os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]),name)) | b9d845c6fe6615d463b2c912ab5678d4669bbd42 | 639,577 |
def dump(file_path, yaml, objyaml):
"""Write the value of objyaml into file path."""
def start_end_lines(input_str):
"""Return formatted string"""
return "---\n{0}---\n".format(input_str)
with open(file_path, 'w') as target_yaml_file:
yaml.dump(objyaml, target_yaml_file, transform=st... | d2efea826a9d65117d8541b70e353ae91f28de4b | 639,578 |
import time
def timestamp_datetime(value):
"""
transfer unix time to formatted timestamp.
Args:
value (int): unix time.
Returns:
str: formatted time.
"""
time_format = '%Y-%m-%dT%H:%M:%S%z'
time_struct = time.localtime(value)
return time.strftime(time_format, time_str... | 8caaaf180682f9ece0703cdbe47945e26e63331b | 639,579 |
import collections
def neighbors(g_vec):
"""Return a dict of neighborhoods keyed by id, where the neighborhood is defined as all the user ids a given user played.
g_vec is a set of tuples (w_id, b_id, ...other stuff)
ratings is a dictionary keyed by user id to floats.
"""
neighbors = collect... | f2b1c32c9779043aa1b3ff929b1b09084ede5efa | 639,580 |
def adt_object_to_element_name(adt_object):
"""Returns XML element name for the given adt_object"""
objtype = adt_object.objtype
return f'{objtype.xmlnamespace.name}:{objtype.xmlname}' | 9b2c9490268ad5dd9ea387255d60d9440e1beff1 | 639,581 |
def split_inp(regex):
"""splits the regex"""
list_of_op = ["*","?","+"]
close_brac = 0
front,end,opr = None,None,None
flag = False
# if it is a open[] bracket
if(regex[0] == "["):
close_brac = regex.find("]")
front = regex[:close_brac+1]
end = regex[close_brac+1:]
... | 11f7e8d98df377521fbe6735b90417d47105693d | 639,582 |
def human_merging_scheme(cname, merging_scheme,
pname, parent_merging_scheme,
artifact_parameters, artifact_filepaths,
parent_parameters):
"""From the artifact and its parent features format the merging scheme
Parameters
----------
... | 2efe60631ef51e555e0f32e3e016df98dda97e25 | 639,583 |
def max_discharge_rule(mod, s, tmp):
"""
**Constraint Name**: Stor_Max_Discharge_Constraint
**Enforced Over**: STOR_OPR_TMPS
Storage discharging power can't exceed available capacity.
"""
return mod.Stor_Discharge_MW[s, tmp] \
<= mod.Capacity_MW[s, mod.period[tmp]] \
* mod.Avail... | 0de0429758ce79d8bb49a1a2daf6181c031a2aee | 639,584 |
def default_login(instance):
""" Default login value """
return f"id{instance.id}" | 3727a9cf5d541d2bb24c3d10ba2af925a105b3ab | 639,585 |
def mock_valid_telegram_config():
"""Mock valid telegram config."""
return {"token": "token", "chat_id": "007"} | d3a104a6ea6f4c9c37959d94a478abb674682f36 | 639,586 |
import os
import json
def join_jsons(templates):
"""Joins multiple JSON files to into one data structure
Used to join multiple template JSON files to create a global config dictionary.
@params templates <list[str]>:
List of template JSON files to join together
@return aggregated <dict>:
... | 320114da1dd8b59c676c43adbd5de01399d5fb56 | 639,587 |
def add_eprint_to_bib(bib, eprint):
"""
Insert the eprint information in a given bibtex string
Parameters
----------
bib: str
The bibtex string without the arxiv number
eprint: str
The arxiv number
Returns
-------
bib: str
The bibtex ... | 703f011199a7d3730b8056cae8bb0cfafab6d1d2 | 639,588 |
def get_throw_descriptions(get_nb_floor_objects, initial_state, current_state):
"""
Get all 'throw' descriptions from the current state (if any).
Parameters
----------
get_nb_floor_objects: function
Function that gets the number of objects thrown on the floor of the current state compared to... | 81d89ccfcab034469be59ca1dd8c7bb6346b69af | 639,589 |
def _merge(listA, listB):
""" Merges two list of objects removing
repetitions.
"""
listA = [x.id for x in listA]
listB = [x.id for x in listB]
listA.extend(listB)
set_ = set(listA)
return list(set_) | 0d9a6f377855cae22388768effca23dda68ac5b3 | 639,590 |
import os
def reserve_universe(filename):
"""deletes the file if it exists, then returns the full path"""
darwin_home_path = os.getenv('DARWIN_HOME_PATH')
if darwin_home_path is None:
raise RuntimeError('DARWIN_HOME_PATH must be set before running the tests')
full_path = os.path.abspath(os.pat... | 8b03bd73ea3aba010713a4bed4972d2668bb898d | 639,591 |
import logging
def calculateLengths(gtflines):
"""
calculate the lengths of each transcript in the gtf file by
summing up the length of all the exons in the transcript
"""
lengths = {}
total_transcripts = 0
for line in gtflines:
if line['feature'] != "exon":
continue
... | 1c001b8163035bd0302c01a93819f61c13090488 | 639,592 |
import re
def protect_uppercase(string):
"""
Protect uppercase letters for bibtex
:param string: string to convert
:returns: string
"""
string = re.sub('([^{]|^)([A-Z])([^}]|$)', '\g<1>{\g<2>}\g<3>', string)
return string | 9e82ab04c223f2f3f87b60cfaeddfafa9dd88ef4 | 639,593 |
def relu_backward(z, a_grad):
"""relu反向
:param z: shape[Out]
:param a_grad: shape[Out]
:return: shape[Out]
"""
return a_grad * (z > 0) | f9ec500feff6bb9360610c4297e61b6f0a521e24 | 639,595 |
import random
def randpop(seq):
""" removes and returns a random item from the sequence """
return seq.pop(random.randrange(len(seq))) | 7f4743ae672126f64940b5cec3a6d62bc149ecee | 639,597 |
import threading
def startWithCallback(process, onExit):
"""
Call process.start(), and then calls the function onExit when the
subprocess completes.
onExit is a callable object, will receive process as parameter.
"""
def runInThread(process, onExit):
process.join()
onExit(proc... | ca174aa1cc3b642cf520a8d404643d09ad41e97e | 639,598 |
def mapCol(table, colIndex, function):
""" Applys the function to every item in the column """
for row in table:
row[colIndex] = function(row[colIndex])
return table | c0a1f2514a29e423b6407f4c1cadbe8b3ec483c7 | 639,599 |
import numpy
def coexistance(phi, tc = 1.0):
"""
Coexistance point - minima of V(phi)
"""
t = numpy.zeros(phi.size)
a = 1.0
u = a*0.1
t[:] = tc - u*phi[:]**2/a
return t | d706e097b3f6a1a1cda018655242e8346ecc3706 | 639,600 |
def OP_stop(Simple_state):
"""Our stop state"""
Simple_state.the_answer = 42 # Do any final processing at shutdown
print("We have stopped")
return(Simple_state) # Returning our completed "output" | 730b7dcb7107b1c4b48d037d97b264970ef1f9fd | 639,601 |
from typing import Iterable
def read_nested_dict_value(nested_dict, nested_keys: Iterable, default_value=None, error_on_miss=False):
"""
Read a value from a series of nested dictionaries, such as returned by ruamel.yaml
:param nested_dict: The nested dictionaries (configuration map) to read from
:par... | 3ee4524ec5495b8936e3f6027a128544737e9d0e | 639,602 |
import os
def dir_create(path: str) -> bool:
"""
Create a directory or if path to directory does not exist create the whole path.
Note: Equivalent of 'mkdir -p <path>'. Bails out on permission error.
:param path: The path/directory to create as string.
:return bool: Returns True on success and F... | 75d738577fc4d09d2b73371903c3a3395e46daaa | 639,603 |
import torch
def euclidean_dist(x, y):
"""Computes Euclidean distance."""
m, n = x.size(0), y.size(0)
xx = torch.pow(x, 2).sum(1, keepdim=True).expand(m, n)
yy = torch.pow(x, 2).sum(1, keepdim=True).expand(m, m).t()
dist = xx + yy - 2 * torch.matmul(x, y.t())
dist = dist.clamp(min=1e-12).sqrt... | 3f232732a9a47843ff2d81e308992bcb0e0191ea | 639,605 |
import re
def update_max_version(src, key, new_max_version, category):
"""
Examples
========
>>> src = '''
... sklearn:
... ...
... models:
... minimum: "0.0.0"
... maximum: "0.0.0"
... xgboost:
... ...
... autologging:
... minimum: "1.1.1"
.... | 4e2bc7f430f7ad2cce70dea18b27def00a496764 | 639,606 |
def gamma(t, alpha):
"""
Arguments:
t: Int.
Discrete timestep.
Get step size as a function of timestep.
The step sizes go to 0 as t increases.
"""
return t ** -alpha | 26a134fc8681a0fd447114ba10f36e76c41f1b71 | 639,607 |
def c2k(c: float, r: int = 2) -> float:
"""Celsius to Kelvin."""
return round(c + 273.15, r) | c30c9af6d641da0167277af86608e5db0a0c20de | 639,608 |
def drop_duplicates(data):
"""Drop duplicate rows in a DataFrame."""
return data.drop_duplicates() | 9fd92cec19326ec584c8186e4fb6ccdce05fd24a | 639,609 |
def expand_tweet_urls(tweet):
""" Replace shortened URLs with long URLs in the twitter status, and add the "RT" flag.
Should be used before urlize_tweet
"""
if 'retweeted_status' in tweet:
text = 'RT @{user}: {text}'.format(user=tweet['retweeted_status']['user']['screen_name'],
... | e67fe54d8da2e441cfe1da5e61ece2890608dee9 | 639,610 |
def fixIoU(bb1, bb2):
"""
Calculate the fix Intersection over Union (IoU) of two bounding boxes.
fixiou = intersection_area / min(bb1_area, bb2_area)
Parameters
----------
bb1 : set
Keys: ('x1', 'y1', 'x2', 'y2')
The (x1, y1) position is at the top left corner,
the ... | 769e245a622c36550ca3fbc90896566c4a85eb61 | 639,611 |
def __eingroup_shapes(in_groups, out_groups, dim):
"""Return shape the input needs to be reshaped, and the output shape."""
def shape(groups, dim):
return [group_dim(group, dim) for group in groups]
def product(nums):
assert len(nums) > 0
result = 1
for num in nums:
... | 7789d23fbe430a1169b8c12df83cf40aeb801009 | 639,612 |
import pickle
def load_pickle(parent_dir):
"""
Accepts a parent directory Path object
which can contain only one pickled file with a .pkl extension
Finds the file, loads it, and returns it
"""
# print(parent_dir)
filepath = list(parent_dir.glob('*.pkl'))[0]
with open(str(filepath), 'rb... | e9aba6608d945ad01894a1af24601af3d9e664e0 | 639,613 |
def commits_per_day_authors(df):
"""TO..in progress"""
#group by author_name
authors = df.groupby("author_name")
#sum up commits each day
commits_per_day = authors.resample('D').count()
return commits_per_day | 1188442f462b7046ac4d1927f24eeca6a93d453e | 639,614 |
def date_to_epoch(date):
"""Convert a datetime stamp to epoch time."""
epoch_time = date.strftime('%s')
return int(epoch_time) | 088c3d28e5badda315908b735eaa15daf5cf559d | 639,615 |
import os
def get_journal_path(name):
"""
Gets the full path to the journal
:param the name of the journal
:return: The filepath to the journal
"""
filename = os.path.abspath(os.path.join(".", "journals", name + '.jrl'))
return filename | 8000e8cdd6bb048c9d4158c1fa53bbd762e3b1c0 | 639,616 |
def ParseAction(messages, action):
"""Converts an action string to the corresponding enum value.
Options are: 'allow' or 'deny', otherwise None will be returned.
Args:
messages: apitools.base.protorpclite.messages, the proto messages class for
this API version for firewall.
action: str, the action... | e13285d2a7873ecbdd7fcf7756e31d9653b7a5d1 | 639,617 |
import csv
def unpackCsvFiles(list_of_files):
"""Take Csv filess and load as a dictionary."""
aggregate = []
for filePath in list_of_files.values():
csvFile = open(filePath)
reader = csv.DictReader(csvFile)
for row in reader:
aggregate.append(row)
return aggregate | 35e22fca0fe9b667aa471373131033f04989eb17 | 639,618 |
import torch
def pad_charts(charts, padding_value=-100):
"""Pad a list of variable-length charts with `padding_value`."""
batch_size = len(charts)
max_len = max(chart.shape[0] for chart in charts)
padded_charts = torch.full(
(batch_size, max_len, max_len),
padding_value,
dtype=... | 349c7bd0b60a8a84bdea3abbbc7adff62a5d683f | 639,619 |
def array_to_string(array):
"""Turns a array into a string separated by §."""
string = ''
for s in array:
string += '§' + s
return string[1:] | 57d5f32c6cd24f8cb9dc1d184cc3e8933261727c | 639,620 |
def product_scoring(new_fsv_vsone):
""" product of all weights """
new_fs_vsone = new_fsv_vsone.prod(axis=1)
return new_fs_vsone | 17926a31d76415d96a34052de730ae87adf9c8b5 | 639,623 |
def percent(obj,object2):
"""
return percentage of 1 of 2
"""
if object2:
return int(float(int(obj))/object2*100)
else:
return 0 | b6d1a9a3bf92846e3b05d1a3ffab982c61d64e9b | 639,624 |
from typing import Dict
def _filter_frequency(ngrams: Dict[str, int], min_freq: int) -> Dict[str, int]:
"""
Filter a ngram list for ngrams with a minimum frequency.
:param ngrams:
:param min_freq:
:return:
"""
output = {}
for (ngram, freq) in ngrams.items():
if freq >= min_fre... | 99582e66a201066808fc1ce525b10e7404023456 | 639,625 |
def tokenize_corpus(corpus, vocabulary, additional_items, character_level,
insert_unk):
"""Translate string words into int ids
Args:
corpus (CategorizedTaggedCorpusReader): corpus object for the corpus being used.
vocabulary (Dictionary): vocabulary being used. Also write vocab mapping t... | cf3aa516ff6a035a5e6ecc179184fb8eb3c74d4a | 639,626 |
def convert_postag(pos):
"""Convert NLTK POS tags to SentiWordNet's POS tags."""
if pos in ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ']:
return 'v'
elif pos in ['JJ', 'JJR', 'JJS']:
return 'a'
elif pos in ['RB', 'RBR', 'RBS']:
return 'r'
elif pos in ['NNS', 'NN', 'NNP', 'NNPS']:... | c1d3c2e154ca6e98c19c3f398dd0aa689db535d2 | 639,627 |
import os
def create_stamp_name(*args):
"""Generate stamp file name based on input keywords"""
stamp = "-".join(args)
path = os.path.join(".stamps", stamp.replace("-", "--").replace(os.sep, "-").replace(":", "-"))
return os.path.abspath(path) | 76644030ebb9467b1e395e25be1eb8f17142f20a | 639,628 |
import subprocess
def find_changed_files(branch):
"""Use subprocess to find all files that are different."""
output = subprocess.run(
["git", "--no-pager", "diff", "--name-status", branch], capture_output=True
)
files = [s[s.find("\\t") + 2 :] for s in str(output.stdout).split("\\n")]
retu... | a83b8a6a56216072dad9a03aad32108ab9a68874 | 639,629 |
def getannotationstrings(cann):
"""
get a nice string summary of a curation
input:
cann : dict from /sequences/get_annotations (one from the list)
output:
cdesc : str
a short summary of each annotation
"""
cdesc = ''
if cann['description']:
cdesc += cann['description... | 2c5f85b61249c282bd10e8cbe24fd4b054597636 | 639,631 |
def get_hierarchical_net_pos(net):
""" Get x,y positions for plotting hierarchical graph.
For example:
.. plot::
:include-source:
>>> import graphy
>>> G = graphy.graphgen.gen_hierarchical_net(5, 2)
>>> pos = graphy.graphgen.get_hierarchical_net_pos(G)
>>> graphy.p... | 1d7f2319403b958c942745865580df06e712c4e5 | 639,632 |
from typing import OrderedDict
def ordered_dict(iterable):
"""Create an OrderedDict from an iterable of (key, value) tuples.
"""
ordict = OrderedDict()
for key, value in iterable:
ordict[key] = value
return ordict | 696776a778877049ec41de7193162013699fa5e3 | 639,633 |
def get_pics(weibo_info):
"""获取微博原始图片url"""
if weibo_info.get('pics'):
pic_info = weibo_info['pics']
pic_list = [pic['large']['url'] for pic in pic_info]
pics = ','.join(pic_list)
else:
pics = ''
return pics | 3198056e97f7f7f8242d484ca62400047259a71d | 639,634 |
def vce_metrics():
"""Details about the UC2/vCE
Returns:
dict: the metrics info
"""
return {
"pid_cpu": {"unit": "%", "type": "gauge"},
"pid_ram": {"unit": "bytes", "type": "gauge"},
"gop_size": {"unit": "number", "type": "gauge"},
"num_fps": {"unit": "fps", "typ... | 39dfa306ea378ceee345733d78bcd108713625c7 | 639,635 |
def pick_third_largest_num(sequence: list[int]) -> int:
"""数列から3番目に大きい整数を取得する
Args:
sequence (list): 整数のリスト
Returns:
(int): 3番目に大きい整数
"""
return sorted(sequence)[-3] | 3d21863a41af4acd2e50fe2999519a3a165a2941 | 639,636 |
def build_gnab_feature_id(gene_label, genomic_build):
"""
Creates a GNAB v2 feature identifier that will be used to fetch data to be rendered in SeqPeek.
For more information on GNAB feature IDs, please see:
bq_data_access/data_types/gnab.py
bq_data_accvess/v2/gnab_data.py
Params:
gene... | b9b6f8f4acb791c7478a621baef8997db503eb71 | 639,637 |
import tempfile
import os
def gen_command_dir():
"""Produces pipes for talking to QEMU and args to enable them"""
command_dir = tempfile.mkdtemp()
os.mkfifo("%s/com.in" % command_dir)
os.mkfifo("%s/com.out" % command_dir)
command_args = [
"-chardev",
"pipe,id=command0,path=%s/com" ... | 75780f8a7ff41fbe68a176bd2f4f18db97094f77 | 639,638 |
def domains_to_samples(domains, sample_column='contig_id', target_column=None):
"""
Group Domain DataFrame into a list of DataFrames and list of output states based on given sample_id column
:param domains: Domain DataFrame with multiple sequences (samples), each marked by a unique ID in the sample_column
... | 6114ffa4294d3a722e44e05b6164392def542867 | 639,639 |
from typing import Union
import os
def _is_in_path(command: str, return_abs_path=False) -> Union[bool, str]:
"""
Check if *command* is in the $PATH or not.
:param str command: The command to be checked.
:param bool return_abs_path: Return the absolute path of the command instead
of True if th... | 758e6efb5e3206ee116d07eec1bc50c2e76fc16a | 639,640 |
def EncodePrivate(sk):
"""
Encode a private key into bytes (exactly 32 bytes for both
do255e and do255s).
"""
return bytes(sk) | 4763eb9bedf0b5d802b3ed3cd9441941c4567710 | 639,641 |
def get_percentage_orthologous_relations(hog_1, hog_2, extent_relations):
"""
compute the % of extant orthologous relations / total possible relations between two hogs
:param hog_1:
:param hog_2:
:param extent_relations:
:return:
"""
n1 = sum(map(len, hog_1.genes.values()))
n2 = sum... | 3384a6cf1a5a2d5188eb2e641651ab06687bc0a6 | 639,642 |
def cached_is_ancestor(is_ancestor):
"""return a cached version of is_ancestor"""
cache = {}
def _is_ancestor(anc, desc):
if anc > desc:
return False
elif anc == desc:
return True
key = (anc, desc)
ret = cache.get(key)
if ret is None:
... | 34cadebe52c08332bd2495bea16ddd117008c3a1 | 639,644 |
import torch
def get_default_device():
"""
Return current default device
"""
if torch.cuda.is_available():
return torch.device('cuda')
else:
return torch.device('cpu') | 7352e26817866c69f32439995b3cc236e970602c | 639,646 |
import re
def get_prefixlength(ip):
"""Returns the length of the network prefix, in bits."""
regex = r'(\d+)[.](\d+)[.](\d+)[.](\d+)[/](\d+)'
if not re.findall(regex, ip):
return ip
p = re.split(regex, ip)
return int(p[5]) | 6ac8e0c827175e13e8adb30010c93be46a35b49f | 639,647 |
from typing import Dict
import pathlib
import json
def load_git_info(input_path=None) -> Dict[str, str]:
"""
Load previously saved output of git_info from a json file.
Args:
input_path: Input path to json file. If None, the default will be
bclustering/git_info.json
Returns:
... | fcfba69430e91b36fb0e4f8047d2e3e673645729 | 639,648 |
def assign_to_group(pt, euclidList, data, k):
"""
Assigns given point to the group with highest frequency of K points
"""
votes = []
for g in euclidList[:k]:
for key, points in data.items():
for pt in points:
if pt==g:
votes.append(key)
... | 8eeda880d90f2d91577735c8007f71c4ca9bed68 | 639,649 |
import os
import sys
def GetCrashDumpDir():
"""Returns the default crash dump directory used by chromium. """
local_app_data = os.environ.get('LOCALAPPDATA')
if not local_app_data:
user_profile = os.environ.get('USERPROFILE')
if not user_profile:
sys.exit(0)
local_app_data = '%s\\Local Setting... | 019e902233466c6d9c3b6938f05ea15490944cf9 | 639,650 |
def _should_run_cmake(commands, cmake_with_sdist):
"""Return True if at least one command requiring ``cmake`` to run
is found in ``commands``."""
for expected_command in [
"build",
"build_ext",
"develop",
"install",
"install_lib",
"bdist",
"bdist_dumb"... | 577f90ac20b028f3d0b7fe4009196352f193faa0 | 639,653 |
def OutputGraphViz(scenario, final_tasks, output):
"""Outputs the build dependency graph covered by this scenario.
Args:
scenario: The generated scenario.
final_tasks: The final tasks used to generate the scenario.
output: A file-like output stream to receive the dot file.
Graph interpretations:
... | 2138632a92a2513adf4b78b913f83a8e85077681 | 639,654 |
def build_option_parser(parser):
"""Hook to add global options"""
# parser.add_argument(
# '--os-volume-api-version',
# metavar='<volume-api-version>',
# default=utils.env('OS_VOLUME_API_VERSION'),
# help='Volume API version, default=' +
# DEFAULT_API_VERSION +
#... | f8c721a67384609db0713f0c03e6f8f4c3a9dfe4 | 639,656 |
def Linear(score, score_min, score_max, val_start, val_end):
"""Computes a value as a linear function of a score within given bounds.
This computes the linear growth/decay of a value based on a given score.
Roughly speaking:
ret = val_start + C * (score - score_min)
where
C = (val_end - val_start) /... | 8f39ba6b5d81b46c382b05c1d74d71926a775013 | 639,657 |
import os
def _LayoutTestFiles(build_dir):
"""Lists all layout test data files that need to be included in the archive.
Args:
build_dir: The build directory.
Returns:
A list of file paths which are relative to the build directory.
"""
results = []
layout_test_data_dir = os.path.join(build_dir, '... | 28cf451689ead2201007d551f1e3370e5e32e221 | 639,658 |
def bytes_packet(_bytes, termination_string=']'):
"""
Create a packet containing the amount of bytes for the proceeding data.
:param _bytes:
:param termination_string:
:return:
"""
return '{}{}'.format(len(_bytes), termination_string) | 7f0d6356ec7afccac8e1865765f7f356ee783644 | 639,659 |
def all_besides_none_equal(*args):
"""Return True if all of the (non-None) elements are equal"""
non_none = list(filter(lambda x: x is not None, args))
for i, arg in enumerate(non_none):
if i + 1 < len(non_none) and arg != args[i + 1]:
print(arg)
return False
return True | 4f906bc579af2489ed1243a1d0054570c539a909 | 639,660 |
import math
def compute_rows_columns(num_wells):
"""Convert 96->(8,12), 384->(16,24), etc."""
a = math.sqrt(num_wells / 6)
n_rows = int(round(2 * a))
n_columns = int(round(3 * a))
return n_rows, n_columns | 4effef41bf38e358a695e667841a3e7817dda849 | 639,661 |
def skip_zone_record(zone_record):
"""Whether a zone record should be skipped or not.
Records are skipped if they are empty or start with
a # (indicating a comment).
:param zone_record: Full zone record, including the command (e.g. ADD).
:returns: True if the record should be skipped, false otherw... | 873545c501df3b5753dae62c0da0bfe655a60fdf | 639,664 |
def map_value(value, min_, max_):
"""
Map a value from 0-1 range to min_-max_ range.
"""
return value * (max_ - min_) + min_ | 9b5e083304d4476b223b156a32105b3bfb776cb5 | 639,665 |
def isXPathNonVar(var):
"""Returns true iff var is a string ("foo" or 'foo') or a number."""
if (var.startswith("'") and var.endswith("'")) or \
(var.startswith('"') and var.endswith('"')):
return True
# list from XPathToCode, below
if var.lower() in ["count", "empty", "true", "fals... | b89d9d5e83042a4e45ffe399db61168c20d254a6 | 639,666 |
def check_influxdb_response(response):
"""Check if the response from influxdb is correct.
InfluxDB normally responds with a 404 on GET to /, but also allow other
non-server-error response codes to allow for that behaviour to change.
"""
return response.code < 500 | b36397785f4cedcef19b05a3f4ed6e59f6b88cab | 639,667 |
def dop2str(dop: float) -> str:
"""
Convert Dilution of Precision float to descriptive string.
:param float dop: dilution of precision as float
:return: dilution of precision as string
:rtype: str
"""
if dop == 1:
dops = "Ideal"
elif dop <= 2:
dops = "Excellent"
el... | 2f9050eb8f3967f299d16377d5e56f2804e15293 | 639,668 |
import argparse
def handle_args():
"""Handle command line arguments"""
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--directory', required=True, help='Directory path to traverse')
parser.add_argument('-sf', '--snapshot-file', required=False, help='Snapshot file path')
parser.add_a... | db41a61fffabfd4c6dbd09d46f164f23ef7a96ab | 639,669 |
def get_complexity(data):
"""
Gets the complexity of the given trial data -- the number of degrees of
freedom that are active, or under control of the subject.
"""
return int(len(data['active_classes'])/2) | 778ff4c5c617afff8a19770fe46afc1c2d6b607f | 639,671 |
def prepare_feed_dict(placeholders, images, labels, batch_size, use_generated_data, idx=0):
"""Return the feed dict per batch with the input data."""
idx = idx * batch_size
if use_generated_data:
return {
placeholders[0]: images
}
return {
placeholders[0]: images[idx:... | b91cabacca5db8fc05bf0c4451886f67ac2bbf62 | 639,672 |
async def tell_joke(gh):
"""
Tell a joke to ease the PR tension!
"""
joke = await gh.getitem(
"https://official-joke-api.appspot.com/jokes/programming/random"
)
joke = joke[0]
return f"> {joke['setup']}\n *{joke['punchline']}*\n😄️" | 0ee0218c0c13ffa7d984912d55ba29f273942fd6 | 639,673 |
import argparse
def handle_args():
"""Create the parser, parse the args, and return them."""
parser = argparse.ArgumentParser(description='Check Azure Compute',
epilog='(c) MS Open Tech')
parser.add_argument('hostname', help='hosted service to check')
parser.add_ar... | 0bf37e7b03f2b8366b2688524d2f9f81678aed0b | 639,674 |
def check_corruption(layers):
"""Return one count * two count of layer with the least zeros in it."""
least_zeros = (None, None)
for layer, values in layers.items():
zeros = values.count(0)
if not least_zeros[0] or zeros < least_zeros[0]:
least_zeros = (zeros, layer)
zeros_l... | 0c435d555574b1fe2431899207b2c62f9eec3645 | 639,675 |
def get_pipeline_script_cmdcall_snli_converter():
"""
Creates a bash cmd to convert the SNLI data into our format
:return:
"""
# convert snli files into jtr format
cmd = "python3 jtr/format/convert/SNLI2jtr_v1.py"
return cmd | 465120577e8dcb9cddcbc651d8f7ee402190fdbf | 639,676 |
def list2str_str(list):
"""Convert list to a single string. Inverse of str2list."""
return ''.join([str(i) + '\n' for i in list]) | 2020d77f8ccb26af71b5d690df6965970f049045 | 639,678 |
def check_perun_integration(subdirs):
"""Helper function for determining the existence of perun wrapper over the underlaying vcs
:param str subdirs: list of subdirectories located in the repository
:return: str depending on the status
"""
for name in subdirs:
if name == '.perun':
... | 5fff5e0786ff1f5e88401c6753f8dae09fe5b493 | 639,679 |
from typing import Union
def format_indexing_element(indexing_element: Union[int, slice]) -> str:
"""Format an indexing element.
This is required mainly for slices. The reason is that string representation of slices
are very long and verbose. To give an example, `x[:, 2:]` will have the following index
... | 5b1e281fc503fcefa94835c3dbf1cd41abfa6588 | 639,680 |
import requests
def pay_paidgroup(group_id, eth_addr):
"""用户发起付款, 扫码成功付款后可查到付款情况
Args:
group_id (str): 组 ID
eth_addr (str): eth 地址
付费组在 RUM 是如何实现?用户加入 group, 利用该 api 发起付费,
将用户 eth 地址附在 memo, 在 RUM 发起 announce, owner 查询付费情况授权
返回值字段:
{'data': {'qrcode': <二维码>
'url': 'm... | 5ce5d8a24bbd400b2c5818dc173573f364c87c9f | 639,682 |
def indent_string(the_string, indent_level):
"""Indents the given string by a given number of spaces
Args:
the_string: str
indent_level: int
Returns a new string that is the same as the_string, except that
each line is indented by 'indent_level' spaces.
In python3, this can be done ... | d366395d81d6d9295a40c6a4894bd847d92c62d5 | 639,683 |
import argparse
def int_type(min_val, max_val):
"""
:param min_val:
:type min_val:
:param max_val:
:type max_val:
"""
def function1(argument):
"""
:param argument:
:type argument:
"""
try:
if argument.upper().startswith("0X"):
... | 85f60ab95cfa00046bf906f4a145cb6c8e67e2c1 | 639,684 |
def getSamplerFun(sampler, distributions):
"""
get distributions' function by class sampler.
Inputs:
sampler : sampler class, pydpm._sampler.Basic_Sampler;
distributions : [str] list of distributions;
Outputs:
funcs : {str: fun}, dict of distributions' functions;
... | d58c48f1b07884f6b3db43e2d0582099baaff846 | 639,685 |
def line_intersects_segment(line, line_segment):
"""Returns the intersection the Line and LineSegment or None if they do
not intersect.
This function is useful for splitting polygons by a straight line.
"""
linesegform = line_segment.to_line()
if line.is_parallel_to(linesegform):
retur... | 90739c66a3fa9abd0d360fdaf1807a3c27713f0a | 639,686 |
import sys
def _get_endianness_string( _map = { 'little' : 'NTEL', 'big' : 'UNIX' } ) :
""" check the endianness of the system """
# NB: Netstation also accepts 'MAC-' .
key = sys.byteorder
return _map[ key ] | d2b5d6afe39229812aa175f423ac21c439724856 | 639,688 |
import copy
def format_sriov_config(config):
"""
Converts a sriov_config resource dictionary to the equivalent puppet
resource definition parameters.
"""
sriov_config = copy.copy(config)
del sriov_config['ifname']
return sriov_config | 26107ca09d466f70ff1579c3f5975030ebea1976 | 639,689 |
import math
def calc_haversine_distance(p1, p2):
"""calculate haversine distance between two points
# formula info
# https://en.wikipedia.org/wiki/Haversine_formula
# http://www.movable-type.co.uk/scripts/latlong.html
Args
p1: tuple of (longitude, latitude) format containing int or float... | b90aa7be6aaf96ec379403d0b73f593db13dc4f4 | 639,690 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.