content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def parse(puzzle_input):
"""Parse input"""
return [tuple(line.split()) for line in puzzle_input.split('\n')] | 42cb62348c5a6c9893480e71db7b60a6053ea4d0 | 33,900 |
def set_new_pw_extra_security_phone(email_code: str, password: str, phone_code: str) -> FluxData:
"""
View that receives an emailed reset password code, an SMS'ed reset password
code, and a password, and sets the password as credential for the user, with
extra security.
Preconditions required for t... | cc695d439d4c0bb6e7ebc6dff9a1049d948a3dd0 | 33,901 |
import getpass
def get_driver_and_zones(driver_name, account_name):
"""
Get the DNS driver, authenticate, and get some zones.
"""
secret_site = "libcloud/" + driver_name
cls = get_driver(driver_name)
pw = get_password(secret_site, account_name)
if not pw:
pw = getpass("Password:")... | 9217ff7082dbcd79154e278d97d47fecbaa574e9 | 33,902 |
def normalize(seed_url, link):
"""Normalize this URL by removing hash and adding domain
"""
link, _ = urldefrag(link)
return urljoin(seed_url, link) | 7e4d5bfbef2cb92869718d0d21acd86a5529aa1b | 33,903 |
def multi_lab_segmentation_dilate_1_above_selected_label(arr_segm, selected_label=-1, labels_to_dilate=(), verbose=2):
"""
The orders of labels to dilate counts.
:param arr_segm:
:param selected_label:
:param labels_to_dilate: if None all labels are dilated, in ascending order (algorithm is NOT orde... | fbc4f0a93cd9d80ef1f1cae23e79612881bcf5da | 33,904 |
import gc
def solver_wrapper(term_spec_list, solver_opts, chain_opts, **kwargs):
"""A Python wrapper for the solvers written in Numba.
This wrapper facilitates getting values in and out of the Numba code and
creates a dictionary of results which can be understood by the calling
Dask code.
Args:
... | a7fc128074be64c06b79a448b0cd71d2051cf355 | 33,905 |
from datetime import datetime
def POST(request):
"""Add a new Topology to the specified project and return it"""
request.check_required_parameters(path={'projectId': 'string'}, body={'topology': {'name': 'string'}})
project = Project.from_id(request.params_path['projectId'])
project.check_exists()
... | 9ee233a708b2093ee482bb3e80f25c70f8eed4ae | 33,906 |
import ray
def deconvolve_channel(channel):
"""Deconvolve a single channel."""
y_pad = jax.device_put(ray.get(y_pad_list)[channel])
psf = jax.device_put(ray.get(psf_list)[channel])
mask = jax.device_put(ray.get(mask_store))
M = linop.Diagonal(mask)
C0 = linop.CircularConvolve(
h=psf, i... | fc861fb6df2caa6a9dddce14d380c519f6bb84c1 | 33,907 |
import os
def seg_ventricles(paths: dict, settings: dict, verbose: bool = True) \
-> tuple[dict, dict]:
"""
This function performs the ventricle segmentation.
It has two variations, one of which is the FreeSurfer
based implementation, which builds upon previously run
FreeSurfer output. The... | 6e036700f12b236382069ba07167f018824751bc | 33,908 |
def sell():
"""Sell shares of stock"""
if request.method == "POST":
symbol = request.form.get("symbol").upper()
shares = request.form.get("shares")
stock = lookup(symbol)
if (stock == None) or (symbol == ''):
return apology("Stock was not found.")
elif not sha... | 3328fba46393455be0baecffb05fdbf4d1a5c770 | 33,909 |
def _compute_third(first, second):
""" Compute a third coordinate given the other two """
return -first - second | 57ea03c71f13f3847d4008516ec8f0f5c02424af | 33,910 |
def decipher(criptotext):
"""
Descifra el mensaje recuperando el texto plano siempre y cuando haya
sido cifrado con XOR.
Parámetro:
cryptotext -- el mensaje a descifrar.
"""
messagedecrip = ""
for elem in criptotext:
code = ord(elem)^1
messagedecrip += chr(code)
return messaged... | c90fc56fda9e65690a0a03ea7f33008883feb3f4 | 33,911 |
def mag(initial, final):
"""
calculate magnification for a value
"""
return float(initial) / float(final) | ab996ee84ff588ce41086927b4da1a74e164278a | 33,912 |
def fetch_ids(product: str, use_usgs_ftp: bool = False) -> [str]:
"""Returns all ids for the given product."""
if use_usgs_ftp:
return _fetch_ids_from_usgs_ftp(product)
else:
return _fetch_ids_from_aws(product) | 10af69c7fe77255ff955c2f97b6056b41cd51d59 | 33,913 |
def to_be_implemented(request):
"""
A notice letting the user know that this particular feature hasn't been
implemented yet.
"""
pagevars = {
"page_title": "To Be Implemented...",
}
return render(request, 'tbi.html', pagevars) | 4ee786b35589a94c0ccb8fe20bae368a594b44f1 | 33,914 |
def unet_brain_connector(wf, cfg, strat_pool, pipe_num, opt):
"""
UNet
options (following numbers are default):
input_slice: 3
conv_block: 5
kernel_root: 16
rescale_dim: 256
"""
unet_mask = pe.Node(util.Function(input_names=['model_path', 'cimg_in'],
... | 559770a4b122970dc7b8a743adb11fd815c3ce21 | 33,915 |
def ganache_second_account(smart_contracts_dir: str):
"""
Returns the second ganache account.
Useful for doing transfers so you can transfer to an
ethereum address that doesn't have anything to do with
paying gas fees.
"""
return ganache_accounts(smart_contracts_dir)["accounts"][1].lower() | 8845f0445c37f48f782dd72ce4be6a31d17502d6 | 33,916 |
def _parse_list_of_lists(string, delimiter_elements=',', delimiter_lists=':', delimiter_pipelines=';', dtype=float):
""" Parses a string that contains single or multiple lists.
Args:
delimiter_elements <str>: delimiter between inner elements of a list.
delimiter_lists <str>: delimiter between l... | d0d14efba74863ec95245255ca10db48fcfb7a01 | 33,917 |
from typing import List
def get_available_dictionaries() -> List[str]:
"""
Return a list of all available dictionaries
Returns
-------
List[str]
Saved dictionaries
"""
return get_available_models("dictionary") | 37c2b882fc443593a45329a2ddd44c517979c342 | 33,918 |
import requests
def get_unscoped_token(os_auth_url, access_token, username, tenant_name):
"""
Get an unscoped token from an access token
"""
url = get_keystone_url(os_auth_url,
'/v3/OS-FEDERATION/identity_providers/%s/protocols/%s/auth' % (username, tenant_name))
respons... | 252990f59f4bc254337dc0f7e13583b7a383d315 | 33,919 |
import numpy
def _pfa_check_stdeskew(PFA, Grid):
"""
Parameters
----------
PFA : sarpy.io.complex.sicd_elements.PFA.PFAType
Grid : sarpy.io.complex.sicd_elements.Grid.GridType
Returns
-------
bool
"""
if PFA.STDeskew is None or not PFA.STDeskew.Applied:
return True
... | 987c492e1210114bf8eb129f60711f280b116a75 | 33,920 |
import os
def get_user(home_at=('/home', '/var', '/opt', '/usr')):
"""Try to find the user who executed the script originally.
:param home_at: List of directories containing home directories
:return: User who probably run the script as pwd struct
It will look the process tree up until it finds a uid... | 658fe193084ac731580ae47fb92a82ebb48e8541 | 33,921 |
import json
def get_peers_for_info_hash_s3(
info_hash,
limit=50
):
"""
Get current peers, S3.
"""
remote_object = s3.Object(BUCKET_NAME, info_hash + '/peers.json').get()
content = remote_object['Body'].read().decode('utf-8')
torrent_info = json.loa... | d1e0ee2112e399d76bdf31774abbf32dbca31526 | 33,922 |
def RGB_to_Lab(RGB, colourspace):
"""
Converts given *RGB* value from given colourspace to *CIE Lab* colourspace.
Parameters
----------
RGB : array_like
*RGB* value.
colourspace : RGB_Colourspace
*RGB* colourspace.
Returns
-------
bool
Definition success.
... | 6942134980f1b0e6ca37276c1d2becec23ba3a2f | 33,923 |
def ltl2ba(formula):
"""Convert LTL formula to Buchi Automaton using ltl2ba.
@type formula: `str(formula)` must be admissible ltl2ba input
@return: Buchi automaton whose edges are annotated
with Boolean formulas as `str`
@rtype: [`Automaton`]
"""
ltl2ba_out = ltl2baint.call_ltl2ba(str(... | 289178f071675cf62546b4403dc8751540c5633f | 33,924 |
def count_org_active_days(odf_day):
"""Return count of active days in org history"""
odf_not_null = org_active_days(odf_day)
return len(odf_not_null) | 13733482dd0a4dcad5cf7a7eb28add145a08dc2f | 33,925 |
import asyncio
import functools
async def update_zigbee_firmware(host: str, custom: bool):
"""Update zigbee firmware for both ZHA and zigbee2mqtt modes"""
sh = TelnetShell()
try:
if not await sh.connect(host) or not await sh.run_zigbee_flash():
return False
except:
pass
... | 00fe85632f55fe4a853ab55f9c2333263b3f6f86 | 33,926 |
def underdog(df):
"""
Filter the dataframe of game data on underdog wins
(games where the team with lower odds won).
Returns: tuple (string reason, pd dataframe)
"""
reason = 'underdog'
filt = df.loc[df['winningOdds']<0.46]
filt = filt.sort_values(['runDiff', 'winningScore'], ascending=[... | 11e8f54d5deb1d61b2feaac163c6c896839a9af8 | 33,927 |
def plot_sino_coverage(theta, h, v, dwell=None, bins=[16, 8, 4],
probe_grid=[[1]], probe_size=(0, 0)):
"""Plots projections of minimum coverage in the sinogram space."""
# Wrap theta into [0, pi)
theta = theta % (np.pi)
# Set default dwell value
if dwell is None:
dwell... | 0179fe192343dcb4ad25297b12981fa2049911f7 | 33,928 |
def divisors(n):
"""Returns the all divisors of n"""
if n == 1: return 1
factors = list(distinct_factors(n))
length = int(log(n, min(factors))) + 1
comb = [item for item in product(list(range(length + 1)), repeat=len(factors))]
result = []
for e in comb:
tmp = []
for p, c in zip(factors, e):
tmp.append(in... | ba6739d65e04c354fc8b52b592ba10e5502f407d | 33,929 |
import itertools
def compute_features_levels(features, base_level=0):
"""Adapted from dnafeaturesviewer, see https://github.com/Edinburgh-Genome-Foundry/DnaFeaturesViewer
Author: Zulko
Compute the vertical levels on which the features should be displayed
in order to avoid collisions.
`features` m... | 93db63a854c2cf237a46d971286bb07feec4c3c1 | 33,930 |
def normalize_answer(s):
"""Lower text and remove extra whitespace."""
def remove_articles(text):
return re_art.sub(' ', text)
def remove_punc(text):
return re_punc.sub(' ', text) # convert punctuation to spaces
def white_space_fix(text):
return ' '.join(text.split())
def... | 9c0c378ae6da3a81c88cb06795ae8f2b2c6eb656 | 33,931 |
def bq_db_dtype_to_dtype(db_dtype: str) -> StructuredDtype:
"""
Given a db_dtype as returned by BigQuery, parse this to an instance-dtype.
Note: We don't yet support Structs with unnamed fields (e.g. 'STRUCT<INT64>' is not supported.
:param db_dtype: BigQuery db-dtype, e.g. 'STRING', or 'STRUCT<column... | 5207c3eabaf424580f481d4433c8bf7716af59db | 33,932 |
def getPixelSize(lat, latsize, lonsize):
""" Get the pixel size (in m) based on latitude and
pixel size in degrees
"""
# Set up parameters for elipse
# Semi-major and semi-minor for WGS-84 ellipse
ellipse = [6378137.0, 6356752.314245]
radlat = np.deg2rad(lat)
Rsq = (ellips... | 3df8e6d17f377493e469fb01e6657eec464ca632 | 33,933 |
def success_response( message, code = 200 ):
"""Returns a JSON response containing `success_message` with a given success code"""
return jsonify( { 'success_message' : message } ), code | 64d3e46872fc17abb0825e8345bfc9929f97e74d | 33,934 |
def sensorsuite(w,q,Parameters):
""" Measurements by onboard sensors """
w_actual = w
q_actual = q
Q_actual = utils.quat_to_rot(q_actual)
bias = np.array([0.5,-0.1,0.2]) #np.zeros(3)
# Measurement of reference directions by Sun Sensor
rNSunSensor = Parameters['Sensors']['SunSenso... | cc78afe736ed61faed03e33a0354ece496ea82bb | 33,935 |
import requests
import time
def get_task_response(taskurl):
"""Check a task url to get it's status. Will return SUCCESS or FAILED, or timeout after 10 minutes (600s)
if the task is still pending
Parameters
----------
taskurl: str
URL to ping
Returns
-------
sta... | 470bad355fe0ce48081112e1b877524c6ba438d4 | 33,936 |
import tokenize
def align(gt, noise, gap_char=GAP_CHAR):
"""Align two text segments via sequence alignment algorithm
**NOTE**: this algorithm is O(N^2) and is NOT efficient for longer text.
Please refer to `genalog.text.anchor` for faster alignment on longer strings.
Arguments:
gt (str) : gr... | 7634349d49163e19235a49b1937e4fa26b3c26bd | 33,937 |
def get_similarity_order(labels, label_means, rank_proximity):
"""
This function take a dictionary of numeric data, and return the i-th closest data point
Parameters
----------
base_statistics : dict {label: (mean, covariance)}
each label is summurized by a mean and a covariance in the featu... | 183024f39fa714e1e427d3795203c257c24bfddf | 33,938 |
import json
def api_v1_votes_put():
"""Records user vote."""
# extract and validate post data
json_string = flask.request.form.get('vote', None)
if not json_string:
abort_user_error('Missing required parameter "vote".')
vote = json.loads(json_string)
post_uid = vote.get('uid')
if not post_uid:
... | e8cc7b9239d43af9a9f86b67ab7c34f27c81e197 | 33,939 |
import collections
def interpolate(vertices, target_vertices, target_triangles):
""" Interpolate missing data.
Parameters
----------
vertices: array (n_samples, n_dim)
points of data set.
target_vertices: array (n_query, n_dim)
points to find interpolated texture for.
target_t... | d1e3c1cf396f719ac8f68ada2cf4d672fc80f136 | 33,940 |
def parse_phot_table(table, rows):
"""
Retrieve filter information from the photometric file
Parameters
----------
path : str
path to LSST light curve file
rows : slice
range of rows for this SN
Returns
-------
dict
dictionary of filter data for the light cu... | 8029a981a8670dc475ee2e29b4fa410e0255ad6d | 33,941 |
def XOR(a: bool, b: bool) -> bool:
"""XOR logical gate
Args:
a (bool): First input signal
b (bool): Second input signal
Returns:
bool: Output signal
"""
return OR(AND(NOT(a), b), AND(a, NOT(b))) | 4b9bfed5454008970e3f3c50b2a16b5224082103 | 33,942 |
def create_list_from_dict(mydict):
"""
Converts entities dictionary to flat list.
Args:
mydict (dict): Input entities dictionary
Returns:
list
"""
outputs = []
for k, v in mydict.items():
if len(v) > 0:
for i in v:
outputs.append(i)
... | 50fba98b7590bd7d243464cf45be24c4405f2cef | 33,943 |
from typing import Iterable
from typing import Any
import numpy
def recode(
_x: Iterable,
*args: Any,
_default: Any = None,
_missing: Any = None,
**kwargs: Any,
) -> Iterable[Any]:
"""Recode a vector, replacing elements in it
Args:
x: A vector to modify
*args: and
... | b06b1467b55ad8c6c510088c7cd65777f384c415 | 33,944 |
from typing import List
from typing import Dict
from typing import Any
def get_details_for_all_categories(categories: List[str]) -> List[Dict[str, Any]]:
"""Get all api details for categories
:param categories List of all categories returned from server
:returns List of api details
"""
api_detail... | f712d2aa0843b33fdeec7f8d46f2f3e00b3caf17 | 33,945 |
from typing import Optional
def remove_event_listener_breakpoint(
eventName: str, targetName: Optional[str] = None
) -> dict:
"""Removes breakpoint on particular DOM event.
Parameters
----------
eventName: str
Event name.
targetName: Optional[str]
EventTarget interface... | a591eea060e7972e50962e53d5226755190a4e88 | 33,946 |
def iirnotch(w0, Q):
"""
Design second-order IIR notch digital filter.
A notch filter is a band-stop filter with a narrow bandwidth
(high quality factor). It rejects a narrow frequency band and
leaves the rest of the spectrum little changed.
Parameters
----------
w0 : float
Nor... | 03735f49548c643404d815f5fe78717471a8e437 | 33,947 |
def update_one(collection_name, _id, **kwargs):
"""
Update document in mongo
"""
collection = getattr(database, collection_name)
return collection.update_one({'_id': ObjectId(_id)}, {'$set': kwargs}) | 1ecd6b8113caa65179da6141b596d7f8f7093eef | 33,948 |
def AAPIEnterVehicle(idveh, idsection):
"""Execute command once a vehicle enters the Aimsun instance."""
global entered_vehicles
entered_vehicles.append(idveh)
return 0 | bfc93be891b104f1a8a3dd0de01265eaba04645c | 33,949 |
import time
import socket
import torch
import pickle
def get_predictionnet(args, model, unlabeled_dataloader):
"""Get predictions using a server client setup with POW on the server side."""
initialized = False
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 65432 # The port used by t... | a95c6dc14eb3ccbe804b60f1cbed720c93f6a1f1 | 33,950 |
async def get_history_care_plan(
api_key: str, doctor: Doctor = Depends(get_current_doctor)
):
"""Get all care plan for client"""
service = TestService()
return service.get_history_care_plan(api_key, doctor) | 9d7e1c56d93214b22f5018e739e1894ed03cf56b | 33,951 |
def bode(sys_list,w=None,x_lim=None,y_lim=None,dB=True,Hz=False,deg=True,log_x=True):
"""
Returns the impulse response of the continuous or discrete-time systems `sys_list`.
Parameters
----------
sys_list : system or list of systems
A single system or a list of systems to analyse
w ... | 4a11e8f7595ec6efeaac2a9a812f2620a5b5f737 | 33,952 |
def annotate_heatmap(im, data=None, valfmt="{x:.2f}",
textcolors=["white", "black"],
threshold=None, **textkw):
"""
A function to annotate a heatmap.
Parameters
----------
im
The AxesImage to be labeled.
data
Data used to annotate. If N... | 6b2f49ecc91ca4af9e7b93cfa05a2fc8348b362f | 33,953 |
def _extract_body(payload, embedded_newlines):
"""
Extract HTTP headers and body
"""
headers_str, body = payload.split('\r\n\r\n',1)
headers = {}
for line in headers_str.splitlines():
line = line.rstrip()
if line.find(':') > -1:
key, value = line.split(':',1)
... | 7ac74fe4454fd00e1ec718dc1c5bb1fe93e1dc37 | 33,954 |
def connect(db_url, *, external=False):
"""Connect to the database using an environment variable.
"""
logger.info("Connecting to SQL database %r", db_url)
kwargs = {}
if db_url.startswith('sqlite:'):
kwargs['connect_args'] = {'check_same_thread': False}
engine = create_engine(db_url, **k... | b62c5a22eeaf63e4989dbde4e685341f37e2a7a1 | 33,955 |
from typing import List
def containsDuplicate(nums: List[int]) -> bool:
"""
Time: O(n)
Space: O(n)
"""
visited = set()
for n in nums:
if n in visited:
return True
else:
visited.add(n)
return False | 673544bcd10d31d185b65cb7c4b4330a0a7199a4 | 33,956 |
import subprocess
import sys
import time
import re
import os
def getbans(chain = 'INPUT'):
""" Gets a list of all bans in a chain """
banlist = []
# Get IPv4 list
for i in range(0,MAX_IPTABLES_TRIES):
out = None
try:
out = subprocess.check_output([IPTABLES_EXEC, '--list', chain, '... | 3c028b675b76fcf3e8eaee39cc4f5907d8b22392 | 33,957 |
def getROC(detector = 0, methods = ['BDT']):
"""Get the ROC curve for a dectector given a set of methods testes
Keyword arguments:
detector -- detector used (default 0)
methods -- list of methods used (default ['BDT'])
"""
# retrive root tree as datafram
df= read_root('resultsDet{0}.root'... | 18e86eedfefd0fd079210a59a16f4537f311efbf | 33,958 |
def classify_dtypes_using_TF2_in_test(data_sample, idcols, verbose=0):
"""
If you send in a batch of Ttf.data.dataset with the name of target variable(s), you will get back
all the features classified by type such as cats, ints, floats and nlps. This is all done using TF2.
"""
print_features = False... | da6c9a82def789f5bb22c806b3cde294cd8d3631 | 33,959 |
def cs2coords(start, qstart, length, strand, cs, offset=1,
splice_donor=['gt', 'at'], splice_acceptor=['ag', 'ac']):
"""
# From minimap2 manual this is the cs flag definitions
Op Regex Description
= [ACGTN]+ Identical sequence (long form)
: [0-9]+ Identical sequence length
* [acgtn... | fa9b283ff58e494914e13aca552ca0bf71e8853a | 33,960 |
def gatherAnnotations(model):
"""Gathers custom properties annotating elements of the robot
across the model. These annotations were created in the model.py
module and are marked with a leading '$'.
Args:
model(dict): The robot model dictionary.
ignore_keys(list): Ignored annotation categor... | 5f65770065753836e43975e7d1a8a056e1090e5f | 33,961 |
def get_learner_goals_from_model(learner_goals_model):
"""Returns the learner goals domain object given the learner goals
model loaded from the datastore.
Args:
learner_goals_model: LearnerGoalsModel. The
learner goals model from the datastore.
Returns:
LearnerGoals. The le... | 9216cc711f24ffbb0554a9dad4af8571c51429a3 | 33,962 |
def prepare_metadata_for_build_wheel(
metadata_directory, config_settings, _allow_fallback):
"""Invoke optional prepare_metadata_for_build_wheel
Implements a fallback by building a wheel if the hook isn't defined,
unless _allow_fallback is False in which case HookMissing is raised.
"""
... | 24826b1f18a83c97ec516dec2e67110d920725a9 | 33,963 |
from datetime import datetime
def get_modtime(ftp, filename):
"""
Get the modtime of a file.
:rtype : datetime
"""
resp = ftp.sendcmd('MDTM ' + filename)
if resp[:3] == '213':
s = resp[3:].strip()
mod_time = datetime.strptime(s,'%Y%m%d%H%M%S')
return mod_time
retur... | 2a69d0448c093319392afafcfff96dc04ec225d0 | 33,964 |
def rotor_between_objects_root(X1, X2):
"""
Lasenby and Hadfield AGACSE2018
For any two conformal objects X1 and X2 this returns a rotor that takes X1 to X2
Uses the square root of rotors for efficiency and numerical stability
"""
X21 = (X2 * X1)
X12 = (X1 * X2)
gamma = (X1 * X1).value[0... | 9b4818aa149b5b8ea1cda3791f88c0650fb7a0bf | 33,965 |
def propose_time_step(
dt: float, scaled_error: float, error_order: int, limits: LimitsType
):
"""
Propose an updated dt based on the scheme suggested in Numerical Recipes, 3rd ed.
"""
SAFETY_FACTOR = 0.95
err_exponent = -1.0 / (1 + error_order)
return jnp.clip(
dt * SAFETY_FACTOR * ... | fa587b612433605ad002cb89a9ba5a46caa90679 | 33,966 |
def cross_column(columns, hash_backet_size=1e4):
"""
generate cross column feature from `columns` with hash bucket.
:param columns: columns to use to generate cross column, Type must be ndarray
:param hash_backet_size: hash bucket size to bucketize cross columns to fixed hash bucket
:return: cross ... | c4dfbf9083686c083e753ec90f9dbb00b06d515c | 33,967 |
def conform_json_response(api, json_response):
"""Get the right data from the json response. Expects a list, either like [[],...], or like [{},..]"""
if api=='cryptowatch':
return list(json_response['result'].values())[0]
elif api=='coincap':
return json_response['data']
elif api in {'po... | a9a2ec51edc13843d0b8b7ce5458bb44f4efd242 | 33,968 |
import sys
def failOnException(wrapped_function):
"""sys.exit(1) on any exception"""
@wraps(wrapped_function)
def failOnException_wrapper(*args, **kwargs):
"""wrapper function"""
try:
return wrapped_function(*args, **kwargs)
except Exception: # pylint: disable=W0703
... | b09ac283e1c5833ef08b6ee36a39f7758e8b23b0 | 33,969 |
import os
import fnmatch
def find_matching(root_path,
relative_paths_to_search,
file_pattern):
"""
Given an absolute `root_path`, a list of relative paths to that
absolute root path (`relative_paths_to_search`), and a `file_pattern`
like '*.sql', returns information... | 696e8b29a3d367f98498efef5d016e73a3359ff4 | 33,970 |
import re
def parse_content(content):
"""
解析网页
:param content:
:return:
"""
movie = {}
html = etree.HTML(content)
try:
info = html.xpath("//div[@id='info']")[0]
movie['director'] = info.xpath("./span[1]/span[2]/a/text()")[0]
movie['screenwriter'] = info.xpath(".... | 3e1bab821268abe99e088f331e317ddf74bb36e8 | 33,971 |
def model_save(self, commit=True):
"""
Creates and returns model instance according to self.clean_data.
This method is created for any form_for_model Form.
"""
if self.errors:
raise ValueError("The %s could not be created because the data didn't validate." % self._model._meta.object_name)
... | 47192e57a91961fcd08ea7091ab8a3a7448e2c97 | 33,972 |
def count_items(item_list: list) -> (list, list):
"""
Essa função lista as categorias de itens e as suas respetivas quantidades.
:param item_list: lista de itens
:return: uma tupla contendo lista de tipos e lista com a contagem de elementos dos tipos
"""
item_types = set(item_list)
count_ite... | 07144327c72fb1c54a1adbd5cadbf8b78324a0df | 33,973 |
def find_adjacent_citations(adfix, uuid_ctd_mid_map, backwards=False):
""" Given text after or before a citation, find all directly adjacent
citations.
"""
if backwards:
perimeter = adfix[-50:]
else:
perimeter = adfix[:50]
match = CITE_PATT.search(perimeter)
if not match... | 3630c524a55c09c3b44e6aec3f5706e6a6253c07 | 33,974 |
def defineTrendingObjects(subsystem):
""" Defines trending histograms and the histograms from which they should be extracted.
Args:
subsystem (subsystemContainer): Current subsystem container
subsystem (str): The current subsystem by three letter, all capital name (ex. ``EMC``).
"""
fun... | f0bd25476c7b9e2db245e4fd07fa03cc521d6c3c | 33,975 |
def staff_beers():
"""
This method is used to return 3 beer
"""
return Beer.query.limit(3) | f4f0d8dbb1b2a0550889ee7d00674e7c939f9eef | 33,976 |
def gen_curves(gen_data, file_path="", plot=True):
"""
Generates all parameters/values needed to produce an IV surface. No actual computations done
except to compute relevant values for the drift.
"""
num_gen_days = len(gen_data)
tau = DEFAULT_TAU
pis, mus, sigs, As, lams = construct_p... | 07f509588bb1c6e21de14189b34c979306e2cc1b | 33,977 |
import math
def mm2phi(mm):
"""Convert a mm float to phi-scale.
Attributes:
mm <float64>: A float value for conversion"""
return(-math.log2(mm)) | b40a9125be92dcdcc2be5b888c971f36f17c1c38 | 33,978 |
def IV_action(arr, iv=None, action="extract"):
"""Extract or store IV at the end of the arr."""
if action == "store" and iv != None:
arr.append(iv)
elif action == "extract" and iv == None:
iv = arr.pop()
return iv
else:
return "Error: No action assigned." | 0844cbb8eb3fb07ff49fb63d035fc7d4b7201700 | 33,979 |
def get_tty_width():
"""
:return: Terminal width as a string
"""
return str(get_terminal_size()[0]) | 2c09599d13417e0243af142b7c79da2cf9802825 | 33,980 |
def set_train_val_test_sequence(df, dt_dset, rcpower_dset, test_cut_off,val_cut_off, f = None ):
"""
:param df: DataFrame object
:param dt_dset: - date/time header name, i.e. "Date Time"
:param rcpower_dset: - actual characteristic header name, i.e. "Imbalance"
:param test_cut_off: - value to pass... | 88145303e494578116e74d713f0e2333a1bd7798 | 33,981 |
def orders(request):
"""显示用户的所有订单"""
username = request.user.get_username()
# 获取所有的uesername=用户名的记录,然后将记录按照time逆序排列
all_orders = Order.objects.filter(username=username)
times = all_orders.values('time')
# 获取不同的时间,因为对于不同的用户按照时间分类即可,相同的时间下的肯定是同一单
distinct_times = set()
for distinct_time in... | 4aa980465fb63e6e28d1020567cb0f6b4b607143 | 33,982 |
def convert_filename(filename):
"""Fix a filename"""
# Try and replace illegal characters
filename = replace_characters(filename)
# Remove remaining illegal characters
filename = remove_characters(filename)
return filename | 6a55ed29842ef08f19ec64db24ebcbe62f3849d9 | 33,983 |
from typing import Optional
from pathlib import Path
def create(
path_or_url: str,
output_dir: Optional[Path] = None,
) -> Path:
"""
Generate a new project from a composition file, local template or remote template.
Args:
path_or_url: The path or url to the composition file or template
... | 37dcc2ebb5c918afaf851f02a5202399947e2c63 | 33,984 |
def get_camera_index(glTF, name):
"""
Return the camera index in the glTF array.
"""
if glTF.get('cameras') is None:
return -1
index = 0
for camera in glTF['cameras']:
if camera['name'] == name:
return index
index += 1
return -1 | 0ffee8f036f5223f419fc3e5f95184c15f1b75d4 | 33,985 |
def local_se(df, kernel, deg, width):
""" This function is used to calculate the local standard errors, based on
estimation results of a local polynomial regression.
"""
if deg != 1:
print(
"WARNING: function local_se is currently hard-coded for ",
"polynomials of degree... | 7b8fbc2d8edb2f572d0a5b06766c0e57d26b2a6a | 33,986 |
import pickle
def data(get_api_data):
"""Get Weather data.
For testing I used pickle to
"""
GET_API_DATA = get_api_data
if GET_API_DATA:
weather_data = WeatherData()
with open('today_weather_data.tmp', 'wb+')as f:
pickle.dump(weather_data, f)
else:
with ope... | 0cf4e45a3129df323ed2089a6c27b8bb0a0e2831 | 33,987 |
def json_format(subtitle, data):
"""
Format json to string
:param subtitle: description to text
:type subtitle: string
:param data: content to format
:type data: dictionary
"""
msg = subtitle+':\n'
for name in data: msg += name+': '+data[name]+'\n'
return msg.strip() | bb3392d7ad57a482b4175838858d316ecc5f56e1 | 33,988 |
def _nSentencesInWordMap(wtm):
"""Return the number of valid word sequence in wtm"""
result = [0] * len(wtm) + [1]
for i_ in xrange(len(wtm)):
i = len(wtm) - i_ - 1
for j in wtm[i].iterkeys():
result[i] += result[j]
return result[0] | 9a771693ec572ad99ee7007efbf9d18e393b2c6c | 33,989 |
import regex
def datum_entspricht_din5008(eingegebenes_datum=abDatum):
"""
Prüft, ob das übergebene Datum der DIN 5008 entspricht.
Zeitpunkte vor 2000-01-01 werden ignoriert!
Siehe auch https://de.wikipedia.org/wiki/Datumsformat#DIN_5008.
:param eingegebenes_datum: String
:return: Boolian
... | 4e476d1b2d17de1214d5eef5e59b1455e5bcae14 | 33,990 |
def hflip(img):
# type: (Tensor) -> Tensor
"""Horizontally flip the given the Image Tensor.
Args:
img (Tensor): Image Tensor to be flipped in the form [C, H, W].
Returns:
Tensor: Horizontally flipped image Tensor.
"""
if not _is_tensor_a_torch_image(img):
raise TypeError... | e551cfe143bc823ff046bd57b524a262b3ecdb8b | 33,991 |
import numpy
def gfalternate_gotnogaps(data,label,mode="verbose"):
"""
Returns true if the data series has no gaps, false if there are gaps
"""
return_code = True
if numpy.ma.count_masked(data)==0:
if mode=="verbose":
msg = " No gaps in "+label
logger.info(msg)
... | bf31bf4da5896ebe37e76d26054d7b7cac8e4a4b | 33,992 |
def expm_tS_v2(t, S):
"""
Compute expm(t*S) using AlgoPy eigendecomposition and an identity.
t: truncated univariate Taylor polynomial
S: symmetric numpy matrix
"""
# Compute the eigendecomposition using a Taylor-aware eigh.
L, Q = eigh(t * S)
return dot(Q * exp(L), Q.T) | 3d5512e3b9fc00b765538c6f1bdb3ea0d460a896 | 33,993 |
def command():
"""
Return the tested command.
"""
return module.Command() | bd79175d169372283fca9e4555ce762f80f60f18 | 33,994 |
def computeSWC(D, cl_cores, ncl, shortpath):
"""
:param D: 2D dataset of n*d, i.e. n the number of cores (initial clusters) with d dimension
:param cl_cores: cluster label of each cores
:param ncl: the number of clusters
:param shortpath: the shortest path length matrix of core-based graph
:retu... | fca3dd6166867cd5d1f41c4dc0e85750f0339086 | 33,995 |
import warnings
def stable_cumsum(arr, axis=None, rtol=1e-05, atol=1e-08):
"""Use high precision for cumsum and check that final value matches sum
Parameters
----------
arr : array-like
To be cumulatively summed as flat
axis : int, optional
Axis along which the cumulative sum is c... | 0a6956461b1870c92a4a1b3556fb0889320fcac5 | 33,996 |
def read_data_min(server, port, user, pwd, instrument):
"""从mongo中读取分钟数据(含实时)"""
#取数据
client = py_at.MongoDBClient.DBConn(server, port)
client.connect(user, pwd)
db = client.get_database("future_min")
coll = client.get_collection("future_min", instrument)
docs = coll.find()
coll_real = client.get_collection("... | 7dfd30a63268318a8339c3c91fc4a477891b908e | 33,997 |
from textwrap import dedent
def _demo(seed=None, out_fc=False, SR=None, corner=[0, 0], angle=0):
"""Generate the grid using the specified or default parameters
"""
corner = corner # [300000.0, 5000000.0]
dx, dy = [1, 1]
cols, rows = [3, 3]
if seed is None:
# seed = rectangle(dx=1, dy=1... | 194582b64bc279ab51c54107811e052019bc862e | 33,998 |
def measure_bb_tpdm(spatial_dim, variance_bound, program, quantum_resource,
transform=jordan_wigner, label_map=None):
"""
Measure the beta-beta block of the 2-RDM
:param spatial_dim: size of spatial basis function
:param variance_bound: variance bound for measurement. Right now thi... | 0b5ec56b6f0b6bb20d30e3d4bbe76b723a0dc631 | 33,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.