content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import List
import os
import fnmatch
def glob(glob_pattern: str, directoryname: str) -> List[str]:
"""
Walks through a directory and its subdirectories looking for files matching
the glob_pattern and returns a list=[].
:param directoryname: Any accessible folder name on the filesystem.
... | 3155ce1037c39339439805024f1d6abac6b24460 | 40,500 |
from typing import Union
import pandas
def _upload_entity_df_into_sqlserver_and_get_entity_schema(
engine: sqlalchemy.engine.Engine,
config: RepoConfig,
entity_df: Union[pandas.DataFrame, str],
) -> EntitySchema:
"""
Uploads a Pandas entity dataframe into a SQL Server table and constructs the
... | f059a7f7dd981b135e9f4e124d3cd57cdb6fb11a | 40,501 |
def test_store_decorator(sirang_instance):
"""Test dstore"""
db = 'dstore'
collection = 'test'
def test_func(arg1, arg2, arg3, arg4):
return arg2
# Test inversions
no_invert = sirang_instance.dstore(
db, collection, keep=['arg1', 'arg2'], inversion=False,
doc_id_templat... | 868d26de1db3af3ea22e129c757400d8d013c9b1 | 40,502 |
def remove_backups(files, cutoff_time):
"""Use this tool to remove backups older than given input from a directory.
"""
def older_than(item):
item_time, item = item
return item_time < cutoff_time
files_to_remove = filter(older_than, files)
for item in files_to_remove:
date_ti... | f7de82dc0afa4f1ca906df86696dbc1690aa8d60 | 40,503 |
def incsum(prevsum, prevmean, mean, x):
"""Caclulate incremental sum of square deviations"""
newsum = prevsum + abs((x - prevmean) * (x - mean))
return newsum | b4e8367d526b0701311eaae969d4143763c08ab2 | 40,504 |
def sdate_from_datetime(datetime_object, format='%y-%m-%d'):
"""
Converts a datetime object to SDATE string.
"""
return datetime_object.strftime(format) | 3f7ee70c47e1971e1c690f564fc8d4df519db5b6 | 40,505 |
def zyz(alpha, beta, gamma):
""" 3d rotation around z-, y-, z-axis:
float, float, float -> (3,3)-array
"""
return np.dot(z(alpha), np.dot(y(beta), z(gamma))) | 554965c844b17bdd8da2c6d835dc6455b5c97788 | 40,506 |
import numpy as np
from functools import partial
from lripy.projindex import projindex
from lripy.proxnonconv import proxnonconv
from lripy.proxnormrast import proxnormrast
from lripy.dr import dr
def drcomplete(N,Index,r,p,solver = None, gamma = 1,rho = 1,Z0 = None,tol = None):
"""
Douglas-Rachford proximal ... | 8d0325a140b79b0cb8fc72a1558d3a43112fc9db | 40,507 |
def load_data(database_filepath):
""" load data and output features and targets
"""
# load data from database
engine = create_engine('sqlite:///{}'.format(database_filepath))
file_name = database_filepath.split("/")[-1]
table_name = file_name.split(".")[0]
df = pd.read_sql_table(ta... | 06abf9bcfae2f813ec88ebcdb09d301d640b9028 | 40,508 |
def hpix2radec(nside, hpix):
"""
Function transforms HEALPix index (ring) to RA, DEC
parameters
----------
nside : int
hpix : array_like
HEALPix indices
returns
-------
ra : array_like
right ascention in deg
dec : array_like
de... | 05b20e48a0c9e74fb5c3cf44e8f79328acfa7966 | 40,509 |
def convert_crop_cam_to_orig_img_and_focal(cam, bbox, img_width, img_height,
focal=5000., resized_width=224, resized_height=224,
new_focal=None):
"""
Borrow from VIBE
"""
'''
Convert predicted camera from cropped i... | 1cfb5bf3c90f41180cad2b0efcdaef92ebdd7e8a | 40,510 |
def ismember(a, b):
"""
equivalent of np.isin but returns indices as in the matlab ismember function
returns an array containing logical 1 (true) where the data in A is B
also returns the location of members in b such as a[lia] == b[locb]
:param a: 1d - array
:param b: 1d - array
:return: is... | ca3926bfc41a2800ab42f5209e6669b42e6babc7 | 40,511 |
def init_obj_discrete(env_fn_discrete):
"""
Instantiate a PolicyWithValue class object
"""
MyNet = PolicyWithValue(
policy_net = 'mlp',
env = env_fn_discrete,
normalize_observations=False
)
return MyNet | 1562319bcf87fb690554d216a2ef9c6a49115873 | 40,512 |
def new_norm(graphs_, bl_feat):
"""Normalize graph function uniformly"""
newnorm = dict(zip(bl_feat, [0] * 5))
for attr in bl_feat:
for gs in graphs_:
for g in gs:
tmp = max(nx.get_node_attributes(g, attr).values())
if tmp > newnorm[attr]:
... | 64f1583ddbe8db04ab110ac71a78f287e0c46af2 | 40,513 |
def in6_and(a1, a2):
"""
Provides a bit to bit AND of provided addresses. They must be
passed in network format. Return value is also an IPv6 address
in network format.
"""
return _in6_bitops(a1, a2, 1) | 501e8029aa7926eded96740ce15f5e3e96b66f0c | 40,514 |
def send_data(socket_path, data):
"""Send data to the socket path.
The send method takes serialized data and submits it to the given
socket path.
This method will return information provided by the server in
String format.
:returns: String
"""
with UNIXSocketConnect(socket_path) as s... | 5cb7caa55943093dcf4b951068cbeab2b9a76c8a | 40,515 |
import os
def get_manifest(apk_path):
"""反编译解压apk,获取AndroidManifest.xml文件"""
# command = 'apktool d ' + apk_path + ' -o apkshield_tmp'
# os.system(command)
decompAPK(apk_path)
stDisassembleDp = apk_path + "decompile"
stAMFp = os.path.join(stDisassembleDp, "AndroidManifest.xml")
print("stAM... | 447cc5c2e85e9a824e6d5c73473ed21dfdc4a4fd | 40,516 |
import functools
def nim(heaps, game_type, output=True):
"""
Computes next move for Nim, for both game types normal and misere.
if there is a winning move:
return tuple(heap_index, amount_to_remove)
else:
return 0, 0
- mid-game scenarios are the same for both game types
>>> ... | 3f39792d0d30335b8b6915fb3c73d76beb4740f4 | 40,517 |
import ctypes
def get_positions(p_state, idx_image=-1, idx_chain=-1):
"""Returns a `numpy.array_view` of `shape(NOS, 3)` with the components of each spins position.
Changing the contents of this array_view will have direct effect on the state and should not be done.
"""
nos = system.get_nos(p_state, ... | ce783050d8ea44738e7febf7a8cd0ae079a067f6 | 40,518 |
def image_dataset_from_tfrecords(globs,
tag,
image_shape,
batch_size = 0,
shuffle = True,
repeat = -1):
"""Loads images from sharded TFRecord files.
A... | 6e72f4d98ee7adfa45dd6b2dbebc9abc0fcfb4d8 | 40,519 |
def get_writer(_):
"""
Returns the writer class.
"""
return LunrWriter | 972cbe7eaa1a0102acae3c5776395b11c7f792c8 | 40,520 |
def test_logo():
"""
Plot the GMT logo as a stand-alone plot.
"""
fig = Figure()
fig.logo()
return fig | 25b9e05536981bb6c77ca557b9f7601f088311dc | 40,521 |
def decrypt(data, key, iv, guest_padding_size):
"""Decrypt using AES CBC"""
decryptor = AES.new(key, AES.MODE_CBC, IV=iv)
# if ValueError AND has correct padding, https://github.com/Legrandin/pycryptodome/issues/10#issuecomment-354960150
if guest_padding_size == 0: # can use as flag bcoz pad with 0 will... | acad2d3e52321cd16eede6c163f28bac38bef68c | 40,522 |
def SRL32(init=0, has_shiftout=False, has_ce=False):
"""
Configure a Slice as a 32-bit shift register
[I, A[5]] -> O
@note: SRL32's can be chained together using SHIFTOUT and SHIFTIN.
In that case, an SRL32 does not generate any output.
"""
if isinstance(init, IntegerTypes):
i... | 706d7ade96e18c7f47236d0bb2be386faf136ae4 | 40,523 |
def compute_peak_valley(rip: DataStream,
rip_quality: DataStream,
fs: float = 21.33,
smoothing_factor: int = 5,
time_window: int = 8,
expiration_amplitude_threshold_perc: float = 0.10,
... | e794f9f49bbec301901970cc1c9700b16943bce3 | 40,524 |
def WaveguideConnect(port1: "DevicePort",port2: "DevicePort",
rad: float = 3):
"""
Simple waveguide connector for two ports. Given a start port and an
end port, the function attempts to connect the ports using
a sequence of straight lines (sequencer command S), 90 degrees bends
... | baf7d48b6cc0e27ea9a1b0797bd781260670e62c | 40,525 |
def convert_title(original_title):
"""Remove underscores from string"""
new_title = original_title.replace("_", " ").title()
new_title = new_title.replace("Api", "API")
return new_title | 34e6441bda4ae1cfe0c092b407c6b0579fe3277f | 40,526 |
import os
import sys
def our_path():
""" This will get us the program's directory,
even if we are frozen using py2exe"""
if _are_we_frozen():
return os.path.dirname(unicode(sys.executable, sys.getfilesystemencoding( )))
return os.path.dirname(unicode(__file__, sys.getfilesystemencoding( ))) | 1cf3b7ef753079df135464e1cde86227a40b4592 | 40,527 |
import types
def type_from_outputs(outputs):
"""
:param outputs: [ Theano Variable ]
:returns: pykit return type
"""
result_types = [map_type(v.type) for v in outputs]
if len(outputs) > 1:
result_type = types.Tuple(result_types)
else:
result_type, = result_types
... | e30efe5b8b7083a61ac63976a690579d0981f277 | 40,528 |
from typing import OrderedDict
def analyze_sentiment(text, **kwargs):
"""
Analyzing Sentiment in a String
Args:
text_content The text content to analyze
"""
if not text:
return "Syntax: /analyze_sentiment <your text here>"
client = language_v1.LanguageServiceClient()
# Av... | b0ce560e778366c68bb8efec1e27f035d40508d0 | 40,529 |
def abbreviate_for_xray(payload: dict) -> dict:
"""
If the payload includes a file, the file is translated
to just it's name and size instead of including the
whole file.
"""
for k in payload.keys():
v = payload.get(k)
if isinstance(v, File):
v = {"type": v.type, "siz... | f46eab117e41b5ed257250d00e64da3b85041f7a | 40,530 |
def get_version(release):
""" Given x.y.z-something, return x.y
On ill-formed return verbatim.
"""
if '.' in release:
sl = release.split(".")
return '%s.%s' % (sl[0], sl[1])
else:
return release | 520438d5ca260caf27df31c4742d9da8c31f3218 | 40,531 |
def arrays_shape(*arrays):
"""Returns the shape of the first array that is not None.
Parameters
----------
arrays : ndarray
Arrays.
Returns
-------
tuple of int
Shape.
"""
for array in arrays:
if array is not None:
shape = array.shape
... | e9e6a4876b938934c843386dffc58f0eccfb20a3 | 40,532 |
def get_coords_2d(obj, P):
"""
calculate the image (2d) coordinates of the 3d bounding box
of an object.
"""
bbox3 = get_coords_3d(obj)
# Rl = obj.Rl
# height = obj.height
# width = obj.width
# length = obj.length
# x = obj.x
# y = obj.y
# z = obj.z
# bbox = np.array(... | 6a0c079addab8a4379f7eafcb90094bdb8188383 | 40,533 |
def setPanicProperty(prop, value):
"""
Method to write global properties
It manages compatibility with PANIC <= 6 using PyAlarm properties
"""
print('setPanicProperty(%s, %s)' % (prop, value))
r = get_tango().get_property('PANIC',[prop])[prop]
o = get_tango().get_class_property('PyAlarm',[p... | 34ba09d338d4ff91a3df7b868f0e662c4119ae35 | 40,534 |
import math
def gridSquare(eastings, northings, squaresize):
"""Returns the appropriate National Grid Reference including 100km letters.
eastings: in metres between 0 and 700000
northings: in metres between 0 and 1300000
squaresize: in kilometres, valid values are 100,10,5,1,0.5,0.1,0.01,0.001
""... | 4149b49c426c895798dcf55a7973370764f06f03 | 40,535 |
def findGenSubClasses(superclass):
"""Find all Generator sub-classes of a certain class, e.g. ODEsystem."""
assert isinstance(superclass, str), \
"findGenSubClasses requires a string as the name of the class to search for subclasses."
subclasslist = []
sc = eval(superclass)
for x in theGe... | a0510e3eb67297483f99ce0326e6be9fe05f211b | 40,536 |
import os
def delete_cache(package, location):
"""
Remove selected cached data, please run print_cache() to get path.
Parameters
----------
location : str
Returns
-------
result : boolean
"""
home, _ = _get_home(package=package)
if not isinstance(location, str):
... | 969f7715e78dc67efd339c9efc8f2e6eb2389607 | 40,537 |
import os
def get_artemis_data_path(relative_path ='', make_local_dir = False):
"""
Get the full local path of a file relative to the Data folder. If the relative path starts with a "/", we consider
it to be a local path already. TODO: Make this Windows-friendly
:param relative_path: A path relativ... | f482479347622b170ae628b15d845a82fa63c42a | 40,538 |
def PSQRT(N, C, M, A):
"""
PSQRT finds the first m + 1 coefficients of the square-root power series
$$ (c_0 + c_1 \, z + \cdots + c_n \, z^n) ^{0.5} = a_0 + a_1 \, z +
+ a_2 \, z^2 + \cdots $$
p. 32
"""
A[0] = SQRT(C[0])
TA = 2 * A[0]
A[1] = C[1] / TA
A[2] = (C[2] - A... | f6a9d11adc39e8b345c859c187c88d5f786837d8 | 40,539 |
import os
def check_is_board(riotdir, board):
"""Verify if board is a RIOT board.
:raises ValueError: on invalid board
:returns: board name
"""
if board == 'common':
raise ValueError("'%s' is not a board" % board)
board_dir = os.path.join(riotdir, 'boards', board)
if not os.path.i... | 94ecf0ca5762e66e667f7021af83038d982a0ff0 | 40,540 |
def overview_command():
"""Market data overview [Wall St. Journal]"""
# Debug user input
if imps.DEBUG:
logger.debug("econ-overview")
# Retrieve data
df = wsj_model.market_overview()
# Check for argument
if df.empty:
raise Exception("No available data found")
df["Last ... | 5470de0db7c655e43c4b8c8b671a576c9c07df7b | 40,541 |
def load_manga(f):
""" Load manga object by query manga_id into g.manga
"""
@wraps(f)
def wrapper(manga_id, *args, **kwargs):
manga = Manga.query.get(manga_id)
if not manga:
return jsonify({
'code': 404,
'message': 'Not Found'
}), 4... | 53b71245ca84466cbde8dec3f28414b9d167bfe9 | 40,542 |
def pln_reflection_basis(pt_coord, pln_pt, pln_normal):
"""
Symétrie mirroir, en 3D, par rapport à un plan.
Le plan est défini par une normale et un point contenu dans ce plan.
"""
# ? laisser la possibilité d'utiliser directement un np.array ou une liste
# ? pour donner les coordonnées pour plu... | aa6269ce06337b8dbcda50a232e521ed663af22e | 40,543 |
import asyncio
def global_bluetooth_lock():
"""Initialize the global bluetooth lock inside the current event loop."""
global GLOBAL_BLUETOOTH_LOCK # pylint: disable=global-statement
if GLOBAL_BLUETOOTH_LOCK is None:
GLOBAL_BLUETOOTH_LOCK = asyncio.Lock()
return GLOBAL_BLUETOOTH_LOCK | 6494062b3ae2a7718725d83b25a4866288c0085d | 40,544 |
def max_profit(prices):
"""
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock),
design an algorithm to find the maximum profit.
Note that you cannot s... | 056dff9d2ad4af9d38f2ce0f1ad27c1c0df69121 | 40,545 |
def intrinsic_photo_all(
request,
category_id='all',
filter_key='all',
template="intrinsic/photo_all.html",
extra_context=None):
""" View judgements in images with each image taking up a block and the
list of photo categories on the left """
entries = Photo.objects.... | d74ef53fbb16a4f574408f60e4ec7e281220f004 | 40,546 |
def get_authenticated_api_session(username, password):
"""
:return: an authenticated api session
"""
session = MoJOAuth2Session(
client=LegacyApplicationClient(
client_id=settings.API_CLIENT_ID
)
)
session.fetch_token(
token_url=get_request_token_url(),
... | 98fec31770dc73e714b6b80062a8ee218cf23c9d | 40,547 |
def add_customer_invoice(customer_invoice_data):
"""
添加信息
:param customer_invoice_data:
:return: None/Value of user.id
:except:
"""
return db_instance.add(CustomerInvoice, customer_invoice_data) | 4f8ae6dfacfcb1c1b0b94a7143b045fe60988987 | 40,548 |
from typing import Dict
from typing import Union
from typing import List
import os
import logging
import io
def get_matrix_from_cellranger_mtx(filedir: str) \
-> Dict[str, Union[sp.csr.csr_matrix, List[np.ndarray], np.ndarray]]:
"""Load a count matrix from an mtx directory from CellRanger's output.
F... | e169451c00893cda7ad4321c5d971a9363e85fe6 | 40,549 |
def model_as_json(bot_entries):
""" Casts a list of lists into a list of modeled dictionaries. New data format is JSON-like and suitable for MongoDB
@param
bot_entries (list) list of sub-lists
@returns
json_list (list) list of modeled dictionaries
"""
... | e18d4c29cdeda950bd0b32db5354f197e38f27ff | 40,550 |
def encompasses_broadcastable(b1, b2):
"""
Parameters
----------
b1
The broadcastable attribute of a tensor type.
b2
The broadcastable attribute of a tensor type.
Returns
-------
bool
True if the broadcastable patterns b1 and b2 are such that b2 is
broad... | 297a709a4f27de85952f48d112013001a7b6b433 | 40,551 |
import types
import numba
def get_key_dict_overload(arr):
"""returns dictionary and possibly a byte_vec for multi-key case
"""
# get byte_vec dict for multi-key case
if isinstance(arr, types.BaseTuple) and len(arr.types) != 1:
n_bytes = 0
context = numba.targets.registry.cpu_target.tar... | f833eb66ecca66394d0322cb41903695212bff29 | 40,552 |
import os
import glob
def get_file_names_from_dir(dir, extension):
""" gets all file names with extension from directory
Args:
dir (string): directory to look for files
extension (string): extension with no '.' ie 'tif', 'JPG'
"""
return [y for x in os.walk(dir) for y in glob(os.path.... | a2593e43e1f69227e4d1da6f6f257434cf8b0041 | 40,553 |
def week():
"""Get latest weekly ranks."""
url = f"{BASE_URL}/week/index.htm"
return utils.get_ranks(url, SELECTOR, parser) | d5bcf3244ecd55f126af9b17db7c33187d1474fa | 40,554 |
def cone(toplexes, subcomplex, coneVertex="*"):
"""Construct the cone over a subcomplex. The cone vertex can be renamed if desired. The resulting complex is homotopy equivalent to the quotient by the subcomplex."""
return toplexes + [spx + [coneVertex] for spx in subcomplex] | 6b1328a2f7c32988666b0c7039efd0ce6ecdffef | 40,555 |
from typing import Any
async def read_item(
*,
con: AsyncIOConnection = Depends(db.get_con),
item_id: UUID,
current_user: schemas.User = Depends(auth.get_current_active_user),
) -> Any:
"""
Get item by id.
"""
item = await crud.item.get(con, id=item_id)
if not item:
raise H... | 8dbc91c0e17e84ed99b3e74e719e12da0f8b1d75 | 40,556 |
from typing import List
async def get_max_power(
token: str,
cups: str,
distrubutor_code: int,
start_date: str,
end_date: str,
authorized_nif: str = None,
) -> List[MaxPower]:
"""Search the maximum power and the result will appear in kW
Args:
token (str): Bearer token
... | 7a4d5d99f8927be64582333453cbacd90b5c93ac | 40,557 |
import logging
def filter_remove_keyword_images(keywords_set, keyword_list, use_lemma=True):
"""Filter keyword-image pairs removing all images with keywords in the specified list.
NOTE: this should be used instead of `filter_remove_images` to remove all
image instances associated with remove keyword, inc... | cce733abd5d224ceb66d2e2645b06d6c4e6dc237 | 40,558 |
def replace(correct, guess, correct2):
"""
Find out if your guess is in the correct answer or not, if yes, put it into your answer
"""
ans = ''
i = 0
for ch in correct:
if guess == ch:
ans += correct[i]
else:
ans += correct2[i]
i += 1
# for i i... | aacd9142599cc815a5526350c96b4db09b74777d | 40,559 |
def V_morse_1dof(x, par):
"""
Parameters
----------
x : TYPE
independent variable value of the potential energy function.
par : TYPE
parameters of the potential energy function.
Returns
-------
V : TYPE
potential energy of the 1 DOF morse oscillator system ... | 8f91a99af2e8b755b2756c8820f0fe044da1999a | 40,560 |
def broadcastable(shape_1, shape_2):
"""Returns whether the two shapes are broadcastable."""
return (not shape_1 or not shape_2 or
all(x == y or x == 1 or y == 1
for x, y in zip(shape_1[::-1], shape_2[::-1]))) | 9a968fdee4a401b5f9cee42286de7553afa02183 | 40,561 |
import json
from datetime import datetime
def getAccount():
"""
API has been changed to accept only POST requests. Path of API has been changed.
Now the body of POST must be
{
"username" : 17BECXXXX,
"password" : password
}
"""
# First check if query is okay or not
dat... | 3976aa5b30ee90e11396269149d2b752bfbd35db | 40,562 |
def mesos_cluster_memory_resource_total_range(cluster_id, start, end):
"""mesos集群内存总量, 单位MB"""
step = (end - start) // 60
prom_query = f"""
max by (cluster_id) (bkbcs_scheduler_cluster_memory_resource_total{{cluster_id="{cluster_id}"}})
""" # noqa
resp = query_range(prom_query, start, end, ... | b551c6d4430e3d6bb11d5869801143a3ad794215 | 40,563 |
def bipartite_sets(bg):
"""Return two nodes sets of a bipartite graph.
Parameters:
-----------
bg: nx.Graph
Bipartite graph to operate on.
"""
top = set(n for n, d in bg.nodes(data=True) if d['bipartite']==0)
bottom = set(bg) - top
return (top, bottom) | 618756dbfa87dc0b5d878545fa5395c4a122c84c | 40,564 |
import logging
import argparse
import sys
def parse_args():
"""
The argument parser
"""
logger = logging.getLogger()
parser = argparse.ArgumentParser(
description=help_description(), epilog=help_epilog()
)
parser.formatter_class = argparse.RawDescriptionHelpFormatter
parser... | abc85b4d7236d5347143a817ac36720c84094a77 | 40,565 |
from datetime import datetime
def log(args, msg):
"""
Prints the message if debugging is turned on.
"""
def __now():
return datetime.utcnow().isoformat()
if args.debug:
print(f"[{__now()}] {msg}") | d32d02be56c4a060801a14786ce6a5e258da6f23 | 40,566 |
def match_any(audit_id, result_to_compare, args):
"""
Match list of strings
:param result_to_compare:
The value to compare.
:param args:
Comparator dictionary as mentioned in the check.
"""
log.debug('Running string::match_any for check: {0}'.format(audit_id))
for option_to... | 47897beab5675f7b3d52bffde5ab404575423bfc | 40,567 |
def find_mqtt_topic(name: str) -> str:
"""
Based on the button name find the corresponding mqtt command
"""
if name == BUTTON_SHUFFLE:
return PHONIEBOX_CMD_PLAYER_SHUFFLE
if name == BUTTON_SCAN:
return PHONIEBOX_CMD_SCAN
if name == BUTTON_REWIND:
return PHONIEBOX_CMD_PLAY... | 6856c45c5b2f9d7ac446988f55838ce6fd6601e0 | 40,568 |
def next(aList, index):
""" Return the index to the next element (compared to the element
with index "index") in aList, or 0 if it already is the last one.
Useful to make a list of loop.
"""
return (index+1) % len(aList) | d3bae9776d32cf1f52bb325cb0a7d9f3ff622d6c | 40,569 |
def load_shp_data(path, drivername='ESRI Shapefile'):
"""
Returns shp file dataset
Parameters
----------
path : str
Path to shp file
drivername : str, optional
ogr driver name (default: 'ESRI Shapefile')
Returns
-------
shp : object
shp data object
"""
... | 4a8c05c950f7245f0322a71467fcd77f8872c583 | 40,570 |
def test_rshift_into_node(clear_default_graph):
"""Test the node rshift operator with an INode as target.
Note that OutputPlug >> INode is tested in the plug tests."""
@Node(outputs=["marker"])
def Node1():
return {"marker": None}
@Node(outputs=[])
def Node2(marker):
return {}
... | daec45c84656a298c4492a89aba589d44a519b45 | 40,571 |
def htmlize(widget):
"""
Jinja filter to render a widget to a html string
"""
html = widget.render(widget)
try:
html = html.decode('utf-8')
except Exception:
pass
return html | a6c4aeac2bc27aeaaccbe78b893ca33181234169 | 40,572 |
def parse_date_format(string: str) -> str:
"""
Parses the date-format string for date-type attributes.
TODO: Implement. csterling
:param string: The date-format string to parse.
:return: Currently, just the input.
"""
return string | b2073b28a203e5b510e7102ca6960ec55810bbe7 | 40,573 |
def parallel_pre_compile_op(job: TbeJob):
"""
Parallel pre compile op
:param job:
:return:
"""
compute_op_info_list = get_compute_op_list(job.content)
if len(compute_op_info_list) != 1:
job.error("Invalid op compute num ({}) in pre compile op".format(len(compute_op_info_list)))
... | 52f4291c176293e56879701242183a21beb36c94 | 40,574 |
def transformFromOutputMatrix(curveMatrix=None, transformType='locator', showLocalAxis=True):
"""create a connected transform for each output.outputMatrix"""
curveMatrix = (mc.ls(curveMatrix, type='prCurveMatrix') or
mc.ls(sl=True, type='prCurveMatrix') or
[None])[0]
tr... | 896b011473f0c2b599dd5c88335d3a9d705045a2 | 40,575 |
def search_sensor_id(endpoint: str) -> int:
""" Retrieve list of connected sensors from:
Integration: VMware Carbon Black EDR (Live Response API).
Command: cb-list-sensors.
Args:
endpoint: Endpoint name - hostname/IP
Returns:
str: sensor id if found else empty string... | 2ef2fe246f379fef4d5288199ffbb272de00ff81 | 40,576 |
import time
def get_packing_recipe(args, sequence_lengths):
"""Given program arguments and a list of sequence lengths return the packing recipe.
A "packing recipe" primarily consists of a set of strategies "strategy_set" and the "mixture"
which states how many times each one of these strategies should be... | 16378a0f33e7fd2f4d0d7411b628d882178a3715 | 40,577 |
def _merge_block(internal_transactions, transactions, whitelist):
"""
Merge responses with trace and chain transactions. Remove non-whitelisted fields
Parameters
----------
internal_transactions : list
List of trace transactions
transactions : list
List of chain transactions
... | b60c9cde133d97ac84b2899956a15a72c720bbaa | 40,578 |
import sys
import os
import time
def make_skies_for_a_brick(survey, brickname, nskiespersqdeg=None, bands=['g', 'r', 'z'],
apertures_arcsec=[0.75], write=False):
"""Generate skies for one brick in the typical format for DESI sky targets.
Parameters
----------
survey : :clas... | 3ca26d5ac3220da68d6ec55774ad26a52b021831 | 40,579 |
import subprocess
def findProcesses(user=None, exe=None):
"""Find processes in process list.
Args:
user: str, optional, username owning process
exe: str, optional, executable name of process
Returns:
dictionary of pids = {
pid: {
'user': str... | 0aaac3c0620ca898397b4f6af97c0fcb177ba3b7 | 40,580 |
from typing import Type
from re import T
def parse_item(location: str, item_type: Type[T], item_name_for_log: str = None,
file_mapping_conf: FileMappingConfiguration = None,
logger: Logger = default_logger, lazy_mfcollection_parsing: bool = False) -> T:
"""
Creates a RootParser()... | ca0eb0cc35edc850d64027ef0e5ce77e50fbd841 | 40,581 |
from re import T
from operator import ne
def tpow(x: T.Tensor, a: float) -> T.Tensor:
"""
Elementwise power of a tensor x to power a.
Args:
x: A tensor.
a: Power.
Returns:
tensor: Elementwise x to the power of a.
"""
return ne.evaluate('x**a') | 21c249561fdbac398dca6d0f0cb2b4655cde7ba7 | 40,582 |
def get_last_price(base,quote, return_price_only):
"""
Args:
'DOT', 'USDT'
"""
tickers = spot_api.list_tickers(currency_pair=f'{base}_{quote}')
assert len(tickers) == 1
t = tickers[0]
if return_price_only:
return t.last
logger.info(f"GET PRICE: {t.currency_pair} | last={... | 42921f8eebce8ce59506305444ee4c4bfe2be851 | 40,583 |
import os
def load_state_dict_from_url(url: str, path: str, md5: str=None) -> os.PathLike:
"""
Download and load a state dict from url
"""
if not os.path.isdir(path):
os.makedirs(path)
download.get_path_from_url(url, path, md5)
return load(os.path.join(path, os.path.basename(url))) | abec19e817cc1f41f7f799b4cb3d37f40443201b | 40,584 |
import hashlib
def decrypt_lsa_key_nt5(lsakey, syskey):
"""
This function decrypts the LSA key using the syskey
"""
dg = hashlib.md5()
dg.update(syskey)
for i in xrange(1000):
dg.update(lsakey[60:76])
arcfour = RC4(dg.digest())
deskey = arcfour.encrypt(lsakey[12:60])
return... | 90243119f42a0df473fe1f9c1028808295ba660d | 40,585 |
def __iot_policy_version_exists(cleaner, iot_policy_name, iot_policy_version_id):
"""
Verifies if a policy version exists. This is should be replaced once iot supports Waiter objects for policy
deletion.
:param cleaner: A Cleaner object from the main cleanup.py script
:param iot_policy_version_id: C... | e45954b0f02b04081d30c0cec61c36f26d04acfb | 40,586 |
from typing import Callable
def milne_predictor_corrector_method(f: Callable[[float, float], float],
y0: float,
x: list[float],
h: float,
yl: list[float]) -> float:
"... | 9e8b10bb5689a906c1f3f7774138ea5f3203e06e | 40,587 |
def value_at_risk_percent(df: pd.DataFrame, t: int, period=10, alpha=0.95, price_col='Close'):
"""Calculates the Value at Risk (VaR) of time period
"""
# t must be bigger than 2 to evaluate percentile
if t-period+2 < 0:
var_df = df.iloc[1:t+1]
else:
var_df = df.iloc[t-period+1:t+1]
... | 37fa5e3bfdcafbd9dbb25bb6e056c4c8639990b0 | 40,588 |
from pathlib import Path
def read_xml(f: Path) -> ElementTree.Element:
"""Read an XML file and return the root"""
with open(f, "r") as xml_file:
return ElementTree.XML(xml_file.read()) | 9a145aeb2d5c7e79825984cc75fc53bd1d89c209 | 40,589 |
def dcg_score(y_true, y_score, k=10, gains="exponential"):
"""Discounted cumulative gain (DCG) at rank k
Parameters
----------
y_true : array-like, shape = [n_samples]
Ground truth (true relevance labels).
y_score : array-like, shape = [n_samples]
Predicted scores.
k : int
... | e7c3cc8a2c31b173cf19cfd2b19c8a37f9aa9345 | 40,590 |
from pathlib import Path
def get_resource_file(resource_name):
"""
:param resource_name: The name of the resource file placed in `SFUTranslate/resources` directory
:return: an object of `pathlib.PosixPath` which can be directly opened or traversed
"""
return Path(get_resources_dir(), resource_name... | fe3b8f289cd2e2a06dfb0e42a15707152dd6e946 | 40,591 |
def _conv_number(number, typen=float):
"""Convert a number.
Parameters
----------
number
Number represented a float.
typen :
The default is ``float``.
Returns
-------
"""
if typen is float:
try:
return float(number)
except:
... | f34bd409c78f25e2179e4f72a6e039ff04432392 | 40,592 |
def is_simple_path(G: nx.Graph, path: VertexList) -> bool:
"""Is the path simple in the graph?
Args:
G: input graph
path: Ordered sequence of vertices
Returns:
True if the path is simple in the graph
"""
return is_walk(G, path) and len(path) == len(set(path)) | d276ff9176c44ae630f59b6274f26cec6d4036e5 | 40,593 |
import sys
def _build_image(client, tag, path) -> Image:
"""
Helper function to get a correct type
"""
try:
return _try_build_image(client, tag, path)
except DppError as e:
message.stdout_progress_error(e)
sys.exit(1) | 9f907de6b767f96af5dafbb6130633cccc2e2f58 | 40,594 |
from datetime import datetime
def str_to_datetime(sdt: str) -> datetime:
"""try convert str to datetime with DATETIME_TYPE format until no exception"""
if sdt:
for k in DATETIME_TYPE:
try:
return datetime.strptime(sdt, k.value)
except:
pass
... | 8d945c7fa5e7ddbd7c58e6a9cfc110b474c4615f | 40,595 |
def remove_virtual_slot_cmd(lpar_id, slot_num):
"""
Generate HMC command to remove virtual slot.
:param lpar_id: LPAR id
:param slot_num: virtual adapter slot number
:returns: A HMC command to remove the virtual slot.
"""
return ("chhwres -r virtualio --rsubtype eth -o r -s %(slot)s "
... | 2c6f14949910865f3a60c0016b4587088441572e | 40,596 |
from datetime import datetime
def daily_quota(day=None):
"""Return the daily quota for a given day.
:param day: date object (defaults to today)
"""
if day is None:
day = datetime.today()
if HAPPY_HOUR_START <= day and day < HAPPY_HOUR_END:
return HAPPY_HOUR_QUOTA
elif day.wee... | 9d5f67834e1e6cd43b85b0b85a1af4f73521eeaa | 40,597 |
import json
def dict_to_bytestring(dictionary):
"""Converts a python dict to json formatted bytestring"""
return json.dumps(dictionary).encode("utf8") | 31e201d87e92075d6078450ad019cc51f474f9d4 | 40,598 |
def login():
"""
Login user to ZenType account.
"""
r = request.get_json()
user_email = r.get('email', None)
user_password = r.get('password', None)
userDO = UserAuth.find_user_and_validate_password(
email=user_email,
password=user_password
)
if userDO is not None:
# if the user was created successfu... | 7dcb2e6bdd3d67f1f4a83c2c0c62e8901d291dae | 40,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.