content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def chomp_lines(istream):
"""
Returns a lazy generator of lines without trailing newline characters from
the specified input stream.
"""
return (line.rstrip('\n\r') for line in istream) | 358d4c69bef724f871d573a43a68f59c8ed63853 | 681,805 |
import math
import collections
def get_number_of_letter_permutations(permute_word):
"""
Finds the number of permutations of letters in a given word
:param permute_word: a word to find permutations of
:return: number of permutations of letters in the word
"""
# find all letter combinations to g... | bf41297cd9aa4f2f6bd32d49443248c23cd15b1d | 681,807 |
import json
def load_hash(filepath):
"""
Load hashes from json file.
Parameters
----------
filepath : str
path to json file to be loaded
Returns
-------
dict { str : dict }
"""
with open(filepath, "r") as f:
return json.load(f) | 457cbdd6622e25d4db9fe92d04fc5ec61d14b60f | 681,808 |
def _snake_to_dromedary_case(string):
"""Convert snake_case to dromedaryCase.
>>> _snake_to_dromedary_case('snake_case')
'snakeCase'
>>> _snake_to_dromedary_case('longer_snake_case_name')
'longerSnakeCaseName'
"""
words = string.split("_")
if len(words) > 1:
words[1:] = [w.title... | 0bc40f5cfad61bb6421c3532207ba489b21da094 | 681,810 |
import math
def rat_from_rtc(rtc_s):
"""
Turn a real-time clock value into a radio time value
Args:
rtc_s: real-time-clock in seconds
Returns:
rat_s: radio time in seconds
rat_t: radio time in ticks
"""
# Updated assumed RAT tick based on RTC value (magic magic)
# ... | b4ec1cc05d980d4dbea22e245995ba3d91a6893f | 681,812 |
def _translate_keyname(inp):
"""map key names in settings file to key names in HotKeys
"""
convert = {'Escape': 'Esc', 'Delete': 'Del', 'Return': 'Enter',
'Page_up': 'PgUp', 'Page_down': 'PgDn', 'NUMPAD_ENTER': 'NumEnter'}
if inp in convert:
out = convert[inp]
else:
ou... | 37fc8863bd9ab9cede86b1601e49f7ac51a90baa | 681,813 |
import copy
import random
def sample_the_triplet(query_img, database, train_dict):
"""
Given the query to generate a triplet.
@input:
query_img: a `key` in the `category_dict`
database: a dictionay contains all images' paths
@output:
A list of the form [query, postive_sample,... | 0d011827d869f46b65e00319b9742c2eccf6ee38 | 681,814 |
from itertools import zip_longest
def grouper(n, iterable, fillvalue=None):
"""
Split an iterable in groups of max N elements.
grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
"""
args = [iter(iterable)] * n
if fillvalue:
return zip_longest(fillvalue=fillvalue, *args)
for chunk in zip_... | 321a19905603b40b19cdce932b913905c2cf2d83 | 681,815 |
def filter_func(bigrams):
"""
Given a list of bigrams from a review's text, returns true if the review is
incentivized by using a lookup list
:param bigrams: Bigrams from the review's text, lemmatized for better matching
:return: True if the review is incentivized, False otherwise
"""
# Tupl... | 5a0250c3f4d07dd21eb74d071b516efe256319ee | 681,816 |
import io
import os
import subprocess
def gawk(
script: str,
stdin: io.TextIOWrapper,
stderr: io.TextIOWrapper
) -> int:
"""Execute a gawk command in the current directory."""
command = f"gawk -f {os.path.dirname(os.path.realpath(__file__))}/{script}"
stderr.write(f"{command}\n")... | 7413ab1d7639c32e7e1f444983205557f5e8bea9 | 681,817 |
def addPEBranchUsage(err=''):
""" Prints the Usage() statement for this method """
m = ''
if len(err):
m += '%s\n\n' %err
m += 'Link a PE Checkpoint to a Task Branch(es) (TB) with a Team Branch (TmB) on Salesforce.\n'
m += '\n'
m += 'Usage:\n'
m += ' lnpechpnt [OPTIONS] ... | d22dd6259118f8a4939d0ef16b09c142c7cd099b | 681,819 |
import os
def testnodes_path() -> str:
"""Get the absolute path to ``gada_pyrunner/test/testnodes``.
:return: path to testnodes directory
"""
return os.path.abspath(
os.path.join(os.path.dirname(__file__), "..", "test", "testnodes")
) | 580dfb3eb6d25fa8196ba1466bf153f93b219dc1 | 681,820 |
def _get_vitals(sample):
"""Returns a summary of the sample"""
return sample.mean(), sample.std() | 1749611abde122f91d2edca42c0d6de671afe9fb | 681,821 |
def permutations(nums):
"""Given a list, return all the possible orderings in an array.
3 ingredients to Backtracking:
1. Goal - fill up a permutation
2. choices - unused values of nums
3. constraint - values that are already used
"""
def find_permutations(current, remaining, fo... | 784e645e53de63f7034338bbd30db277c31bed2c | 681,822 |
from typing import Set
import os
def get_archs(dist_dir: str) -> Set[str]:
"""Returns a set of architectures based on directory listing."""
result = set()
for file_ in os.listdir(dist_dir):
if "zip" == file_.split(".")[-1]:
if "mac" in file_:
result.add("macosx_10_7_int... | d16fa84b42e5b8df3162aa5f5a9daa61facd2539 | 681,823 |
def andGate(a, b):
"""
Input:
a, b
Two 1 bit values as 1/0
Returns:
1 if both incoming bits are 1 otherwise 0
"""
if a == 1 and b == 1:
return 1
else:
return 0 | 17c4f22a41946ef5193f7a9b38373fde2b87cae8 | 681,824 |
def get_default_config():
"""
Returns a default configuration.
"""
return {
"backup_path": "~/shallow-backup",
"dotfiles" : [
".bashrc",
".bash_profile",
".gitconfig",
".profile",
".pypirc",
".shallow-backup",
".vimrc",
".zshrc"
],
"dotfolders" : [
".ssh",
".vim"
],
"defa... | 3fe85eb7b03ee805405907e0409669a1e1d5f683 | 681,825 |
def gen_kv_dict(dt_data, key, col_names):
"""根据读取到的pkl对象, 返回主键到目标列值组成的字典. 可以同时指定多个列"""
assert isinstance(col_names, (list, tuple, str))
res = {}
if isinstance(col_names, str): # 值只有一列
key_idx = dt_data['cols'].index(key)
col_idx = dt_data['cols'].index(col_names)
for line in d... | 287742746571619fb3ea27875e0895cee79fbd00 | 681,826 |
def discrete_signal(signal0, step_size):
"""
Discretize the bet size, it is likely that small trades will be triggered with every prediction
:param signal0:
:param step_size:
:return:
"""
signal1 = (signal0/step_size).round()*step_size
signal1[signal1>1] = 1 # cap
signal1[signal1<-1]... | 0dbaa2a889c3025e98acbd3de222244561e5dd02 | 681,827 |
import torch
def select_device() -> str:
"""Selects the device to use, either CPU (default) or CUDA/GPU; assuming just one GPU."""
return "cuda" if torch.cuda.is_available() else "cpu" | eead9233b86887847d6a4aa837a78cfe0bbabaae | 681,828 |
def _normalize_integer_rgb(value: int) -> int:
"""
Internal normalization function for clipping integer values into
the permitted range (0-255, inclusive).
"""
return 0 if value < 0 else 255 if value > 255 else value | 1e765e74e1dfd029c14c8e6b9201bd814530b1ec | 681,829 |
def count_descendents(graph, root):
"""
Inputs: A weighted directed acyclic `graph` with positive edge weights and a starting `root` node
Let the weight of a path in the graph be the product of the weights of its constituent edges
and 0 if the path is trivial with no edges
Returns: The sum of the we... | 54c7320c1a009a7686e44d0f3f22a6107b3d10bf | 681,830 |
import re
def applyRegexps(text, listRegExp):
""" Applies successively many regexps to a text"""
# apply all the rules in the ruleset
for element in listRegExp:
left = element['left']
right = element['right']
r = re.compile(left)
text = r.sub(right, text)
return text | 50cc3b293eafd3be82c5ffae29dd316139d96802 | 681,831 |
def check_success_file(full_data):
"""Parse each s3 path to get _SUCCESS file for each path
Args:
full_data (s3_full_path): S3 list_objects full path;
Returns:
dictionary: dictionary containing hour(int):status(bool) mapping
"""
load_status = {}
for elt in full_data["Contents"]... | cd849b5523e357036317ab56e466be34f87d5a61 | 681,832 |
def is_multiple(n, divide):
"""
>>> is_multiple(0, 1)
False
>>> is_multiple(10, 1)
True
>>> is_multiple(10, 2)
True
>>> is_multiple(10, 3)
False
"""
return (0 != n) and (0 == (n % divide)) | afa052d81f20542494b446faa95b52330833ce23 | 681,833 |
import csv
def detect(stream):
"""Returns True if given stream is valid CSV."""
try:
csv.Sniffer().sniff(stream, delimiters=',')
return True
except (csv.Error, TypeError):
return False | 92dfeb58c4505fd9843ec1463ba6ae88349dd8d9 | 681,834 |
def temp_rh(cube):
"""
Perform simple arithmetic with variables
:param data: a dictionary of variables and their data
:return: result of equation, name of results, unit
"""
# Perform equation wirh temperature and salinity
result = cube['temp'].data - cube['rh'].data
name = 'diff_temp_rh'
... | f8f6bd5489af952c9918009f93b80f9dc62b20e1 | 681,835 |
from typing import List
def rotate90(buttonsIdx: List[int]) -> List[int]:
"""
Rotate puzzle by 90 degrees counterclockwise.
:param buttonsIdx: list with position index for each button and empty cell
:returns: list with positions after rotation
"""
newButtonsIdx = []
for i in buttonsIdx:
... | 2b7b09a1e5aec3f09e2226bc1bdd0363a4f13511 | 681,836 |
import decimal
def nth_fib_without_precision(x, _len):
"""Calculating nth term through Binet's formula with no accurate precision (incorrect digits after 13th)"""
nth_fib = (
(1 + decimal.Decimal(5).sqrt()) ** x - (1 - decimal.Decimal(5).sqrt()) ** x
) / (2 ** x * decimal.Decimal(5).sqrt())
re... | 2cc70d38d56022c0af95274c3f118c05a033d1e9 | 681,837 |
import os
import six
def validate_requirements(req, cython_required):
"""Validate the package requirements.
Validate and format the package requirements to get a new-line separated
list of requirements to write to requirements.txt. Also, since Numpy is
required to build the package that's generated, ... | 361825982e99b7e2eaf795c73e828a79707c5fa8 | 681,838 |
def get_equivalence_ratio(
p_fuel,
p_oxidizer,
f_a_st
):
"""
Simple equivalence ratio function
Parameters
----------
p_fuel : float or un.ufloat
Partial pressure of fuel
p_oxidizer : float or un.ufloat
Partial pressure of oxidizer
f_a_st : float or un... | c07a853bfc517ad980cc34f0a66a67a24b16fbc3 | 681,839 |
def sv_length(pos, end, chrom, end_chrom, svlen=None):
"""Return the length of a structural variant
Args:
pos(int)
end(int)
chrom(str)
end_chrom(str)
svlen(int)
Returns:
length(int)
"""
if chrom != end_chrom:
return int(10e10)
if svlen:
... | 4a15ba3f718323fd52ce1b55157189b4978dee17 | 681,840 |
import socket
def gethostname():
"""try to get docker host's hostname rather than container hostname first"""
try:
with open('/etc/host_hostname', 'r') as fd:
return fd.read().strip('\n ')
except Exception as e:
return socket.gethostname() | f037e4f0e2d29e900903df2f59852025ed2ee3b3 | 681,841 |
import re
def find_school_year_in_filename(name):
"""
finds year and school year embedded in name of file if it exists in filename
school_year taken as the range of YYYY-YYYY, year taken as the first YYYY segment
:param name: filename of input file
:type name: string
:return: year, school_year... | 879c283f618b24de894b4dd2ae1b78a520b2e2f5 | 681,842 |
def _step_summary(step_list):
"""Creates a single string representation of the step status
Success/Failed/Other counts in each position
"""
successes = 0
failures = 0
other = 0
for s in step_list:
state = s.get('state')
if state in ['success']:
successes += 1
... | d85335c444b887d3c7f5f3aa9b1c5a2362640197 | 681,843 |
import os
import codecs
import re
def find_version(*file_paths):
"""Recommended way of getting the version without importing swimpy from
https://packaging.python.org/guides/single-sourcing-package-version"""
fp = os.path.join(os.path.abspath(os.path.dirname(__file__)), *file_paths)
with codecs.open(fp... | 5f90f6336692a4def88bb5c0b0e4e542958d7790 | 681,844 |
import torch
def generator_loss_adv(sharp_scores, deblur_scores, SampleScores):
"""
Computes the DoubleScale RaGANLS Generator Adverseraial Loss
"""
# Compute the generator loss using
# Paper:
# The relativistic discriminator: a key element missing from standard gan. arXiv preprint... | 4ca72b3aa936b2cb653dab629978d18b0bf66ee4 | 681,845 |
def sampling(generate_data, nb_samples):
"""
Generates nb_samples from generate_data
:param generate_data: Function that takes takes an integer n and samples from a synthetic distribution.
Returns an array of n samples.
:param nb_samples: Number of samples to generate
:retu... | c6cb5b133500f2292d3303db1c28c60c415c097e | 681,846 |
def identity(x, name=None):
"""Returns a tensor with the same content as the input tensor.
# Arguments
x: The input tensor.
name: String, name for the variable to create.
# Returns
A tensor of the same shape, type and content.
"""
return x.copy(name=name) | ca7da1887b4bcd8db740f7aabb8a36ae6fde2486 | 681,847 |
import math
def same_padding(in_dim, kernel_dim, stride_dim):
"""
Calculates the output dimension and also the padding required for that dimension.
:param in_dim: Width/Height of Input
:param kernel_dim: Width/Height of Kernel
:param stride_dim: Vertical/Horizontal Stride
"""
output_dim = ... | 48c39b0f3b490028ae06b5474101f42db612b761 | 681,848 |
def parameters_equal(a, b):
"""Compares two parameter instances
Checks full name, data, and ranges. Does not consider the comment.
:return: True or False
:raises: ValueError if both inputs are no parameter instances
"""
if (not b.v_is_parameter and
not a.v_is_parameter):
... | 0eb019fb340c5baeaf270c7c53ee4a2cb1b94eaa | 681,849 |
def binary_string(number: int) -> str:
"""Number to binary string
:param number: some number (an integer) to turn into a binary string
:return: Some string which is the binary string
:rtype: str
.. doctest:: python
>>> binary_string(200)
'11001000'
>>> binary_string(10)
... | aa22bcc4ddd5546805db333c9b0be2e7f0e1c703 | 681,850 |
from typing import List
def moeglichkeiten(flaschen: int, kisten: List[int]) -> int:
"""
Bestimmt die Anzahl der Möglichkeiten die Flaschen zu verteilen.
:param flaschen: Anzahl der Flaschen, die verteilt werden müssen.
:param kisten: Liste mit den Größen der Kisten.
:return: Anzahl der Möglichkei... | ca5d41551fa5ceee0ef5c37ea54be5ba4dfe20f7 | 681,851 |
def get_ytid2labels(segment_csv):
"""
compute the mapping (dict object) from youtube id to audioset labels.
"""
with open(segment_csv) as F:
lines = F.read().split('\n')
lines = [l for l in lines if len(l) > 0 and l[0] != '#']
ytid2labels = {l.split(',')[0]: l.split('"')[-2] for l in li... | 9afcb0637f338977e7107dd6e5445ec8e29a0abe | 681,852 |
def get_bind_addr(conf, default_port=None):
"""Return the host and port to bind to."""
return (conf.bind_host, conf.bind_port or default_port) | e7791a9eafd0b2386f92755a8a8d3dddd70d52ce | 681,854 |
def _part(f):
"""
Return a character representing a partly-filled cell with proportion
`f` (rounded down to width of nearest available character).
"""
return [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉", "█"][int(9*f)] | 5919707099b8bd09467056a770a6b8904a991c32 | 681,855 |
def join_infile_path(*paths):
"""
Join path components using '/' as separator.
This method is defined as an alternative to os.path.join, which uses '\\'
as separator in Windows environments and is therefore not valid to navigate
within data files.
Parameters:
-----------
*paths: all str... | 5bd109b5708fe48c5f9a8e2e3c418ab62ace23bb | 681,856 |
def get_latlon_from_cube(cube):
"""Return domain covered by cube, taking into account cell boundaries
:param cube: target cube
:return: tuple(lat_max, lat_min, lon_max, lon_min, nlat, nlon)
"""
for latlon in ['latitude', 'longitude']:
if not cube.coord(latlon).has_bounds():
cube... | 5c49a6fbfb94962f4d39061252898dc1f0776ad1 | 681,857 |
def wait_timer(index: int, time: int):
"""Wait for timer."""
return f'B;WaitTimer("{index}","{time}");'.encode() | 86a4525febc90d87531e46e7910cd293623b4a9b | 681,858 |
def trapezoid(poly, lower, upper):
"""Calculate trapezoid slice from two polynomial evaluations and step size"""
lower_value = poly.evaluate(lower)
upper_value = poly.evaluate(upper)
return (upper - lower) * ((lower_value + upper_value)/2.0) | 777a4f569506524e57f979192467414509318f95 | 681,859 |
def loadVocabWithCount(fileName):
"""
This function can load the existing vocabulary file, and return a vocabulary dict with vocabulary count
paramIn@ fileName the vocabulary file name
return@ vocabDict the vocabulary dict load from file
"""
vocabDict = dict()
fp = open(fileName, 'r')
for line in fp.readlin... | b2dc09df6ad233b132c58b6c3e47ccf552216093 | 681,860 |
def check_size_pdf(input_pdf):
"""
- checks to see if pdf is over 50 mb
"""
return input_pdf.stat().st_size > 49000000 | bf0cd1d07bf1c42e57e4e0803652355a2e662f42 | 681,861 |
def set_dict_indices(my_array):
"""Creates a dictionary based on values in my_array, and links each of them to an index.
Parameters
----------
my_array:
An array (e.g. [a,b,c])
Returns
-------
my_dict:
A dictionary (e.g. {a:0, b:1, c:2})
"""
my_dict = {}
i = 0
... | c9e0b05f4eeeef04f1fc42cdc06cf61f0f9b2e70 | 681,862 |
import argparse
import sys
def parse_arguments():
"""
Parse command line arguments and return them
:return: command line arguments
"""
parser = argparse.ArgumentParser()
parser.add_argument('--all', help='test all operators', action="store_true")
parser.add_argument('--binarize_cols', help... | ce0b7e2a1bc76f8f30487bec37c875cc81818a4f | 681,863 |
def NER_space_word_tokenize_string(s, tokenizer):
"""
This method is used to tokenize a string in a way that matches AllenNLP's NER predictor,
making use of an allenNLP's tokenizer's tokenize method.
:param s : The string to be space tokenized.
:param tokenizer: The tokenizer that will be ... | 971a795812f1ef15de32d90d8ee45fdbf483156c | 681,864 |
def get_day_of_the_week_number_from_datetime(datetime_obj) -> int:
"""Does what the function title states."""
return datetime_obj.weekday() | f39ef66090501da260b698901bc35b23d224a363 | 681,865 |
from numpy import memmap,uint16
def Rayonix_roi_read(image_file,rmin,rmax,cmin,cmax):
"""Returns region of interest (roi) sub image from Rayonix image via
memory mapping. With NumPy indexing, the origin (image[0,0]) is found at
the top-left corner and corresponds to the geometric center of that pixel.
... | e7f8e04e3ccd02b56c7d8a5b4df30d8ba6a91954 | 681,866 |
def search2(value, arr):
"""
Experimental implementation of binary search using recursion.
Not very good solution because of recursion. It may lead to stack
overflow on big arrays.
:param value: Value to search.
:param arr: Array to search in.
:return: Index of found element or -1 if no elem... | f1ec803023620523fb1446dab141758b9e9c2c36 | 681,867 |
def clean_data(df):
"""
Clean a DataFrame track. This function is under development.
Parameters
----------
df : pandas DataFrame
DataFrame to clean. Currently, only missing points are deleted.
Returns
-------
df : pandas DataFrame
Cleaned DataFrame.
"""
# Fill N... | 89efc2d71840bd1edea55d5c3bb4b0acf57bb7d9 | 681,868 |
import os
def get_model_path():
"""Generating model path for save/load model weights.
outputs:
model_path = os model path, for example: "models/blazeface_model_weights.h5"
"""
main_path = "trained"
if not os.path.exists(main_path):
os.makedirs(main_path)
model_path = os.path.j... | e309fff6b1dd79d57f9d3504f01e6de97fc6cb50 | 681,870 |
def index():
"""This is main request of this application containing instruction how to use it"""
message = "Welcome to this simple Darts Checkout REST API!"
return message | 331524d53fae4826f1f8ed4d0a0862678c155c4e | 681,871 |
import configparser
def get_config(filepath):
"""Pull configuration settings from the configuration file."""
config_file = open(filepath)
config = configparser.ConfigParser()
config.read_file(config_file)
return config['precommit'] | fe8ca7e36cefc4b0f8f9a2cd8f22a5bd07fd08cb | 681,873 |
import logging
def setup_logging(args):
"""Setup logging for the application"""
log = logging.getLogger(__package__)
log.setLevel(args.loglevel)
# disable root logger handlers
root_logger = logging.getLogger()
root_logger.handlers = []
# set log output destination
if args.logfile:
... | ee28234842897f194b300878cdc7ca0ad738f1fd | 681,874 |
def count(val, iterable):
"""
Counts how many times a value (val) occurs in an iterable, excluding `None`
:param val: The value to be counted
:param iterable: values to be counted over
:type iterable: iterable
:return: the count of values
:rtype: int
"""
return sum(1 for x ... | 59fc5ad8c8ad233f00c0f4d000242db92af6c457 | 681,875 |
def get_coreference(pronoun):
"""Implement if time -> pronoun get document coreference with neuralcoref"""
return 0 | 2a7c407a13267607d7404851f56e65930da3dff3 | 681,877 |
def calcsize(values, sizerange=(4, 70), inds=None, plaw=2):
""" Use set of values to calculate symbol size.
values is a list of floats for candidate significance.
inds is an optional list of indexes to use to calculate symbol size.
Scaling of symbol size min max set by sizerange tuple (min, max).
p... | 9b4164faac8e0ec666c492eb2ae759753c1a968a | 681,878 |
from typing import Optional
from typing import Any
def use_defaults_in_missing_fields(data: dict) -> bool:
"""Sets missing field values to `None`, so :class:`.ClientConfig`
and its components can fill out the defaults.
Returns `True`, if any changes were made.
:param data: json to deseria... | 17d13e96699f56bb6ac786990680f894d317ddad | 681,879 |
def format_metrics(metrics, split):
"""Formats metrics for logging.
Args:
metrics: Dictionary with metrics.
split: String indicating the KG dataset split.
Returns:
String with formatted metrics.
"""
result = '\t {} MR: {:.2f} | '.format(split, metrics['MR'])
result += 'MRR: {:.3f} | '.format(m... | c3c42afb289149585506b0548910c213cf745222 | 681,880 |
def querystring(request, **kwargs):
"""
Append or update the page number in a querystring.
"""
querydict = request.GET.copy()
for k, v in kwargs.items():
if v is not None:
querydict[k] = v
elif k in querydict:
querydict.pop(k)
querystring = querydict.urlen... | d7425e7767ba795f4509fd4030796f19781ca841 | 681,881 |
import json
import gzip
import base64
def encode(value, compress=False):
"""Converts dict to JSON and encodes it to Base64."""
encoded = json.dumps(value, separators=(",", ":")).encode()
if compress:
encoded = gzip.compress(encoded)
return base64.b64encode(encoded).decode() | 25ed0fe45f9ce4e9c54d04bb2b575019c02cef01 | 681,882 |
def frac(h,w,n=5):
"""
This function takes an image shape as input (h,w) and a integer n. It returns
the closest image shape (h_out,w_out) of the original one such that h_out < n
and w_out < n.
We can then cut the image in h_out*w_out pieces.
examples:
frac(500,375,5) returns (4,3)
frac(... | 7a104d4996a62acc2beff2e13d048969580126b8 | 681,883 |
def cal_item_pos(target_offset, idx_list):
"""Get the index list where the token is located"""
target_idx = []
for target in target_offset:
start, end = target[1], target[2]
cur_idx = []
for i, idx in enumerate(idx_list):
if idx >= start and idx < end:
cur... | c6e5f6796d6ffd86d573e90ab24dd86ea30765ba | 681,884 |
def fibonacci_sequence(size):
"""fibonacci
"""
sequence = []
for n in range(size):
if n == 0:
sequence.append(1)
elif n == 1:
sequence.append(1)
else:
sequence.append(sequence[-1] + sequence[-2])
return sequence | ed86b1db695a44c4b1bc512899eb1422641a8427 | 681,885 |
import argparse
def parse_args():
"""Pass command line arguments"""
parser = argparse.ArgumentParser()
parser.add_argument('-j', '--jbrowse_dir', help='jbrowse directory', default='/Applications/MAMP/htdocs/jbrowse/')
parser.add_argument('-i', '--input_dir', help='input directory')
parser.add_arg... | 605963dd2dbdfe0b1c242997053476e8063f4486 | 681,887 |
def word_count(review_str)->int:
""" count number of words in a string of reviews
"""
return len(review_str.split()) | 5a980f7252f3cd840d92726e475360d0b50fab05 | 681,888 |
def _kl_normal_loss(mean, logvar, storer=None):
"""
Calculates the KL divergence between a normal distribution
with diagonal covariance and a unit normal distribution.
Parameters
----------
mean : torch.Tensor
Mean of the normal distribution. Shape (batch_size, latent_dim) where
... | 343cf098c00be7407a0e48bb3c53e449228c32c7 | 681,889 |
import torch
def index2points(points, idx):
"""Construct edge feature for each point
Parameters
----------
points: (batch_size, num_dims, num_points)
idx: (batch_size, num_points) or (batch_size, num_points, k)
Returns
-------
edge_features: (batch_size, num_dims, num_points) or (bat... | 0a730ba273582ab1c82e8f743ba9ef96599c3c39 | 681,890 |
from typing import IO
def read_line(in_fd: IO[str]) -> str:
"""
Reads a single line from a file in bytes mode
:param in_fd: Input file descriptor
:return: The line (from in_fd current position), without EOL
"""
result = []
while True:
# Ignore the first line
read_char = in... | 310ab4f74d89f49cfa503aaa30dd08f252a09aaf | 681,891 |
import math
def get_int(celda):
"""Convierte el valor de una celda en entero"""
if celda.value == '':
return 0
try:
if celda.ctype != 2:
return 0
return math.ceil(celda.value)
except ValueError:
return 0 | 7c069f2ce108f5ac51958eecdc5c9c46ce08194e | 681,892 |
def compute_Cp(T,Cv,V,B0,beta):
"""
This function computes the isobaric heat capacity from the equation:
:math:`Cp - Cv = T V beta^2 B0`
where *Cp,Cv* are the isobaric and isocoric heat capacities respectively,
*T* is the temperature, *V* the unit cell volume, *beta* the volumetric
thermal... | 68504262c4bd49ef87b4ffcb4f09f75722f788c0 | 681,893 |
def _architecture(target):
"""Returns architecture for current active target, e.g. i386, x86_64, armv7"""
return target.GetTriple().split('-', 1)[0] | ad403b92ae3cb14379970a98f7eb6bcc69d2542f | 681,895 |
def get_hello():
"""
summary: return string hello
"""
return "hello" | 650e3579ec39559143c1d836e7f88810b84db799 | 681,896 |
def is_same(answer, number):
"""
answer, number가 같은지 출력
"""
answer_list = list(answer)
number_list = list(number)
check_list = {"ball" : 0, "strike" : 0}
for i in range(len(number_list)):
if number_list[i] in answer_list:
if number_list[i] == answer_list[i]:
... | 0c128c5d10a2fddeadcfa7019e97c827daa904ad | 681,897 |
import torch
def _tokenize_str(string, char_tensor=None):
"""
Parses a utf-8 encoded string and assigns to ByteTensor char_tensor.
If no char_tensor is provide one is created.
Typically used internally by `tokenize_str_batch`.
"""
if char_tensor is None:
char_tensor = torch.ByteTensor(len(string.encode()))
f... | 047fb42570978c0cb0613ddd93afebc52fb0a57f | 681,898 |
import logging
def is_encoded_image_spec(tensor_spec):
"""Determines whether the passed tensor_spec speficies an encoded image."""
if hasattr(tensor_spec, 'data_format'):
# If tensor_spec is an ExtendedTensorSpec, use the data_format to check.
return (tensor_spec.data_format is not None) and (
ten... | a5e5376961f8e26f088aef4db0aa8460673b2839 | 681,899 |
def colour_linear_interpolation(col_a, col_b, t):
"""
Linearly interpolates between two colours.
"""
col = tuple([a + (b - a) * t for a, b in zip(col_a, col_b)])
return col | 411456a3ecdff685302d50b906f9933ff46aa931 | 681,901 |
def is_valid_instant(x):
"""
Returns true iff x is a well-shaped concrete time instant (i.e. has a numeric position).
"""
try:
return hasattr(x, "inTimePosition") and len(x.inTimePosition) > 0 and \
len(x.inTimePosition[0].numericPosition) > 0
except TypeError:
return ... | 920aff48da7747aac4350a0a977f40899d57e1ca | 681,902 |
def block_level_whitelist():
"""Elements that we will always accept."""
elements = ['article', 'aside', 'blockquote', 'caption', 'colgroup', 'col',
'div', 'dl', 'dt', 'dd', 'figure', 'figcaption', 'footer',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'li', 'main',
... | 41ef564bb40c84fb81d1033ff4863880a593c564 | 681,903 |
def MakePreservedState(messages, preserved_state_disks=None):
"""Make preservedState message for preservedStateFromPolicy."""
preserved_state = messages.PreservedState()
if preserved_state:
preserved_state.disks = messages.PreservedState.DisksValue(
additionalProperties=preserved_state_disks)
return... | ecdf9c7f0da7ddbfa0e4d31148cbbcdff25f4835 | 681,904 |
def _amp_ ( self , x , *a ) :
""" Get the complex value for amplitude
>>> fun
>>> a = fun.amp ( x )
"""
v = self.amplitude ( x , *a )
return complex( v ) | 0eeaf902ec7cf4ddacb1127fcce8c6f4795fc1fc | 681,905 |
def truncate_val(val, lower_bound, upper_bound):
"""Truncate val to be in the range [lower_bound, upper_bound]."""
val = max(val, lower_bound)
val = min(val, upper_bound)
return val | fb5438c7687d7e69efbf4fd061c85178f9b2f9a1 | 681,906 |
def _access(*args, **kargs):
"""Assume access to the path is allowed."""
return True | 99d8a326a34eed5bdeb1a32d285d81f14470af02 | 681,907 |
def mk_wxid(id):
"""Creates wxWidgets library identifier from bakefile target ID that
follows this convention: DLLs end with 'dll', static libraries
end with 'lib'. If withPrefix=1, then _wxid is returned instead
of wxid."""
if id.endswith('dll') or id.endswith('lib'):
wxid = id[:-3... | 6779e2812158f3f5a8206fdbb6cec64a4b65dbd2 | 681,908 |
def _shapeString(ob):
""" _shapeString(ob)
Returns a string that represents the shape of the given array.
"""
ss = str()
for n in ob.shape:
ss += '%ix' % n
return ss[:-1] | 0e796c2de9e5d726159c01b70e8209e816d4f757 | 681,909 |
from pathlib import Path
import os
def privoxy_blocklist():
"""return the path to privoxy-blocklist.sh"""
for known_path in [
"./privoxy-blocklist.sh",
"/privoxy-blocklist.sh",
"/app/privoxy-blocklist.sh",
]:
path = Path(known_path)
if path.exists() and path.is_file... | 3ca7ac8804cb56ec6f580f93a8cd8afd633449a7 | 681,910 |
import re
def custom_exclude_filters(user_input, node, filter_list_exclude, exclude_name_for_log, filter_list_include):
""" Figure out custom global/system filter includes and excludes """
if user_input.removed_titles.get(exclude_name_for_log) == None:
user_input.removed_titles[exclude_name_for_log] ... | 4e788008d9af38958876b43f3073b1b2fcea44b2 | 681,911 |
import json
def loadJson(file_path):
"""
loads json serializable object
file_path could be r'C:\Desktop\FILENAME.txt'
"""
with open(file_path, 'r') as file:
json_obj = json.load(file)
#return json.loads(json_obj) # converts string to python object
return json_obj | ff349d512d6df33173e3e4dcecf50f7738d0bd19 | 681,913 |
def S_get_histogram_values(_data_list, _level=0.1):
"""
Finds the groups present for given data samples
Groups will be divided based on value difference as set by level parameter
"""
ds = len(_data_list)
if ds < 1:
return []
s_data = sorted(_data_list)
bins = []
bin_curso... | eb67ab38b73ff0f00561ce6096adee538eff9aa0 | 681,914 |
import binascii
def printFullCombinedInfo(ui, repo, **opts):
# The doc string below will show up in hg help
"""Print consildated information about the repository.
Print the tip, parents, local tags, global tags, bookmarks,
active branches, inactive branches, closed branches, and open heads"""
# ... | bf77a9aee8af2e65926fc1e61d36381c14ce0b25 | 681,916 |
import sys
def os_specific_cmake_flags():
"""CMake args that should be passed to all benchmarks on current OS."""
if sys.platform == "win32":
return ("-A", "x64", "-Thost=x86",
"-DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded",
"-DCMAKE_SYSTEM_VERSION=10.0.19041.0")
elif sys.platform.star... | 5b7cacbbd3963a6a0e760bf825cc2f2e64972dae | 681,917 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.