content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def get_potential(q):
"""Return potential energy on scaled oscillator displacement grid q."""
return q ** 2 / 2 | 78f657d950dab0ac1821fbca5454e9b0dfb4eaab | 204,886 |
def get_data_type(azdat):
"""
Get the radar file type (radial or raster).
Args:
azdat: Boolean.
Returns:
Radial or raster.
"""
if azdat:
return "radial"
return "raster" | 375d250665f728bbf76b88a66f8352b623a55983 | 430,313 |
def csv2dict(filename, key_column, val_column, lower=True, header=True): #---<<<
"""
Create a dictionary from two columns in a CSV file.
filename = name of .CSV file
key_column = column # (0-based) for dictionary keys
val_column = column # (0-based) for dictionary values
lower = whether to make... | 799c7d530c44d36cd244046cc46abb237d80f40d | 249,457 |
def decompress_amount(x):
""" Decompresses the Satoshi amount of a UTXO stored in the LevelDB. Code is a port from the Bitcoin Core C++
source:
https://github.com/bitcoin/bitcoin/blob/v0.13.2/src/compressor.cpp#L161#L185
:param x: Compressed amount to be decompressed.
:type x: int
:return: T... | 85856d220be484b294622b99433ada47d04ec4e0 | 572,865 |
import csv
def load_angle_offsets(csv_path):
"""Load additive euler angles from CSV file.
header: joint, i, j, k
Order of x,y,z values must match order of rotation channels in BVH file. If the order is zxy then i=z, j=x, k=y.
:param csv_path: Path to CSV file containing values.
:type csv_path... | aed976ebf2801364b9d770895e943d0864c46d5c | 609,553 |
def _LLF(job, t):
"""
Least-Laxity-First assigns higher priority to jobs with lesser laxity (slack).
The laxity (slack) of a job of a job with deadline d at time t is equal to
deadline - t - (time required to complete the remaining portion of the job)
"""
return job.deadline - t - job.remai... | 8dd5025c5ee077352c7f0cf0e23fc76bc29950c3 | 658,039 |
def get_doi_url(doi):
"""
Given a DOI, get the URL for the DOI
"""
return "https://doi.org/%s" % doi | ab7bd3a4fb488f376021804783ca4ce88c938d70 | 190,081 |
def fix_sign(x, N=360 * 60 * 10):
"""
Convert negative tenths of arcminutes *x* to positive by checking
bounds and taking the modulus N (360 degrees * 60 minutes per
degree * 10 tenths per 1).
"""
if x < 0:
assert x > -N
x += N
assert x < N
return x % N | 77063cd2a2680937276a3ef752782bc537942827 | 182,877 |
def get_topics(lda_model):
"""get_topics. Extract list of topics with top twenty words.
Parameters
----------
lda_model : gensim.models.ldamulticore.LdaMulticore
Trained LDA model. Takes output from get_model.
"""
topics = lda_model.show_topics(num_topics = -1, num_words=20, formatted=F... | c7819badbbc9037be6780c93d1771812f20f79c1 | 362,161 |
from typing import Counter
def recount_answers(group):
"""Count the number of positive answers of a group.
Only the questions to which everyone in a group answered
yes to count.
"""
people = len(group)
line = ''.join([n.strip('\n') for n in group])
count = Counter(line)
number = 0
... | f5695311d36ae71d4dca2dc57a720f216e725701 | 222,737 |
import torch
def precision(cm):
"""
Precision: of all predicted positive samples, what fraction was correct?
precision = TP / (TP + FP)
Args:
cm: Binary confusion matrix like this:
| TN | FP |
| FN | TP |
Returns:
scalar precision score
"""
rv... | ce5faf206d3ece17ee0069b1ad1f2ee47c71d712 | 80,083 |
def fa_attachment(extension):
"""
Add fontawesome icon if found. Else return normal extension as string.
:param extension: file extension
:return: matching fontawesome icon as string
"""
if extension == 'pdf':
return "<i class='fa fa-file-pdf-o fa-lg'></i>"
elif extension == 'jpg' o... | 3add6bf4c177cba893a2242df352fd0ae619ee90 | 22,194 |
def listGetShiftedGeometricMean(listofnumbers, shiftby=10.0):
""" Return the shifted geometric mean of a list of numbers, where the additional shift defaults to
10.0 and can be set via shiftby
"""
geommean = 1.0
nitems = 0
for number in listofnumbers:
nitems = nitems + 1
nextnumb... | 904bb38a199052b086b7a2c695ce675011f65019 | 17,561 |
def extract_medium(medium):
"""
Convert Medium to simplified dictionary
:param medium: ILoop medium object
:return: list of dictionaries of format
{'id': <compound id (<database>:<id>, f.e. chebi:12345)>, 'concentration': <compound concentration (float)>}
"""
if medium is None:
... | 0b31e1807271379caa74f62a2bd7acb6fd33936a | 293,918 |
import json
def load_dict_json(file_path: str) -> dict:
"""
Loads a JSON file as a dictionary.
# Arguments
file_path (string): Path to the JSON file.
# Returns
Dictionary with the data from the JSON file.
"""
with open(file_path, 'rb') as fp:
return json.load(fp) | d692e55dda5818cc9aaede507165f56057c85ba5 | 89,918 |
def dzip(items1, items2, cls=dict):
"""
Zips elementwise pairs between items1 and items2 into a dictionary. Values
from items2 can be broadcast onto items1.
Args:
items1 (Sequence): full sequence
items2 (Sequence): can either be a sequence of one item or a sequence of
equal ... | c50e414c6ce06c0427750995c8bfb1bdfd18bf2b | 476,170 |
def even_chunker(seq, n_chunks):
"""Given a sequence, returns that sequence divided into n_chunks of (roughly) the same size.
In other words, it returns a list of lists.
When len(seq) is evenly divisible by n_chunks, all chunks are the same size.
When len(seq) is not evenly divisible by n_chunks, all ... | 936c4c262644eec119eec9d73a6f61171a584408 | 105,281 |
def single_line(line, report_errors=True, joiner='+'):
"""Force a string to be a single line with no carriage returns, and report
a warning if there was more than one line."""
lines = line.strip().splitlines()
if report_errors and len(lines) > 1:
print('multiline result:', lines)
return joiner... | e150f0d9039f3f4bc0cb1213d5670bc7519b1bbf | 683,771 |
import time
def date(representation='literal'):
"""Return the local date.
Parameters
----------
representation : 'literal', 'number' (default: 'literal')
Example : 'literal' --> "24 march 2020"
'number' --> "24/03/2020"
"""
localtime = time.localtime()
year = l... | d194ea8ee1b8dad4d79971fd1bff4f82d2cfc984 | 186,404 |
def notas(* tot, sit=False):
"""
:param tot: É o valor das notas que serão passados como paramêtro
:param sit: Pode ser True or False, dando a opções de mostrar ou não a situação
do aluno, podendo ser, ruim para média baixa, Razoavél para medias intermediarias
ou Ótima para boas medias.
:return... | ab3edb6e9e201562351a3440fda5be2e08427ac0 | 540,974 |
def print_board(board):
"""
Input: takes a xo board as a list from values of a 3x3 board
Returns: a tic-tac-toe board in a visual manner
"""
return print("\n{} | {} | {}\n--+---+--\n{} | {} | {}\n--+---+--\n{} | {} | {}\n"
.format(
board[1],board[2],board[3],board[4],
board[5],b... | 9968895a5c25a50644c4577c7f38654dcf5f9748 | 578,343 |
def int_to_vlq(val):
"""
Converts an integer value into a variable length quantity (list).
"""
vlq = []
for i in range(21, 0, -7):
if val >= (1 << i):
vlq.append(((val >> i) & 0x7F) | 0x80)
vlq.append(val & 0x7F)
return vlq | 0e8dd5affb8084109d34751c3151aeaeacac1314 | 585,564 |
import re
def _match_op(ops, regex):
"""Returns ops that match given regex along with the matched sections."""
matches = []
prog = re.compile(regex)
for op in ops:
op_matches = prog.findall(op)
if op_matches:
matches.append((op, op_matches[0]))
return matches | 98bf8e34f5b5b02d8f90a7d40ca8b98784113b3e | 459,852 |
import warnings
def _handle_alias(X, Z):
"""Handle Z as an alias for X, return X/Z.
Parameters
----------
X: any object
Z: any object
Returns
-------
X if Z is None, Z if X is None
Raises
------
ValueError both X and Z are not None
"""
if Z is None:
retur... | 83ba789ff108f201d765f414a161052326d02ad9 | 424,792 |
def can_contain(parent_type, child_type):
""" Returns true if parent block can contain child block.
"""
return (parent_type in ['Document', 'BlockQuote', 'ListItem'] or
(parent_type == 'List' and child_type == 'ListItem')) | c8cef3515b3306f779525c59486b526654649433 | 31,441 |
def rgba_from_argb_int(color):
"""
Converts ARGB int into RGBA tuple.
Returns:
(int, int, int, int)
Red, green, blue and alpha channels.
"""
a = ((color >> 24) & 0xFF) / 255.
r = (color >> 16) & 0xFF
g = (color >> 8) & 0xFF
b = color & 0xFF
return r... | a92d676f89678556a3382af4642408c5cb72f06c | 258,171 |
def _clean_header(text: str, is_unit: bool = False) -> str:
"""
Extract header text from each raw trajectory summary csv file header.
:param text: Raw trajectory summary csv column header text.
:param is_unit: If True, return text with brackets for units.
:returns: Formatted text.
"""
# Re... | 000ab01267e78d621fd8a8e6844523e7fa909ba4 | 696,156 |
def filter_valid_transit(df_in, hour_in):
"""Filters master dataframe for VEH_IDs valid for specified hour
Inputs: df_in, a pandas dataframe containing joined transit_lines and
transit_types excel worksheets.
hour_in, an emme hour code as user arg.
Returns: transit_list, a list of va... | 800b30ba3784150f7a5f30c6c9436564847c57a1 | 169,444 |
def bmatrix(a):
"""Returns a LaTeX bmatrix
:a: numpy array
:returns: LaTeX bmatrix as a string
"""
if len(a.shape) > 2:
raise ValueError('bmatrix can at most display two dimensions')
lines = str(a).replace('[', '').replace(']', '').splitlines()
rv = [r'\begin{bmatrix}']
rv += ['... | 3be2e4c67f535996161252d4da2c2397c21855da | 223,680 |
def get_error(intercept, slope, points):
"""get_error function computes the error for a line passing through a
given set of points (x, y)
:intercept: y-intercept of the line passing through a set of points
:slope: slope of the equation represented as m
:points: set of (x, y) coordinates
:return... | cd271598a01eee12b343ae422b79085cac86a702 | 96,530 |
def subtract(x, y):
""" Returns the first vector minus the second. """
n = len(x)
assert len(y) == n
return map(lambda i: x[i]-y[i], range(0, n)) | dd66579b99d01c42b9773a116b4989910a6be3be | 646,088 |
def blend(a, scale, b):
"""
Returns a color that's 'scale' of the way between 'a' and 'b'.
(Interpolates RGB space; very simple)
"""
ar,ag,ab = a
br,bg,bb = b
return (min(255, max(0, br- (br-ar)*(1-scale))),
min(255, max(0, bg- (bg-ag)*(1-scale))),
min(255, max(0, bb-... | 9ef9271f688e205f9da1105ba041fca44e497aa5 | 237,201 |
import time
def formatentry_ls(l):
"""Returns a string in a format similar to that produced by
'ls -la'. This is particularly handy to get Emacs' ange-ftp
working well with FtpServers.
Expects a list or tuple containing the following members:
- [0] - permissions, in 'drwxrwxrwx' format
- [1] - number of lin... | cc4f83bdbefd27dfd563d1b722d24e026ecde573 | 239,876 |
import asyncio
async def check_address(host: str, port: int = 80, timeout: int = 2) -> bool:
"""
Async version of test if an address (IP) is reachable.
Parameters:
host: str
host IP address or hostname
port : int
HTTP port number
Returns
-------
awaitable bool
"... | e08da38636c66a59948adc4fa08132f9f7438db9 | 686,738 |
def delay(func):
"""
When schemas are referencing to each other, this decorator will help by
marking a schema as ``delayed`` to avoid the need for calling a schema to
generate itself until it is actually needed.
For example, if a schema function references to itself in this manner::
def my... | 162b738c7af8a93ff9ffb87fad5e14a514d44695 | 417,727 |
def member_needs_update(before, after):
"""
See if the given member update is something
we care about.
Returns 'False' for no difference or
change we will ignore.
"""
for attr in ("nick", "avatar", "roles"):
if getattr(before, attr) != getattr(after, attr):
return True
... | 5803e9affa7028e36e2bd5a74049ecc3771896ca | 626,196 |
from typing import List
from typing import Any
def __find_item_index(list_to_look_in: List[Any], item_name: str):
"""
Returns the index of the first item in the list that matches the given name.
:param list_to_look_in: list of elements that contain name attributes
:param item_name: the item name to ac... | 7081e45bfe0e6151a939b1533ce684ace7791d8f | 253,322 |
from typing import OrderedDict
def pool_usage_metrics_list_table_format(result):
"""Format pool usage-metrics list as a table."""
table_output = []
for item in result:
table_row = OrderedDict()
table_row['Pool Id'] = item['poolId']
table_row['Start Time'] = item['startTime'] if ite... | 1639a8602fba1dd12f87f1c094314bcea8c79766 | 357,521 |
def extra_hour_bits(value):
"""
practice getting extra bits out of the hours bytes
>>> extra_hour_bits(0x28)
[0, 0, 1]
>>> extra_hour_bits(0x8)
[0, 0, 0]
"""
masks = [ ( 0x80, 7), (0x40, 6), (0x20, 5), ]
nibbles = [ ]
for mask, shift in masks:
nibbles.append( ( (value & mask) >> shift ) )
re... | 635c7f8d4aa752001b75eba8518d1e3c857bc297 | 123,858 |
def CsvEscape(text):
"""Escapes data entry for consistency with CSV format.
The CSV format rules:
- Fields with embedded commas must be enclosed within double-quote
characters.
- Fields with embedded double-quote characters must be enclosed within
double-quote characters, and each of the embedd... | a28620e204f5433c580c00a234ea0ab5e6ac060c | 29,705 |
from datetime import datetime
def now() -> datetime:
"""Return the datetime object of the current time.
:return: datetime object represeting current time
"""
return datetime.now().astimezone() | e1ca72a8cf22b1614a406a3d44148fb509d262a8 | 627,014 |
def _substitution_mask(sent1, sent2):
"""Binary mask identifying substituted part in two sentences.
Example sentence and their mask:
First sentence = "I like the cat 's color"
0 0 0 1 0 0
Second sentence = "I like the yellow dog 's color"
... | b93de9dfb6bde55859f57e6957f31c319e9417f6 | 227,465 |
def first_invoke(func1, func2):
"""
Return a function that when invoked will invoke func1 without
any parameters (for its side-effect) and then invoke func2
with whatever parameters were passed, returning its result.
"""
def wrapper(*args, **kwargs):
func1()
return func2(*args, **kwargs)
return wrapper | 0190c4f7aa4cde2a6df964a8f3e4408ebceedfb7 | 297,582 |
import torch
def get_prediction(model, batch, device):
"""Get predicted labels for given input batch and model."""
images = torch.tensor(batch, dtype=torch.float).to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
return predicted | e8bb4257dc19f26fa206e26fa844ec9717974e52 | 9,250 |
def get_group_from_table(metatable_dict_entry):
"""
Return the appropriate group title based on either the SGID table name or
the shelved category.
"""
sgid_name, _, item_category, _ = metatable_dict_entry
if item_category == 'shelved':
group = 'UGRC Shelf'
else:
table_cate... | 1e356f0204aa099728ba0a5c595c25f1abd45de3 | 550,514 |
def escape(v):
"""
Escapes values so they can be used as query parameters
:param v: The raw value. May be None.
:return: The escaped value.
"""
if v is None:
return None
elif isinstance(v, bool):
return str(v).lower()
else:
return str(v) | 304079292532ef905099f1fd047ddb95df231076 | 672,692 |
import math
def Naca_00XX(c, t, x_list):
"""
Generates a simetric NACA airfoil.
Inputs:
:param c: chord
:param t: max thickness as a fraction of the chord.
:param x_list: points between 0 and c (chord lenght)
Returns dictionary with keys 'u'pper and 'l'ower
The Naca functio... | 8fe95b7b02569138cc2adabcc526490341c0a71d | 512,427 |
def serialise_matched_reference(data, current_timestamp):
"""Serialise the data matched by the model."""
serialised_data = {
'publication_id': data['WT_Ref_Id'],
'cosine_similarity': data['Cosine_Similarity'],
'datetime_creation': current_timestamp,
'document_hash': data['Documen... | 36f6f22eccf0bcb06c21b68de18e7d606cb4e48b | 283,449 |
def get_idx_using_unique_iso(mol, iso_val):
"""
This function takes a value for an isotope label and finds the atom in a
mol which has that isotope label. This assumes there is only 1 atom in a
mol with the same isotope value
Inputs:
:param rdkit.Chem.rdchem.Mol mol: a molecule whose atom's hav... | 7528955c114bb6c7dd086f6f86058aa7cda193dd | 431,006 |
def default_decision_function(position, solutions):
"""The default decision function - returns the first solution."""
return solutions[0] | 7fb8678ab1c3298fe9cf0fe72aca0ee1d8c4161b | 198,010 |
def process_fatal_error(token_list, values):
"""Retrieve and categorize fatal error.
This function parses a line, retrieves fatal error message, categorizes it
and stores it in the main 'values' dictionary with a key 'fatal'.
Arguments:
token_list (list)[-]: A list of tokens to be processed.
... | b769ac051f1103e4fe95fc842b26f4efa2f04159 | 179,819 |
import base64
def is_jwt_well_formed(jwt: str):
"""Check if JWT is well formed
Args:
jwt (str): Json Web Token
Returns:
Boolean: True if JWT is well formed, otherwise False
"""
if isinstance(jwt, str):
# JWT should contain three segments, separated by two period ('.') cha... | 4406ea2ab186c601f0959ec68107671b1a7f1990 | 268,868 |
from pathlib import Path
def create_symlinks(paths):
"""Create symlinks with unique file names."""
container_paths = [f"{n}_{Path(path).name}" for n, path in enumerate(paths)]
for container_path, path in zip(container_paths, paths):
Path(container_path).symlink_to(path)
return container_paths | 9189255a5642cc24c6c762b0e2d1c6a704c4a1ff | 350,317 |
def __find_notification_channel_name_in_message(message):
"""
The command "gcloud alpha monitoring channels create", communicates a notification channel Id as part of its output.
Knowing the message format, this function extracts the channel Id and returns it to the caller.
Sample messa... | d53df43da83f85ec5174ced8780015cb690be1d0 | 276,075 |
def replace_escape_codes(input_str):
"""Replace escape codes function
Parameters
----------
input_str : str
String of input
Returns
-------
str
Sting to replace escape codes to print properly
"""
return input_str.replace('"', '"').replace(''', "'").replace... | 7ec7beb47412d828bcee1c02edbdde15940487f0 | 467,430 |
def list_check(lst):
"""Are all items in lst a list?
>>> list_check([[1], [2, 3]])
True
>>> list_check([[1], "nope"])
False
"""
counter = []
for each in lst:
if isinstance(each, list):
counter.append(True)
else:
counter.appen... | e3dd483d57f153c102ecd2d2592491ec36afd077 | 575,212 |
def flatten(tuple_entry):
"""
Given a tuple of tuples and objects, flatten into one tuple of objects
@param {Tuple} tuple_entry Tuple containing possibly nested tuples
@return {Tuple} One dimensional tuple of objects
"""
if len(tuple_entry) == 0:
return tuple_entry
if isinstance(tup... | 0cfdf8345f3304e4a60085d7767040439281c273 | 556,744 |
def stripNameSpace(objName):
"""
Check to see if there is a namespace on the incoming name, if yes, strip and return name with no namespace
:param name: str
:return: str, name with no namespace
"""
name = objName
if ':' in name:
name = name.split(':')[-1]
return name | 8f2e5ba1b39712ca8e0255b2cbfc72b9d64d5503 | 398,676 |
def allocated_size(allocation_unit, requested_size):
"""
Round ``requested_size`` up to the nearest ``allocation_unit``.
:param int allocation_unit: The interval in ``bytes`` to which
``requested_size`` will be rounded up.
:param int requested_size: The size in ``bytes`` that is required.
:... | f25a55f3cf96194c5357e106642b89f6aefba65c | 639,699 |
from re import sub
def replace(given_text: str, sub_string: str, replacable_str: str) -> str:
"""Replace a substring with another string from a given text.
Args:
given_text (str): the full text where to be replaced
sub_string (str): the string to be replaced
replacable_str (str): the ... | e0110d446c401af47fa42033048e30ffe28d2bc9 | 439,005 |
def parse_name_scope(name):
"""
Given a tensor or op name, return the name scope of the raw name.
Args:
name: The name of a tensor or an op.
Returns:
str: The name scope
"""
i = name.rfind('/')
if i != -1:
return name[:i] if not name.startswith('^') else name[1:i]
... | dc0de1327a56f3d8cf110d4cd8a804a282bb52e1 | 571,611 |
def count_vowels(s):
"""
(str)-int
return number of vowels in s.
>>> count_vowels('The quick brown fox')
5
"""
lowerS = s.lower()
vowels = ['a', 'e', 'i', 'o', 'u']
ctr = 0
for ch in lowerS:
if ch in vowels:
ctr += 1
print ('There are {} vowels in: "{}"'.... | a043f65cb6fba8063139c5a57aec87cbfb891409 | 158,430 |
import json
def read_json(filepath, **kwargs):
"""Load JSON file `filepath` as dictionary. `kwargs` are keyword arguments
for `json.load()`.
Args:
filepath: path-like, path to JSON file.
Returns:
Dictionary of JSON contents.
"""
with open(filepath, 'r') as fp:
return ... | 09e1b28c065eee619a242790de65f3bee4eec4af | 562,316 |
import base64
def encode_b64(data):
"""Encode data in base64."""
return base64.b64encode(data) | 753b01c577794e65de7c714cad772c0de4230413 | 496,387 |
import io
def data_read(filename):
"""Read string from a file with leading and trailing whitespace removed.
:param ``str`` filename:
File to read from.
:returns ``str``:
File content.
"""
with io.open(filename) as f:
data = f.readline()
return data.strip() | 78945d3929c293791ba43cb0863fdd6acc1a5460 | 417,243 |
import re
def is_commit(string: str) -> bool:
"""Tests if a string is a SHA1 hash."""
return bool(re.match("[0-9a-f]{5,40}", string)) | 538b34becb3cc1edcab90f62fbecf1a7dfcfeceb | 340,857 |
def count_rectangles(m: int, n: int) -> int:
"""Returns the number of rectangles in an m by n rectangular grid."""
return m * (m + 1) * n * (n + 1) // 4 | e868b081b006f019c3b6ae92ed0a20215c472e24 | 362,759 |
import logging
def is_matching_filename(filename, suffix_list):
"""
Return True/False if filename's suffix is in suffix list.
(Returns False if the file doesn't seem to have a suffix)
Assumption: members of suffix_list are lower case
"""
try:
_, suffix = filename.rsplit(".", 1)
exc... | 2bb8d0cda0210fa185bebade3e7851c07f3124f4 | 469,120 |
import re
def smart_title(value):
"""Converts a string into titlecase."""
"""Excludes [a, an, the, and, but, or, for, nor, of]"""
# strip smart single quotes
t = re.sub('\\u2018|\\u2019','\'', value.title())
# fix the plural
t = re.sub(r'([a-z])\'([A-Z])', lambda m: m.group(0).lower(), t)
... | e93b2ee7e0859bb0bd2df937a1f8c54f8fdedaf5 | 611,278 |
def atfile_sci(filename):
"""
Return the filename of the science image
which is assumed to be the first word
in the atfile the user gave.
"""
return filename.split()[0] | 85d01f0da9fd065f486a0266db483e8a845db4a8 | 560,298 |
def integer(v):
""" Is arg an integer? """
return type(v) is int | 66ec3c118ee8bf8c717e393b6774ba5e30d7b0dd | 261,605 |
def sample_labels(model, wkrs, imgs):
"""
Generate a full labeling by workers given worker and image parameters.
Input:
- `model`: model instance to use for sampling parameters and labels.
- `wkrs`: list of worker parameters.
- `imgs`: list of image parameters.
Output:
1. list ... | 1abd2d0d087f7ce452db7c899f753366b148e9e6 | 17,152 |
def parse_None(el: object) -> object:
"""
Parse element or list of elements, inserting None when it finds a string 'None'
:param el: List or single element to parse
:return: List or single element parsed
"""
if isinstance(el, list):
for i in range(0, len(el)):
if el[i] == 'N... | b2e36dcc9a9a7dc6401148553ab8035f0ea56a70 | 545,269 |
def tableToDicts(header, entries):
"""Converts a tuple of header names, and a list of entry tuples, to a list of dictionaries
"""
dicts = []
for entry in entries:
dicts.append(dict(zip(header, entry)))
return dicts | 3b7f7939b32f65e116a57683dca84cb80328aaaa | 103,507 |
def info(v, row, row_n, i_s, i_d, header_s, header_d, scratch, errors, accumulator):
""" Print information about a value, and return the value. Prints out these values:
- row_n: The row number
- header_d: Schema header
- type: The python type of the value
- value: The value of the row, truncated to... | 6c74f34f4d33b854ca216c6ba3a4e8cc43b71e99 | 191,007 |
import ast
def format_itervars(ast_node):
"""Formats an `ast_node` of loop iteration variables as string, e.g. 'a, b'"""
# handle the case that there only is a single loop var
if isinstance(ast_node, ast.Name):
return ast_node.id
names = []
for child in ast_node.elts:
if isinst... | e5fa14fa230f671bba0b9683eab1023b390b02de | 522,342 |
def draw_rect(surface, fill_color, outline_color, rect, border=1):
"""
Draw cells on surface
:param surface: surface
:param fill_color: cell color
:param outline_color: out color
:param rect: rect to draw
:param border: border width
:return: rect
"""
surface.fill(outline_color, r... | 9da4bb071b016d7dae81668416c3a2d9a27af4eb | 545,041 |
import textwrap
def testdir(testdir):
"""Return default testdir fixture with additional helper methods."""
def _path_has_content(path, content):
return testdir.tmpdir.join(path).read() == textwrap.dedent(content)
testdir.path_has_content = _path_has_content
def _write_path(path, content):
... | 42797a41dbfa2c56f939d8f72b61833843773d23 | 257,445 |
def line_number_in_contents(contents, regex, default=1):
"""Find the line number where regex first occurs inside contents.
If regex has a matching group, the line number of the start of the
matching group will be returned. If the regex is not found,
'default' is returned.
"""
m = regex.search(... | 51ebe0a23ebc19bbb997bddf651179088d32a81f | 104,044 |
def find_variable(frame, varname):
"""Find variable named varname in the scope of a frame.
Raise a KeyError when the varname cannot be found.
"""
try:
return frame.f_locals[varname]
except KeyError:
return frame.f_globals[varname] | f97bbcd5d60faf7cecce12d08f53eb144a766bd0 | 660,049 |
def _invert(x, limits):
"""inverts a value x on a scale from
limits[0] to limits[1]"""
return limits[1] - (x - limits[0]) | 116a8420548097fe80ffc0a92acdf382b937ff1f | 310,232 |
import string
def __camelize(value):
"""Camelize a variable name.
e.g. 'dumb_clusterer' to "DumbClusterer".
>>> __camelize('dumb_clusterer')
'DumbClusterer'
"""
return "".join(string.capwords(x) for x in value.split("_")) | f89ffa9ff262f0fc959c37af5063c4bf37a6504a | 280,019 |
def get_mean_rate(reviewer):
"""Function that returns the mean rate of a viewer."""
#Take the mean rate of the viewer.
mean_rates = reviewer['Review Rating'].mean()
#Return this value.
return mean_rates | d67bdac1958419f952c8e92e97ecd2514651cfe9 | 307,135 |
from typing import Dict
from typing import Tuple
from typing import Literal
from typing import List
def place_colorstrip(
anchor_coords: Dict[str, Tuple[float, float]],
width: float,
height: float,
spacing: float,
loc: Literal["left", "right", "up", "down", "polar"],
) -> Tuple[
Dict[str, Tupl... | e667de3478ee0b8ae02e5ec26272e8262ae72cdf | 545,771 |
def tonumber(v):
"""
Convert a value to int if its an int otherwise a float.
"""
try:
v = int(v)
except ValueError as e:
v = float(v)
return v | 8b52ac3385b3ffc721af523799ef3a6da4e29060 | 16,682 |
def get_user_attrs(object):
"""
Return the attributes of an object
:param object: the object to get attributes from
:return: list of attributes
"""
return [k for k in dir(object)
if not k.startswith('__')
and not k.endswith('__')] | 44e1a8bcfedad46f92cd9d98f39f5797f9de15d5 | 602,852 |
def _get_username(user):
"""
Return user's username. ``user`` can be standard Django User
instance, a custom user model or just an username (as string).
"""
value = None
# custom user, django 1.5+
get_username = getattr(user, 'get_username', None)
if get_username is not None:
val... | e0f80aee5b8f8be2c5c11ca3cbe556f9c80637e9 | 569,371 |
def inverse_monoalpha_cipher(monoalpha_cipher):
"""Given a Monoalphabetic Cipher (dictionary) return the inverse."""
inverse_monoalpha = {}
for key, value in monoalpha_cipher.iteritems():
inverse_monoalpha[value] = key
return inverse_monoalpha | dcad6fae88fb005e39313dce6a977d653e58c599 | 514,414 |
def build_geometry(self, sym=1, alpha=0, delta=0):
"""Build the geometry of the machine
Parameters
----------
self : Machine
Machine object
sym : int
Symmetry factor (1= full machine, 2= half of the machine...)
alpha : float
Angle for rotation [rad]
delta : complex
... | 670e7ae40e6f02d386cba477cd6bc6dfcf2f42e9 | 676,441 |
def status_code_to_text(status):
"""
Takes an Solarwinds Orion status code and translates it to
human text and also a colour that can be used in Slack.
"""
if status == 0:
return ("Unknown", None) # aka slack 'grey'
elif status == 1:
return ("Up", "#00ad52") # aka slack 'good'... | 96bc37cddafa9b2cfde2d53f910c4d96fea594a7 | 422,239 |
def parse_photos(soup):
"""Parse photo URLs from soup
Arguments:
soup: the soup object to parse from
Returns:
URL list: list of image URLs
"""
imgEles = soup.select("div.imgList")[0].findChildren("img")
imgUrlList = []
for img in imgEles:
imgUrlList.append(img["src... | a7fad05f6ed00a67e7f65c6195088161005661f7 | 411,059 |
def parse_comma_sep_list(csl):
"""Parse comma separated list of integers."""
return [int(x) for x in csl if x != ""] | df4396fd46749b6bb7cec03c1cc98062454f05a1 | 456,816 |
def adjust_fields(prefix, task):
"""
Prepend the prefix to a task's fields
:param prefix: string prepended to task fields
:type prefix: str
:param task: a JSOn task object from task.json
:type task: dict
:return: a modified JSON task object from task.json
:rtype: dict
"""
out... | 21fefa294ee2c10dd2388bd70be11828753df7c9 | 77,452 |
def filter_paired_dataset_indices_by_size(src_sizes, tgt_sizes, indices, max_sizes):
"""Filter a list of sample indices. Remove those that are longer
than specified in max_sizes.
Args:
indices (np.array): original array of sample indices
max_sizes (int or list[int] or tuple[int]): max s... | 16f82b1413a9e6cf389567c724f7267f4dc97891 | 483,797 |
def ExtractLogId(log_resource):
"""Extracts only the log id and restore original slashes.
Args:
log_resource: The full log uri e.g projects/my-projects/logs/my-log.
Returns:
A log id that can be used in other commands.
"""
log_id = log_resource.split('/logs/', 1)[1]
return log_id.replace('%2F', '/... | b8a26978e7a394fd84e86182cbe365e3fde69dc7 | 443,260 |
def plus1(x):
"""
returns x + 1
"""
return x + 1 | e27669977aceca1d2c4fc34de7ca0d822d1fda57 | 505,862 |
async def in_voice(ctx):
"""Checks that the command sender is in the same voice channel as the bot."""
bot_voice = ctx.guild.voice_client
if bot_voice is not None and bot_voice.channel is not None:
return True
else:
return False | 8d89b0b1d4a8fa79bb591d5326f41de1d8138df9 | 288,330 |
def _get_order_and_exponentiation_step(method):
"""Return order and exponentiation step given ``method``.
Given ``method`` we return the initial order of the approximation error of the
sequence under consideration (order) as well as the step size representing the
growth of the exponent in the series ex... | 6c48956b0d2c016a2409a14f2512257d03b38571 | 441,886 |
def nested_get(dictionary: dict, keys: list):
"""Set value to dict for list of nested keys
>>> nested_get({'key': {'nested_key': 123}}, keys=['key', 'nested_key'])
123
"""
nested_dict = dictionary
for key in keys[:-1]:
nested_dict = nested_dict[key]
return nested_dict.get(keys[-1]) | 87444ae9d67c66b6eb0b4389a4a7bc51a5f05502 | 267,113 |
def lookup_movieId(movies, movieId):
"""
Convert output of recommendation to movie title
"""
# match movieId to title
movies = movies.reset_index()
boolean = movies["movieid"] == movieId
movie_title = list(movies[boolean]["title"])[0]
return movie_title
return movie_title | d7eae506b47a8d9045318e264032ee928c7b8fb2 | 292,537 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.