content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def psi4calc(mol):
"""
Creates a molecule object for Psi4 from XYZ file
"""
geom=psi4.qcdb.Molecule.init_with_xyz(mol)
mol=psi4.geometry(geom.create_psi4_string_from_molecule())
return mol | ce27ecec44c24553b600a1a88238481687dac59d | 81,101 |
def parse_linestring(wkt):
"""
Parses LINESTRING WKT into a list of lon/lat (str) tuples.
:param wkt: The WKT for the LINESTRING
:type wkt: str`
:return: List of (lon,lat) tuples.
:rtype: list[(str,str)]
"""
return [
lonlat.split(" ") for lonlat in _linestring_rx.match(wkt).grou... | 8339b7d4814794db910d9278344f98f9d1506b3f | 81,102 |
def docker_mem(container_id):
"""
Calculates the current, maximal and percentage usage of the specified docker container.
:param container_id: The full ID of the docker container.
:type container_id: ``str``
:return: Returns a dictionary with the total memory usage, the maximal available memory and... | 884ba15d13774119846c5d5ea3ae4f718d5c9006 | 81,103 |
def get_fk_query_name(model, related_model):
"""
Format the DB column name of a foreign key field of a model
with the DB table of the model. Finds the foreign key relating to
related model automatically, but assumes that there is only one related field.
Args:
model (Model): The model f... | 4b3c145486537274a64d8675f81276ba5018975e | 81,104 |
def read_camera_readouts(filename):
"""
Read all camera readouts from a DL1 file
Parameters
----------
filename: str
Returns
-------
dict of `ctapipe.instrument.camera.description.CameraDescription` by tel_id
"""
subarray_layout_path = "configuration/instrument/subarray/layout... | 0d7756a5bb4be0c1e227f3cac9860602451442da | 81,106 |
from typing import Dict
def get_file(file_id: list) -> Dict:
"""
Get put-files based on the ID's given
:param file_id: ID of file to get
:return: Response JSON which contains errors (if exist) and retrieved resources
"""
endpoint_url = '/real-time-response/entities/put-files/v1'
... | 4c879d1e0017b305baca0db4d2f47eaa89d6b0e7 | 81,107 |
from .integrateFullOrbit import _parse_scf_pot
import numpy
def _parse_pot(pot):
"""Parse the potential so it can be fed to C"""
#Figure out what's in pot
if not isinstance(pot,list):
pot= [pot]
#Initialize everything
pot_type= []
pot_args= []
npot= len(pot)
for p in pot:
... | 6edf9692d3ea541ab660efbcb181b51260e96aa8 | 81,108 |
def load_caffe_graph(prototxt_path: str, caffemodel_path: str,
setting: QuantizationSetting) -> BaseGraph:
"""
从一个指定位置加载 caffe 计算图
load caffe graph from the specified location
Args:
prototxt_path (str): caffe prototxt的保存位置 the specified location of caffe prototxt
... | f6df7efb0d0b491102ffee00f646874f9f023ecf | 81,109 |
import io
def open_general(filename_or_handle, iomode=None):
"""
Open a file directly from a path or use a file handle if that is given.
Also take care of closed files by reopenning them.
This is intended to be used like this::
f = open_general(outfile)
with f: # make sure the file is... | b03a3e76d3585eabdca5a70fc72ed53d01d1f193 | 81,113 |
import re
def parse_files(s, regex=r'^\s+Filename: (.+).(mp4|3gp)$'):
"""Returns a tuple representing the IDs, filenames, and file sizes of
mtp-files output."""
# Some preparation.
ret = set()
found_filename = False
found_filesize = False
found_fileID = False
# Loop.
temp_fileID, t... | 98028fd02a06f037fd03ff9cec4bbcf36d6df98b | 81,114 |
def get_mask(image, model, augs, device='cuda'):
"""
:param image: image with shame H, W, C
:param model: segmentation torch model
:param augs: preprocessing function for input image
:param device: torch device
:return: cv2 mask
"""
image = image.copy()
image = cv2.cvtColor(image, cv... | 50c5356f60f93f34566721fcb9c08caa4829b54f | 81,115 |
def inception_block(net, activation_fn=tf.nn.relu,scope=None, reuse=None):
"""Builds the inception with dimension reductions block"""
with tf.variable_scope(scope, 'inception_block',[net], reuse=reuse):
with tf.variable_scope('Branch_0'):
conv1_0 = slim.conv2d(net,
... | 51b8edd458c108cb92d666a9edc402425613a743 | 81,117 |
def get_user_lang(user=None):
"""Set frappe.local.lang from user preferences on session beginning or resumption"""
user = user or frappe.session.user
lang = frappe.cache().hget("lang", user)
if not lang:
# User.language => Session Defaults => frappe.local.lang => 'en'
lang = (
frappe.db.get_value("User", us... | e7ea333132fe53c2cef83c98e55ab84fbb584321 | 81,118 |
import json
def delete_message(request):
"""" delete the message by the giving id """
try:
print('im start to deleting')
json_data = json.loads(request.body)
msgs_list = Message.objects.filter(reciever=json_data['email'], id=json_data['id'])
msgs_list2 = Message.objects.filter(... | 379a421fb824e7a2bb5c8c6ad87b077b0451e4ca | 81,119 |
def add_salt_and_pepper(img):
""" Add salt and pepper noise to an image. """
noise = np.zeros((img.shape[0], img.shape[1]), dtype=np.uint8)
cv.randu(noise, 0, 255)
black = noise < 30
white = noise > 225
img[white > 0] = 255
img[black > 0] = 0
cv.blur(img, (5, 5), img)
return np.empty... | cf6e706ffebb01611c3a1ce0dc64bad079a73535 | 81,120 |
from typing import Optional
from typing import List
from typing import Dict
def fetch_indicators(client: Client,
is_get_command: bool,
tlp_color: Optional[str] = None,
feed_tags: List = None,
limit: int = -1,
crea... | 93808368f475929ab945f9bc03bb20e6d684d958 | 81,121 |
def dense(data, weight, bias=None, out_dtype=None):
"""The default implementation of dense in topi.
Parameters
----------
data : tvm.te.Tensor
2-D with shape [batch, in_dim]
weight : tvm.te.Tensor
2-D with shape [out_dim, in_dim]
bias : tvm.te.Tensor, optional
1-D with sh... | 2d508383924e96dcc3e6619b03cf4ac61acb3c23 | 81,122 |
def cold_gas_efficiency(self, fuel_lhv, moisture_fuel):
"""
Return cold gas efficiency of gasification.
fuel_lhv : ndarray
Fuel LHV
moisture_fuel : ndarray
Fuel moisture
"""
return (syngas_lhv(self, 1 + moisture_fuel)/fuel_lhv) | f0da4953fb578e197f65211a07ff89442f417a94 | 81,123 |
from typing import Union
from typing import TextIO
from pathlib import Path
from typing import Dict
from typing import Any
import io
def rinexheader(fn: Union[TextIO, str, Path]) -> Dict[str, Any]:
"""
retrieve RINEX 2/3 or CRINEX 1/3 header as unparsed dict()
"""
if isinstance(fn, (str, Path)):
... | fd32c235ecd0e3c4e827806462f1995fb1813217 | 81,124 |
def is_shortcut_name(name: str) -> bool:
"""Returns true if the name is a valid short-cut name."""
return name.count(config.name_separator) == 1 | 769fd20fe1deece31aa0eebe73ffc361145c9336 | 81,125 |
import unittest
def suite():
"""Define all the tests of the module."""
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(GetMetricV2TestCase))
return suite | 0ddc3307eb4c155ee58bf508e172056eafb42528 | 81,126 |
def compute_something(a: float, b: int) -> float:
"""Sums `a` and `b`.
Args:
a: A brief explanation of `a`.
b: A brief explanation of `b`.
Returns:
float: The sum of `a` and `b`.
Notes:
The addition of an `int` and a `float` returns a `float`.
Mathematically,... | 997d6d811d10a2d70606addc76f7e906e8f9c73d | 81,127 |
def getOperations(public_key: str) -> list:
"""
Get all the claimable_balance operations a user executed.
"""
operations = server.operations().for_account(public_key).limit(200).order(desc=True).include_failed(False).call()['_embedded']['records']
data = []
for operation in operations:
i... | b3917c125219d403462e3216f5afdf4195fc6ed8 | 81,128 |
from pathlib import Path
import pickle
def generate_elasticity_data(
download_data=True,
cif=False,
train_e_above_hull=0.05,
val_e_above_hull=0.05,
theoretical=False,
folder=join("mat_discover", "data", "elasticity"),
):
"""Download (or reload) elasticity data using MPRester.
Paramete... | 0a912b468267fdb1b20f28bda3afbf88d874328d | 81,130 |
def get_model(key):
""" Get different backbone network by key,
support ResNet50, ResNet_101, ResNet_152
IR_18, IR_34, IR_50, IR_101, IR_152, IR_200,
IR_SE_50, IR_SE_101, IR_SE_152, IR_SE_200,
EfficientNetB0, EfficientNetB1.
MobileFaceNet, FBNets.
"""
if key in _model_... | f2d358ff3553d33c8748210b6cc8cf9d34c4e56f | 81,131 |
def cli(ctx, form_xml_text):
"""Create a new form.
Output:
Unique URL of newly created form with encoded id
"""
return ctx.gi.forms.create_form(form_xml_text) | 2258febff3094f14b96ce156ef596be368096bd6 | 81,132 |
def fib_4_binets_formula(n):
"""
Solution (cheat): Use Binet's formula.
Sometimes math just wins.
Complexity:
Time: O(1)
Space: O(1)
"""
if n < 0:
raise ValueError('input must be a positive whole number')
v1 = 1 / sqrt(5)
v2 = pow((1 + sqrt(5)) / 2, n)
v3 = pow((1 - sqrt(5)) / 2, n)
return int(v1 * (v2... | 7af674f16fedf92876890d7967ec8932503ac4f8 | 81,133 |
def get_project(domain_id=None, enabled=None, is_domain=None, name=None, parent_id=None, region=None):
"""
Use this data source to get the ID of an OpenStack project.
"""
__args__ = dict()
__args__['domainId'] = domain_id
__args__['enabled'] = enabled
__args__['isDomain'] = is_domain
__... | 9a618a49690eecb5b6f155b4fce9362118aed3fc | 81,134 |
def sanitize_suffixes(*suffixes):
""" Ensure suffixes (which may be passed in from the user) are clean
"""
return set((suffix.lower() for suffix in suffixes)) | 9981a932637e1677141ebff02119e48bf9b6cd1a | 81,135 |
def by_volume(self, TP):
"""Return a ChemicalVolumetricFlowIndexer that references this object's molar data.
Parameters
----------
TP : ThermalCondition
"""
try:
vol = self._data_cache['vol', TP]
except:
chemicals = self.chemicals
mol = self.data
vol... | ce4eca9993b4abdd8dfc007da49800e650a9d114 | 81,136 |
import torch
def prepare_data(features,edge_list,labels):
"""准备输入数据
Params:
features:网络节点总数ee
edge_list:连边列表e
"""
# 构造输入特征
features = sp.csr_matrix(features,dtype=np.float64)
adj = sp.coo_matrix((np.ones(edge_list.shape[0]), (edge_list[:, 0], edge_list[:, 1])), shape=(),
... | 9bb3451a20e8d4fb615b1d40f051295f15a1d91f | 81,137 |
def resize_sample(sample, shape, image_interpolation=Image.ANTIALIAS):
"""
Resizes a sample, including image, intrinsics and depth maps.
Parameters
----------
sample : dict
Dictionary with sample values
shape : tuple (H,W)
Output shape
image_interpolation : int
Inter... | b2803e33200905713394e461ecd737a3d608644e | 81,138 |
import time
def som(X, range_n_dim, top_lbls=10, preprocessing = None, bin_X=False, transform=None, experiment_name=None, **kwargs):
"""
This function applies the self organising maps algorithm from somoclu on inputs X over square maps of range_n_dim.
If preprossing = True, X is normalised with sklearn.pr... | a720f23cf054b0b7d5d7c20bbd4ab1af75552a06 | 81,139 |
def turn_finder(Seq, Table):
"""
Find the residues that might correspond to turns in a sequence.
Conditions are as per the algorithm.
Returns a list of indices with predicted turns.
"""
results = []
for i in range(len(Seq)-4):
window = Seq[i:i+4]
#Three Conditions
... | e85136767184e0fa7c0a8b0097233e7d322d4190 | 81,140 |
def peak_ratio(DataFrame_x, DataFrame_y):
"""Outputs the peak ratios from cyclic voltammetry data.
Parameters
----------
DataFrame_x : should be in the form of a pandas DataFrame column.
For example, df['potentials'] could be input as the column of x
data.
DataFrame_... | c9fefd2c5f5ab6220cd199d605dbf582c1f3dc0b | 81,143 |
def H3(*content, **attrs):
"""
Wrapper for h3 tag
>>> H3().render()
'<h3></h3>'
"""
return KWElement('h3', *content, **attrs) | 0dd7632df4df6341a9d81ba0bdf8c3a25124f05d | 81,144 |
from typing import Optional
from datetime import datetime
import time
def json_iso_dttm_ser(obj, pessimistic: Optional[bool] = False):
"""
json serializer that deals with dates
>>> dttm = datetime(1970, 1, 1)
>>> json.dumps({'dttm': dttm}, default=json_iso_dttm_ser)
'{"dttm": "1970-01-01T00:00:00... | e47b5516a2b2570608f643eb4763fa465a492329 | 81,146 |
def quat_to_pol_and_roll(qfin, opaxis=[1, 0, 0], north=[0, 0, 1]):
"""
it is assumed that quaternion is acting on the sattelite coordinate system
in order to orient in in icrs coordinates
opaxis - define dirrection of the main axis (x axis [1, 0, 0] coinside with optical axis)
we assume that north i... | ba98d4539da8d2502f9cd4a545a06357675fcf29 | 81,147 |
def rstarlines_special_2(vals, uvbounds, c=None, sty={}, inf=100., npoints=1000, eps=1e-12):
"""
Produce lines of constant rstar for rstar in vals. Return list of curves.
(v-u)/2 = rstar - c
"""
## initialize
crvlist = []
uvb = uvbounds.copy()
cc = 1.*float(c)
## go
for val in vals:
## create new curve
... | 3adc015ce09638ce0d50406bdf03640d0ddf57a5 | 81,148 |
import math
def is_finite(x):
"""
Returns true if the argument is a float or int and it is not infinite or NaN
"""
try:
return not math.isinf(x)
except TypeError:
return False | 1dc4e253078f73126320a0e80658d52cceabdb07 | 81,149 |
from datetime import datetime
import time
def get_time_remaining():
""" returns the hours and minutes till midnight """
now = datetime.now()
midnight = datetime.combine(date.today() + timedelta(1), time())
time_remaining = midnight - now
seconds_left = time_remaining.seconds
total_minutes_left... | 1f7951e11bc43c17d65e137dbc69ddb3ce7c7027 | 81,150 |
import array
def int2buf(cnt: int, value: int
) -> array:
"""Converts an integer value to an
unsigned byte array
Args:
cnt : uint length of int data
value : value of uint data
Returns:
unsigned byte array
"""
return array('B', [(value >> (i ... | 13ad8517888411ade18767268f2a48bb7036dafd | 81,151 |
def str2bool(value):
"""
Convert a string boolean to a boolean value.
Parameters
----------
value : str or bool
The value to convert.
Return
------
value : bool
The string converted into a boolean value.
"""
if isinstance(value, bool):
return value
... | 25879baa1ef32806fa2f8f9b8f0c2b76efbc39f0 | 81,152 |
def pitching_stats(start_season, end_season=None, league='all', qual=1, ind=1):
"""
Get season-level pitching data from FanGraphs.
ARGUMENTS:
start_season : int : first season you want data for (or the only season if you do not specify an end_season)
end_season : int : final season you want data f... | c7c0511371b83763cf3ccb431d9419982f37d941 | 81,153 |
def disable_dns_hostnames(profile, vpc):
"""Disable DNS hostnames for instances in a VPC.
Args:
profile
A profile to connect to AWS with.
vpc
The ID of the VPC you want to disable DNS hostnames for.
Returns:
The JSON response returned by boto3.
"""
... | f64bf625b8c35962c0ca301b6204692d1fd7ffc4 | 81,154 |
import time
def mkpasswd(length=8, digits=2, upper=2, lower=2, symbols=2):
""" Create a random password """
seed(time())
symbol_chars = '.!@$%^&*()'
other_chars_len = length - digits - upper - lower - symbols
password = list(
chain(
(choice(UPPERCASE) for _ in range(upper)... | 0bfd2c3fba8ea1414997888102122495265e847f | 81,155 |
def vi_pairwise_matrix(segs, split=False):
"""Compute the pairwise VI distances within a set of segmentations.
If 'split' is set to True, two matrices are returned, one for each
direction of the conditional entropy.
0-labeled pixels are ignored.
"""
d = np.array([s.ravel() for s in segs])... | ea43fc897fe1fb32c0ec7f2d291ed2c2cb8f622e | 81,156 |
def crosstab_ztest(ctab):
"""
z-scores from 2x2 cross tabs of passing rate across groups
Parameters
----------
ctab: array, shape=(2,2);
crosstab of passing rate across groups, where each row is a group
and the first and second columns count the number of unsuccessful
and su... | 39f4eabefc5c281a3a8f5929f83000488ce69373 | 81,157 |
def get_backbone():
"""获取ResNet50的骨架网络, 返回ResNet50提取的特征信息."""
backbone = ResNet50(include_top=False, input_shape=[None, None, 3])
c3_output, c4_output, c5_output = [
backbone.get_layer(layer_name).output
for layer_name in ['conv3_block4_out', 'conv4_block6_out', 'conv5_block3_out']
]
... | e6aa5cac6d0b15db28697048623abe9fe1ffee2d | 81,158 |
def find_sift(im_source, im_search, threshold=0.5, rgb=True, good_ratio=FILTER_RATIO, get_point=False):
"""基于sift进行图像识别,只筛选出最优区域."""
# 第一步:校验图像输入
check_source_larger_than_search(im_source, im_search)
# 第二步:获取特征点集并匹配出特征点对: 返回值 good, pypts, kp_sch, kp_src
kp_sch, kp_src, good = _get_key_points(im_sou... | 1cf5b8605c028b3266279b627106e41bc25143fc | 81,159 |
from types import IntType
def no_ints_nulls(list):
"""in place remove all ints, Nones from a list (for null handling)"""
tt = type
nn = None
count = 0
for x in list:
if tt(x) is not IntType and x is not nn:
list[count] = x
count = count+1
del list[count:]
re... | 6fd90905167e69ac9272d182eb248b5f1acd031a | 81,161 |
def _get_dim_size(start, stop, step):
"""Given start, stop, and stop, calculate the number of elements
of this slice."""
assert step != 0
if step > 0:
assert start < stop
dim_size = (stop - start - 1) // step + 1
else:
assert stop < start
dim_size = (start - stop - 1)... | 550f77162570fb6b0608b4f5640a5487dd728ea2 | 81,162 |
def compact_capitalized_geography_string(s):
""" Go from lowercase "county, state-abbrev" string to Capitalized string
Args:
s:
Returns:
Examples:
"lancaster, pa" --> "LancasterPA"
"anne arundel, md" --> "AnneArundelMD"
"st. mary's, md" --> "StMarysMD"
"""
s =... | 2393e09007774b965f556af40c1e0cb969362cc2 | 81,163 |
def oucru_parental_fluid_correction(tidy, verbose=10):
"""Corrects parental fluid related columns.
It ensures that parental_fluid is True also when the
parental_fluid_volume is specified but no specific
parental_fluid column is found.
.. note: Uses compound_feature_correction
Parameters
-... | c0f73c167b071b6c41dc71744d4a7bb58224d639 | 81,164 |
import scipy
def combine_atlas_model(xi,yi,zi,pmask,local,VARIABLE=None):
"""
Combines global and local ATLAS tidal solutions into a single
high-resolution solution
Arguments
---------
xi: input x-coordinates of global tide model
yi: input y-coordinates of global tide model
zi: global... | e4a0b0814bb4881ea85ca5ea517a1fd4bd60f7a8 | 81,166 |
def mappings_from_sorted_tables(tables, table_order, reference_fields):
"""Generate mapping.yml data structures. """
mappings = {}
for table_name in table_order:
table = tables[table_name]
fields = {
fieldname: fieldname
for fieldname, fielddef in table.fields.items()... | 48e6cba1c06eaee6146a04cb469641830f771515 | 81,167 |
def rstate(rng=None):
"""
Return a RandomState object. This is just a simple wrapper such that if rng
is already an instance of RandomState it will be passed through, otherwise
it will create a RandomState object using rng as its seed.
"""
if not isinstance(rng, np.random.RandomState):
r... | 6dfd2a0173ef9e941a4a03496b0186a20076b9eb | 81,169 |
def cron_affiliate_jobs() -> tuple:
"""
**cron_affiliate_jobs**
affiliate related cron jobs - for checking and
1. finalizing affiliate payments.
2. sending finalized amounts to wallets
3. sending affiliate report - recruitments & earnings
:retu... | bf78f0b4f1c6013da8d445e512fce18cc45b8189 | 81,171 |
from typing import Callable
import re
def _regex_condition(value: str) -> Callable[[Message], bool]:
"""Creates a condition that is true when message text matches the given regex"""
exp = re.compile(value, flags=re.IGNORECASE)
def condition(message: Message):
return exp.search(message.text) is no... | 0eb69a2684f93a1641545e279ed8d642c445f9f3 | 81,172 |
def update_direction(direction, turn):
"""Return the directions ID after the given turn."""
answer = None
if turn == "R":
answer = (direction + 1) % 4
elif turn == "L":
answer = (direction - 1) % 4
return answer | a8ea3da50df3cbca3af2a4f42de764d1031285a6 | 81,173 |
def close_dock_control ( dock_control ):
""" Closes a DockControl (if allowed by the associated Traits UI Handler).
"""
# Retrieve the traits UI object set when we created the DockControl:
ui = dock_control.data
# Ask the traits UI handler if it is OK to close the window:
if not ui.handler.clos... | de923cc8055d300eb7ade08ea00020e1cdc25fe9 | 81,175 |
from typing import Sequence
from typing import Optional
from typing import MutableMapping
import collections
from typing import Set
import itertools
def confusion_matrix(
export_path: str,
classes_predictions: np.ndarray,
classes_trues: np.ndarray,
classes: Sequence[str] = None,
... | b66e19021841aa63ecfdb465334a6002e3fefa9b | 81,176 |
def jaccard_coef_metric_per_classes(probabilities: np.ndarray,
truth: np.ndarray,
treshold: float = 0.5,
eps: float = 1e-9,
classes: list = ['WT', 'TC', 'ET']) -> np.ndarray:
... | c92f61130a009fa3742ec8e32bf4e9584cdc8f4c | 81,177 |
def delta_chi2(ptarg, ndeg):
""" Find delta chi2 corresponding to the given probability for n
degrees of freedom (number of data points - number of free
parameters).
ptarg is the target probability (ptarg=0.9 correponds to 90%).
ptarg is the probability that a model fitted to data with the
giv... | 3877946fffd5cc5af4a3ccf048fb35205738ce55 | 81,178 |
def _all_units(pk):
"""
Total units per rack
"""
units = {}
units['all_units'] = Rack.objects.get(id=pk).rack_amount
return units | 703e074b45d0040a7889c55fabddcaa1cb51c9b4 | 81,179 |
import torch
def build_general_train_loader(
dataset, *, mapper, sampler=None, total_batch_size, aspect_ratio_grouping=True, num_workers=0
):
"""
Build a dataloader for object detection with some default features.
This interface is experimental.
Args:
dataset (list or torch.utils.data.Dat... | b905e0366e85efa45e8b27b694858fa64470cccc | 81,180 |
def partition(lst, fn):
"""Partition lst by predicate.
- lst: list of items
- fn: function that returns True or False
Returns new list: [a, b], where `a` are items that passed fn test,
and `b` are items that failed fn test.
>>> def is_even(num):
... return num % ... | 74b4a293bc13c06759a5334164d80f63651aefab | 81,181 |
import aiohttp
async def get_ncbi_blast_result(
config: Config, run_in_process: callable, rid: str
) -> dict:
"""
Retrieve the BLAST result with the given `rid` from NCBI.
:param config: the application configuration
:param run_in_process: the application processing running function
:param ri... | f05fc8f10d6ebdfa1dfbbbfbb1df5abea5346ab5 | 81,182 |
def percentile_n_moments(traces,proba,ind_full,algo,MaxFunEvals):
""" percentile_n_moments returns the approximate percentiles of a normal form x'*A*x (where x is a multivariate standard normal distribution and A is a real symmetric matrix) by conserving its first n moments. The normal form is approximated with a (g... | a9eb2dc5c3f9932b8327543d53264d67d45f5cd6 | 81,183 |
from datetime import datetime
def as_pydatetime(d, ts):
"""returns a datetime object.
d: date object
ts: tm_struct
"""
return datetime(year=d.year, month=d.month, day=d.day,
hour=ts.tm_hour, minute=ts.tm_min, second=ts.tm_sec) | 869f411f11583a14759ef089d175080c3479c685 | 81,184 |
def take_closest(myList, myNumber):
"""
Assumes myList is sorted. Returns closest value to myNumber.
If two numbers are equally close, return the smallest number.
"""
pos = bisect_left(myList, myNumber)
if pos == 0:
return myList[0]
if pos == len(myList):
return myList[-1]
... | 0497da57103bd7f8eef93931faceae6b7f2a61b1 | 81,185 |
def check_str_splitlines(string: str, keepends: bool) -> ResultComparison:
""" post: _ """
return compare_results(lambda s, *a: s.splitlines(*a), string, keepends) | 99d9fcd44c6ce0d2b41cef4cba0f54c4e3ef8979 | 81,186 |
from typing import Union
def fp_to_array(
fp: Union[np.ndarray, SparseBitVect, ExplicitBitVect, UIntSparseIntVect]
) -> np.ndarray:
"""Convert rdkit fingerprint to numpy array.
Note:
This implementation has shown to be faster than using `DataStructs.ConvertToNumpyArray`
by a factor of ~4.... | f0ed4dcd793d81f0db7a9031cb528647eee5ce22 | 81,187 |
import numpy
def _percentile_factory(perc):
"""Percentile function usable within a group.
Source: https://stackoverflow.com/a/54593214
"""
def percentile_(values):
return numpy.percentile(values, perc)
percentile_.__name__ = f"percentile_{perc}"
return percentile_ | 1f6b8ed9e7ffc41e33dbd4ee9178285327175fd6 | 81,189 |
import unicodedata
def charwidth(char):
""" The width of a single character. Ambiguous width is considered 1"""
cat = unicodedata.category(char)
if cat == "Mn":
return 0
eaw = unicodedata.east_asian_width(char)
if eaw == "Na" or eaw == "H":
return 1
if eaw == "F" or eaw == "W":
return 2
if eaw == "A":
... | 9e0a2bbcb70b23f7c3a41bb9ac938e3b140badf0 | 81,190 |
def prepare_hide(input_image_path, input_file_path):
"""Prepare files for reading and writing for hiding data."""
image = Image.open(input_image_path)
input_file = open(input_file_path, "rb")
return image, input_file | a4a286d018bbdea91fb4c9bee20a9eb6c60a91a5 | 81,193 |
def get_project_vendor_by_name(vendor_name):
"""
支持*语法的查询
:param vendor_name:
:return:
"""
if vendor_name.startswith('*'):
if vendor_name.endswith('*'):
pvs = ProjectVendors.objects.filter(name__icontains=vendor_name.strip('*'))
else:
pvs = ProjectVendors... | 601d6a7b9b2bdf417afd9448c09dab9a3a37d4a6 | 81,194 |
def mk_some(x, body):
"""Given a variable x and a term P possibly depending on x, return
the term SOME x. P.
"""
assert x.is_var(), "mk_some"
some_t = Const("Some", TFun(TFun(x.T, BoolType), x.T))
return some_t(Lambda(x, body)) | 0f204491eec8dc28c58835c6be8d541b0a79c8aa | 81,195 |
def get_bibtex(arxiv_id):
"""
Get a BibTeX entry for a given arXiv ID.
.. note::
Using awesome https://pypi.python.org/pypi/arxiv2bib/ module.
:param arxiv_id: The canonical arXiv id to get BibTeX from.
:returns: A BibTeX string or ``None``.
>>> get_bibtex('1506.06690')
"@article... | e4c9371f13b82176f4379b7bb8ea5c4f615d9f96 | 81,196 |
def make_rev_comp(s):
"""
Generates reverse comp sequences from an input sequence.
"""
return s[::-1].translate(s[::-1].maketrans("ACGT", "TGCA")) | 4cb65d3a2c2345b7189a01affd3f46f2de8ae06b | 81,197 |
def get_topic_list(bag_name):
""" Return a list of topics stored in this bag """
bag = rosbag.Bag(bag_name, 'r')
return bag.get_type_and_topic_info()[1].keys() | 2cb6c647b59281786f0b157280302f59ce2d6190 | 81,198 |
def client():
"""
Return a test client for the app.
Use TestClient as context manager to run startup and shutdown handlers.
Ref: https://www.starlette.io/events/#running-event-handlers-in-tests
def test__homepage(client):
with client:
response = client.get('/')
asse... | fec81051d85a3eed994117520bc11294b45c3897 | 81,199 |
def my_function(number_a, number_b):
""" test doctest in my_function """
return number_a * number_b | cb0938c07160712c7ad12d98645571e5f80a0cc1 | 81,200 |
def rbf_kernel(X, Y=None, gamma=None):
"""
Compute the rbf (gaussian) kernel between X and Y:
K(x, y) = exp(-gamma ||x-y||^2)
for each pair of rows x in X and y in Y.
Parameters
----------
X : ndarray of shape (n_samples_X, n_features)
Y : ndarray of shape (n_samples_Y, n_feature... | a13ec76866cfc3bd5d6c7082085d6f0e5bb0fd50 | 81,201 |
def get_recess(df, Q, freq='1D', inplace=False):
""" Select the data when values are decreasing compared to previous time step
:param df: DataFrame of hydro data
:param Q: DataFrame field with discharge or water level data
:param freq: Frequency of measurement of data; default is 1D
:param inplace:... | b9afc9eae0a24db48b29c08579bd0b3ce2104dcd | 81,202 |
from numpy import cumprod,empty_like,mgrid,float64,subtract,exp,flatnonzero,dot
from scipy.special import erfc
def _ewald_correction(x, alpha=2.0):
"""
calculate the Ewald-correction forces, i.e. the force due to all the images
of a point particle, EXCLUDING the nearest one.
Particle at 0,0,0, in the... | d82fc6f7f25ff86d776bd060e796a5e545b70013 | 81,203 |
from ..alignment_tools import translation_align_pts
from ..alignment_tools import fft3d_from2d
from ..spot_tools.matching import find_paired_centers, check_paired_centers
def align_beads(tar_cts, ref_cts,
tar_im=None, ref_im=None,
use_fft=True, fft_filt_size=0,
match_... | ef932b4eb63f83055422ee0df92306f27b18c858 | 81,204 |
def build_mn_net_graph(nets_routes, prior_constraints=None):
"""Build a graph the nodes of which represent multicast nets and the edges
of which represent constraints upon which nets may share keys.
Parameters
----------
nets_routes : {net: [RoutingTree, ...], ...}
Dictionary mapping multi-... | 2290d70b892faefbc05cacb4181c3c8f8febdbf9 | 81,205 |
def get_db():
"""Opens db connection if there isn't one"""
if not hasattr(g, 'sqlite_db'):
g.sqlite_db = connect_db()
return g.sqlite_db | 04c309afb2ba19f6156c12ff07e6c2169225b8f8 | 81,206 |
import json
def createMessage(message):
"""Create a JSON string to be returned as response to requests"""
return json.dumps({"message": message}) | 3a37a494e0876af8f176338c16e81b41a27993d5 | 81,207 |
def platform_module(name = platform_default()):
"""Return the imported module for the platform.
This looks for a module name that matches the specified argument.
If the name is unspecified, we fetch the appropriate default for
our execution environment.
"""
full_name = 'SCons.Platform.' + name
... | 51c27709cb6467c493904fe95d3119fecc77fb46 | 81,208 |
def index(request):
"""Main listing."""
forums = Forum.objects.all()
return render_to_response("django_simple_forum/list.html", {'forums': forums,
'user': request.user},
context_instance=RequestContext(request)) | f9d3dbc32d85b69ca65d40ab741223932bb08a00 | 81,210 |
def login_box_raw(request, return_url='/', auth_systems = None):
"""
a chunk of HTML that shows the various login options
"""
default_auth_system_obj = None
if DEFAULT_AUTH_SYSTEM:
default_auth_system_obj = AUTH_SYSTEMS[DEFAULT_AUTH_SYSTEM]
# make sure that auth_systems includes only available and enab... | 60df0f21f73c53ea3b559157bb99742206eddc0e | 81,211 |
import distro
def get_distribution():
"""Function to acquire current Distribution
This function will return the current distribution
if the user is running on a Linux machine.
"""
return distro.id() | 0598b4854f1b4b5ce8a6d55b2a017377405e7d7b | 81,212 |
def pack(fmt, *args): # known case of _struct.pack
"""
pack(fmt, v1, v2, ...) -> bytes
Return a bytes object containing the values v1, v2, ... packed according
to the format string fmt. See help(struct) for more on format strings.
"""
return b"" | 5abcc237f37802c39a392994ab3042f35619f275 | 81,213 |
from typing import Any
def read_cryptobots_with_last_action(
db: Session = Depends(deps.get_db),
skip: int = 0,
limit: int = 100,
current_user: models.User = Depends(deps.get_current_active_user),
) -> Any:
"""
Retrieve cryptobots.
"""
if crud.user.is_superuser(current_user):
c... | 67525aba02884c15703753dfb141ff531fdca192 | 81,215 |
def calc_flow(depth_src, pose_src, pose_tgt, K, depth_tgt, thresh=3e-3, standard_rep=False):
"""
project the points in source corrd to target corrd
:param standard_rep:
:param depth_src: depth image of source(m)
:param pose_src: pose matrix of soucre, [R|T], 3x4
:param depth_tgt: depth image of ... | 4e370a6bec1a2e59c49be7499e9ffc26d42106d0 | 81,216 |
import hashlib
import hmac
def rfc6979_k(msg, secret0, V=None):
"""
Generate a deterministic nonce according to
`rfc6979 spec <https://tools.ietf.org/html/rfc6979#section-3.2>`_.
Args:
msg (:class:`bytes`): 32-bytes sequence
secret0 (:class:`bytes`): private key
V (:class:`byt... | 82dfd81846cd46e719867aaf973b8d5651be1b54 | 81,217 |
def return_head(ser: pd.Series, num: int) -> pd.core.series.Series:
"""Return the first num elements of the given Series.
"""
return ser.head(num)
pass | 20830fe75543d41c83c0b030a4a901f88d61b853 | 81,218 |
from typing import FrozenSet
from typing import List
def subMISs(G: CausalDiagram, Y: str, Xs: FrozenSet[str], Ws: List[str]) -> FrozenSet[FrozenSet[str]]:
""" subroutine for MISs -- this creates a recursive call tree with n, n-1, n-2, ... widths """
out = frozenset({Xs})
for i, W_i in enumerate(Ws):
... | b0856c0fe5c3f98b7e57d014af7dc08d75f39666 | 81,220 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.