content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def clean_attribute_spacing(lines):
"""Justify the spacing of attributes accross multiple xml elements
This is accomplished by adding spaces to the attributes smaller
than the largest of its type.
Args:
lines (string): Lines of xml to process
Return:
list. Lines of text... | 2b5153127c92369be287eb70e648ba2ce5b4ee85 | 689,353 |
def parse_args_and_kwargs(cmdline):
"""
cmdline: list
returns tuple of: args (list), kwargs (dict)
"""
# Parse args and kwargs
args = []
kwargs = {}
if len(cmdline) > 1:
for item in cmdline[1:]:
if '=' in item:
(key, value) = item.split('=', 1)
... | 9f57d3ea9ad5780d0319e37c81c75228de504ddc | 689,354 |
def isodate(dt):
"""Takes a date, returns ISO8601 date format"""
return dt.strftime('%Y-%m-%d') | 9f29806f8473db762bbbdb7bb99da56ba527fd4e | 689,355 |
def start_smash(stage=None, game_type=None):
"""Provides information to start the game in smash mode. The function takes the parameters to
set the stage and game type. It checks whether any arguments were passed to these parameters
and returns an f-string based on the parameters passed.
Parameters:... | f66aeb4c4cc5afbbec4b991dda70e9a68fc1e4ee | 689,356 |
def _cell_index(dataframe, template='phderi'):
"""Return cell index (column, row) of first value on pivot.
Parameters
----------
dataframe : DataFrame
Raw dataframe imported from excel
template : str, optional
Template, by default 'phderi'
Returns
-------
list
R... | 3d290b0f5ff12077d903f979ce9c9b42de37f44b | 689,357 |
import subprocess
def check_for_git(function):
"""
Makes sure git is installed on the system.
Returns None if it is not.
"""
def _check_for_git(*args, **kwargs):
try:
subprocess.check_call(
"git config --global --list &> /dev/null",
shell=True
... | 645f748d7e192ac4d6a53c0cdae3484a989ed185 | 689,359 |
import torch
def train_mlp(model, epoch, *args, **kwargs):
"""
Simple example of training a model using the
@train decorator.
:param model: The model that we will be training
:param epoch: The current epoch
:param args: Extra arguments passed
:param kwargs: Key word... | 0d65cd6e217e049736be09a8e77985df55658f26 | 689,360 |
def name(self):
"""
Save name which can be used for alphabetic sorting and can be turned
into a kwarg.
"""
base_str = 'd{}{}_'.format(self.derivative_count if
self.derivative_count > 1 else '', self.expr)
for var, count in self.variable_count:
base_str += '... | 9cb57ed5de725349a3aebc8b7ea91c5b34cf55fe | 689,361 |
def context_combination(
use_docker,
include_docker_compose,
include_page_view_tutorial,
faust_loglevel,
worker_port,
kafka_server_environment_variable,
include_codec_example,
include_schema_registry,
include_rocksdb,
):
"""Fixture that parametrize the function where it's used.""... | b034535e6120277973ccf63f3e43e45c117a95ce | 689,362 |
import argparse
def parse_args():
"""parse command line arguments and return them as Namespace"""
parser = argparse.ArgumentParser(
description='Generates variants from an embedded tex doc and compiles them to a combined PDF.')
parser.add_argument('texfile', help='the tex file where the two variants shall be cr... | 1682d953b10b381434262990b8cfedea5d649f30 | 689,363 |
import os
def mpath(path):
"""Converts a POSIX path to an equivalent Macintosh path.
Works for ./x ../x /x and bare pathnames.
Won't work for '../../style/paths'.
Also will expand environment variables and Cshell tilde
notation if running on a POSIX platform.
"""
if os.name == 'mac' : #I... | 7970215f257049b65ec189dd8562b8812d0ad305 | 689,364 |
def splitIntoTetrahedra(poly = "const PolyClipperPolyhedron&",
tol = ("const double", "0.0")):
"""Split a PolyClipper::Polyhedron into tetrahedra.
The result is returned as a vector<vector<int>>, where each inner vector is a set of four
ints representing vertex indices in the input Polyhedro... | 1399e39cf54b9da0b597d9e0cf06728b467c4159 | 689,365 |
def is_change_applicable_for_power_state(current_power_state, apply_power_state):
""" checks if changes are applicable or not for current system state
:param current_power_state: Current power state
:type current_power_state: str
:param apply_power_state: Required power state
:type a... | 26751cbaba9897f740949a967a68ea14129fbcfd | 689,366 |
def update_start(tournaments):
"""Update the start date for the tournaments query based on the most recent data"""
# This is fragile, but should only have to work like twice
return tournaments[0]['events'][0]['createdAt'] | f69e4ca9bedb40de0c12e191e8c39324a7fad98a | 689,367 |
def add_members_to_policy(role: str, iam_policy: list, members: list, command_name: str) -> list:
"""
Append members to policy role members.
Args:
role (str): The name of policy role.
iam_policy (list): IAM policies.
members (list): Members to append to policy.
command_name (... | c8faa020b8349f0ad9a8f41e48b8ee26cc8db0ec | 689,368 |
def interseccion(m1,b1,m2,b2):
"""Da la interseccion entre dos rectas"""
if m1 != m2:
return False
x = (b2-b1) / (m1 - m2)
y = m1* x + b1
return (x,y) | 2099e3a8a551936198e4bdfe092f32d9c16476a3 | 689,369 |
def _is_decoy_suffix(pg, suffix='_DECOY'):
"""Determine if a protein group should be considered decoy.
This function checks that all protein names in a group end with `suffix`.
You may need to provide your own function for correct filtering and FDR estimation.
Parameters
----------
pg : dict
... | 77da0255f7fe9672f502817bd5ab07f0bd6e3159 | 689,370 |
import os
import time
def is_stale(target, freshness_interval):
"""
Determines if a device list is stale.
:param target: the file path to be checked
:param freshness_interval: elapsed seconds the target is considered fresh
:return: True if device list should be refreshed, False otherwise
"""
... | ab63add8f7f5bdb8d9e3f8a4ec4d1c4731b886cf | 689,371 |
def indeterminate(seg):
"""Returns true as long as the segment is internally consistent.
Checks invariants of mark_done, depending on whether the segment
has been uploaded. This is useful in cases with tests with
failures and concurrent execution, and calls out the state of the
segment in any case... | 7b8911b17950ebf9c1d1372750ddd987a0bdbac9 | 689,372 |
import mpmath
def calc(algorithm: str, accuracy: int) -> mpmath.mpf:
"""Return Pi.
Args:
accuracy (int): accuracy
algorithm (str): algorithm by which pi is calcurated
Returns:
mpmath.mpf: Pi value
"""
pi: mpmath.mpf = globals()[algorithm].pi(accuracy) # pylint: disable=i... | c94138cec64556702acf82a2573888e4b5340795 | 689,373 |
def get_grant_name(grant):
"""Get grant name based on Grantee type."""
grant_name = ""
if grant["Grantee"]["Type"] == "Group":
uri = grant["Grantee"]["URI"]
grant_name = uri.rsplit("/", 1)[-1]
if grant["Grantee"]["Type"] == "CanonicalUser":
grant_name = grant["Grantee"]["Display... | ec97f7edaada27d3a2670dbcadc1191f4371626b | 689,374 |
import _struct
def int_to_packed(int_val):
"""
:param int_val: the integer to be packed.
:return: a packed string that is equivalent to value represented by an
unsigned integer.
"""
return _struct.pack('>I', int_val) | 37d31e041d898e067047ca933fcfaa662a208ffa | 689,375 |
def validate_params(params):
"""
Validate the parameters passed to KBParallel.run_batch
Also refer to the type def for run_batch in KBParallel.spec
"""
if 'tasks' not in params or not params['tasks']:
raise ValueError('"tasks" field with a list of tasks is required.')
if 'runner' not in ... | d08fb83588e75892c3fcfef31eb6882f8bdf0f1b | 689,376 |
def check_for_negatives(terms):
"""
Returns `True` for a list of sympy expressions contains any
expressions that are negative.
Parameters
----------
terms : list of sympy expressions
A list where expressions may be either positive or negative.
Returns
-------
bool
... | 9c2ce07ad46f531d094e7da97bba7b2f41197444 | 689,377 |
import subprocess
import traceback
def play_audio(audio_path):
"""
Play audio
"""
try:
subprocess.call(["ffplay", "-nodisp","-af","atempo=0.9", "-autoexit","-hide_banner","-loglevel","error", audio_path])
#if sys.platform == "win32":
# os.startfile(audio_path)
#else:... | 9788533d590d98aaec55a5de1d83f6c497d25329 | 689,378 |
def get_powermax_portgroup_parameters():
"""This method provide parameter required for the ansible port group modules on PowerMax"""
return dict(
portgroup_name=dict(required=True, type='str'),
ports=dict(required=False, type='list'),
state=dict(required=True, type='str'),
port_s... | 7fdce4019c0fb40017ab8826fac74a00b4f85772 | 689,379 |
import os
import csv
def load_key(keys_path):
"""Load beatport_key format key data from a file
Args:
keys_path (str): path to key annotation file
Returns:
list: list of annotated keys
"""
if keys_path is None:
return None
if not os.path.exists(keys_path):
ra... | a3c119ed11b14997f2ca9b065918598a4186b27f | 689,380 |
import re
def filt(seq, lst):
"""
filters lst. returns sublist
Args:
seq: list
used to build a regex for matching
lst: list
Returns:
slst: list
elements of lst that match at least one element of seq
"""
regex = "(" + ")|(".join(seq) + ")"
regex = re.compile(... | 06d6403f22a37089e3aad7fa42049d1ee97eaabc | 689,381 |
import re
def get_task_name_without_suffix(task_name, variant_name):
"""Return evergreen task name without suffix added to the generated task.
Remove evergreen variant name, numerical suffix and underscores between them from evergreen task name.
Example: "noPassthrough_0_enterprise-rhel-80-64-bit-dynamic... | f4ddda7d8f7d778f15f9f7d81751c0fad4fba444 | 689,382 |
def get_decision_sequence(size):
"""
Get the decision sequence for generating valid cycles with DGMG for teacher
forcing optimization.
"""
decision_sequence = []
for i in range(size):
decision_sequence.append(0) # Add node
if i != 0:
decision_sequence.append(0) # ... | 32d70e0161ac141d269f0ec5463ad0496fced23f | 689,383 |
def struct2Str(edge, chart, grammar):
"""Returns a string representation of the parse with
labled brackets.
Parameters:
edges - the lsit of edges that make a parse
chart - the current chart (list of edges)
"""
tmpstr = ""
edgenums = chart[edge][5]
tmpstr = "".join((tmpstr, "[", g... | 99668d74bdac129c0e8e14327d48d1bff6f6e5b1 | 689,384 |
def split_fn_ext(filename):
"""
Return tuple of directory and filename and extenstion.
"""
l = filename.rpartition('.')
d = filename.rpartition('/')
l = d[2].rpartition('.')
di = ''
if d[0] == '':
di = ''
else:
di = d[0] + '/'
return (di, l[0], l[2]) | c553fe5c44d9ddfc863457db3a002d7e82ea9817 | 689,385 |
def answer(input):
"""
>>> answer("+3\\n+3\\n+4\\n-2\\n-4")
10
>>> answer("+7\\n+7\\n-2\\n-7\\n-4")
14
"""
y = []
z = 0
zs = []
ins = input.split('\n')
while True:
for x in ins:
#y.append(int(x))
z += int(x)
if z in zs:
... | d3d844d8db24c1abb2d2152f421db92a5c60bf48 | 689,386 |
import requests
import json
def get_identiy_endpoints(access_token):
"""
Function to get list of mac-addresses from Aruba OS switch
:param auth: AOSSAuth class object returned by pyarubaoss.auth
:return list of mac-addresses
:rtype list
"""
headers = {'Accept': "application/json", 'Author... | 2849ee2593e9210dc5d8e8d7193dd5e20d2d2123 | 689,387 |
from typing import Counter
def modify_mesa_terminal_output(input_file, output_file, i_ignore=2,
files=[]):
"""
Input:
- input_file: output text file from mesa run with write(*,*) statements
- output_file: modified version of the output file to write to
- i_ignore: i... | cd25b56a7c9c7d1d172f900ada53f8cdab356de0 | 689,388 |
import os
def OfficialBuildSpecPath(version_info):
"""Generate an offical build version build spec file path.
Args:
version_info: VersionInfo instance describing the current version.
Returns:
Path for buildspec, relative to manifest_versions root.
"""
return os.path.join(
'buildspecs',
... | 994bfd1dc0d380d01991659020765ae480f3dd66 | 689,389 |
import asyncio
import functools
import glob
async def aglob(pathname, *, recursive=False):
"""
:py:mod:`asyncio` wrapper for :py:func:`glob.glob`.
"""
loop = asyncio.get_running_loop()
return await loop.run_in_executor(
None, functools.partial(glob.glob, pathname, recursive=recursive)) | 65ad538f2d30750aa85d56a60c067d3bf0c6a3db | 689,390 |
def drop_last_month(df):
"""Drop last month, which might have missing data.
For first month, Jan 2012, we have complete data.
"""
ym = df.transaction_date.dt.to_period('M')
return df[ym < ym.max()] | f5a5be8ac8dd5d8b2fe4c40f8d1e99c645699927 | 689,391 |
import re
def parse_list_str(setting_str):
"""
Split a string like 'foo, bar' into ('foo', 'bar').
Also handles 'irregular' spacing like "foo ,bar".
"""
return re.split('\s*,\s*', setting_str) | 7c264bf945114d166776f20fe60877d5e6bca1e6 | 689,392 |
def collatz_rec(p, nr_steps):
"""Recursive Collatz Step Calculation"""
nr_steps += 1
if (p <= 1):
return nr_steps
if p % 2 == 0:
return collatz_rec(int(p/2), nr_steps)
else:
return collatz_rec(int(3*p + 1), nr_steps) | e00d869d18425dbd09bbb490a63ad97480643806 | 689,395 |
import sys
import importlib
import pkgutil
def import_submodules(package_name):
""" Import all submodules of a module, recursively
:param package_name: Package name
:type package_name: str
:rtype: dict[types.ModuleType]
"""
package = sys.modules[package_name]
return {
name: impor... | 60d905a745c0607de9d78cade51d3291c6508a16 | 689,396 |
def scientific(x, n):
"""Represent a float in scientific notation.
This function is merely a wrapper around the 'e' type flag in the
formatting specification.
"""
n = int(n)
x = float(x)
if n < 1: raise ValueError("1+ significant digits required.")
return ''.join(('{:.', str(n - 1), 'e}')).format(x) | ef208058722d8d08912f38c1f127fa6639f29d5a | 689,397 |
def prCal(scoreList, prk, rightOne):
"""计算scoreList的prk值
Params:
scoreList: list of tuple (node, score)
prk: the top n nodes to consider
rightOne: ground truth nodes
"""
prkSum = 0
for k in range(min(prk, len(scoreList))):
if scoreList[k][0] in rightOne:
... | f125b9a64fe4be7e3e32ff436cd3665a2c7e8fb2 | 689,398 |
def _generate_reset_key(user):
"""Return a reset key for the given User factory stub object."""
return "{0}_reset_key".format(user.name).lower() | 8701d398cf530d399fffa498855e69802b373418 | 689,399 |
def getFactoryMeritMultiplier(factoryId):
"""
Returns the skill merit multiplier for a particular factory.
factoryId is the factory-interior zone defined in ToontownGlobals.py.
"""
# Many people complained about how many runs you must make now that
# we lowered the cog levels so I have upped thi... | 2340ff5b8a8ece16b1fece2dfa02d725acc97a13 | 689,400 |
from typing import Optional
import math
def _seconds_to_frame_index(
time_in_seconds: float, fps: int, zero_indexed: Optional[bool] = True
) -> int:
"""
Converts a point in time (in seconds) within a video clip to its closest
frame indexed (rounding down), based on a specified frame rate.
Args:
... | 63b5e3e6631fd6d5e58fb0eef12721df37163e7f | 689,401 |
def cost_part1(crabs: list[int], target: int) -> int:
"""
Calculates the total fuel that would be required for all crabs to move to
the given position if the assumption from part 1 was true
"""
return sum(abs(target - crab) for crab in crabs) | 4df995bdd0dfe90a120186b91eae4a4ff94765ec | 689,403 |
def parse_n_features(n_features, total):
"""Parse either the `n_features` for forward
and backward selection. Namely
(a) if `param` is an int, ensure it lies on (0, `total`),
(a) if `param` is a float, ensure it lies on (0, 1).
Args:
n_features : int
An `n_features` parameter pa... | e4c3f27600b088e77543fbd5bad73832a6e1d4b1 | 689,404 |
def where(self, test):
"""
Create a new :class:`.Table` with only those rows that pass a test.
:param test:
A function that takes a :class:`.Row` and returns :code:`True` if
it should be included in the new :class:`.Table`.
:type test:
:class:`function`
:returns:
A n... | ef7a8761285b5679a69e9ca87ec6bc23e98c3f60 | 689,405 |
def fields_to_batches(d, keys_to_ignore=[]):
"""
The input is a dict whose items are batched tensors. The output is a list of dictionaries - one
per entry in the batch - with the slices of the tensors for that entry. Here's an example.
Input:
d = {"a": [[1, 2], [3,4]], "b": [1, 2]}
Output:
r... | 6896adacfd34754bd49d8b53aff5bc9b1222677c | 689,406 |
def my_import(name):
"""Function converts a string based import into a module object, used for
dynamically importing modules from config.
Parameters
----------
:str: `str`
A string name of the module to import
Returns
-------
:obj: `module`
A module object converted fro... | 689a38f20aa402db0625c5f5384cb0b88dfe98a2 | 689,407 |
def sec2time(secs):
#return strftime("%H:%M:%S",time.gmtime(secs)) # doesnt support millisecs
"""
>>> strftime("%H:%M:%S",time.gmtime(24232.4242))
'06:43:52'
>>> sec2time(24232.4242)
'06:43:52.424200'
>>>
"""
m,s = divmod(secs,60)
#print m,s
h,m = divmod(m,60)
if(s >= 10.0):
return "%02d:%02d:%.3f"%(h,m,... | 9c479cfc1beb1e018ad96a2d936313daea1290af | 689,408 |
import re
def is_one_line_method(line, keywords):
"""
Gets True if the line holds a complete method declaration (from 'def to :),
otherwise it gets False
----------
str line: Text line
list keywords: list of keywords like def for python, func for go etc.
"""
found = [word.lstrip() for... | 7c68fa7dc0c5daef17834ba63771a28543108fb9 | 689,409 |
def swap1(num1, num2):
"""Works for integers"""
num1 += num2
num2 = num1 - num2
num1 = num1 - num2
return num1, num2 | cfe8d4c9f54687c9e7cfe418ec4f23f1bcf4ea55 | 689,410 |
import sqlite3
def execute_command_with_params(db, query, params):
"""Execute a simple query which requires additional parameter"""
with sqlite3.connect(db) as conn:
cursor = conn.cursor()
res = cursor.execute(query, params)
return res | a99565ee9f3663f894572f71e102b258b4a00222 | 689,411 |
def gen_Message(message):
"""Create a new Message."""
message = {
"@type": "Message",
"MessageString": message,
}
return message | 13ed53733d3910df7e0bdc3eb5fc3d40a1275390 | 689,412 |
def seconds_to_datetime(second: int) -> str:
"""Convert seconds to datetime string."""
mins, secs = divmod(int(second), 60)
hours, mins = divmod(mins, 60)
return f'{hours:02d}:{mins:02d}:{secs:02d}' | 2d300a71bdbfecb3b3620c8a7b77e778957f89e3 | 689,413 |
import re
def jsonify(s: str) -> str:
"""
javascript var -> json, i.e. add quotation to dict keys
:param s:
:return:
"""
# do some small cleanings
s = s.replace('\t', ' ').replace('\'', '"')
# regexps to match for variable names and null values
patt = re.compile(r'(\w+)(:)')
... | ab7b1be4f7ae9b72bc68b3f8d1bb8fd8711b94c5 | 689,414 |
def safe_int_cast(val, default=0):
"""Safely casts a value to an int"""
try:
return int(val)
except (ValueError, TypeError):
return default | 0282539ec33efd8264d7fe2fb09dfb4668f0c942 | 689,415 |
def _get_regular_HD_name(name):
"""Convert an HD name in *Henry Draper Catalogue* to its regular form
`"HD NNNN"` or `"HD NNNN C"`.
Args:
name (str or int): Name or HD number of a star (e.g. `"HD8276"`,
`"HD 8276A"`, `8443`).
Returns:
str: Regular HD name `"HD NNNN"` or ... | f69f14d1d0e3d1632adb7dc059ac67e5c6e9a1a4 | 689,416 |
def or_of_bits(*bits):
"""OR the given bits.
Args:
*bits (int): Bits for OR. More than one argument required.
Return:
or_bit (int): OR of the given bits.
Example:
>>> or_of_bits(1, 4, 16)
21 # 0b10101, 0x15
>>> or_of_bits(0b00010, 0b10000)
18 # 0b10010,... | 621b71ee4828912da027c63d61b7de669f7029e4 | 689,417 |
import yaml
def parse_yaml(config):
"""Safely loads yaml data
Args:
config: YAML configuration file
Returns:
Dictionary representation of given YAML
"""
return yaml.safe_load(config) | 17c719e994df6208e6b53913bb8fe19767b3663e | 689,418 |
import torch
def apply_distance_bound(data_region_i, data_region_i_orig, args):
"""
Input:
data_region_i: (S,3) tensor, current region i points
data_region_i_orig: (S,3) tensor, original region i points
Return:
data_region_i: modified data_region_i
count: number of points t... | 0cf40bfbc83ad3c2104c969bb5faaace6b88d5db | 689,419 |
def attach_disk(fco_api, server_uuid, disk_uuid, index):
"""
Attach disk to server.
:param fco_api: FCO API object
:param server_uuid: Server UUID
:param disk_uuid: Disk UUID
:param index: Disk index on the server
:return: Job-compatible object
"""
return fco_api.attachDisk(serverUU... | ab32f750effef35cae5d5932e941d99f4ce5888e | 689,420 |
import os
def dir_size(path):
"""Returns the total size of all files under the
given path, recursively
"""
total_size = 0
for pathname, dirnames, filenames in os.walk(path):
for file in filenames:
total_size += os.path.getsize(os.path.join(pathname, file))
return total_size | fabcf23ee689022afecba5825ce085961643209d | 689,421 |
import re
def remove_emoji_ucs4(text):
"""
Wide UCS-4 build. It is useful before adding utf8mb4 support for mysql
:param text:
:return:
"""
myre = re.compile(u'['
u'\U0001F300-\U0001F64F'
u'\U0001F680-\U0001F6FF'
u'\u2600-\u26FF... | 4e9150df21caaa7105525c2cf52dc7692550ea29 | 689,422 |
def median_zero_normalization(data, normalize='samples'):
"""
This function normalizes each sample by using its median.
:param data:
:param str normalize: whether the normalization should be done by 'features' (columns) or 'samples' (rows)
:return: Pandas dataframe.
Example::
data = pd... | 098ed48e1f4337353a662a53a93fd08169982be9 | 689,423 |
def fofx (x):
"""
fofx ():
return value of a piecewise discontinuous function
"""
x0=953.155e3
x1=956.0e3
x2=957.0e3
x3=957.2e3
(x3cad,y3cad) = (957738.41,1844520.82)
(x4cad,y4cad)= (957987.1, 1844566.5)
x4=958.15e3
x5=959.640e3
y1=1844.5e3
y2=1843.6e3
y3... | 793de69e70b317bde3247abf3fd156f6c8358a57 | 689,424 |
import torch
def masked_revert(tensor, mask, dim):
"""
suppose you have mask that starts with 1s and has trailing 0s, e.g.:
data = [3, 9, 4, 0, 5, 2, 7, 7, 7]
mask = [1, 1, 1, 1, 1, 1, 0, 0, 0]
With 7 being the index for "<pad>" token. If you want to revert the data, most likely you want to revert the da... | 83248db7a4e6df9de2451720e3d9f3d631d378e5 | 689,425 |
def check_S3_bucket(ggd_recipe, ggd_jdict):
"""Method to check if the recipe is stored on the ggd S3 bucket. If so it installs from S3
check_S3_bucket
==============
This method is used to check if the recipe has been cached on aws S3 bucket. It returns true if the
the recipe is cached, and false... | 88385ea0f52637d174536a22f16f156cbc3adfa6 | 689,426 |
def sse_pack(event_id: int, event: str, data: int, retry: str = "2000") -> str:
"""Pack data in Server-Sent Events (SSE) format."""
return f"retry: {retry}\nid: {event_id}\nevent: {event}\ndata: {data}\n\n" | 075d7f58248b72a5835c6b9b65332fbcb799f2a8 | 689,427 |
def _lyn(w):
"""
Returns the length of the longest prefix of ``w`` that is a Lyndon word.
EXAMPLES::
sage: import sage.combinat.necklace as necklace
sage: necklace._lyn([0,1,1,0,0,1,2])
3
sage: necklace._lyn([0,0,0,1])
4
sage: necklace._lyn([2,1,0,0,2,2,1])
... | eaec9d87f91b7d87282f7909d5e4dcb1b4ad1daa | 689,429 |
def no_ones(number: int) -> int:
"""
nr: 101010
nr - 1: 101001
nr & (nr - 1) == 101000
"""
ones = 0
while number:
ones += 1
number = number & (number - 1)
return ones | 9c6be63f548aeeca1f7c7ec0e22ca62976ef8baf | 689,430 |
import os
def get_folder_size(folder: str):
"""
Get the folder size (MB)
Args:
folder (str): Input folder
Returns:
float: Folder size, MB
"""
size = 0
for root, _, files in os.walk(folder):
for f in files:
size += os.path.getsize(os.path.join(root, f))... | 1e39816b742b29bea4790c996d614c2033d8448f | 689,431 |
def return_payload(stmts):
# pylint: disable=too-many-branches,too-many-return-statements
"""Compute payload returned by stmts."""
for stmt in stmts:
if stmt.HasField('call'):
pass
elif stmt.HasField('action'):
pass
elif stmt.HasField('cond'):
payl... | 2c200030f7aadc6fe0f22abc6957944357a766ab | 689,432 |
def split_kwargs(relaxation_kwds):
"""Split relaxation keywords to keywords for optimizer and others"""
optimizer_keys_list = [
'step_method',
'linesearch',
'eta_max',
'eta',
'm',
'linesearch_first'
]
optimizer_kwargs = { k:relaxation_kwds.pop(k) for k in ... | 8c3daa004388b33e3eecd735ed5273061ffc78bc | 689,433 |
def valid_int_id(int_id: int) -> bool:
"""Validates an ID value as a signed 32-bit integer used
in ID fields in MySQL tables.
:param int_id: ID number to validate
:return: True or False, based on if the integer falls inclusively
between 0 and 2147483647
"""
try:
if not int_id:
... | 1805073a675f12b846b8ca5544d602aaba57e232 | 689,434 |
import zipfile
def _read_zipfile_metadata(stream):
"""Read zipfile metadata from the given stream.
The result is a zipfile.ZipFile object where all members are zero length.
"""
return zipfile.ZipFile(stream,"r") | c8659eda918a2c14a606c783b423175f52a13b21 | 689,435 |
def parse_option_settings(option_settings):
"""
Parses option_settings as they are defined in the configuration file
"""
ret = []
for namespace, params in option_settings.items():
for key, value in params.items():
ret.append((namespace, key, value))
return ret | f6c92eb1fc3943747c7e65af21502ec2490961cb | 689,436 |
from typing import Any
def configure_v1(config: dict[str, Any]) -> dict[str, Any]:
"""Tries to read version 1 configuration files
This function may fail for valid configuration files for LADiM version 1.
Ordinary use cases at IMR should work.
"""
conf2: dict[str, Any] = dict() # output version... | 67ab549b4a864e9089489bbd1914dab8286cd5e0 | 689,438 |
def _build_localename(localetuple):
""" Builds a locale code from the given tuple (language code,
encoding).
No aliasing or normalizing takes place.
"""
try:
language, encoding = localetuple
if language is None:
language = 'C'
if encoding is None:
... | ed267f2e2ef81a7eeddea5a2363cd72c726ddecb | 689,439 |
def home():
"""
.. :quickref: Home; The Home page
Home page.
"""
return 'home' | 290a60c32b5cf23e0cac3e09c051530a6f9e74f9 | 689,440 |
import os
def get_tests_directory():
"""discover and return the absolute path of the root directory"""
testdir = os.getcwd()
if not testdir.endswith("tests"):
testdir = os.path.join(testdir, "tests")
if not os.path.exists(testdir):
raise ValueError("can not find test directory"... | fcc49183bc1f186a6350a5fcc3062c3af73fdb9f | 689,441 |
from typing import Counter
import string
def is_isogram(word):
"""Check word to see if it is an Isogram."""
char_counts = Counter(word.lower())
return all(count == 1 for char, count in char_counts.items()
if char in string.ascii_lowercase) | 54f7a6abc9ecb9b9c4db973d66fd0ced17d0f78e | 689,442 |
import torch
def train_model(model, optimizer, criterion, epochs, trainloaders, validloaders, device):
"""
Trains a network with an optimizer according to a criterion over a number of epochs
on data provided by trainloaders and validloaders using device.
Returns
None
"""
# Push model to cp... | af2e68b5694c7c49f936e79e53f50478ca9e3b9e | 689,444 |
import math
def lcm(a: int, b: int) -> int:
"""Return lowest common multiple."""
return a * b // math.gcd(a, b) | e40e99b167bf8aa3cfeedf56c5c2082da5ce1498 | 689,445 |
def get_intro(title, article):
"""
Function to extract the first paragraph from a news article
:param title: Title of the news article
:param article: Full text of the article
:return: the extracted first paragraph
"""
# Split the article in paragraphs and remove empty paragraphs
parap... | 9cdbcc64f5ff85b7425b1c47e23b484f5fdb9b2a | 689,446 |
def merge_dict_of_dicts(list_of_dicts):
"""
merges list of dicts
arg: list of dicts (to be merged)
returns: merged dict
"""
final_dict = {}
for d in list_of_dicts:
for k, v in d.items():
final_dict.setdefault(k, []).append(v)
final_dict.update((k, [item for sublist i... | 47f6c59837379308291d8075c492422e6809280b | 689,447 |
import numpy
def calc_shift_p_by_constraints_hamilton(delta_p, dder_chi_sq, matrix_q):
"""Linear type Hamilton constraints.
"""
q_t = matrix_q.transpose()
q_dder_chi_sq = matrix_q.dot(dder_chi_sq)
q_dder_chi_sq_qt = q_dder_chi_sq.dot(q_t)
inv_q_dder_qt = numpy.linalg.inv(q_dder_chi_sq_qt)
... | c4ebda082f54a2070386095dfdb8cc21885f124f | 689,448 |
import re
def validate_url(url, playlist=False):
"""
Confirms the validity of the provided YouTube video/playlist URL
Args:
url: A YouTube video/playlist URL
playlist: A boolean flag to determine playlist URL
Returns:
A bool indicating the validity of the provided URL
"""
pattern = r'^(https?\... | 3d4242c45ba82a772231b5376149d4cf3211e17b | 689,450 |
import math
def split_array(totnum,nprocs,lpp,myrank):
""" Returns the indices of the chunk(of the input file) to be split based on the
rank of the processor."""
totnum = totnum/lpp
n2=int(math.floor(totnum/nprocs))
remain=int(math.fmod(totnum,nprocs))
if (myrank < remain) :
n1=n2... | 634352e3f083a4f8fc1325cc3268d384111d4191 | 689,452 |
def tile(x, count, dim=0):
"""
Tiles x on dimension dim count times.
E.g. [1, 2, 3], count=2 ==> [1, 1, 2, 2, 3, 3]
[[1, 2], [3, 4]], count=3, dim=1 ==> [[1, 1, 1, 2, 2, 2], [3, 3, 3, 4, 4, 4]]
Different from torch.repeat
"""
if x is None:
return x
elif type(x... | c8bcbf94fa0e1cdf0f4922620ffea151cb5b8563 | 689,453 |
def _multiple_of_n(a, n_boundary):
"""Calculates ceil like operation to make 'a' to be multiple of n boundary."""
ceil_like = (a + n_boundary - 1) // n_boundary
return ceil_like * n_boundary | 5d61b57d9813703e3ece9e0a60109e5afc03b03e | 689,454 |
def find(pred, iterable):
"""
Find the first occurrence of the predicate function returning true
over the iterable; otherwise None.
>>> find(lambda e: e.startswith('g'), ['alpha', 'beta', 'gamma', 'delta'])
'gamma'
>>> find(lambda e: e.startswith('p'), ['alpha', 'beta', 'gamma', 'delta'])
No... | f0a491e4c8dfce292b604193fde25f317b0978b8 | 689,455 |
def robots():
"""
"""
return """
User-agent: *\n
Disallow: /\n
""" | b6969c79b4b0eb51645bc412d011a69c017f6265 | 689,456 |
def label_other(df, label_id, cat, label, start_time, end_time, session=-1):
""" Add label to single ``Object'', ``none'', and ``control'' sequence
"""
# Index
idx_start = df[df["start_time"] == start_time].index
idx_end = df[df["start_time"] == end_time].index
if (len(idx_start) != 1) or ... | eacad7671fd21755a859525b14cbbce59b399c15 | 689,457 |
import json
def sample_json_from_status(status):
"""Converts a sample list to json."""
if not(status is None) and 'players' in status.raw.keys() and \
'sample' in status.raw['players'].keys():
return json.dumps(status.raw['players']['sample'])
else:
return '[]' | 4c46b1bf750f7f3a40875cb07bfc6dffbf7db1b0 | 689,458 |
import re
def _parse_annotations_ica(ica_strings):
"""Read bad channel definitions from text file"""
# prepare splitting
for char in '}]': # multi line array definitions
ica_strings = ica_strings.replace(
char + ';', 'splitme'
)
# scalar variables
match_inds = list()
... | 69167648d8fe619d36075c852ba6d3478fd6a9b8 | 689,459 |
def _softUpdateWrapper(wrapper, wrapped):
"""
Update a wrapper function to look like the wrapped function.
Like functools.update_wrapper, but doesn't fail when attributes
are not found.
"""
attrs = ['__name__', '__doc__']
for attr in attrs:
if hasattr(wrapped, attr):
seta... | 4042f7a5db73cab83a741dadbc2f475c56a05d50 | 689,460 |
def topological_sort(graph):
"""
Preforms a topological sort on the given graph. Code by Paul Harrison in
the public domain.
graph should be a dictionary mapping node names to lists of
successor nodes.
"""
# Count the occurrences of each node as a successor
count = { }
for node in ... | 18d8247287e4c0bfb74eb597ff2d4cc6938e287c | 689,462 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.