content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import OrderedDict
def get_explicit_kwargs_OD(f_params, bound_args, kwargs) -> OrderedDict:
"""For some call to a function f, args *arg and **kwargs,
:param f_params: inspect.signature(f).parameters
:param bound_args: inspect.signature(f).bind(*args, **kwargs)
:return: OrderedDict of th... | abf069f5a15f159535825d77015af5205ff72c5c | 3,642,300 |
import os
def generate_variable_formants_point_function(corpus_context, min_formants, max_formants):
"""Generates a function used to call Praat to measure formants and bandwidths with variable num_formants.
Parameters
----------
corpus_context : :class:`~polyglot.corpus.context.CorpusContext`
... | 62ba3be914caaff2dbf71b3e43ae27142c4ff6af | 3,642,301 |
def handle_player_dead_keys(key):
"""
The set of keys for a dead player.
Can only see the inventory and toggle fullscreen.
"""
key_char = chr(key.c) if key.vk == libtcod.KEY_CHAR else ""
if key_char == 'i':
return {'show_inventory': True}
if key.vk == libtcod.KEY_ENTER and key.la... | 35f6288e7e830c36b163cd762a3a53531bbee394 | 3,642,302 |
def safe_std(values):
"""Remove zero std values for ones."""
return np.array([val if val != 0.0 else 1.0 for val in values]) | ab09a435393ea8025af966f4b464e088dce7a00b | 3,642,303 |
def _munge_source_data(data_source=settings.NETDEVICES_SOURCE):
"""
Read the source data in the specified format, parse it, and return a
:param data_source:
Absolute path to source data file
"""
log.msg('LOADING FROM: ', data_source)
kwargs = parse_url(data_source)
path = kwargs.pop... | bda1261e3cf914402aa4e7b4e49f523088da1fe9 | 3,642,304 |
def create_app(settings_override=None):
"""
Create a flask application using the app factory pattern
:return: Flask app
"""
app = Flask(__name__, instance_relative_config=True)
app.config.from_object('config.settings')
app.config.from_pyfile('settings.py', silent=True)
if setting... | de3dbd009b67cfabd37e71063dc3d2b925b08cb6 | 3,642,305 |
def convex_hull(ps: Polygon) -> Polygon:
"""Andrew's algorithm"""
def construct(limit, start, stop, step=1):
for i in range(start, stop, step):
while len(res) > limit and cross(res[-1] - res[-2], s_ps[i] - res[-1]) < 0:
res.pop()
res.append(s_ps[i])
assert l... | 4cdf71cdb65e838f6ef2b4617237d483257364df | 3,642,306 |
def get_api_file_url(file_id):
"""Get BaseSpace API file URL."""
api_url = get_api_url()
return f'{api_url}/files/{file_id}' | eff39b6dc2470f4217b8190104b3efb7c532f995 | 3,642,307 |
def Tr(*content, **attrs):
"""
Wrapper for tr tag
>>> Tr().render()
'<tr></tr>'
"""
return KWElement('tr', *content, **attrs) | 30b3cd48fb96a0d7d04f5deebe85f4de77d82126 | 3,642,308 |
import numpy
def _read_storm_locations_one_time(
top_tracking_dir_name, valid_time_unix_sec, desired_full_id_strings):
"""Reads storm locations at one time.
K = number of storm objects desired
:param top_tracking_dir_name: See documentation at top of file.
:param valid_time_unix_sec: Valid t... | 7867d2a36b71d0ab0c4d694e617cabe2aa960e92 | 3,642,309 |
def ja_il(il, instr):
"""
Returns llil expression to goto target of instruction
:param il: llil function to generate expression with
:param instr: instruction to pull jump target from
:return: llil expression to goto target of instr
"""
label = valid_label(il, instr.ja_target)
return il.... | 9eb18f9b709c960467d9c6a9d9cbed0d7619c5fe | 3,642,310 |
def create_plot_durations_v_nrows(source, x_axis_type='log', x_range=(1, 10**5),
y_axis_type='log', y_range=(0.001, 10**3)):
"""
Create a Bokeh plot (Figure) of do_query_dur and stream_to_file_dur versus num_rows.
num_rows is the number of result rows from the query.
P... | 2c018a68d521ba7116086f4d9f2fb015c4f584d8 | 3,642,311 |
from auroraapi.text import Text
import functools
def listen_and_transcribe(length=0, silence_len=0.5):
"""
Listen with the given parameters, but simulaneously stream the audio to the
Aurora API, transcribe, and return a Text object. This reduces latency if
you already know you want to convert the speech to text.
... | 2807b00fc760d4767c211ba168ac38dc793743aa | 3,642,312 |
def load_test_dataframes(feature_folder, **kwargs):
"""
Convenience function for loading unlabeled test dataframes. Does not add a 'Preictal' column.
:param feature_folder: The folder to load the feature data from.
:param kwargs: keyword arguments to use for loading the features.
:return: A DataFra... | 69d503c61ec752ed640c9416f7d2292788389aee | 3,642,313 |
import random
def _match_grid(grid):
"""
given a grid, create the other side to obey:
one p1 black must be a p2 green, tan, and black; and vice versa
"""
l = [""] * 25
color_dict = {
"b": [i for i in range(25) if grid[i] == "b"],
"t": [i for i in range(25) if grid[i] =... | 83b2ee7ac92c5f5d085cd5da11fff7132449736e | 3,642,314 |
def add_vary_callback_if_cookie(*varies):
"""Add vary: cookie header to all session responses.
Prevent downstream web serves to accidentally cache session set-cookie reponses,
potentially resulting to session leakage.
"""
def inner(request, response):
vary = set(response.vary if response.va... | ee7949f8c6ba1c11784b2c460e3c9dd962473412 | 3,642,315 |
import re
def fix_span(text_context, offsets, span):
"""
find start-end indices of the span in the text_context nearest to the existing token start-end indices
:param text_context: (str) text to search for span in
:param offsets: (List(Tuple[int, int]) list of begins and ends for each token in the tex... | 0c4802c20fa138a6e011f550a58328eb54a487a5 | 3,642,316 |
def update_moira_lists(
strategy, backend, user=None, **kwargs
): # pylint: disable=unused-argument
"""
Update a user's moira lists
Args:
strategy (social_django.strategy.DjangoStrategy): the strategy used to authenticate
backend (social_core.backends.base.BaseAuth): the backend being ... | f21f481bbf0b12e76149a93fee3c5c4923407c29 | 3,642,317 |
def certificate_get_all_by_project(context, project_id):
"""Get all certificates for a project."""
return IMPL.certificate_get_all_by_project(context, project_id) | 6e4c83ff75c229034ae843607d20ae211e094df9 | 3,642,318 |
def simple_list(li):
"""
takes in a list li
returns a sorted list without doubles
"""
return sorted(set(li)) | 1e36f15cea4be4b403f0a9795a2924c08b2cb262 | 3,642,319 |
from typing import OrderedDict
def create_model(gpu, arch = 'vgg16', input_size = 25088, hidden_layer_size = 512, output_size = 102):
"""Creates a neural network model.
"""
if arch in archs_dict:
model = archs_dict[arch]
else:
print("You haven`t inserted a valid architecture. Check the... | 39b8b58cfe97b5872a20f67fbeadff8b5d8e1b16 | 3,642,320 |
import json
def write_json(object_list, metadata,num_frames, out_file = None):
"""
"""
classes = ["person","bicycle","car","motorbike","NA","bus","train","truck"]
# metadata = {
# "camera_id": camera_id,
# "start_time":start_time,
# "num_frames":num_frames,
# ... | 8b224af4edbd31570a432a8c551e95cd7a002818 | 3,642,321 |
def get_infer_iterator(src_dataset,
src_vocab_table,
batch_size,
eos,
sos,
src_max_len=None):
"""Get dataset for inference."""
# Totol number of examples in src_dataset
# (3003 examples + 69 padding ... | 81ebd9f9f7d17bf1046f3fd0fafcbc3cdbb53ef4 | 3,642,322 |
def get_num_hearts(image):
"""Returns the number of full and total hearts.
Keyword arguements:
image - image of hearts region
"""
# definitions:
lower_full = np.array([0, 15, 70])
upper_full = np.array([30, 35, 250])
lower_empty = np.array([150, 160, 220])
upper_empty = np.... | 614d11546c5d458b5e9d485024da4bdb34688e24 | 3,642,323 |
import copy
def _clean_root(tool_xml):
"""XSD assumes macros have been expanded, so remove them."""
clean_tool_xml = copy.deepcopy(tool_xml)
to_remove = []
for macros_el in clean_tool_xml.getroot().findall("macros"):
to_remove.append(macros_el)
for macros_el in to_remove:
clean_too... | 9df0980265b26a2de1c88d2999f10cd5d1421e0b | 3,642,324 |
import logging
import traceback
def page_not_found(e):
"""Return a custom 404 error."""
logging.error(':: A 404 was thrown a bad URL was requested ::')
logging.error(traceback.format_exc())
return render_template('404.html'), 404 | 11a553ab9ce52b4b1ba12916887f636d02aaef8f | 3,642,325 |
def find_prime_factors(num):
"""Return prime factors of num."""
validate_integers(num)
zero_divisors_error(num)
potential_factor = 2
prime_factors = set()
while potential_factor <= num:
if num % potential_factor == 0:
prime_factors.add(potential_factor)
num = num/... | fe15c75d19081ec5fa5cfdefa0c95e4bcd20c26d | 3,642,326 |
from datetime import datetime
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, (datetime, date)):
return obj.isoformat()
elif isinstance(obj, (dict)):
return obj
raise TypeError("Type %s not serializable" % type(obj)) | 7da3adb9dde3315741b5dcad2fa276e9f0b582af | 3,642,327 |
import os
import yaml
def read_yaml_files(directories):
"""Read the contents of all yaml files in a directory.
Args:
directories: List of directory names with configuration files
Returns:
config_dict: Dict of yaml read
"""
# Initialize key variables
yaml_found = False
ya... | c849280c1b267984d779adfbd5a18d3316254117 | 3,642,328 |
import sys
import logging
def _check_for_crash(project_name, fuzz_target, testcase_path):
"""Check for crash."""
def docker_run(args):
command = ['docker', 'run', '--rm', '--privileged']
if sys.stdin.isatty():
command.append('-i')
return utils.execute(command + args)
logging.info('Checking ... | 00531cff78355d1b7e84bcffdcf2c1cb943803e2 | 3,642,329 |
import os
import sys
def parse_from_compdb(compdb, file_to_parse):
"""Extracts the absolute file path of the file to parse and its arguments from compdb"""
absolute_filepath = None
file_arguments = []
compdb = compdb_parser.load_compdb(compdb)
if compdb:
commands = compdb.getAllCompileCom... | d1f9b3098335571f5ef2c96727d9d8be5eecaacd | 3,642,330 |
import subprocess
def _pyenv_version():
"""Determine which pyenv
Returns:
str: pyenv version
"""
return subprocess.check_output(['pyenv', 'version']).split(' ')[0] | 83c9f3a7ba15996392d8510f34e555e39c813a1a | 3,642,331 |
import subprocess
def reset_config_on_routers(tgen, routerName=None):
"""
Resets configuration on routers to the snapshot created using input JSON
file. It replaces existing router configuration with FRRCFG_BKUP_FILE
Parameters
----------
* `tgen` : Topogen object
* `routerName` : router ... | 3f90d31d2ac1d85bf52a341433ccb96cb044c938 | 3,642,332 |
def ignore_exception(exception):
"""Check whether we can safely ignore this exception."""
if isinstance(exception, BadRequest):
if 'Query is too old' in exception.message or \
exception.message.startswith('Have no rights to send a message') or \
exception.message.startswith('Messag... | 3f0182fbe7cec2e5978c61c110d10ed039869fd7 | 3,642,333 |
def rmse_loss(prediction, ground_truth, weight_map=None):
"""
:param prediction: the current prediction of the ground truth.
:param ground_truth: the measurement you are approximating with regression.
:param weight_map: a weight map for the cost function. .
:return: sqrt(mean(differences squared))
... | aef45b5549151a3d6c026dd34ccd9b6aa2b6d695 | 3,642,334 |
def get_corrupted_simulation_docs():
"""Returns iterable of simdocs without samples (when num_paticles >0)
When num_particle<=0, no samples are created and the simulation is considered Finished anyway.
These ignored simulations
"""
return db[DBCOLLECTIONS.SIMULATION].find({
'procstatus.stat... | f23620d7ea09fd37790ceb682f15dc0183b17c9c | 3,642,335 |
def residual_block(x: Tensor, downsample: bool, filters: int, kernel_size: int = 3) -> Tensor:
"""
Parameters
----------
x : Tensor
DESCRIPTION.
downsample : bool
DESCRIPTION.
filters : int
DESCRIPTION.
kernel_size : int, optional
DESCRIPTION. The defaul... | 092c41b6508ccb52d545219e0d2e254c3430362a | 3,642,336 |
def dehaze(img, level):
"""use Otsu to threshold https://scikit-image.org/docs/stable/auto_examples/segmentation/plot_multiotsu.html
n.b. threshold used to mask image: dark values are zeroed, but result is NOT binary
level: value 1..5 with larger values preserving more bright voxels
level: d... | bdb6f55fd09986a2abac92728644777fae77f6ca | 3,642,337 |
def matthews_correlation_coefficient(tp, tn, fp, fn):
"""Return Matthews correlation coefficient for values from a confusion matrix.
Implementation is based on the definition from wikipedia:
https://en.wikipedia.org/wiki/Matthews_correlation_coefficient
"""
numerator = (tp * tn) - (fp * fn)
den... | 2048fb05664b3fcab99e08c51eb11a222676df84 | 3,642,338 |
import os
import yaml
def find_graph(hostnames):
"""
Find a graph file contains all devices in testbed.
duts are spcified by hostnames
Parameters:
hostnames: list of duts in the target testbed.
"""
filename = os.path.join(LAB_GRAPHFILE_PATH, LAB_CONNECTION_GRAPH_FILE)
with open(fi... | 307c939bdac3bf106ba12d12fbf0a41b06b3d525 | 3,642,339 |
import re
def run_analysis(apk_dir, md5_hash, package):
"""Run Dynamic File Analysis."""
analysis_result = {}
logger.info('Dynamic File Analysis')
domains = {}
clipboard = []
# Collect Log data
data = get_log_data(apk_dir, package)
clip_tag = 'I/CLIPDUMP-INFO-LOG'
clip_tag2 = 'I CL... | f5108c8e3a09799e451bc8182018acf1481615e4 | 3,642,340 |
from datetime import datetime
import fastapi
async def quotes(
ticker: str, date: datetime.date,
uow: UoW = fastapi.Depends(dependendies.get_uow),
) -> ListResponse[Ticker]:
"""Return the list of available tickers."""
with uow:
results = uow.quotes.iterator({'ticker': ticker, 'date': date})
... | 4267815af0ec13bc617870ee16b7b452a66d7891 | 3,642,341 |
from typing import Tuple
from typing import Union
def delete_snapshot(client, data_args) -> Tuple[str, dict, Union[list, dict]]:
""" Delete exsisting snapshot from the system.
:type client: ``Client``
:param client: client which connects to api.
:type data_args: ``dict``
:param da... | 509298677120b61dd9aa050dbe40aacffff6d97c | 3,642,342 |
from backend.models.prices import PriceDB
def api_user_submissions(user_id):
"""Gets the price submissions for a user matching the user_id.
Example Request:
HTTP GET /api/v1/users/56cf848722e7c01d0466e533/submissions
Example Response:
{
"success": "OK",
"user_submissi... | 498c91451896dde6d347492acad9573839c45e13 | 3,642,343 |
def get_pdf_info(pdf_path: str) -> PdfInfo:
"""Get meta information of a PDF file."""
info: PdfInfo = PdfInfo(path=pdf_path)
keys = get_flat_cfg_file(path="~/.edapy/pdf_keys.csv")
ignore_keys = get_flat_cfg_file(path="~/.edapy/pdf_ignore_keys.csv")
for key in keys:
info.user_attributes[key... | 3f80d9d50261e6b7a9e1c90b504abcbeed2b214d | 3,642,344 |
import json
import zlib
import base64
def convert_gz_json_type(value):
"""Provide an ArgumentParser type function to unmarshal a b64 gz JSON string.
"""
return json.loads(zlib.decompress(base64.b64decode(value))) | 1cf0300f40c8367b9129f230a7fef0c9b89ba012 | 3,642,345 |
def get_tag(tag):
"""
Returns a tag object for the string passed to it
If it does not appear in the database then return a new tag object
If it does exisit in the data then return the database object
"""
tag = tag.lower()
try:
return Session.query(Tag).filter_by(name=unicode(tag)).on... | e11ae349fa4d436a6b7057bf0b5d8b74a7e0f4e4 | 3,642,346 |
import requests
import json
def makeApiCall( url, endpointParams, debug = 'no' ) :
""" Request data from endpoint with params
Args:
url: string of the url endpoint to make request from
endpointParams: dictionary keyed by the names of the url parameters
Returns:
object: data from... | 5f9362d6b34ee4809714ae7380bfaa5500763177 | 3,642,347 |
def get_closest_area(
lat: float, lng: float, locations: t.List[config.Area]
) -> t.Optional[config.Area]:
"""Return area if image taken within 50 km from center of area"""
distances = [
(great_circle((area.lat, area.lng), (lat, lng)).km, area) for area in locations
]
distance, closest_area ... | 3deb96bc1863ed1d02699cff0a48edd9471bbade | 3,642,348 |
def disable(request):
"""
Disable Pool Member Running Script
"""
try:
auth = AuthSession(request.session)
client = auth.get_clientFactory()
id_server_pool = request.POST.get('id_server_pool')
ids = request.POST.get('ids')
if id_server_pool and ids:
... | 9c56d891a86db3e9f999cb8f329630172ea9703e | 3,642,349 |
def fastapi_native_middleware_factory():
"""Create a FastAPI app that uses native-style middleware."""
app = FastAPI()
# Exception handler for `/client_error_from_handled_exception`
app.add_exception_handler(IndexError, client_induced_exception_handler)
app.add_middleware(BaseHTTPMiddleware, dispa... | 5c85df93f126443b19b10b58fc7cb57661fd3388 | 3,642,350 |
def _partial_dependence(
pipeline,
X,
features,
percentiles=(0.05, 0.95),
grid_resolution=100,
kind="average",
custom_range=None,
):
"""Compute the partial dependence for features of X.
Args:
pipeline (PipelineBase): pipeline.
X (pd.DataFrame): Holdout data
f... | 1b8ae5811b7e815805e95d1c4ccc2fb1127187a9 | 3,642,351 |
from typing import Union
from typing import Tuple
def nplog(
a: np.ndarray, deriv: bool = False, eps: float = 1e-30, verbose: bool = False
) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]:
"""$C^2$ extension of $\ln(a)$ below `eps`
Args:
a: a Numpy array
deriv: if `True`, the first ... | cc2258b78aca58c71d61aa058b9de0d408165268 | 3,642,352 |
from typing import List
import os
import json
def translate_names(recipe_names: List[str], locale: str) -> List[str]:
"""Translates a list of recipe names to the given locale."""
if locale in ['auto', 'en-us']:
return recipe_names
translation_path = os.path.join('recipes', 'translations.json')
... | 2294f1ee2556521ae080eee7d9050873d9a723cb | 3,642,353 |
def _section_to_text(config_section: ConfigSection) -> str:
"""Convert a single config section to text"""
return (f'[{config_section.name}]{LINE_SEP}'
f'{LINE_SEP.join(_option_to_text(option) for option in config_section.options)}{LINE_SEP}') | ee5feed2f9453c9f3338997d5294bada22961f07 | 3,642,354 |
import tempfile
def TempFileDecorator(func):
"""Populates self.tempfile with path to a temporary writeable file"""
def f(self, *args, **kwargs):
with tempfile.NamedTemporaryFile(dir=self.tempdir, delete=False) as f:
self.tempfile = f.name
return func(self, *args, **kwargs)
f.__name__ = func.__nam... | d696a16cade0eee36fee9cba4c0d8b96fbcc79e4 | 3,642,355 |
import string
import random
def get_random_string(length: int) -> str:
"""
Returns a random string starting with a lower-case letter.
Later parts can contain numbers, lower- and uppercase letters.
Note: Random Seed should be set somewhere in the program!
:param length: How long the required strin... | 6cf20ce7d158ac158ffa49cac427c396cfd840db | 3,642,356 |
import numpy
def subset_by_month(prediction_dict, desired_month):
"""Subsets examples by month.
:param prediction_dict: See doc for `write_file`.
:param desired_month: Desired month (integer from 1...12).
:return: prediction_dict: Same as input but with fewer examples.
"""
error_checking.ass... | 4df4eca74bcb433e85a06a99b32877890909ba86 | 3,642,357 |
import time
def build_dataset_mce(platform, dataset_name, columns):
"""
Creates MetadataChangeEvent for the dataset.
"""
actor, sys_time = "urn:li:corpuser:etl", int(time.time())
fields = []
for column in columns:
fields.append({
"fieldPath": column["name"],
"n... | 22fab14fe4a6e9f01b24ca67dce40b5860aebbe2 | 3,642,358 |
from copy import copy
import re
import logging
def tag_source_file(path):
"""Returns a list of tuples: (line_text, list_of_tags)"""
file = open(path, "r")
# The list of tagged lines
tagged_lines = []
# The list of tags that currently apply
current_tags = []
# Use this to st... | 0d46748a2145bcd70115bf5047fce21184a4f535 | 3,642,359 |
def FindMissingReconstruction(X, track_i):
"""
Find the points that will be newly added
Parameters
----------
X : ndarray of shape (F, 3)
3D points
track_i : ndarray of shape (F, 2)
2D points of the newly registered image
Returns
-------
new_point : ndarray of shape... | 36e0f0f2dbc6a68f20a349a92fc1c882d5d0b73a | 3,642,360 |
def deserialize(iodata):
"""
Turn IOData back into a Python object of the appropriate kind.
An object is deemed deserializable if
1) it is recorded in SERIALIZABLE_REGISTRY and has a `.deserialize` method
2) there exists a function `file_io_serializers.<typename>_deserialize`
Parameters
---... | 3eb21f34b1571626a40fc52bd2eae2a42ff7dbb4 | 3,642,361 |
from typing import Union
from typing import Iterable
from typing import Tuple
from typing import Optional
def business_day_offset(dates: DateOrDates, offsets: Union[int, Iterable[int]], roll: str= 'raise', calendars: Union[str, Tuple[str, ...]]=(), week_mask: Optional[str]=None) -> DateOrDates:
"""
Apply offs... | 32769b604b8e671b8318b0a6e00cdb8331774870 | 3,642,362 |
def factorial(n):
"""
Return n! - the factorial of n.
>>> factorial(1)
1
>>> factorial(0)
1
>>> factorial(3)
6
"""
if n<=0:
return 0
elif n==1:
return 1
else:
return n*factorial(n-1) | da5bc6f68375c7db03b7b2bdac1fec2b476ba563 | 3,642,363 |
from scipy.io import loadmat
from scipy.interpolate import interp1d
def _load_absorption(freqs):
"""Load molar extinction coefficients."""
# Data from https://omlc.org/spectra/hemoglobin/summary.html
# The text was copied to a text file. The text before and
# after the table was deleted. The the follo... | e31c5d46c5e2de81627834f51ddb79f6f1265e5a | 3,642,364 |
import math
def pw_sin_relaxation(b, x, w, x_pts, relaxation_side=RelaxationSide.BOTH, pw_repn='INC', safety_tol=1e-10):
"""
This function creates piecewise relaxations to relax "w=sin(x)" for -pi/2 <= x <= pi/2.
Parameters
----------
b: pyo.Block
x: pyomo.core.base.var.SimpleVar or pyomo.cor... | 38c5d8a459f8c90aaa17a95f4000e4388e491f69 | 3,642,365 |
import sys,time
from datetime import datetime
from datetime import timedelta
def getAsDateTimeStr(value, offset=0,fmt=_formatTimeStr()):
""" return time as 2004-01-10T00:13:50.000Z """
if (not isinstance(offset,str)):
if isinstance(value, (tuple, time.struct_time,)):
return time.strftime(... | ddf47f2e8f9be7d1387baaf7c1dc0fd83ddf3022 | 3,642,366 |
def doc_to_tokenlist_no_sents(doc):
""" serializes a spacy DOC object into a python list with tokens grouped by sents
:param doc: spacy DOC element
:return: a list of of token objects/dicts
"""
result = []
for x in doc:
token = {}
if y.has_extension('tokenId'):
parts[... | 0879e49836910d1f3a9be93281158c1b64978d53 | 3,642,367 |
def _applychange(raw_text: Text, content_change: t.TextDocumentContentChangeEvent):
"""Apply changes in-place"""
# Remove chars
start = content_change.range.start
range_length = content_change.range_length
index = _find_position(raw_text, start)
for _ in range(range_length):
raw_text.pop... | 9dddeb69a5830980721d747f743e5e516f2eba51 | 3,642,368 |
def get_engine():
"""Return a SQLAlchemy engine."""
connection_dict = sqlalchemy.engine.url.make_url(FLAGS.sql_connection)
engine_args = {
"pool_recycle": FLAGS.sql_idle_timeout,
"echo": False,
}
if "sqlite" in connection_dict.drivername:
engine_args["poolclass"] = sqlalche... | f93bfe29b7cf96d32f250e4385d3d2a794a02ee0 | 3,642,369 |
def ccw(p0, p1, p2):
"""
Judge whether p0p2 vector is ccw to p0p1 vector.
Return value map: \n
1: p0p2 is ccw to p0p1 (angle to x axis bigger) \n
0: p0p2 and p0p1 on a same line \n
-1: p0p2 is cw to p0p1 (angle to x axis smaller) \n
Args:
p0: base point index 0 and 1 is... | 46599e0df6c39346e4b61f6daeb140a8db6225a3 | 3,642,370 |
def get_ffmpeg_folder():
# type: () -> str
"""
Returns the path to the folder containing the ffmpeg executable
:return:
"""
return 'C:/ffmpeg/bin' | 4708eec64ff56b72f7b1b9cc7f5ee7916f6310bd | 3,642,371 |
import subprocess
def decode_typeinfo(typeinfo):
"""Invoke c++filt to decode a typeinfo"""
try:
type_string = subprocess.check_output(["c++filt", typeinfo], stdin=subprocess.DEVNULL)
except FileNotFoundError:
# This happens when c++filt (from package binutils) is not found,
# and w... | 95211c7175a572ba2b5a627e0e18d95e68405f86 | 3,642,372 |
def get_nums(image):
"""get the words from an image using pytesseract.
the extracted words are cleaned and all spaces, newlines and non uppercase
characters are removed.
:param image: inpout image
:type image: cv2 image
:return: extracted words
:rtype: list
"""
# pytesseract c... | 0ff23d8363a14a46c7f6ffa2be130c6eb61409c8 | 3,642,373 |
def create_bag_of_vocabulary_words():
"""
Form the array of words which can be conceived during the game.
This words are stored in hangman/vocabulary.txt
"""
words_array = []
file_object = open("./hangman/vocabulary.txt")
for line in file_object:
for word in line.split():
... | e3aadad2575e28b19b83158eb2127437c8aada89 | 3,642,374 |
import math
def kato_ranking_candidates(identifier: Identifier, params=None):
"""rank candidates based on the method proposed by Kato, S. and Kano, M..
Candidates are the noun phrases in the sentence where the identifier was appeared first.
Args:
identifier (Identifier)
params (dict)
R... | c8a413118b599eb3cb9c9db877d7d489871d65a2 | 3,642,375 |
def _get_bag_of_pos_with_dependency(words, index):
"""Return pos list surrounding index
Args:
words (list): stanfordnlp word list object having pos attributes.
index (int): target index
Return:
pos_list (List[str]): xpos format string list
"""
pos_list = []
def _get_gove... | 02fc508583d79464161927080c1c55d308926274 | 3,642,376 |
def fix_time_individual(df):
"""
1. pandas.apply a jit function to add 0 to time
2. concat date + time
3. change to np.datetime64
"""
@jit
def _fix_time(x):
aux = "0" * (8 - len(str(x))) + str(x)
return aux[:2] + ":" + aux[2:4] + ":" + aux[4:6] + "." + aux[6:]
... | 8d0c99d3f485d852130f9f4fe7ab05bbcdd99557 | 3,642,377 |
def convolve_fft(data, kernel, kernel_fft=False, return_fft=False):
"""
Convolve data with a kernel.
This is inspired by astropy.convolution.convolve_fft, but
stripped down to what's needed for the expected application. That
has the benefit of cutting down on the execution time, but limits
its ... | 64fc4c02f72c419f6c315f524597a32391ea7b8c | 3,642,378 |
import os
def segment_nifti(fname_image, folder_model, fname_prior=None, param=None):
"""
Segment a nifti file.
:param fname_image: str: Filename of the image to segment.
:param folder_model: str: Folder that encloses the deep learning model.
:param fname_prior: str: Filename of a previous segmen... | 74ea5aa03f1f36c717e6f700c91d26fda3afb78d | 3,642,379 |
def friable_sand(Ks, Gs, phi, phic, P_eff, n=-1, f=1.0):
"""
Friable sand rock physics model.
Reference: Avseth et al., Quantitative Seismic Interpretation, p.54
Inputs:
Ks = Bulk modulus of mineral matrix
Gs = Shear modulus of mineral matrix
phi = porosity
phic = cr... | ace533ee727cd4749ad210b13eec5193b74416b8 | 3,642,380 |
def get_available_currencies():
"""
This function retrieves a listing with all the available currencies with indexed currency crosses in order to
get to know which are the available currencies. The currencies listed in this function, so on, can be used to
search currency crosses and used the retrieved d... | 139f775943bc251149444c702cb4290d78a58a03 | 3,642,381 |
def mktemp(suffix="", prefix=template, dir=None):
"""User-callable function to return a unique temporary file name. The
file is not created.
Arguments are as for mkstemp, except that the 'text' argument is
not accepted.
This function is unsafe and should not be used. The file name
refers to a file that ... | 0785609c3284b0052fa31767d0df11476b28c786 | 3,642,382 |
def getTaskIdentifier( task_id ) :
"""Get tuple of Type and Instance identifiers."""
_inst = Instance.objects.get( id = task_id )
return ( _inst.type.identifier , _inst.identifier ) | fb18be814330bd02205d355b3ebfb68f777ee9c2 | 3,642,383 |
def hessian_vector_product(loss, weights, v):
"""Compute the tensor of the product H.v, where H is the loss Hessian with
respect to the weights. v is a vector (a rank 1 Tensor) of the same size as
the loss gradient. The ordering of elements in v is the same obtained from
flatten_tensor_list() acting on t... | 35ef7772367f56fcded2e4173fe194cb28da3bc7 | 3,642,384 |
def clean_cells(nb_node):
"""Delete any outputs and resets cell count."""
for cell in nb_node['cells']:
if 'code' == cell['cell_type']:
if 'outputs' in cell:
cell['outputs'] = []
if 'execution_count' in cell:
cell['execution_count'] = None
ret... | 67dce7ecc3590143730f943d3eb07ae7df9d8145 | 3,642,385 |
from typing import Callable
from typing import Any
import asyncio
import inspect
def _spanned(scond: _SpanConductor) -> Callable[..., Any]:
"""Handle decorating a function with either a new span or a reused span."""
def inner_function(func: Callable[..., Any]) -> Callable[..., Any]:
def setup(args: A... | 4d6b9bc4a56ae50c781da2078e2d919bae19bfdf | 3,642,386 |
def getProjectProperties():
"""
:return:
@rtype: list of ProjectProperty
"""
return getMetDataLoader().projectProperties | 7f517a20d83002c41867bbc7911f775d64b21b88 | 3,642,387 |
def svn_client_cleanup(*args):
"""svn_client_cleanup(char dir, svn_client_ctx_t ctx, apr_pool_t scratch_pool) -> svn_error_t"""
return _client.svn_client_cleanup(*args) | 2a9921e8521e927e124633bb932b158a1f9abdf3 | 3,642,388 |
def model_chromatic(psrs, psd='powerlaw', noisedict=None, components=30,
gamma_common=None, upper_limit=False, bayesephem=False,
wideband=False,
idx=4, chromatic_psd='powerlaw', c_psrs=['J1713+0747']):
"""
Reads in list of enterprise Pulsar instance an... | 568f4951930fe6f8175417785c4503895f76bc88 | 3,642,389 |
import os
import shutil
def restore(backup_path: str, storage_name: str, target: str or None = None, token: str or None = None) -> str:
"""
Downloads the information from the backup
:returns path to the file
"""
if not token:
token = _restore_token(storage_name)
print(f'[{__name__}] G... | 380a654c98b406c892f50deba80c00ec3d37fa50 | 3,642,390 |
def test_f32(heavydb):
"""If UDF name ends with an underscore, expect strange behaviour. For
instance, defining
@heavydb('f32(f32)', 'f32(f64)')
def f32_(x): return x+4.5
the query `select f32_(0.0E0))` fails but not when defining
@heavydb('f32(f64)', 'f32(f32)')
def f32_(x): retu... | 157560cc90e3f869d84198eeb26896a76157eb39 | 3,642,391 |
from typing import Union
from pathlib import Path
def get_message_bytes(
file_path: Union[str, Path],
count: int,
) -> bytes:
"""
从 GRIB2 文件中读取第 count 个要素场,裁剪区域 (东北区域),并返回新场的字节码
Parameters
----------
file_path
count
要素场序号,从 1 开始,ecCodes GRIB Key count
Returns
... | 6a2ad3a20e02283c2bffe31eb78cacf84d92ff6f | 3,642,392 |
from typing import Union
from typing import List
import json
def discover_climate_observations(
time_resolution: Union[
None, str, TimeResolution, List[Union[str, TimeResolution]]
] = None,
parameter: Union[None, str, Parameter, List[Union[str, Parameter]]] = None,
period_type: Union[None, str... | b96fd2a0a9bcb9a7b50018a1b7e3ae7add3e3c63 | 3,642,393 |
def set_template(template_name, file_name, p_name):
"""
Insert template into the E-mail.
"""
corp = template(template_name, file_name, p_name)
msg = MIMEMultipart()
msg['from'] = p_name
msg['subject'] = f'{file_name}'
msg.attach(MIMEText(corp, 'html'))
return msg | 8745d9729ddbe159e0bca90dee198ce4e3efb489 | 3,642,394 |
import gettext
def lazy_gettext(string):
"""A lazy version of `gettext`."""
if isinstance(string, _TranslationProxy):
return string
return _TranslationProxy(gettext, string) | 9229c987d6b2f300f7225ea4b58f964c70e882fc | 3,642,395 |
def toggleautowithdrawalstatus(status, fid, alternate_token=False):
"""
Sets auto-withdrawal status of the account associated
with the current OAuth token under the specified
funding ID.
:param status: Boolean for toggle.
:param fid: String with funding ID for target account
:return: String ... | 4df2be7801a23978c58b7ce8aec7e5fd30fb1e76 | 3,642,396 |
def load_avenger_models():
"""
Load each instance of data from the repository into its associated model at this point in the schema lifecycle
"""
avengers = []
for item in fetch_avenger_data():
# Explicitly assign each attribute of the model, so various attributes can be ignored
ave... | 70740495be63a198cf5ec1308608955f52be46f0 | 3,642,397 |
import json
import _json
import _datetime
def aggregate_points(point_layer,
bin_type=None,
bin_size=None,
bin_size_unit=None,
polygon_layer=None,
time_step_interval=None,
time_step_interval_un... | fe946d4273ed1ce4e4cd3e46d9f9a3e0ff5c6725 | 3,642,398 |
def scattered_embedding_lookup(params,
values,
dimension,
name=None,
hash_key=None):
"""Looks up embeddings using parameter hashing for each value in `values`.
The i-th embedding component of... | a317d7d494bd9b9918f6f2354d854c2fbffc1c6c | 3,642,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.