content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_parallel(a, n):
"""Get input for GNU parallel based on a-list of filenames and n-chunks.
The a-list is split into n-chunks. Offset and amount are provided."""
k, m = divmod(len(a), n)
# chunked = list((a[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(n)))
offset = ' '.join(lis... | 105a9eb4563307612430e9ec812378bc52c022d1 | 688,323 |
def BE_to_LE(value):
"""
Convert Big Endian to Little Endian
@param value: value expressed in Big Endian
@param size: number of bytes generated
@return: a string containing the value converted
"""
data = [char for char in value]
data.reverse()
return int("".join(["%2.2X"%ord(ch... | fd209dd7b85b6a30e8b5caeaad9079ba6a02326b | 688,324 |
import random
def feedback_default(_):
"""This does nothing with the user feedback and simply returns a random
float between 0 and 1.
"""
return random.random() | 4aafea4d11133675da14160ef54eb0be6bbec711 | 688,325 |
def images_composed(connect, list_connections):
"""
combine labels with the same connection
@param connect : dict contain all pixels label and sprite's label that key belong to
@param list_connections : list contain all key label in dict connect
@return a dict contain label and sprite's label that k... | 624bcab3ebcda7c2d399455bf87afdf711f9df4c | 688,326 |
def _format_brief_report_one(result):
"""Formats the given `Result` as a condensed report str."""
report = f'\nExpected mean({result.reduction_size} draws)'
report += f' in {result.expected:.3g} +- {result.tolerance:.3g};'
report += f' got mean ~ N(loc={result.gaussian.loc:.3g}, scale={result.gaussian.scale:.3g... | ff15fc8e0625d617fd693ca6f2b04673a83dded0 | 688,327 |
def positive_probability_delta(By, Bz):
"""
calculates the probability of a positive using the delta equation
:param By: bloom clock By
:param Bz: bloom clock Bz
:return: probability of positive
"""
return int((Bz >= By).all()) | d11abc3f821ce8ba497fa2733e4173d1bf3f7162 | 688,331 |
def get_label_color(status):
"""
Get a customized color of the status
:param status: The requested status to get a customized color for
:return: customized color
"""
colors = {'NEW':'grey',
'ASSIGNED':'blue',
'OPEN': 'orange',
'FIXED': 'purp... | 6bcf168d653801999bc2c2528a426ec43afdd349 | 688,333 |
def GetSyntenicOrthologs(orthologs, last_contig, last_rank,
max_synteny_distance=5):
"""get orthologs that are syntenic to previous one."""
oo = []
for o in orthologs:
if o.contig == last_contig and \
abs(o.mRank - last_rank) <= max_synteny_distance:
... | 28057497cd77321dd8370ec9ec36b86d67c8a802 | 688,334 |
def gaseste_unic(istoric):
"""Functia pentru aflarea elementului cu numar impar de aparitii"""
unic = 0
for curent in istoric:
unic = unic ^ curent
return unic | ce28bd2579aafd40376413d4c96d99365c7c5f16 | 688,335 |
def BitAdd(m, n, length):
"""Return m+n in string.
Arguments:
m -- Binary number in string
n -- Same as above
length -- The length of returned number (overflowed bit will be ignored)
Returns: string
"""
lmax = max(len(m), len(n))
c = 0
ml = [0] * (lmax - len(m)) + [int(x) ... | e30e90567de97e310b1eb8ec0b15d7e4678a93f3 | 688,336 |
def node_type(node):
"""
Node numbering scheme is as follows:
[c1-c309] [c321-c478] old compute nodes (Sandy Bridge)
[c579-c628],[c639-c985] new compute nodes (Haswell)
Special nodes:
c309-c320 old big memory nodes (Sandy Bridge)
c629-c638 new big memory nodes (Haswell)
c577,c578 old huge memory nodes (HP Prol... | 108624339784301d1eb132fd45524f63065e7825 | 688,337 |
def plugger(inbox):
"""
Returns nothing.
"""
return None | fcbcb769b2f73f107fbb3fcbe0dfbf0dae74ee5f | 688,338 |
def remove_duplicates(seq):
"""
Removes duplicates from a list.
This is the fastest solution, source:
http://www.peterbe.com/plog/uniqifiers-benchmark
Input arguments:
seq -- list from which we are removing duplicates
Output:
List without duplicates.
Example:
... | 460e585e04fb7f868e0216e6d82808c68be80a7d | 688,340 |
import torch
def compute_bboxes_from_keypoints(keypoints):
"""
keypoints: B x 68*2
return value: B x 4 (t, b, l, r)
Compute a very rough bounding box approximate from 68 keypoints.
"""
x, y = keypoints.float().view(-1, 68, 2).transpose(0, 2)
face_height = y[8] - y[27]
b = y[8] + face_... | 25a3135c40e9b2e615b2d8dc2eba425ff38177b2 | 688,341 |
def switch_state_function(wanted_object, _, **kwargs):
"""Case 'list function State' """
function_list = []
for allocated_fun in wanted_object.allocated_function_list:
for fun in kwargs['xml_function_list']:
if fun.id == allocated_fun:
function_list.append((fun.name, "Fun... | 22421fcdbdbd84ff327a9aa73e2ddb617f355639 | 688,342 |
def write_matlabbatch(template, nii_file, tpm_file, darteltpm_file, outfile):
""" Complete matlab batch from template.
Parameters
----------
template: str
path to template batch to be completed.
nii_files: list
the Nifti image to be processed.
tpm_file: str
path to the S... | 39cbf74ced5c35e171e18c5261b7f017adb8cd6c | 688,343 |
def shrink_node(node, reg_param, parent_val, parent_num, cum_sum, scheme, constant):
"""Shrink the tree
"""
is_leaf = not node.hasChildNodes()
# if self.prediction_task == 'regression':
val = node.nodeValue
is_root = parent_val is None and parent_num is None
n_samples = len(node.labels) if ... | dd948a9776b763454d5f2bad0a311221a0e01150 | 688,344 |
def run_episode(env, agent):
"""
Shows a UnityAgent perform a single episode in the specified Unity ML environment.
"""
done = False
score = 0 # initialize score
env_info = env.reset(train_mode=False)[agent.brain_name] # reset the environment
while not done:
state = env_info.vect... | 3de2bd34b18bca16bf8ef08ecfa1101a7be531ee | 688,347 |
def average_cases(cases_array):
"""
WHAT IT DOES: Averages out the number of cases over the last 14 days
PARAMETERS: A cases array of integers
RETURNS: An integer of the average amount of cases
"""
len_cases = len(cases_array)
i = 1
loop_cases = 0
while i < 15:
loop_cases =... | ebd1a38262ab11f13d7fed8f5f83ee1c931db3f6 | 688,348 |
def fake_detect_own_answers(input_str):
"""Imitates the ability of a self-aware model to detect its own answers.
In GoodModel.generate_text, we make the model answer with "dummy" to most questions.
Here, we exploit the keyword to cheat the test.
Args:
input_str: String: The model's input, cont... | 180d7ca7962cc3a21fe4798034e604106ceb670b | 688,349 |
import html
import re
def reddit_sanitize( text ):
"""
Convert comments in the Reddit API format to actual plain-text likely
constructed by the individual who posted it. HTML is unescaped, markup
is removed, and quotes are removed.
"""
# Unescape HTML (IE, '>' becomes '>')
text = html.... | 304e3f0900a50d0e2d0e204f7391ba106bed805b | 688,350 |
import click
import functools
def needs_gdf(func):
"""Marks a callback as wanting to receive the current GeoDataFrame
object as first argument."""
def wrapper(*args, **kwargs):
ctx = click.get_current_context().find_root()
gdf = ctx.obj
if gdf is None:
raise click.Click... | f8e29ef766f205f3efe4b280f97bf2363204c23c | 688,351 |
def parse_operating_point(operating_point, operating_kinds, class_names):
"""Checks the operating point contents and extracts the three defined
variables
"""
if "kind" not in operating_point:
raise ValueError("Failed to find the kind of operating point.")
if operating_point["kind"] not in o... | cb12198b4ddb3f830cf7b52bbcc57346e17624c5 | 688,352 |
def ancestors(node):
"""
Returns the list of all nodes dominating the given tree node.
This method will not work with leaf nodes, since there is no way
to recover the parent.
"""
results = []
try:
current = node.parent()
except AttributeError:
# if node is a leaf, we cann... | 6237d5016bc5ba877d62b8da30501119bb50e9ce | 688,353 |
def config2object(config):
"""
Convert dictionary into instance allowing access to dictionary keys using
dot notation (attributes).
"""
class ConfigObject(dict):
"""
Represents configuration options' group, works like a dict
"""
def __init__(self, *args, **kwargs):
... | 1523329a0ba6495d1b23530aa6d02f9c953d7e51 | 688,354 |
import socket
def _get_available_ports(n: int) -> list[int]:
"""
Get available ports.
Parameters
----------
n : int
number of ports to get.
Returns
-------
list[int]
Available ports.
"""
socks: list[socket.socket] = [socket.socket() for _ in range(n)]
list... | 64e4f6f0683ff7df34a2e264c0e22d2d3a7414ec | 688,355 |
def mean(sequence):
"""
Calculates the arithmetic mean of a list / tuple
"""
return sum(sequence) / float(len(sequence)) | aa800eac51de57c9b4c7c5e2fe749f058cfe6c81 | 688,356 |
def get_contained(list1, list2):
""" A function that returns all communs between 2 litst """
return [x for x in list1 for y in list2 if x == y] | 480d4b052efde01208b4f71b0e50b1b1dfe9d250 | 688,357 |
import struct
def pack_integer(format, value):
"""Packs integer as a binary string
I = python 4 byte unsigned integer to an arduino unsigned long
h = python 2 byte short to an arduino integer
"""
return struct.pack(format, value) | 2bd22c430361b2301934387dd9dd6c5b89c7b049 | 688,358 |
import textwrap
def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50):
"""
Takes a proteins dictionary and returns a string containing
all the sequences in FASTA format. Option parameters are
a list of seqids to output (seqids) and the line width (width).
"""
if seqids:
... | 569682abb4f8b0d62cba39f5720e09fb8baf7ec8 | 688,359 |
def table_to_list(cells,pgs) :
"""Output list of lists"""
l=[0,0,0]
for (i,j,u,v,pg,value) in cells :
r=[i,j,pg]
l = [max(x) for x in zip(l,r)]
tab = [ [ [ "" for x in range(l[0]+1)
] for x in range(l[1]+1)
] for x in range(l[2]+1)
]
for (i,j,u,v,pg,value) in cell... | 72dde28ffc4e6103f54df3aede86572dda4af491 | 688,360 |
def convert(type, list):
"""
Converts a Python array to a C type from
``ctypes``.
Parameters
----------
type : _ctypes.PyCSimpleType
Type to cast to.
list : list
List to cast
Returns
-------
Any
A C array
"""
return (type * len(list))(*list) | 37878a78e87bb15dfbf889e971e68812941e137b | 688,361 |
def simpleInterest(amount_borrowed, years_borrowed, interest_rate_percent):
"""assumes amount_borrowed in an int, representing the amoutn fo money borrowed
assumes year+borrowed is an int, representing the years the amount was borrowed for
assumes interest_rate_percent is a number, representing the interest... | 1b9e53fd66ed1a042a63afa66e539d8ff19f43a8 | 688,362 |
def lowercase(data):
"""Lowercase text
Args:
data (list,str): Data to lowercase (either a string or a list
[of lists..] of strings)
Returns:
list, str: Lowercased data
"""
if isinstance(data, (list, tuple)):
return [lowercase(item) for item in data]
elif is... | fd173620e8ddb58d5966b235a3b9236ebf01f9d5 | 688,363 |
import os
from sys import path
import pickle
def save_pickle_file(G,fname, extention):
"""
Saves graph into a pickle.
Parameters
----------
G : NetworkX Graph or DiGraph or iGraph Graph
Graph to save.
fname: string
directory + file name
extention: string
may be an... | ab3580bccb2c4029a5b4c9a70ff430db8e60ada9 | 688,364 |
def overlay_image(foreground_image, mask, background_image):
""" Overlay foreground image onto the background given a mask
:param foreground_image: foreground image points
:param mask: [0-255] values in mask
:param background_image: background image points
:returns: image with foreground where mask > 0 overla... | fb6b8a854e99fe984b6f57eb683a8f77a507e155 | 688,365 |
def eq_or_in(val, options):
"""Return True if options contains value or if value is equal to options."""
return val in options if isinstance(options, tuple) else val == options | bbaa3fbc91429adc7db4c6fcbcfeb860508ade21 | 688,366 |
def get_users(cfmclient, params=None):
"""
Function to query current local users from a Composable Fabric Manager represented
by the CFMClient object
:param cfmclient: Composable Fabric Manager connection object of type CFMClient
:return: list of dict where each dict represents a CFM... | 2e009c88a9baa4bdf3f6a07304dc60a4e107f4f9 | 688,367 |
from typing import Counter
def get_bow(tokenized_text):
"""
Function to generate bow_list and word_freq from a tokenized_text
-----PARAMETER-----
tokenized_text should be in the form of [['a'], ['a', 'b'], ['b']] format,
where the object is a list of survey response, with each survey response
... | 656d9dab1b2bee350cecca5fd693fcbc3eafb2bd | 688,368 |
def is_same_py_file(file_1, file_2):
"""Compares 2 filenames accounting for .pyc files."""
if file_1.endswith('.pyc') or file_1.endswith('.pyo'):
file_1 = file_1[:-1]
if file_2.endswith('.pyc') or file_2.endswith('.pyo'):
file_2 = file_2[:-1]
return file_1 == file_2 | 897c6b84389290d98bf4fa449763a01c83354302 | 688,369 |
def multiply(x: float, y: float) -> float:
"""
Multiply 2 numbers.
Although this function is intended to multiply 2 numbers,
you can also use it to multiply a sequence. If you pass
a string, for example , as the first argument, you'll get
the string repeated `y` times as the returned value
... | a76c0da79523402d645fbd01a418a57cab5762f4 | 688,370 |
import torch
def loglikelihood(w, weights=None):
"""
Calculates the estimated loglikehood given weights.
:param w: The log weights, corresponding to likelihood
:type w: torch.Tensor
:param weights: Whether to weight the log-likelihood.
:type weights: torch.Tensor
:return: The log-likelihoo... | fbaff2c7d99c11b6c7d5dd2296b8470fdd798e03 | 688,371 |
def resolve_crop(im, crop):
"""Convert a crop (i.e. slice definition) to only positive values
crops might contain None, or - values"""
# only works for two dimension
crop = list(crop)
assert len(crop) == 2
for i in (0, 1):
assert len(crop[i]) == 2
for j in (0, 1):
if ... | 791331619401664f9cb4c4d01f852b39a568f585 | 688,372 |
import csv
def write_d10d11_singlecell(packed_data):
"""Write the content of cell in a D10 and D11 file."""
fname, cid, d10data = packed_data
if d10data is None:
fname = None
else:
with open(fname, 'w') as csvfile:
writer = csv.writer(csvfile, lineterminator='\n')
... | 0c37479f7582beb058a4889ffb953cab2b65f3b3 | 688,373 |
def normalize_spaces(s):
"""replace any sequence of whitespace
characters with a single space"""
return ' '.join(s.split()) | f602797e46ec70309326fa71b305e24d2c180190 | 688,375 |
def checksum(digits):
"""
Returns the checksum of CPF digits.
References to the algorithm:
https://pt.wikipedia.org/wiki/Cadastro_de_pessoas_f%C3%ADsicas#Algoritmo
https://metacpan.org/source/MAMAWE/Algorithm-CheckDigits-v1.3.0/lib/Algorithm/CheckDigits/M11_004.pm
"""
s = 0
p = len(digit... | 0e3f8cc4b1f42265f27c03b10559183f0bbd87e0 | 688,376 |
def fa5_icon(name, style_prefix='fas', title=None):
"""Returns a HMTL snippet which generates an fontawesome 5 icon.
Parameters:
style_prefix: str
'fas' (default) for solid icons, 'far' for regular icons
"""
return {
'classes': f'fa-{name} {style_prefix}',
'title': ... | 1c82dfd8199a3db1212623299b4b6b5f0436f765 | 688,377 |
import os
def get_file_path(category, file_name):
"""
ie: examples/generic/adder.qasm
- category: "generic"
- file_name: "adder"
"""
return os.path.join(os.path.dirname(__file__), "../examples", category, file_name + ".qasm") | a4f6fcbe3dc05c439b588e8c13ba09236188c0a6 | 688,378 |
def find_rlc(p_utility, q_utility, r_set, l_set, c_set):
"""
Proportional controllers for adjusting the resistance and capacitance values in the RLC load bank
:param p_utility: utility/source active power in watts
:param q_utility: utility/source reactive power in var
:param r_set: prior resistor %... | ec6a4476bb842f0e305e25da0245a4ee2c0945b0 | 688,380 |
import os
import re
def deformable_alignment_population(affine_template, subjects_affine,
output_dir, ftol):
""" Wraps DTI-TK script dti_diffeomorphic_population which improves
alignment by removing size or shape differences between local
structures.
Parameters
... | b2f71ea9ade5a052febeb4b2d936075c4e0acf49 | 688,381 |
def score1(rule, c=0):
"""
Calculate candidate score depending on the rule's confidence.
Parameters:
rule (dict): rule from rules_dict
c (int): constant for smoothing
Returns:
score (float): candidate score
"""
score = rule["rule_supp"] / (rule["body_supp"] + c)
r... | c329d1154d59aed6bf62f0af1bcbbd7e237871c2 | 688,382 |
import os
def checking_dir(dir_name):
"""Checking if a directory is existed, if not create one.
Args:
dir_name (str): parent directory
folder (str, optional): Name of folder. Defaults to "data".
Returns:
dir (str): checked directory
"""
if not os.path.exists(dir_name):
... | 5810d7b9533180d3cdc3eeaf19e5239877b0b6ac | 688,383 |
def sort_paths(paths):
"""Returns a list ordered by path length"""
output = []
longest = 0
for path in paths:
length = len(str(path.resolve()))
if length >= longest:
output.insert(0, path)
longest = length
else:
output.insert(len(output), path)... | feb6f5f3b66e569bc637211bde15ebc29e0de256 | 688,384 |
import os
def is_file(path):
"""Checks whether a path exists and is a regular file"""
try:
return os.stat(path)[0] & 61440 == 32768
except OSError as e:
if e.args[0] == 2:
return False
else:
raise e | c92f1c540209a5f7c7b960ca18cbcb16ef3e1cec | 688,385 |
def _package_key_options(metadata):
"""Command-line arguments related to the current package key."""
return [
"-this-unit-id",
metadata.key,
"-optP-DCURRENT_PACKAGE_KEY=\"{}\"".format(metadata.key),
] | 5e03ed40ca152ed8b34ad077251dac1e516e7d94 | 688,386 |
import logging
import json
def extract_english_corpus(json_str, verbose=False):
"""A helper function to extract English corpus from KPTimes dataset in json
:param: json_str: the json string
:param: verbose: bool, if logging the process of data processing
:returns: the articles and keywords for each ... | 7a587733c24a33a5140dac695f4d10a5c18d6e97 | 688,387 |
def get_freq_avg(ts, freq="10T", fill_method='pad', fill_method2=None):
"""resample the timeserie with the new frequence <freq> using the fill methods for NANs"""
#"""
res = ts.resample(freq)
if fill_method == "pad":
res = res.pad()
elif fill_method == "ffill":
res = res.ffill()
... | f0b57509ea201cf9257e80060cecf63157892ff3 | 688,388 |
def inter_visit_features(data_df, mini_data_df):
"""
For each member, compute:
1. Difference in days_stay between current and previous/next visit
2. Difference in roomnights between current and previous/next visit
3. Difference in days_advance_booking between current and previous/next visit
:par... | 7fff50ba4de13d3e1ccca025a3b0da8663c67330 | 688,389 |
def _get_prefixes_for_action(action):
"""
:param action: iam:cat
:return: [ "iam:", "iam:c", "iam:ca", "iam:cat" ]
"""
(technology, permission) = action.split(':')
retval = ["{}:".format(technology)]
phrase = ""
for char in permission:
newphrase = "{}{}".format(phrase, char)
... | b1bbb164f13a156bcf0d9c75a6e5614d266ec053 | 688,391 |
def multiply(*args):
"""Multiplies list of inputed sys arguments"""
mul = 1.0
for arg in args:
mul *= arg
return mul | 3c0c382ee223720d1f33c1176104295651af534d | 688,392 |
import re
def humansorted_datasets(l, key=None):
"""Sort a list of datasets according to a key of a dataset
Parameters
----------
l : list
The list of datasets to be sorted
key : str (optional)
The key of the dataset the datasets should be sorted according to.
Defaults to ... | 8817fb61b563feaec51aa6ae35c7df1ae20f4ac7 | 688,393 |
def sum_multiples_three_five(number):
"""
number: random integer
return: the sum of all multipliers of 3 and 5 below number
"""
multipliers = []
n = 0
while n < number:
if n % 3 == 0 or n % 5 == 0:
multipliers.append(n)
n += 1
return sum(multipliers) | 8a8b5fcd5c66db6a9dea95e0a7fc5d3c5a7900a6 | 688,394 |
def asURL(epsg):
""" convert EPSG code to OGC URL CRS
``http://www.opengis.net/def/crs/EPSG/0/<code>`` notation """
return "http://www.opengis.net/def/crs/EPSG/0/%d" % int(epsg) | f0bb82853e2782cbef7fbd54414c26a159669a08 | 688,395 |
def build_complement(dna):
"""
:param dna: The original DNA strand input by user.
:return: The complement strand of the original DNA.
"""
new_dna = ''
for nucleotide in dna:
if nucleotide == "A":
new_dna = new_dna + "T"
elif nucleotide == "T":
new_dna = ne... | 0af5c4a120a4df408be86ba46e6227000a2f75f4 | 688,396 |
def state_to_mask(state):
"""Gets the mask of valid DCs for the latest order"""
latest_open_order = state.open[0]
customer_id = state.physical_network.get_customer_id(
latest_open_order.customer.node_id
)
mask = state.physical_network.dcs_per_customer_array[customer_id, :]
return mask | cae79c44d6a2bfd90ab0cac3a36e4a50d8dd10c2 | 688,397 |
def filetxt_if_txt(filepath):
"""
return filetxt if the file is text. Otherwise, raise IOError
"""
lines = []
with open(filepath,'rb') as F:
for line in F:
if b'\0' in line:
raise IOError('File is binary (or contains a null character)')
try:
... | bf503540df693ebd765f113ee8bfa6a80710eeed | 688,398 |
import os
def get_suffix(name):
"""
Return the suffix of name.
Example: given name = 'file.f90', return '.f90'.
"""
return os.path.splitext(name)[1] | 2cc8bf91823a3fa4cee15796aa330d8f5e176506 | 688,399 |
def example_channel():
"""
Purpose:
Set example channel to post to in Slack
Args:
N/A
Return:
example_channel (Pytest Fixture (String)): example channel to post to in Slack
"""
return "#fake_channel" | fb31777728a8ee016e01b970ee485f781d111b70 | 688,400 |
import copy
def min_specializations(h,domains,x):
"""Implement a function min_specializations(h, domains, x)
for a hypothesis h and an example x. The argument
domains is a list of lists, in which the i-th
sub-list contains the possible values of feature i.
The function should return all minimal specializati... | fb0205ca1a25aa31bcc9ebb4eefbacbd2dce8800 | 688,401 |
def clipping_img(img, points):
"""
Baesed on the appoint points to clip the image, thus we are able to acquire the part to recognize.
:param img: the processed image
:param points: the corner points of the table we wanna to recognize in the image.
:return:
"""
(x0, y0), (x1, y1), (x2, y2), (... | 053554532b77c62e53cf24c28bd44ee60f1511a8 | 688,402 |
import random
def random_cell(grid, snake):
"""
Generates a new random position on the space of free cells.
:param grid: The grid.
:param snake: The snake whose body will represent occupied cells.
:returns: Position of a free cell.
"""
while True:
x = random.randrange(grid.rows)
... | f4cb0d7940c07e94972de3c1e38c3a9116acb435 | 688,403 |
def point_in_polygon(point, polygon):
"""
Determines whether a [x,y] point is strictly inside a convex polygon
defined as an ordered list of [x,y] points.
:param point: the point to check
:param polygon: the polygon
:return: True if point is inside polygon, False otherwise
"""
x = point... | a776f16b6560d2efcc8e86a56f89029cb35a2867 | 688,404 |
def has_deepnet(args):
"""Returns whether some kind of deepnet
"""
return args.deepnet or args.deepnets or \
args.deepnet_tag | 1c69befbccb2b2d9344c37aab15d3d3ac1301167 | 688,405 |
def pagerank(graph, damping_factor=0.85, max_iterations=100, \
min_delta=0.00001):
"""
Compute and return the PageRank in an directed graph.
@type graph: digraph
@param graph: Digraph.
@type damping_factor: number
@param damping_factor: PageRank dumping factor.
@type max_i... | 6f4c8e4f91dc93a2b60dad8ba8961aebf864e3cc | 688,406 |
def _digraph_to_graph(digraph, prime_node_mapping):
"""Convert digraph to a graph.
:param digraph: A directed graph in the form
{from:{to:value}}.
:param prime_node_mapping: A mapping from every
node in digraph to a new unique and not in digraph node.
:return: A symmetric graph in the f... | 184b0c904d35156b219be9469e2170cc5bbbceaf | 688,407 |
import sys
def openForCsv(path):
""" Open a file with flags suitable for csv.reader.
This is different for python2 it means with mode 'rb',
for python3 this means 'r' with "universal newlines".
"""
if sys.version_info[0] < 3:
return open(path, 'rb')
else:
return open(path, 'r',... | 22ecb168dd33334b90e688f0941c2882faf18651 | 688,408 |
import itertools
def generate_peptide_pattern(pattern):
"""
Method to generate a peptide sequences following a pattern using only natural amino acids
Arguments:
pattern -- Pattern based on XX to generate the list of sequences
Return:
list_peptides -- List with the sequences generated... | ed1fe3008d40979f1883fe6a8478dd67af7da40c | 688,409 |
def tag(pages, tag):
"""Pages with a given tag."""
if not tag:
return pages
return [p for p in pages if tag in p.tags] | aadb70a84364042863e57bc6aa40b2ff8f4a4158 | 688,410 |
def get_speciesindices(specieslist):
"""
Create a dictionary to assign an arbitrary index to each of the species in
the kinetic scheme.
Parameters
----------
specieslist : list
a list of all the species in the model
Returns
-------
speciesindices : dict
... | 8f309de181cbed3eb6499821da59116a426c16c3 | 688,412 |
def dump_cookies(cookies_list):
"""Dumps cookies to list
"""
cookies = []
for c in cookies_list:
cookies.append({
'name': c.name,
'domain': c.domain,
'value': c.value})
return cookies | b04b1a54bc4aa10e15fe5e28d59b4b9a51a89f1f | 688,413 |
def distHamming(lineA, lineB):
"""
Hamming distance
Input: two bytearrays of equal length
Output: number of differing bits
"""
if len(lineA) != len(lineB): raise ValueError("lineA and lineB need to be same length")
diffBits = 0
for i in range(len(lineA)):
a = lineA[i]
b... | 4a1b1e7f38891bf18f2c2567b1de0d02d4fff919 | 688,414 |
def is_optimal_id(id):
"""
Returns true if the Cremona id refers to an optimal curve, and
false otherwise. The curve is optimal if the id, which is of the
form [letter code][number] has number 1.
.. note::
990h3 is the optimal curve in that class, so doesn't obey
this rule.
INPU... | bab98f7d821882e8e213b4205d6cac598f9f588a | 688,415 |
from typing import List
from typing import Dict
def divide_blocks(
blocks: List[int],
world_size: int) -> Dict[int, List[int]]:
"""
Divide the blocks into world_size partitions, and return the divided block indexes for the
given work_rank
:param blocks: the blocks and each item is the ... | ff14768161a78aacccfe827f00493482dd54c830 | 688,416 |
def split_train_test(X, y, test_percentage):
"""
Randomly split given dataset into training- and testing sets
:param X: Design matrix to split
:param y: Response vector to split
:param test_percentage: Percentage of samples to use as test
:return: Two tuples of: (train set X, train set y), (test... | 7f98f9bb5ef9376308da9e10518c94ee1680f71e | 688,417 |
def p1_f_linear(x):
"""DocTest module Expected Output Test - don't change or delete these lines
>>> x = [565, 872, 711, 964, 340, 761, 2, 233, 562, 854]
>>> print("The minimum is: ",p1_f_linear(x))
The minimum is: 2
"""
# ******ENTER YOUR FINAL CHECKED CODE AFTER THIS COMMENT BLOCK***... | 3f2cf29418d29aacce8e86f2b644da98cb683313 | 688,418 |
import base64
def GenerateId_base64old(hash_sha512, input_file):
"""
Implement asset id of input file for base64 format
@param hash_sha512: string to encode
@param input_file: input file to encode
"""
string_id = base64.b64encode(hash_sha512)
return string_id | 279110a69445b840d207cc415fba9de18d39662a | 688,419 |
def erroCsv(csvFile):
"""
Rename the csv file with err notation
:param csvFile: input csv file name
:return: new file name
"""
return csvFile.replace('.csv', '_err.csv') | 5d53de212072be4b28f2655c75e6205af27eed69 | 688,421 |
from typing import Iterable
def _format_point_value(value: Iterable) -> str:
"""Convert a iterable with a point to text."""
return ' '.join(str(v) for v in value) | 8f9387139d4f09100af6a077621a6e4c4ae23712 | 688,422 |
from typing import List
def _generate_sharded_filenames(filename: str) -> List[str]:
"""Generates filenames of the each file in the sharded filepath.
Based on github.com/google/revisiting-self-supervised/blob/master/datasets.py.
Args:
filename: The sharded filepath.
Returns:
A list of filepaths for... | 4686aee6dc4d1924dfb1745c5d8a3ae77a604a85 | 688,423 |
def drop_columns(tabular, n):
"""drops first n items from each row and returns new tabular data
>>> drop_columns([[1, 2, 3],
[21, 22, 23],
[31, 32, 33]],
1)
[[2, 3], [22, 23], [32, 33]]
"""
return [row[n:] for row in tabular] | d70698637c96eb579439e01bf7c913f7d64d3567 | 688,424 |
import pandas
def replicate_df_for_variable(hh_df, var_name, var_values):
"""
Duplicate the given hh_df for the given variable with the given values and return.
"""
new_var_df = pandas.DataFrame({var_name: var_values})
new_var_df["join_key"] = 1
hh_df["join_key"] = 1
ret_hh_df = pand... | a3bfb5721ca063c567807bd5fd9911c4311f1585 | 688,425 |
def clicked_quality_reward(responses):
"""Calculates the total clicked watchtime from a list of responses.
Args:
responses: A list of IEvResponse objects
Returns:
reward: A float representing the total watch time from the responses
"""
qual = 0.0
watch = 0.0
for response in res... | a1b1b5cd93b759775125f486146823e771fc4231 | 688,426 |
def get_nim_sum(state: tuple[int, ...]) -> int:
"""
Get the nim sum of a position. See https://www.archimedes-lab.org/How_to_Solve/Win_at_Nim.html
:param state: the state of the game
:return: the nim sum of the current position
"""
cur_sum = 0
for n in state:
cur_sum ^= n
return cur_sum | d1b3cf67d86fce56ffd69cb6ede438b8c2cc85f6 | 688,427 |
def DES3200(v):
"""
DES-3200-series
:param v:
:return:
"""
return v["platform"].startswith("DES-3200") | 377abe2ba49ab6e38c2be79c668715ed4a3faf6c | 688,428 |
def strip_article_title_word(word:str):
"""
Used when tokenizing the titles of articles
in order to index them for search
"""
return word.strip('":;?!<>\'').lower() | b9071dad28c9efc3153ecbe6ac418369a8ef60fe | 688,430 |
def compValAlla(v1, v2):
"""
Compare in-values and return a list of 0/1 in the order
both exist and equal, both exist and not equal, does not exist
"""
if ((not v1) or (not v2)): return [0,0,1]
elif v1 == v2: return [1,0,0]
else: return [0,1,0] | a2cc3c5ec55e7352f8e068918047075b83b454a0 | 688,431 |
import os
def list_dir( extension=".xls", path="."):
""" Called to list the excel files in the current path. Ignores all files
that may be excel files but are not measurement files
Parameters
----------
extension : string
file extension, typically .xls or .xlsx
path : string
f... | ed5ed3bae74f85e99d0aaffe451a611d5471f2f0 | 688,432 |
import os
def create_dir(page_name):
"""
make a new directory for non-existing page data directory
Args:
page_name (str)
Returns:
[boolen]: return True if the directory not exist and make it
return False if the directory exist
"""
dir_path = "./data/%s" %... | 484aa46a2eaf300d620c32b1e90ee22075dd5e39 | 688,433 |
import math
def quadratic(eq):
"""solves simple quadratic equation"""
a, b, c = map(int, eq.split())
d = b ** 2 - (4 * a * c)
if d < 0.0:
return 'None'
elif d > 0.0:
return ', '.join(list(map(str, [(-b + math.sqrt(d)) /(2 * a), (-b - math.sqrt(d)) /(2 * a)])))
else:
ret... | 429f5f4f882f40356fb19ea8d5cd127883e0d132 | 688,434 |
import csv
def read_matrix_of_drugs(matrix_file):
"""
Read a matrix file of the comparison.
"""
drug_id = 1
ids_drugs_removed = set()
with open(matrix_file, 'r') as matrix_fd:
data = csv.reader(matrix_fd, delimiter=',')
for row in data:
if not '1' in row:
... | fe922f7c7df2845fbf7c171250c2dae5bd830b71 | 688,435 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.