content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def is_power_of_two_brian_kernighan(number):
"""Checks whether a given integer is a power of 2
It uses the Brian Kernighan algorithm used to count the set bits.
We know that powers of 2 only have 1 set bit.
e.g 2^0 = 1, 2^1= 10, 2^2= 100 ...
By applying a bitwise & to the given integer and the nex... | 7406bf475d82909eacc42f8fdac9fb81ac141103 | 588,308 |
def leave_only_keys(*keys):
"""
A function to leave only the specified keys in the dictionary.
"""
def filtered(dict_):
"""
Filter a dictionary by keys.
"""
return {
key: dict_[key]
for key in keys
if key in dict_
}
return... | 6f15b12c6e1c655a430b9d32ecee74f08144bcfd | 588,314 |
import itertools
import operator
def invert_otm_mapping(mapping):
"""Inverts a one-to-many mapping."""
# Create a list of inverted (v, k) tuples.
tuples = (itertools.zip_longest(v, [k], fillvalue=k)
for k, v in mapping.items() if len(v) > 0) # yapf: disable
tuples = itertools.chain.from... | e4d3d0449f7b7e87ff00447228653788805a5a6d | 588,316 |
import re
def split_units(value):
"""
Split string dimensionful value.
Return tuple ``(val, unit)``, where ``val`` is the float part of the value, and ``unit`` is the string representing units.
"""
m=re.match(r"([+-.\d]+)\s*([a-zA-Z]*)$",value)
if not m:
raise ValueError("can't parse ... | ea3faeaf9f725a56d86690424f8e93439e561a4f | 588,319 |
import math
def length_of_segment(index_pair):
"""Returns the length in base pairs between two indices (inclusive)."""
return math.fabs(index_pair[1] - index_pair[0]) + 1 | 9f002e63d6e186869a650e24def22b4432b1f822 | 588,320 |
import json
def parse_file(filepath: str) -> dict:
""" Parses a file in the actions folder and returns dict. """
f = open(filepath, "r")
return json.load(f) | e0cb08fadd002125f91c571768cf4f04ef7900b4 | 588,321 |
def col_names_conn_matrix(n: int,
preprocessing_type: str = 'conn'):
"""
creates the column names for the flattened connectivity matrix
Args:
n: number of columns in connectivity matrix
preprocessing_type: conn for connectivity matrix,
"aggregation" fo... | 6e3752f178a6bd4d1c3828698bfe3c357c8c6e79 | 588,324 |
def trim_base(full_tour):
"""
Trims start/end city from tour and returns the trimmed
tour and the base city.
E.g. Passed a full symmetric tour [0, 1, 2, 0]
trim_base returns two objects:
trimmed_tour = [1, 2]
base_city 0
"""
base_city = full_tour[0]
trimmed_tour = f... | b5ac71d4b689c6a0390066f8ce82cc27e20899f2 | 588,336 |
import pickle
def load_tag2id(tag2id_filepath):
"""
Load the dictionary mapping from tag to id
:param tag2id_filepath: the file path to the pre-built dictionary
:return: the dictionary mapping from tag to id
"""
with open(tag2id_filepath, "rb") as fr:
tag2id = pickle.load(fr)
retu... | 75fba0d959e61a66d40d4fa4d61420ffc3db4940 | 588,339 |
import torch
def _L1(tensor: torch.Tensor):
"""
Calculates the L1 loss
"""
tensor = torch.abs(tensor)
tensor = tensor.mean()
return tensor | 9c1aba496846eb7de6c675db6b46c1b558c8b558 | 588,340 |
def parse_variable(line):
"""Parse a variable line from CDL"""
line = line.replace('(', ' ')
line = line.replace(')', ' ')
line = line.replace(',', ' ')
words = line.split()
nctype = words[0]
name = words[1]
shape = tuple(words[2:])
return name, nctype, shape | f81b3c13f5abbe0d2aae704671e9f10e0ba7081a | 588,341 |
import heapq
def _prune_branches(beam_entries, k):
"""Prune all but the `k` sequences with highest score from the beam."""
indices = heapq.nlargest(k, range(len(beam_entries)),
key=lambda i: beam_entries[i].score)
return [beam_entries[i] for i in indices] | c4336fac55a46c0d051f6d12d69ff73238e53712 | 588,344 |
def get_unique_list(predictors):
""" Return a list of unique predictors. Two Predictors are equal if they have the same name."""
results = []
for P in predictors:
#if not P.name in [p.name for p in results] : results.append(P)
if P not in results : results.append(P)
return results | b45466f80e9643b129b559ee647c896d157e637c | 588,351 |
import re
def clean_dirty(value):
"""Given a dirty literal string, clean up repeated occurrences of
'[object Object]."""
return re.sub(r'(?:\[object Object]){2,}', '[object Object]', value) | 5ca86a38fc42ede1843c1106768229e50ed5635a | 588,353 |
def fallback_aggregation(values) -> str:
"""
Fallback aggregation where values are simply joined into a string.
"""
return str(values) | 2bb883bed3d76ac1580d19b335f6e063031fe135 | 588,356 |
import json
def get_output_altering_options(config_txt):
"""
:param config_txt: serialized json dictionary containing an agent's
configuration. Its 'output_altering_options' key lists other keys that
contain configuration parameters that influence the agent's output.
Returns a string describing o... | 38481351b6a7981d9408a5ebeb715b0704fb5338 | 588,357 |
import struct
def is_little_endian(endian):
""" Determine whether the give endian is little or not on the host machine. """
if endian == '<':
return True
return struct.pack(endian + 'H', 0x00FF) == struct.pack('<H', 0x00FF) | 404932834ddcc2773873289e84c860da2b07dd1f | 588,360 |
def to_pipeport(dp):
"""
Convert a physical 9-bit (devport) number into (pipe, port) pair
NOTE: For now this is a Tofino-specific method
"""
return (dp >> 7, dp & 0x7F) | d9437ea3a96e63eee5a336038a20e5cbe059e6ab | 588,361 |
def concatenate_timestreams(ts_lst, ts_rounding_error=0.6, ts_interp_threshold=0):
"""
Concatenate G3Timestream or G3TimestreamMap objects together.
Arguments
---------
ts_lst : list
list of G3Timestream or G3TimestreamMap objects. Must all be
the same type.
ts_rounding_error :... | 4a0664508f6c72a68587025d9a835e871a66c35b | 588,364 |
def add_three(n):
"""Add three to a number."""
return n + 3.0 | a1d17b50cff03b08f5793750cf542859c3ea3199 | 588,370 |
def reduce_id(id_):
"""Reduce the SsODNet ID to a string with fewer free parameters."""
return id_.replace("_(Asteroid)", "").replace("_", "").replace(" ", "").lower() | 8f6d236030bb6304af04808cdabc6a15c06aeb40 | 588,372 |
import typing
def identifier_path(it: typing.Union[typing.Type[object], typing.Callable]) -> str:
"""Generate an identifier based on an object's module and qualified name. This can
be useful such as for adding attributes to existing objects while minimizing odds
of collisions and maximizing traceability ... | 6702c0d98c93d5ffbccbef4bdbca9884302358f6 | 588,377 |
def interpret_line(line, splitter=','):
"""
Split text into arguments and parse each of them to an appropriate format (int, float or string)
Args:
line: text line
splitter: value to split by
Returns: list of arguments
"""
parsed = []
elms = line.split(splitter)
for elm i... | 0f51c08484dfd126b59d89231b072523fea4e72a | 588,378 |
import csv
def get_data(filename):
"""
Get occurrence_data from csv <filename> as a nested list, one list for each line.
:param filename: (str) file path to open
:return: (list) file contents as nested list
"""
with open(filename, newline='', encoding='utf-8') as csvfile:
infile = csv.... | 11d23468c6d687908ab86217b2c6903a5d694dff | 588,381 |
def list_to_num(l):
"""
Concatenate list of numbers & returns the number.
"""
s=''
for i in range(len(l)):
s+=l[i]
return int(s) | 7af2a6b993ab4201905ebd448d3f487f1bac0754 | 588,382 |
def filter_points(data, extent):
"""
Filter points that are within the extent
Parameters:
-----------
data: [[]]
A 2D numpy array containing x,y values
extent: [x_start, x_end, y_start, y_end]
The region we want to return points within
Returns
-------
data: [[]]
... | 6a4879783538fe64a960a2172852667bb5d1eb47 | 588,385 |
def pd_reindex(data, index):
"""Reindex with automatic level selection
Parameters
----------
data: pandas.Series, pandas.DataFrame
index: subclass of pandas.Index
Returns
-------
reindexed: same type as `data`
"""
try:
return data.reindex(index, level=index.names)
e... | 5c29563a1d8c220a70952959b15402c7ef5c474e | 588,392 |
import hashlib
import six
def get_text_sharder(num_shards):
"""Returns a deterministic string-sharding function."""
def sharder(text):
return int(hashlib.md5(six.ensure_binary(text, 'utf-8')).hexdigest(),
16) % num_shards
return sharder | 73dc64a1c9158c804c29089d893004e1ae5e3094 | 588,393 |
def deploy(cloud_formation_script, stack_name, cf_resource):
"""
Deploys scaffold resources used by the example. The resources are
defined in the CloudFormation script. They're deployed as a CloudFormation stack
so you can manage and destroy them by using CloudFormation actions.
:param cloud_format... | 58689e01551cfedfce99cb8c3209d7579eb97135 | 588,394 |
import requests
def _get_federation_info(address_or_id, federation_service, fed_type='name'):
"""Send a federation query to a Stellar Federation service.
Note: The preferred method of making this call is via
:function:`federation`, as it handles error checking and parsing of
arguments.
:param st... | f812a40a66ae213613c1b46bc795bd170e02eb89 | 588,397 |
def getDomainLabel(state, maze):
"""
Return the domain LABEL (not index).
:param state: state tuple
:param maze: maze parameters
:return: the domain LABEL
"""
assert len(state) == 2 and state not in maze.WALL_STATES, 'ERROR: Cannot get domain for a wall state.'
if state in maze.WALL_ST... | 34818f7f09f6b837e62cf82643e3b5ee5a2c3d3c | 588,398 |
def check_to_avoid_overwrite(thing_to_check):
"""Makes a decorator which makes sure 'thing_to_check' is None before running func."""
def _decorator(func):
def careful_func(*args, force_overwrite=False, **kwargs):
if force_overwrite:
func(*args, **kwargs)
else:
... | 2284b0aeb3946434ce10f2c934cd3c3cb30a0e9b | 588,401 |
def fully_connected_forward(x, w, b):
"""
Forward pass for the fully connected layer.
Arguments:
x: numpy array of image input with shape (N, d1, d2,..., dc)
w: numpy array of weight matrix with shape (D, B)
b: numpy array of bias with shape (B,)
Outputs:
... | dbdb58bee9e58a87f39cb0353578931e8172dc70 | 588,403 |
def startwith (pool, term, case_sensitive = True, unique = False):
"""Look in a set of strings for ones that start with a given string.
startwith(pool, term, case_sensitive = True, unique = False) -> match(es)
pool: the set of strings to search in.
term: the string to match against.
case_sensitive: whether to do ... | e00d9b6973f8790df98d57781a89a9c20a71bd33 | 588,406 |
def get_authority_records(entity, authorities):
"""Return a QuerySet of authority records available to entity
and which are associated with one of the authorities."""
return entity.get_authority_records().filter(authority__in=authorities) | 1ea15358c91d9f468b4a67614f470aa1d3f542b4 | 588,409 |
def remove_extension(filepath):
"""Removes all extensions of the filename pointed by filepath.
:Example:
>>> remove_extension('home/user/t1_image.nii.gz')
'home/user/t1_image'
>>> remove_extension('home/user/t1_image.nii.gz') + '_processed.nii.gz'
'home/user/t1_image_processed.nii.gz'
"""
... | 410e16aa01f51bacfd164c9d3406e51b91503a05 | 588,413 |
def third_bubble_sort(numbers):
"""Third implementation of bubble sort. Contains the second optimization
plus a new one: a boolean that indicated if any swap has been made. If
not, the list is already sorted. The iteration counter will be present
to show the difference between each implementation.
... | a5dfa03871bd8e78449f8be88f6ef71fc24796fc | 588,415 |
def matching_ngram_completions(comparison_seq, hypothesis, n):
"""
Return the list of words that if appended to hypothesis, would create a n-gram that
already exists in comparison_seq. For efficiency, this function represents words
as integers not strings.
Inputs:
comparison_seq: list of in... | 468ee39e4cd858893ad4cc5c81e8fe68e5f90de8 | 588,416 |
def getCasing(word):
"""Returns the casing for a word"""
casing = 'other'
numDigits = 0
for char in word:
if char.isdigit():
numDigits += 1
digitFraction = numDigits / float(len(word))
if word.isdigit(): #Is a digit
casing = 'numeric'
elif digitFraction > 0.5:
... | 69c48dd1f6943257570ac98a794909d01fd1db0e | 588,418 |
import warnings
def deprecated(comment=None, replacement=None):
""" A decorator which can be used to mark functions as deprecated.
Emits a DeprecationWarning showing the module and method being flagged
as deprecated. If replacement is set, the warn will also show which is
the function or c... | 244a5abb00c9910c84feb4087a3d229a93517828 | 588,420 |
def isAttribute(node):
"""
Returns True if the supplied node is an attribute
"""
return node.nodeType == node.ATTRIBUTE_NODE | d4394f2742b08e03c21ca5393c29527510b91efe | 588,422 |
import re
def line_has_timing_data(line):
"""
Determine whether the line has Verifier client timing data in it.
>>> line_has_timing_data(' [0]: h2 is negotiated.')
False
>>> line_has_timing_data(' [1]: 2 transactions in 2 sessions (reuse 1) in 1790 milliseconds (0.1 / millisecond).')
True
... | eb2a92974d70017cd832d16890e3c7016284d6e6 | 588,423 |
import hashlib
def make_pkey_from_review_item(productReviewDict):
"""Make the primary key for each review."""
return hashlib.md5(productReviewDict['review'].encode('utf-8')).hexdigest() | 9f2c29579fd9bef36272d98f89aa6c0096e69210 | 588,424 |
import re
def parse_show_lldp_neighbor_info(raw_result):
"""
Parse the 'show lldp neighbor-info' command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the show lldp neighbor-info command in a \
dictionary of the form:
::
... | 7ccbe2df689d011281ac1666d0e061b71eb77a05 | 588,425 |
def Gassmann(Kd, Km, Kfl, phi):
"""
B = (1.0 - Kd/Km)
Ks = Kd + B*B/(phi/Kfl - phi/Km + B/Km)
"""
Ks = Kd + (1.0 - Kd/Km)**2/(phi/Kfl + (1.0 - phi)/Km - Kd/Km**2)
return Ks | bdf96d1a08784f1b548beb1df688ae93ad98f6f4 | 588,427 |
import inspect
def get_inheritance_map(class_to_process):
"""
Return the inheritance mapping of the given class
:param class_to_process: class
"""
return inspect.getmro(class_to_process) | bea3176264ea8b34ced0f6b02fb44470527714fe | 588,428 |
def sort_array_of_tuple_with_second_value(array):
"""
Return an array of tuple sorted by second key values
"""
array.sort(key=lambda x: x[1], reverse=True)
return array | 494ee4e1641b90af4720c212a3abbcf3ac85ade8 | 588,431 |
def _convert_to_list(value):
"""Convert a value to a list if it's not already a list"""
if value is None: # empty value
return []
if not isinstance(value, list):
return [value] # single value
return value | aef5dae34c31a478d6ded868db57c4c7eb26aac4 | 588,432 |
import asyncio
def sync(cor, loop=None):
"""Wait for a task and return the result."""
if loop is None:
loop = asyncio.get_event_loop()
return loop.run_until_complete(cor) | efb825d6cd21a573dc8d4b0e49d3cb8ac83e56bd | 588,437 |
import csv
def csv_dict_list(grid_data_path):
"""
Read GRID data from .csv to a dict of org_info items.
:param grid_data_path: Path to where GRID data is stored.
:return: dictionary of grid info items.
"""
# Open variable-based csv, iterate over the rows and map values to a list of dictionarie... | 4a4567c7c1e74dc4b9e89484a8aac9a9eccbacae | 588,443 |
from typing import Tuple
def make_flow_paths(
GCM: str,
SCENARIO: str,
TRAIN_PERIOD_START: str,
TRAIN_PERIOD_END: str,
PREDICT_PERIOD_START: str,
PREDICT_PERIOD_END: str,
VARIABLE: str,
workdir: str = "az://cmip6",
outdir: str = "az://cmip6/results",
) -> Tuple[str, str, str, str]:... | 42d7dda7a6d3c6f1dc806b6ab3600f3aa2b570fa | 588,446 |
def only_extreme_entropy(df):
"""
Returns the trials that involve words with extreme values of entropy (either positive or negative).
:param df: dataframe with responses.
:return: dataframe only with responses of trials with extreme values of entropy.
"""
extremes=["extreme_neg","extreme_pos"]
... | 7f56c830f11a1114f1a35e5d9c5ec7a9e9be8a4a | 588,448 |
def int_convert(arg):
"""
Convert a VBA expression to an int, handling VBA NULL.
"""
if (arg == "NULL"):
return 0
return int(arg) | 6dee40fc9a044c2e303bcf48938517e5fc612810 | 588,449 |
from typing import List
from typing import Tuple
def policy_svhn() -> List[List[Tuple[str, float, int]]]:
"""Returns the AutoAugment policies found on SVHN.
A policy is composed of two augmentations applied sequentially to the image.
Each augmentation is described as a tuple where the first element is the
ty... | eb9eb223d3d992726f4a44d8d3d4087edea65d57 | 588,450 |
def get_img_height() -> int:
"""Fixed height for NN."""
return 32 | 8c443baf5c7ea6d49fbe17337877ea99eb59af35 | 588,453 |
def DmsToDecimal(degree_num, degree_den, minute_num, minute_den,
second_num, second_den):
"""Converts the Degree/Minute/Second formatted GPS data to decimal degrees.
Args:
degree_num: The numerator of the degree object.
degree_den: The denominator of the degree object.
minute_num: The ... | 3555ae452724be81153e7b5a2c2342f12a7b5514 | 588,456 |
from typing import Sequence
def argmin(sequence: Sequence) -> int:
"""Find the argmin of a sequence."""
return min(range(len(sequence)), key=lambda i: sequence[i]) | aebf2c2b8c4b4e74c2c7ed40425e23b13a73277f | 588,459 |
def getMissedAnnoIds(missed_annotations):
"""
Extract oid from annotations
Parameters
----------------
missed_annotations: list of dict
Returns
----------------
missedAnnoIds: list of ints
"""
missedAnnoIds = []
for anno in missed_annotations:
missedAnnoIds.append(an... | fdd848a7d77fcdc6706a5b20d66b1e3897488d8b | 588,460 |
def getpath(data, path):
"""`getpath()` returns the value at a dot-separated getitem path.
`data` can be a nested combination of dicts and arrays. Each part of the
path is interpreted as an integer if it looks like an integer.
"""
for p in path.split('.'):
try:
p = int(p)
... | 2cadf041675db40730f8cec1935f1722133ebecc | 588,462 |
def parse_input(text: str) -> str:
"""Return a string of '1's and '0''s representing the input hex string."""
return "".join([f"{int(text[i:i+2], 16):08b}" for i in range(0, len(text), 2)]) | e5df83669e31bc8e2a6e3e3f34781dd65ea6d78a | 588,465 |
def match_mass(candidates: list, range: tuple) -> list:
"""
Matches candidate m/z values to tolerance range.
Args:
candidates (List[float]): list of candidate m/z values.
range (Tuple[float, float]): tolerance range for m/z matches in format:
(minimum m/z, maximum m/z).
Ret... | a773d3b27e2f52343303431527c22c57803804bd | 588,466 |
def file_on_ref(repo, path, ref):
"""Return the content of the file at specified 'path' on branch 'ref'.
Raise if the file or ref does not exist.
:repo: a callable supporting git commands, e.g. repo("status")
:path: the string path to the file on the branch, e.g. 'src/main.cpp'
:ref: the string re... | a4607823945a65489d4abd630c232b3f2f44f38b | 588,472 |
def ranges(nums):
"""
Take a list of numbers (sorted or unsorted) and return all contiguous ranges within the list
Ranges should be returned as tuples, where the first value is the start of the range and
the last value is the end (inclusive). Single numbers are returned as tuples where both
values ... | 319bd42ea21f5ec9bce5c6d942fe0b85fa21d86d | 588,474 |
from typing import Dict
from typing import Any
def make_group_name(labels: Dict[str, Any]) -> str:
"""Create a name for a group by assembling labels.
Different labels are separated by & while label and values are separated by ::
Floating points number are formatted using g to avoid rounding issue to lead... | 12daec56428de575efeb62e01645c82ac6f69a41 | 588,475 |
def count(s, letter):
"""return the number of occurrences of a letter in a string"""
count = 0
for c in s:
if c == letter:
count += 1
return count | 29274f271ceb24e6170344e909bf940ef4164e58 | 588,476 |
import re
def extract_floats(str):
"""Takes a string and returns a list of floats in that string.
"""
return [float(n) for n in re.findall(r"[-+]?\d*\.\d+|\d+", str)] | 64c8fefbfc40564ba6eb4b3a27beaca78ddb7d56 | 588,479 |
def parse_exif_val(val):
"""
Sometimes EXIF values are stored in a fraction as a string.
This will return the value as a decimal.
"""
nums = val.split('/')
if len(nums) == 1:
return float(nums[0])
return float(nums[0]) / float(nums[1]) | c0d3d5b4b54db06e71bf331612f4d752f6fc3543 | 588,486 |
import time
def format_as_asctime(a_datetime):
"""Given a UTC datetime.datetime instance, return it formatted in C's asctime() format.
e.g. - Sun Nov 6 08:49:37 1994
"""
# Per Python's documentation, "Locale information is not used by asctime()" which saves me
# some work.
return time.asctim... | 0e8914ee6e2dd52809a5f52f46a598decd50b4ec | 588,488 |
import itertools
def test_combination_combinator(container, pairs_):
"""
r-length tuples, in sorted order, no repeated elements
combinations('ABCD', 2)
AB AC AD BC BD CD
"""
return list(
itertools.combinations(container, pairs_)
) | 5bd1b6f2e2e6360c1db8b663445085d8b2ae3e99 | 588,490 |
def send_tweet(api, contents):
"""Sends a tweet using `api`."""
return api.update_status(contents) | 2e5b958896b119ed1bb722b6faa17620d46a9e50 | 588,492 |
import uuid
def create_marconi_headers(conf):
"""Returns headers to be used for all Marconi requests."""
headers = {
"User-Agent": conf.headers.user_agent,
"Accept": "application/json",
"X-Project-ID": conf.headers.project_id,
"Client-ID": str(uuid.uuid1()),
}
return ... | 73a4a348b36651f1431865c2b9f197ad78765a61 | 588,494 |
from typing import Any
def to_bool(value: Any) -> bool:
"""Convert given value to Boolean. Only of the string matches 'True' (ignoring
case) the result will be True.
Parameters
----------
value: any
Expects a string representation of a Boolean value.
Returns
-------
bool
... | d04752c23316d8254e980a3fa48d44682b1f8aaf | 588,497 |
def alpha_liq_deph(Nu_deph, lyambda_coolwater, d_inner_deph):
"""
Calculates the coefficent of heat transfer(alpha) from liquid to wall of pipe.
Parameters
----------
Nu_deph : float
The Nusselt criterion, [dimensionless]
lyambda_coolwater : float
The thermal conductivity of cool... | 51aea066f6f8a227b95ccf666e98b11eaa8cb684 | 588,500 |
def getAnchorVerticies(vertices):
"""Get the top left and bottom right vertices in that order."""
return [
dict(
x= min([v.x for v in vertices]),
y= min([v.y for v in vertices])
),
dict(
x= max([v.x for v in vertices]),
y= max([v.y for v in vertices])
)
... | fbecc492567b21e0577c4ec72996eac3e3dc4e95 | 588,507 |
from re import VERBOSE
def _infer_scripts_path(compss_path):
"""
Infer the remote helper scripts path.
Uses the COMPSs installation path as base and includes the necessary
folders: Runtime/scripts/system/jupyter
:param compss_path: Remote COMPSs installation path.
:return: Remote helper script... | 97ec466583a0180ea2bd736949d0146343ccad1f | 588,508 |
import math
def get_smallest(l) :
"""
Get the smallest element of a list
:param l: List to inspect
:return: The element value
"""
assert type(l) is list
val = math.inf
for i in l :
if i < val :
val = i
return val if val != math.inf or math.inf in l else None | 46d9ef55cb1d592bb0bc674c610b9c2a8e98ba9a | 588,510 |
def link_id_degrees(full_id_degrees, id_degrees, i, bins):
""" Puts the ids of specific updates/times into a full dictionary of id-[degrees]
Takes in a specific update (id_degrees), and adds the degrees present in that
update to the full id:degree dictionary. The degrees are a list of len(bins),
and ea... | 3507117c44d86096b01f09f77958d1bf9e184448 | 588,513 |
def format_timedelta(td):
"""formats a timedelta into the largest unit possible
"""
total_seconds = td.total_seconds()
units = [(604800, 'w'), (86400, 'd'), (3600, 'h'), (60, 'm'), (1, 's')]
for seconds, unit in units:
if total_seconds >= seconds and total_seconds % seconds == 0:
... | 68a257b345220330b99dffee3502d096c696e352 | 588,517 |
def parse_args(parser):
"""
Parse commandline arguments.
"""
parser.add_argument('--bench-class', type=str, choices=['train', 'perf-infer', 'perf-train'], required=True, help='Choose test class')
return parser | 93d041a9d4d4d4b540dc5831b268b4dc0649b1fd | 588,521 |
import time
import hashlib
def write_str_to_file(string, extension='', encoding='utf-8'):
"""
Save the contents of a string to a file.
:param string: the data to be saved
:param extension: the file extension to be used for the file's name
:returns the name of the file containing the string data
... | 8fad8f4f8bbe2b909b90c303ac9abfed4f592b3a | 588,524 |
def clip_rect_to_image(rect, img_width, img_height):
"""Ensure that the rectangle is within the image boundaries.
Explicitly casts all entries to integer.
:param rect: list/tuple (l,t,w,h)
:param img_width: int
:param img_height: int
:return: (l, t, w, h)
"""
l, t, w, h = int(rect[0]), i... | e02d69d9b09d6ca246954092e1231ab0f1cc7658 | 588,526 |
def get_group_name(group):
"""Returns the group name if available, empty string otherwise."""
try:
group_name = group["name"]
except KeyError:
group_name = ""
return group_name | 821523cac6f2ae471bd82e4f4957a96fc34f045a | 588,527 |
def apply_elasticity(base_demand, elasticity, price_base, price_curr):
"""Calculate current demand based on demand elasticity
As an input the base data is provided and price differences and elasticity
Parameters
----------
base_demand : array_like
Input with base fuel demand
elasticity... | e7851271b9ddf264c28abaaebf810caab1cd08e7 | 588,530 |
import requests
def get_source_autoannotations(sourceid):
"""Fetch a specific source's autoannotations from the GROWTH marshal and
create a string with the autoannotations available."""
r = requests.post(
'http://skipper.caltech.edu:8080/cgi-bin/growth/source_summary.cgi',
data={'sourceid'... | f69099553be4a3af40a097960b82c4e91fae2743 | 588,532 |
def iterative_sum(num_list):
"""Calculate the sum using a for loop."""
total = 0
for num in num_list:
total += num
return total | 19c6c4bcac291c6bab7a9c5932f1c0d59cddd15b | 588,533 |
def fibonacci_recursive(number):
"""Returns the nth Fibonacci number in the Fibonacci sequence.
The Fibonacci numbers are the numbers in the Fibonacci sequence, defined by
the equation and seed values:
F(n) = F(n - 1) + F(n - 2)
F(0) = 0
F(1) = 1
* O(2^n) time complexity
* O(n) space complexity
A... | b68083cf68eca75e2f1e6ed562f3fc4a3db8f42d | 588,534 |
import re
def number_of_lines(fname, count_comment_lines=False):
"""Return number of lines in file.
Parameters
----------
fname: string
Input file name
count_comment_lines: boolean
If False (default), do not include comment lines in count
Returns
-------
num_lines: in... | 8ddc015b43fa5c5c368d5d1f227f7077fbc930ae | 588,535 |
def thread_posts(new_posts_for_user):
"""Get only new thread posts for a user."""
return new_posts_for_user[0] | 3ed2d52316314df978550d38ca0f1855ecd51c71 | 588,538 |
def preferredVersionMatch(pe, pv, pr, preferred_e, preferred_v, preferred_r):
"""
Check if the version pe,pv,pr is the preferred one.
If there is preferred version defined and ends with '%', then pv has to start with that version after removing the '%'
"""
if pr == preferred_r or preferred_r is None... | e706fa96f168528570b58d2375abefee9950e7c9 | 588,539 |
from typing import List
from typing import Dict
from typing import Any
def get_logging_query(
model_name: str,
docs: List[str],
search_keys: Dict[str, Any]
) -> Dict[str, Any]:
"""
The process to extract features from Elasticsearch involves sending what is known
as the "logging query". The res... | e105f794746833075a35aa71b9e6012d4bac720b | 588,540 |
def get_doc_offset(offset, document):
"""
:type offset: list[str]
:type document: dict
>>> get_doc_offset(['a'], {'a': 4})
4
>>> get_doc_offset(['a', 'b'], {'a': {'b': 4}})
4
>>> get_doc_offset(['a'], {})
Traceback (most recent call last):
...
KeyError: 'a'
"""
value... | c0393a026831d669fadf9593dff4a6c96f80186f | 588,541 |
def eq(x, y):
"""Implement `eq`."""
return x == y | c382f63b08865b41e3324a4d3f233ed67c3beeae | 588,551 |
def deg_min_sec_to_dec_deg(deg_min_sec):
"""Convert Degrees minutes and seconds.ms to decimal degrees"""
deg = int(deg_min_sec.split(' ')[0])
min = int(deg_min_sec.split(' ')[1])
sec = float(deg_min_sec.split(' ')[2])
dec_deg = abs(deg) + min/60 + sec/3600
dec_deg = round(dec_deg, 8)
if de... | d71c89609faee78fce6b3269f8c5ea6b7145a020 | 588,552 |
def number_of_interactions(G, u=None, v=None, t=None):
"""Return the number of edges between two nodes at time t.
Parameters
----------
u, v : nodes, optional (default=all edges)
If u and v are specified, return the number of edges between
u and v. Otherwise return t... | 8e1e3636a0620b54f52707a2edf265ab4bdedcfd | 588,558 |
def gen_bitstring(xdelays, ydelays):
"""Given two arrays of 16 integers, representing the xdelays and ydelays, return
a string containing 253 characters, each '1' or '0', representing the bit stream
to be sent to the beamformer.
Format is:
8 zeroes
4 ones
20 zeroe... | 4dada2f629cbe8ebc090136275f0dfa0666fcff5 | 588,560 |
def get_piece(board, index):
"""Returns the nth piece of the provided board"""
board = board if board >= 0 else -board
return (board % 10 ** (index + 1)) // 10 ** index | 3c70ad3590905a0a707ba11cf7e8894f565396d6 | 588,561 |
import re
def breakHexDirections(tape: str) -> list[str]:
"""
Helper method to HexGrid: breaks a tape containing directions into a list of directions
"""
directionsRE = re.compile("NE|NW|N|SE|SW|S|UL|UR|U|DL|DR|D")
return directionsRE.findall(tape.upper()) | 44b2c4d29b27dad929e2a86e3bbd02bf54e2a438 | 588,563 |
def send_raw_transaction(w3, tx):
"""
Given a signed transaction, broadcast it.
"""
return w3.eth.sendRawTransaction(tx.rawTransaction) | 0fa2ab4eaf030e8e4c421480fc126d19a1359950 | 588,564 |
def root(dimensioned_number, n):
"""Take the n-th root of a Dn() instance. All of the
dimension exponents must be divisible by n. math.pow() is
called with an exponent of 1.0/float(n) on the numeric
part of the dimensioned number.
:param dimensioned_number: A Dn() instance.
:param n: A positi... | e80a836571f13870df871b7c628595252716d5ad | 588,565 |
def query_to_dict(results, descriptions):
"""
Replacement method for cursor.dictfetchall() as that method no longer
exists in psycopg2, and I'm guessing in other backends too.
Converts the results of a raw SQL query into a list of dictionaries, suitable
for use in templates etc.
"""
output... | 7426a6efb6cccd3f92e85c62675f5384a0886c2d | 588,567 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.