content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def generate_path(altitude_data):
"""
generates the path for the uphill/downhill/flat detection
:param altitude_data: the altitude data
:return: the string to write to the KML file
"""
# various strings for building the KML output
open_placemark = '<Placemark> '
open_line = """
<LineSt... | f6892e6a1a47c5afcd0a66ee3ac4d3151b7ceab3 | 679,246 |
def byte2str(_bytes):
"""
bytes to str
:param _bytes:
:return:
"""
return str(_bytes, encoding="utf-8") | 1064772aabeac3d63810dadd9ebc5dcbfa211f11 | 679,247 |
def check_contains(line, name):
"""
Check if the value field for REQUIRE_DISTRO contains the given name.
@param name line The REQUIRE_DISTRO line
@param name name The name to look for in the value field of the line.
"""
try:
(label, distros) = line.split(":")
return name in distros.split()
except ... | 6f977e35b97ccb07be28e033840dac1e53734cb0 | 679,248 |
import os
def get_data(path):
"""
获取人工打分结果和原始输入数据
:param path: 含有input和golden文件的路径
:return:golden文件内容&input文件内容
"""
path = os.path.join(path)
golden_file = os.path.join(path, 'golden.txt')
input_file = os.path.join(path, 'input.txt')
with open(golden_file, 'r') as f:
g_cont... | 2c937256c07c7437aad085011fb68d2cccab623f | 679,249 |
import grp
def check_gid(val):
"""Return a gid, given a group value
If the group value is unknown, raises a ValueError.
"""
if isinstance(val, int):
try:
grp.getgrgid(val)
return val
except (KeyError, OverflowError):
raise ValueError("No such group:... | 01f7c6c75a9055872d659f64bafc20e4cc8d3151 | 679,250 |
import re
def check_summary_worthy(x, tokenizer,
min_length=50,
max_length=90,
max_symbols=0,
max_tridots=0):
"""
Check whether the review x is summary-worthy or not.
"""
x = tokenizer.decode(x)
x = x.repl... | 248673edf3cb4d5fa3bf6f5bf2ebe81d446809db | 679,251 |
import os
import configparser
def _get_galaxy_tool_info(galaxy_base):
"""Retrieve Galaxy tool-data information from defaults or galaxy config file.
"""
ini_file = os.path.join(galaxy_base, "universe_wsgi.ini")
info = {"tool_data_table_config_path": os.path.join(galaxy_base, "tool_data_table_conf.xml")... | 62bfb14a6beb0732ef6a8e51b485b352c9ca4080 | 679,252 |
def _increment_if_zero(M, pos, zero_count):
"""
:param M: matrix
:param pos: 2 tuple (row, column)
:param zero_count: dictionary of row and column zero counts
:return: updated zero_count
"""
# short circuit
v = M[pos[0], pos[1]]
zero_count['row'][pos[0]] += 1 if v == 0 else 0
ze... | a8545cb6a09cc3d8368003387f051ca2f0a26709 | 679,253 |
def Usable(entity_type, entity_ids_arr):
"""Nmap must be accessible"""
return True | 81554186af38a7e71868b8a72f49983f2f4f0fc9 | 679,255 |
def ignition_delay(states, species):
"""
This function computes the ignition delay from the occurrence of the
peak in species' concentration.
"""
i_ign = states(species).Y.argmax()
return states.t[i_ign] | 5abcbebbff401cd5f6f9ab9634edcf344cbea41d | 679,256 |
import configparser
import ast
def read_config():
""" assuming all values are set properly, missing data etc can be handled
later """
config = configparser.ConfigParser()
config.read('config.ini')
endpoints = ast.literal_eval(config.get('steem-blockchain', 'endpoints'))
hostname = config.g... | 62e9f052fe3c2bea8bc27b152bcd8ddd346680f9 | 679,257 |
def checksum_tle_line(_line):
""" Performs TLE-defined checksum on TLE line"""
check = 0
for char in _line[:-1]:
if char.isdigit():
check += int(char)
if char == "-":
check += 1
_check_val = check % 10
return(_check_val) | 7a39f5c6be38d4ba2a7aa8118d74a98dbc683d2a | 679,258 |
import numpy
def success_rate(model,target,img_size,discrepancy_threshold,success_threshold=70):
"""
Number of reconstructed images for which 70% (or the percentage defined by the success_threshold argument) of the pixels are 90% similar.
"""
# Set model to evaluation mode
model.eval()
# Execu... | 5452fb127303ddcee27f3549ff0b9e831a1ddce0 | 679,259 |
import numpy
def sum_ordered(addends, problems):
"""
Sums the given addends, starting by the smallest and following the natural order.
"""
result = numpy.float16(0)
for addend in sorted(addends):
if numpy.isnan(addend):
problems.append("NaN")
elif numpy.isposinf(addend)... | 3b7f21e55b66b4180d4757dbca3bd5c08267754e | 679,260 |
def average_tweets_per_user(tweets, users_with_freq):
"""
Return the average number of tweets per user from a list of tweets.
:param tweets: the list of tweets.
:param users_with_freq: a Counter of usernames with the number of tweets in 'tweets' from each user.
:return: float. average number ... | f2fc5b725003b39a5e429a4945007fbb16640b54 | 679,261 |
import torch
def cross_entropy_soft_targets(predicted_distribution, target_distribution):
"""Cross entropy loss with soft targets.
B = batch size, D = dimension of target (num classes), N = ensemble size
Args:
inputs (torch.tensor((B, D - 1))): predicted distribution
soft_target (torch.te... | 4c142ae3ab9440bd5a5456ce70f6b4493cc89256 | 679,264 |
def id_conflict(required_tiles, flanking, all_variable: list):
"""
search for the positions of snps that collide with other snps in the user defined k-mer window
Parameters
----------
required_tiles: list
position information of all snps that support groups
flanking: int
size of ... | 5908c0b97b33a0fbe2efc970655714b948dfa0e0 | 679,265 |
import math
def pwr_list_elements(in_list, populationSet=True):
"""
Return mean power of list elements (= mean**2 + std**2)
When population is True divide by len(in_list) to get the standard deviation of a complete set,
else divide by len(in_list)-1 to get the standard deviation for a sample of a... | 85a211a8f0837f0df355b7f3308eaaf50677ac25 | 679,266 |
import csv
def loadGrabbers(fname="grabbers.csv"):
"""
Read a CSV file and return contents as a list of dictionaries.
"""
columns = ["ID", "call", "title", "name", "loc", "site", "url"]
grabbers = []
with open(fname) as f:
reader = csv.reader(f, delimiter=",", quotechar='"')
fo... | e0472382ec4547bc53ab5d3c2d8aa3cc48ba64d3 | 679,268 |
def make_car(manufacturer, model, **car_info):
"""Build a dictionary containing information about a car."""
car_info['manufacturer_name'] = manufacturer
car_info['model_name'] = model
return car_info | 01db04acdbfea8d4604d82ee6246f18afc147b51 | 679,269 |
from typing import List
def split_into_lists(input_list: List, target_number_of_lists: int) -> List[List]:
"""
Evenly splits list into n lists.
E.g split_into_lists([1,2,3,4], 4) returns [[1], [2], [3], [4]].
:param input_list: object to split
:param target_number_of_lists: how many lists to spli... | daf9bcad6d86d3654c36bca15f1c9943acb21159 | 679,270 |
def get_job(api, job_id):
"""Get a Borgy job."""
return api.v1_jobs_job_id_get(job_id) | 70b537d6067417479e33d4d9b38f4291af6c1ccb | 679,271 |
import requests
def get_json_from_query(location):
"""Search for a city and return metadata from API"""
url = f"https://www.metaweather.com/api/location/search/?query={location}"
r = requests.get(url).json()
return r[0] | 281c7d8f3f3b6bb92bf4bdb5d76dd3f3c4499143 | 679,272 |
def available(func):
"""A decorator to indicate that a method on the adapter will be exposed to
the database wrapper, and the model name will be injected into the
arguments.
"""
func._is_available_ = True
func._model_name_ = True
return func | 9691f87341cfb2e8560bcdb6c3a5b0c05ea560cc | 679,273 |
def is_punkt(token):
"""
Return if token consists of only punctuation and whitespace
Args:
token: single token
Returns:
Boolean
Raises:
None
Examples:
>>> is_punkt(" ")
True
>>> is_punkt(", ,")
True
>>> is_punkt("?!!")
True
... | 07da56563f7a11a3c6899dd6f3f4bc941338bff4 | 679,274 |
from typing import List
def segments(consent: str) -> List[str]:
"""Helper to split the core and non core consents."""
return consent.split(".") | 820909fadd7018dc919930667c9829337880926b | 679,275 |
def human_size(s, factor):
"""
:s: size
:factor: 1000 or 1024
"""
unit = 'B'
if s > factor:
s /= factor
unit = 'KB'
if s > factor:
s /= factor
unit = 'MB'
if s > factor:
s /= factor
unit = 'GB'
if s > factor:
s /= factor
... | 3a7ce617f3dcdb167720eaaebb6dc18f1066d869 | 679,276 |
def build_hashes():
"""Provides the hashes for files in build_path."""
return (
'7c211433f02071597741e6ff5a8ea34789abbf43',
'aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d',
) | 203bcbda26c1d109d899691ba70b5c04ef616d0d | 679,277 |
def movie_sort(movies):
"""Sorts a list of movies by their release date using bubble sort.
Args:
movies: a list of movies.
Returns:
A sorted list of movies.
"""
sorted_movies = movies.copy()
swapped = True
while swapped:
swapped = False
for i in range(1, len... | ef1399f7af77ad9ef8dc3e5a4d4c2b0d93c119ff | 679,278 |
def _MachineTypeMemoryToCell(machine_type):
"""Returns the memory of the given machine type in GB."""
memory = machine_type.get('memoryMb')
if memory:
return '{0:5.2f}'.format(memory / 2.0 ** 10)
else:
return '' | 56f94624a57af80887dae0a38ec88ed1bbf324ad | 679,279 |
def xor_hex_strings(bytes_a, bytes_b):
# type: (str, str) -> str
"""Given two hex strings of equal length, return a hex string with
the bitwise xor of the two hex strings."""
assert len(bytes_a) == len(bytes_b)
return ''.join(["%x" % (int(x, 16) ^ int(y, 16))
for x, y in zip(byte... | 7031b25da743c0a9b4de517c6c4d24606345ee8e | 679,280 |
import re
import json
def read_job_properties(jobscript,
prefix="# properties",
pattern=re.compile("# properties = (.*)")):
"""Read the job properties defined in a snakemake jobscript.
This function is a helper for writing custom wrappers for the
snakemake ... | ea81eec9dfc9bbfe65c19c5f3169e7568300aecb | 679,282 |
def solve(input):
"""Solve the puzzle."""
return int(input/3)-2 | 6a4c7fea5d17a4ab736bab850b108dcf13111401 | 679,284 |
import sys
def allowcustom():
"""Helper for backups.py to determine if custom backup code should be run
"""
return any(x in ['--custom', '--all'] for x in sys.argv) | da7ff53277ac638504afaf88f2b24b877a323f4f | 679,285 |
import argparse
def get_default_experiment_parser():
"""
Construct an argument parser with many options to run experiments.
Returns:
argparse.ArgumentParser: The argument parser.
"""
parser = argparse.ArgumentParser()
parser.add_argument("base_dir", type=str, help="Working directory... | 11d93384f5a3dc06cc8e089c1b50b21f4050d73f | 679,286 |
def is_owned_by(self, user_or_token):
"""Generic ownership logic for any `skyportal` ORM model.
Models with complicated ownership logic should implement their own method
instead of adding too many additional conditions here.
"""
if hasattr(self, 'tokens'):
return user_or_token in self.token... | 61c0599e355f25607765a4ca12aaefca1268eadb | 679,287 |
def map_cluster(dp_means_cluster, mol_id_list):
"""
:param dp_means_cluster:
:param mol_id_list:
:return:
"""
out_dict = {}
for cluster in dp_means_cluster.clusters:
out_dict[cluster] = {
"centre_of_mass": dp_means_cluster.clusters[cluster],
"mol_ids": [],
... | 4ece9b26a956064090dbd83344598680c863f55b | 679,288 |
def bbox_flip(bboxes, img_shape, direction='horizontal'):
"""Flip bboxes horizontally or vertically.
Args:
bboxes (Tensor): Shape (..., 4*k)
img_shape (tuple): Image shape.
direction (str): Flip direction, options are "horizontal", "vertical",
"diagonal". Default: "horizonta... | b4354ec263f043a74bc28eca4852814d42c8a04d | 679,289 |
def Dic_Extract_By_Subkeylist(indic,keylist):
"""
Return a new dic by extracting the key/value paris present in keylist
"""
outdic={}
for key in keylist:
try:
outdic[key]=indic[key]
except KeyError:
raise KeyError("input key {0} not present!".format(key))
... | a0ac2c9ee28de9fc8cabfb05f37b57009841b03b | 679,290 |
def shiftCoordsForHeight(s):
"""
Shift with height s
origin = 0,0
"""
coords = (
( # path
(s/2,s), (0,s*4/9), (s*4/15,s*4/9), (s*4/15,0),
(s*11/15,0), (s*11/15,s*4/9), (s,s*4/9),
),
)
return coords | 687f48c0a6bf95484ce6342e21701d4cffbf5364 | 679,291 |
def sanitize_cfn_resource_name(name):
""" Sets Logical Name in CloudFormation """
name = ''.join([n.title() for n in name.split('-')])
return name | 757ffb377b37c59188a51b71fc40042086ce0191 | 679,293 |
import six
def generate_duid(mac):
"""DUID is consisted of 10 hex numbers.
0x00 + mac with last 3 hex + mac with 6 hex
"""
valid = mac and isinstance(mac, six.string_types)
if not valid:
raise ValueError("Invalid argument was passed")
return "00:" + mac[9:] + ":" + mac | 264e32d5ce37d4af1096cf1ab5f258016258bc0a | 679,294 |
def canonicalize_tensor_name(name):
"""Canonicalizes tensor names.
For an op that produces only one output, we may be refer to its output tensor
as either "op_name:0" or simply "op_name". This standardizes all internal
names as "op_name:0" to simplify the logic.
Args:
name: Input name to canonicalize.
... | 5f32572372d9ad6a69f7f9991d2cd8beae3f3d07 | 679,295 |
def _get_header(request_type):
"""Returns header str for talking with cosmos
:param request_type: name of specified request (ie uninstall-request)
:type request_type: str
:returns: header information
:rtype: str
"""
return ("application/vnd.dcos.package.{}+json;"
"charset=utf-8... | 9cb0f296455b78ef522a2797d7a07046853d11c8 | 679,296 |
def strip_html_comments(text):
"""Strip HTML comments from a unicode string."""
lines = text.splitlines(True) # preserve line endings.
# Remove HTML comments (which we only allow to take a special form).
new_lines = [line for line in lines if not line.startswith("<!--")]
return "".join(new_lines) | 289ab694a1fa2a6c9a1f60e0ead8b13e62a0bff0 | 679,297 |
import torch
def matrix_to_cartesian(batch: torch.Tensor, keep_square: bool = False) -> torch.Tensor:
"""
Transforms a matrix for a homogeneous transformation back to cartesian
coordinates.
Args:
batch: the batch oif matrices to convert back
keep_square: if False: returns a NDIM x NDI... | 3147a7d04b01f36a42b385de45676fa1ddad4581 | 679,298 |
def _recur_children(node):
"""
Recursive through node to when it has multiple children
"""
if len(node.getchildren()) == 0:
parts = (
([node.text or ""] + [node.tail or ""])
if (node.tag != "label" and node.tag != "sup")
else ([node.tail or ""])
)
... | aab24e27eac22032cb7f4823eaadf1340d97ce4d | 679,301 |
import requests
import ssl
import base64
def get_digest_base64(location):
"""Download the sha256sum.txt message digest file at the given
`location`.
:return: A `string` of the base64-encoded message digest
"""
res = requests.get(location,
verify=ssl.get_default_verify_paths().opens... | 3b54eb3fe3099892bf1bcd0d5c3dc6891951feeb | 679,303 |
def _is_inline_update(job):
"""This returns true if the job contains an inline update"""
if not job.metadata.get('update'):
return False
return job.metadata["update"].inline_query | 67e99413dfeb3aee28c13458cb7f7769155cb77b | 679,305 |
def _note(item):
"""Handle secure note entries
Returns: title, username, password, url, notes
"""
return f"{item['name']} - Secure Note", "", "", "", item.get('notes', '') or "" | 4bb92b4de36842753c650b77196bb48629b73246 | 679,307 |
import unicodedata
def remove_accentuated(s):
"""Removes accentuated chars and lower case
"""
s = ''.join(c for c in unicodedata.normalize('NFD', s.lower()) if unicodedata.category(c) != 'Mn')
return s | 7d17863f3ead81ff4839f897abe6f9f69ae3a6ad | 679,308 |
def get_filters(filters):
"""Return the rsync options for the given filters."""
arguments = []
for filter_ in filters:
if len(filter_) > 1:
raise Exception(
"Filter must contain only one entry: {}".format(filter_))
if "exclude" in filter_:
argumen... | 7704c7fe440fe93c392a8a1d37d31f336eb3e5b0 | 679,309 |
def _replace_words(replacements, string):
"""Replace words with corresponding values in replacements dict.
Words must be separated by spaces or newlines.
"""
output_lines = []
for line in string.split('\n'):
output_words = []
for word in line.split(' '):
new_word = repla... | db7afda0aeece6d40a2f6f89c4de52afd68ca87e | 679,310 |
def continue_crawl(search_history, target_url, max_steps = 25):
"""
Determines whether or not we should keep crawling
search_history: is a list of strings which are urls of Wikipedia
articles. The last item in the list is the most
recently found url.
... | 1d7aef1ac18e186c4b60b317386d51490b01470a | 679,311 |
def describe_load_balancer_types(policies, **kwargs):
"""
Describe the policies with policy details.
:param policies:
:return:
"""
return kwargs['client'].describe_load_balancer_policy_types(PolicyTypeNames=policies) | 9120340480c30df335205fc6f14da6103fa3c6b3 | 679,312 |
def agg_event_role_tpfpfn_stats(pred_records, gold_records, role_num):
"""
Aggregate TP,FP,FN statistics for a single event prediction of one instance.
A pred_records should be formated as
[(Record Index)
((Role Index)
argument 1, ...
), ...
], where argument 1 should sup... | c646111aa11122ca94b0bc4d181a260d4a1a4caf | 679,313 |
def converge(n):
"""Function to represent non-converging areas of the continuation space"""
centre1 = [9,10]
centre2 = [6,2]
centre3 = [2,12]
r1 = 4
r2 = 4
r3 = 4
if (n.ind[0]-centre1[0])**2 + (n.ind[1]-centre1[1])**2 < r1**2:
return 0
if (n.ind[0]-centre2[0])**2 + (n.ind[1]-... | aaff09fb299a1d8ac11f1e56747c3547719a36de | 679,314 |
import subprocess
def test(name):
"""Test a single playbook."""
print('testing', name, end='... ', flush=True)
program = f"""- hosts: all
become: no
gather_facts: no
tasks:
- include_tasks: playbooks/measurements/{name}
"""
with open('temp.yml', 'w') as f:
f.write(program)
run = ... | 2e23c477b68ae2feb8fcb0fbe4f0baeb2a4b3cb3 | 679,315 |
def odd(number):
""" Returns True if number is odd """
return number % 2 == 1 | 5f8030f59f48b0c5662006a7facfe6f4c174a743 | 679,317 |
def reverse(current_block, *args):
"""Reverses the data of the current block."""
return current_block[::-1] | 1e7c2529123fd97916120ed53b46f819642ea586 | 679,318 |
from typing import Optional
def frame_index_to_seconds(
frame_index: int, fps: int, zero_indexed: Optional[bool] = True
) -> float:
"""Converts a frame index within a video clip to the corresponding
point in time (in seconds) within the video, based on a specified frame rate.
Args:
frame_inde... | 5cceab326ee446825f758b1d717d41775c769c10 | 679,319 |
def escape_special(v):
""" Escape literal bools and None as strings.
"""
if v is True or v is False or v is None:
return str(v)
else:
return v | 72666184a65fbdf8aaa4371945e127128729db39 | 679,320 |
def get_params_or_defaults(params, defaults):
"""Returns params.update(default) restricted to default keys."""
merged = {
key: params.get(key, default)
for key, default in defaults.items()
}
return merged | 44ae50a399d90298bab5d445b92cf1f317e59275 | 679,321 |
def tuple_set(base, values, indices):
"""
Creates a new tuple with the given values put at indices and otherwise the same as base. The
list of indices must be in sorted order.
"""
new = base[:indices[0]]
for i in range(len(indices)-1):
new += (values[i],) + base[indices[i]+1:indices[i+1]... | 6f594cf189d71754e024f4770ad516f889ad7921 | 679,322 |
def alter_context(context):
""" Modify the context and return it """
# An extra variable
context['ADD'] = '127'
return context | 286e18ae53c1849fb0fcd4231cd0e125d2ecc2ee | 679,323 |
def hass_time_zone():
"""Return default hass timezone."""
return "US/Pacific" | 7adda8ada2433bc988eb8709c729eb54f6a7016b | 679,324 |
def table_to_list(table_name, engine):
"""
Take sqlite table and return a mongoDB bulk insertable list
table_name: name of table to acquire from sqlite db
engine: cursor from sqlite3 connection
"""
query = f"""
SELECT * FROM {table_name}
"""
result = engine.execute(query).fetchall(... | bb59a8d97bbd882b14a01fd60912b4caf599eefa | 679,325 |
def get_all_context_names(context_num):
"""Based on the nucleotide base context number, return
a list of strings representing each context.
Parameters
----------
context_num : int
number representing the amount of nucleotide base context to use.
Returns
-------
a list of st... | 94de6fbad73d25ef242b4e2f6b0f378baa17aaf4 | 679,326 |
import pickle
def get_password():
"""Get pickled password and username"""
with open("login.pickle", "rb") as f:
login = pickle.load(f)
username = login["username"]
password = login["password"]
return username, password | 7f4aa180a18ab6e1dc0c8bd6da8fd5fe1616d146 | 679,327 |
import socket
import os
import logging
def getSyncCE():
"""
_getSyncCE_
Extract the SyncCE from GLOBUS_GRAM_JOB_CONTACT if available for OSG,
otherwise broker info for LCG
"""
result = socket.gethostname()
if 'GLOBUS_GRAM_JOB_CONTACT' in os.environ:
# //
# // OSG, Sync ... | 92603900fc4de77153251e0f9e36d9374dfdb59b | 679,328 |
def is_valid_ip(ip):
"""
Check if IP address is valid
:param ip: IP address
:return: Is valid
"""
ip = ip.split(".")
if len(ip) != 4:
return False
return all([0 <= int(t) <= 255 for t in ip]) | 35ae6f11928cabacb61611526c3cff26b179c1a4 | 679,329 |
def split_rows_by_condition(df, mask):
"""Split dataframe based on logical indexes (that could come from a condition).
Args:
df (pd.DataFrame): Dataframe.
mask (pd.Series): Series with boolean indexes (could come from a condition).
Returns:
list: List of split dataframes.
... | 6241207ae59c76d2105af3dd90c8673b8c8ba166 | 679,330 |
def celcius(temperature):
"""Converts a temperature from degrees Kelvin to degrees Celcius."""
return temperature - 273.15 | 71dd3704ecba33cfec39e7b62bdc9b7b8ef7160d | 679,332 |
def filter_label(label, replace_by_similar=True):
"""Some labels currently don't work together because of LaTeX naming
clashes. Those will be replaced by simple strings."""
bad_names = [
"celsius",
"degree",
"ohm",
"venus",
"mars",
"astrosun",
"fullmoo... | c478cb6945f4e9ea5b5738ed2236f5b7187006a7 | 679,334 |
def config2action(config):
"""flatten config into list"""
enc_config, dec_config = config
action = enc_config.copy()
for block in dec_config:
action += block
return action | 01ee2124f4982cb8750a1a21d2ce442e4e65ca9b | 679,335 |
def mplt_bars(ax, ticks, values, colors, ylabel=None, title=None):
"""Quick function for creating stacked matplotlib barplot"""
bar0 = ax.bar(ticks, values[0], color=colors[0])
bar1 = ax.bar(ticks, values[1], bottom=values[0], color=colors[1])
if ylabel is not None:
ax.set_ylabel(ylabel)
if ... | 2ab89435eee20aeedbaf7232fc5fc297a26e4e48 | 679,336 |
def _tag_tuple(revision_string):
"""convert a revision number or branch number into a tuple of integers"""
if revision_string:
t = [int(x) for x in revision_string.split('.')]
l = len(t)
if l == 1:
return ()
if l > 2 and t[-2] == 0 and l % 2 == 0:
del t[-2]
return tuple(t)
return (... | e6f1b6111dd5e95ba9009e6593d580afa7203c0b | 679,337 |
def _dummy_jit(*args, **kwargs):
"""Dummy wrapper for jitting if numba not applicable."""
def wrapper(f):
return f
def marker(*args, **kwargs):
return marker
if (
len(args) > 0
and (args[0] is marker or not callable(args[0]))
or len(kwargs) > 0
):
r... | 5086aa26c7d49a1e2f3d7b13a39e793040470292 | 679,338 |
def indentLevel(line):
"""Returns the indentation level of a line, defined in Piklisp as the number of leading tabs."""
for i in range(len(line)):
if line[i] != "\t":
return i # i characters were "\t" before lines[i]
return None | b95c1adf499336ef33e68bfc89daf2b34d2013da | 679,339 |
import math
def exponential_decay(now_step, total_step, final_value, rate):
"""exponential decay scheduler"""
decay = math.exp(math.log(final_value)/total_step ** rate)
return max(final_value, 1 * decay ** (now_step ** rate)) | 1a2130a9e41fa1cec1de6e6f52734e5fa2cccbc3 | 679,340 |
def marker_cell_identifier(marker_region, cells):
"""Return cell identifier of marker region."""
pos = marker_region.convex_hull.centroid
return cells[pos] | dae7848f2dd99e942925fdfda625a445912a065b | 679,341 |
def get_synapse_data_by_contin(cur,contin):
"""
Returns synapse data for given contin
Each row is a single section of the synapse
Row format: [section_number,preobj,[post_obj]]
Parameters:
-----------
cur : MySQLdb cursor
contin : str
Contin number
"""
sql = ("select IMG... | 206feed563ab32324cbbe48e6c69389f811c741c | 679,342 |
def bind(context, block=False):
"""
Given the context, returns a decorator wrapper;
the binder replaces the wrapped func with the
value from the context OR puts this function in
the context with the name.
"""
if block:
def decorate(func):
name = func.__name__.replace('__... | a81678340f7a57c9332da34fa6a1de9407e99658 | 679,343 |
def hasPrevious (it):
"""
Returns :code:`True` if this list iterator has more elements when
traversing the list in the reverse direction. (In other words,
returns :code:`True` if :code:`previous(it)` would return an
element rather than throwing an exception.)
:param it: The iterator
:type i... | 13a354a398e738f64cc076041b10fcb34b9681a3 | 679,344 |
import os
def output_basename_only(f):
"""decorator
if f(path,*args,**kwargs) would recieve and return full paths,
it may return only the basename when decorated
:example:
>>> @output_basename_only
... def rename_func(path):
... return path
>>> print rename_func("a/b/c")
... | 4685f86e41ccd8385c21b6acf04f5867ca4afd20 | 679,345 |
def add_id_to_dict(doc):
""" Adds the document's id to the document's fields dictionary.
"""
full_dict = doc.to_dict()
full_dict['id'] = doc.id
return full_dict | 3626ee822817fde648e46fcd6862dc689cc20c5a | 679,346 |
def s_to_b(s: str) -> bytes:
"""convert string to bytes
:param s: input string
:type s: str
:return: output bytes
:rtype: bytes
"""
b = s.encode('utf8')
return b | 8affe4850d40754e2c9338e270c9813edad2797b | 679,347 |
def match_to_int(match):
"""Returns trace line number matches as integers for sorting.
Maps other matches to negative integers.
"""
# Hard coded string are necessary since each trace must have the address
# accessed, which is printed before trace lines.
if match == "use-after-poison" or match ==... | c2daab64bc4a2ae258b7ac6152a949b48d8d7906 | 679,348 |
def to_pascal_case(string):
"""Convert from snake_case to PascalCase
Using the standard library `title` doesn't help as it changes everything after the first letter to lowercase, we
want the following:
- API -> API
- api_key -> ApiKey
- user -> User
- paginated_response(account) -> Paginate... | 0ef2b2f7aeb7f550026df25cd060a5313a3017a5 | 679,350 |
def related_to_hardware(cpes):
"""
Return True if the CVE item is related to hardware.
"""
for cpe in cpes:
cpe_comps = cpe.split(":")
# CPE follow the format cpe:cpe_version:product_type:vendor:product
if len(cpe_comps) > 2 and cpe_comps[2] == "h":
return True
r... | 7072255239be18589ff2d9abcb0aca721478c5f5 | 679,351 |
import requests
import json
def call_salt(url: str, data):
"""
:param url: url to call
:param data: data to post
:return: request response
"""
headers = {
'Accept': 'application/x-yaml',
'Content-type': 'application/json',
}
response = requests.post(url, headers=headers... | c2aea7fcc06b80a180105fe1f3cb52b129f2ace3 | 679,352 |
def get_hello_world():
"""This method does blah blah."""
return "Hello World !!!" | 924340b9dcdfa32c77b19f7d087b0483e25ec610 | 679,353 |
def map_range(x, in_min, in_max, out_min, out_max):
"""Map Value from one range to another."""
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min | aa1765d29eaa9527cb03733b3b2e7548ccdf1fec | 679,354 |
def compare_dicts(file, src_test_dict, infer_dict):
"""
Check if a particular file
exists in the source/test dict and infer dict
If file exists, decrement the counter in
both dictionaries
Args:
file: file potentially not analyzed by infer
src_test_dict: dictionary contain... | e8ca69d85cfb18be8e92ed6c39eeca46e71a0598 | 679,355 |
def parse_requirements(fname):
"""Read requirements from a pip-compatible requirements file."""
with open(fname):
lines = (line.strip() for line in open(fname))
return [line for line in lines if line and not line.startswith("#")] | 9b27d34324b5ea304ff5c66289193640a385f393 | 679,356 |
import math
def actual_pressure(temperature, pressure, height=0.0):
"""
Convert the pressure from absolute pressure into sea-level adjusted
atmospheric pressure.
Uses the barometric formula.
Returns the mean sea-level pressure values in hPa.
"""
temperature = temperature + 273.15
press... | 5743ee84d007f399ff706bf1a4c022cda50840d0 | 679,357 |
import os
def fixup_url(url, eads, bucket):
"""dirty path hacking specific to Online Archive of California here"""
dir, ext = os.path.splitext(url)
fixup = url.replace(eads, bucket)
return u"%s.pdf" % (os.path.splitext(fixup)[0]) | 14eccb74eb803a7ba30832dbf81e7fdce3217b06 | 679,358 |
import re
def is_valid_url(url):
"""
验证url是否合法
:param url:
:return:
"""
if re.match(r"(^https?:/{2}\w.+$)|(ftp://)", url):
return True
else:
return False | 1a29b8ff58d5de8ada4e8c0f70518d87ac0ed300 | 679,359 |
import re
def get_emails(s):
"""Returns first matched email found in string s."""
# Removing lines that start with '//' because the regular expression
# mistakenly matches patterns like 'http://foo@bar.com' as '//foo@bar.com'.
# Adopted from code by Dennis Ideler ideler.dennis@gmail.com
regex = re... | 624aa54b0fe7f118d7c9b1101314605c80ac7080 | 679,360 |
def ss(value, decimals):
"""Help function to calc_properties."""
if isinstance(value,str):
tmp = value
else:
tmp = str(round(value, decimals))
return " "+tmp.ljust(decimals + 6) | 4526b5cd342a70c9cf0f48acddda9d3fbe22cb6a | 679,361 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.