content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def evaluate_batch(session, qa_model, examples, vocab):
"""
Arguments:
session: tensorflow session
qa_model: model object
examples: list(tuple(question, context))
vocab: vocabulary object
Returns list of predictions in the same order as examples
"""
batch_feature... | c8281564750f43ea9ba6f60398226082bd8adbc6 | 3,598,014 |
import mimetypes
import base64
def inlineimg(context, path):
""" Render an image inline using a data:// URI. Will return
a retina version if it is requested and exists.
"""
request = context['request']
highres = getattr(request, 'highres', False)
path = select_image(path, highres)
co... | 6cc0f6f30b62c89ad3654c9a2d18aa24357bac82 | 3,598,015 |
def query_by_port_dimension_event(
portia_config: dict,
edge_id: str,
port: int,
dimension_code: int,
event_code: int,
last: bool=False,
params: dict={
'from': None,
'to': None,
'order': None,
'limit': None,
'precision': 'ms',
'timezone': 'Etc/... | d266a1d818ba19a1d48be71ef629090e3a4d6112 | 3,598,016 |
def auth_view(request):
"""Start an oauth flow."""
FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY,
request.user)
# If we lose a refresh token at some point, this will allow a re-auth to give us one.
FLOW.params['approval_prompt'] =... | 28b357e46070eb0dcba50adb759796ab0daa4b39 | 3,598,018 |
from typing import Tuple
def interpolate_nodata_sgm(img: np.ndarray, valid: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""
Interpolation of the input image to resolve invalid (nodata) pixels.
Interpolate invalid pixels by finding the nearest correct pixels in 8 different directions
and use the medi... | 4691643cec73f434f82e6761143b55e81ea08ec2 | 3,598,019 |
import importlib
def unpack_table(ferc1_df, table_name, data_cols, data_rows):
"""
Normalize a row-and-column based FERC Form 1 table.
Pulls the named database table from the FERC Form 1 DB and uses the corresponding
ferc1_row_map to unpack the row_number coded data.
Args:
ferc1_df (pand... | fcb082a303ff0e314544c25141eb4fc776b7b0d8 | 3,598,020 |
def gram_translation_invariant(Z): # (N, C, H, W)
"""
Computes the empirical second moment of a multi-channel 2D data matrix Z.
Should be used in contexts where Z matrix is already FFTed in last two dimensions.
Args:
Z: a data matrix (N, C, H, W)
Returns:
The covariance matrix of Z... | a8513b4bdd7cea66813bb9b103508bfae2a47be8 | 3,598,021 |
def _time_to_range(hours):
"""
Converts a time from format '11:00AM - 1:00PM' to (660, 780)
"""
first_colon = hours.find(':')
if first_colon != 1 and first_colon != 2:
return
first_half = hours[first_colon + 3:first_colon + 5]
if first_half != 'AM' and first_half != 'PM':
re... | 035199ca17b474db003535dd1e3887d0797e607c | 3,598,022 |
import cgi
def post(param_map, url=URL):
"""Posts a `param_map` created with `config` to
the FlashAir config.cgi entrypoint"""
prepped_request = _prep_post(url=url, **param_map)
return cgi.send(prepped_request) | bc2b5bf89b4166d498001d5ced9fb2a67bf68d2b | 3,598,023 |
def action_import(request):
"""
This request imports one action given in a gz file
:param request: Http request
:return: HTTP response
"""
# Get workflow
workflow = get_workflow(request)
if not workflow:
return redirect('workflow:index')
form = ActionImportForm(request.POST... | 13b53b6939a80af18453573908f7cef13aad60fc | 3,598,024 |
def less_latest_tag(latest_tag):
"""当前应用是否小于GitHub最新版本比较"""
if latest_tag and is_valid_verion(latest_tag):
return semver.compare(latest_tag, PICBED_VERSION) == 1 | fb430344ee396414f0ac4676009e3f2a1f97b2e9 | 3,598,025 |
def is_installed(pkg_name):
"""
Check if .deb package is installed
"""
with settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True):
res = run("dpkg -s %(pkg_name)s" % locals())
for line in res.splitlines():
if line.startswith("Status: "):
st... | 7a2b5af2b8d623709c0290cb27d45f6640c3f7c1 | 3,598,026 |
from datetime import datetime
def _iardict_to_fil_header(iardict: dict) -> dict:
"""Build dict header from dict iar."""
source_name = iardict["Source Name"]
source_ra = iardict["Source RA (hhmmss.s)"]
source_dec = iardict["Source DEC (ddmmss.s)"]
# ref_dm = iardict["Reference DM"]
# pul_period... | 920ce832d0ab9b7fa219b14572cbfa04c4c0dfc2 | 3,598,027 |
def with_previous_theta_transform_memoized(func):
"""Memoize the latest result.
Decorator for a Trainer method of the form `func(self, theta)`, which memoizes
the result of the previous computation. This is designed specifically as an
performance optimization for methods called repeatedly during LBFGS,... | 4309996e3341e434a16af2182af9943f3466a70b | 3,598,028 |
def forwardPath(path):
"""Replace backslashes with slashes in a given path.
:Parameter path: the path being transformed
"""
while path.count(chr(92)):
path = path.replace(chr(92), '/')
return path | 4f2d2dfae06ba79f59e7fd2d938332fe5bbae9ac | 3,598,029 |
def box_voting(top_dets, all_dets, thresh, scoring_method='ID', beta=1.0):
"""Apply bounding-box voting to refine `top_dets` by voting with `all_dets`.
See: https://arxiv.org/abs/1505.01749. Optional score averaging (not in the
referenced paper) can be applied by setting `scoring_method` appropriately.
... | 96f10fc141e570ad9c33425194792397e8756f4f | 3,598,030 |
def update_item(user):
"""input put user to DynamoDB"""
# 元がちょっと変??(createdAtとupdatedAtが逆?)
input = defaultdict(
dict,
Key={"PK": user.PK, "SK": user.PK},
UpdateExpression="SET createdAt=:date",
ExpressionAttributeValues={":date": timestamp_jst()},
)
if user.name is... | 26ad14e29a3805d8e701d0e74d1f5da0892c677b | 3,598,031 |
def which_node(ant_num, session=None):
"""
Find node for antenna.
Parameters
----------
ant_num : int or list of int or csv-list or hyphen-range str
Antenna numbers, as int
Returns
-------
dict
Contains antenna and node
"""
na_from_file = node_antennas('file', s... | c0341503911bd781afec2cf6770571f796fad5ca | 3,598,032 |
import spacy.displacy
def render_parse_tree(
token_features: pd.DataFrame,
text_col: str = "token_span",
tag_col: str = "tag",
label_col: str = "dep",
):
"""
Display a DataFrame in the format returned by `make_tokens_and_features()`
using displaCy's dependency tree renderer.
:param tok... | 166650fbafd0a31e23198417ecc556ae8500f561 | 3,598,033 |
def nthnumeric(N, Sigma={'a','b'}):
"""Assume Sigma is a 2-sized list/set of chars (default {'a','b'}).
Produce the Nth string in numeric order, where N >= 0.
Idea : Given N, get b = floor(log_2(N+1)) - need that
many places; what to fill in the places is the binary
code for N - (2^b ... | 9f31cd78f11af4bdfb2f6342ab17298cd83c707c | 3,598,035 |
from typing import Dict
from typing import Any
def search_malicious_urls(client: Client, args: Dict[str, Any]) -> CommandResults:
"""Gets the Malicious url using the '/threat-stream/malicious-urls' API endpoint
:type format: ``str``
:param - format: It determines the data type of the response tha... | 2ab6bb618faeaf62ad235ae67d82779b1edd8f66 | 3,598,036 |
def _trim_site(read_and_slice, read_type):
"""Remove DpnII or MboI site from the left read,
remove NalIII site from the right read"""
read, slice = read_and_slice
start = slice.start
stop = slice.stop
sequence = read.sequence
if read_type == 'R1':
if sequence[-3:] == 'ATC':
... | d5abb679a88a94176a0dac6aaf2f5996d34fcb94 | 3,598,037 |
import cmd
def django_cmd(sys, settings, *args):
"""
Construct a Django management command.
`sys` is either 'lms' or 'studio'.
`settings` is the Django settings module (such as "dev" or "test")
`args` are concatenated to form the rest of the command.
"""
# Maintain backwards compatibility... | c023dcb8e2367724375ec0d4f5a63a3b6596361d | 3,598,038 |
def corrCoef_Threshold(data, threshold):
"""
Function aimed to calculate the corrCoef between each pair of variables
input: data->dataframe
threshold -> True: we want to keep the variables with a corrCoef higher than the income
False: we want to keep all values, no f... | 966f7467aae577547066fed61f07ef412d246c20 | 3,598,040 |
from typing import OrderedDict
def make_per_dataset_plot(delta_cchalf_i):
"""Make a line plot of delta cc half per group."""
d = OrderedDict()
d.update(
{
"per_dataset_plot": {
"data": [
{
"y": [i * 100 for i in list(delta_cc... | 219b7a981f896c7723e8f6ccde16819703503e54 | 3,598,042 |
def merge_sort(array):
"""
An implementation of the merge sort algorithm. Recursively sorts arrays
by calling merge sort on halves of the array, then merging by comparing
the first element of each array, then adding the smaller of the two to a
the sorted array.
"""
# Base Cases
if len(a... | 659260d8a9b9160d0576c62d17dadd91925fb05c | 3,598,043 |
def get_simple_contrapunctus(notes, duration):
"""
Given a list of notes as integers and the duration to use, will return the
lilypond notes for the contrapunctus.
Durations: 1-semibreve, 2-minim, 4-crotchet
"""
result = ""
# Ensure the notes are in range
normalised = [note for note in ... | 55738f24cbecc53fc5f2d29fa27d173e4229c080 | 3,598,044 |
def introduction(params, rc, solver):
"""
First lines of the SMT file
"""
result = ""
if solver == "cvc4":
result += "(set-logic LIA)\n"
result += "(set-option :produce-models true)\n"
result += parameters(params) + "\n"
result += assertion(list_conjunction(rc)) + "\n"
re... | c6b785f475c057bfbb79b8020a9013c537a48050 | 3,598,045 |
def naive_S2_conv(f1, f2, alpha, beta, gamma, g_parameterization='EA323'):
"""
Compute int_S^2 f1(x) f2(g^{-1} x)* dx,
where x = (theta, phi) is a point on the sphere S^2,
and g = (alpha, beta, gamma) is a point in SO(3) in Euler angle parameterization
:param f1, f2: functions to be convolved
:... | c43f50eead9f658495dcaf156a5848a9de3a9f0b | 3,598,046 |
def retract(Z, M):
"""Retract onto Stiefel manifold.
See section A.3 of Cunningham and Ghahramani, 2015
"""
# Note that this requires computing the inverse of the square root of a
# matrix (X^(-1/2)), which is defined as the solution to XX = B.
S = np.eye(M.shape[1]) + Z.T @ Z
d, Q = np.li... | 4ba70d4153c2a295b775fd5c079f6939109b3ac6 | 3,598,047 |
def dict_to_rec(x, dtype=None):
"""Convert dictionary {field_name: array} to record array
Optionally, provide dtype
"""
if isinstance(x, np.ndarray):
return x
if dtype is None:
if not len(x):
raise ValueError("Cannot infer dtype from empty dict")
dtype = to_numpy... | 006d49afde2b89aad6129391aefdaaf018332ca4 | 3,598,048 |
import array
import math
def sine12_array(sample_count: int) -> array[int]:
"""Return a monophonic signed 16-bit wavetable with a single cycle of a 1+2 sine.
A 1+2 sine is a sine wave modulated by its first harmonic.
"""
numbers = []
for i in range(sample_count):
current = round(
... | 420d9f5067830b3c8f92b963e2c5f8d04573068f | 3,598,049 |
def remove_duplicates(nums) -> int:
"""
remove_duplicates
:param nums:
:return:
"""
# print(list(set(nums)))
return len(set(nums)) | 1605c594d18ae39749fa9da17700504747b98024 | 3,598,050 |
from typing import Union
from typing import Tuple
from typing import BinaryIO
import re
import numpy
def tile(
z: int,
x: int,
y: int,
scale: int = 1,
ext: str = None,
url: str = None,
indexes: Union[str, Tuple[int]] = None,
expr: str = None,
nodata: Union[str, int, float] = None,
... | c10158095103c0e8c2294ffcadf84f098fb2ae3d | 3,598,051 |
def nor_data(img):
"""
Normalize the image
Parameters
----------
img: array
The images need to be normalized
Returns
-------
img
Description.
"""
mean_tmp = np.mean(img)
std_tmp = np.std(img)
img = (img - mean_tmp) / std_tmp
img = (img - img.min()) /... | f5fdda1e1edf73fb3ba5d3b5d427a3cc06a08336 | 3,598,052 |
def vectorize_cst(value, cst_precision):
""" if cst_precision is a vector format return a list uniformly initialized
with value whose size macthes the vector size of cst_precision, else
return the scalar value """
if cst_precision.is_vector_format():
return [value] * cst_precision.get_ve... | 9a5ba282309f8134007084e32a4a58876ec05d73 | 3,598,053 |
def board_methods():
"""
Route incoming request with prefix /board.
Route incoming request to the responible controller
depending on request method
Returns:
flask.Response
Raises:
MethodNotAllowed: if request method not in [GET, PUT, POST, DELETE]
"""
data = get_reques... | 313d71ccd2d059604daba0a0da422391f57f905a | 3,598,054 |
def subtract_bias(image, master_bias, inplace=False,
logger=logger):
"""Subtract a master_bias frame from a CCDData."""
master_bias = check_framedata(master_bias)
nim = imarith(image, master_bias, '-', inplace=False, logger=logger)
nim.header['hierarch astropop bias_corrected'] = True... | 20f3f63326725a43a7a49a4866fad6ef8505bbe7 | 3,598,055 |
def hood(request):
"""
Renders the index page
"""
if Join.objects.filter(user_id = request.user).exists():
neighbourhood = NeighbourHood.objects.get(pk = request.user.join.hood_id)
# occupants = Profile.get_user_by_hood(id= request.user.join.hood_id).all()
posts = Post.objects.fi... | 64365faea17a75921b8e3c4a7c65a9ee6ec8bf97 | 3,598,057 |
def del_segm(*args):
"""
del_segm(ea, flags) -> bool
Delete a segment.
@param ea: any address belonging to the segment (C++: ea_t)
@param flags: Segment modification flags (C++: int)
"""
return _ida_segment.del_segm(*args) | b2b70b840e57576227e5b3f26aa70088c56aa361 | 3,598,058 |
def fitsin(x,y,tau=1,delta=0,A=1,C=1,sig=1):
"""Fit data in x and y to a sin function"""
data=zeros((len(x),3),typecode='d')
data[:,2]=sig
data[:,0]=x
data[:,1]=y
return LS(sinus,(tau,delta,A,C),data) | 8437a9f8150b00b54f2d83a01c04f38f35496215 | 3,598,059 |
def writeEndfINTG( row, col, vals, ndigit ):
"""Special INTG format, only used for sparse correlation matrices."""
def toStr( val ) :
if( val == 0 ): return ' ' * ( ndigit + 1 )
if( abs( val ) > 10**ndigit ) :
raise ValueError( "%d too large for INTG format with ndigit=%d!" % ( val,... | 89c3fae44fead6b8e670bbc69ed4b4083bdd406e | 3,598,060 |
def delete_experiment(uuid, project_id):
"""Delete an experiment in our database and in the object storage.
Args:
uuid (str): the experiment uuid to look for in our database.
project_id (str): the project uuid.
Returns:
The deletion result.
"""
raise_if_project_does_not_exi... | 06c9c75bd05d5a9fe02f2b51afbd029840bca814 | 3,598,061 |
def ring_int_label_to_str(ring_int_label):
"""
Binary encoding only works when you can only have at most one of each type
e.g. one inner 2^2 = 4 = 2^1 + 2^1 = two nuclear
There are many examples of e.g. '36' which could be four outer rings, three outer and two inner, etc.
This seems a silly way to e... | 2f8ce0476bf300a803f13cf5603e909f0b31045f | 3,598,062 |
def move_elements_to_end(array: [], element) -> []:
"""Reorganizing the given array and returning the same array
with the elements that match the given element value at the end of the array
:param array: array of elements
:param element: element of a given value"""
# Time Complexity: O(n), Space C... | 5b8dc987af6bf4f13119926f2088c8969b8f5ee5 | 3,598,063 |
import json
def prettify_dict(rule):
""" Prettifies printout of dictionary as string.
rule: rule
Return value: rule string
"""
return json.dumps(rule, sort_keys=False, indent=4, separators=(',', ': ')) | a4ff4e4b088246d8f36851b5fc7d69828dd99a83 | 3,598,064 |
def SMD(x, n: int):
""" Simple Moving Deviation
:param x: a numeric sequence
:param n: period for the moving average
:return: np.ndarray
"""
if not isinstance(x, pd.Series):
x = pd.Series(x)
try:
rolling_sdev_values = x.rolling(n).std().dropna()
rolling_sdev_values... | 89d643d71b72d2e716c82209bec803d5016e6524 | 3,598,066 |
import asyncio
def event_loop():
"""A module-scoped event loop."""
return asyncio.new_event_loop() | 59f006ee32a6319cfeecb74d87c781d8a2887b20 | 3,598,067 |
def get_old_help_pages_redirecting_to_new_one(language):
"""
:param language: string
:return: list of strings: the pages which redirect to the renamed page
"""
old_help_pages = []
for page in get_help_pages_in(language=language):
if is_old_help_page_redirecting_to_new_one(language=langua... | 27abaa64d9d13ee36bb95accb29cb07283d3bdf7 | 3,598,068 |
import copy
def run(trans_desc):
"""
Script for pulse generation. Adjusts some input parameters to be in the
correct units.
time_steps - int, the number of data points in the output waveform
duration - float, total time of pulse, in msec
resolution - the calculation res... | 00f62ca0a453b20ef98bf5db72a370d332ffe75e | 3,598,069 |
def reduce_puzzle(values):
"""
Iterate eliminate() and only_choice(). If at some point, there is a box with no available values, return False.
If the sudoku is solved, return the sudoku.
If after an iteration of both functions, the sudoku remains the same, return the sudoku.
Input: A sudoku in dicti... | f39f54c3e97ed61e2d0b6011727662de08065d55 | 3,598,070 |
def delete(oid):
"""
This function deletes a bgpRoutingMode from the bgpRoutingModes list
:param key: key of the bgpRoutingMode to delete
:return: 200 on successful delete, 404 if not found
"""
# Does the bgpRoutingMode to delete exist?
existing_bgpRoutingMode = BGPRoutingMode.query.filt... | 2880a743601b34f9ba1aecc8a32d28fcb4849cb9 | 3,598,071 |
def copy_dictionary(original):
"""Copies a dictionary where each entry is a :obj:`Numpy Array`
"""
copy = {}
for spx_idx in iter(original):
copy[spx_idx] = np.copy(original[spx_idx])
return copy | c709917aba26d46962afa89a372bd0ffb01d27a5 | 3,598,072 |
def split_me(strings):
"""
Function to split strings into an array to loop later
from the template.
"""
splited_values = strings.split(",")
return splited_values | 2b62cccac7602054b0e5cde34d0dbfc9964c0970 | 3,598,073 |
def get_engine(db_name="eq_stress_test.db", username=None, pswd=None, port=None,
db_type="sqlite", hostname="localhost"):
"""
:param db_name: Database name to be used default: eq_stress_test.db for a sqlite3 db
:param username: Username (str)
:param pswd: Password (str)
:param p... | e127bf8281837e59e421801fa966cd34ece7eb8e | 3,598,074 |
def _open_circ_options_process(options):
"""For use in both ``_ctrlo_circ`` and ``_target_x``."""
if options is None:
options = {}
new_options = options.copy()
if "color" in new_options:
new_options["facecolor"] = plt.rcParams["axes.facecolor"]
new_options["edgecolor"] = options... | dbfd251e2bef915fe1490c1baa12f8166fd77908 | 3,598,075 |
def stroke_distance(stroke_1, stroke_2):
"""Returns the minimum distance between two strokes"""
s_1 = stroke_1.starting_point
e_1 = stroke_1.ending_point
s_2 = stroke_2.starting_point
e_2 = stroke_2.ending_point
set_1 = [s_1, e_1]
set_2 = [s_2, e_2]
frontier = None
minimum_distance =... | 8e511a304fd0aae66e37491d28c009db40f7776e | 3,598,076 |
from ..util import get_dtype_min_max, get_array_module, is_on_gpu
def __calc_transform(h_dst, dt, n_mask, idx):
"""Create the transform that is the size of the image but with sorted histogram values."""
xp = get_array_module(idx)
mn, mx = get_dtype_min_max(dt)
values = xp.linspace(mn, mx, len(h_dst),... | 81bdfc40523ae955f6e0cd701d17d127c0338bae | 3,598,077 |
def hamming_distance(Subspace1, Subspace2):
"""
Returns the Hamming distance between to subspaces.
Variables that are free in either subspace are ignored.
**arguments**:
* *Subspace1, Subspace2* (dict): subspaces in dictionary representation
**returns**:
* *Distance* (int): the dis... | f42d13bd1d980b092235aa472a24a1cebe078f44 | 3,598,079 |
def dictBuilder(l, root=PARENT):
"""
Takes in a list of child-parent pairs L and a root value ROOT and returns a hierarchical dictionary, maintaining sorting.
"""
seen = 0
d = {root: []}
for pair in l:
if pair[3] != root and seen:
break
if pair[3] == root:
... | 5e471b0ded2963a83fef3bf1aeecfe51ac5213a6 | 3,598,080 |
def addnotes():
"""Make notes on stocks"""
if request.method == "POST":
# Current user that is logged-in saved in variable
memberId = session['user_id']
symbol = request.form.get("symbol")
if not symbol:
return apology("for better organized notes, please enter stock... | b58ffce72be61b8863d7b473f941e8de1ddecf02 | 3,598,081 |
def dtype():
"""A fixture providing the ExtensionDtype to validate."""
return skfda.representation.grid.FDataGridDType(
grid_points=[
np.arange(10),
np.arange(10) / 10],
dim_codomain=3
) | fa3d2b13a2a91f487ae429586d4bfa9d1764ab8e | 3,598,082 |
def decide_merge(base, local, remote, strategies=None):
"""Do a three-way merge of same-type collections b, l, r.
Terminology:
collection = list | dict | string
value = int | float | string
(string is a collection of chars or an atomic value depending on parameters)
(an alter... | daf2dc1305dd2a9548ab009aabdc968bf3587d5d | 3,598,085 |
def get_last_root_page(pages):
"""
This tag returns the last page on the root level.
:param pages: The requested page tree
:type pages: list [ ~cms.models.pages.page.Page ]
:return: The last root page of the given page list
:rtype: ~cms.models.pages.page.Page
"""
root_pages = list(filt... | 0fc938ac35dadc7da6c2215c17a68fbb184ee40f | 3,598,086 |
def fixture_train_form_recognizer() -> TrainFormRecognizer:
"""Returns `TrainFormRecognizer` instance
Returns
-------
TrainFormRecognizer
`TrainFormRecognizer` instance
"""
return TrainFormRecognizer("", "") | 1f7da1ad37b91b113f7bde80c7d1640b81b90245 | 3,598,088 |
import re
def get_clean_doi(doi: str) -> str:
"""Check if the DOI is actually a URL and in that case just get
the exact DOI.
:param doi: String containing a DOI.
:returns: The extracted DOI.
"""
doi = re.sub(r'%2F', '/', doi)
# For pdfs
doi = re.sub(r'\)>', ' ', doi)
doi = re.sub(... | 5dd823b0ff69f3a51557f4fe992bb5108f86bf75 | 3,598,089 |
def sorted_values_into_combinations(values_sorted, no_of_ps, no_of_values):
"""
Transfrom sorted values into unique combinations of values.
Parameters
----------
values_sorted : 2D numpy array. Sorted values for each policy score
no_of_ps : Int. Number of policy scores.
no_of_values : Int. ... | 8ade45ad69188f0e8957cfc9533a4fcf3e27424f | 3,598,091 |
def inference_fconv_small(alpha=1.,input_shape=[None, 22,22,10,1],
input_shape_m=[None, 22,22,10,3],
n_filters=[1, 32, 32, 32],
filter_sizes=[3, 2, 3, 2],
corruption=False):
"""Build the fMRI model.
Args:
images: Images.
"""
# inpu... | 0ef903afa7dce123c1a8c0d711bb586b239cf82d | 3,598,092 |
def generate_canonical_request(method, parsed_url, headers, signed_headers,
content_sha256):
"""
Generate canonical request.
:param method: HTTP method.
:param parsed_url: Parsed url is input from :func:`urlsplit`
:param headers: HTTP header dictionary.
:param con... | 2074a58f850893fe91fccb592ee9db238d5da7c6 | 3,598,093 |
def potential_visit_poi (directions, tracking_interval, filename='', add_no_stop=False):
"""calculate probability to visit POIs and overall entropy"""
tracking_interval = tracking_interval/60
for i in range(len(directions)):
all_probab = []
duration = directions[i]['duration']/60
f... | fc876afc6be1bcc3957258c7777a900403857a2c | 3,598,094 |
from pathlib import Path
def find_path(paths):
"""Given a search path of files or directories with absolute paths, find
the first existing path.
Args:
paths (list): A list of strings with absolute paths.
Returns:
str: The first path in the list `paths` that exists, or `None` if
... | 53dda06e55c26d0fce43bca5eea0cdc3fca53b11 | 3,598,095 |
import time
def SKL_Train(clf, X, Y):
"""
Wrapper to train any machine learning model/classifier from the Scikit-Learn suite which uses fit() to train and
predict() to predict the outcome values.
:param clf:
:param X:
:param Y:
:return:
"""
st = time.time()
X_train, X_test, ... | 2aafad43e814c7e3b4146541f4868f77b06fef4c | 3,598,096 |
import functools
import psutil
def kill_process_psutil(proc, timeout=5, signal_=None, output=None):
"""
If alive, kills the process (an instance of ``psutil.Process``).
Try killing the child process at first and then killing itself.
First call ``terminate()`` or pass ``signal_`` if specified
to te... | 129e89334f3b4493e201d86930063215ceb5ac81 | 3,598,097 |
import warnings
def forward_stft(samps,
frame_len=1024,
frame_hop=256,
round_power_of_two=True,
center=False,
window="hann",
apply_abs=False,
apply_log=False,
apply_pow=False,
... | 313189009cf341ca3ddc29fa50a43a53fdb71231 | 3,598,098 |
def embeddings2ranks(embeddings):
""" Converts embeddings to ranks"""
microbes = embeddings.loc[embeddings.embed_type == 'microbe']
metabolites = embeddings.loc[embeddings.embed_type == 'metabolite']
U = microbes.pivot(index='feature_id', columns='axis', values='values')
V = metabolites.pivot(index... | 24bb2e9e06d20e025c7f9ee4054d9479987d7685 | 3,598,099 |
def s2b(s):
"""Converts an ASCII string into binary data
Args:
s: A string of ASCII characters
Returns:
A long of binary data
"""
#start a binary long
r=0
#for each character in the string
for c in s:
#left shift the data by 8 bits and add the integer representation of the character
... | edf3ca83dd7339b509edd6820da1026dc20c2918 | 3,598,101 |
def time_to_str(t):
""" Turns time objects to strings like '08:30' """
return t.strftime('%H:%M') | 6427b9267b63dc6d75dce2afae24bbbd58b0b0dd | 3,598,102 |
def aggregate_min(results, _):
"""aggregate_score is the minimum score."""
results = [result for result in results if result[-1].active]
return min(results, key=lambda result: result[0])[:-1] | 07b5caffcbbe0bad87c4f18bb6feda3780e54ec9 | 3,598,103 |
def difftags(ui, repo, oldfnodes, newfnodes):
"""list differences between tags expressed in two set of file-nodes
The list contains entries in the form: (tagname, oldvalue, new value).
None is used to expressed missing value:
('foo', None, 'abcd') is a new tag,
('bar', 'ef01', None) is a de... | 234f85f06a4202f24f1fca5f4a70fe70ccac00e0 | 3,598,104 |
from datetime import datetime
async def get_activity_span(session, query_defuzzed):
""" Fetches the activity span of a search as well as active months within that span """
# Fetch any private lists included in search results
fuzz_private_only = dict(query_defuzzed)
fuzz_private_only["filter"] = [{"te... | d5ae4c54f4f0b100deff1b75276f7f220de1edd0 | 3,598,105 |
from typing import Optional
def Sinh(input_vertex: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
"""
:param input_vertex: the vertex
"""
return Vertex(context.jvm_view().SinhVertex, label, cast_to_vertex(input_vertex)) | 980940724d7bd32d6bc019c6451f4c04894addf9 | 3,598,108 |
import tqdm
def create_adjacency_matrix(influence_relations, network_size):
"""takes a dictionary of users as keys and their influenced users (who retweeted them) as values, the constructs
an adjaceny matrix to build up a network graph of such relations"""
A = np.zeros((network_size, network_size))
... | ef2d18a15ac9cf672d2c1e3c72581efb4b710477 | 3,598,109 |
from typing import Dict
from typing import Any
from typing import cast
def encode(json: Dict[str, Any]) -> str:
"""
Encode a transaction.
Args:
json: the JSON representation of a transaction.
Returns:
A hex-string of the encoded transaction.
"""
return cast(str, _serialize_js... | f4bd0ae732518f0cb9452c068402e8fd04631f5e | 3,598,110 |
def resize_to_fit(image, width, height):
"""
A helper function to resize an image to fit within a given size
:param image: image to resize
:param width: desired width in pixels
:param height: desired height in pixels
:return: the resized image
"""
# grab the dimensions of the image, the... | 32865da9d65a2732851130aea39696d5f4efa4e4 | 3,598,112 |
def login_and_permission(permission_name):
""" First requires log in, but if you're already logged in but don't have permission,
displays more info. """
def decorator(func):
return wraps(func)( # preserves function attributes to the decorated function
login_required(login_url='/a... | 19dd851b29dbdfc0973f8bf51539a48852177223 | 3,598,113 |
def extract_off_diag(mtx):
"""
extract off diagonal entries in mtx.
The output vector is order in a column major manner.
:param mtx: input matrix to extract the off diagonal entries
:return:
"""
# we transpose the matrix because the function np.extract will first flatten the matrix
# wit... | f4848cba9f2b64532edb129818dc2f1a4cb00978 | 3,598,114 |
def decodeextra(text):
"""
>>> from .pycompat import bytechr as chr
>>> sorted(decodeextra(encodeextra({b'foo': b'bar', b'baz': chr(0) + b'2'})
... ).items())
[('baz', '\\x002'), ('branch', 'default'), ('foo', 'bar')]
>>> sorted(decodeextra(encodeextra({b'foo': b'bar',
...... | 5f65e5d507b23842e26dc17b5849d35d129b86ea | 3,598,115 |
from typing import List
from typing import Tuple
from typing import Optional
def _find_floor_ceiling(
items: List[str],
) -> Tuple[List[str], Optional[Number], Optional[Number]]:
"""Extracts the floor and ceiling from item list"""
floor: Optional[Number] = None
ceiling: Optional[Number] = None
fo... | 97ee6345d6481b79c6f6b319e63d74d1e3246301 | 3,598,116 |
def GitHub_release_text(version):
"""
Generate text to put in the GitHub release Markdown box
"""
shortversion = get_sympy_short_version(version)
htmltable = table(version)
out = """\
See https://github.com/sympy/sympy/wiki/release-notes-for-{shortversion} for the release notes.
{htmltable}
**... | e18d470c5024eb26ead2286b95b250c69b020fb3 | 3,598,117 |
from typing import Tuple
def save_scatter_replicates_results(
scatter_data: pd.DataFrame, intensity_label: str = "Intensity", show_suptitle: bool = True,
close_plots: str = "all", exp_has_techrep: bool = False, **kwargs
) -> Tuple[plt.Figure, plt.Axes]:
"""
saves plot with prefix: {{name}}
... | c30bc33d7aa4e43d1bb2be50aefce12b475308d3 | 3,598,118 |
def fisher(data, num_instances: list, top_k_features=2):
"""
Performs Fisher feature selection method according to the following formula:
D(f) = (m1(f) - m2(f) / (std1(f) - std2(f))
:param data:
:param num_instances:
:param top_k_features:
:return: the list of most significant features.
... | a3221313fd6c1264c5577a9c63cdef5f803fee40 | 3,598,120 |
def forward_step_transpose_endo_2d(D, x_i, y_i, x_pi, y_pi):
"""Endogenous update part of forward_step_transpose_2d"""
nZ, nX, nY = D.shape
Dnew = np.empty_like(D)
for iz in range(nZ):
for ix in range(nX):
for iy in range(nY):
ixp = x_i[iz, ix, iy]
iyp... | 17708b9eae0b9af8a16c9667cf3063ec4f41632c | 3,598,121 |
def read_fc_phonopy(FC_file,natom,masses):
"""
Reading force constant data from phonopy format.
In this module, force constant is scaled by mass.
Thus, the return is dynamical matrix
"""
with open(FC_file,'r') as fc:
lines=fc.readlines()
nlineblock=4
fc_all=np.zeros((na... | 2369a916a776fb027c5ba191ca3cf8af2a18c26e | 3,598,122 |
def calculate_monthly_cost(
record, month, day_type, tier_maximums, db, ev_specific
):
"""
Calculate the cost to charge an EV based on pre-specified baseline and
charging profiles in a given month and 'day type.' Day types can be
'weekday,' 'weekend,' and 'total.' We use the 'total,' i.e. lumpin... | 2a7e5e3c87e74e755f90290ba8b06ec0dbe560d1 | 3,598,123 |
def arrFind(arr, v, default=-1):
"""аналог str.find() для массивов"""
if isGenerator(arr): arr=list(arr)
try:
return arr.index(v)
except ValueError: return default | 8ba89470fa9a92fc0a0cb2826b4deadabc9f2766 | 3,598,124 |
def searchInterfaceIds(context, search_string=None, base=None):
"""Interfaces search
"""
return [iface_util[0] for iface_util in
searchInterfaceUtilities(context, search_string, base)] | f0084fd7eb67a97ff6e8cf1c62236a4cc3737e78 | 3,598,125 |
def import_file_to_ast(fpath, module_name):
"""Import content from fpath and return a Python AST."""
return hy_compile(import_file_to_hst(fpath), module_name) | eee529575c5d12bb104c847731ae9878225f7c79 | 3,598,126 |
def test(one, two, three, **kwargs) -> int:
"""Return the sum of the arguments."""
return one + two + three + kwargs["four"] + kwargs["five"] + kwargs["six"] | c48a6968b6d4f1c673f7749e810d8d360e8d8d20 | 3,598,127 |
def collect_pair(fname ,inds=False, delimiter=',',remove_last=False):
"""
:param fname: the name of the file
:param inds: the indexes of the elements in each row of the file that you want to store in output list
:return: a list with n elements where n is the number of lines in fname, and each element o... | e57c8afed6bb5e96833ecb66cc3156c3c9a0589f | 3,598,128 |
def decrypt_string(string, key, ttl=None):
""" Decrypts an encrypted string with the specified key. The key must be 32 raw bytes. """
f = Fernet(key)
try:
return f.decrypt(str(string), ttl=ttl)
except InvalidToken:
return None
except TypeError:
return None | 7988c8bc78b509521563bc3b2a4b4334be48b18f | 3,598,129 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.