content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import math
def cost(a, b, c, e, f, p_min, p):
"""cost: fuel cost based on "standard" parameters
(with valve-point loading effect)
"""
return a + b * p + c * p * p + abs(e * math.sin(f * (p_min - p))) | 62e93d90b7a9620376ea3a91156707f5a6ef5105 | 676,002 |
import torch
def coco_annotations_to_tensors(coco_annotations,
image_shape,
parts,
topology,
max_count=100):
"""Gets tensors corresponding to peak counts, peak coordinates, and peak to p... | d5943f974d1a6dae899449bae070e38c0239c577 | 676,003 |
def calculate_offset(address, base, shadow_base=0):
""" Calculates an offset between two addresses, taking optional
shadow base into consideration.
Args:
address (int): first address
base (int): second address
shadow_base (int): mask of shadow address that is applied to `base`
... | 7614a1263c2d73cacf509c769e53503b80052839 | 676,004 |
import yaml
def get_yaml_dict(yaml_file):
"""Return a yaml_dict from reading yaml_file. If yaml_file is empty or
doesn't exist, return an empty dict instead."""
try:
with open(yaml_file, "r") as file_:
yaml_dict = yaml.safe_load(file_.read()) or {}
return yaml_dict
except FileNotFoundError:
return {} | bf290735bc3d30f8517d8513f8d2679a1383e718 | 676,005 |
import os
import subprocess
import sys
import traceback
def execute(args, command_args):
"""Execute IDA Pro as a subprocess, passing this file in as a batch-mode
script for IDA to run. This forwards along arguments passed to `mcsema-disass`
down into the IDA script. `command_args` contains unparsed arguments pa... | 3caedbf21a89604a7d016cf61cee914f60a5ea9e | 676,007 |
import math
def tand(v):
"""Return the tangent of x (measured in in degrees)."""
return math.tan(math.radians(v)) | a3023dcdf19bb7b235ac5389011c0243498b7128 | 676,008 |
def decode_to_string(data):
"""
:param data:
:return:
"""
decoding = {}
for k, v in data.items():
decoding[k] = v[0].decode() if type(v) == list and len(v) == 1 else [i.decode() for i in v]
return decoding | 83e13291ae4ae3208f8ac14cc1167d693fbf9ffd | 676,009 |
import torch
def compute_mask(x, sequence_lengths, batch_axis=0, sequence_axis=1):
"""
This function calculates a mask which indicates the position of non-padded values.
It can be used to do subsequent operations only on non-padded values.
>>> x, seq_len = 2*torch.ones((3,1,10,4)), [1, 2, 3]
>>> ... | e75c2e40b5dfd76565d6fd3b72fadd151160f4b2 | 676,010 |
def misra_c2012_compare(rule):
""" compare misra C2012 rules """
return int(rule.split('.')[0])*100 + int(rule.split('.')[1]) | 16a35130f9b3338638645d3cde9c4997034f4dde | 676,011 |
import numpy
def unDiskify(x, y, scaleR):
"""
Convert x y to unit disk, return the radial scale factor
"""
r = numpy.sqrt(x**2 + y**2) * scaleR
theta = numpy.arctan2(y, x)
_x = numpy.cos(theta) * r
_y = numpy.sin(theta) * r
return _x, _y | c5ff58021284a609429e06760b1f492cfa78f44f | 676,012 |
def cartesian(coords):
""" Convert 2D homogeneus/projective coordinates to cartesian. """
return coords[:, :2] | 36566982c7d2aa9cb3fda1aeab8de1d0ee2fb115 | 676,013 |
def getObjectKey(rpcObject):
"""Given a rpc object, get a unique key that in the form
'class.id'
@type rpcObject: grpc.Message
@param rpcObject: Rpc object to get a key for
@rtype: str
@return: String key in the form <class>.<id>
"""
objectClass = rpcObject.__class__.__name__
object... | dcd1af06fcbe6022d5382eee79878ad6a222a3c5 | 676,014 |
import calendar
def sort_months(months):
"""Sort a sequence of months by their calendar order"""
month_ref = list(calendar.month_name)[1:]
return sorted(months, key=lambda month: month_ref.index(month)) | 71c465901149f3a7dac325d3f3e97d495a245c94 | 676,015 |
def _python_command(self):
"""
如果是py文件,则存成一条command
"""
with open(self.file_path, 'r') as f:
py_string = f.read()
return py_string | 02516d59ea0c3618a79f97d7e2810f951cf2c406 | 676,016 |
def find_md_link_or_url(text):
"""
find_md_link_or_url('ab[cd](ef)xy') returns:
('abcdxy', 'ef')
All the text goes into the text, and the URL as well.
"""
start = (0,)
open_sq = (1,)
closed_sq = (2,)
open_curve = (3,)
closed_curve = (4,)
state = start
text_content = ... | e7bfa888a1e08d5efc9a522f3d83b98e3ca6c1fc | 676,017 |
from pathlib import Path
import tempfile
import venv
def create_new_venv() -> Path:
"""Create a new venv.
Returns:
path to created venv
"""
# Create venv
venv_dir = Path(tempfile.mkdtemp())
venv.main([str(venv_dir)])
return venv_dir | 077dd1318d579ccdb3333849b092555c54297903 | 676,018 |
import os
def _get_log_file_for_script(config, script_name):
"""Returns a path to the log file for the given script."""
logs_dir = config['logging']['logs_dir']
if not os.path.isabs(logs_dir):
logs_dir = os.path.join(os.path.dirname(__file__), os.pardir, logs_dir)
return os.path.join(logs_dir... | 5fb34b39eab28d173413fdd37237dd0730dee5d2 | 676,019 |
def compare_files(first_list, second_list):
"""
Compares two lists that should contain the path + filename of the modified
files. The two lists are mutable.
:param first_list: First lists.
:param second_list: Second list
:return: returns boolean value in case a match is found.
"""
for e... | c388ac2c536e7650d3f0fc5becf0c6790919d9f2 | 676,020 |
import os
import json
def get_splits(root: str):
"""
Reads splits file indices.json
:param root:
:return:
"""
with open(os.path.join(root, "training_indices.json")) as f:
dict = json.load(f)
return dict | 989dec3f980179453e3f40a5954d8c15d3ade013 | 676,021 |
def inc(x_b):
"""Return the pathname of the KOS root directory."""
return x_b + 1 | 8a57ca513d5c84233dcf7382a0d9fade3a8b8226 | 676,022 |
def total_seconds(td):
"""
Return total seconds in timedelta object
:param td: timedelta
:type td: datetime.timedelta
:return: seconds
:rtype: float
"""
return (td.microseconds + (td.seconds + td.days * 86400) * 1000000) / 1000000.0 | 8aab761d946bee240e2c49d5de0885f021d82ba6 | 676,024 |
def adjust_lenght(string, max_length):
"""Adjust the length of string."""
while len(string) > max_length:
string = string[:-1]
return string | e3eca0886ee1f9a85bcf3bd6c4976999613531d9 | 676,025 |
import getpass
def get_mysql_pwd(config):
"""Get the MySQL password from the config file or an interactive prompt."""
# Two ways to get the password are supported.
#
# 1. Read clear-text password from config file. (least secure)
# 2. Read password as entered manually from a console prompt. (most s... | 3077fca733739d1d0648e555fa2a485a31cc3d8a | 676,026 |
def postfix_to_infix(postfix: str) -> str:
"""
start reading from beginning
1. every operand gets pushed into the stack
2. for every operator, pop 2 operands and push (op1 op op2) back into stack
3. repeat
"""
stack: list = []
for c in postfix:
if c.isalpha():
stack.... | 5e403754ccb91e4a1abf695c055ee63707299f7e | 676,027 |
import os
def is_testmode():
"""Server is running in the wttr.in test mode"""
return "WTTRIN_TEST" in os.environ | 01ecb4d62a5563dc8c034f48c92ff2294efa388d | 676,029 |
import six
def median_from_dict(total, count):
"""
total is the number of requests made
count is a dict {response_time: count}
"""
pos = (total - 1) / 2
for k in sorted(six.iterkeys(count)):
if pos < count[k]:
return k
pos -= count[k] | d4993ffb8f140c1a3f322b19b6975a7a8fd04d95 | 676,030 |
import torch
def scaled_sign(x, name=None):
"""
:param x: torch Tensor
:return: The sign tensor scaled by it's L1 norm divided by the number of elements
"""
_scale = x.norm(p=1) / x.numel()
_sign = torch.sign(x)
return _scale, _sign | a632c7d23527fce80f2c195e5208c5a1eb629718 | 676,031 |
def deep_merge(a, b):
"""Merges a and b, letting b win if there is a conflict"""
merged = a.copy()
for key in b:
b_value = b[key]
merged[key] = b_value
if key in a:
a_value = a[key]
if isinstance(a_value, dict) and isinstance(b_value, dict):
me... | d5b557c155867b386e99babd14036ca7f25c05d0 | 676,032 |
def nstr(n):
"""Represent integer in radix with base up to 62 using digits, big letters and small letters. """
if n < 10:
return str(n)
n -= 10
if n < 26:
return chr(ord('A') + n)
n -= 26
return chr(ord('a') + n) | 0c9b6ce6d974cf03a10a178a96828a9b0d854034 | 676,033 |
def resolve_attribute(name, bases, default=None):
"""Find the first definition of an attribute according to MRO order."""
for base in bases:
if hasattr(base, name):
return getattr(base, name)
return default | ed358e230da7ca7bb2a413caee151f344c111b25 | 676,034 |
def findORF_all_sorted_longest_n(dna_seq, n):
"""
Finds all the longest open reading frames in the DNA sequence.
"""
tmpseq = dna_seq.upper();
orf_all = []
for i in range(0, len(tmpseq), 3):
codon = tmpseq[i:i+3]
if codon == 'ATG':
orf = tmpseq[i:]
for j i... | 240d91053b8dfa925601c1004430cbfb0d120e71 | 676,035 |
def _get_date_and_time_strings(date):
"""Return string of YYYYMMDD and time in HHMM format for file access."""
y, m, d, h = [str(i) for i in [date.year, date.month, date.day, date.hour]]
# add zeros if needed
if len(m) == 1:
m = '0' + m
if len(d) == 1:
d = '0' + d
if len(h) == 1... | da60c58bd6c13e104caf2d01d479675d7d7a7b8a | 676,037 |
import os
import fnmatch
def read_files(directory, pattern='*.png'):
"""
Recursively read a directory and return all files
that match file pattern.
"""
matched_files = []
for root, dirs, files in os.walk(directory):
# Filter only filename matches
matches = [os.path.join(root, f... | 1cc77a718252a72809bf57ecec0e8a94226fb636 | 676,038 |
import typing
def format_scopes(scopes: typing.List[str]) -> str:
"""Format a list of scopes."""
return " ".join(scopes) | 5776e849ff96ab250f2b957309c6b1829ac54383 | 676,039 |
import re
def get_size_from_tags(tags):
"""Searches a tags string for a size tag and returns the size tag.
Size tags: spacesuit, extrasmall, small, medium, large, extralarge.
"""
match = re.search(
r'\b(spacesuit|extrasmall|small|medium|large|extralarge)\b', tags
)
if match:
re... | 8d406d237a7249b6d3807af6375f56b5c124ca8b | 676,040 |
def distance_from_camera(bbox, image_shape, real_life_size):
"""
Calculates the distance of the object from the camera.
PARMS
bbox: Bounding box [px]
image_shape: Size of the image (width, height) [px]
real_life_size: Height of the object in real world [cms]
"""
## REFERENCE FOR GOPRO
... | 037adbaba89ae13ed74ac5fc1d1cfc080c5107d1 | 676,041 |
def get_occurences(node, root):
""" Count occurences of root in node. """
count = 0
for c in node:
if c == root: count += 1
return count | 7df5e3e1c5fbcdca482a297e38b5e09be1b3d8e1 | 676,042 |
import os
def get_path(parsed_args, *args):
"""Return an absolute path, given a path relative to the base."""
base_path = os.path.abspath(parsed_args.base_path)
return os.path.join(base_path, *args) | c90e98b85b49a70432f1881242240b333daeb9e4 | 676,043 |
import re
def handle_globals(local_identifiers, global_identifiers, YoPy):
"""
This function handles the preceding ':' for external variables
"""
output = ""
YoPy.seek(0, 0)
for line in YoPy.readlines():
matches = re.findall(r'(:[a-z0-9]+)', line)
if matches:
for m ... | 134f2d316b9455da1d5bcadb97c39f9e7e06c96c | 676,044 |
import json
import subprocess
import os
def dangerously_simulate_api_response(request_dict):
"""*SHOULD NOT RECEIVE USER INPUT*. Simulates the API output for the specified request using server files located within this repository's directory structure.
The request should be in the form of a dictionary specifyin... | 2c7f570f6f14302e44f278433ad34ea7ed6a8224 | 676,045 |
from typing import OrderedDict
def remove_duplicates(text: str) -> str:
"""Remove duplicates from text.
Function uses OrderedDict, which keeps order and distinct elements.
"""
set_ = OrderedDict()
for x in text:
set_[x] = None
return ''.join(set_.keys()) | c0d1d0e853cd96ca387dfae625c730eda2793858 | 676,046 |
import os
import pickle
def load_dataset(pickle_path,only_one=False):
"""Loads and returns dataset clips from pickled_path"""
clips = {}
if(only_one):
#Loads only one pkl. Useful for testing purposes
pkl = sorted(os.listdir(pickle_path))[0]
clips["1"] = pickle.load(open(pickle_path... | f62ad07f3b73499f835235714f04e1f1be0b8c7e | 676,047 |
def snd(tpl):
"""
>>> snd((0, 1))
1
"""
return tpl[1] | d002211609082a2c14f49b826643c774dd6205c3 | 676,048 |
from pathlib import Path
from typing import List
def get_regions_data(path: Path) -> List[dict]:
"""Gets base data for a region in a page.
:param path: Path to the region directory.
:return: List of dictionaries holding base region data.
"""
regions = list()
for region in sorted(path.glob(".... | b5e4d10f58815eaec23104ec37ac6c9beaa45c43 | 676,050 |
def get_members_name(member):
"""Check if member has a nickname on server.
Args:
member (Union[discord.member.Member, list]): Info about member of guild
Returns:
str: User's name, if user doesn't have a nickname and otherwise
list: List of names of user's nicknames
"""
if i... | 4b8798a98dc6064b775a72e44c1189408e7a0073 | 676,051 |
from typing import Callable
from typing import Any
from typing import Optional
import inspect
def has_param(fn: Callable[..., Any], name: str, pos: Optional[int] = None) -> bool:
"""
Inspects function fn for presence of an argument.
"""
args = inspect.getfullargspec(fn)[0]
if name in args:
... | b4c29366a29bda65e1337301545fc4cf9b18d76c | 676,052 |
def cgr_neighbor_function(contact_graph, node, destination, current_distance,
set_visited, suppressed_contacts, lookahead_time):
"""Neighbor function of CGR used by the Dijkstra algorithm.
Used to determine feasible direct neigbors of a given node.
Args:
contact_graph (C... | 1a5efa908b22424d22b2b823fd0f425d4ea3d611 | 676,053 |
def to_alternating_case(string):
"""Input a string, return string with case swapped"""
return "".join([s.swapcase() for s in string]) | 3e94a5fbfdaccb496fd90453f070baf8ea422f14 | 676,054 |
import re
def escape_shell_chars_tmsu(str):
"""
escapes all chars which would cause problems in shell and
also replaces / with \, because tmsu does not accept \ in tags
:param str:
:return:
"""
str = str.replace("/", "\\")
str = re.sub("(!|\$|#|&|\"|\'|\(|\)|\||<|>|`|\\\|;| )", r"\\\1"... | 3a8685084e639ea9c68e3bea0c99b2c23425fa4f | 676,055 |
import os
def abslistdir(directory):
"""
returns a list of absolute filepaths for all files found in the given
directory.
"""
abs_dir = os.path.abspath(directory)
filenames = os.listdir(abs_dir)
return [os.path.join(abs_dir, filename) for filename in filenames] | 9f76193e4f966c7c3f5477623ebc5d819b60dc75 | 676,056 |
def get_all_children(base_pid):
"""
Return all child PIDs of base_pid process
:param base_pid starting PID to scan for children
:return tuple of the following: pid, binary name, command line incl. binary
:type base_pid int
:rtype list[(int, str, str)]
"""
parent_pid_path_pattern = "/proc/{0}/task/{0}/... | 85859188c990dec234a96e32e822293462140f7b | 676,057 |
def find_layer_idx(model, layer_name):
"""Looks up the layer index corresponding to `layer_name` from `model`.
Args:
model: The `keras.models.Model` instance.
layer_name: The name of the layer to lookup.
Returns:
The layer index if found. Raises an exception otherwise.
"""
... | ab5c8bcde11e22aa0081a2bb60c9b99c324b6525 | 676,058 |
def _start_time_from_groupdict(groupdict):
"""Convert the argument hour/minute/seconds minute into a millisecond value.
"""
if groupdict['hours'] is None:
groupdict['hours'] = 0
return (int(groupdict['hours']) * 3600 +
int(groupdict['minutes']) * 60 +
int(groupdict['seco... | 0f09960f3cb482931445d304a963236db11c2228 | 676,059 |
def frame_to_pattern(frame_path):
"""Convert frame count to frame pattern in an image file path.
Args:
frame_path (str): Path of an image file with frame count.
Returns:
str: Path of an image sequence with frame pattern.
"""
name_list = frame_path.split('.')
name_list[-2] = '%... | bfd1c973281b11295d4c17752c5ae1b2c221fad7 | 676,060 |
import math
def visibility(nov, nol, a):
"""Compute visibility using height-correlated GGX.
Heitz 2014, "Understanding the Masking-Shadowing Function in Microfacet-Based
BRDFs"
Args:
nov: Normal dot view direction.
nol: Normal dot light direction.
a: Linear roughness.
Returns:
The geometr... | 04fb867d55622951fee64c7edb22d042f890ae74 | 676,061 |
def flip(res):
"""flips 'x', 'o' or 'draw'."""
if res == 'x':
return 'o'
elif res == 'o':
return 'x'
elif res == 'draw':
return 'draw'
else:
raise RuntimeError("Invalid res: %s" % str(res)) | 22438c63ae9cc456c2d090b2462e6277a6146d6e | 676,062 |
def plot_info(ax, freq, label=False):
""" Plots the marker for the simulated frequency
Parameters
----------
For a description of the parameters see 'plot_panel_row'.
"""
# if label:
# ax.text(freq+0.2, 0.85, f'P$_\mathrm{{sim.}}$ = {1/freq:.2f} d',
# transform=ax.trans... | 0a67e8191614535c9ec8b427e612ac0c5636ede8 | 676,063 |
def RotXOR(s, n, target):
"""
Input: Byte array 's' of size 16, integer 'n', Byte array 'target' of size 16
Output: Byte array of size 16 which is result of operation
Right-rotate 's' by 'n' bits and XOR with 'target' then return the result
If in any case we have to do left shift/rotate x bits ... | 48c58d200bd0031f0e448b608e1a23026b188c4a | 676,064 |
import math
def calculate_tail_correction(box_legth, n_particles, cutoff):
"""
Calculates the tail correction
Parameters
----------
box_legth : float
The distance between the particles in reduced units.
n_particles : int
The number of particles.
cutoff : float
... | 16ea67d6423cf4a466313a2766aa9c9c4d7c0f15 | 676,065 |
def getPdbCifLink(pdb_code):
"""Returns the html path to the cif file on the pdb server
"""
file_name = pdb_code + '.cif'
pdb_loc = 'https://files.rcsb.org/download/' + file_name
return file_name, pdb_loc | ff8eebf8eb5559088e8f37be67b9b032383b2541 | 676,066 |
def prep_sub_id(sub_id_input):
"""Processes subscription ID
Args:
sub_id_input: raw subscription id
Returns:
Processed subscription id
"""
if not isinstance(sub_id_input, str):
return ""
if len(sub_id_input) == 0:
return ""
return "{" + sub_id_input.strip... | 719693c2a11d1e8611fceec80b34b07a157e91ad | 676,067 |
def ls(conn, path):
"""If path contains a wildcard (* or %):
Return all paths known to the database that start match the given path
argument (containing wildcards).
If path doesn't contain wildcards:
Return the exact match on the path argument."""
if path.find('*') >= 0 or path.find('%'... | cc289fe13a6d3e96a3004a7f9431ff448523f177 | 676,068 |
def list_tokenizer(tokenizer, text_list):
"""Split train dataset corpus to list """
line_list = list()
for text in text_list:
line_list.append(tokenizer.tokenize(text))
return line_list | 76a2081f7ef12d5f4c571400f2669d22b52f4364 | 676,069 |
def nth_eol(src, lineno):
"""
Compute the ending index of the n-th line (before the newline,
where n is 1-indexed)
>>> nth_eol("aaa\\nbb\\nc", 2)
6
"""
assert lineno >= 1
pos = -1
for _ in range(lineno):
pos = src.find('\n', pos + 1)
if pos == -1:
return ... | d0a77d3541874d054297a78bd1307bc18ec220af | 676,070 |
import requests
def get_online_person(params=None, **kwargs) -> bytes:
"""Get a picture of a fictional person from the ThisPersonDoesNotExist webpage.
:param params: params dictionary used by requests.get
:param kwargs: kwargs used by requests.get
:return: the image as bytes
"""
r = requests.g... | 1b492fcf4d67f1431d8883af1761135d4d52cd97 | 676,071 |
def safe_pop(data, index=0, default=None):
"""This function pops safetly a GqlResponse from a subscription queue.
Args:
data (list): Is the list of GqlResponse that caught the subscription.
index (int, optional): Index of the subscription queue. Defaults to 0.
default (None, optional): Define the... | 207a1a1acd688ea7485d5d4034b4f7cc6618d6aa | 676,072 |
def cols_to_count(df, group, columns):
"""Count the number of column values when grouping by another column and return new columns in original dataframe.
Args:
df: Pandas DataFrame.
group: Column name to groupby
columns: Columns to count.
Returns:
Original DataFrame with ne... | d9bdb0e6a87805a02a21d7f19505e84206264d66 | 676,074 |
def node_exists(api, node_name):
"""Determines whether the specified node is still part of the cluster-on-aws."""
nodes = api.list_node(include_uninitialized=True, pretty=True).items
node = next((n for n in nodes if n.metadata.name == node_name), None)
return False if not node else True | 50083fddbd767a015ec1a429cd838084c1ecb495 | 676,076 |
import hashlib
import binascii
def _get_hash(password):
"""
calculate hash on password
:param password:
:return hash:
"""
hex_hash = hashlib.pbkdf2_hmac('sha256', password.encode(), b'user', 100_000)
return binascii.hexlify(hex_hash) | 5d637d22ab710912cfae5525e368403890456333 | 676,078 |
import math
def calcVector(p1,p2):
"""
calculate a line vector in polar form from two points. The return
is the length of the line and the slope in degrees
"""
dx = p2[0]-p1[0]
dy = p2[1]-p1[1]
mag = math.sqrt(dx * dx + dy * dy)
theta = math.atan2(dy,dx) * 180.0 / math.pi + 90.0
re... | bb89a5332aba097f6178d679accc8786b3e07d51 | 676,079 |
def striplines(text):
""" Remove all leading/trailing whitespaces from lines and blank lines. """
return "\n".join(
line.strip() for line in text.splitlines() if len(line.strip())
) | d0122580daa2e0bff8be323b2eeb1f7966b86cf0 | 676,080 |
def hop(context):
"""multi-lines string"""
return ['''<a id="sendbutton" href="javascript: $('%(domid)s').submit()">
<img src="%(sendimgpath)s" alt="%(send)s"/>%(send)s</a>''' % context,
'''<a id="cancelbutton" href="javascript: history.back()">
<img src="%(cancelimgpath)s" alt="%(cancel)s"/>%(cance... | 9ad98fd5007dbae3f62440e463b94e65244af3da | 676,081 |
def combine(background_img, figure_img):
"""
Erase the green screen in figure_img and
combine the result 'figure' with 'space_ship'.
:param background_img: the background image to place 'figure'
:param figure_img: the figure with green screen,
erase the green screen in image w... | e1fa1dc4986d2d0c252a85d7830064f6153aa5d1 | 676,082 |
import os
import tempfile
from typing import Any
def save_artifact(model: Any, filename: str):
"""
Parameters
----------
model The model bytes to save.
filename The filename for the model
Returns
-------
Return the local folder
"""
folder = tempfile.mkdtemp()
print(fold... | c5f244c48d78e209180786980781bf492f675dc7 | 676,083 |
def exchange(flw, exchanges_list):
"""Add docstring."""
exchanges_list.append(flw)
return exchanges_list | f3823077da5dd9aeca3a36ecd2f967bd911c92c5 | 676,084 |
from datetime import datetime
def ms_since_epoch(dt):
"""
Get the milliseconds since epoch until specific a date and time.
Args:
dt (datetime): date and time limit.
Returns:
int: number of milliseconds.
"""
return (dt - datetime(1970, 1, 1)).total_seconds() * 1000 | 3a7630c0930949f06573292729156c2e881107bd | 676,086 |
def hasEnoughHarmonics(baseFrequency, harmonics):
"""
harmonics is an array of integers where each integer is
represented as a string!!, e.g. "1" "3" "4" "5"
NOTE: the standard says that at least 4 harmonics must
be present for better spacial location of the sound
it does not menti... | d0e5b191b34aedfb17510c2625533524a3200d95 | 676,087 |
import os
def get_fetch_fout(filename):
"""Create a output file name where EFetch data will be stored."""
return ''.join([os.path.basename(os.path.splitext(filename)[0]), '.Entrez_downloads']) | 7d8a6e0852013db13009b9caef72e850f7d17820 | 676,088 |
def prob15(size=20):
"""
Starting in the top left corner of a 2*2 grid, there are 6 routes (without
backtracking) to the bottom right corner.
How many routes are there through a 20*20 grid?
"""
a = 1
for i in range(1, size + 1):
#print a
a = a * (size + i) / i
return a | 73d088ee201991bf927b25e0be0d32f1d2ab17f3 | 676,089 |
import re
def slugify(s):
"""
Simplifies ugly strings into something URL-friendly.
>>> print slugify("[Some] _ Article's Title--")
some-articles-title
"""
# "[Some] _ Article's Title--"
# "[some] _ article's title--"
s = s.lower()
# "[some] _ article's_title--"
# "[some]___ar... | fb403a0e8ff10e4c672f2fb3835da8b25877da46 | 676,090 |
def s2t_check(s2t_str):
"""
Example:
tree_string = "(TOP (S (VP (VBP Do) (RB n't) (VP (VB be) (NP (JJ such) (DT a) (NN pessimist)) (, ,) (NP (NNP Mr.) (NNP Ambassador)))) (. .)))"
_, tgt = tree_to_s2t(tree_string)
print(s2t_check(tgt))
print(s2t_check(tgt + " /NP"))
print... | a917e253069567f91380fb65427118e511401729 | 676,091 |
import os
def blast(sample,db,output, identity=90, threads=1, mincov=0,dbtype='nucl'):
"""
Call blastn with params
:param query_file (in fasta), db (blast indexed db), number of threads and identity
:return: list BLASTFields objects
"""
#check db is indexed
#dbfile=os.path.join(db_folder, ... | 8b9a0e0f278d5adbf5bf8dc69671241bec5f356b | 676,092 |
from typing import Optional
def get_between(haystack: str, start_token: str, end_token: str) -> Optional[str]:
"""Returns the first instance of a string between start and tokens."""
start_idx = haystack.find(start_token)
if start_idx == -1:
return None
start_idx += len(start_token)
end_... | 497a4f9abe7479fb4fa142fe8a76271578fd75b6 | 676,093 |
def get_side_menu_matrices(children):
"""Given a matrix structure defined in config.py, return stripped structure
with only names"""
def children_helper(matrix, path_prefix):
children = matrix["subtypes"]
return {
"name": matrix["name"],
"id": matrix["name"].spl... | 3d6dbbe2ef0d108db0a18a81e6c2307f614f7c04 | 676,094 |
import functools
def ensure_external_storage(fn):
"""Ensure management of external storage on methods which depend on it.
:raises: ``errors.ExternalStorageNotInstalled``
:raises: ``errors.ExternalStorageDisabled``
"""
# noqa
@functools.wraps(fn)
def wrapper(self, *args, **kwargs):
... | f73565ec061d3964535ee9e50919a26462134031 | 676,095 |
from typing import Optional
def is_upper_case_name(name: Optional[str]) -> bool:
"""
Checks that attribute name has no upper-case letters.
>>> is_upper_case_name('camelCase')
True
>>> is_upper_case_name('UPPER_CASE')
True
>>> is_upper_case_name('camel_Case')
True
>>> is_upper_c... | 4735edf75dce024b881016a427f878f4dadde92d | 676,096 |
import numpy
def power_cheap(f1, f2=None, boxsize=1.0, average=True):
""" stupid power spectrum calculator.
f1 f2 must be density fields in configuration or fourier space.
For convenience if f1 is strictly overdensity in fourier space,
(zero mode is zero) the code still works.
Does... | c1fd837277419fbc1bc369477b92611f7395d5c2 | 676,097 |
def serialize_table_umd(analysis, type):
""" Convert the aggregate_values=false Hansen response into a table"""
rows = []
for year in analysis.get('loss', None):
rows.append({'year': year,
'loss': analysis.get('loss', None).get(year),
'gain': analysis.get('g... | a57a749e39ff5ebd696a8ac052100ba4186aa429 | 676,098 |
def gradient_descent(x0, grad, step_size, T):
"""run gradient descent for given gradient grad and step size for T steps"""
x = x0
for t in range(T):
grad_x = grad(x)
x -= step_size * grad_x
return x | c7b69ecc9291064835690b997477841414bfe6a9 | 676,099 |
def nm_to_n(s):
"""Get the nick part of a nickmask.
(The source of an Event is a nickmask.)
"""
return s.split("!")[0] | 19995784deef1d4cb31360e3bf3680286509e591 | 676,100 |
def get_lab_name(sen, labels):
"""
sen = list of numerical labels
"""
inv_l = {v: k for k, v in list(labels.items())}
res = ""
for i in sen:
if i in inv_l:
res = res + " " + inv_l[i]
else:
res = res + " *NEWLABEL"
return res | 99c64a8f2b2db51a08d7f5db6bb0652659e93dab | 676,101 |
def reactionHasReactants(reaction, reactants):
"""
Return ``True`` if the given `reaction` has all of the specified
`reactants` (and no others), or ``False if not.
"""
if len(reactants) == len(reaction.products) == 1:
if reaction.products[0].isIsomorphic(reactants[0]):
return Fa... | 6e8f0da2f9756e96cd7f2f0b609b82d0c4772330 | 676,102 |
import linecache
def get_title(notes_path, file_stem):
""" Get the title by reading the second line of the .md file """
title = linecache.getline(notes_path + file_stem + '.md', 2)
title = title.replace('\n', '')
title = title.replace('title: ', '')
return title | 990047acbdcbf3e8d04c8167c59b985938829867 | 676,103 |
from typing import List
from typing import Dict
from typing import Any
def sew_messages_and_reactions(
messages: List[Dict[str, Any]], reactions: List[Dict[str, Any]]
) -> List[Dict[str, Any]]:
"""Given a iterable of messages and reactions stitch reactions
into messages.
"""
# Add all messages wit... | 01824e078fb7a44af6af80f49ff00b5ca5fcd3a6 | 676,104 |
def get_timing(line: str) -> str:
"""
Returns the stimulus timing from a line of text grabbed from a .vmrk file.
"""
return line.split(",")[2] | 299d0e0cd9c84ee926c1a69828c4db966c09fff1 | 676,105 |
def empty_string_check(string, raise_exception=True):
"""
Simple check to see if the string provided by parameter string is empty. False indicates the string is NOT empty.
Parameter raise_exception determines if a ValueError exception should be raised if the string is empty.
If raise_exception is False and the str... | 37b3ea789d31b9aec3c184e35026ad4b4f608d26 | 676,106 |
def get_public_key_from_x509cert_obj(x509cert) -> bytes:
""" returns a RSA public key object from a x509 certificate object """
return x509cert.public_key() | 896411f57781ae0b3537d2678345f0a69311b1e4 | 676,107 |
import os
import string
def getWinDrives():
""" Return list of detected drives """
assert os.name == 'nt'
drives = []
bitmask = windll.kernel32.GetLogicalDrives() #@UndefinedVariable
for letter in string.uppercase:
if bitmask & 1:
drives.append(letter)
bitmask >>= 1
... | 0406ec175c5f498a1d6cdb580f5211469705cdf0 | 676,109 |
def home():
""" Welcome to the Station Climate Home Page """
return(
f"""Available Routes:<br/><br/>
/api/v1.0/precipitation<br/><br/>
lists precipitation for last year of data<br/><br/>
/api/v1.0/stations<br/><br/>
lists all weather st... | 85dd8f66272acbb7cd62839abe0c4f80ff769024 | 676,110 |
def getfieldnamesendswith(idfobject, endswith):
"""get the filednames for the idfobject based on endswith"""
objls = idfobject.objls
tmp = [name for name in objls if name.endswith(endswith)]
if tmp == []:
pass
return [name for name in objls if name.endswith(endswith)] | 09815199d2c4e0bfae3ee583d1b6d2391d4d6dc9 | 676,111 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.