content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def color_rgb_to_hex(r: int, g: int, b: int) -> str:
"""Return a RGB color from a hex color string."""
return "{0:02x}{1:02x}{2:02x}".format(round(r), round(g), round(b)) | e3d2236486858f5a44e84bf1705618ac358da004 | 642,089 |
def get_traffic_behavior(self) -> dict:
"""Get traffic behavior configuration and names from Cloud Portal
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - spPortal
- GET
- /spPortal/trafficBehavior
:return: Returns... | 381a5b5fe55fec6e88af91d318c369aea51b959b | 642,090 |
def check_clause(sw, idx, out_degree, in_degree, cjc_idx, c_and_e):
"""
Check out clause
"""
if ',' not in sw:
f_flag, b_flag = 0, 0
for i in range(0, cjc_idx+2, 1):
if out_degree[i] != out_degree[cjc_idx] or in_degree[i] != in_degree[cjc_idx]:
f_flag = 1
... | 828882c7249cb9239eb5a4896ba304e910c708c5 | 642,091 |
import time
def create_redshift_cluster(DWH_CLUSTER_TYPE,
DWH_NODE_TYPE,
DWH_NUM_NODES,
DWH_DB,
DWH_CLUSTER_IDENTIFIER,
DWH_DB_USER,
DWH_DB_PASSWORD... | 202f32699e761e12b78fe483fc1da9a81a02a30e | 642,093 |
def check_for_code(module):
"""
Check if there's at least one class or one function in the module.
"""
fd = open(module, 'r')
for line in fd:
if line.startswith('def ') or line.startswith('class '):
fd.close()
return True
fd.close()
return False | 12161a25b2d09d2626e478f406745cadd67ae8ab | 642,094 |
import sys
def get_yaxis_range(list):
"""
Given a list of dictionaries, where each dict holds the information
about an IB, this function returns a tuple (low, high) with the lowest
and the highest value of y-axis, respectively.
"""
low, high = sys.maxsize, -1
for node in list:
low... | 52b0dc09826c19f6c96973e5efa8679396983988 | 642,095 |
def bytes_endswith(x: bytes, suffix: bytes) -> bool:
"""Does given bytes object end with the subsequence suffix?
Compiling bytes.endswith, with no range arguments, compiles this function.
This function is only intended to be executed in this compiled form.
Args:
x: The bytes object to examine.... | 5d81c0b9dd37f2a0938c428e6bf2676f6b17b969 | 642,096 |
def find_allocas(func):
"""
Find allocas that can be promoted to registers. We do this only if the
alloca is used only in load and store operations.
"""
allocas = set()
for op in func.ops:
if (op.opcode == 'alloca' and
all(u.opcode in ('load', 'store') for u in func.uses[... | e7ca08ebf07b9822b7d4480abf5bfe3ef300a3b8 | 642,097 |
import argparse
def get_arg_parser(parser=None):
"""
Args:
parser (argparse.ArgumentParser): an argument parser instance
Returns:
argparse.ArgumentParser: the argument parser instance
Notes:
if parser is None, creates a new parser instance
"""
# add arguments that are... | a03df2ddb3c999f1a90d2d2cce8ac20dded98f99 | 642,098 |
def get_p(df, gs):
"""
计算 sigma1
:param df:
:param gs:
:return:
"""
return 1 - gs.predict_proba(df)[:, 1] | ec6049d2359e4ed8ffcfc1b3a00c0ccdd5357656 | 642,099 |
from typing import List
def search_word_from(
db: List[str], query: str, split_token: str = "", ingore_case: bool = True
) -> List[str]:
"""Search str qurey from list of str db. If split_token is given,
split each str in db by split_token and check for exact match.
If ingore_case is True, ignore case.... | 18b54bff51686601a5f1bd4eb8c61e538c0328d4 | 642,100 |
import os
def check_dir(path: str) -> bool:
"""
Checks whether a directory exists or not.
"""
return os.path.isdir(path) | 4df65e2ba29a5aa5ac76f206cb1c1abc368d7d1f | 642,102 |
def currency(value=0.0, currency='R$'):
"""
#EN-US:
→ Formats the value to display it as a monetary value.
:param value: the value to be formatted.
:param currency: (Optional) the currency symbol that will be
used for formatting. The default is Real (R$).
:return: the value formatted with th... | a8da828a65ad04043a6f6c77c046999666b3c877 | 642,103 |
def get_conv_weights_names(G):
"""Get convolutional layer weights names from StyleGAN2 generator model."""
state_dict = G.state_dict()
keys = state_dict.keys()
keys = [k for k in keys if "conv" in k]
keys = [k for k in keys if k.endswith(".weight") or k.endswith(".bias")]
keys = [k for k in ke... | d818f8bf16bf85ff74ea1929332e007f819a5e02 | 642,104 |
import sympy
def DefineCalculateNormals(normal, tangent1, tangent2, J):
""" This method calculates the normals and tangents
Keyword arguments:
normal -- The normal vector
tangent1 -- The first tangent vector
tangent2 -- The second tangent vector
J -- The Jacobian matrix
"""
[nnodes, ... | 5b34e862bb0ad255cd56da8fc4f09878c7d8caa1 | 642,105 |
import glob
import os
def find_resource_path(path, max_up=5):
"""Recursively looks for files on the current directory and parents.
Args:
path(str): base path or files name of resource to search.
max_up(int): max parent directory from which to recurse.
Returns:
(str): path to foun... | 8e89d4d7f6b502a991ece4ebadacf4752179ae4d | 642,106 |
def filters_logical_and(f1, f2, f3):
"""
given three filters, returns the logical and of these filters
in the order: f1 AND f2 AND f3.
Parameters:
-----------
f[1/2/3]: `dict`
filter expression to be combined.
Returns... | b1fb288219a475b2807804af22dcf1989aa67689 | 642,107 |
def dict_to_model(model: object, **data):
"""
将 dict 转为对象
使用示例:
dic = {'name': 'python', 'price': 10}
model = Model()
BeanUtil.dict_to_model(model, **dic)
"""
model.__dict__.update(data)
return model | a6a0bfafab83675869bfedb4d6993f7fa94415dc | 642,108 |
import json
def generate_ctx(row, input_lifespan=0, output_lifespan=2):
"""
Generates json objects for the input and output contexts, containing their names and lifespans,
from a dictionary corresponding to a row in a dataframe.
Example format:
{"name": "await_18", "lifespan": 0}
: param row... | 05c2c4c102e5c71f77aa8182e57ccaf42da9d49d | 642,109 |
def roll_damage(damage_string: str):
"""
Damage is usually given as a string in the format XdY+Z. We extract X, Y, and Z from this format and then roll the
necessary dice
:param damage_string: XdY+Z
:return: the amount of damage done with this attack
"""
return 0 | d6423d70682c81691488b2c740d5801880454310 | 642,110 |
def get_model_fields(model):
"""
Retrieves all non-auto- and non-relation- fields from the supplied model and returns as a list
"""
return list(
filter(
lambda x: x.get_internal_type() != "AutoField"
and not getattr(x, "is_relation"),
model._meta.get_fields(),... | a4caf70abdb7aded4f0a4cef7d17f547b631e8ec | 642,111 |
import bs4
def beautiful_soup(*args, **kwargs):
"""Indirection function so we can lazy-import bs4.
It's an expensive import that invokes re.compile a lot, so we don't want to incur that cost
unless we must.
"""
return bs4.BeautifulSoup(*args, **kwargs) | 195f6f6a736c867c5f40b564406812ecaa82deb8 | 642,112 |
def XYtoJI(x, y, ext, cellsize):
"""return a tuple of array-space coordinates
arguments
x, y x and y coordinates (numeric)
ext arcpy Extent object (array extent)
cellsize square array cell size (numeric)
"""
jFloat = ((ext.YMin + ext.height - y) / cellsize)
iFloat = ((x - ... | 2aa362481bceb95ceae6cc6900e48c12fc8481e3 | 642,113 |
import os
def tabstr2list(data):
"""tabstr2list"""
alist = data.split(os.linesep)
blist = alist[1].split('\t')
clist = []
for num in range(0, len(alist)):
ilist = alist[num].split('\t')
clist = clist+[ilist]
cclist = clist[:-1]
#the last element is turning out to be empt... | 343c9b864af30cd76138efa9fcde3c5d3eeb501f | 642,114 |
import setuptools
def packages():
"""return `packages` list - `setuptools.find_packages()`"""
return setuptools.find_packages() | 2e102c2295f2a1d38c252f4e5003077746668e38 | 642,115 |
import os
def get_integration_folder():
"""
returns the integration test folder
"""
return os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) | cb652e0a256445e1c72ee927fea6a80e9cad07c5 | 642,116 |
def calculate_stats(array):
"""Return min, max, avg in the given array.
"""
_count = 0
_max = _sum = 0.0
_min = None
for number in array:
_count += 1
if _min is None or number < _min:
_min = number
if number > _max:
_max = number
_sum += nu... | 73c727de560a9cdb0355c4b77d9ae134805b0843 | 642,117 |
import random
def choose_from_options(options, name, selection="user"):
"""
Prints out options from a list, and returns the requested option.
:param options: dict or Array, options to choose from. If dict, the value entries are assumed to be docstrings
explaining the individual options
:param... | 2edbd17da2fb2ddb4034983ded4fc6c367a8494d | 642,119 |
def UnsplitUriRef(uriRefSeq):
"""should replace urlparse.urlunsplit
Given a sequence as would be produced by SplitUriRef(), assembles and
returns a URI reference as a string.
"""
if not isinstance(uriRefSeq, (tuple, list)):
raise TypeError("sequence expected, got %s" % type(uriRefSeq))
... | 1a236481511a77e18bb7eb70a2c06f6be2f0d67c | 642,120 |
def flatten(items):
"""Flattens a potentially nested sequence into a flat list.
:param items: the sequence to flatten
>>> flatten((1, 2))
[1, 2]
>>> flatten([1, (2, 3), 4])
[1, 2, 3, 4]
>>> flatten([1, (2, [3, 4]), 5])
[1, 2, 3, 4, 5]
"""
retval = []
for item in ite... | be48b6481bf47c9d80902b0f3df7f25a533d6814 | 642,121 |
def __is_dunder(attr_name: str) -> bool:
""" check if a given attr_name is `double underscored` one.
"""
return (
attr_name.startswith('__') and
attr_name.endswith('__')
) | a6ed2aa725c7835d2bbb9c20913245afcdfbc5bd | 642,123 |
def get_events_per_second_api(replay, mods):
"""Gets coordinates and key pressed per second for API"""
events = []
time = 0
replay_events = replay.split(",")
for event in replay_events:
values = event.split("|")
try:
time += float(values[0])
except ValueError:
... | 3e68a6a9e617b312d605d8380b54afca2a3fca3d | 642,124 |
def get_standard_tag (filename, lang):
"""Get the standard tag. Create standard tag dictionary."""
word_tag_dict = {}
tag_dict = {}
sentence_cnt = 1
word_tag_dict[sentence_cnt] = {}
tag_dict[sentence_cnt] = []
word_position = 0
sentence_dict = {}
sentence_dict[sentence_cnt] = []
... | 02203b00b7cf09560c086fe0fec2c89bf2a804b7 | 642,125 |
def barcode_header(date, price):
"""Format barcode header info line
date: datetime object
price: float
barcode_header takes a datetime object and a float,
representing the price and formats them as so:
MSTAR YYYY-MM-DD DAY P.p
Example:
MSTAR 2016-11-12 SAT 1.2
"""
... | e079ba68511242ba92600a4364a476502abe5411 | 642,126 |
def is_guc_configurable(cursor, guc):
"""Check if guc is a preset parameter
https://www.postgresql.org/docs/current/static/runtime-config-preset.html
"""
cursor.execute("""
SELECT EXISTS
(SELECT 1
FROM pg_settings
WHERE context <> 'internal'
AND... | ca01a26c7cd276eabc44414820cb8c10dd837a18 | 642,127 |
import numpy as np
def augment_flip(X, Y_loc, flip):
"""A function to flip data horizontally or vertically
and apply the same transformation to the location label
Inputs:
X | r4 array | samples x height x width x channels
Y_loc | r2 array | samples X 4
flip | string | determines w... | c779cfd05b4f855c1c34e15a2ee5ee34138d9bed | 642,128 |
def init_filter(df, report=False):
"""Keep relevant subset of topics"""
keep_topics = ['economy', 'europe', 'health', 'crime', 'education', 'immigration', 'law']
groups = df.groupby('topic')
sub_df = df[df['topic'].isin(keep_topics)]
sub_groups = sub_df.groupby('topic')
if report:
print(... | 40f1b09f3e1bda21b2a28d31303250c19a437b71 | 642,129 |
import re
def parse_gtf_attr_line(attr_line):
"""parse a GTF attributes line"""
if len(attr_line) == 0:
return {}
attr_line = [x.split(' ') for x in re.split('; +', attr_line.replace('"', ''))]
attr_line[-1][-1] = attr_line[-1][-1].rstrip().replace(';', '')
return dict(attr_line) | e338dc12476abd5560ea828fb9bf1b5259ef47b2 | 642,130 |
from typing import Callable
from typing import Any
import cProfile
import io
import pstats
def profiler(function: Callable) -> Any:
"""Profiler & optimizer decorator.
Decorator function that uses cProfile to profile, test & optimise
other functions. The profiling is done at the later stage once the
b... | 6fc8767bb9831a7e954973c579066fe8a4731a60 | 642,131 |
import six
def is_string(value):
"""Return a boolean value indicating whether the value is a string or not.
This method is compatible with both Python 2.7 and Python 3.x.
NOTE:
1. We can't use isinstance(string_value, str) because strings in Python 2.7 can have "unicode" type.
2. We can't use isi... | 809e4d43390219f08cf81e9389b38e045aae0e0c | 642,132 |
def slide_window(track, n=4, start_cycle=1, skip_cycle=2):
"""
:param track:
:param n:
:param start_cycle:
:param skip_cycle:
:return:
"""
window = [track[i]
for i in range(start_cycle - skip_cycle, start_cycle + n)]
return window | c86bfeb84251481e068b965ee6e6bf868143d42f | 642,133 |
def iterative_lcs(var1, var2):
"""
:param var1: variable
:param var2: 2nd variable to compare and finding common sequence
:return: return length of longest common subsequence
examples:
>>> iterative_lcs("abcd", "abxbxbc")
3
>>> iterative_lcs([1, 2, 4, 3], [1, 2, 3, 4])
3
"""
... | 838b9592ce9bf27cf4f5854dd66ff13110da8cc0 | 642,134 |
def color_amount(accel_component):
"""Convert acceleration component (x, y, or z) to color amount (r, g, or b)"""
standard_gravity = 9.81 # Acceleration (m/s²) due to gravity at the earth’s surface
accel_magnitude = abs(accel_component) # Ignore the direction
constrained_accel = min(accel_magnitude, s... | 487f1c66426bc1c69f86781c46906d2631aedf17 | 642,135 |
def _distant_model_inputs(model):
"""Get inputs for distant Nodes in a Model used as feedabck or teacher.
These inputs should be already computed by other Nodes."""
input_data = {}
for p, c in model.edges:
if p in model.input_nodes:
input_data[c.name] = p.state_proxy()
return inp... | 4456c5d2931c24e194ba607c43adcd6fcd3d8de6 | 642,136 |
def extract_attr_for_match(items, **kwargs):
"""Helper method to get attribute value for an item matching some criterion.
Specify target criteria value as dict, with target attribute having value -1
Example:
to extract state of vpc matching given vpc id
response = [{'State': 'available', 'VpcId': 'vpc-2bb... | 1500f8ebc9c6962fd3afaf5cda1962972040060b | 642,137 |
from typing import Iterable
from typing import Any
def pretty_function(name: str, args: Iterable[Any]) -> str:
"""Produce a pretty textual description of a function call.
Produce a string describing a function call. This is of the form:
name(args[0], args[1], ...)
Arguments:
name: Name of fu... | b9c7147f1d7e0500da1037c44e049c12998e17e2 | 642,138 |
def insertFace(bm, v):
"""
insert face using an array of vertices indices
:param bm:
:param v: list of vertices indices
"""
a = []
for k in range(len(v)):
a.append(bm.verts[v[k]])
f = bm.faces.new(a)
bm.faces.ensure_lookup_table()
return f | c02b2ca52d4aa3bfc89daeb84579e66bc55b1310 | 642,140 |
def accuracy_calculation(actual_label, predicted_label):
"""计算准确率
:param actual_label: 真实类标
:param predicted_label: 模型预测的类标
:return: 准确率(百分制)
"""
correct_count = 0
for i in range(len(actual_label)):
if actual_label[i] == predicted_label[i]:
correct_count += 1
return c... | ae788ab2aa9fb9c1ad111cf749d9bc047c372319 | 642,141 |
def conv_8to16(v):
""" Conversion d'une variable 8 bits en 16 bits
:param v: var (8b)
:return: 16bit conversion """
return ((v << 8) + v) & 0xFFFF | 1f9f1c764ca91c175d8d69de3878247b6c35c5ca | 642,142 |
import subprocess
def run_sleep(period):
"""
run_sleep
@param period:
@return:
"""
proc = subprocess.Popen(['sleep', str(period)])
return proc | e8e2d101f25ea9bb5eb7f4361f6373eb218beab2 | 642,143 |
from typing import Tuple
from pathlib import Path
def endswith(path, suffixes: Tuple[str, ...]) -> bool:
"""
Returns whether the path ends with one of the given suffixes.
If `path` is not actually a path, returns True. This is useful
for allowing interpreters to bypass inappropriate paths, but
alw... | 0feae633bede862ac839b95ebe0a9b3ffd16949d | 642,147 |
def open_data(file_position):
"""this function is defined to read the targe file and return with an matries"""
with open(file_position) as file:
data=[];
for line in file:
item=line.split(',');
data.append(item);
file.closed;
return data; | 9ea632edf7409c78279aa89976d82d4ce1f87e15 | 642,148 |
def create_unique(dic):
"""
create unique identifier from the dict
"""
return dict(zip(range(1, len(dic.keys()) + 1), dic.keys())) | b89fb7b0b485659bfd778eb9a308c6e452e5d380 | 642,149 |
def decode(param):
"""Decodes the given param when it is bytes."""
if isinstance(param, (float, int)):
return param
return param.decode("utf-8") | 566ec8ff60c88b18e42a432b10a512e20ba007fe | 642,150 |
def _default_ret(name):
"""
Default dictionary returned.
"""
return {"name": name, "result": False, "comment": "", "changes": {}} | 11b51981ec910df2ec8e0a1bead0f2d3d5f44c30 | 642,151 |
import os
def unique_filename(path):
"""Returns a unique path by appending (n) for some number n to the end of the filename."""
base, ext = os.path.splitext(path)
counter = 0
while os.path.exists(path):
counter += 1
path = base + ("(%d)" % counter) + ext
return path | a389b23adcee8ddba2fab98d8f5912aae67a4865 | 642,152 |
def funex(c):
"""
Compiles a scriptlet expression into a Python function
:param c: function to compile
:type c: string
:return: the function 'f' declared in the input string
:rtype: function
"""
dc = {}
exec(c, dc)
return dc['f'] | 4bb35bd3bcdd8819a465079ce3f3cf0394179364 | 642,153 |
def f(y, t, params):
"""A function that does derivatives"""
X, S = y # unpack current values of y
umax, Ks, Yxs = params # unpack parameters
derivs = [X*umax*S/(Ks+S), # list of dy/dt=f functions
-X*umax*S/(Yxs*(Ks+S))]
return derivs | 7968f024145d6b8121c89e257aa1ef244d18d031 | 642,154 |
def good_response(response):
"""
Returns True if the response is HTML.
"""
resp_type = response.headers['Content-Type'].lower()
return response.status_code == 200 and \
resp_type is not None and resp_type.find('html') > -1 | 3c0613258ae92196488d9c2b474d83f63aa24699 | 642,155 |
import re
def capital_case_without_symbols(name: str) -> str:
"""
Determine the name of the output file by stripping
all special characters and capital casing the words.
:param name: Deck name (unsanitized)
:return: Sanitized deck name
"""
word_characters_only_regex = re.compile(r"[^\w]")
... | 71d11f7ba41244f05e407fd38b708987c58a5012 | 642,157 |
import argparse
def parse_args():
"""arguments for this script"""
parser = argparse.ArgumentParser(
description="deployed server yaml to ansible inventory"
)
parser.add_argument(
"input_yaml", help="openstack overcloud node provision output yaml"
)
parser.add_argument(
... | fc6d003da030e21487f7259e69573de9b481d6a0 | 642,158 |
from typing import Dict
import re
def extract_district(original_fields: Dict):
"""
Extract the Brazilian district name from the city name and send it as
district. Example: 'Jaci Paraná (Porto Velho)' for 76840-000
"""
fields = original_fields.copy()
if fields.get("district") is None:
m... | 5033d428bbc08ab07b25e45154bf4d7245384669 | 642,159 |
def LineColour(argument):
"""Dictionary for switching line colours where appropriate"""
switcher = {
'Black': 'k',
'Red': 'r',
'Green': 'g',
'Blue': 'b'
}
return switcher.get(argument, argument) | 6a45aa61641143125b2bae24989721324a3bbe35 | 642,161 |
def candies(n, ratings):
"""https://www.hackerrank.com/challenges/candies"""
result = [1] * n
for i in range(1, n):
if ratings[i] > ratings[i - 1]:
result[i] = result[i - 1] + 1
else:
result[i] = 1
for i in range(n - 2, -1, -1):
if ratings[i] > ratings[i... | 110eb7ddd141ee5931fa2cfc88627a69d3e15d2f | 642,162 |
import re
def escapeLiterals(s):
"""Escape string of literals s."""
return r'\|'.join([re.escape(x) for x in s]) | 16eb896bfa86b71c2764f38ff4be290508f39af7 | 642,163 |
import re
def latexify_ion(formula):
"""
Convert a formula to latex format.
Args:
formula (str): Formula
Returns:
Latex string.
"""
return re.sub(r"()\[([^)]*)\]", r"\1$^{\2}$", formula) | f44abd7d997bfe40ed23b9bc053fce77619bd771 | 642,164 |
def getNetwork(networks, name):
"""
Get the network with a specific name. This method does not create a network
if no network exists with the given name.
Arguments:
networks -- Network objects for searching.
name -- Name the network shall have.
Returns:
network object on s... | 2c84f24fa839fad86d82dc56a6484659fa259226 | 642,165 |
def getTag(read, tagId):
"""
Returns the specified tag or None from an AlignmentRecord
"""
for i in read.tags:
if i[0] == tagId:
return i[1]
return None | 55c5d6b4f6d2a6e1d6920f44e9b61464970e3818 | 642,166 |
def merge_lists(results_from_fc):
"""
Function for merging multiple lists
"""
combined_list = []
for li in results_from_fc:
combined_list.extend(li)
return combined_list | 812c48ea055225b8a5f056469ebc31d5c6f7615d | 642,169 |
def title_word_feature(title, processed_text):
""" List of values from 0 to 1 rating the number title words that appear in the sentence"""
title_word_feature_values = []
# Calculate the number of common words with the title that the sentence has
word_intersection = [set(filter(lambda title_word: titl... | 73fb9b6d1950a3106fed528663436ded69953758 | 642,170 |
import math
def zr2uv(zr, wavelength, sinalpha, refr_index, magnification=1.0):
"""Return u,v in optical units from z,r given in units of the wavelength.
For excitation, magnification should be 1.
Examples
--------
>>> numpy.allclose(zr2uv((1e3, 1e3), 488, 0.9, 1.33),
... (13.... | c475eb622b02fe347d6c035e059159564790abe9 | 642,171 |
def extract_component_name(path):
"""
>>> extract_component_name('/foo/trunk/bar.txt')
'foo'
>>> extract_component_name('/foo/trunk/')
'foo'
>>> extract_component_name('/foo/branches/1.x/abcd.txt')
'foo'
>>> extract_component_name('/foo')
Traceback (most recent call last):
.... | 2b35265b2af993d31c19509d418a4704ed85ceb9 | 642,172 |
def get_parent_repo_path(repo, repotype="main"):
"""Return the path of the parent git repository corresponding to the
provided Repository object from the DB.
"""
if repo.parent:
return repo.parent.repopath(repotype)
else:
return repo.repopath(repotype) | ef777490102eb123e4b1ff009e774eb0256d3285 | 642,173 |
def set_convolution_options(opts, convolution_options=None):
"""Set the IPU convolution options for the session.
.. code-block:: python
# Set "availableMemoryProportion" flag to "0.1"
opts = create_ipu_config()
opts = set_convolution_options(opts,
convolution_options={"availableMemoryP... | 102dd191af47dd1e971d423a0c5e5a3ea8b34532 | 642,174 |
import os
import csv
def read_locations(path):
"""
Read the pre-existing locations file, if it already exists.
"""
locations = {}
if os.path.exists(path):
with open(path, 'r') as f:
reader = csv.DictReader(f, delimiter=',')
for row in reader:
iid = i... | 923933f35f2243a7ecd408d1741cc6a2f83ef7be | 642,175 |
def select_all_reads(conn):
"""
Query all rows in the reads table
:param conn: the Connection object
:return:
"""
cur = conn.cursor()
cur.execute("SELECT * FROM reads")
rows = cur.fetchall()
return rows | 60ce7f30d48de0a661b01f4f9185a434128b5059 | 642,176 |
def rel_ref(from_path: str, to_path: str) -> str:
"""
Calculate related reference
:param from_path:
:param to_path:
:return:
"""
path1 = from_path.split("/")[:-1]
path2 = to_path.split("/")
fn = path2.pop(-1)
common = 0
for x, y in zip(path1, path2):
if x != y:
... | 1d5a7d1f6b3659461336d68b04d88d69fe91e683 | 642,177 |
import os
def _find_md(path, dst_depth, depth=1):
"""Find network md files."""
mds = []
files = os.listdir(path)
if dst_depth < depth:
return []
if dst_depth == depth:
for f in files:
tmp = os.path.join(path, f)
if os.path.isfile(tmp) and tmp.endswith('.md'... | 89b6b33801216b1bf724c3a0a82bfe329aa808f9 | 642,179 |
def parse_haga(res_data):
"""
Print a link to the menu of Haga gatukök
"""
return {"menu": []} | dbaea5b60c7484a997f935f2f77e84f6cca483de | 642,180 |
def strip_alligators(string):
"""
This will strip all < > from a string and return it so that a JSON linter quits barking at me
Args:
string (str) : string to strip
Return:
string : original strin minus < and >
"""
try:
first_replace = str(string).replace("<", "[")
... | 5286e20de5aef20d29fc5f12728f937b89119f4b | 642,182 |
def getRadiiFromParameters(p, pointsO, pointsN):
"""
:param p:
:param pointsO:
:param pointsN:
:return:
"""
return p[pointsO + pointsN * 2: pointsO + pointsN * 3] | 55255a008c97760b031c73fdf10c266806fb1bd8 | 642,183 |
def check_equals(generated_value, expected_value, **kwargs):
"""Check that generated_value is equal to expected_value."""
return generated_value == expected_value | 722f79878c6e9874e24cb6bcefcaee63f8a5f0db | 642,184 |
import os
def get_all_xmls(folder_path: str) -> list:
"""
:param folder_path: 读取文件的目录地址
:return: 返回所有的 (xml标注)
"""
# 所有文件
xmls = []
# 返回一个列表,其中包含在目录条目的名称(google翻译)
files = os.listdir(folder_path)
for file_name in files:
# 判断是 xml 或者是 jpg,png 等就放进去
if os.path.isfile(... | 977efb7397ccb271322b1a268a2c39156b90bf50 | 642,185 |
import os
def find(name, directory):
"""
Find the given file in the given directory recursively
:param name: The file to look for
:param directory: The root directory
:return: The full path
"""
for root, dirs, files in os.walk(directory):
if name in files:
return os.pat... | 98d545b6977f0995c3cfe49d930d367df309a35b | 642,186 |
def filter_seg_appear_prop(x, filter_column, prop):
"""
Only keep those segments that appear >= prop*len(segment).
Note: appeared days are original days before filling.
Do it for the filled record.
"""
all_record = x['all_record']
to_filter_record = x[filter_column]
result_dict = {}
... | 4a77bb8d13fb253f16e16a89caccba7c6ea8ff17 | 642,187 |
async def auto_increment_mongo(client, database, collection):
"""Retrieve the next _id for a given Mongo collection
that's based on _id being a simple integer."""
db = getattr(client, database)
collection = getattr(db, collection)
last_id_list = list(
collection.aggregate([{"$group": {"_id":... | 3fe058f9cd1421070e608dd66f90d4d92c86f81d | 642,188 |
import configparser
from pathlib import Path
def get_path_setting(name=''):
"""
Gets a path specified in the Files section of the settings.ini file.
:param name: One of the variable names in the FILES section of settings.ini
:return: Path object from the pathlib library
"""
config = configpars... | 5338a0335d00be1ec05b5f63c1f1c1f7555e7005 | 642,189 |
def int_32_lsb(x: int):
"""
Get the 32 least significant bits.
:param x: A number.
:return: The 32 LSBits of x.
"""
return int(0xFFFFFFFF & x) | afca818f3c7eadc201770bb02a3538bb533b5bb4 | 642,190 |
import csv
def read_csv_file(filename):
"""
Reading data from file filename
"""
name = filename
"""initializing the rows list"""
rows = []
"""reading csv file"""
with open(name, 'r') as csvfile:
"""creating a csv reader object"""
csvreader = csv.reader(csvfile)
... | 533291c04dee7008308dc2fd0033bbb3cfcc15b6 | 642,191 |
import itertools
def time_series_cv(raw_data_filled_df, num_train_years, percentage_cut):
"""Custom time-series split in train-validation sets per year.
If there are more than 3 years in training dataset:
First split: training dataset is first 3 years of data, validation set 4th year data
Second split... | 5052489b94cd7c9be4528a58263fc825bc2483da | 642,192 |
def __index_query(query, key: str) -> float:
""" Returns a property of the query class, keyed by a string.
The key must be one of:
['Memory', 'Duration', 'Bytes Processed', 'Bytes Billed']
Args:
query (BigQueryResult): A BigQuery result class
key (string): A key ... | 6550d6985b6cffe71101a4a0f8a89a3391650296 | 642,195 |
def computescale(population):
"""
Computes appropriate scale to show locations with specific population
"""
if population == '': population = 0
population = int(population)
if population < 20000: return 15
if population < 40000: return 14.5
if population < 60000: return 14
if popul... | d62b6be6c0ec027cc66b8071145ae52ae7a2a2ec | 642,196 |
def init_IndepVar_set(prob, data):
""" Set component independent vars from a dictionary of inputs """
for var in data.keys():
prob[var] = data[var]
return prob | 124e3f06290370fe4cd51e3b82ebdc2b56a6a842 | 642,198 |
def split_index_keywords(kwds):
"""
Split the dictionary ``kwds`` into two dictionaries, one containing
keywords for :class:`IndexedGenerators`, and the other is everything else.
OUTPUT:
The dictionary containing only they keywords
for :class:`IndexedGenerators`. This modifies the dictionary `... | dec8bc9c672bf9972e365bb88697965352f4637f | 642,200 |
def _find_tools_paths(full_args):
"""Finds all paths where the script should look for additional tools."""
paths = []
for idx, arg in enumerate(full_args):
if arg in ['-B', '--prefix']:
paths.append(full_args[idx + 1])
elif arg.startswith('-B'):
paths.append(arg[2:])
... | f98576a92ee7443aba01a7d8a60a804580da15ca | 642,201 |
def readiter(fi, names, sep=' '):
"""
Return an iterator for item sequences read from a file object.
This function reads a sequence from a file object L{fi}, and
yields the sequence as a list of mapping objects. Each line
(item) from the file object is split by the separator character
L{sep}. Se... | 29339e354f782d60d1f88851152a066c3550294c | 642,202 |
def test_simple():
"""Test simple math.
Returns
-------
answer : :obj:`bool`
Returns result of 1 + 1 == 2.
"""
answer = 1 + 1 == 2
return answer | 24560853445e389b416b96f4ec6465c7453ae893 | 642,203 |
def mapSeries(requestContext, seriesList, mapNode):
"""
Short form: ``map()``
Takes a seriesList and maps it to a list of seriesList. Each seriesList has the
given mapNode in common.
.. note:: This function is not very useful alone. It should be used with :py:func:`reduceSeries`
.. code-block:: none
... | 689a5630f4288e03dbb03417b49a1eb70ff041c8 | 642,204 |
import itertools
def arbitrary_string(size=4, base_text=None):
"""
Return size characters from base_text, repeating the base_text infinitely
if needed.
"""
if not base_text:
base_text = 'test'
return ''.join(itertools.islice(itertools.cycle(base_text), size)) | ad430683fa0a98ecddaf96f288f96a54ef39d576 | 642,205 |
def is_sequence(x):
"""Algorithmically determines if x is a sequence."""
try:
len(x)
x[0:0]
return True
except:
return False | 175e9ffbda72559796386a2e44479ac409bfe280 | 642,206 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.