content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def fn_HMS_to_S(hrs,mins,secs):
"""
Convert from hours and minutes and seconds to seconds.
Date: 02 October 2016.
originally in AstroFunctions.py
"""
epoch_time = (hrs*60*60)+(mins*60.0)+secs;
return epoch_time | cc0407fb4824f5688a73762376e9177542c48b2b | 695,965 |
async def fixture_players(lms, request):
"""Return list of players."""
players = await lms.async_get_players()
prefer = request.config.option.PREFER
exclude = request.config.option.EXCLUDE if request.config.option.EXCLUDE else []
include_players = []
if prefer:
print(f"Preferring {prefe... | e4a1a51b3b7b5cc7a055b03645d7582b24459f2b | 695,966 |
import os
def _get_base_app_name(value):
"""Remove path and extension from an application name.
Parameters
----------
value : str
application name that may include a directory path and extension
Returns
-------
value : str
application name base name with out directory pat... | 5002bba117645275dc328cae27e1c160c1df8173 | 695,967 |
import re
def read_cal(infile):
"""
read calibration file
"""
out = []
out2 = []
for line in open(infile, "r"):
tmp_ = re.split(r"\t+", line.rstrip("\n"))
out.append(int(tmp_[0]))
out2.append(float(tmp_[1]))
return out, out2 | 68cbb6c62c054d85c6d9a6ff8fdbdb06e7ba4360 | 695,968 |
import bz2
def serialize_dataframe(report, compressed=True):
"""Serialize a dataframe for storing.
The dataframe is serialized as CSV and compressed with bzip2.
"""
result = report.to_csv(index=False)
if compressed:
result = bz2.compress(result.encode())
return result | f879da2ebb6a9c4a1f5274efd6dfa506af585ce8 | 695,970 |
import random
def get_random_string(length=10):
"""
Generates a random string of fixed length
"""
string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
return ''.join(random.choice(string) for i in range(length)) | 043f7ef3b495c199825242ffd55fabf9e7c1cda7 | 695,971 |
def global_dataframe_resolver(obj, resolver):
"""Return a list of dataframes."""
meta = obj.meta
num = int(meta['partitions_-size'])
dataframes = []
orders = []
for i in range(num):
df = meta.get_member('partitions_-%d' % i)
if df.meta.islocal:
dataframes.append(reso... | 577c453ebff948fc8beaf99b63d8dc93e7be2dcc | 695,972 |
def tpr(true_graph, est_graph):
""" Calculates the True positive rate of an estimated adjacency matrix.
"""
N = len(true_graph)
no_correct = 0.0
no_false_rej = 0.0
for i in range(N):
for j in range(N):
if est_graph.item(i, j) == 1 and true_graph.item(i, j) == 1:
... | f2cb900989a311cddccca8a214d60f00c3174820 | 695,973 |
def _get_label_kwargs_lpt(plot, idx_key=None):
"""Function to get a dictionary for the label keyword arguments for
formatting
:param plot: (x, y, const_list, const_dict)
:param idx_key: I do not even remember what the point of this argument is.
"""
return {'exp': plot[3]['exp'], 'N': plot[3]['N'... | 7c821b7d960a8103598a33c1c488f44538ee7a73 | 695,974 |
import math
def convert_size(size_bytes):
"""
Obtain human readable file sizes
:param size_bytes: Size in bytes
:return:
"""
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size_bytes, 1024)))
p =... | 962b41d64c1892584ff436799b643890a946d17b | 695,975 |
def sperm_translator(cell):
"""If the cell has the DNA for food donation to its offspring, giving 1/6th of its
food in addition to the birthing partner, it is a sperm.
Active DNA: x,B,(D/C),x,x,x
"""
dna = cell.dna.split(',')
if dna[1] == 'B' and dna[2] == 'D':
return True
elif dna[1... | d5a8abb7bea9a6c53856ef069ba3890cb27750b9 | 695,976 |
def get_letter_grade_definitions(letter_grade: str) -> str:
"""
Returns the definition of the letter grade that is passed into the function
Grading Scale -
89.50 - 100 = A \n
88.50 - 89.49 = B+ \n
79.50 - 88.49 = B \n
78.50 - 79.49 = C+ \n
69.50 - 78.49 =... | fd9697063aef5f9b56850a42d333d725e5bc1377 | 695,977 |
def assemble_api_url(domain, operators, protocol='https'):
"""Assemble the requests api url."""
return '{}://{}{}'.format(protocol, domain, operators) | 105d541f2e9196583b2fd5eac1af75cf4c62669f | 695,979 |
from datetime import datetime
import uuid
def generate_ami_name(prefix):
"""
Generate AMI image name.
"""
# current date and time
now = datetime.now()
s2 = now.strftime("%Y%m%d%H%M%S")
x = uuid.uuid4().hex
postfix = str(x)[:10]
ami_name = prefix + "-" + s2 + "-" + postfix
return ami_name | 50cf4e6f8ab55b252503319429594242cea9a77e | 695,980 |
def _cap_str_to_mln_float(cap: str):
"""If cap = 'n/a' return 0, else:
- strip off leading '$',
- if 'M' in cap value, strip it off and return value as float,
- if 'B', strip it off and multiple by 1,000 and return
value as float"""
if cap == "n/a":
return 0
capital = ... | a4c984013ba7c1e06b3569f61d65fe69d98ae2da | 695,981 |
def _get_groupby_and_reduce_dims(ds, frequency):
"""
Get the groupby and reduction dimensions for performing operations like
calculating anomalies and percentile thresholds
"""
def _same_group_per_lead(time, frequency):
group_value = getattr(time.dt, frequency)
return (group_value =... | 0edf7a0798afe5243aa4a8ee52a75c1b6cf36e5d | 695,982 |
import re
def message_match(tpl, key, text):
"""True if text matches tpl for the key"""
for i in tpl["subject_templates"].values():
if re.fullmatch(i[key], text):
return True
return False | f81fe54ec60d592805a94bae700cf2e3a14464bd | 695,983 |
def bed_get_region_id_scores(in_bed, no_float=False):
"""
Read in .bed file, and store scores for each region in dictionary
(unique column 4 ID and column 5 score have to be present).
Return dictionary with mappings region ID -> region score
>>> test_bed = "test_data/test5.bed"
>>> bed_get_regi... | cd4305388251ab9ff9d301ff4bf0409783d1bcfd | 695,984 |
import json
def put_json(client, url, data, headers={}):
"""Send PUT request with JSON data to specified URL.
:url: URL string
:data: Data dict
:headers: Optional headers argument (usually will be authorization)
:returns: Flask response object
"""
return client.put(url, data=json.dumps(dat... | e5fff7c1fdc9cf72e8b314854415c9426e5b261b | 695,985 |
def sipi(b3, b4, b8):
"""
Structure Intensive Pigment Index \
(Peñuelas, Baret and Filella, 1995).
.. math:: SIPI = b3/b8 - b4
:param b3: Green.
:type b3: numpy.ndarray or float
:param b4: Red.
:type b4: numpy.ndarray or float
:param b8: NIR.
:type b8: numpy.ndarray or float
... | b0a7181970e9165d0e75ab7319646fd6bd1c6bbd | 695,986 |
import random
def random_nucleotides(sample_size: int, seq_length: int, seed: int = 1789):
""" Return a random list of DNA nucleotides sequences.
Args:
sample_size: generate N random sequences.
seq_length: set sequence length.
seed: random seed for reproducibility.
Returns:
... | ce283d43495fa53be4276cf0ab3c6793e053a723 | 695,987 |
import difflib
def get_hunks(fromlines, tolines, context=None):
"""Generator yielding grouped opcodes describing differences .
See `get_filtered_hunks` for the parameter descriptions.
"""
matcher = difflib.SequenceMatcher(None, fromlines, tolines)
if context is None:
return (hunk for hunk... | b2a2c36be17a6f481564fa9edb6f480ef7e0361c | 695,988 |
def populate_game_starting_lineups(gl, games, player_id):
""" Populates all the starting lineups in a game by updating the "teams" dictionary in each Game
object, with key = team_id, value = [list of player_ids on that team]
Every "teams" dictionary has two keys because two teams play in a game
Each ke... | 9de9be892765581a4c74d060979d086a0bf6031c | 695,989 |
def clean_venue_name(venue_name: str) -> str:
"""Clean the venue name, by removing or replacing symbols that are not allowed in a file name.
Args:
venue_name: Original venue name.
Returns:
Cleaned venue name.
"""
return venue_name.replace("*", "").replace("/", "_").replace(" ", "_"... | 90b6f8b3787af17750c548bb816383bf8a5b07a4 | 695,990 |
import os
def test_fixtures_dir():
"""the test fixture directory"""
return os.path.join(os.path.dirname(__file__), "..", "fixtures") | 16d27847103775120a109b6038b71e42b284522e | 695,991 |
from typing import List
def merge(intervals: List[List[int]]) -> List[List[int]]:
"""
Sort the interval by their starting points. Compare the ending point of current interval with
next examining interval to determine if we can merge them
:param intervals: list of intervals
:return: merged interval... | e30c89ca7aef8a2050b7f3b91baf8f049bcc49c2 | 695,992 |
def get_model_args(parser, args=[]):
"""
parameters determing the network architecture
-> model_type: Which model should be applied?
-> load_model: Use pretrained model?
-> model_path: pretrained from which path?
"""
# Model:
# ------------------------------------------------------------... | 73d7cf35b37192abb87c4458f95ef9e874d83e9a | 695,994 |
def _extract_symbols(simple_elf, symbols, default=None):
"""Fill 'symbols' field with required flash algo symbols"""
to_ret = {}
for symbol in symbols:
if symbol not in simple_elf.symbols:
if default is not None:
to_ret[symbol] = default
continue
... | 43e8c1a51d68aecfdb4e259bedfa9d518a7f7a37 | 695,995 |
def get_border(char, length):
"""Get a border consisting of a character repeated multiple times.
:param char: The character to make up the border.
:param length: The length of the border.
:return: A string consisting of the character repeated for the given length.
"""
border = ''
for i in r... | 9cd73504dc450e1e31c75b398240a27184a130e4 | 695,996 |
import html
def unescape_html(cbot, statement):
"""
处理html中的空白
如: "<b>" becomes "<b>".
"""
statement.text = html.unescape(statement.text)
return statement | 3df2dd86d696356fa7ac349a8b1a7b50668fce3b | 695,997 |
from datetime import datetime
def extract_data(table):
"""
提取数据
:param table:
:return:
"""
rows = table.find_all("tr")
assert len(rows) == 5
dates = rows[0].find_all("td")
staff_counts = rows[1].find_all("td")
student_counts = rows[2].find_all("td")
other_counts = rows[3].... | 236e65cb79839bcab5b910c686637cfda9da4223 | 695,999 |
def orbit_transfers(orbits, obj_name_1, obj_name_2):
"""
>>> orbit_transfers([["COM", "B"], ["B", "C"], ["C", "D"], ["D", "E"], ["E", "F"], ["B", "G"], ["G", "H"], ["D", "I"], ["E", "J"], ["J", "K"], ["K", "L"], ["K", "YOU"], ["I", "SAN"]], "YOU", "SAN")
4
"""
orbit_dict = {orbits[i][1]: orbits[i][0... | 58be5a73493e75ff01f62aea4e30237463b2850e | 696,000 |
def is_pass(record):
"""Return whether a PyVCF record passes all filters.
From the VCF spec, that's if it's 'PASS' or '.'.
But PyVCF uses '[]' for 'PASS' (older versions used 'None').
PyVCF uses None for "." now, presumably to be pythonic (not [] is true; not None is true)
"""
filters = record.FILTER
ret... | 839c6989fa4dae677da0d60adac78861cf81d18b | 696,001 |
from typing import Iterable
def hash_from_dict(dictionary):
"""
Creates a hashable string from a dictionary
that maps values to their assignments.
Ex:
dictionary={"A": 1, "B": 5, "C": 1}
=> "A=1,B=5,C=1"
"""
hashstring = ""
for i, key in enumerate(sorted(list(dictionary.keys()))):
hashstring +... | 1e906f178a6353e9bdac7bed929be1e0f16ae060 | 696,002 |
def default_leader():
"""Default leader for multi-region instances."""
return "us-east4" | 999051105a4f93552d920734bef0cca4cc40ba03 | 696,003 |
def normalize_intensity(inten, max_num=None):
"""
The max_num here is the maximum number of intensity, and it will be 1 if is not defined
"""
if not max_num:
max_num = 1
if isinstance(inten, dict):
max_intensity = max(inten.values())
scale = max_num / max_intensity
fo... | fd258cfb19eb666afb7aceef594df857fb28f0ac | 696,005 |
def almost_equal_floats(value_1: float, value_2: float, *, delta: float = 1e-8) -> bool:
"""
Return True if two floats are almost equal
"""
return abs(value_1 - value_2) <= delta | ff1c29c57434a169824fe76e451053f3edc6e519 | 696,006 |
def stationObjectsByRiver(stations, rivers):
"""Returns a list of Monitoring Station objects which are on the rivers input"""
stationObjectsByRiverOutput = []
for river in rivers:
for station in stations:
if station.river==river:
stationObjectsByRiverOutput.append(station... | 882c42acf4ef1d9af2aec8a1c4090f8bca4322e7 | 696,007 |
from typing import Tuple
def _yymmdd2ymd(yymmdd: int) -> Tuple[int, int, int]:
"""yymmdd -> (year, month, day)
Examples:
>>> _yymmdd2ymd(321123)
(32, 11, 23)
>>> _yymmdd2ymd(320323)
(32, 3, 23)
"""
year, mmdd = divmod(yymmdd, 10000)
month, day = divmod(mmdd, 100)
... | 9e9d3fa20b4684b603a203c5cc8c8284a8f45dd7 | 696,008 |
def _flatten_result(result):
"""
Ensure we can serialize a celery result.
"""
if issubclass(type(result), Exception):
return result.message
else:
return result | 7fbd9507b8b91398a6a0f3a8e530074d92c0ed5a | 696,009 |
import subprocess
def run_bash(cmd):
"""Run a subprocess
Args:
cmd (str): command
Returns:
result (str): stdout + stderr
"""
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, executable='/bin/bash')
(stdout, stderr) = proc.communicate()... | 5fd6df3ebb003f0933d847f1dbf07e167e70d7a3 | 696,010 |
from datetime import datetime
def test_data():
"""Get a list of 8 records that follow the schema in test_table"""
now = datetime.now()
return [
{
"id": 1,
"id2": "a1",
"str_attr": "sadf",
"float_attr": 1.111_111_111_1,
"int_attr": 11,
... | ccc053a50c3b4b33dd6b846bbd804d2e73283fd6 | 696,011 |
def parse_param(param, forced_device=None):
"""
Extract account representation
string format is <account_name>@<domain_name>[@<device_name>]
If @<device_name> is absent, <domain_name> is a global domain name
Else <domain_name> is a local domain name of the forced_device
if 'forced_device' is ... | ac16ca7715d2596798576da23474f083a0ab9ee9 | 696,012 |
def sqliteRowToDict(sqliteRow):
"""
Unpacks a single sqlite row as returned by fetchone
into a simple dict.
:param sqliteRow: single row returned from fetchone DB call
:return: dictionary corresponding to this row
"""
return dict(zip(sqliteRow.keys(), sqliteRow)) | 979bb63142a797749937ee382d9b9eb1c26dd7bd | 696,013 |
import os
def get_image_path(raw_input_dir: str) -> list:
"""
get image path and id from root resource path.
:return: a list contains all images' path.
"""
result = []
for root, dirs, files in os.walk(raw_input_dir):
for file in files:
result.append(os.path.join(root, file))
return result | 879f49f931d73fad34a4ae28b9094f70427a0d46 | 696,014 |
def _get_average_score(concept, _keywords):
"""Get average score of words in `concept`.
Parameters
----------
concept : str
Input text.
_keywords : dict
Keywords as keys and its scores as values.
Returns
-------
float
Average score.
"""
word_list = conc... | ce930ae5871dfc218ae5f057f7dc76d64671a7f6 | 696,015 |
from typing import Counter
def print_machine_config(config):
"""Printable version of config"""
cpu_cores = config['cpu']['physical_cores']
cpu_freq = int(round(config['cpu']['max_freq_MHz'], 0))
ram = int(round(config['cpu']['total_mem_GB'], 0))
cpu_config_message = f'{cpu_freq} MHz CPU with {cpu_... | 406ff85abe548ea64d1de7f1a65af3c3c4ea4902 | 696,016 |
import sys
import pickle
import subprocess
import os
def outside(code_str, *import_modules):
"""Runs a code string in a separate process, pickles the result, and returns it"""
import_modules_str = 'import %s' % ', '.join(import_modules) if import_modules else ''
if sys.version_info.major < 3:
comm... | ad94b7694b5681fb16a5db589e54b933e280266e | 696,017 |
def issilk(data: bytes):
"""判断音频是否为silkv3格式"""
f = data[1:11] if data.startswith(b'\x02') else data[:9]
return f == b"#!SILK_V3" | 6a964960e820eab1689fc5c4a760025a987ad98a | 696,018 |
from datetime import datetime
def get_start_next_month(date):
"""
Parameters
----------
date: datetime.datetime
Returns
-------
datetime.datetime
date of the start of the next month
"""
if date.month+1 <= 12:
return datetime(date.year,date.month+1,1)
return d... | 737ace5854593007ff62d169c3b69f3118056be1 | 696,019 |
def computePoint(triangle):
"""
Computes the last point D in an ABC square triangle
where a and c are the diagonal - triangle = [a,b,c]
D--- C
| / |
| / |
|/ |
A----B
"""
# get coordinates of each point a, b, c
a, b, c = triangle
xa, ya = a
x... | e7b37852440eaf43844d5d6e1cd2c2921bc9e6b3 | 696,020 |
def _funcIsMethod(stackFromFunc):
""" Determine whether a function being decorated is actually a method of a
class, given the stack frames above the decorator invocation. """
funcFrame = stackFromFunc[0]
potentialClassName = funcFrame[3]
nextFrame = stackFromFunc[1]
return nextFrame[3] == '<mod... | ecb80a8a7565b33aeae72672665c1e21a76cf2c7 | 696,021 |
def decrypt(key, enc):
"""Simple decryption. Reverse of the encryption function
Please note that this is quite weak security, and completely breakable
with little or no effort. If you take issue with this method, don't
hesitate to offer your own implementation. I know very little about
security and... | c277ccc6741bc3c471351429fd6f6a433a28ef40 | 696,022 |
def get_position_patterns(contours, hierarchy):
"""
get qr code position pattern
:param contours:
:param hierarchy:
:return: found position pattern index
"""
found = []
for i in range(len(contours)):
k = i
c = 0
while hierarchy[k][2] != -1:
k = hierarc... | c560b60838823b14ac58f3ef1a0829afabe7a588 | 696,023 |
def filter_data(imgs, dt, inds):
"""
Picks out ind rows from various fields in dt.
:params imgs: list of cv2 images (numpy arrays)
:params dt: dictionary with data captured during calibration
:params ind: numpy array of indices to sample from imgs and dt
:type imgs: list of cv2 images (numy arra... | a5ece4f9f415c6a72f1d3d5597199dfcf7df5c2d | 696,024 |
def get_metric_scores(ground_truth, simulation, measurement, metric, measurement_kwargs={}, metric_kwargs={}):
"""
Function to combine measurement and metric computations
:param ground_truth: pandas dataframe of ground truth
:param simulation: pandas dataframe of simulation
:param measurement: meas... | 4087e60ce0578d11756f449e776e01ee81b6e4ac | 696,025 |
def solution(x: int, y: int, d: int) -> int:
"""
>>> solution(1, 1, 1)
0
>>> solution(10, 85, 30)
3
>>> solution(10, 95, 30)
3
>>> solution(10, 105, 30)
4
>>> solution(1, 1000000000, 1)
999999999
>>> solution(1, 1000000000, 2)
500000000
>>> solution(1, 1000000000,... | b1b3651bf47ec476df71908ef6119f8143512b87 | 696,026 |
import os
def descfile(font):
"""Get the path of the DESCRIPTION file of a given font project."""
if font:
directory = os.path.dirname(font)
descfilepath = os.path.join(directory, "DESCRIPTION.en_us.html")
if os.path.exists(descfilepath):
return descfilepath | daaf649979305680fb4ff614cf4a2682ab7ff533 | 696,028 |
import os
def get_layers(loc):
""" explore a repository and get image file names containing layers
:param loc: path to the repository contening files (str)
:return: list of image file names to transform (without path)
"""
# migh tbe useful to add a test on whether or not the file is compatible wi... | 9604e61ebd3d3450c64d454e2b39af1e45eb631c | 696,029 |
def parse_results(results, skip = 16):
""" convert the print outs of a run to a csv file """
# analyze the results
domain = []
variant = None
total = []
halo = []
pack = []
wait = []
put = []
rows = []
counter = 0
with open(results, "r") as file:
lines = file.read... | cde628726ce436f2198058252db4828754295f14 | 696,030 |
def keywords2tag(tag) :
"""
remove the last number in tag
e.g. "span1" to "span"
"""
i = 0
for x in tag[::-1] : # reversed checking
if x.isdigit():
i += 1
if i > 0 :
return tag[:-i]
else :
return tag | 2e31e195c0fb7ceedc71418cd0382bbee95f52b8 | 696,032 |
def install_plugins_models(installed_app, config):
""" Add to INSTALLED_APPS the plugin """
for plugin in config.Plugins:
installed_app += 'yablog.plugins.%s' % plugin, # do not erase the comma
return installed_app | e8b7b1a4995004fbdebeda75447596fb70e9d6c6 | 696,033 |
import json
def util_json_get_value ( s_json, key ):
"""Returns value for supplied key in JSON document"""
try:
t = json.loads(s_json, strict=False)
except ValueError:
return ''
try:
value = t[key]
except KeyError:
return ''
return value | 773ae165ac58f4ac20772d5c344aca241c74786c | 696,034 |
import torch
def classification_margin(output, true_label):
"""Calculate classification margin for outputs.
`probs_true_label - probs_best_second_class`
Parameters
----------
output: torch.Tensor
output vector (1 dimension)
true_label: int
true label for this node
Returns... | db9e557d1ed52249554ff1beb96725616d2fa426 | 696,035 |
def format_builtin():
"""format: Formated representation of an object."""
return "{} ready".format(format(1, '.0%')) | 6b39ec8e61908f3bcfba8bb34c18d2312b6e830e | 696,036 |
import hashlib
import json
def treehash(var):
"""
Returns the hash of any dict or list, by using a string conversion
via the json library.
"""
return hashlib.sha256(json.dumps(var, sort_keys=True).encode("utf-8")).hexdigest() | e196a8d601b59a893bf05bc903aa7e3af4927cef | 696,038 |
def format_kv(batched):
"""Format raw data into key-value format"""
aggregated_kv = []
for event in batched:
kv_str = ""
for key, value in event.items():
kv_str += "%s=\"%s\" " % (key, value)
kv_str += "\n"
aggregated_kv.append(kv_str)
return aggregated_kv | 39df6dc9fe5ebc8efafec0460a98d0c3457f6334 | 696,040 |
def is_float(dtype):
"""Return True if datatype dtype is a float kind"""
return ('float' in dtype.name) or dtype.name in ['single', 'double'] | 3c6301e6d89fb8d825ac4181ca02b5cf95028066 | 696,041 |
def _find_method(obj, string):
"""Find methods in object that starts with `string`.
"""
out = []
for key in dir(obj):
if key.startswith(string):
out.append(getattr(obj, key))
return out | 1250a6dc39d2ac47ca4a5e561f55f4fb2b456c96 | 696,042 |
def index_value_append(spl, sp_num, sample_vec, l1=0, l2=0):
"""
This function generates two lists: Indices and Values.
Indices is used to record sampling position.
Values is used to record sampling value from sample vector.
Parameters
----------
spl:
Sample list includes three rows a, ... | fec835a4e933a3e6f75d6afa0ac7b693304ba37f | 696,044 |
def offset_to_matlab(offset):
"""
Change offset to MATLAB
---------------------
:param offset: base offet
:return: MATLAB offset
"""
new = offset
new[1] = offset[0]
new[0] = offset[1]
return new | a7abede8dd9795aa26da88cb2bdd3ab199b8cf00 | 696,045 |
def split_list(ls, size):
"""
Split list
:param list ls: list
:param int size: size
:return list: result
>>> split_list([1, 2, 3, 4], 3)
[[1, 2, 3], [4]]
"""
if size == 0:
return ls
return [ls[i:i + size] for i in range(0, len(ls), size)] | de28981d576122f99be34a57c94d73457b63c04b | 696,046 |
def getColumnsEndingAt(columns, zLevel):
"""Returns columns w/ endPoint at zLevel"""
columnGroup = {}
for columnID, column in columns.inventory.iteritems():
diff = abs(zLevel - column.endJoint.z)
if diff <= 0.001:
columnGroup[column.uniqueName] = column
return columnGroup | 4f6b7aac922bd5985b6faeb509d26bf6aec98629 | 696,047 |
def available_phrases(fs, phrases):
"""
return:
set of phrase indexed tuple like
{((1, "I"), (2, "am")),
((1, "I"),)
...}
"""
available = set()
for i, f in enumerate(fs):
f_rest = ()
for fr in fs[i:]:
f_rest += (fr,)
... | fee8e4f355786946532e64cc51d8cd1d4d15f12a | 696,048 |
import inspect
import os
def is_blazing_query():
"""
Method that returns true if caller of the utility is a blazing query, returns false otherwise
Assumes that caller is 3 levels above the stack
query_of_interest -> utils.push_to_google_sheet -> utils.build_payload -> utils.is_blazing_query
Anoth... | 1f5cc26e059d0d4c7b6ed5917d7d9d19aefb027b | 696,049 |
def hpo_job_describe(sm_client, tuning_job_name):
"""API call to describe a hyperparameter tuning job."""
try:
response = sm_client.describe_hyper_parameter_tuning_job(
HyperParameterTuningJobName=tuning_job_name
)
return response
except sm_client.exceptions.ResourceNotFound:
raise Exception... | 98bb1ad03883e862a8730ec4740c3bb92b1a4830 | 696,050 |
import traceback
def tb_log_str(exception) -> str:
"""
Format an exception as a full traceback.
"""
return "".join(traceback.format_exception(None, exception, exception.__traceback__)) | 6776a7416cb512bf23e6557833e3a95779172bd4 | 696,051 |
def addB(n1, n2):
"""adds 2 binary numbers without converting to decimal or using ints"""
if n1 == "":
return n2
elif n2 == "":
return n1
elif n1[-1] == "0" and n2[-1] == "0":
return addB(n1[:-1], n2[:-1]) + '0'
elif (n1[-1] == "0" and n2[-1] == "1") or (n1[-1] == "1" and n2[... | 0c43ece2c83063401ad78182134570a67b1bd657 | 696,052 |
import requests
def get_agol_token(username, password):
"""
purpose:
get a security token from ArcGIS Online
arguments:
username: string
password: string
return value: string
token, None if error
"""
try:
url = "https://www.arcgis.com/sharing/rest/gener... | 9086fbb7e199c7dd9410bfe4f89b65d34a2424be | 696,055 |
from datetime import datetime
def check_date(date):
"""
Функция проверки правильности ввода даты
:param date:
:return: date
"""
# проверка формата даты
get_date = lambda d: datetime.strptime(d, '%Y.%m.%d').date() <= datetime.today().date()
ex = False
while ex != True:
try:
... | fd651552148fa57c42c340ffe796689de5131496 | 696,056 |
def smallerNumbersThanCurrent(nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
res = []
c = 0
for i in range(len(nums)):
count = 0
for e in nums:
if e < nums[c]:
count += 1
res.append(count)
c += 1
return res | 880ccbb19767c4643075d9a7947a2eb369063e2b | 696,057 |
def no_annotation(num: int):
"""
This function contains no return annotation
>>> no_annotation(5)
10
"""
return num + 5 | e0bdfde9a58d96140978a45d627857f7f51a5667 | 696,058 |
def read_grammar(grammar_file):
"""
Reads in the given grammar file and splits it into separate lists for each rule.
:param grammar_file: the grammar file to read in.
:return: the list of rules.
"""
with open(grammar_file) as cfg:
lines = cfg.readlines()
return [x.replace("->", "").s... | c9320a4126ed6bc05a5df8b05c9997890c7f620a | 696,059 |
from pathlib import Path
def list_files(dirpath: str, pattern: str = "*.csv") -> list:
"""
List files in a directory
"""
file_names = list(Path(dirpath).glob(pattern))
return file_names | 0c291d6818c38f6f9219f92b900e5fd8ed5960d6 | 696,060 |
def getNetworkParameters(channels:int, layers:int):
"""
Returns the command line arguments for that specific network
:param channels:
:param layers:
:return:
"""
# -1 because last layer is implicit
# The parameter lists the feature size of the hidden features
return ["--layers", ':'... | b06fca71d4daee46a864d9a235361498de4d0442 | 696,061 |
def _plot(ax, coords, pos_columns, **plot_style):
""" This function wraps Axes.plot to make its call signature the same for
2D and 3D plotting. The y axis is inverted for 2D plots, but not for 3D
plots.
Parameters
----------
ax : Axes object
The axes object on which the plot will be cal... | 80cadfff00f864b9d38e51768e68674dfc981a06 | 696,062 |
def inverse_names(iformat):
""" Inverses an input format name to
generate the config used
"""
iformat_split = iformat.split("_")
if "depth" != iformat_split[0]:
return None
# Remove _<number>
iformat = iformat if len(iformat_split) < 3 else "_".join(iformat_split[:-1])
# Remo... | 655a565a07f0510851fc46544c6fcbf901736308 | 696,063 |
def get_i_colour(axis_handle) -> int:
""" Get index appropriate to colour value to plot on a figure (will be 0 if brand new figure) """
if axis_handle is None:
return 0
else:
if len(axis_handle.lines) == 0:
return 0
else:
return len(axis_handle.lines)-1 | b5001da3325168e0f359596bfe65487708f59e3b | 696,064 |
def read_all(port, chunk_size=200):
"""Read all characters on the serial port and return them."""
if not port.timeout:
raise TypeError('Port needs to have a timeout set!')
read_buffer = b''
while True:
# Read in chunks. Each chunk will wait as long as specified by
# timeout. In... | cf894c2449fa4eba763dc7bf4da86b0072a78a19 | 696,065 |
import base64
import pickle
def encode_store_data(store_data):
"""
Encode store_data dict into a JSON serializable dict
This is currently done by pickling store_data and converting to a base64 encoded
string. If HoloViews supports JSON serialization in the future, this method could
be updated to ... | 0a576a8146c0657610b508ebc6338d3ed6790b70 | 696,066 |
from typing import List
import os
def listImages(dir: str) -> List[str]:
"""
List all images (where zoom accepts: jpeg jpg png) in a directory.
"""
return [f for f in os.listdir(dir)
if os.path.isfile(os.path.join(dir, f))
and f.endswith((".png", ".jpeg", ".jpg"))] | 653ce307f9e2ebfd46dad9381ae2dedfdbc183dc | 696,067 |
def dependabot_prs(repo):
"""Returns all repository PRs created by Dependabot."""
prs = repo.get_pulls(state="open")
return [u for u in prs if "dependabot" in u.user.login] | 3963c6e39f99257c0e259abc7fe6f6fdffd00404 | 696,068 |
import warnings
def count_free_closing_brackets(input_string, start_index=0):
"""
DEPRECATED - No more needed since eggPlant 20.1.0 as it uses new list format
and quotes string value in returned lists.
The function has been used to handle lists returned by eggplant which contain unpaired closing brack... | 826ed3233a68e3fdc279d1d72305fff9768d737c | 696,069 |
def find_feature_by_gi(gid, record, ftype):
""" Loops over the ftype features in the passed SeqRecord, checking
db_xref qualifiers for a match to the passed gid.
Returns the first feature identified, or None if no feature found.
"""
for feature in [f for f in record.features if f.type == fty... | 050c5464a8d425f5db53440abd79c64b2938f81b | 696,070 |
from datetime import datetime
def format_date(date_str):
""" format experience summary api date to mm/dd/yyyy"""
no_time = date_str[:10]
formatted = datetime.strptime(no_time, '%Y-%m-%d')
return formatted.strftime("%m/%d/%Y") | 2e6f0739fe269ff828bc19c0754909062d160254 | 696,071 |
def loglik_nats(model, x):
"""Compute the log-likelihood in nats."""
return - model.log_prob(x).mean() | f929be38cb70fe56b6bb1a0e5cc21cf02fead3b6 | 696,072 |
def _none_not_equal_scalar(x, y):
"""
Determine if number not_equals none.
Args:
x: None.
y: Number.
Returns:
bool, return True.
"""
return True | 9e29c770f0f3003a61199b4e340a2341c9df0e9f | 696,073 |
def _get_item(node):
"""
Returns the item element of the specified node if [the node] is not null.
:param node: The node to extract the item from.
:return: A node's item.
"""
return node.item if node is not None else None | 42dff5ef2e98a0dd78b822ee29a75c72d737e23f | 696,075 |
def countWords(speech):
"""Create a dictionary and count the occurrences of each word.
If a word already exists in the dictionary, add 1 to its counter
otherwise set a counter for to to an initial value of 1"""
counts = {}
for word in speech:
if word in counts:
counts[word] += 1
... | 630685207d57098c18f1084e60a8f1dd21c92638 | 696,076 |
def change_action_status(action_type, new_status):
"""
This function changes the status of an action type.
"""
# replace the last bit of a dot separate string with the new_status
return "%s.%s" % ('.'.join(action_type.split('.')[:-1]) , new_status) | 1032486b1f5b32a36806d397a68f42f549b6228c | 696,077 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.