content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import importlib
def api(package_name, client, name):
"""Return an API instance."""
module_name = snake_case(name)
package = importlib.import_module(f"{package_name}.api.{module_name}_api")
return {
"api": getattr(package, name + "Api")(client),
"calls": [],
} | e1d149ab987e9923a42866c5f0f3ae946887e7ab | 3,615,079 |
import json
def checa_registro_json(registro, caminho_json):
"""
Checa se um <registro> já está no arquivo <caminho_json>.
Parâmetros
----------
registro : dict
Dicionário contendo o registro a ser checado.
Espera-se o formato:
{
... | b888781ed0e4fbc87f888afeec643e51b305157c | 3,615,080 |
def from_baseclaim(baseclaim: Baseclaim) -> VictorSolution:
"""Converts a Baseclaim into a VictorSolution.
Args:
baseclaim (Baseclaim): a Baseclaim.
Returns:
solution (VictorSolution): a VictorSolution.
"""
square_above_second = Square(row=baseclaim.second.row - 1, col=baseclaim.se... | c44b5770cb53cdb914c89130260bf1d6973b5cb9 | 3,615,083 |
def amsthm_latex(elem: Element, doc: Doc) -> pf.RawBlock | None:
"""Transform amsthm defintion to LaTeX package specifications."""
# check if it is a Div, and the class is an amsthm environment
options: DocOptions = doc._amsthm
if isinstance(elem, pf.Div):
environments: set[str] = options.theore... | 3b524464b41532810212ac1a5c3ec214baa2cff5 | 3,615,084 |
def async_run_in_kivy(func=None, clock=None):
"""Decorator that runs the given function in a Kivy context in an
asynchronous manner, waiting (asynchronously) until it's done.
It is primarily useful when kivy and trio are running in different threads.
See :mod:`kivy_trio.context` and the note below for ... | 635deedba8e62e341f501df9c66938da36641b3d | 3,615,085 |
def he_normal():
""" Returns a weight initializer with a Gaussian distribution whose mean is
zero and standard deviation is :math:`\\sqrt{\\frac{2}{n_i}}`, where
:math:`n_i` is the number inputs to a layer.
See "Delving deep into rectifiers: Surpassing human-level performance on
ImageNet classifica... | 6238592022eba777b3ce4118154bfab961d275b5 | 3,615,086 |
import copy
import random
import time
def upper_bound(sequences, max_run_time_random_seconds = 1):
""" Finds an upper bound based on some fast approximation algorithms."""
def alphabet_leftmost(sequences):
""" Approximation algorithm by looping through a random permutation on the alphabet """
... | 13268c26b00e6edfc9a581078f5105755e98834a | 3,615,087 |
import re
def get_block_source(template_source, block_name):
"""
Given a template's source code, and the name of a defined block tag,
returns the source inside the block tag.
"""
# Find the open block for the given name
match = re.search(NAMED_BLOCK_RE % (block_name,), template_source)
if ... | 83a4245dca634c6fa39b584cc9bfcabff8aa5866 | 3,615,088 |
import json
def get_mysql_connection(replica_set_name,
writeable=False,
user_role=None,
replica_set_role=None):
""" Get MySQL connection information. This code also exists in
the wiki and is copied numberous places across the pinterest... | 79909884edc6ba7c559ee84380d7f1692ad46517 | 3,615,089 |
import json
def dj(_dict):
"""Converts dicts to JSON and safely handles non-serializable items"""
return json.dumps(
_dict,
default=lambda o: 'ERROR: Item not JSON serializable',
sort_keys=True,
indent=3) | 042fdc731a084e1d74175a1ac22bc5b4204050c6 | 3,615,090 |
async def google_signin(
request: Request,
provider: StarletteOAuth2App = Depends(GoogleProviderMarker)
) -> RedirectResponse:
""" Redirect to the login through Google OAuth. """
return await provider.authorize_redirect( # type: ignore[no-any-return]
request=request,
redirect_ur... | f0c5809fa67ec55b4bc3b260c780ec337eecfa2d | 3,615,092 |
def fillna_bfill(array):
"""Backward fills an array.
Args:
array: A 2d numpy array with dimensions (location, time)
Returns:
A numpy array.
"""
_assume_2d(array)
flipped = np.flip(array)
filled = fillna_ffill(flipped)
return np.flip(filled) | 6bdca95590a3ad1d0feb32480b193fbe5dede4dc | 3,615,093 |
def generate_cholesky_factor(n=100, k=20):
"""
Generate a toy banded Cholesky factor
"""
L_band = np.random.uniform(low=0.1, high=1.0, size=(k, n))
L_band[0, :] = np.abs(L_band[0, :])
L_dense = construct_banded_matrix_from_band(k - 1, 0, L_band)
return L_dense | 7924449aeda724e8b3f2742409500a5500a04c3c | 3,615,094 |
def get_task_status(request):
""" AJAX: Gets the status of a pending background task by hash """
task_hash = request.GET.get("task_hash", "")
if not task_hash:
return {'response': 'bad', 'message': 'Invalid request'}
# Check if completed
if CompletedTask.objects.filter(task_hash=task_hash).... | 729552dc7e646c6a046be053d9fa6cff2d11dd05 | 3,615,095 |
def convert_to_fortran_bool(boolean):
"""
Converts a Boolean as string to the format defined in the input
:param boolean: either a boolean or a string ('True', 'False', 'F', 'T')
:return: a string (either 't' or 'f')
"""
if isinstance(boolean, bool):
if boolean:
new_string... | 9c129fff7e09f5619489206ecd95c9c72fd17627 | 3,615,096 |
def iter_dumps(iterable, width=2):
"""Converts numbers from iterable in the range from -1 to 1 into signed integers 'width' wide. And dumps them into a string or a bytearray."""
if width == 1:
return bytearray(map(lambda x: int(x * 127) & 255, iterable))
elif width == 2:
return bytearray(_se... | e5662483e938aebca9a750d1de4af944d49282f0 | 3,615,097 |
def scatterplot(
a,
b=None,
along="x",
area=None,
aspect=None,
color=None,
filename=None,
height=None,
hyperlink=None,
label=None,
margin=50,
marker="o",
mlstyle=None,
mstyle=None,
opacity=1.0,
... | 0b06e7ad2aa3a2aef045b366e57a82dd420e6d36 | 3,615,098 |
def is_decorated(field_spec):
"""
is this spec a decorated one
:param field_spec: to check
:return: true or false
"""
if 'config' not in field_spec:
return False
config = field_spec.get('config')
return 'prefix' in config or 'suffix' in config or 'quote' in config | b44d13fbcadc67ac191d07b1c304f2ec5ce1f081 | 3,615,099 |
import typing
def with_any_role_check(
roles: collections_abc.Sequence[typing.Union[hikari.SnowflakeishOr[hikari.Role], int, str]] = [],
*,
error_message: typing.Optional[str] = "You do not have the required roles to use this command!",
halt_execution: bool = False,
) -> collections_abc.Callable[[Comm... | 69a448ed7849900d32d800dc71ad0ba79057228f | 3,615,100 |
def split_path(path):
"""
Normalise S3 path string into bucket and key.
Parameters
----------
path : string
Input path, like `s3://mybucket/path/to/file`
Examples
--------
>>> split_path("s3://mybucket/path/to/file")
['mybucket', 'path/to/file']
"""
if path.startswi... | 446f7643066864937e11b915d4ff842f21c65dd6 | 3,615,101 |
def unixtime2mjd(unixtime):
"""
Converts a UNIX time stamp in Modified Julian Day
Input: time in UNIX seconds
Output: time in MJD (fraction of a day)
"""
# unixtime gives seconds passed since "The Epoch": 1.1.1970 00:00
# MJD at that time was 40587.0
result = 40587.0 + unixtime / (2... | 670e915b7a5de8cd9ced28e6b4d32c51ac916d54 | 3,615,102 |
import pydoc
def splitdocfor(path):
"""split the docstring for a path
valid paths are::
./path/to/module.py
./path/to/module.py:SomeClass.method
returns (description, long_description) from the docstring for path
or (None, None) if there isn't a docstring.
... | cdbf516b648b57fff0e9ceec750759aa65d0626a | 3,615,103 |
def vecdist3(coord1, coord2):
"""Calculate vector between two 3d points."""
#return [i - j for i, j in zip(coord1, coord2)]
# Twice as fast for fixed 3d vectors
vec = [coord2[0] - coord1[0],
coord2[1] - coord1[1],
coord2[2] - coord1[2]]
return (vec[0]*vec[0] + vec[1]*vec[1] + ... | 0315ec921c051eb46da9f073e6bc76b2a0a448bb | 3,615,104 |
def svn_wc_get_status_editor(*args):
"""
svn_wc_get_status_editor(svn_wc_adm_access_t anchor, char target, apr_hash_t config,
svn_boolean_t recurse, svn_boolean_t get_all,
svn_boolean_t no_ignore, svn_wc_status_func_t status_func,
svn_cancel_func_t cancel_func,
svn_wc_traversal... | b0dc063e54b4ac337833edbf2220a26402a7c5d3 | 3,615,105 |
def getFORCodes(node, kw):
"""
Helper function for retrieving and organising FOR codes from the CSV file that contains them.
:param node: Node that the returnd values are for.
:param kw: Arguments that are passed to the shema's bind() method.
:return: OrderedDict of FOR codes nested appropriately.
... | 4d05fb78f47f3449d65cebd535e5f874148f6e01 | 3,615,106 |
def num_active_calls(log, ad):
"""Get the count of current active calls.
Args:
log: Log object.
ad: Android Device Object.
Returns:
Count of current active calls.
"""
calls = ad.droid.telecomCallGetCallIds()
return len(calls) if calls else 0 | a6674df1e8e539478db6ab1a640fbce1cf0b6b4c | 3,615,107 |
def module_create_from_connection_string(transportType, connectionString, caCertificate=None): # noqa: E501
"""Create a module client from a connection string
# noqa: E501
:param transportType: Transport to use
:type transportType: str
:param connectionString: connection string
:type connect... | 16df883f99e8ad3a7751fa70845fb60962bf1c02 | 3,615,109 |
def ldns_rdf_new_frm_fp_l(*args):
"""LDNS buffer."""
return _ldns.ldns_rdf_new_frm_fp_l(*args) | d4549e4ccde6b5ebb090ea9cca6ea3b05482df82 | 3,615,110 |
import math
def run_experiment(fr: int, to: int) -> (int, int):
"""Run the classical part of Shor's algorithm."""
n = get_odd_non_prime(fr, to)
a = get_coprime(n)
order = classic_order(a, n)
factor1 = math.gcd(a ** (order // 2) + 1, n)
factor2 = math.gcd(a ** (order // 2) - 1, n)
if factor1 == 1 or fa... | 04ea055743b519f4c32c853fa161877a7c5c21e2 | 3,615,111 |
def backward_prop(data, labels, params, forward_prop_func):
"""
Implement the backward propegation gradient computation step for a neural network
Args:
data: A numpy array containing the input
labels: A 2d numpy array containing the labels
params: A dictionary mapping parameter ... | f91560c56e694b08b845e26fe320f453c894d361 | 3,615,112 |
def homepage(js):
"""
Extract an URL for that researcher (if any)
"""
lst = jpath(
'person/researcher-urls/researcher-url', js, default=[])
for url in lst:
val = jpath('url/value', url)
name = jpath('url-name', url)
if name is not None and ('home' in name.lower() or '... | 64b50cf0bc1a8324b480cf4d8cd63606e5a7d95c | 3,615,113 |
def get_result(filename):
"""
This route returns the details of the analysis relative to the filename specified
along with the source code analyzed
"""
response = {
"success": True,
"data" : {
"by_context" : utils.getAnalysisResultByContext(app.config, filename),
... | 5aec0ef12070293ee4fa3d457145f650161a6afb | 3,615,116 |
def reader_mock() -> AsyncMock:
"""Cria um objeto reader mock para os testes."""
reader = AsyncMock()
return reader | f262b2d5949fd6630ed53c8879e532d39d27b399 | 3,615,117 |
def _blkidx(n_s=3):
"""Calculate indices for a 3x3x3 grid around an index of 0"""
return (np.array(np.where(np.zeros((n_s, n_s, n_s)) == 0)).T - (
(n_s - 1) / 2)).astype(int) | 04c996d2d1249fa5c36557bb4165f7193ecc4331 | 3,615,118 |
def cdsem_bend180(
width: float = 0.5,
radius: float = 10.0,
wg_length: float = LINE_LENGTH,
straight: ComponentFactory = straight_function,
bend90: ComponentFactory = bend_circular,
cross_section: CrossSectionFactory = strip,
text: ComponentFactory = text_rectangular_mini,
) -> Component:
... | e0b8b6012ca719478b73e8a9130639382b6bde44 | 3,615,119 |
def EWMA(inputs, *args, **kwargs):
"""EWMA of an inputted list, returns the weighted list. """
if "alpha" in kwargs:
alpha = kwargs.get("alpha")
if alpha > 1 or alpha < 0:
print("Alpha value cannot exced range of [0,1]!!!")
return
else:
alpha = 0.5 # init, default alpha
S1 = inputs.sum()/len(inputs)
... | fce299fea21d3bcd6d81d2a4d4d0601ed3e9b203 | 3,615,120 |
def desaturate(img_paths, percent=30, write=True):
""" desaturate(img_paths, percent=30, write=True)
Takes image(s) and desaturates them.
:type img_paths: pyifx.misc.PyifxImage, pyifx.misc.ImageVolume, list
:param img_paths: The image(s) to be desaturated.
:type percent: int
:param percent: How much the i... | 59e0a5f8618ecd3c93d5a31c5698978e77ce1bf9 | 3,615,121 |
def density_standard(components):
"""
Natural gas density at standard temperature, kg/m3
:param components: (list) List of gas components. Each item is an object of class GasComponent
:return: (float) The density of natural gas an standard parameters, kg/m3
"""
return sum([component.density_sta... | c087ce6ae1a3486dd092341286023c56606380a3 | 3,615,122 |
def get_latlongrid(dset, xindx, yindx):
"""
INPUTS
dset : xarray data set from ModelBin class
xindx : list of integers
yindx : list of integers
RETURNS
mgrid : output of numpy meshgrid function.
Two 2d arrays of latitude, longitude.
"""
llcrnr_lat = dset.attrs["Concentra... | 35c9467237be0b6853f32b099e74ff618df33529 | 3,615,123 |
def Network_RosslerSystem(Y,t, F,w, A, b, c, Nsys):
"""Defines a set of coupled Rossler Systems in a Network structure.
Coupling is done through the y variable.
The coupling and the network topology is defined by the matrix A.
The sistem is (where (i) * is multiplication element wise
... | 78dcffabd07c79b05e7c4726fe8780450e870f45 | 3,615,125 |
def plot_flux_boxplot(ENSEMBLE_DIR, sample_id, popfva_df, react_plot_list, pheno_id, obj_direction,pre_y=False,
savefig=True,whis=1.5,s_size=100,width=0.5,labelsizes=10,notch=True,jitter=True,linewidth=1,
dodge=True,palette=["#2020FF", "#FF0303"],f_scale=1.0,figSIZE=(40,5),pl... | a32f7799a080ad2d102eabe779aa468687287a3a | 3,615,126 |
def getStudentByID(studentID):
"""
根据学生ID获取学生
"""
condition = 'studentID={}'.format(studentID)
return generalGet('student', 0, condition) | 925b032a2bc74acec7b929e4fd1f56de0e52b83d | 3,615,127 |
import re
def range_address_number(num, include_last=True):
"""
'5-7' -> [5, 6, 7]
'5' -> ['5']
:param num:
:return:
"""
range_re = re.search('(\d+)-(\d+)', num)
if range_re:
min, max = list(map(
lambda i: int(i),
list(range_re.groups())
))
... | 3c67ddcba2a25915fce89c198d4d4f2a11f5ef60 | 3,615,128 |
def generate_test_uuid(tail_value=0):
"""Returns a blank uuid with the given value added to the end segment."""
return '00000000-0000-0000-0000-{value:0>{pad}}'.format(value=tail_value,
pad=12) | f113eef54eba9d8d1fb5234c87af3cb6290ea25e | 3,615,129 |
def copy_cluster_decoys(decoy_list, target_dir, create_dir=True, verbose=True, **kwargs):
"""
Copy cluster decoys specified in <decoy_list> to <target_dir>.
Args:
decoy_list (list):
| output of abinitio.get_decoy_list()
| or cluster.rank_cluster_decoys(return_path=True)
... | 44e3767179d03d84a5b174f0473cf75d23a6435b | 3,615,130 |
def download(url, destination, overwrite=False):
"""
Download a file
:param url: URL to download from
:type url: str|unicode
:param destination: target path and filename for downloaded file
:type destination: str|unicode
:param overwrite: specify whether or not an existing destination shou... | ae948f7790460c008f554ef4f8bd97b7bda1f584 | 3,615,131 |
def create_sub_graph_copy(graph: Graph, nodes_to_extract: list):
"""
Create new graph which is a sub-graph of the 'graph' that contains just nodes from 'nodes_to_extract' list. The
returned sub-graph is a deep copy of the provided graph nodes.
:param graph: graph to create a sub-graph from.
:param n... | efadb29c9bb522e448cb07079f17b4e0c51956e1 | 3,615,132 |
def descent_direction_i(X, i):
"""
Returns the 3D vector for the direction of decreasing energy at point i.
Parameters
----------
X : numpy.nadarray, with shape (N, 3)
Current configuration of points. Each row of `X` is the 3D position
vector for the corresponding point in the curre... | 0d31adb9ee65cb8f9851c2eeb24c333d3cff780b | 3,615,133 |
from typing import List
def java_args(spark: SparkSession, args: List[str]):
"""
Convert a Python list into the corresponding Java argument array.
"""
rv = SparkContext._gateway.new_array(spark._jvm.java.lang.String, len(args))
# https://stackoverflow.com/a/522578
for index, arg in enumerate(... | f02af6e73cbf9c3505b64e9568b51226c9a1cdd8 | 3,615,134 |
def format_revision_list(revisions, use_html=True):
"""Converts component revision list to html."""
result = ''
for revision in revisions:
if revision['component']:
result += '%s: ' % revision['component']
if 'link_url' in revision and revision['link_url'] and use_html:
result += '<a target="... | d49e91069a1f33a7ee32963e81a3e19ea768d3ea | 3,615,136 |
def order_table(headers, table, order_column, natural_order=None, limit=None):
"""
:type natural_order: list
:param natural_order: define the order for each column.
if the value in natural_order is true, the reverse is True else False
[True, False, True]
build the table
"""
if len(head... | 68b1c3fbd53799267707eb2788e9115f3fd943e2 | 3,615,137 |
from typing import Dict
async def total() -> Dict:
"""
Sum of a list of numbers
---
tags:
- Total
get:
parameters:
- N/A
response:
200:
description: returns a dictionary with a total sum of a list of numbers
"""
retu... | 67c1d1abf6c76c533d8ea776dbb46a4184b0fca5 | 3,615,140 |
import inspect
def is_extension(cls):
""" Check if a class is a MudPi Extension.
Accepts class or instance of class
"""
if not inspect.isclass(cls):
if hasattr(cls, '__class__'):
cls = cls.__class__
else:
return False
return issubclass(cls, BaseExtensio... | ea58d6107524d1e349c06e7153d38e13c6991cb6 | 3,615,141 |
def kalman_xy(x, P, measurement, R,
motion = np.matrix('0. 0. 0. 0.').T,
Q = np.matrix(np.eye(4))):
"""
Parameters:
x: initial state 4-tuple of location and velocity: (x0, x1, x0_dot, x1_dot)
P: initial uncertainty convariance matrix
measurement: observed position
... | fcc2ae434533e281aeee619350ab9b28f09972de | 3,615,142 |
import click
def create_droplet_click(token):
"""
Creates a droplet in your DigitalOcean account.
Accepts one option (the Digital Ocean API token key).
token: [env var name | path to file | token str] Resolved in that order.
Example:
droplet -t MY_TOKEN
The above will first look at an ... | c7b5c00b59c256fda1e64c041694301a3ca18a21 | 3,615,143 |
def is_view_loaded(view):
"""returns a buf if the view is loaded in sublime and
the buf is populated by us"""
if not G.AGENT:
return
if not G.AGENT.joined_workspace:
return
if view.is_loading():
return
buf = get_buf(view)
if not buf or buf.get('buf') is None:
... | e6db647e079bb40b6dcf419ed6b2d04c9140c439 | 3,615,144 |
def linearmap(x, ymin, ymax, flag='linear'):
"""
Maps given function in the range of ymin, ymax
"""
if flag =='log':
x = np.log10(x)
ymin = np.log10(ymin)
ymax = np.log10(ymax)
xmin = Utils.mkvc(x).min()
xmax = Utils.mkvc(x).max()
y = (ymax-ymin)*(x-xmin)/(xmax-xmin) + ... | 68ddf5d9784ded1f88cca9c1f19e0b25846b7b76 | 3,615,145 |
def Log_SetRepetitionCounting(*args, **kwargs):
"""Log_SetRepetitionCounting(bool bRepetCounting=True)"""
return _misc_.Log_SetRepetitionCounting(*args, **kwargs) | 226ec96f45e40171c8b5f59c11c814c6317819b9 | 3,615,146 |
from typing import Optional
from typing import List
def get_optimal_index_keys_v2(
nb_vectors: int,
dim_vector: int,
max_index_memory_usage: str,
flat_threshold: int = 1000,
quantization_threshold: int = 10000,
force_pq: Optional[int] = None,
make_direct_map: bool = False,
should_be_me... | 90972d9f4a951dfd80bb05c48440a63676ebc047 | 3,615,147 |
import scipy
def laplacian_ij(X,hi,hj):
"""
Compute the LAPLACIAN OPERATOR of an image
"""
M,N = X.shape
D2i = (toeplitz(scipy.append(scipy.array([-2,1]),scipy.zeros((M-2,1))))/(hi**2));
D2j = (toeplitz(scipy.append(scipy.array([-2,1]),scipy.zeros((N-2,1))))/(hj**2));
D2i[0,1] =... | 60080483176071814a8603f952c706bdb282848a | 3,615,148 |
def memoize(f):
"""
A simple memoize implementation. It works by adding a .cache dictionary
to the decorated function. The cache will grow indefinitely, so it is
your responsibility to clear it, if needed.
to clear: `memoized_function.cache = {}`
"""
def _memoize(func, *args, **kw):
... | 5db3894b24017035f8f122cc09e558ee9e034607 | 3,615,149 |
from bs4 import BeautifulSoup
def bishijie_info_parse(parse_str:str = ''):
"""
传入一个待解析的字符串
"""
# html_info = etree.HTML(parse_str,parser=None)
soup = BeautifulSoup(parse_str,features="lxml")
info_list = soup.find_all('div',class_="content")
result_info_list = []
for info in info_list:... | e89a875f9c98b3b9cabeed2eb362ad1196b14275 | 3,615,151 |
def connect_tcp(host, port):
""" return Client connected to the TCP socket """
c = Client()
c.setup_tcp_socket(host, port)
c.connect()
return c | 7f87953d3da354c2db1675b262f196758e5bde05 | 3,615,152 |
def parse_args():
"""
Handles argument parsing for bvauto.
"""
res = {}
nargs = len(sys.argv)
if nargs < 2:
print "usage:"
print " Test build_visit on current machine:"
print " bvauto.py [bvauto.input]"
print " Test build_visit on current machine and post result... | 663dd78d98387ccb76e199113f4d77c5a4a68f86 | 3,615,153 |
def state_store(decoy: Decoy) -> StateStore:
"""Get a mocked out StateStore."""
return decoy.mock(cls=StateStore) | 3b3b69b226d884546ef1fd87c069a24faf0b783b | 3,615,154 |
def get_model_specs(model_name):
"""Return a dict with configurations required for configuring `model_name` model."""
if model_name == "lm":
return lm_wikitext2.get_model_config()
elif model_name == "seq":
return offload_seq.get_model_config()
else:
raise RuntimeError("Unrecogni... | 1c0ff40cb550ef79435ec41805daea843a7f138c | 3,615,155 |
def rbf_lmsq_error_d_wrt_ith_g(x, y, g, w, u, i):
"""
radial basis function
least mean square error derivative
with respect to the ith gamma
g : gammas
w : weights
u : centers
"""
return -2 * w[i] * np.linalg.norm(x - u[i]) * gaussian(g[i], x, u[i]) * (rbf_h(x, g, w, u) - y) | bfcbf07a2efa77b487d894c34bcc19dbd851aed9 | 3,615,156 |
def schedule_pool(outs, layout):
"""Schedule for various pooling operators.
Parameters
----------
outs: Array of Tensor
The computation graph description of pool
in the format of an array of tensors.
layout: str
Data layout.
Returns
-------
s: Schedule
... | 7d77f1260e60e0216400c2423d92013cc137470e | 3,615,157 |
def Hamiltonian(N,V):
""" Generates the 'N'-dimensional Hamiltonian matrix of
a 1-d tight binding model for an array nearest neighbor site couplings 'V'
"""
H = np.zeros((N,N))
H[0][1] = V[0]
H[N-1][N-2] = V[N-1]
for i in range(1,N-1):
H[i][i+1] = V[i]
H[i][i-1] = V[i]
... | de94262c8ebe8d2e3fd00b0b63adeef95edaa6c3 | 3,615,158 |
from typing import Iterable
def _create_lines_for_order(
manager: "PluginsManager",
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
discounts: Iterable[DiscountInfo],
) -> Iterable[OrderLineData]:
"""Create a lines for the given order.
:raises InsufficientStock: when there... | f80a82ab022ab5375b6f0b46f4becaec4a72b4ca | 3,615,160 |
import pprint
import warnings
def single_mode(ell, m, **kwargs):
"""WaveformModes object with 1 in selected slot and 0 elsewhere
Additional keyword arguments are passed to `modes_constructor`.
Parameters
----------
ell, m : int
The (ell, m) value of the nonzero mode
"""
if kwarg... | a2f83370ae82119f3805dddc4a049f96b4db9dcc | 3,615,161 |
def extractAliasFromContainerName(containerName):
""" Take a compose created container name and extract the alias to which it
will be refered. For example bddtests_vp1_0 will return vp0 """
return containerName.split("_")[1] | a5ab9487ae31ee1a4b2ed9b67062817488107983 | 3,615,163 |
from datetime import datetime
def sell():
"""Sell shares of stock"""
# Retrieve current symbols and shares of stocks owned by the user
stocks = db.execute(
"SELECT stock AS symbol, SUM(CASE WHEN transaction_type='buy' THEN shares WHEN transaction_type='sell' THEN -shares ELSE NULL END) AS shares ... | 0bdab7d0b90f852324f28f0cb38c9932c1c6e888 | 3,615,164 |
def disable_fetcher():
"""arg: fetcher_id"""
disable_user_fetcher(
get_current_user_id(), request.values['fetcher_id'])
return {'success': 1} | b2026254096e5c837a8137de0d0f98a4ca55363b | 3,615,165 |
def jupyter_show_as_svg(g):
"""
Shows object as SVG (by default it is rendered as image).
@param g: digraph object
"""
return HTML(g.pipe(format='svg').decode("utf-8")) | 1f12a270f87976c1f57e24eb82fbe77bd90937e5 | 3,615,166 |
from copy import deepcopy
def parse_data(train, test):
"""Load data from train and test files respectively."""
# Scale X and Y features in train to 0 mean, unit variance
xy_scaler = StandardScaler()
xy_scaler.fit(train[["X", "Y"]])
train[["X", "Y"]] = xy_scaler.transform(train[["X", "Y"]])
tr... | 4ce2b26d04cce01e12d98a97aa1b6f1f2d8a6021 | 3,615,167 |
from typing import Sequence
def primes(n: int) -> Sequence[int]:
"""Returns the first n prime numbers in sorted order."""
_compute_primes(n)
return _prime_sequence[:n] | 54f8a552636ca74999f855a3ec2c403bb81ca794 | 3,615,168 |
import time
def _create_docstring_df():
"""creates the df used in the docstring of single_val_cols_to_dict"""
return pd.DataFrame(index=pd.date_range(time, periods=3, freq='1H'),
columns=['col1', 'col2', 'col3'], data=[[1.0, 2.0, 3.0], [1.0, 4.0, 3.0], [1.0, 6.0, 3.0]]) | 5e78f1ad8e2e50bc64ab068011490cecafa030cb | 3,615,169 |
def test_if_df(data: pd.DataFrame) -> bool:
"""Test if passed data instance is from class DataFrame
Arguments:
data {pd.DataFrame} -- This is data input
Returns:
bool -- Returns bool if passed data is data
"""
return isinstance(df, pd.DataFrame) | 1786e97f430a079635ea9e48419e96a8fc240713 | 3,615,170 |
def load_data(projection: dict) -> pd.DataFrame:
"""
Load the data from the Mongo collection and transform
into a pandas dataframe
:projection: A dictionary with the fields to load from database
:return: A pandas dataframe with the data
"""
articles = db.read_articles(
projection=pro... | 481c44364dbee99e22cd6d95dc9778a52f15c997 | 3,615,171 |
def block_to_actions(block, delete_existing=False):
"""Converts a block vector representation into actions that create the block.
The idea here is that a block with the properties of `block` will be created
when the returned actions are executed in the unity environment.
Note that if delete_existing=False, an... | ab42f2ecfe9944be30ea13d678e5562765487c9f | 3,615,172 |
def get_stack(token, stack_id):
"""
Asks OpenStack Heat for stack details
"""
url = token.get_service_url(OPENSTACK_SERVICE.HEAT)
if url is None:
raise ValueError("OpenStack Heat URL is invalid")
api_cmd = url + "/stacks/%s" % stack_id
response = rest_api_request(token, "GET", api_... | b2947caa33d6ab3232468d78818b187616c687ab | 3,615,173 |
def is_log_i18n_msg_with_mod(n):
"""LOG.xxx("Hello %s" % xyz) should be LOG.xxx("Hello %s", xyz)"""
if not isinstance(n.parent.parent, compiler.ast.Mod):
return False
n = n.parent.parent
if isinstance(n.parent, compiler.ast.CallFunc):
if isinstance(n.parent.node, compiler.ast.Getattr):
... | 51dcc456444b7332b4cc5444551b0f34fe1149f2 | 3,615,174 |
from datetime import datetime
import pytz
def _unpack_series(json_data, product):
"""Returns a list of time series from get-netcdf-data JSON."""
key = 'long_range_mem1' if product == 'long_range' else product
time_step_hrs = PRODUCTSv1_1[key]['step_hrs']
offset_hrs = PRODUCTSv1_1[key]['offset_hrs']
... | 102c234c0e590a6e50fff20b092e7f3047ba0be8 | 3,615,176 |
def HexToByte( hexStr ):
"""
Convert a string hex byte values into a byte string. The Hex Byte values may
or may not be space separated.
"""
# The list comprehension implementation is fractionally slower in this case
#
# hexStr = ''.join( hexStr.split(" ") )
# return ''.join( [... | eab4fd7ecaae10add8411cf51c03d1bf5b902700 | 3,615,177 |
def gabor(sigma, theta, Lambda, psi, gamma):
"""Gabor feature extraction."""
sigma_x = float(sigma) / gamma
sigma_y = float(sigma) / gamma
# Bounding box
nstds = 3 # Number of standard deviation sigma
xmax = max(abs(nstds * sigma_x * np.cos(theta)), abs(nstds * sigma_y * np.sin(theta)))
xm... | d5fafd33ba13a9e863b150634da6315dddda0599 | 3,615,178 |
def brier_score_loss_for_true_class(y_true, y_proba):
"""
Calculates Brier score for from a set of class probabilities.
:param y_true: True class labels.
:type y_true: list
:param y_proba: Predicted class probabilities.
:type y_proba: array-like
:return: Brier score
"""
if y_proba is... | bc56e176bf61a5da5c7343f338d1caaf03a9229a | 3,615,180 |
def _truncate_term_length(term, taken=0):
"""truncate the length of a term string length to the maximum allowed
for xapian terms
:param term: the value of the term, that should be truncated
:type term: str
:param taken: since a term consists of the name of the term and its
actual value, thi... | 4011f1614ff79a84449fe3ac8fda48b354394e32 | 3,615,181 |
def families_sextupoles():
"""."""
return [] | 6863e887f377bc7afc8430878bf74a7c9e1d1085 | 3,615,182 |
def get_schema_from_list(schema_list):
"""
Create a bigquery schema from a list
:param schema_list: Columns definitions separate by "," character,
A column definition is NAME: TYPE
:return: bigquery schema
"""
schema = []
columns_def = schema_list.split(',')
for column_def in co... | 2b1311b1008543182a296f870fa4a3e2a20bbdc1 | 3,615,184 |
def calcError(svm, alpha_k):
"""
计算误差: E = g(X) - y
"""
g_k = float(np.multiply(svm.alphas, svm.label).T * svm.kernel_mat[:, alpha_k] + svm.b)
error_k = g_k - float(svm.label[alpha_k])
return error_k | 811d377e65fff58405bd3f52dd17bf9ef8df791e | 3,615,185 |
def ma30_cross_func(data):
"""
MA均线金叉指标
"""
MA5 = talib.MA(data.close, 5)
MA10 = talib.MA(data.close, 10)
MA30 = talib.MA(data.close, 30)
MA90 = talib.MA(data.close, 90)
MA120 = talib.MA(data.close, 120)
MA30_CROSS = pd.DataFrame(np.c_[MA5,
MA10,
... | 7e933d1d54a53ab69e59f80992ef083c3ecd1aae | 3,615,186 |
def get_method_from_html(html_file):
"""
Parse simulation method name from html_file
"""
input_file = open(html_file, 'r')
for line in input_file:
if line.find("Simulation Method") > 0:
line = next(input_file)
break
token = line[4:].split("<")[0]
input_file.cl... | da7e459852b5bfdf5de3d1375d23120ed5be2feb | 3,615,188 |
import copy
def make_test_problems(settings):
"""Creates test problems from settings.
Args:
settings (list[dict]): raw settings of the problems
Returns:
list[ExtensionTestProblem]
"""
problem_dicts = []
for setting in settings:
setting = add_missing_defaults(setting)... | 5eaa360e472b7ba6884dde482c449e67224963c7 | 3,615,189 |
def plot_hits(
ax,
hits_dict,
reference_length=None,
plot_range=None,
hide_missing_pairs=True,
bar_height=0.8,
bar_color="blue",
sort_key=lambda i: i,
):
""" Groups hits by query, and places above reference
hits_dict: map from query_id to list of hit objects
bar_color... | 9fd2cea23ceccb1b7703db412826ee7aa47739bc | 3,615,190 |
import re
def UserUpdate(fCallback):
"""Get User and log update requests passing to fCallback
The log will be handed to fCallback when 'ok' is received"""
def log_update_requests_and_call(self, *args, **kwargs):
cmd = args[0]
arg = args[1]
# Empty line
if cmd is None:
... | 2cf80f8ebd6a98f47bb3a220854ea9791c5d53be | 3,615,191 |
from typing import List
from typing import Tuple
def get_sub_graph_external_input_output(
predict_net: caffe2_pb2.NetDef, sub_graph_op_indices: List[int]
) -> Tuple[List[Tuple[str, int]], List[Tuple[str, int]]]:
"""
Return the list of external input/output of sub-graph,
each element is tuple of the na... | b8b6a22980ab2afb5f5ff83dd8c757740fe6bf25 | 3,615,192 |
def _butterworth(ts, low_frequency, high_factor, order, sampling_frequency):
"""Butterworth filter
Parameters
----------
ts: np.array
T numpy array, where T is the number of time samples
low_frequency: int
Low pass frequency (Hz)
high_factor: float
High pass factor (pro... | 4f68657c2686c0683a421bc7b8b4e3cd906362d4 | 3,615,193 |
import tempfile
def mk_conf_file(conf):
"""
Creates config file in temporary file.
"""
tmp_fp = tempfile.mktemp()
with open(tmp_fp, "w") as f:
print(mk_conf_str(conf), file=f)
return tmp_fp | 57fbcf4ca427455b103fe9efeee79246a35c7141 | 3,615,194 |
def get_string(request, key):
"""Returns the first value in the request args for a given key."""
if not request.args:
return None
if type(key) is not bytes:
key = key.encode()
if key not in request.args:
return None
val = request.args[key][0]
if val is not None and typ... | ae43bb3e11cf21deb8f726ed6a2321c51099e4f3 | 3,615,195 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.