content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import math
def factors(n):
""" Returns the list of n's factors
--param
n : int
--return
list
"""
if n < 1:
return []
elif n in {1,2,3}:
temp = set()
temp.add(1)
temp.add(n)
return list(temp)
else:
temp = set()
temp.add(1)
... | 47d8fce4c7d736badb769c94455fe5df8e021bf3 | 665,999 |
def f6a_target_resource(plate, params_simulation):
"""
Function as maximized non-supplied resource production
The target resource by default is the resouce in the last index
If rich medium is provided, the target resource amount in the initial plate is set to 0
"""
target_resource_index = plate.... | c68fb88fad3332192c6db91f72893b9593407ae2 | 666,000 |
import json
def _schema(**vals):
"""Default schema."""
data = dict(
id='a-b-c-d-e',
date="2016-08-23 15:03:49.178000",
layout="grid",
name="testlayout",
modules=[],
)
data.update(**vals)
return json.dumps(data) | 7f3c768f95a3a32cf803d2621f112951eebc98b2 | 666,001 |
import socket
def get_hostname():
"""Get hostname for this machine."""
# pylint:disable=no-member
return socket.gethostname() | 843c3caf9c5e23899d49b26af3acf0377f00bc18 | 666,002 |
def temp_cache_pos_file(temp_folder, temp_cache_pos_filename):
"""Create a file path to for the cached part-of-speech (POS) file."""
return temp_folder.join(temp_cache_pos_filename) | 29672c9d7bf84cfcf76f15ff719ae197ee9d9d71 | 666,003 |
import sqlite3
def construct_db(db: str):
"""Build empty database."""
con = sqlite3.connect(db)
c = con.cursor()
c.executescript('''
CREATE TABLE blob (
Offset INTEGER PRIMARY KEY,
InternalPath TEXT,
Unk INTEGER,
OriginalFilePath TEXT,
TimeStamp INTEGER,
... | 605bf6f3d34a59e3f95ffef46c3c253492460396 | 666,004 |
from random import random
def game():
"""
Create a bet with random probability of winning, p and price of b when won
"""
p, b = random(), random() * 10
return p, b | 6f86cc955d5d180063ed09367e09f14eae24c3bc | 666,005 |
import requests
def get_interlanguage_links(page_title, endpoint='en.wikipedia.org/w/api.php', redirects=1):
"""The function accepts a page_title and returns a dictionary containing
the title of the page in its other languages
page_title - a string with the title of the page on Wikipedia
endp... | cd96b0a0962a8edf4f28958a4f7b850bbb2e0f74 | 666,006 |
import json
def check_keys_with_wsid(errored, errlog_dictionary):
"""check_keys_with_wsid is a function that diligently checks the structure and key present in the errorlog coming from EE2.
This function is made to accommodate many different structures of errored app logs coming from EE2 with many different k... | 70ae08c8ab946aef5a1e89e264c12e1f18e8fb9e | 666,007 |
def in_seconds(days=0, hours=0, minutes=0, seconds=0):
"""
Tiny helper that is similar to the timedelta API that turns the keyword arguments into
seconds. Most useful for calculating the number of seconds relative to an epoch.
>>> in_seconds()
0
>>> in_seconds(hours=1.5)
5400
>>> in_sec... | cdd9878ff99448717ea8eb36452ed1536d64fe44 | 666,008 |
import argparse
def parse_CLI_arguments():
"""
Parses any command-line arguments passed to this script and returns an
ArgParse object.
"""
parser = argparse.ArgumentParser('Creates a workflow iterator for the '
'get_bam_coverage_dx component')
parser.add_ar... | 69efb1314d033c673f49f36db5d317e41e12e221 | 666,009 |
import random
def findAndReplaceSimilarChar(word, optionsList, similarCharsList):
"""This method takes a word and replace a character with similar character if it is possible.
The method also checks, if new created word is not already in optionsList argument to prevent duplicates.
Args:
word (str... | 0bf3b280786d3ab32f61ae93e5943686ea6df001 | 666,010 |
import six
def as_identifier(s):
"""
Take a bytes string and make sure that it can be used as an identifier.
Return bytes on Py2 and unicode on Py3.
This is needed for Python2/3 compatibility: in the capnproto schema,
things like field and struct names are of type Text, and they are
represent... | 2b6a58bb37c52aba5e23f06c4e1009771981cc58 | 666,011 |
def ote_test_scenario_fx():
"""
The fixture returns a string that will be used as the 'scenario' field in the
e2e test system dashboard.
At the moment it is supposed that the fixture should return something like
'api' or 'integration' or 'reallife'.
The fixture may be overriden in algo backend'... | ff6bed84f130d7c8851da11fac172425dc6c010d | 666,012 |
def _submatrix(A, row_idx, col_idx):
"""Sub-matrix by index calculation."""
return [[A[i][j] for j in col_idx] for i in row_idx] | 65d8305f639ee15d825e658175731d028669c3a5 | 666,013 |
def reference_cluster(envs, name):
"""
Return set of all env names referencing or
referenced by given name.
>>> cluster = sorted(reference_cluster([
... {'name': 'base', 'refs': []},
... {'name': 'test', 'refs': ['base']},
... {'name': 'local', 'refs': ['test']},
... ], 'tes... | 8c8c6530548a5a783f6752a185a29206963580a2 | 666,014 |
from typing import List
from typing import Optional
def response_detect_blocking_messages(
text: str, blocking_messages: List[str]
) -> Optional[str]:
"""Method to check whether any of blocking messages appears in the response text.
:param text: response text
:param blocking_messages: list of pot... | dd8c1b5fc7761fcfee066671da1415d7bb4aeab0 | 666,016 |
def get_short_imagename(imagename):
"""Return image-specific suffix of imagename.
This excludes a possible experiment-specific prefix,
such as 0001_... for trial #1.
"""
splits = imagename.split("_")
if len(splits) > 1:
name = splits[-2:]
if name[0].startswith("n0"):
... | cf178854ed83143883f6c091807eb81ece44e8e7 | 666,017 |
def is_sqlite_available():
"""
Checks if the sqlite3 module is available. Usually this is built in, but some
platforms such as FreeBSD and Gentoo exclude it by default.
.. versionadded:: 1.6.0
:returns: **True** if we can use the sqlite3 module and **False** otherwise
"""
try:
return True
except ... | 08d941603811b9358510531f3b128d63f8c45589 | 666,018 |
import time
def TimeoutExpired(epoch, timeout, _time_fn=time.time):
"""Checks whether a timeout has expired.
"""
return _time_fn() > (epoch + timeout) | 8d667b9cbf31adefba826d0a59359bdb17211eb9 | 666,019 |
def get_bool(value: str) -> bool:
"""Get boolean from string."""
if value.upper() in ["1", "T", "TRUE"]:
return True
if value.upper() in ["0", "F", "FALSE"]:
return False
raise ValueError(f"Unable to convert {value} to boolean.") | 35d6cbe90f04a5fd9942a51c8ea3c412b38250eb | 666,020 |
def preprocess(dataset):
"""
Given train dataset from Forest Cover Type dataset, it returns
two dataframes, one with just labels and one with train dataset with all
atritubes except CoverType atribute
"""
labels = dataset.Cover_Type.values
dataset= dataset.drop(['Cover_Type'], axis=1)
... | a73fd7f24fb75ba3a07e80497bbc8b958e5d5636 | 666,022 |
def reorder_cards_table(request):
"""Reorder carousel items table"""
order = request.params.get('order').split(';')
request.context.updateOrder(order)
return {
'status': 'success',
'closeForm': False
} | 88e82fadf34fb036f581cbe39a4384ac4053076c | 666,023 |
import argparse
def get_parser():
""" Return argument parser. """
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
'filename', default='model.sqlite',
help='filename (including path) o... | 8fcc1de3c4df513e3aa2c724c8245f9048b91bc6 | 666,024 |
def incsum(prevsum, prevmean, mean, x):
"""Caclulate incremental sum of square deviations"""
newsum = prevsum + (x - prevmean) * (x - mean)
return newsum | 20df738f798081727d8ea0a8790c4b341601f2ac | 666,025 |
def linne() -> list:
"""
Returns the linnean Taxonomy:
species,
genus,
family,
order,
class,
phylum,
kingdom
"""
return ['species',
'genus',
'family',
'order',
'class',
'phylum',
'kingdom'] | def4cf538af94a73cd6e369eb7921988e7a91ff6 | 666,026 |
import torch
def pool_max(mask,embed_matrix,use_cuda):
"""
max pool
mask shape is B_S
embed_matrix shape S_F
"""
assert mask.shape[1]==embed_matrix.shape[0], 'mask shape 1 must match embed_matrix shape 0'
b,s=mask.shape
mask=mask.t()
s,f=embed_matrix.shape
feats=[]
for i in... | c30dfd5105708bab98d4c465b1b13adedb9d2661 | 666,027 |
import argparse
def parse_args():
"""
Parses the command line arguments.
Returns:
"""
parser = argparse.ArgumentParser(
description="Run link prediction on homogeneous and heterogeneous graphs."
)
parser.add_argument(
"--dataset_name",
nargs="?",
default="... | d263d3649a61fd3b415dbab14ab369c9e7852d83 | 666,028 |
def convert_pc_to_ly(pc):
"""Converts distance in parsecs into lightyears and returns integer."""
return pc * 3.2615638 | ea97aa26f4ce1c6d87146c1b1875a9512ecec4ee | 666,030 |
def iqr(x):
"""
Function for getting IQR value
"""
return x.quantile(0.75) - x.quantile(0.25) | 17113d7d0216ce0ca351034edb3233c5ccecf2f4 | 666,031 |
import os
def _fileExists(filepath: str) -> bool:
"""Tests for existence of a file."""
return bool(os.path.exists(filepath) and os.path.isfile(filepath)) | e45ffa4c2ebf165baa397db1185e78e14f4092d5 | 666,032 |
def get_year():
"""
Returns user input after checking it.
:return year: integer, given year
"""
try:
year = int(input("Enter a year: "))
assert 1889 < year <= 2024 or year in [1251, 1478, 1874, 1888, 2315,
2551, 4906, 5514, 7921, 8341], ... | 08dd53a8e14fd2b9711ef9a0d3b5850679bd5e85 | 666,033 |
def initialize_hyper_parameters(layer_acts, learning_rate):
"""
Initialize parameters for different levels of the network
Arguments:
layer_acts -- python array (list) containing the activation functions of each layer in the network
learning_rate -- float value used as constant for gradient descent
... | 110e6cf603e241028e291fa8cb4552e124f4a1e5 | 666,034 |
def count_sequential_elem_increases(arr: list) -> int:
"""
Args:
arr (list): list of numeric values
Returns:
count of the number of times that a value increases from the previous array entry
"""
return sum(arr[i-1] < arr[i] for i in range(1, len(arr))) | 7fc2f07da325ea66684a1fff320b6c47db1cbc5c | 666,035 |
import requests
def get_token(username: str,
pw: str,
filehost: str = "securefileshare.wales.nhs.uk") -> dict:
"""
Fetch Bearer token for securefileshare
Parameters
----------
username: str
pw: str
filehost: str
Returns
-------
dict
Diction... | 98593425daaa606c938e63d488ebcd72a314d57d | 666,036 |
import click
def validate_timeout_option(ctx, param, value):
"""Callback for monitor-timeout parameter validation"""
try:
value = int(value)
if value <= 0:
raise ValueError()
except ValueError:
raise click.BadParameter(f"'{value}' is not a positive integer.")
else:
... | 6078d897636402c9476e8489d74ee6ed0a11ac8e | 666,037 |
import os
def load_properties(filename):
"""
Load properties from file
"""
props = {}
if not filename or not os.path.isfile(filename):
return props
# print('Loading properties: ' + properties_file)
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
... | c14e1a2ea7550ac0fb3d04e2d66ecea3ff051585 | 666,039 |
def is_bucket_needed(dpath, cmd):
"""
judge buckets are needed.
"""
ofp = dpath.ofproto
return cmd != ofp.OFPGC_DELETE | b7b8d618aea9c17b0eb98268abd585315113799d | 666,040 |
def resolve_locations(ctx, strategy, d):
"""Resolve $(location) references in the values of a dictionary.
Args:
ctx: the 'ctx' argument of the rule implementation function
strategy: a struct with an 'as_path(string) -> string' function
d: {string: string} dictionary; values may contain $(loca... | ff0f4c83b44e0a6b7430b6bea39ee60e959e1fe8 | 666,041 |
def avg(lst: list) -> float:
"""return the average of a list.
Preconditions:
- all items in lst are ins or floats.
"""
return sum(lst) / len(lst) | a413a71e47301095615f05d629f273e00e1fbc1b | 666,042 |
def interactions_to_edges(interactions, interaction_symbol='<->'):
"""Split interaction df into tuples of edges."""
return {
tuple(interaction.split(interaction_symbol))
for interaction in interactions.index
} | 3c1cc627af961f74308cb51721b21e160a0ad4bb | 666,043 |
def _Boolean(value):
"""Returns a string indication whether a value is true ("truthy").
Args:
value: Any value.
Returns:
String indicating whether the value is true.
"""
return '*' if value else '-' | 32fc213e9ecb13f55576522037ea85c65e863a5d | 666,044 |
def _intsqrt(v):
"""Compute int squareroot floor"""
c = 0
while c**2 <= v:
c += 1
return c - 1 | 5368eac7afe25fa6743fd78b999d9dcfe4b63432 | 666,045 |
def speaker_id_dic(files_np):
"""
Generates speaker dictionary to be used for speaker embedding
"""
Y_np_list = []
for file in files_np:
trial_y = file.split('trim_spec_p')[1][:3]
Y_np_list.append(trial_y)
Y_np_list = list(set(Y_np_list))
speaker_dic = {Y_np_list[i]: i for i... | 18d5186ead3b1ead0a82d8caeef5b02f5e4f1da5 | 666,046 |
import argparse
def set_parser():
""" set custom parser """
parser = argparse.ArgumentParser(description="")
parser.add_argument("-df", "--date_from", type=str, required=True,
help="Sensing date from YYYYMMDD ")
parser.add_argument("-dt", "--date_t... | fcb5326237486fd5f79b812ea3c58facb40eea90 | 666,047 |
def exists(env):
""" NOOP method required by SCons """
return 1 | c60be843097ef6c8830b73d29f5dacac95d4a98f | 666,048 |
import re
def add_list_border(nested_list):
"""Returns: a ragged list with ASCII borders. The nested lists will have borders.
Precondition: list is a nested list and all items in the nested list are strings"""
for index in range(len(nested_list)):
list_item = nested_list[index]
border_widt... | d9ba70ea5cc35efa585f1df8cc050186d52a6472 | 666,049 |
def PalindromePermutation(s: str) -> bool:
"""Determines if s is a permutation of a palindrome.
>>> PalindromePermutation("")
True
>>> PalindromePermutation("a")
True
>>> PalindromePermutation("Tact Coa")
True
>>> PalindromePermutation("ace CarR")
True
>>> PalindromePermutat... | fd8f58fb9bc3b0886f46413e2122e4508ffe8946 | 666,050 |
import multiprocessing
def setup_multiprocessing_queue():
"""Wrapper around multiprocessing so that only this script
needs to import multiprocessing
"""
mp_queue = multiprocessing.Queue()
return mp_queue | f67aea9f943e909dcbf9cdd5e528e4d11da3ea8e | 666,051 |
def and_join(strings):
"""Join the given ``strings`` by commas with last `' and '` conjuction.
>>> and_join(['Korea', 'Japan', 'China', 'Taiwan'])
'Korea, Japan, China, and Taiwan'
:param strings: a list of words to join
:type string: :class:`collections.abc.Sequence`
:returns: a joined string... | 4b9a411738a662897095a055cd9037ca1a3a0c98 | 666,052 |
import os
def get_data_dir():
"""returs the {REPO_PATH}/data"""
_dir = os.path.dirname(os.path.abspath(__file__))
return os.path.join(_dir[:_dir.rfind('src')], 'data') | 17d2b5c72fcb0ec3f6363dfa531b2ddd4eb908c6 | 666,053 |
def none(owner, currentTime):
"""Возвращает None"""
return None | f9cdb0fe18b53acfad81bb73ebb36afab74107e5 | 666,056 |
def get_file_name(file_name: str, at: int = -1, split: str = '/') -> str:
"""
Extracts fileName from a file.
Example:
get_file_name('/a/b/file_dir/my_file.csv') -> 'my_file'
get_file_name('/a/b/file_dir/my_file.csv',at=-2) -> 'file_dir'
:param file_name:
:param at: fetch name after... | cfca089f4a652fa922c85e662bbde2238a995f32 | 666,057 |
def limit_issues(issues, limit_len=100000):
"""Limit the number of issues saved in our DB."""
sorted_issues = sorted(issues, key=lambda x: x['updated_at'], reverse=True)
return sorted_issues[:limit_len] | 1dcd4461e9ca78605bf03e7a0fd1635a49bdd69a | 666,058 |
import glob
def expand_file_pattern(pattern):
"""
use glob to find all files matching the pattern
Parameters
----------
pattern : str
unix bash shell like search pattern
Returns
-------
list
list of file names matching the pattern
"""
assert pattern is... | c4e70527163f2167265693b9497deb238a39ea85 | 666,059 |
def calc_avg(varlist):
"""
Collecting the statistics for descriptives, including number of elements, number of functions,
number of variables, number of constants
:param varlist: list of dict of the variables
:return: total variables, average elements per equation, number of functions and average, ... | 59fc8048881a7a092a4ee8ccaec5543a4f82649a | 666,060 |
import itertools
def all_neighbors(graph, node):
""" Returns all of the neighbors of a node in the graph.
If the graph is directed returns predecessors as well as successors.
Parameters
----------
graph : NetworkX graph
Graph to find neighbors.
node : node
The node whose nei... | fed95fed1771194df42bae7387dcb318ba7aea31 | 666,061 |
def dashes(i=1, max_n=12, width=1):
"""
Dashes for matplotlib.
Parameters
----------
i : int, optional
Number of dots. The default is 1.
max_n : int, optional
Maximal Number of dots. The default is 12.
width : float, optional
Linewidth. The default is 1.
Returns... | 2cffaa4448d7d3d4765dfb83f644fcf2ed6344e5 | 666,062 |
def timeseries_train_test_split(X, y, test_size):
"""
Perform train-test split with respect to time series structure
"""
# get the index after which test set starts
test_index = int(len(X)*(1-test_size))
X_train = X.iloc[:test_index]
y_train = y.iloc[:test_index]
X_test = X... | f066cde3fc58de00b6d592d406b94e98beb0cbeb | 666,063 |
def concat_all_gather(tensor):
"""
Performs all_gather operation on the provided tensors.
*** Warning ***: torch.distributed.all_gather has no gradient.
"""
# tensors_gather = [torch.ones_like(tensor) for _ in range(torch.distributed.get_world_size())]
# torch.distributed.all_gather(tensors_gath... | 48165e6dfb80ea3ef5654c235a97be67c37de2bb | 666,064 |
def fontawesome(icon_name, size=""):
"""
Generate fontawesome syntax for HTML.
Usage:
{% fontawesome "iconname" %}
{% fontawesome "iconname" "size" %}
Size values are: lg, 2x, 3x, 4x, 5x
"""
if len(size) > 0:
size = "fa-%s" % size
return '<i class="fa fa-%s %s"></i... | af0ab4c5264a2e6117ca3b94d096862f5e401876 | 666,065 |
def ask_confirmation(message, yes = 'y', no = 'n', default = False):
"""
Ask user to confirm something. Ask again if answer other than expected.
Arguments:
- message (string): message to print (e.g. "Are you sure?")
- yes (string): expected value if user confirms
- no (s... | bd66b526f1efe8f648b3d204e7c791a74b4324b7 | 666,066 |
def valider_reponse(reponses):
""" Demande à l'utilisateur d'entrer une réponse.
1 : La réponse est correcte
0 : La réponse n'est pas correcte
-1 : Fin du programme
"""
while True:
choix = input("Quel est votre choix? (N° de la réponse) ")
if choix == 'stop':
... | 952559d38a80f6ab911421212697898eecd925bb | 666,067 |
def match_substructures(mol, substructures):
"""
This function checks if a molecule contains any of the provided substructures.
Parameters
----------
mol : Chem.rdchem.Mol
An RDKit molecule.
substructures: list
List of substructures as RDKit molecules.
Returns
-------
... | 070a3d1dfdce75f910329ecfde1bedc898c1be65 | 666,068 |
def mongo_map(name):
"""
mongo db的映射
:param name: 创建的mongo集合名称
:return: mongo集合,类似于表格
"""
return eval('mdb.{0}'.format(name)) | 1d680987706d057018862038ad9861557e3630c1 | 666,069 |
def temp_ampersand_fixer(s):
"""As a workaround for ampersands stored as escape sequences in database, unescape text before use on a safe page
Explicitly differentiate from safe_unescape_html in case use cases/behaviors diverge
"""
return s.replace('&', '&') | 28981ce5d30f7d01e81921524f569e064457c147 | 666,070 |
def _to_time(integ, frac, n=32):
"""Return a timestamp from an integral and fractional part.
Parameters:
integ -- integral part
frac -- fractional part
n -- number of bits of the fractional part
Retuns:
timestamp
"""
return integ + float(frac)/2**n | b558806f174f5305bf1c1b0c20c2a5fab8331037 | 666,071 |
def get_current_history_length(): # real signature unknown; restored from __doc__
"""
get_current_history_length() -> integer
return the current (not the maximum) length of history.
"""
return 0 | 6468305dc7d4e70a78ef5944568d2aebe8a7a03b | 666,072 |
import math
def negative_binomial(x, k, p):
"""
Evaluate the negative binomial distribution b*(x; k, p) as defined in the textbook.
Equivalent to finding the probability of coin flip x to be the k-th head when the
probability of getting a head on any one coin flip is p.
Found with the equation (... | c4b2d923cafdb95142cafe40c1f4248278f06323 | 666,073 |
def _check_monit_services_status(check_result, monit_services_status):
"""
@summary: Check whether each type of service which was monitored by Monit was in correct status or not.
If a service was in "Not monitored" status, sanity check will skip it since this service
was temporarily ... | ca3eb912c025a49f797608f825932c0b1f8da54d | 666,074 |
def square(inp):
"""*inp* squared"""
return inp ** 2 | 6c7a62c80f838c11fc7f260a54f779addbb1f52e | 666,076 |
import random
def select_vowel_sample(X, Y, F, y_class, ind=None):
"""Select a specific vowel sample from the set
"""
labels_ints = [y.argmax().item() for y in Y]
inds_this_clss = [i for i in range(len(labels_ints)) if labels_ints[i] == y_class]
if ind is None:
ind = int(random.random()*l... | d81a2da5392bdd2a63d4682e761f9f49782b63cc | 666,077 |
def _get_locales_session(self, request):
"""
Retrieves the locales list value using a
request session strategy.
:type request: Request
:param request: The request to be used.
:rtype: List
:return: The retrieved locales list.
"""
# retrieves the accepted language
locale = self.g... | 63ebe95d5e2fe4aba6d3e7ea21b25d97f685bcf3 | 666,078 |
import hashlib
def sha224hash(text):
"""Takes in text and returns the sha224 hash"""
hash = hashlib.sha224()
hash.update(text.encode("utf-8"))
return hash.hexdigest() | 7667a4ff9571505c53015f89d392f88819dc6e73 | 666,079 |
import os.path as op
def concat_iterables(iterables):
""" Concatenates iterables (starting with subject).
Parameters
----------
iterables : list
List of iterables to be concatenated into a path (e.g. after using
nipype Merge-node).
Returns
-------
out_name : str
C... | e7f75b14d3148aa1ad7c870ddfd559fa6af680ac | 666,080 |
def get_alias_names(meta_data):
"""Returns the list of configured alias names."""
if len(meta_data) <= 0 or 'alias' not in meta_data:
return None
aliases = meta_data['alias']
if isinstance(aliases, list):
# If the alias meta data is a list, ensure that they're strings
return list... | b00ba31d9c60c001f950a2a3c4d7a0d8e863d7f9 | 666,081 |
def simplify(seq, drop_zero):
"""
Combine coefficients of terms with the same variable and optionally drop
zero weights and sum up terms without a variable.
"""
elements = []
seen = {}
rhs = 0
for co, var in seq:
if co == 0:
continue
if var is None:
... | da5a4aef7e483b31996cfb9d5381f1e056b4b130 | 666,082 |
def get_Q_HP_d(L_HP_d, etr_loss_TU):
"""
Args:
L_HP_d: param etr_loss_TU:
etr_loss_TU:
Returns:
"""
return L_HP_d / (1 - etr_loss_TU) | dc3cd20d7d6d80bf9d75db3e9169a70e043692f4 | 666,083 |
def parse_line(pnts, im_scale):
"""
:param pnts:
"x1,y1,x2,y2,x3,y3,x4,y4,language,text"
矩形四点坐标的顺序: left-top, right-top, right-bottom, left-bottom
:return:
(x1,y1,x2,y2,x3,y3,x4,y4), language, text
"""
splited_line = pnts.split(',')
if len(splited_line) > 10:
spli... | db9970a232c63c46ffa191306f3b188a3242cca0 | 666,085 |
import json
def read_json(filename: str):
"""Read a json file and return data as a dict object"""
print('Reading json file ' + filename + '...')
f = open(filename, 'r')
Instance = json.load(f)
f.close()
print('Done')
return Instance | d5327b4a34e9c5635fd51ad5d45c47a0d4ab2f46 | 666,086 |
def unescape_string(escaped_string):
"""
Remove escape character in a string.
:param escaped_string: String to be unescaped.
:type escaped_string: 'str'
:return: Unescaped string.
:rtype: 'str'
"""
modified_string = escaped_string
str_len = len(modified_string)
i = 0
while i ... | e80a9de9e06e384566a4fbd7ed4aef667bed6b6b | 666,087 |
def Porcentagem(p, v):
"""
Retorna a porcentagem de um valor
p: porcento
v: valor
"""
return p * v / 100 | f7bc1ffd866c1bcdf3143a4d640fb2cde21c20d5 | 666,088 |
import os
def get_package_name_from_path(path):
"""Get package name as file portion of path.
>>> get_package_name_from_path('/some/random/path/package.tar.gz')
'package.tar.gz'
>>> get_package_name_from_path('/path/underscored_name.zip')
'underscored_name.zip'
>>> get_package_name_from_path('... | c7a566a66fc7849cb102c0cd4069c2af46ee7745 | 666,089 |
def policyNoAction(decstate):
""" No shaping action is taken """
return set([]) | d5c971e77043adc417a3cc5881a762338ce9b76c | 666,090 |
def create_graph():
"""Reads graph.txt and returns a dictionary
with nodes as keys and the value is a list of
nodes that the given node has a directed edge to.
Returns:
dict: the graph as a dictionary
"""
with open('graph.txt', 'r') as g_file:
K = int(g_file.readline())
... | b0f4a4b589887c0347732056c0ba64a676e9951e | 666,091 |
import os
def dirDiff(srcDir, dstDir, excludes=None):
"""
比较两个目录的结构差异
:return 返回srcDir比dstDir多出的目录和文件路径列表(diffDirs, diffFiles), 注意多出目录内的内容不会列出来
srcDir比dstDir少的部分可以通过反向比较获得
"""
def match(name, patterns):
for pattern in patterns:
if pattern in name:
return Tru... | 987d9684308841920dd29321ea9105537810cc2d | 666,092 |
def ImportModule(moduleName):
"""
A convenience method for importing the given module name.
@param moduleName: the name of the module to attempt to import
@type moduleName: C{str}
@return: A reference to the module object that can be queried, introspected,
or instantiated.
@rtype: C{module}... | 37c2ee934e5220bc74bfac67843afc7c76e84e04 | 666,093 |
def readPgfamGeneMatrix(fileHandle):
""" read pgfamGeneMatrix from file handle
Data are list of genes (comma-delimited) per genome per pgfam
rows are pgfams, cols are genomes, column headers identify genomes
"""
# genome ids are headers in first line
header = fileHandle.readline().rstrip()
g... | 0d154d0051ed7390e3b37011f3c1b04a6c348f60 | 666,094 |
def get_routing_list(app):
"""Make a sumple list of routing rules.
:param app: Flask application
:returns: list of routes
"""
routes = []
for route in app.url_map.iter_rules():
routes.append({"uri": route.rule,
"methods": sorted(list(route.methods)),
... | ee5627398f5b663ff1a62cbdf5c1dbd524a6702f | 666,095 |
def _keyword_parsed_sub_dir(job):
"""
Return parsed `sub_dir` string
"""
split_at_slashes = job.sub_dir.split("/")
parsed_words = set()
for folder_name in split_at_slashes:
parsed_words.add(folder_name)
if "_" in folder_name:
for word in folder_name.split("_"):
... | 428db4841d925e4a3cd8a154cd6084369130b921 | 666,096 |
def xl_cell_example(cell):
"""a cell has a value, address, formula and note"""
return "[value=%s, address=%s, formula=%s, note=%s]" % (cell.value,
cell.address,
cell.formula,
... | ec69b6260d1059150a01b5f928b88e88c8b1c66f | 666,098 |
from typing import Optional
from typing import List
from typing import Tuple
def is_valid_atom_index(index: int,
coordinates: Optional[dict] = None,
existing_indices: Optional[List[int]] = None,
) -> Tuple[bool, str]:
"""
Check whether an... | 311b106f00994f617b953d6b630f8f3515f8dd8b | 666,099 |
from operator import add
def top_five_urls(rdd):
"""
Return a rdd only with the top 5 url's
with more requests by descending order.
return type: pyspark.rdd.PipelinedRDD
"""
urls_rdd = rdd.map(lambda line: line.split('"')[1].split(' ')[1])
count_rdd = urls_rdd.map(lambda url... | d0a8826e47dc16026acd9568b91038fe11023749 | 666,100 |
def str_bool(s: str) -> bool:
"""Converts string ('0' or '1') to boolean"""
return s == '1' | 740299a29eca3f851ad3aec5f836c3db5c98a2c5 | 666,101 |
import sys
def is_piped_input():
"""
Checks the piped input.
This function checks if this script
is being executed with a piped input.
E.g.: echo abcde | python shift.py
Returns
-------
bool
True if the is a piped input, False otherwise.
"""
return not sys.stdin.isat... | 9814faa9d528e477f08e428e199d13781cfb2b05 | 666,102 |
import os
import glob
def return_running_pids():
"""return list of running processids, excluding this one"""
mypid = os.getpid()
pids = []
for fn in glob.glob('/proc/[0123456789]*'):
if mypid == os.path.basename(fn):
continue
pids.append(os.path.basename(fn))
return pid... | f334ff26228c084e5c28f3d961fbd07cba6dd62e | 666,104 |
def Nobullet_f(val):
"""
:param val: The value of this Nobullet
"""
return val.strip() + '\n' | 7576585e592c0e90fd384d0f267cf227540af9e4 | 666,106 |
def encode(self, inputs, label):
""" Encodes the input into the latent space."""
return self.sess.run(self.z_mean, feed_dict={self.x: inputs, self.y: label}) | ab51527090212251a803e7a0406c790ad2224a4a | 666,107 |
def generate_diffs(list_stats, agg_stats):
"""Generates diffs between last month and this month's stats and returns
them in a dictionary."""
diffs = {}
for k in agg_stats.keys():
diffs[k] = [
((list_stats[k][1] - list_stats[k][0]) / list_stats[k][0]
if list_stats[k][0] e... | 4cc5c37346889b09f895d9b2476796fe1667cd78 | 666,108 |
def hashStr(String, tablesize):
"""
添加权重计算散列值
:param String:字符串
:param tablesize:散列表的长度
:return:散列值
"""
sum = 0
for i in range(len(String)):
sum = sum + (ord(String[i])*(i+1)) # 为字符添加权重,为下标加1
return sum % tablesize # 3 | 33f41371e0849f3bd7b7659ccac413baa7ca5bad | 666,109 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.