content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _convert_json_properties(properties):
"""
Convert a geojson expression of the properties of a sector into a
list of properties. Properties are in a dictionary.
The geojson has no object id field so we inject one.
"""
return [properties['AC_ID'], properties['AV_AIRSPACE_ID'],
pro... | ce6f90ea0a4cdc983b04da853b0ef16d35bec22c | 689,463 |
import subprocess
import os
def get_cwd():
""" Since we're working in a mixed sl5/sl6 environment paths
beginning with /amd/... can cause issues as sl6 uses autofs, which
does not rely on the automounter for nfs shares.
Try to use 'pawd' command first, on error revert to os.getcwd()
"""
retur... | 4e0f65675f614d5b04eb6f9b62ec3925c6949704 | 689,464 |
import re
def _parse_bovespa(df_str):
"""Parse tabela bovespa.Retornando valores no formato delista.
Args:
df_str (str): String contendo tabela.
Returns:
lista str: lista com valores de items.
"""
linhas = df_str.split("\n")
linhas_processed = [x.lower().replace(".", "").rep... | 7330a9cccb3e9b9eededb46b6113d97511a264d1 | 689,465 |
def match_candidate_span_keyphrase(segment_span, candidate_span_segment, keyphrases):
"""Receive element from dataset and return keyphrases ids with token indices"""
start, end = segment_span
token_keyphrases_ids = map(lambda token: token[3], candidate_span_segment)
keyphrases_ids = set(kpid for kps_ids... | ded968c1c4db90f0e92f071b4a6ad7b9e6f4233a | 689,466 |
import os
import importlib
def get_issue(issue_number):
"""
Returns the issue object for the given number
"""
backend_name = os.environ['ISSUE_BACKEND']
backend_module = importlib.import_module('issuebranch.backends.{}'.format(backend_name))
return getattr(backend_module, 'Backend')(issue_num... | 783cd487ac88cc91fd9d6fe510845028ee438c7a | 689,467 |
def _group_by_labels(cbdbscan_topics):
"""Group all the learned cores by their label, which was assigned in the cluster_model.
Parameters
----------
cbdbscan_topics : list of :class:`Topic`
A list of topic data resulting from fitting a :class:`~CBDBSCAN` object.
After calling .fit on a ... | 43c8a1ed4eab9bd08f8bd4ac4f1df4b5ab1a0ef4 | 689,468 |
def posIntInput(string):
"""Function to ensure that the input is a positive integer
Arguments:
string {str} -- string to print while taking input from user
"""
while True:
try:
while True:
value = int(input(string))
if value > 0:
... | 2cdcabab003811795f1f8a640a4eeb4d41cb42a8 | 689,471 |
def flip_ctrlpts_u(ctrlpts, size_u, size_v):
""" Flips a list of 1-dimensional control points in u-row order to v-row order.
**u-row order**: each row corresponds to a list of u values (in 2-dimensions, an array of [v][u])
**v-row order**: each row corresponds to a list of v values (in 2-dimensions, an arr... | 6c28a487b05de5490d244a04d19d25c575ebdd75 | 689,472 |
def divup(x: int, y: int) -> int:
"""Divide x by y and round the result upwards."""
return (x + y - 1) // y | 5fa0ede218aa30bb58eadaedf32da0fd853664f7 | 689,473 |
def create_test_results(suite_name, test_name, timestamp, command_args_printable, rc):
"""
Create a minimal test results object for test cases that did not produce their own
:param suite_name: the name of the subdirectory for the suite this test was run in
:param test_name: the name of the subdirectory... | 2af568e094b64a08a8b32afb702492e17c1f8fcb | 689,474 |
import string
import random
def gen_passwd(size: int) -> str:
"""Generate password for ray.init call.
See
https://docs.ray.io/en/latest/configure.html?highlight=security#redis-port-authentication
This function was adapted from https://stackoverflow.com/a/2257449
Example
-------
ray.init... | 570b185d650bac6f7bf60411dfc72a46d6151ec3 | 689,475 |
def socketread(socket, count, flags = None):
"""
Retry socket read until *count* amount of data received,
like reading from a file.
:param int count: the amount of data received
:param flags: socket.recv() related flags
"""
if not flags:
flags = 0
data = socket.recv(count, flags... | e09014ac863cb9463313074ec28afad438d104f3 | 689,476 |
def compare_extension(filename: str, expected_extension: str):
""" Compare the extension of the given file with the expected extension """
return filename.endswith(expected_extension) | c6021ec04fe287f70a3eadf7f977e8f29a6937fc | 689,478 |
import math
def distance(latOne, lonOne, latTwo, lonTwo):
"""
haversine formula
"""
R = 6371 # KM
latOneRadians = math.radians(latOne)
latTwoRadians = math.radians(latTwo)
latDistance = math.radians(latTwo-latOne)
lonDistance = math.radians(lonTwo-lonOne)
a = math.sin(latDista... | 62e7c75bcd9aeb1167ccee336298b71426d75f64 | 689,479 |
import json
def read_settings_file(file= "settings.json"):
"""Function to read the configuration file, settings.jsonself.
Parameters:
file (str): name of file.
Returns:
dict: Data from the json object.
"""
with open(file) as f:
data = json.load(f)
# 'Default' value for p... | f400d796f1ea1379e37bc2e4e2f8fd5f5e71a814 | 689,480 |
import hashlib
def md5(content):
"""
Generates md5 hash of content 2019-03-10
:param content: a data for md5 generation
:return: an md5 hash of a content
"""
hash_md5 = hashlib.md5()
hash_md5.update(content)
return hash_md5.hexdigest() | ee9a3dea80a83d2d503a160d2ed20681a1523eef | 689,481 |
def aprs_object_name(par):
"""
Return global name for the aprs object
"""
if "object_name" in par:
return par["object_name"].strip()
return par["from"] | f6b48edeeedb688ff9c44d316d6349c1ce667076 | 689,483 |
import json
def set_json_percentage(filepath, percentage) -> bool:
"""
Update the 'percentage' value in the JSON file.
Return TRUE if the update is successful and
return FALSE if the JSON file given is not found
"""
try:
with open(filepath, 'r+') as f:
json_data... | c66419a864e8ff515d37e8493be94937d9a1eb11 | 689,484 |
def bgr_skin(b, g, r):
"""Rule for skin pixel segmentation based on the paper 'RGB-H-CbCr Skin Colour Model for Human Face Detection'"""
e1 = bool((r > 95) and (g > 40) and (b > 20) and ((max(r, max(g, b)) - min(r, min(g, b))) > 15) and (
abs(int(r) - int(g)) > 15) and (r > g) and (r > b))
e2 =... | b6c048673966b5557555387bc466a6659fe79c2e | 689,485 |
import random
from time import gmtime, strftime
def generate_DOB(age=65):
"""Randomly generate a month & date for DOB """
birth_month = random.randint(1,12)
if birth_month == "1" or "3" or "5" or "7" or "8" or "10" or "12":
birth_day = random.randint(1,31)
if birth_month == "2":
birth_day = random... | 1bd23e352ff01a0287d6e13b16604f0896caa9cd | 689,487 |
def nts(s):
"""Convert a null-terminated string field to a python string.
"""
# Use the string up to the first null char.
p = s.find("\0")
if p == -1:
return s
return s[:p] | f93e11fd38e1f47e0e183e60a363d035a016b5c5 | 689,488 |
import pathlib
import yaml
def _load_yaml(stem, filename):
"""Provide utility to load yaml."""
ifile = pathlib.Path('') / stem / filename
with open(ifile, 'r+') as fp:
data = fp.read()
content = yaml.full_load(data)
return content | 8ba7f7ddaf2648da45281c36e12959a5a22ab8dc | 689,489 |
import uuid
def tei_bibl_id(domain=None):
"""
| generate uuid for @xml:id of TEI element <bibl> by given domain
| if domain is None a random uuid is being generated
"""
found = False
if domain is not None:
while not found:
domain_uuid = str(uuid.uuid3(uuid.NAMESPACE_URL, do... | e20868b6b43fd3f0a394f0953d648705da8ea1f0 | 689,490 |
def parse_csv_data(csv_filename: str) -> list:
"""Parses through a CSV file, reading and storing each line of the file.
Opens a csv file, assigning covid_csv_file to a list of all lines in the
file. For each line in the file, the newline character and the commas are
removed from the file, with each lin... | 4c7edfd0f06a796f43f7793e98c7174c60cf704d | 689,491 |
import os
def _find_file_path(name, path="../../.."):
""" this is a utility method. it resembles: find . -print | grep name
Parameters
----------
name: the file name we are looking
path: the relative path from current location
... | 5f8dabab4b30a814e5c94377ca4262a633e0b88c | 689,492 |
def get_iscam_mws(intensities, mw_intensity_line_pars=None):
"""
Calculate the molecular weights of the intensities with the line parameters
`mw_intensity_line_pars`
Parameters
----------
intensities : np.ndarray
inensities of an iscam measurements
mw_intensity_line_pars : array lik... | 9fdc17f17fe7341c9567e8626f025bac1c42d625 | 689,494 |
import logging
import os
import importlib
def create_email_sender(name, conf):
"""
Creates an email sender dynamically from a module name.
conf is a dictionary that will be passed to the class constructor as **conf.
"""
log = logging.getLogger("intogensm.smtp")
name = name.lower()
mfile = os.path.join(os... | d7cc5e94f997637c63548b909dbf8c5744889b3d | 689,495 |
import numpy
def generate_mapping(scale: float, feature_dim: int, map_dim: int, seed: int = 0):
"""
generate kernel mapping matrix and bias vector
"""
numpy.random.seed(seed)
bias = numpy.random.uniform(0, 2 * numpy.pi, map_dim)
matrix = numpy.sqrt(2 * scale) * numpy.random.normal(size=(featur... | af04ee6c5cad3ce4cd6e89ed50fbb5041c3f5c6f | 689,496 |
import torch
def torch_dot(x: torch.Tensor, y: torch.Tensor):
"""
Dot product of two tensors.
"""
return (x * y).sum(-1) | d250bb8a6f7e18cf55dbfaf32a6219b6e49582a2 | 689,497 |
def dottedToBinary(dottedString):
""" This function takes the dotted IP address and returns a 32 bit binary string
"""
binaryString=""
for octet in dottedString.split('.'):
# convert the int to a binary string - string manipulation to remove the 0b at beginning
binOctet=bin(int(octet))[2:]
# now to pad w... | f58020ec9a5289dfd7db2865f649416eb9584164 | 689,498 |
def _CheckTestDataReadmeUpdated(input_api, output_api):
"""
Checks to make sure the README.md file is updated when changing test files.
"""
test_data_dir = input_api.os_path.join('media', 'test', 'data')
readme_path = input_api.os_path.join('media', 'test', 'data', 'README.md')
test_files = []
readme_upda... | d2332b87137646e9eeda2ecca35b1e4f6c0e3125 | 689,499 |
def format_custom_attr(ddic):
"""
Format a dictionary of dictionaries in string format in the "custom attribute" syntax
e.g. custom="readingOrder {index:1;} structure {type:heading;}"
"""
s = ""
for k1, d2 in ddic.items():
if s:
s += " "
s += "%s" % k1
s2 = ""... | 9d52d9e2d90b36a0c9363f55655a073851ddd009 | 689,500 |
def parse_bitmask(text):
"""
Parse bitmasks like so:
- "0000 aaaa" (ridx: 3) => 0xf
- "0aaa aaaa" (ridx: 0) => 0x7f
- "0000 bbbb" (ridx: 3) => 0xf
"""
text = text.replace(" ", "")
last_zero = "".rfind("0")
p2 = 1 << (8 - last_zero)
return p2 - 1 | 71c75436e3ecd8fb1e102bd796d75353fb0786c5 | 689,501 |
import argparse
def parse_args():
"""
Parse the command line arguments and return an object representing the
command line (as returned by argparse's parse_args()).
Returns
-------
The argparse namespace.
"""
parser = argparse.ArgumentParser(description='Utility for exploring '
... | b7ea840006c126307e05a43362dbc16f345674e5 | 689,502 |
import re
def mark_quoted_strings(sql):
"""Mark all quoted strings in the SOQL by '@' and get them as params,
with respect to all escaped backslashes and quotes.
"""
pm_pattern = re.compile(r"'[^\\']*(?:\\[\\'][^\\']*)*'")
bs_pattern = re.compile(r"\\([\\'])")
out_pattern = re.compile("^[-!()*... | 22ddf388b9cfe9bece59a1718d4679a5f5d29aae | 689,503 |
def has_portfolio_applications(_user, portfolio=None, **_kwargs):
"""
If the portfolio exists and the user has access to applications
within the scoped portfolio, the user has access to the
portfolio landing page.
"""
if portfolio and portfolio.applications:
return True | ae94ced0c501a62c1841ce7dca6c45b2e061177c | 689,504 |
def eff_heat_pump(temp_diff, efficiency_intersect, m_slope=-.08, h_diff=10):
"""Calculate efficiency of heat pump
Parameters
----------
temp_diff: array
Temperature difference
efficiency_intersect : float,default=-0.08
Extrapolated intersect at temp diff of 10 degree (which is treat... | c2643af29cd3fd25968a9374e56082378987e2d6 | 689,505 |
def _reorder_lines(lines):
"""
Reorder lines so that the distance from the end of one to the beginning of
the next is minimised.
"""
x = 0
y = 0
new_lines = []
# treat the list of lines as a stack, off which we keep popping the best
# one to add next.
while lines:
# loo... | c96bc1b68726d2d8116f0e9a93c758754fedec05 | 689,506 |
def equally_sized_accessor(elements, n_variadic, n_preceding_simple,
n_preceding_variadic):
"""
Returns a starting position and a number of elements per variadic group
assuming equally-sized groups and the given numbers of preceding groups.
elements: a sequential container.
n_v... | fb724c9bf7b012472f76ada6181536bbaa2274f0 | 689,507 |
import argparse
def parse_cmdargs():
"""Parse command line arguments"""
parser = argparse.ArgumentParser("Train history plotter")
parser.add_argument(
'savedir',
metavar = 'MODEL_DIR',
type = str,
help = 'Model save directory'
)
parser.add_argument(
... | edc5b80dad7c9d8ddec5b9d6c7f401468b379f32 | 689,508 |
def _make_extra_string(s=''):
""" Create an extra function that just returns a constant string.
"""
def extra(attr, die, section_offset):
return s
return extra | 45a583d58214c622e035c297b9fe54289a785d4e | 689,509 |
import os
def get_full_path(root_folder):
""" Takes the name of a root folder and returns list of all the full name paths to each file"""
absolute_list = []
for dirpath,_,filenames in os.walk(root_folder):
for f in filenames:
absolute_list.append((os.path.abspath(os.path.join(dirpath, ... | 7326f4d133b89cb8f1a944ab9cadc269dacd8dfa | 689,510 |
def _gen_cmd_script(ppx, cookies, expected_out, expected_err, inparam, outfile, errfile, verbose):
"""Return shell commands for ppx preprocessing of file 'src'."""
return """
{ppx} \
{cookies} \
$@ \
-o $TEST_UNDECLARED_OUTPUTS_DIR/{stdout_file} \
{inparam} \
2> $TEST_UNDECLARED_OUTPUTS_DIR/{stderr_file}
if [[... | f5a8cb680bc34b70165494aa094cd750c7328a89 | 689,511 |
import re
def tr_title(paramWord: str) -> str:
"""
Türkçe harfler için title fonksiyonu
title() fonksiyonunda 'ı' ve 'i' harflerine yaşanan sorunlar sebebiyle hazırlanan metod.
:param paramWord: Sadece baş harflerinin büyük olması istenen string
:type paramWord: str
:rtype: str
:returns: Türkçe harfler de so... | ecb177981cbab81326655c709d2e7d6119b8ff39 | 689,512 |
def previous(field):
"""Generates s-expression to access a `field` previous value.
"""
return ["f", field, -1] | 77a346f18db87895cfd83464702b654114d55e69 | 689,514 |
def is_inside(x, y, window):
"""
Check if (x, y) is a valid coordinate in input window
Args:
x (int): x-coordinate
y (int): y-coordinate
window (face_spinner.Window): Window
Returns:
bool -> True if valid, False otherwise
"""
if window.x <= x < (window.x + windo... | 61667e218edb8d1474587d1579b06e44a32a4867 | 689,515 |
import itertools
def sawtooth_wave(amplitude=0.0125, frequency=440., sample_rate=44100.):
"""
Calculates a sawtooth-wave
:param amplitude: the amplitude of the wave
:param frequency: the frequency of the wave
:param sample_rate: the sample rate of the wave
:return: an infinite iterator of the ... | 9f48a9f5f92808329eea0fa75fd40fb1e4188876 | 689,519 |
def is_source_directory(src_count, files_count):
"""
Return True is this resource is a source directory with at least over 90% of
source code files at full depth.
"""
return src_count / files_count >= 0.9 | 5826aa4fe35dd513ddeea39311414acca4898cd8 | 689,520 |
def _prev_char(s: str, idx: int):
"""Returns the character from *s* at the position before *idx*
or None, if *idx* is zero.
"""
if idx <= 0:
return None
else:
return s[idx - 1] | aebcb183ea40f9916e07fa8d976754717829c836 | 689,522 |
def no_annotations(num: int, boolean: bool) -> None:
"""No arguments require annotations
>>> no_args(1, True)
None
"""
return None | d0cf43a48669c31d62e2226ce265d5775d4a5dc1 | 689,523 |
import difflib
def diff_difflib(a, b):
"""
WARNING! WARNING! WARNING! WARNING!
This code is really slow! Use only if you need a lot of precision
in the diff result! Use chunked_diff if precision is not what you
aim for.
WARNING! WARNING! WARNING! WARNING!
:param a: A string
... | 370ac2dbf8f11c0e27509097cb0c2e6c78228326 | 689,525 |
from typing import Sequence
from typing import Dict
from typing import Union
def get_instance_class_from_properties_seq(
instance_idx: Sequence, map_dict: Dict[str, Union[str, int]]) -> Sequence:
"""
Extract instance classes form mapping dict
Args:
instance_idx: instance ids present in se... | df0a6bf84e7e8580be2e4152c8e982184c26867d | 689,526 |
import os
def convert_csv_with_dialog_paths(csv_file):
"""
Converts CSV file with comma separated paths to filesystem paths.
:param csv_file:
:return:
"""
def convert_line_to_path(line):
file, dir = map(lambda x : x.strip(), line.split(","))
return os.path.join(dir, file)
... | f2af26daf2f61b9f871322f5510fb45da53cc0f1 | 689,527 |
def _item_to_value_identity(iterator, item):
"""An item to value transformer that returns the item un-changed."""
# pylint: disable=unused-argument
# We are conforming to the interface defined by Iterator.
return item | 07f15c861583196908a76e40646ad649da5f4922 | 689,528 |
import random
def cheat_pos(origin, factor=5):
"""
对原始点击坐标进行随机偏移,防止检测
:param origin:原始坐标
:param factor:偏移量
:return new:偏移后的坐标
"""
if origin is not None:
x, y = random.randint(-factor, factor), random.randint(-factor, factor)
new = (origin[0] + x, origin[1] + y)
retu... | 987dd10c89e1a52661534d741d5140790da55b18 | 689,529 |
def forecast_var(model_est_var, *args, **kwargs):
"""
Use historical data (0 to t) to forecast variance at t+1
via the model (defined in arch)
Args:
* args[0]: returns (numpy array or array): Returns for security.
Returns:
forecast variance: float
resid... | 2d926937342d914f47352df0c802d1146af4de24 | 689,530 |
import argparse
def _get_parser():
"""
Builds an ``argparse`` parser for the ``edotenv`` command line tool.
Returns
-------
:class:`argparse.ArgumentParser`
An ``argparse`` parser for ``edotenv``.
Example
-------
.. jupyter-execute::
:hide-output:
from edoten... | c61dbbd93d492300581b99d0b7a6403b951acfae | 689,531 |
import logging
def get_column_names(args):
"""Compile the column names for the output df.
:param args: cmd-line args parser
Return list of column names"""
logger = logging.getLogger(__name__)
logger.info("Compiling column names for the CSV output")
column_names = ["genbank_accession... | 8d6687fb33b58e54e6a367d94973d517f430a46d | 689,532 |
def lower(low, temp):
"""
:param low: int, the lowest temperature data before
:param temp: int, the new temperature data
:return: int, the lower one between high and temp, which becomes the lowest temperature
"""
if temp < low:
return temp
return low | 1ebb5d21ae8a4c5d745d80ab5560649bf04ba634 | 689,533 |
import os
def get_filename_and_extension(string_):
"""
Extracts and returns the file name and extension from a file path or file name
Args:
string_ (str): File path or file name
Returns:
'<filename>', '<extension>'
"""
assert isinstance(string_, str)
assert bool(string_), '... | 4d5ddccab88f9cbf6d6b9e894d07bf58fa0fb6f2 | 689,534 |
def get_A_roof_f_i(total_roof_area, dwelling_units):
"""階層fにおける単位住戸iの屋根面積…………式(8)
Args:
total_roof_area(float): 階層fにおける単位住戸の屋根面積の合計(m2)…………式(32)/get_total_roof_area
dwelling_units(float): 階層fにおける単位住戸iの総数(-)…………入力1.2(2)11
Returns:
float: 階層fにおける単位住戸iの屋根面積(m2)
"""
return total_ro... | f6dfa48f17e77407a74b9ea4f566bc05ac45a617 | 689,535 |
def get_first_line(filename, nlines=1):
"""return the first line of a file.
Arguments
---------
filename : string
The name of the file to be opened.
nlines : int
Number of lines to return.
Returns
-------
string
The first line(s) of the file.
"""
# U is to... | 384146c26d0dbe007951b91a67a8a6de89328241 | 689,536 |
def get_new_file_name(old_file_name):
"""传入旧的文件名,获取新的文件名"""
head,*tail = old_file_name #分配变量。head取出首字符,*tail取出剩余字符串. *tail表示很多单个变量,tail表示单个变量组成的列表
new_tail = "_my_" #新的字符串尾部
for j in tail:
new_tail = new_tail + j #依次取出每个字符,将它拼接到新的字符串尾部
new_file_name = head + new_tail #整合成新的文件名
return ne... | 633a4e19ff48f1693d1d4ac51fa60e3432bcc546 | 689,537 |
import sys
def load_class(classname: str) -> type:
"""
通过类名加载类
:param classname:
:return:
"""
class_path = classname.split('.')
module, classname = '.'.join(class_path[:-1]), class_path[-1]
__import__(module)
return getattr(sys.modules[module], classname) | 260b34592fd29c0bfa2d69f5238718ac6eeb4d39 | 689,538 |
def _IsBuildRunning(build_data):
"""Checks whether the build is in progress on buildbot.
Presence of currentStep element in build JSON indicates build is in progress.
Args:
build_data: A dictionary with build data, loaded from buildbot JSON API.
Returns:
True if build is in progress, otherwise False.... | 34b0f46e2fae86cb82a82c3e73c010f4517eb4ac | 689,539 |
import ipaddress
def search_prefix_list(ip, prefix_list):
"""
Check if IP address exists in some prefix which is part of `prefix_list`
`prefix_list` must be a list of tuples
Each tuple must be of form (ip_prefix_begin, ip_prefix_end) in int equivalent (check preparation step)
1. Convert IP to int ... | ae42cb909cb8b2d30eccbd2fbd0ad525206cacc4 | 689,540 |
def inches(f):
"""
inches(f)
Return f (in feet) converted to inches.
"""
return f * 12 | e764b7b4330a986e6e45b9bedcdf31533eff6751 | 689,541 |
def differ_in_at_most_one(first, second):
"""Check if two strings differ in at most one position."""
# Check if length differences make it possible
if abs(len(first) - len(second)) > 1:
return False
if len(first) > len(second):
longer, shorter = first, second
else:
longer, s... | a3b86958d0a03a459a7909651b193c0f09a0f7a6 | 689,542 |
import csv
def read_csv(file_name='data.csv'):
"""Returns a list of dicts from a csv file.
This is somewhat easier."""
with open(file_name) as f:
reader = csv.DictReader(f)
return [row for row in reader] | a85f39c0fe2e9a831ef1313d99a7e49e83a8e28f | 689,545 |
def parse_atrv(v):
"""
Parses the battery voltage and returns it in [Volt] as float with 1 decimal place
:param str v: e.g. "12.3V"
:return float:
"""
try:
return float(v.replace('V', ''))
except ValueError:
return None | 021f5ad69b7d2ec40d01d4f9b146e6c93fe52c8d | 689,547 |
def delayed_bamprep_merge(samples, run_parallel):
"""Perform a delayed merge on regional prepared BAM files.
"""
needs_merge = False
for data in samples:
if (data[0]["config"]["algorithm"].get("merge_bamprep", True) and
"combine" in data[0]):
needs_merge = True
... | de1945955e9e5da6c7479d90275b16b633b4924b | 689,548 |
import hashlib
import os
import json
def _read_cache(url):
"""
Read the local cache file that contains the previously downloaded JSON from URL.
:param url:
:return: JSON dictionary.
"""
j = None
m = hashlib.md5()
m.update(url)
if os.path.exists('.cache.%s' % m.hexdigest()):
... | f95db490ece43a425304d4ccad2301cbc423ec39 | 689,549 |
import copy
def add_values(w1, w2, update_keys):
"""
Returns topk weights.
"""
sum_w = copy.deepcopy(w1)
for key in sum_w.keys():
if key in update_keys and key in w2:
sum_w[key] += w2[key]
return sum_w | 30f49b8d5ee065cdec7c7a1a8f6ab6f36340eb3e | 689,550 |
def multiprocessing_func(fn_to_eval, random_var_gen, i):
"""Allows monte carlo to run on multiple CPUs."""
random_vars = random_var_gen(i)
result = fn_to_eval(*random_vars)
return result | a294d67359f5cbbd6cfa86224e62bff6330b9c5d | 689,552 |
from pathlib import Path
def is_within(parent, child) -> bool:
"""
Check that a path is within another.
"""
return Path(parent).resolve() in Path(child).resolve().parents | 04f0347663bcc380ca0100f177571c55e8b43e8e | 689,553 |
import sys
def build_user_agent() -> str:
"""Build a User-Agent to use in making requests."""
agent = 'DiscordBot (https://github.com/wumpyproject/wumpy, version: 0.0.1)'
agent += f" Python/{'.'.join([str(i) for i in sys.version_info])}"
return agent | 75afe3b1e39de50e95c3cb31c64f9ce5b90ab696 | 689,554 |
def is_retweet(source_tweet_json : dict):
"""
a temporary solution to load actual source tweet data from "retweeted_status" in our augmented dataset
:param source_tweet_json:
:return:
"""
return "retweeted_status" in source_tweet_json | 93364802002ac080e7ca4c6a48238b83080f7c00 | 689,555 |
import sys
import importlib
def get_pyextension_imports(module_name):
"""
Return list of modules required by binary (C/C++) Python extension.
Python extension files ends with .so (Unix) or .pyd (Windows). It is almost impossible to analyze binary extension
and its dependencies.
Module cannot be ... | 09178aa86fb8eeb3c48a7dab966b76e3564c2671 | 689,556 |
import torch
def rankdata_pt(b, tie_method='ordinal', dim=0):
"""
pytorch equivalent of scipy.stats.rankdata, GPU compatible.
:param b: torch.Tensor
The 1-D or 2-D tensor of values to be ranked. The tensor is first flattened
if tie_method is not 'ordinal'.
:param tie_method: s... | 88bd901c945d6ca9b3d2e785c6b0ea627116a03f | 689,557 |
def get_temp_var(used_vars):
"""get a temp variable name """
for i in range(0, 1000):
var_name = "t{}".format(i)
if var_name not in used_vars:
return var_name | cab07c74bf6807a72b4968deb6d49e31f85df3d6 | 689,558 |
def getCoinbaseAddr (node, blockHash):
"""
Extract the coinbase tx' payout address for the given block.
"""
blockData = node.getblock (blockHash)
txn = blockData['tx']
assert len (txn) >= 1
txData = node.getrawtransaction (txn[0], True, blockHash)
assert len (txData['vout']) >= 1 and l... | 12e87ecde415d013935a060b7008ddd4056c76c8 | 689,559 |
def get_children(obj, key=None):
"""
:param bpy.types.Object obj:
:param callable key:
Function for sorting children
(default=None: sorting by names)
:return:
:rtype: list[bpy.types.Object]
"""
fn = (lambda c: c.name) if key is None else key
return sorted(obj.children, k... | e9cf031d870a841267057a49d6765675518d8388 | 689,560 |
import time
def format_ampm(time_24hour) -> str:
"""Convert 24 hour to 12 hour system"""
t = time.strptime(time_24hour, "%H%M") # Create time object
timevalue_12hour = time.strftime("%-I:%M %p", t) # e.g. From 08:14 to 8:14 AM or 15:24 to 3:24 PM
return timevalue_12hour | 2e4852ba060df38b59f704610098c665d606d320 | 689,561 |
import os
import sys
def setup_filepaths(organism):
"""Setup full file paths for functional net and BIOGRID"""
if organism == 'cerevisiae':
biogridpath = os.path.join('..', 'data',
'BIOGRID-3.4.130-yeast-post2006.txt')
fnetpath = os.path.join('..', 'data', 'YeastNetDataFrame.p... | 9bc4e5595b7f93f76ec3fd76fec16927f98358b8 | 689,563 |
def all_filled(board):
"""
Returns True if all board is filled, False otherwise.
"""
for i in range(len(board)):
if board[i].count(None):
return False
return True | 2b3acc1b32630c0a7232ac9eb88691a61cbce0c0 | 689,564 |
def cint(obj):
"""
Interprets an object as a integer value.
:param obj:
:return:
"""
if isinstance(obj, str):
obj = obj.strip().lower()
try:
return int(obj)
except ValueError:
raise ValueError('Unable to interpret value "%s" as integer' % obj)
elif obj is None:
return obj
re... | 6e5ae2c6ac7b94b48454c619283c43a2f643918e | 689,565 |
import struct
def decode_ieee(val_int):
"""Decode Python int (32 bits integer) as an IEEE single precision format
Support NaN.
:param val_int: a 32 bit integer as an int Python value
:type val_int: int
:returns: float result
:rtype: float
"""
return struct.unpack(... | ce86bd855466adaab8b2bae2fa76e9f76526aa91 | 689,566 |
import re
def typeset_chemical(s: str) -> str:
"""
Typesets chemical formulas using Latex.
Parameters
----------
s : str
Input string
Returns
-------
str
Output string with chemical formulas typeset correctly
"""
parts = []
for n in re.sub(r'[A-Z]_\d', r... | 4a40675c9eef7480f40985cb4563ce38373e0c59 | 689,567 |
import torch
def log1p_exp(input_tensor):
""" Computationally stable function for computing log(1+exp(x)).
"""
x = input_tensor * input_tensor.ge(0).to(torch.float32)
res = x + torch.log1p(torch.exp(-torch.abs(input_tensor)))
return res | 788addfb31f05b193d4c4fe8e0563e98d123fbe7 | 689,568 |
def jacobian_f(f):
"""
This function aims to compute the Jacobian of any given MX function
input: MX function
output: Jacobian
"""
F_x = f.jacobian()
return F_x | 0dff3d5ed9d85dd27671bbf249569c96a2153fcd | 689,569 |
from typing import OrderedDict
def tuples_as_dict(_list):
"""Translate a list of tuples to OrderedDict with key and val as strings.
Parameters
----------
_list : list of tuples
Returns
-------
collections.OrderedDict
Example
-------
::
>>> tuples_as_dict([('cmd', 'v... | f7e3b3b829e91d903cca504e1597404f4e1a2ab2 | 689,570 |
def find_adjacent_segment_type(segments, time):
"""Find boundary type on left and right (NONSPEECH or SPEECH)"""
# find previous segment type
segments[0].append("NS")
prev = segments[0]
for i in range(1, len(segments)):
if (segments[i][0] - time) > prev[2]:
segments[i].append("NS... | 1cc7ea22d5314eb3c5780612119c103ddb59dd0c | 689,571 |
import math
def get_elapsed_time(start, end):
"""
Compute elapsed time.
@param start: start time
@param end: end time
@return: elapsed time (string)
"""
diff = end - start
days, hours, minutes = [0, 0, 0]
s_time = []
if diff > 86400: # day
days = math.floor(dif... | 4fd67b646876d098cc87d1f3fe9fdc264afd9828 | 689,572 |
def detect_internals(pstart, pend, hit_start, hit_end):
"""[Local] Check for internal features (for 'genomic_location' column, independent of users key option) """
feat_in_peak = (pstart < hit_start and hit_end < pend)
peak_in_feat = (hit_start < pstart and pend < hit_end)
if feat_in_peak:
ret... | 67d32888676f88699f5354affa14e5a0c8b1e429 | 689,573 |
import asyncio
def async_test(test):
"""
Decorator to run async test methods.
"""
def wrapper(*args, **kwargs):
asyncio.run(test(*args, **kwargs))
return wrapper | b03c10f6b16fb7af148d21a89f1d3485b4fe4681 | 689,574 |
def suit_form_field_placeholder(field, placeholder):
"""
Get CSS class for field by widget name, for easier styling
"""
field.field.widget.attrs['placeholder'] = placeholder
return field | d2199376857bdc187a13ba8444559c9c21b2d3e3 | 689,575 |
def _is_asc(filename):
"""
Checks whether a file is a Seismic Handler ASCII file or not.
:type filename: str
:param filename: Name of the ASCII file to be checked.
:rtype: bool
:return: ``True`` if a Seismic Handler ASCII file.
.. rubric:: Example
>>> _is_asc("/path/to/QFILE-TEST-ASC.... | 23fcd22eabf42ad36c905c8774ae6ea277ed8194 | 689,577 |
import itertools
def flatten(sequence_list, cls=list):
"""
Flatten one level of nesting
:param sequence_list: list of sequence
:param cls: create instance of cls by flatten_gen
:return: cls instance or generator
"""
flatten_gen = itertools.chain.from_iterable(sequence_list)
return cls(... | 2e28b9c44b26f6749dfa8f02337aacaf2e74adc5 | 689,578 |
import os
def get_files_of_a_type(root_path, file_extension='.mat'):
"""
Recursively traverses from root_path to find all files ending
in a given extension (e.g. '.mat')
Parameters
-----------------------
root_path: string
The absolute path to start searching from
file_extension: ... | e06d1268773733584556f9d487db995888221c96 | 689,580 |
def camel_case(string):
"""Makes a string camelCase
:param string: String to convert
"""
return ''.join((string[0].lower(), string[1:])) | cb4da0c974dc41d11b1174876e6ff4d8f378f770 | 689,581 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.