content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import logging
def norm_range(voltage):
"""Check to see if the voltage values are within the acceptable normal range
The normal range for the voltage readings is +/- 300 mV. Within the
assignment, it was asked that if a voltage reading were found to be outside
of this range, then add a warning entry ... | 65a891c17421899612928cb8ec6c5f4f32db4f6b | 678,229 |
def is_test_directory_name(directory_name):
"""
Returns whether the given directory name is a name of a test directory.
Parameters
----------
directory_name : `str`
A directory's name.
Returns
-------
is_test_directory_name : `bool`
"""
if directory_name == 'tes... | f3de8256181176df743de2d04fb4987b8b4dc07d | 678,230 |
import re
def restore_windows_1252_characters(s):
"""Replace C1 control characters in the Unicode string s by the
characters at the corresponding code points in Windows-1252,
where possible.
"""
def to_windows_1252(match):
try:
return bytes([ord(match.group(0))]).decode('windo... | 37f16e7feee452fd26a169971de0f4cce4ed1c6a | 678,231 |
def waterGmKgDryToPpmvDry(q):
"""
Convert water vapor Grams H2o / Kg dry air to ppmv dry air.
"""
Mair = 28.9648
Mh2o = 18.01528
return (q*1e3*Mair)/Mh2o | eb5b11b02133295eef691e9c0c91fe13332e6df9 | 678,232 |
def read_file(path):
"""
Read file at `path`.
Return a list of lines
"""
lines = []
with open(path, 'r') as srcfile:
return srcfile.read().split('\n') | 4c011a3e2a45d8d46ac3592a4f72a82ee03075ec | 678,233 |
def _make_args(cmd, opts, os_opts, separator='-', flags=None, cmd_args=None):
"""
Construct command line arguments for given options.
"""
args = [""]
flags = flags or []
for k, v in opts.items():
arg = "--" + k.replace("_", "-")
args = args + [arg, v]
for k, v in os_opts.item... | fb1f0f5ad4b5c8292ac04b9b6ee936d6db4f5773 | 678,234 |
def s2i(s):
""" Convert a string to an integer even if it has + and , in it. """
# Turns out sometimes there can be text in the string, for example "pending",
# and that made this function crash.
if type(s)==type(0):
# Input is already a number
return s
try:
# Sometimes inpu... | b49ee7a37c9d98415693321dd5a3e94a816f2d48 | 678,236 |
def tf_shape_to_list(shape):
"""Get shape from tensorflow attr 'shape'."""
dims = None
try:
if not shape.unknown_rank:
dims = [int(d.size) for d in shape.dim]
except: # pylint: disable=bare-except
pass
return dims | f3df18ff4808bebb512fde3a552d650578f75270 | 678,237 |
def _get_fields(attrs, field_class, pop=False):
"""
Get fields from a class.
:param attrs: Mapping of class attributes
:param type field_class: Base field class
:param bool pop: Remove matching fields
"""
fields = [
(field_name, field_value)
for field_name, field_value in at... | 65219d144954232161345b26bf085b2e4f2f2dce | 678,238 |
from typing import List
def recall_score(relevant: List, recovered: List) -> float:
"""Recall score is: which of the total relevant documents where recovered"""
# Recovered relevant
rr = [d for d in recovered if d in relevant]
return len(rr) / len(relevant) | 8db00c547e7a4d1c8b4e43f663a7a37f11850e35 | 678,239 |
from typing import Dict
from typing import List
def get_retrohunt_rules(r: Dict) -> List[str]:
"""Extracts rules used within a retrohunt."""
rules = []
for line in r.get("attributes", {}).get("rules", "").splitlines():
line = line.strip()
if "rule" in line[:4]:
line = line.spli... | 78f122542d3a925efb018cb2787a7000d3914c81 | 678,240 |
import string
def normalformstr(s,
remove_digits=True,
remove_punctuation=True,
remove_blanks=True,
remove_special=True,
remove_short=True
):
"""
strip and lower case string
optional: remove blanks... | b4de6ac43f14522873fc6391dd12be192b4a3d2b | 678,241 |
from typing import List
def calc_mean_pt_of_3d_neuron(neuron_mean_pts: List[List]) -> List[float]:
"""
:param neuron_mean_pts: a neuron with bboxes after mean operation
:return: [x, y, z]
"""
mean_x = sum([b[0] for b in neuron_mean_pts]) / len(neuron_mean_pts)
mean_y = sum([b[1] for b in neu... | 548e34cd06f74048fcd1ec0a3b71f40ca39ce796 | 678,242 |
def _genotype_in_background(rec, base_name, back_samples):
"""Check if the genotype in the record of interest is present in the background records.
"""
def passes(rec):
return not rec.FILTER or len(rec.FILTER) == 0
return (passes(rec) and
any(rec.genotype(base_name).gt_alleles == rec... | 275bca0c17bdcc3397bcefd0d0b46ec05ca476db | 678,243 |
import click
def require_region(ctx, param, value):
"""
Require region to be set in parameter or in context
:param ctx: Context
:param param: Click Parameter
:param value: Parameter value
:return: Parameter value
"""
if not value and not ctx.obj.config.region:
raise click.BadPa... | 4c48ba51a3a683d831b3d4425566967e9e828253 | 678,245 |
def torr_to_pascal(torr):
"""Convert Torr to Pascal."""
return torr * 101325.0 / 760.0 | 8050507ee06f5703af15385506b7cc6285053ac9 | 678,246 |
def get_item(d, k):
"""attempts to get an item from d
at key k. if d is a list and the key is the list selector [],
then tries to return the first item from the list.
if the list is empty, returns None."""
try:
return d[k]
except KeyError:
if k.endswith('[]'):
lst = d... | e301c56a3e4cc8526a0f526b79f7b53c8749b34c | 678,247 |
import random
def return_random_from_word(word):
"""
This function receives a TextMobject,
obtains its length:
len(TextMobject("Some text"))
and returns a random list, example:
INPUT: word = TextMobjecT("Hello")
length = len(word) # 4
rango = list(range(length)) # [0,1,2,3]
... | 34e0ddd5978fa5a0f35d333856f4b89cdee4e118 | 678,249 |
def transition_model(corpus, page, damping_factor):
"""
Return a probability distribution over which page to visit next,
given a current page.
With probability `damping_factor`, choose a link at random
linked to by `page`. With probability `1 - damping_factor`, choose
a link at random chosen fr... | 1d43b53b60ed5c9f99bf05eafad8ca8b8e96aaea | 678,250 |
def initialize_lr_scheduler(lr=0.001, epochs=250, epoch_decay_start=80):
"""Scheduler to adjust learning rate and betas for Adam Optimizer"""
mom1 = 0.9
mom2 = 0.1
alpha_plan = [lr] * epochs
beta1_plan = [mom1] * epochs
for i in range(epoch_decay_start, epochs):
alpha_plan[i] = float(epo... | a30ff818033f8a248b3f17cb98c6809f119d1a53 | 678,251 |
def is_link_field(field):
"""Return boolean whether field should be considered a link."""
return "." in field | ad68eb6ae3b795fea64575272fde7df6be501007 | 678,252 |
def anagram_solution2(s1, s2):
"""
@rtype : bool
@param s1: str1
@param s2: str2
@return: True or False
"""
anagram_list1 = list(s1)
anagram_list2 = list(s2)
anagram_list1.sort()
anagram_list2.sort()
pos = 0
matches = True
while pos < len(s1) and matches:
... | 7eb0aced0c281758df909ab4fa44029763491379 | 678,253 |
def convert2relative(image, bbox):
"""
YOLO format use relative coordinates for annotation
"""
x, y, w, h = bbox
height, width, _ = image.shape
return x/width, y/height, w/width, h/height | a614ebdd53bf36bb2049b948d984956c0f0063ba | 678,254 |
def minForestSizeTLCovers(tlcovs):
"""
Prune top-level covers for minimum forest size
Inputs:
tlcovs: A list of top-level covers as returned by explain.
Outputs:
tlcovs_fs_min: The pruned top level covers.
fs_min: The minimum forest size found.
"""
fs_min = min(sum(ts) fo... | 059f200a22ca2c6cfa40e5562f7a9beb12222a8f | 678,255 |
import os
def extractRootName(filename):
"""Extract the root name from the filename (path)."""
return os.path.splitext(os.path.split(filename)[1])[0] | e3467f0dab4b28d35e52381960e228563f99a36e | 678,256 |
def get_all(model, scenario):
"""
:param model: a database model with fields scenario and name which are unique together
:return: a dictionary of the fields of the given model corresponding to the current simulation,
with their name fields as key.
"""
records = model.objects.filter(scenario=sce... | ac53802ce77dabe070f18c6c4aaac8fdf213d950 | 678,257 |
import re
def extract_tags(item):
"""Extracts the hashtags from the caption text."""
caption_text = ''
if 'caption' in item and item['caption']:
if isinstance(item['caption'], dict):
caption_text = item['caption']['text']
else:
caption_text = item['caption']
el... | 0b9045427b9a72d35e105ec827f41c7bb3488a37 | 678,258 |
def convert_from_bytes_if_necessary(prefix, suffix):
"""
Depending on how we extract data from pysam we may end up with either
a string or a byte array of nucleotides. For consistency and simplicity,
we want to only use strings in the rest of our code.
"""
if isinstance(prefix, bytes):
p... | 6466bf121c93b2428646b4b7c45542aa94fce4f7 | 678,259 |
def get_display_settings_for_lid(local_identifier, label):
""" Search a PDS4 label for Display_Settings of a data structure with local_identifier.
Parameters
----------
local_identifier : str or unicode
The local identifier of the data structure to which the display settings belong.
label :... | 4349d97cf600f24d274d02121b72e3461422b96a | 678,260 |
from typing import List
import re
def find_assets(html: str) -> List[str]:
"""
Return a list of assets found in the given HTML string
"""
return re.findall(
r'"([^"]+\.(?:css|js|jpg|jpeg|gif|tiff|png|bmp|svg|ico|pdf))"',
html, flags=re.IGNORECASE) | 511fb8cadc6acbbeb5d86f2568a0a5a31f76dd7d | 678,262 |
from typing import Any
import json
def read_json(path: str) -> Any:
"""
The `read_json()` function takes one parameter, which is a file-like object
(`String`, `File`) and returns a data type which matches the data
structure in the JSON file. See
https://github.com/openwdl/wdl/blob/main/versions/... | dcb9e94722ce4936f136ebb0d7c6c4082a519549 | 678,263 |
import requests
def get(url):
"""
Get the http response.
"""
return requests.get(url).json() | 9053f5c3b7ddb863bac503e061546ab09627fbb8 | 678,264 |
def zip(lst1, lst2):
"""
>>> zip([1, 2, 3], ["a", "b", "c"])
[(1, 'a'), (2, 'b'), (3, 'c')]
"""
return [(lst1[i], lst2[i]) for i in range(min(len(lst1), len(lst2)))] | fa022c1fa3e4e511e5bd10dc61801cb35a829d95 | 678,265 |
def get_float_format(number, places=2):
"""
Return number with specific float formatting
"""
format_string = '{:.' + str(places) + 'f}'
return format_string.format(number) if number % 100 else str(number) | b21d3b3ec20d7440ed220eea2d25e79e08ceb635 | 678,266 |
def scheme_ij(u, u_n, u_nm1, k_1, k_2, k_3, k_4,
f, dt2, Cx2, Cy2, x, y, t_1,
i, j, im1, ip1, jm1, jp1):
"""
Right-hand side of finite difference at point [i,j].
im1, ip1 denote i-1, i+1, resp. Similar for jm1, jp1.
t_1 corresponds to u_n (previous time level relative to u).
... | ce612b7b18ccc2b8a601861ea1c5f35d2a35cc38 | 678,267 |
import csv
import itertools
def gen_csv(f):
"""peek at rows from a csv and start yielding when we get past the comments
to a row that starts with an int"""
def startswith_int(row):
try:
int(row[0][0])
return True
except (ValueError, IndexError):
return F... | 83798fbe9e79382f7711a968f5e3a1c519efd7cb | 678,268 |
import math
def haversine(row):
"""
Non-vectorized harversine
"""
a_lat, a_lng, b_lat, b_lng = row
R = 6371 # earth radius in km
a_lat = math.radians(a_lat)
a_lng = math.radians(a_lng)
b_lat = math.radians(b_lat)
b_lng = math.radians(b_lng)
d_lat = b_lat - a_lat
d_lng = ... | d0a200796e6056d83eab444e79aa61f05ce96d51 | 678,269 |
def countissue(s):
"""Count number of issues"""
if s:#check if Nonetype.
if s=='None':
#if type(s)==str or type(s)==float:#Handle
return 0
else:
return len(s)
else:#if empty
return 0 | e1960898476b7a20377293d413b10c9f0ab9b1bb | 678,270 |
def getTransitionWithSymbol( dfa, symbol, source ):
"""
Find a transition, if one exists, that involves the named
symbol and source
"""
for event in dfa.events.keys():
for transition in event.transitions.values():
if event == symbol and transition.source == source:
... | 4ddbd2d165951153c25ae7a1d909972390a26749 | 678,271 |
def to_float(value):
"""
Noneを0.0に置き換えfloat化する。
引数:
value 対象値
戻り値:
置き換え済みfloat値
"""
if value is None:
return 0.0
else:
return float(value) | 3b047a1e09ded7b99955c99ab9db02063cd6f7f0 | 678,272 |
from enum import Enum
def AgeEnum(ctx):
"""Age Enumeration."""
return Enum(
ctx,
what=-2,
unset=-1,
dark=0,
feudal=1,
castle=2,
imperial=3,
postimperial=4,
dmpostimperial=6,
default='unknown'
) | 264f8aeafb300aa73821fecd7391c7f17e80e68e | 678,273 |
def int_points(path):
"""Returns interior points in a path
Interior points are all the points that appear explicitely in the path
(we do not recurse into aggregated segments), except the source and the
destination.
"""
return [dest for src, dest, _ in path[:-1]] | ca2b20255eb64acef7f33a904c280f4ff6e87fea | 678,274 |
def generate_patterns(haystack):
""" Generate tuples of integer patterns from ASCII uppercase strings """
total = 0
stack = [0] * 128
pattern = []
for char in haystack:
byte = ord(char)
needle = stack[byte]
if needle == 0:
total += 1
stack[byte] = tot... | 68ae8ee3870c1b0d88f6607fd4a11b1664d91975 | 678,275 |
def get_field_data_type(field):
"""Returns the description for a given field type, if it exists,
Fields' descriptions can contain format strings, which will be interpolated
against the values of field.__dict__ before being output."""
return field.description % field.__dict__ | bc9fa0941441b2e47d7502106e3475b8e8712956 | 678,278 |
def fibo_even_sum(limit: int) -> int:
"""Compute the sum of the even fibonacci numbers that are <= limit
using a while loop with accumulator and trial division.
:param limit: Max value of the fibonacci range to sum.
:return: Sum of the even fibonacci numbers that are <= limit.
"""
even_sum = 0
... | 356ce6ffd6b586e81a8db4844517f0601a385888 | 678,279 |
import re
def _convert_camelcase(name, seperator=' '):
"""ExtraCondensed -> Extra Condensed"""
return re.sub('(?!^)([A-Z]|[0-9]+)', r'%s\1' % seperator, name) | 0933fb0de25bc3f0fe2b4653123b2b50f04ab1b1 | 678,280 |
def spaceship(a,b):
"""3-way comparison like the <=> operator in perl"""
return (a > b) - (a < b) | f2e33d9ebbbf9cd4e1636fa4e3d62398218425e4 | 678,281 |
def _repo_fixture(request) -> str:
"""Create a repository name from the test function name."""
return request.node.nodeid.replace("/", "-").replace(":", "-").replace(".py", "") | eb3fec394bf84e970770ca2022f2b79e05279c7c | 678,282 |
def outputids2words(id_list, vocab, article_oovs):
""" Maps output ids to words,
including mapping in-article OOVs from their temporary ids to the original OOV string
(applicable in pointer-generator mode).
Args:
id_list: list of ids (integers)
vocab: Vocabulary object
... | 6a06d118db7b9462284ea11c4c59445768b919c7 | 678,283 |
import string
def lowercase(s):
"""Return string s converted all to lowercase.
>>> lowercase("Hello")
'hello'
"""
ls = ""
for c in s:
if c in string.ascii_uppercase:
ls = ls + string.ascii_lowercase[string.ascii_uppercase.index(c)]
else:
ls = ls + c
... | d0b2534a2cc59125092a948f618ddceb8d3cc52a | 678,284 |
def convert_scan_dict_to_string(scan_dict):
"""
converts parsed ImageScanStatus dictionary to string.
:param scan_dict: {'HIGH': 64, 'MEDIUM': 269, 'INFORMATIONAL': 157, 'LOW': 127, 'CRITICAL': 17, 'UNDEFINED': 6}
:return: HIGH 64, MEDIUM 269, INFORMATIONAL 157, LOW 127, CRITICAL 17, UNDEFINED 6
""... | 011a040261e61d7f9b926554ecd6149f50aaa8c1 | 678,285 |
import time
def timestamp_to_datetime_str(ts, time_format=None):
"""
时间戳转化为日期字符串(1476547200->'2016-10-16')
:param ts: 时间戳
:param time_format: '日期格式'
:return: 日期字符串
"""
if time_format is None or time_format == '':
time_format = '%Y-%m-%d'
ts = time.localtime(float(ts))
retur... | 9140304ea9c4485e4da4a7d9f806ad01b360160f | 678,287 |
import math
def entropy(data):
"""
Calculate entropy, used by entropy_graph()
"""
h = 0
bins = [0 for x in range(0, 256)]
length = len(data)
for v in data:
bins[ord(v)] += 1
for x in range(0, 256):
p_x = float(bins[x]) / length
if p_x > 0:
h += - p... | 286326d9c583c644b8043249f09e294537493a5e | 678,288 |
def bkjd_to_jd(bkjd, offset):
"""Barycentric Kepler Julian Date (BKJD) to Julian Date (JD).
Kepler Barycentric Julian Day is the value recorded in the 'TIME' column
in the official Kepler/K2 lightcurve and target pixel files.
It is a Julian day minus 2454833.0 (UTC=January 1, 2009 12:00:00)
and cor... | 829f790fb13268c0638ffcdb0d4a3785ba46da67 | 678,289 |
import logging
def insert_db(database, data):
"""This function insert rows in the database
mongodatabase
:returns: inserts rows in the database
:rtype: rows in database
"""
logging.info("%s this is the data add in database", data)
return database.insert(data) | e55dba91e6e9c9aa8cf328882c8c55dae109eb4f | 678,292 |
def increment_count(val):
""" Increments the value by 1. """
return val + 1 | 107dc447d5e749daae5b1d0f578a213088d5ba84 | 678,294 |
def _mutable_union(s0, s1):
"""Modify set `s0` adding elements from `s1` to it.
Args:
s0: One set.
s1: Another set.
Result:
set, union of the two sets.
"""
s0._set_items.update(s1._set_items)
return s0 | ec103133397ae7425badf7561fd2dd75034245a0 | 678,295 |
import time
def timeit(func, iter = 1000, *args, **kwargs):
"""timeit(func, iter = 1000 *args, **kwargs) -> elapsed time
calls func iter times with args and kwargs, returns time elapsed
"""
r = range(iter)
t = time.time()
for i in r:
func(*args, **kwargs)
return time.time() -... | 39ba84bed0d20ee30782eab5bc7574253e038860 | 678,296 |
def _decide_field_order(field_rules, possible_fields):
"""For each field_idx with a single rule, take note, and remove rule from all others
Repeat until all field_idx assigned"""
decided_fields = {}
while len(decided_fields) < len(field_rules):
removable = set()
for idx, options in possi... | 7e7123ec1dc6fa93f39294ef40fb71676d22bbe2 | 678,297 |
import hashlib
def md5sum(infile):
"""Calculate the md5sum of a file
"""
# Implementation taken from: http://stackoverflow.com/a/4213255
md5 = hashlib.md5()
with open(infile,'rb') as f:
for chunk in iter(lambda: f.read(128*md5.block_size), b''):
md5.update(chunk)
return md5... | 475ad58c71d361a6dfec9127dbbddc53fb60cd21 | 678,298 |
import json
import collections
def extract_from_json(path, key, values, proc=(lambda x: x)):
"""Extracts and parses data from json files and returns a dictionary.
Args:
path: string, path to input data.
key: string, name of key column.
values: string, name of column containing values to extract.
... | 93068d5e27a439a0b1d908d5b8f5362c06a21859 | 678,299 |
def get_areas(objects):
"""
Get rounded area sizes (in m^2) of the geometries in given objects.
The results are rounded to two digits (dm^2 if the unit is metre)
and converted to string to allow easy comparison with equals.
"""
return {str(obj): '{:.2f}'.format(obj.geom.area) for obj in objects... | 4e5428ad6d53568edd154ccc1427d96dc1210351 | 678,300 |
def vec_to_str(vec):
"""
Convert a vec (of supposedly integers) into a str
"""
return ''.join(map(str, map(int, vec))) | 1093cbd9c944f45464f7f2b52ef01de39bea8932 | 678,301 |
def url_cutter(url):
"""
Cuts down the given url to a more suitable length.
Parameters
----------
url : `str`
Returns
-------
result : `str`
"""
if len(url) < 50:
return url
position = url.find('/')
if position == -1:
return f'{url[:28]}...{url[-19:]}'... | a813ccbac478da1eca3341983a3348b1cdc506d4 | 678,302 |
import torch
def _instance_grouping_term(embed_vals, keypoint_vis, reference_embeds):
"""
This function implements the first sub-expression from the grouping loss
in the associative embedding paper. This sub-expression incentivizes
grouping within instances
"""
instance_count = reference_embed... | f3205c2a99bd4ef345a9b6b7d6bfd099d58aadde | 678,303 |
import tkinter as tk
def get_screen_size():
""" Return the screen size in inches """
root = tk.Tk()
width = root.winfo_screenmmwidth() * 0.0393701
height = root.winfo_screenmmheight() * 0.0393701
root.destroy()
return width, height | 7f1d6b4ae29f122beb94dae9b6f19f25477e0f09 | 678,304 |
def get_data_dim(dataset):
"""
:param dataset: Name of dataset
:return: Number of dimensions in data
"""
if dataset == "SMAP":
return 25
elif dataset == "MSL":
return 55
elif str(dataset).startswith("machine"):
return 38
else:
raise ValueError("unknown dat... | 7888924bf3aaf69317fa9fed72e05f9554ce98c4 | 678,306 |
import math
def _deck_name(current_cnt, total_cnt):
""" Get deck name for DriveThruCards.
"""
if total_cnt > 130:
return 'deck{}/'.format(min(math.floor((current_cnt - 1) / 120) + 1,
math.ceil((total_cnt - 10) / 120)))
return '' | 39d92172b463e5efe83fb7b93fad695bbaa08c2d | 678,307 |
def _can_show_deleted(context):
"""
Calculates whether to include deleted objects based on context.
Currently just looks for a flag called deleted in the context dict.
"""
if hasattr(context, 'show_deleted'):
return context.show_deleted
if not hasattr(context, 'get'):
return Fals... | dc8833bb7a1fa45fa016f31f99efce22a7c05f1a | 678,308 |
def sort_dict_by_value(d, increase=True):
"""sort dict by value
Args:
d(dict): dict to be sorted
increase(bool, optional): increase sort or decrease sort. Defaults to True.
Returns:
[type]: [description]
Examples:
>>> d = Dict()
>>> d.sort_dict_by_value({"a": 1... | c2fbfca5fa572c3f030e14ea74e8c1ae29e3e6d7 | 678,309 |
import inspect
import operator
def _get_defined_methods(cls):
"""
Get all the methods that are defined on *that* class, ignoring parents.
"""
ret = []
for name, val in cls.__dict__.items():
if inspect.isfunction(val):
lines, lnum = inspect.getsourcelines(val)
ret.ap... | 698ace5d700d74ab09035ea9fb439af191508d59 | 678,310 |
def _squeeze(lines, width):
"""
Squeeze the contents of a cell into a fixed width column, breaking lines on spaces where possible.
:param lines: list of string lines in the cell
:param width: fixed width of the column
:return: list of lines squeezed to fit
"""
if all(len(line) <= width for ... | 6e4c6f6f991dfbf02a145b1d304bbb1bc345b021 | 678,312 |
import os
import pathlib
def xdg_data_config(default):
"""Return the path to the config file in XDG user config directory
Argument:
default: the default to use if either the XDG_DATA_HOME environment is
not set, or the XDG_DATA_HOME directory does not contain a 'gist'
file.
... | fd7d84fa5c2605e82ba6388b0d18c5795d9eac4a | 678,313 |
def irc_split(line):
"""Split an event line, with any trailing free-form text as one item."""
try:
rest_pos = line.index(' :')
bits = line[0:rest_pos].split(' ') + [line[rest_pos + 2:]]
except ValueError:
bits = line.split(' ')
return bits | 42a9bf33e7ca0d85f1ddfa242e661d984f3c88ce | 678,314 |
def listOfValidPoints(map_len, map_bre, radius=1):
"""
Definition
---
Method to generate a list of all valid points on a map
Parameters
---
map_len : length of map
map_bre : breadth of map
radius: radius of the robot (default, point robot)
Returns
---
validPoints : list... | 06164d64f55b1b3205e1a920844b19f952c228e3 | 678,315 |
def energy_capacity_rule(mod, g, p):
"""
The total energy capacity of dr_new operational in period p.
"""
return mod.DRNew_Energy_Capacity_MWh[g, p] | 39254e81cbbcff85773af4415c33a5896191e4cd | 678,316 |
def list_cycles(grammar, max_count, parent, length, counts, prev_pair=""):
"""Restricted to max_count"""
counts[prev_pair] += 1
result = (
[parent]
if length == 1
else [
parent + x
for node in grammar[parent]
for x in list_cycles(
... | 179ca98cab72a471ff68dd1bcac738fa76923a8d | 678,317 |
import re
def creator_time(time):
"""
Creates the time format to use directly with CallistoSpectrogram
"""
time = str(time)
long = len(time)
new = ''
for x in range(long): new = new + time[x]
return re.sub(r'((?:(?=(1|.))\2){2})(?!$)', r'\1:', new) | bba18edc2add299e2f5e390ebec4f96d29398e1d | 678,318 |
def is_ps_zone(zone_conn):
"""check if a specific zone is pubsub zone"""
if not zone_conn:
return False
return zone_conn.zone.tier_type() == "pubsub" | 44fd3289b418bc62d99360d7acf6a63344ea88c9 | 678,319 |
import json
def get_images_name_by_ids(image_ids):
"""
@param image_ids: List [N]
@return: List[N]
"""
names = []
# with open(caption_path) as f:
with open('data/caption_2.json') as f:
raw = json.load(f)
for id in image_ids:
name = raw[str(id)]["filename"] # list type... | 378055c0ba9eb7fd6caef8753633869b6d6d03b1 | 678,320 |
def bollinger_bands(price_col, length=20, std=1.96):
"""
Calculate Bollinger Bands
:param price_col: A series of prices
:param length: Window length
:param std: Standard deviation
:return: A 3-tuple (upper band, mid, lower band)
"""
mid = price_col.rolling(window=length).mean()
upper... | b48008c4ed44c9386e03d4e2906a1663cdbe4e82 | 678,321 |
def get_census_params_by_county(columns):
"""Returns the base set of params for making a census API call by county.
columns: The list of columns to request."""
return {"get": ",".join(columns), "for": "county:*", "in": "state:*"} | 7fed3bb9b75e9396b18f85a33ef9a57cc6408b9f | 678,322 |
def bindingType(b):
"""
Function returns the type of a variable binding. Commonly 'uri' or 'literal'.
"""
type = b['type']
if type == "typed-literal" and b['datatype'] == "http://www.w3.org/2001/XMLSchema#string":
type = 'literal'
return type | a4bfd6922da1cacada316069edf2e6feb7e8584d | 678,324 |
import sys
def get_outlier_definition_string(outlier_definition, rmsd_cutoff = 1.5, dihdist_cutoff = 40):
"""
Returns a string for adding to a database query which removes outliers. Need to add AND manually to the string.
"""
if outlier_definition == "conservative":
s = " (bb_rmsd_cdr_align <... | ad607f468ce463f0b739cf885019572417a8977a | 678,325 |
import json
import sys
def json2dict(data):
"""
Convert json to dict (output: dict)
"""
try:
return json.loads(data)
except ValueError as e:
print('error: Bad JSON format: {}'.format(e), file=sys.stderr)
sys.exit() | e0130f2005cb19303b513fff205598cf9a5225fc | 678,326 |
def make_blank_git(out_dict):
"""Adds blank git info
*Args*:
out_dict: current output dictionary
*Returns*:
out_dict: output dictionary with added git info
"""
for key in ("BRANCH", "COMMIT SHA", "STATUS", "ORIGIN"):
out_dict.update({f"# Git {key}": "UNKNOWN"})
retur... | daa056f4390585a95a711ab85caf6c1db9aee009 | 678,327 |
def average_out_obj_func(data_path, user_id):
"""this function average out all runs of a user objective function and returns the final iteration x axis
and loss values for the y axis """
r = open(data_path+'/'+str(user_id)+'.txt', 'r')
runs = r.readlines()
all_x = []
all_y = []
lengthes = [... | f93e34286dc1856cd1fd36349360a2fe4832e6a2 | 678,328 |
def get_position_list(target, obs):
"""
Get the list of positions of obs in target
"""
pos_of_obs_in_target = [0]
if len(obs) != 0:
pos_of_obs_in_target =\
[j for j, w in enumerate(obs, start=1) if w in target]
if len(pos_of_obs_in_target) == 0:
pos_of_obs... | 92536e38483163e50d7472f2192eaaf8b052b3e2 | 678,329 |
def incremental_mean(mu_i, n, x):
"""
Calculates the mean after adding x to a vector with given mean and size.
:param mu_i: Mean before adding x.
:param n: Number of elements before adding x.
:param x: Element to be added.
:return: New mean.
"""
delta = (x - mu_i) / float(n + 1)
mu... | 8f1db96c12856f5bcdbf3cb154b93be944a6b289 | 678,330 |
def get_object_id_value(spall_dict):
"""
get the best value for OBJID
:param spall_dict:
:return:
"""
if "BESTOBJID" in spall_dict.keys():
return spall_dict["BESTOBJID"]
else:
return spall_dict["OBJID"] | a0809d787115c8ef64eba373c9c5c65438cc839a | 678,332 |
def first(seq, pred=None):
"""Return the first item in seq for which the predicate is true.
If the predicate is None, return the first item regardless of value.
If no items satisfy the predicate, return None.
"""
if pred is None:
pred = lambda x: True
for item in seq:
if pr... | f545ab4deb8c6d8103dd46dc85e0afd1f2597c6e | 678,333 |
def multiple_benchmark_thetas(benchmark_names):
"""
Utility function to be used as input to various SampleAugmenter functions, specifying multiple parameter benchmarks.
Parameters
----------
benchmark_names : list of str
List of names of the benchmarks (as in `madminer.core.MadMiner.add_ben... | b4e2fad24c6b8303f8985ed9cd8e4a352b70da38 | 678,334 |
def convertWCS(inwcs,drizwcs):
""" Copy WCSObject WCS into Drizzle compatible array."""
drizwcs[0] = inwcs.crpix[0]
drizwcs[1] = inwcs.crval[0]
drizwcs[2] = inwcs.crpix[1]
drizwcs[3] = inwcs.crval[1]
drizwcs[4] = inwcs.cd[0][0]
drizwcs[5] = inwcs.cd[1][0]
drizwcs[6] = inwcs.cd[0][1]
... | ca5f490ffac73d9510ccbeb927ddc818cafbf5a9 | 678,335 |
import re
def normalize_version(version):
"""
This function convers a string representation of a version into
a list of integer values.
e.g.: "1.5.10" => [1, 5, 10]
http://stackoverflow.com/questions/1714027/version-number-comparison
"""
return [int(x) for x in re.sub(r'(\.0+)*$','', ver... | 758a956321061940982f82d39b25824fc73306a7 | 678,336 |
def is_eligible_for_exam(mmtrack, course_run):
"""
Returns True if user is eligible exam authorization process. For that the course must have exam
settings and user must have paid for it.
Args:
mmtrack (dashboard.utils.MMTrack): a instance of all user information about a program.
course... | 2ee804ac8f338186bd543584b207cde440a109c5 | 678,337 |
import numpy
def gen_Mrot(angle_rads, axis):
"""Generate a 4x4 single-axis numpy rotation matrix.
:param float angle_rads: the desired rotation angle in radians
:param char axis: character specifying the rotation axis
"""
cosang = numpy.cos(angle_rads)
sinang = numpy.sin(angle_rads)
if '... | ae428384e8c7d7bd958858578a8fdbb7fc29f63d | 678,338 |
def load_vocab(vocab_file):
"""
:param vocab_file:vocab file path
:return:
"""
vocab = {}
labels = {}
index_ = 0
index = 0
words = []
tags = []
with open(vocab_file, "r", encoding="utf-8") as f:
sentences = f.readlines()
for sentence in sentences:
... | ee2ef84bab187dbc010bb362a6a0cc0c0b6265ae | 678,339 |
import math
def calc_tf_padding(x,
kernel_size,
stride=1,
dilation=1):
"""
Calculate TF-same like padding size.
Parameters:
----------
x : tensor
Input tensor.
kernel_size : int
Convolution window size.
stride : in... | 4d1ac3cdf451fdfc86fa4b41a217f6813b401252 | 678,340 |
def get(server_id, **kwargs):
"""Return one server."""
url = '/servers/{server_id}'.format(server_id=server_id)
return url, {} | 03416fc01f5a618b92701a3a17d2809237fda23a | 678,341 |
def bytes_to_human_readable(num, suffix='B'):
"""
Convert number of bytes to a human readable string
"""
for unit in ['','k','M','G','T','P','E','Z']:
if abs(num) < 1024.0:
return '{0:3.1f} {1}b'.format(num, unit)
num /= 1024.0
return '{0:3.1f} {1}b'.format(num, 'Y') | 07245d978543664e62c4abb4a617a0e1cbf48638 | 678,342 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.