content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def normalize_unit_box(V, margin = 0.0):
"""
NORMALIZE_UNIT_BOX normalize a set of points to a unit bounding box with a user-specified margin
Input:
V: (n,3) numpy array of point locations
margin: a constant of user specified margin
Output:
V: (n,3) numpy array of point locations bounded by margin ~ 1-... | 9a23967b6f472a808c2dfa193c09b4a712b63628 | 667,108 |
import requests
def get_poins(url):
"""获取沸点的Json数据"""
request = requests.get(url)
poins = request.json()
return poins | 352fa10dbcd500c391dfae8c79ec7339b237b602 | 667,109 |
def weighted_sum(predictions, weight=None):
"""Returns a weighted sum of the predictions
"""
return sum([prediction["prediction"] * prediction[weight] for
prediction in predictions]) | ca0c7725082aeefe5c61a656f955c87a97048541 | 667,110 |
def contains_cycle(self):
"""
Determines if one of the connected components contains a cycle
:return: true if one of the connected components contains a cycle
:rtype: bool
"""
contains_cycle = False
STATUS_STARTED = 1
STATUS_FINISHED = 2
for vertex in self.get_vertex():
stat... | f8e4b3c28a5b4d53133982f7b07c6ce94691291b | 667,111 |
def get_form_weight(form):
"""Try to get form weight attribute"""
try:
return form.weight
except AttributeError:
return 0 | c85a172846e793ae7cf2180413ed654d706bd01d | 667,112 |
def matchPrefix(text):
"""
This is silver bullet, cornerstone and magic wand of speed of this algorithm
it filters patterns using manually selected rules. Yes, yes, it's "dirty" code and it could be beautified in
many ways but this library intended to be fast, not beautiful. Without matching is x1.3 slo... | 359bb51a6e473fd0b2ebceec3d731f7879c17cff | 667,113 |
def powerset_table(alphabet):
""" As most of FSA tools doesn't support symbols larger than
one character, we have to use a one-symbol representation.
Eg. : {a,b} is 0, {a,c} is 1, etc.
This function generates a list. l[0] = 'ab', l[1]='ac', ... """
alphabet = list(set(alphabet))
table = []
... | 546fb94847f9d2c39b3a7175d7001ee71b1e082c | 667,114 |
def multi_order_has_good_order(uid, history_grouped, flag):
""" 多次订单并且有精品的老用户 """
if flag == 0:
return 0
df = history_grouped[uid]
if (df.shape[0] > 1) and sum(df['orderType']) > 0:
return 1
return 0 | 8559a13332639b8abbd19389956b2dfe2730d90b | 667,115 |
import json
def gather_overhead_stats(overhead_stats_files):
"""
overhead_stats_files: a (regex) glob of all overhead stats files
"""
launches = {}
for file in overhead_stats_files:
with open(file) as f:
overhead = json.load(f)
for k, v in overhead['launches'].items... | 0fce91af8a442604639188a0153acd78e2ad76b8 | 667,116 |
import time
def time_ymdhm():
"""
获取当前年月日
:return: 当前年月日 例:"20181012"
"""
return time.strftime("%Y%m%d%H%M", time.localtime(time.time())) | 20217e9c38dd41ec7c66b80c302da11abe12d5d9 | 667,117 |
import random
def find_spanning_tree(nodes):
""" Find a random spanning tree."""
# Start with a random node.
row = random.randint(0, len(nodes) - 1)
column = random.randint(0, len(nodes[0]) - 1)
root = nodes[row][column]
root.visited = True
# Create the candidate list.
candidates = ro... | c08e97204dc2a046df1f44e0d54d19ccee9ac657 | 667,119 |
def create_delete_marker_msg(id):
""" Creates a delete marker message.
Marker with the given id will be delete, -1 deletes all markers
Args:
id (int): Identifier of the marker
Returns:
dict: JSON message to be emitted as socketio event
"""
return {'id': id} | 519ab5e4040b39eb6e2bc2c7736be323052a1282 | 667,120 |
import os
def make_full_path(basedir, outkey, origname):
"""Make a full file path"""
return os.path.join(basedir, outkey, os.path.basename(
origname).replace('.fits', '_%s.fits' % outkey)) | 7320a3b22de25186204f548635bcc6078e8188cf | 667,121 |
from typing import Dict
def parse(input_string: str) -> Dict[str, str]:
"""Try to parse input into a dictionary of `variable`:`value` pairs. Raise
ValueError if parsing fails for some reason."""
for sep in ["\r\n", "\n", ";", ","]:
lines = input_string.split(sep)
if len(lines) > 1:
... | 5f707a14abbb0d037283ae1bd32a833f6bfa4ec0 | 667,122 |
def gen_table(codepoints):
"""Generate a binary search table using |codepoints|."""
codepoints = sorted(codepoints)
ranges = []
start = last = codepoints.pop(0)
for codepoint in codepoints:
if codepoint != last + 1:
ranges.append([start, last])
start = last = codepoi... | d4d8cf1a785e85771b91f35803d588626e711675 | 667,123 |
def e(request):
"""Parametrized fixture with all possible entity definitions."""
return request.param | 15d81d4fce235631f6d8433c26c1b6f02fe43fe7 | 667,124 |
def multi_to_one_dim(in_shape, in_index):
""" Convert an index from a multi-dimension into the corresponding index in flat array """
out_index = 0
for dim, index in zip(in_shape, in_index):
out_index = dim * out_index + index
return out_index | b1a38f72225b354a4c8a0ca93f016ac77752bc98 | 667,125 |
def drop_defective_cases(df, feature_list):
"""
Load Patient information from the csv file as a dataframe
"""
drop_index = []
for ind in df.index:
if df.loc[ind,feature_list].sum() == 0 and df.loc[ind, 'stage']!=0:
# print (df.loc[ind, 'patient_name'], df.loc[ind, 'stage'])
... | 4ffaf5bc83c372d68dbdf650563d80e8515a5d12 | 667,126 |
import os
def find_include( include, relative_to ):
"""
Try to match the include to an existing file.
:param include: the text within "" or <> from the include directive
:param relative_to: the directory from which to start finding if include is non-absolute
:return: the normalized & absolute fil... | cf801997d54a2861322595f87cafdafc2a52d4c7 | 667,127 |
def total_seconds(td):
"""
http://docs.python.org/library/datetime.html#datetime.timedelta.total_seconds
"""
return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / float(10**6) | 1ca433fabfd3c6465965f489900612f99d738d2a | 667,128 |
def scc(graph):
"""
Finds what strongly connected components each node
is a part of in a directed graph,
it also finds a weak topological ordering of the nodes
"""
n = len(graph)
comp = [-1] * n
top_order = []
Q = []
stack = []
new_node = None
for root in range(n):
... | 85a9f7fef226b3047ab43934127bb2f00831a248 | 667,129 |
def sort_012(nums):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
nums(list): List to be sorted
Returns: Sorted nums
"""
# Linear search, O(1) in time, O(1) in space
pos0, pos2 = 0, len(nums)-1
i = 0
while i <= pos2 and p... | 0a485a59f851c6a454fee21dec0ed195f7d21e1c | 667,130 |
def max_chan_width(ref_freq, fractional_bandwidth):
"""
Derive max_𝞓𝝼, the maximum change in bandwidth
before decorrelation occurs in frequency
Fractional Bandwidth is defined by
https://en.wikipedia.org/wiki/Bandwidth_(signal_processing)
for Wideband Antennas as:
(1) 𝞓𝝼/𝝼 = fb = (fh... | a72cbafde5af02c4baa50ea64a12fa50adca8869 | 667,131 |
def build_request_url(method, output_format='tsv'):
"""Create url to query the string database
Allows us to create stubs for querying the string api with various methods
Parameters
----------
method: str
options - get_string_ids, network, interaction_partners, homology, homology_best,
... | 5f0d4abd97233ecd3efd98d8f38af6e9c66b9694 | 667,132 |
def getType(line):
"""
reads the resName from the pdbline
"""
if line == None:
return ""
else:
return line[:6].strip().lower() | 442d85275a03d388440f776b5f6c6d3345934577 | 667,133 |
def depunycode(domain: str) -> str:
"""
convert punycode domain to utf8
"""
result = []
for _ in domain.split("."):
if _.startswith("xn--"):
result.append(_[len("xn--") :].encode("ascii").decode("punycode"))
else:
result.append(_)
return ".".join(result) | 22927beb39d27da36074ce16dae0ff040bb4eb70 | 667,135 |
def join_types():
"""Returns a list of the supported join types"""
return ["", "INNER", "LEFT OUTER", "RIGHT OUTER", "FULL OUTER", "CROSS"] | 46b629bfa1ff524e72115023d6566ce420148e69 | 667,136 |
def _add_formset_field_ids(form_field_ids, formset):
"""
Add all input fields of a given form set to the list of all field ids in order to avoid
keyboard navigation while entering text in form fields.
"""
for i, form in enumerate(formset):
for field in form.base_fields.keys():
f... | a5ab6983259f72f6c27668472af68fcc7b864c84 | 667,137 |
def check_brackets_match(text):
"""
Checks, whether brackets in the given string are in correct sequence.
Any opening bracket should have closing bracket of the same type.
Bracket pairs should not overlap, though they could be nested.
Returns true if bracket sequence is correct, false otherwise.
... | df1167fbcacf8f6b0f9691042d1fd7ff6f23d7d7 | 667,138 |
def merge_two_dicts(d1, d2):
"""
Slower implementation that works on older versions of python
:param d1: Dict 1
:param d2: Dict 2
:return: Copy of d1 with new keys from d2 and overlap overwritten by d2
"""
result = d1.copy()
result.update(d2)
return result | a8de8140b9ee409fdc368c58c7faa9c88fbda34d | 667,139 |
def GetBaseResourceId(resource_id):
"""Removes common suffixes from a resource ID.
Removes suffixies that may be added by macros like IMAGE_GRID or IMAGE_BORDER.
For example, converts IDR_FOO_LEFT and IDR_FOO_RIGHT to just IDR_FOO.
Args:
resource_id: String resource ID.
Returns:
A string with the b... | 70f46f9bdedeb927f0aa23e0ee9297ca3aeb710e | 667,140 |
def _filter_by_attr(list_in, attr_name, attr_val, match_substring=False):
"""
Filter input list by the value of its elements' attributes.
"""
list_out = []
for val in list_in:
if match_substring:
if attr_val in getattr(val, attr_name):
list_out.append(val)
... | 2446a748b55631a8bd60d6bfaf09e2fa454ab3c3 | 667,141 |
def add_additional_columns(data):
"""
adds "highlighted" and "profile_selected" column
:param data: ptcf data frane
:return: ptcf data frame with additional information
"""
highlighted = [True] * len(data.index)
data['highlighted'] = highlighted
profile_selected = [False] * len(data.index)
da... | a511f62b438ca7885ba8b168e5aae534b9f222ac | 667,142 |
def is_hidden_file(filename):
"""Does the filename start with a period?"""
return filename[0] == '.' | 534d3afe9b45393fb35866014b11eac55100d6ae | 667,143 |
def do_nothing_decorator(*_args, **_kws):
"""
Callable decorator that does nothing.
Arguments are catched, but ignored.
This is very useful to provide proxy for decorators that may not be
defined.
Args:
*_args: Positional arguments.
**_kws: Keyword arguments.
Returns:
... | 8b8dff61d9248c767025e65fb5771b73e9c661c1 | 667,144 |
import struct
def unpack_dint(st):
"""unpack 4 bytes little endian to int"""
return int(struct.unpack('<i', st[0:4])[0]) | 8924e18537dc4b25cb48a74bcaad3b01991c426e | 667,145 |
from typing import List
from typing import Tuple
import torch
def _mul_m_lm(mul_l: List[Tuple[int, int]], x_m: torch.Tensor, x_lm: torch.Tensor) -> torch.Tensor:
"""
multiply tensor [..., l * m] by [..., m]
"""
l_max = x_m.shape[-1] // 2
out = []
i = 0
for mul, l in mul_l:
d = mul ... | e23d072780effb1cf129c811042a08dddab6d61e | 667,146 |
import torch
def scale_boxes(bboxes, scale):
"""Expand an array of boxes by a given scale.
Args:
bboxes (Tensor): shape (m, 4)
scale (float): the scale factor of bboxes
Returns:
(Tensor): shape (m, 4) scaled bboxes
"""
w_half = (bboxes[:, 2] - bboxe... | 7f8e99f67a7b6945a82eef6ade3f7d6c6c24afce | 667,147 |
def seismic_suspension_fitered(sus, in_trans):
"""Seismic displacement noise for single suspended test mass.
:sus: gwinc suspension structure
:in_trans: input translational displacement spectrum
:returns: tuple of displacement noise power spectrum at :f:, and
horizontal and vertical components.
... | 38515f96dceeb66e100645658211ecfdc2177489 | 667,148 |
import re
def clean_string(t, keep_dot=False, space_to_underscore=True, case="lower"):
"""Sanitising text:
- Keeps only [a-zA-Z0-9]
- Optional to retain dot
- Spaces to underscore
- Removes multiple spaces , trims
- Optional to lowercase
The purpose is just for easier typing, exporting, sa... | 36d72799c5ad4df6f64b3a7ba387adbc45ae645a | 667,149 |
def only_letter(s: str) -> str:
"""Filter out letters in the string."""
return ''.join([c for c in s if c.isalpha()]) | a754578aaffce8299387db669874a9e2c63a1130 | 667,150 |
def test_begin_str(test_name,max_len=40):
"""
Use with test_end_str(test_name) to make string like this:\n
******** Test Begin ********\n
******** Test End **********
"""
if (len(test_name)%2==1):
star_len=(max_len-len(test_name))//2+1
return '*'*star_len+" "+test_name+" Begin "+... | 46e5872899458803a5db134307d68b651168bea7 | 667,151 |
def _add_associated_policy_to_vault_obj(data, columns):
"""Add associated resources to column and data tuples
"""
return_data = ()
for k, v in data['associate_policy'].items():
return_data += (v,)
columns = columns + (k,)
return return_data, columns | 43645d482f1dbb68fb518ffb4368e95fbd9fe542 | 667,152 |
import random
def tempo_do_equipamento_funcionando():
"""Return actual processing time for a concrete part."""
return random.normalvariate(10.0, 2.0) | 3cf615d0cd6cdb104fe497315a9f34120e6a053a | 667,153 |
def indefinite_integral_over(expression, feed, relation):
"""
https://docs.sympy.org/latest/modules/integrals/integrals.html
"""
return relation(expression.lhs, expression.rhs, evaluate=False) | 4c059020c6713fff226b9768a52d25a4b55af49a | 667,154 |
def add_epochs(imaging, nwbfile):
"""
Auxiliary static method for nwbextractor.
Adds epochs from recording object to nwbfile object.
"""
# add/update epochs
for (name, ep) in imaging._epochs.items():
if nwbfile.epochs is None:
nwbfile.add_epoch(
start_time=im... | 6069be4b830ec8abc1a8cdb42a1a55bd1cea9e5e | 667,155 |
def realm_scope(realm_role):
"""
:return scope of policy for client role
"""
return {"realm_roles": [{"name": realm_role()}]} | b8b9719595b0d53ebf598dd1b94f81538c96c4a5 | 667,157 |
import time
def time_func_call(func):
"""
Prints the processing time of the wrapped function after its context is left.
:param func: Function to be wrapped.
Usage:
@time_func_call
def func():
pass
"""
def wrapped_func(*args, **kwargs):
start = time.process_time()
... | 61b2a11b07ea65b7d3d67cc26033d54e21c80d46 | 667,158 |
from os.path import join, dirname, expanduser
from sys import argv
def read_credentials():
"""Read credentials from file."""
for directory in [dirname(argv[0]),
expanduser('~')]:
try:
with open(join(directory, '.landroid.conf')) as config:
return dict(x.split(': ')
for x in config.read().strip(... | 9b6a61bdfc3ad55891283a785a5b3d535089b4c7 | 667,159 |
import os
def get_prefix_update(path):
"""
Generate a prefix for qresource in function of the passed path for
update command.
Args:
path (str): Relative path of a folder of resources from project dir.
Returns;
str: Prefix corresponding to `path`
"""
# Remove finishing se... | 6f059f4604db3fafd76c94240a7ce5fe748840ac | 667,160 |
def invert_dictionary(old_dic):
"""
This will invert any dictionary so that the keys are the values and the
values are the keys.
Inputs:
:param dict old_dic: a dictionary to invert
Returns:
:returns: dict inverted_dic: old_dict dict inverted so the keys are the
items and the items ... | 8ebae6530e5157e583467aa710654266b731eb22 | 667,161 |
def phase_rms(antbl, scale_prms = 1.0, nu_scale = None):
"""Function that computes phase rms for a given baseline.
The structure function here gives 30 deg phase rms at 10000m = 10km, which
is the limit "go" conditions when performing a go-nogo at ALMA.
Args:
antbl:
Antenna baseline in m... | b081379924bd2cd7ebb227297d6d3aa100ed8fb5 | 667,162 |
def convert_timedelta_to_millis(time_delta):
"""
Conversion routine
:param time_delta:
:return:
"""
return (time_delta.days * 24 * 60 * 60 + time_delta.seconds) * 1000 + \
time_delta.microseconds / 1000.0 | c90184a68ea3faed099168ce0b403377a43e9da6 | 667,163 |
def set_desc(f_nm: str) -> str:
"""
Prompts the user for a description of each line in fname, appends the user
input to that line
:param f_nm: file where each line is formatted "item : *"
:return: f_nm
"""
bltins = dir(__builtins__)
skp = "S"
with open(f_nm, "r") as f:
lines = f.readlines()
with open(f_nm, ... | 424c6adc9268ff83ef1c5bd8d9a0e59aca884b2a | 667,164 |
def set_shape_element(shape, index, value):
"""Set element of shape tuple, adding ones if necessary.
Examples:
set_shape_element((2,3),2,4)=(2,3,1,4)
set_shape_element((2,3),-4,4)=(4,1,2,3)
"""
if index >= 0:
return shape[:index] + (1,)*(index - len(shape)) + (value,) + shape[ind... | beb7668a2c5dc51cbef3b13cfaf0e740c3fbe1cb | 667,165 |
def rm_whitespace(data):
"""Function: rm_whitespace
Description: Remove white space from a data string.
Arguments:
(input) data -> Data string.
(output) Data string minus any white spaces.
"""
return data.replace(" ", "") | 1f9a2a82f6a4a2e136a0876ff9f76269d0b3de23 | 667,166 |
def answer_dict(my_list):
"""Get an item from a list"""
for i in my_list:
return i | ceeca434a1ae4379064f0974f49f3b7c5914d24a | 667,167 |
def GetNextTokenIndex(tokens, pos):
"""Get the index of the next token after pos."""
for index, token in enumerate(tokens):
if (token.lineno, token.column) >= pos:
return index
return None | fca0bd994bbe5fadac1db22f8960ae2d8f08f9fc | 667,169 |
def hsv_to_rgb(h, s, v):
"""Taken from https://github.com/python/cpython/blob/3.7/Lib/colorsys.py and tweaked a bit"""
h = (h % 360) / 360
if s == 0.0:
return int(v * 255), int(v * 255), int(v * 255)
i = int(h*6.0)
f = (h*6.0) - i
p = v*(1.0 - s)
q = v*(1.0 - s*f)
t = v*(1.0 - s*... | 867e30349ea2bffac5c02c70541ac51a04028228 | 667,170 |
import numpy as np
def softmax(x, axis=0):
"""Compute softmax values for each sets of scores in x."""
x = np.swapaxes(x, 0, axis)
e_x = np.exp(x - np.max(x, axis=0))
r = e_x / e_x.sum(axis=0)
return np.swapaxes(r, 0, axis) | 52d33911b59ae9970439e081898656689fb1e646 | 667,171 |
def isPush(cp):
"""
:return bool: If the push parser should be enabled
"""
return cp.get("Push", "enabled", fallback="false").lower() == "true" | f3046c7f4f672efb412f7862e00c0459c1dc59c8 | 667,172 |
def validate_passwords2(password_list):
""" Find valid passwords with min and max as char positions """
count = 0
for password in password_list:
if ((password["password"][password["min"]-1] == password["char"]) !=
(password["password"][password["max"]-1] == password["char"])):
... | 76ecf35420d7b3ba30af6f398e67b9e257d25783 | 667,173 |
def eq_column(table, column, value):
"""column == value"""
return getattr(table.c, column) == value | 07484686e725cab4933e5d0af51ebfc8e115dda7 | 667,175 |
def func_with_args(a: int, b: int, c: int = 3) -> int:
"""
This function has some args.
# Parameters
a : `int`
A number.
b : `int`
Another number.
c : `int`, optional (default = `3`)
Yet another number.
Notes
-----
These are some notes.
# Returns
... | f899eb562d872437e0cb05e7285fc3a2df1d057c | 667,176 |
def a_to_b_concordance(a_df, b_df, a_dv, a_rv, a_geo_id, b_dv, b_rv, b_geo_id):
"""Generalized A->B concordance. """
a_geo = set(a_df[a_geo_id])
b_geo = set(b_df[b_geo_id])
diff = a_geo ^ b_geo
a_to_b = {}
# Generate identity mapping for intersection
# (assumes that if the same GeoIDs occur... | 6433d4bed9cf339012febc1058d7a8e749864f41 | 667,177 |
def compute_total_unique_words_fraction(sentence_list):
"""
Compute fraction os unique words
:param sentence_list: a list of sentences, each being a list of words
:return: the fraction of unique words in the sentences
"""
all_words = [word for word_list in sentence_list for word in word_list]
... | 4b2a9cbef50a1195abc14760d7d2ebf0216ba63b | 667,178 |
def get_dict_string(data: dict, prefix: str = "- ", precision: str = ": {:.4f} "):
"""将字典数据转换成key——value字符串
:param data: 字典数据
:param prefix: 组合前缀
:param precision: key——value打印精度
:return: 字符串
"""
result = ""
for key, value in data.items():
result += (prefix + key + precision).for... | e97e577fb926f89fcaf739e7dc9f38e2e66a186b | 667,179 |
import os
def get_fault_yaml_path(sim_root, fault_name=None):
"""
Gets the fault_params.yaml for the specified simulation.
Note: For the manual workflow set fault_name to None as the
fault params are stored directly in the simulation directory.
"""
fault_name = "" if fault_name is None else fa... | a2974173e181b7db559a057d66b686bb4ef3429a | 667,180 |
def factorialFinderLoops(n):
"""Returns the factorial of the positive integer n using
loops."""
if not isinstance(n, int):
raise TypeError('n should be a positive integer.')
return None
if n < 0:
raise ValueError('n should be a positive integer.')
return None
resul... | 75a258f05230818f3ce00648d3af154315083341 | 667,181 |
def string_to_interactions(string):
"""
Converts a compact string representation of an interaction to an
interaction:
'CDCDDD' -> [('C', 'D'), ('C', 'D'), ('D', 'D')]
"""
interactions = []
interactions_list = list(string)
while interactions_list:
p1action = interactions_list.pop... | 005bebe3dd4368af174d6e73c98757f2b486f974 | 667,182 |
def make_po_file_function_dict(pos, filefilter=lambda f: True):
"""Create a file, function dictionary from a list of proof obligations.
Args:
pos: list of proof obligations (primary or supporting)
filefilter: predicate that specifies which c files to include
Returns:
dictionary that organ... | ea57ad2001c6a7f95d874fa5a41f7273630c7aa3 | 667,183 |
from pathlib import Path
from typing import List
def collect_app_bundles(source_dir: Path) -> List[Path]:
"""
Collect all app bundles which are to be put into DMG
If the source directory points to FOO.app it will be the only app bundle
packed.
Otherwise all .app bundles from given directory are ... | 50a4bf767eb0208045257a2ebf8a760ae7a5fc6d | 667,184 |
import socket
def get_vm_priv_ip():
""" Get VM private IP """
ip = socket.gethostbyname(socket.getfqdn())
return ip | b0fc78aa7cd904f860f42bfd475418ad24d6c6ab | 667,185 |
def select_all_en(con):
""" SELECTする """
cur = con.execute(
'select id, case when length(title_en) > 0 then title_en else title_ja end as title,'
'substr(case when length(description_en) > 0 then description_en else description_ja end, 1, 25) || "..." as description,'
'author, created fr... | 43e63eda44d0132f231f3971c6b87addd8287e97 | 667,186 |
def obter_exercito (unidade):
"""Esta funcao devolve o nome do exercito da unidade dada como argumento"""
return unidade[3] | 76c6318915bc017eecbefdd10df91d56e6be28b4 | 667,187 |
def UserOwnsProject(project, effective_ids):
"""Return True if any of the effective_ids is a project owner."""
return not effective_ids.isdisjoint(project.owner_ids or set()) | a2fe6315835faea262c1774c82c48ff9e0f8ba0c | 667,189 |
def flatten(nested_list):
"""Flatten a nested list."""
return [item for sublist in nested_list for item in sublist] | 764df7f221cb48c60619e97f9b92f298a4ebad26 | 667,191 |
import random
def randomword(length=12):
"""
Generate a string of random alphanumeric characters
"""
valid_chars = \
'abcdefghijklmnopqrstuvyxwzABCDEFGHIJKLMNOPQRSTUVYXWZ012345689'
return ''.join(random.choice(valid_chars) for i in range(length)) | 812a14f247562d8395077231c104eb5e939e8199 | 667,193 |
def read_file() -> list:
"""
Reads file locations.list and returns list of strings
"""
with open("locations.list", "r") as f:
hello = f.readlines()
return hello[14:] | 90c4716936635962376268b7bc179be722bae641 | 667,194 |
import typing
import numpy
def striplist(array : typing.Union[list, numpy.ndarray]) -> str:
"""
Turn the list of objects into a string.
What it does is just simply turn the list into a string and strip away `[]` and `'`.
If the list is empty, it'll return the string "".
Parameter:
- `array`... | 25032636be4f9b89a588e8e722771f1c95697b8f | 667,196 |
def DFS(graph, vertex_edge, start_v_name):
"""Depth First Search"""
for i, vertex in graph.vertex_map.items():
vertex.parent = None
vertex.distance = -1
vertex.visit = False
stack = list()
start_vertex = graph.find(start_v_name)
stack.append(start_vertex)
visit_vertex_l... | 98618104942ba86ffb0e32e3e6478999c99898ee | 667,199 |
from typing import OrderedDict
def _get_price_statistics(trading_day_feed):
"""Calculate and print the following data for each Symbol as a comma-delimiter string.
Rows should be printed in alphabetical order based on Symbol
i. Time: Most recent timestamp for that Symbol in YYYY-mm-dd HH:MM:SS format
... | 9d44ec4a80581475784f08b3af42fcce98f3e6a5 | 667,200 |
def get_polarization_weights(pol=(0.8, -0.3)):
"""Calculate the polarization weights."""
def valid_pol(p):
return p >= -1 and p <= 1
if len(pol) != 2 or not valid_pol(pol[0]) or not valid_pol(pol[1]):
raise Exception(
f"The polarisation {pol} is not understood. Should be "
... | d4f6dd039edd3e9575d4a23c2aa375f0b892b310 | 667,201 |
def rectangle_clip(recta, rectb):
"""
Return the clipped rectangle of ``recta`` and ``rectb``. If they
do not intersect, ``None`` is returned.
>>> rectangle_clip((0, 0, 20, 20), (10, 10, 20, 20))
(10, 10, 10, 10)
"""
ax, ay, aw, ah = recta
bx, by, bw, bh = rectb
x = max(ax, bx)
... | a04265bc26620c99c2635681ccb0a759a081152b | 667,202 |
def polygon_from_bbox(bbox):
""" Generate a polygon geometry from a ESWN bouding box
:param bbox: a 4 float bounding box
:returns: a polygon geometry
"""
return [
[
[bbox[0], bbox[1]],
[bbox[2], bbox[1]],
[bbox[2], bbox[3]],
[bbox[0], bbox[3]]... | e891c60f67474b318fa5c18c34df45632bcf2bd2 | 667,203 |
import re
def myAtoi(str):
"""
:type str: str
:rtype: int
"""
pattern = r"[\s]*[+-]?[\d]+"
match = re.match(pattern, str)
if match:
res = int(match.group(0))
if res > 2 ** 31 - 1:
res = 2 ** 31 -1
if res < - 2 ** 31:
res = - 2 ** 31
else:... | 478dfdc03ac4d90b0cbce477edd0493fc5b6396b | 667,204 |
def normalize_string(name, _cache={}):
"""
Return uppercase string without any surrounding whitespace and
without any characters such as '-', '_' ':' or "'"
"""
if name is None:
return None
if name in _cache:
return _cache[name]
t = type(name)
if t is float or t is int:... | 6d066e08fe4648dcada9e93649eb9ee46b45ea94 | 667,205 |
import re
def simplify_string(string: str) -> str:
"""Remove special symbols end extra spaces.
:param string: what is needed to simplify
:return: simplified string
"""
simpl1 = re.sub(r'[^\w\d\-. ]', '', string)
simpl2 = re.sub(r'[ ]+', ' ', simpl1)
return simpl2 | afee2b4680226e92baf58faa0e96f3ddb7ce473d | 667,206 |
def superuser_user_header(valid_jwt_generator):
"""This fixture further simplifies JWT handling by providing a ready-to-use
headers with a valid superuser JSON Web Token for `requests` module to
use"""
token = valid_jwt_generator(uid='root')
header = {'Authorization': 'token={}'.format(token)}
... | a51765f3a2bf16f73d6d9023717a595018633858 | 667,207 |
import os
import requests
import json
def send_photo(chat_id, photo_url, caption="", reply_to_message_id=0):
""" reply_markup não é apenas ID, é uma array com opções. """
url = "https://api.telegram.org/" + os.environ['REBORNKEY'] + "/sendPhoto?"
url += "chat_id=" + str(chat_id) + "&"
url += "photo=" ... | 73be19161c3cb8d53df236e90ac61713117b0d57 | 667,208 |
import re
def normalize_target(target: str) -> str:
"""Normalize targets to allow easy matching against the target
database: normalize whitespace and convert to lowercase."""
return re.sub(r"\s+", " ", target).lower() | 8388b7eb4e3d2553bb9dd899609ec35718ea63eb | 667,209 |
def _t_contrast_rel_properties(item):
"""Find properties of a compiled t-contrast
Parameters
----------
item : tuple
Contrast specification.
Returns
-------
n_buffers : int
Number of buffer maps needed.
cells : set
names of all cells that occur in the contrast.
... | e20fe3affe6c4ec9c7ff43cc3fbb4d4c043474e7 | 667,210 |
import os
def guessSymbolFile(fn, symbolsDir):
"""Guess a symbol file based on an object file's basename, ignoring the path and UUID."""
fn = os.path.basename(fn)
d1 = os.path.join(symbolsDir, fn)
if not os.path.exists(d1):
return None
uuids = os.listdir(d1)
if len(uuids) == 0:
raise Exception("Mi... | e89c6411dc63eb2b08f2d14d01818de1e84c61ed | 667,211 |
import csv
def check_csv(filename):
"""add some sort of validation. The code here is not working properly. This sniffer package is not working."""
return
with open(filename, 'r') as f:
try:
dialect = csv.Sniffer().sniff(f.read(4096))
except csv.Error:
return 'Not a ... | 2ab60463ac940db0591d007e8e4c590a90eb0fa6 | 667,214 |
def get_dict_path(base, path):
"""
Get the value at the dict path ``path`` on the dict ``base``.
A dict path is a way to represent an item deep inside a dict structure.
For example, the dict path ``["a", "b"]`` represents the number 42 in the
dict ``{"a": {"b": 42}}``
"""
path = list(path)
... | 2aa4930077258a6bac45717b2e2138ae8897a9a6 | 667,216 |
import os
import errno
def get_file_size(file_obj):
"""Analyze file-like object and attempt to determine its size.
:param file_obj: file-like object.
:retval: The file's size or None if it cannot be determined.
"""
if (hasattr(file_obj, 'seek') and hasattr(file_obj, 'tell') and
file_o... | 51f54df9a312f41f044f972aaf697235da199057 | 667,217 |
def hms_to_s(h=0, m=0, s=0):
""" Get total seconds from tuple (hours, minutes, seconds) """
return h * 3600 + m * 60 + s | 2f78dab3a2719d07004cee4621ce67624174030a | 667,218 |
from typing import List
def get_params(opcode: int) -> List[int]:
"""Get params from an `opcode`.
Args:
opcode (int): the opcode to extract params
Returns:
list: of length 0-2
"""
if opcode < 100:
return []
return [int(p) for p in str(opcode//100)] | 5f91503909cad00e27c99078032cb994e2efbfde | 667,219 |
def expense_by_store(transactions_and_receipt_metadata):
"""Takes a transaction df of expenses and receipt metadata and groups on receipt id, in addition to year, month and cat
input:
df (pd.DataFrame): dataframe of transactions to group and filter
returns:
df (pd.DataFrame): grouped datafra... | 59f5c00326dd5f91024557b57e82af5ad1a0bd92 | 667,220 |
def sort_selection(data):
"""选择排序。
先固定第一个元素,找出其右侧最小的元素后,与之交换;依次更新第二个、第三个元素,直至完成排序。
"""
data_len = len(data)
first_unsorted_index = 0
while first_unsorted_index != data_len:
current_min = data[first_unsorted_index]
current_min_index = first_unsorted_index
for i in range(f... | 89cfd3f72f794f15874607810d00f54b3265727c | 667,221 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.