content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def drop_table(name, con):
"""
drop table from database
Parameters
----------
name : string, name of SQL table
con : sqlalchemy.engine.Engine or sqlite3.Connection
Returns
-------
True
Examples
--------
>>> import pandas as pd
>>> from sqlalchemy import create_engi... | c86ad4e71c24bdfaba924171a21e74096ab8c11e | 10,956 |
def class_info_interface(**class_name):
"""
Set Class_Name, Class_Index, and DNN Model
\nclass_name (kwargs) : Input Class Name with list type,
if want to set class number, add tuple parameters
like 'class_info_interface(class_name = [list], class_number = [list])'
\nclass_number : Default the n... | a9da1515192cf67bfe326ab90ff7c12a32106304 | 10,957 |
def uint8(value):
"""
Create an SPL ``uint8`` value.
Returns:
Expression: Expression representing the value.
"""
return streamsx.spl.op.Expression('UINT8', int(value)) | 7e8562b4ec82bbb932c92a9af4cfd06224b6596d | 10,958 |
import re
def print_table(log_results,
platform_width = 0,
build_failures_width = 0,
test_failures_width = 0,
successful_width = 0,
space_char = " ",
list_separator = DEFAULT_LIST_SEPARATOR):
"""Print out a table in the requested format (text o... | e12ada2d86f3dcecef6292b5c052094599abda4b | 10,959 |
def checkLengthSmaller(op, graph, frm, to):
"""
Confirm resulting video has less frames that source.
:param op:
:param graph:
:param frm:
:param to:
:return:
@type op: Operation
@type graph: ImageGraph
@type frm: str
@type to: str
... | a2101371e4f8af0ebaab1ece5d7cc31f4a277aca | 10,962 |
import logging
def enable_log(fmt='[%(asctime)s] [%(process)5s] %(levelname)s %(module)s %(name)s %(message)s',
enable_color=True, filename=None):
"""
Clears all log handlers, and adds color handler and/or file handlers
:param fmt: logging format string
:param enable_color: True to ena... | 3e018012e7cff555d86e93396485c9644dfb32ae | 10,963 |
def build_con_and_ds(dataset: str):
"""
Builds test connector and test datasource for testing with API key
Leave this function in if ever want to run tests without skipping
due to there being no Bearer tokens
How to use:
Replace build_ds function with this one in test_aircall file
Be sure t... | 7fa19e15e0a38c22f575d6509e3156a874b8ea60 | 10,964 |
def is_palindrome_recursive(text, left=None, right=None):
"""time complexity: O(1) because you are checking which conditional will run, which does not involve any loops
text = str
left = int
right = int"""
if len(text) == 0:
return True
given = get_letters(text)
if left is None and r... | d7bf4ab6e7f43d6418cde3485f94dc2d83e40180 | 10,966 |
import operator
import numpy
def flip(m, axis=None):
"""Reverses the order of elements in an array along the given axis.
The shape of the array is preserved, but the elements are reordered.
Parameters
----------
m : array_like
Input array.
axis : None or int or tuple of ints, optiona... | 495b75a548d94bc9dbc9827678b08282efb104d8 | 10,967 |
def radius_of_gyration(pos):
"""
Radius of gyration of a group of positions.
Does not account for periodic boundaries.
"""
com = np.mean(pos, axis = 0)
delta = pos - com
rgv = np.sqrt(np.sum(delta**2, axis = 0) / len(pos))
return np.linalg.norm(rgv) | a12450cf63768bf9a238bef11a3360ce49e3092f | 10,968 |
def get_metadata_for_list(commit_range, git_dir=None, count=None,
series=None, allow_overwrite=False):
"""Reads out patch series metadata from the commits
This does a 'git log' on the relevant commits and pulls out the tags we
are interested in.
Args:
commit_range (st... | 0134a836f28bf97e5196c63f80f5b07d372cc5d4 | 10,969 |
def side_seperator(lsep,rsep):
"""
To have a custom side lined formatter.
A side-lined formatter is:
`[DATE] SEP "L_SEP" EVENT "R_SEP" LOG`
`loggy.side_seperator(lsep="||",rsep="||") # Default vals`
"""
fmt['ls']=lsep
fmt['rs']=rsep
return fmt | 803519e93cef7342e9f951090823fc536f37839f | 10,970 |
from typing import OrderedDict
def make_sequential(layer_configs, input):
"""Makes sequential layers automatically.
Arguments:
layer_configs: An OrderedDict that contains the configurations of a
sequence of layers. The key is the layer_name while the value is a dict
contains hyper-param... | 662c8787115c7d6d3e499a89aa7e8c301b9e5e4b | 10,972 |
import random
def Pol_Dyn_ExploreWithNUTS(resultsList,totalSimDays=1000,numDaysRemain=1000,\
totalBudget=1000,numBudgetRemain=1000,policyParamList=[0],startDay=0):
"""
Grab intermediate and end node distribtuions via NUTS. Identify intermediate node
sample variances. Pick an in... | a96638a7f2816a42069cfa714822e728ee7e325f | 10,973 |
import numpy
def calc_cos_t(hb_ratio, d, theta_s_i, theta_v_i, relative_azimuth):
"""Calculate t cossine.
Args:
hb_ratio (int): h/b.
d (numpy array): d.
theta_s_i (numpy array): theta_s_i.
theta_v_i (numpy array): theta_v_i.
relative_azimuth (numpy array): relative_azi... | 5ac37f2aa8994b75bb0c71d9f54616ff041a5ff6 | 10,974 |
from typing import Callable
def guild_only() -> Callable:
"""A decorator that limits the usage of a slash command to guild contexts.
The command won't be able to be used in private message channels.
Example
---------
.. code-block:: python3
from discord import guild_only
@bot.s... | d8ca993dd0ea71791458edd3c3bcec0551262552 | 10,975 |
import re
def truncate(text, words=25):
"""Remove tags and truncate text to the specified number of words."""
return " ".join(re.sub("(?s)<.*?>", " ", text).split()[:words]) | 18d994a52dc5549aabb7cc8f33d5755be5392208 | 10,976 |
from datetime import datetime
def _run_query_create_log(query, client, destination_table=None):
"""
Runs BigQuery queryjob
:param query: Query to run as a string
:param client: BigQuery client object
:return: QueryJob object
"""
# Job config
job_config = bigquery.QueryJobConfig()
... | 265361c150f654bc8826cda096d85b4ae2911317 | 10,977 |
def read_disparity_gt(filename: str) -> np.ndarray:
"""
reads the disparity files used for training/testing.
:param filename: name of the file.
:return: data points.
"""
points = []
with open(filename, 'r') as file:
for line in file:
line = line.split(' ')
fra... | bad5ad6698d58e5173709cf866fb027367daa8b1 | 10,978 |
def purchase_index(request):
"""displays users purchase history"""
login_id = request.user.id
context = {'histories': Purchase_history.objects.all().filter(acc_id=login_id).order_by('-date')} # get users purchase history
return render(request, 'profile/histories/purchase_history.html', context) | d353e839ff08adfeebaa28a708d36df4d21a7ea8 | 10,979 |
import array
def solve_EEC(self):
"""Compute the parameters dict for the equivalent electrical circuit
cf "Advanced Electrical Drives, analysis, modeling, control"
Rik de doncker, Duco W.J. Pulle, Andre Veltman, Springer edition
<--- --->
-----R-----wsL... | ad862028447acd038e76ba95960b089985bffe9b | 10,980 |
def is_active(seat):
"""Return True if seat is empty. If occupied return False. """
active = seat_map.get(seat, ".")
return True if active == "#" else False | 098c4ccf9d4e9bbadb853d77a100eabd4e5142bf | 10,981 |
from typing import List
import tqdm
def calibrate_intensity_to_powder(peak_intensity: dict, powder_peak_intensity: dict,
powder_peak_label: List[str], image_numbers: List[int], powder_start: int = 1):
"""Calibrate peak intensity values to intensity measurements taken from a 'rand... | 8019eec6c63152ee25bacc9dcf8fa723407f8107 | 10,982 |
import json
def examine(path):
""" Look for forbidden tasks in a job-output.json file path """
data = json.load(open(path))
to_fix = False
for playbook in data:
if playbook['trusted']:
continue
for play in playbook['plays']:
for task in play['tasks']:
... | e441fc58bbfc4547bbdff451d6d06ba952e5a1ba | 10,983 |
def config_ask(default_message = True,
config_args = config_variables):
"""Formats user command line input for configuration details"""
if default_message:
print("Enter configuration parameters for the following variables... ")
config_dictionary = dict()
for v in config_ar... | 277d26ae67baf14ee6b16547bb72c029ab0bc610 | 10,985 |
def build_A(N):
"""
Build A based on the defined problem.
Args:
N -- (int) as defined above
Returns:
NumPy ndarray - A
"""
A = np.hstack( (np.eye(N), np.negative(np.eye(N))) )
A = np.vstack( (A, np.negative(np.hstack( (np.eye(N), np.eye(N)) ))) )
A = np.vstack( (A, np.h... | eecb541e44cc177e594f38d9a7c1930f2d4f0c40 | 10,987 |
def gms_change_est2(T_cont, T_pert, q_cont, precip, level, lat,
lev_sfc=925., gamma=1.):
"""
Gross moist stability change estimate.
Near surface MSE difference between ITCZ and local latitude, neglecting
geopotential term and applying a thermodynamic scaling for the moisture
ter... | 991721a2dae52269dec276fa384d568b1d58672f | 10,988 |
def solid_polygon_info_(base_sides, printed=False):
"""Get information about a solid polygon from its side count."""
# Example: A rectangular solid (Each base has four sides) is made up of
# 12 edges, 8 vertices, 6 faces, and 12 triangles.
edges = base_sides * 3
vertices = base_sides * 2
faces =... | a16bae9b82fd7a89332d5403359c2aa1eddf6cb4 | 10,989 |
def load_prism_theme():
"""Loads a PrismJS theme from settings."""
theme = get_theme()
if theme:
script = (
f"""<link href="{PRISM_PREFIX}{PRISM_VERSION}/themes/prism-{theme}"""
""".min.css" rel="stylesheet">"""
)
return mark_safe(script)
return "" | 565e9fdb7b201bf6c34b3b2d198aa18f22070145 | 10,991 |
def get_root_name(depth):
""" Returns the Rootname. """
return Alphabet.get_null_character() * depth | 1514bcd0ef9c6a2a4051772d8eeee34f3f7197a7 | 10,992 |
import hashlib
def md5(fname):
"""
Cacualte the MD5 hash of the file given as input.
Returns the hash value of the input file.
"""
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest() | 0c238810f1682f86e8a31982135c37017df4d6fd | 10,993 |
def date2num(date_axis, units, calendar):
"""
A wrapper from ``netCDF4.date2num`` able to handle "years since" and "months since" units.
If time units are not "years since" or "months since" calls usual ``netcdftime.date2num``.
:param numpy.array date_axis: The date axis following units
:param str ... | b435697098c58d1045f7e31eefb23cac201bfe0c | 10,994 |
import gettext
def _(txt):
""" Custom gettext translation function that uses the CurlyTx domain """
t = gettext.dgettext("CurlyTx", txt)
if t == txt:
#print "[CurlyTx] fallback to default translation for", txt
t = gettext.gettext(txt)
return t | 839c36184eabde641a40d7b7ad55d4695574dafb | 10,995 |
import html
def output_node(ctx, difference, path, indentstr, indentnum):
"""Returns a tuple (parent, continuation) where
- parent is a PartialString representing the body of the node, including
its comments, visuals, unified_diff and headers for its children - but
not the bodies of the children
... | dbe4c5f806457d4308954fb9e13bf01419b4e1a1 | 10,996 |
def split_tree_into_feature_groups(tree: TreeObsForRailEnv.Node, max_tree_depth: int) -> (
np.ndarray, np.ndarray, np.ndarray):
"""
This function splits the tree into three difference arrays of values
"""
data, distance, agent_data = _split_node_into_feature_groups(tree)
for direction in TreeObsFor... | 87352b0d500d178b32d4697ae49736133c7fd6a1 | 10,997 |
def _generate_training_batch(ground_truth_data, representation_function,
batch_size, num_points, random_state):
"""Sample a set of training samples based on a batch of ground-truth data.
Args:
ground_truth_data: GroundTruthData to be sampled from.
representation_function: Functi... | 944ed5845385089063f0e1558a9a9aedb4aa6d26 | 10,998 |
def get_mnist_loaders(data_dir, b_sz, shuffle=True):
"""Helper function that deserializes MNIST data
and returns the relevant data loaders.
params:
data_dir: string - root directory where the data will be saved
b_sz: integer - the batch size
shuffle: boolean - whether... | 7149dbe78ceb321c0afea52c20ae927ce154a8f6 | 10,999 |
def atomic_coordinates_as_json(pk):
"""Get atomic coordinates from database."""
subset = models.Subset.objects.get(pk=pk)
vectors = models.NumericalValue.objects.filter(
datapoint__subset=subset).filter(
datapoint__symbols__isnull=True).order_by(
'datapoint_id', 'counter'... | 515854e789a15e845b0dbcd754e17bedfc0bcf69 | 11,000 |
def additional_bases():
""""Manually added bases that cannot be retrieved from the REST API"""
return [
{
"facility_name": "Koltyr Northern Warpgate",
"facility_id": 400014,
"facility_type_id": 7,
"facility_type": "Warpgate"
},
{
... | e2a5ad97ca1b424466f5ebe340466eaf9f627e7e | 11,001 |
def get_all_label_values(dataset_info):
"""Retrieves possible values for modeled labels from a `Seq2LabelDatasetInfo`.
Args:
dataset_info: a `Seq2LabelDatasetInfo` message.
Returns:
A dictionary mapping each label name to a tuple of its permissible values.
"""
return {
label_info.name: tuple(l... | 929db286b3f7ee8917618e9f46feabdff630d3b2 | 11,002 |
def load_input(file: str) -> ArrayLike:
"""Load the puzzle input and duplicate 5 times in each direction,
adding 1 to the array for each copy.
"""
input = puzzle_1.load_input(file)
input_1x5 = np.copy(input)
for _ in range(4):
input = np.clip(np.mod(input + 1, 10), a_min=1, a_max=Non... | 91b2cd7854a793ebbbfee2400eddb22304fc18bd | 11,003 |
def _get_xvals(end, dx):
"""Returns a integer numpy array of x-values incrementing by "dx"
and ending with "end".
Args:
end (int)
dx (int)
"""
arange = np.arange(0, end-1+dx, dx, dtype=int)
xvals = arange[1:]
return xvals | 24a4d7b7c470abb881700a1775008d16c35c1fc3 | 11,004 |
import torch
def top_filtering(logits, top_k=0, top_p=0.0, filter_value=-float('Inf')):
""" Filter a distribution of logits using top-k, top-p (nucleus) and/or threshold filtering
Args:
logits: logits distribution shape (vocabulary size)
top_k: <=0: no filtering, >0: keep only top ... | 5cbbd9959a80e72364f098fe031e5e3c78485826 | 11,005 |
def get_reference_shift( self, seqID ):
"""Get a ``reference_shift`` attached to a particular ``seqID``.
If none was provided, it will return **1** as default.
:param str seqID: |seqID_param|.
:type shift: Union[:class:`int`, :class:`list`]
:raises:
:TypeError: |indf_error|.
.. rubr... | 4a8f9fe683c9cf0085754ca2ebb9132bbae427ea | 11,006 |
def load_and_resolve_feature_metadata(eval_saved_model_path: Text,
graph: tf.Graph):
"""Get feature data (feature columns, feature) from EvalSavedModel metadata.
Like load_feature_metadata, but additionally resolves the Tensors in the given
graph.
Args:
eval_saved_mod... | 3377d66c962ccccab7b62abf563f88032a8a7b14 | 11,008 |
def greater_than_or_eq(quant1, quant2):
"""Binary function to call the operator"""
return quant1 >= quant2 | 920c28da125b567bc32a149aec6aaade3645ef87 | 11,009 |
def pr_define_role(pe_id,
role=None,
role_type=None,
entity_type=None,
sub_type=None):
"""
Back-end method to define a new affiliates-role for a person entity
@param pe_id: the person entity ID
@param role: the role... | 3f09ac9eca47347b51069a20b7b08b2192e2d452 | 11,010 |
def inherently_superior(df):
"""
Find rows in a dataframe with all values 'inherently superior',
meaning that all values for certain metrics are as high or higher
then for all other rows.
Parameters
----------
df : DataFrame
Pandas dataframe containing the columns to be compared... | 02dd6db624efd4f1daa4c0ef4f126c6c60c0376e | 11,011 |
def LineColourArray():
"""Line colour options array"""
Colour = [
'Black',
'dimgrey',
'darkgrey',
'silver',
'lightgrey',
'maroon',
'darkred',
'firebrick',
'red',
'orangered',
'darkorange',
'orange',
... | 94f91d17c6e539983ab38ca7fdadd211e6268bfb | 11,012 |
from typing import Any
def parse_ccu_sys_var(data: dict[str, Any]) -> tuple[str, Any]:
"""Helper to parse type of system variables of CCU."""
# pylint: disable=no-else-return
if data[ATTR_TYPE] == ATTR_HM_LOGIC:
return data[ATTR_NAME], data[ATTR_VALUE] == "true"
if data[ATTR_TYPE] == ATTR_HM_A... | 8b77dbbaa93739457a2e92aad79ac5b6bd3a6af0 | 11,014 |
def one_time_log_fixture(request, workspace) -> Single_Use_Log:
"""
Pytest Fixture for setting up a single use log file
At test conclusion, runs the cleanup to delete the single use text file
:return: Single_Use_Log class
"""
log_class = Single_Use_Log(workspace)
request.addfinalizer(log_cl... | 73332892ece76ee90c15d84294b70d935e8a2f4c | 11,015 |
import json
def details(request, path):
"""
Returns detailed information on the entity at path.
:param path: Path to the entity (namespaceName/.../.../.../)
:return: JSON Struct: {property1: value, property2: value, ...}
"""
item = CACHE.get(ENTITIES_DETAIL_CACHE_KEY)
# ENTITIES_DETAIL : {"namespaceNam... | b460dc76f18f35b48509a1b2d8daa104bc89fbb5 | 11,016 |
def ca_get_container_capability_set(slot, h_container):
"""
Get the container capabilities of the given slot.
:param int slot: target slot number
:param int h_container: target container handle
:return: result code, {id: val} dict of capabilities (None if command failed)
"""
slot_id = CK_SL... | cf97db8f201d0c5fce12902b92abdc3a819ac394 | 11,017 |
def load_pyfunc(model_file):
"""
Loads a Keras model as a PyFunc from the passed-in persisted Keras model file.
:param model_file: Path to Keras model file.
:return: PyFunc model.
"""
return _KerasModelWrapper(_load_model(model_file)) | eb21f47a55f35bf3707ba7c5cb56e72948d24866 | 11,018 |
def business_days(start, stop):
"""
Return business days between two datetimes (inclusive).
"""
return dt_business_days(start.date(), stop.date()) | 1fa8c38e6cceca448bc988cd0c1eb24a27508a78 | 11,019 |
def empty_nzb_document():
""" Creates xmldoc XML document for a NZB file. """
# http://stackoverflow.com/questions/1980380/how-to-render-a-doctype-with-pythons-xml-dom-minidom
imp = minidom.getDOMImplementation()
dt = imp.createDocumentType("nzb", "-//newzBin//DTD NZB 1.1//EN",
"http://... | 7cd8aa73f201b4f432aa6adaed18d133ec08fa48 | 11,020 |
def get_output_directory(create_statistics=None, undersample=None, oversample=None):
"""
Determines the output directory given the balance of the dataset as well as columns.
Parameters
----------
create_statistics: bool
Whether the std, min and max columns have been created
undersample: ... | c10859e1eba4afb61d967e56be8a8206f5202618 | 11,021 |
def removePrefixes(word, prefixes):
"""
Attempts to remove the given prefixes from the given word.
Args:
word (string): Word to remove prefixes from.
prefixes (collections.Iterable or string): Prefixes to remove from given word.
Returns:
(string): Word with prefixes removed.
... | 6932e5605b11eee004a350c7f9be831d8bb7ca9d | 11,022 |
def isSol(res):
"""
Check if the string is of the type ai bj ck
"""
if not res or res[0] != 'a' or res[-1] != 'c':
return False
l = 0
r = len(res)-1
while res[l] == "a":
l+=1
while res[r] == "c":
r-=1
if r-l+1 <= 0:
return False
... | 14030e52a588dc13029602e81a5f2068707bca17 | 11,023 |
import pandas
def _h1_to_dataframe(h1: Histogram1D) -> pandas.DataFrame:
"""Convert histogram to pandas DataFrame."""
return pandas.DataFrame(
{"frequency": h1.frequencies, "error": h1.errors},
index=binning_to_index(h1.binning, name=h1.name),
) | 28aa8cc36abd21a17e0a30f4bde2bb996753864b | 11,024 |
def wgt_area_sum(data, lat_wgt, lon_wgt):
"""wgt_area_sum() performas weighted area addition over a geographical area.
data: data of which last 2 dimensions are lat and lon. Strictly needs to be a masked array
lat_wgt: weights over latitude of area (usually cos(lat * pi/180))
lon_wgt: weights over long... | 725f7f199e634cf56afb846ebff2a0917a92c685 | 11,025 |
def load(filename):
"""Load the labels and scores for Hits at K evaluation.
Loads labels and model predictions from files of the format:
Query \t Example \t Label \t Score
:param filename: Filename to load.
:return: list_of_list_of_labels, list_of_list_of_scores
"""
result_labels = []
re... | 8d9570d794ebf09eb393342f926a5536dd0c1a75 | 11,027 |
def expanding_sum(a, axis = 0, data = None, state = None):
"""
equivalent to pandas a.expanding().sum().
- works with np.arrays
- handles nan without forward filling.
- supports state parameters
:Parameters:
------------
a : array, pd.Series, pd.DataFrame or list/dict of these
... | ec3fb41784f7ce5ef268ec8e7d8fe8e65f222157 | 11,028 |
def accuracy(output, target, top_k=(1,)):
"""Calculate classification accuracy between output and target.
:param output: output of classification network
:type output: pytorch tensor
:param target: ground truth from dataset
:type target: pytorch tensor
:param top_k: top k of metric, k is an int... | 68b7c48e5bd832a637e7a06353c48ffa09b449cd | 11,029 |
def sum_digits(number):
"""
Write a function named sum_digits which takes a number as input and
returns the sum of the absolute value of each of the number's decimal digits.
"""
return sum(int(n) for n in str(number) if n.isdigit()) | b6d8083a78d67a268316716174723f47d84b2287 | 11,032 |
import numpy
def label(input, structure=None, output=None):
"""Labels features in an array.
Args:
input (cupy.ndarray): The input array.
structure (array_like or None): A structuring element that defines
feature connections. ```structure``` must be centersymmetric. If
... | fe3e4b7ee30f7dc1ae0541133f7db3d02c7d3157 | 11,033 |
import functools
def get_experiment_fn(nnObj,data_dir, num_gpus,variable_strategy,use_distortion_for_training=True):
"""Returns an Experiment function.
Experiments perform training on several workers in parallel,
in other words experiments know how to invoke train and eval in a sensible
fashion for distribut... | 07ddb4ebac493826127464f76fd79ea17e7bf474 | 11,034 |
def calc_psnr(tar_img, ref_img):
""" Compute the peak signal to noise ratio (PSNR) for an image.
Parameters
----------
tar_img : sitk
Test image.
ref_img : sitk
Ground-truth image.
Returns
-------
psnr : float
The PSNR metric.
References
----------
..... | 61097170fb439b85583cd8aac8002c70d02c094b | 11,035 |
from typing import Callable
from typing import Dict
from typing import Any
import functools
def glacier_wrap(
f: Callable[..., None],
enum_map: Dict[str, Dict[str, Any]],
) -> Callable[..., None]:
"""
Return the new function which is click-compatible
(has no enum signature arguments) from the arbi... | 01f3a90179bb0dba29ffb0b2fa9d91be15e0ee7e | 11,037 |
def _cluster_spec_to_device_list(cluster_spec, num_gpus_per_worker):
"""Returns a device list given a cluster spec."""
cluster_spec = multi_worker_util.normalize_cluster_spec(cluster_spec)
devices = []
for task_type in ("chief", "worker"):
for task_id in range(len(cluster_spec.as_dict().get(task_type, [])))... | 3032a28f80dbed1fd870e4fc2ea06d724fc529ce | 11,038 |
def group_by_time(df, col, by='day', fun='max', args=(), kwargs={}, index='categories'):
""" See <https://pandas.pydata.org/pandas-docs/stable/api.html#groupby>_ for the set of `fun` parameters
available. Examples are: 'count', 'max', 'min', 'median', etc
.. Tip:: Since Access inherits from Tim... | 6695d285b52757ee7dfd32ad5943aa433504322f | 11,039 |
def param_rischDE(fa, fd, G, DE):
"""
Solve a Parametric Risch Differential Equation: Dy + f*y == Sum(ci*Gi, (i, 1, m)).
Given a derivation D in k(t), f in k(t), and G
= [G1, ..., Gm] in k(t)^m, return h = [h1, ..., hr] in k(t)^r and
a matrix A with m + r columns and entries in Const(k) such that
... | afb910a9590195fa637be9c64382419c1c79a885 | 11,041 |
import torch
def huber_loss(x, delta=1.):
""" Standard Huber loss of parameter delta
https://en.wikipedia.org/wiki/Huber_loss
returns 0.5 * x^2 if |a| <= \delta
\delta * (|a| - 0.5 * \delta) o.w.
"""
if torch.abs(x) <= delta:
return 0.5 * (x ** 2)
else:
return del... | b3493eb9d4e38fa36f92db80dc52a47c32caf3c9 | 11,043 |
def licenses_mapper(license, licenses, package): # NOQA
"""
Update package licensing and return package based on the `license` and
`licenses` values found in a package.
Licensing data structure has evolved over time and is a tad messy.
https://docs.npmjs.com/files/package.json#license
license(... | 5568c323b342cc09d966ddef3455381abdca1ccc | 11,044 |
def send_command(target, data):
"""sends a nudge api command"""
url = urljoin(settings.NUDGE_REMOTE_ADDRESS, target)
req = urllib2.Request(url, urllib.urlencode(data))
try:
return urllib2.urlopen(req)
except urllib2.HTTPError, e:
raise CommandException(
'An exception occu... | fc6967f84568b755db7f132f5fc511ef9687369f | 11,045 |
def logistic_log_partial_ij(x_i, y_i, beta, j):
"""i is index of point and j is index of derivative"""
return (y_i - logistic(dot(x_i, beta))) * x_i[j] | a24f704bc3178c6f2d8b37ad075f1beea3666964 | 11,046 |
def expected_win(theirs, mine):
"""Compute the expected win rate of my strategy given theirs"""
assert abs(theirs.r + theirs.p + theirs.s - 1) < 0.001
assert abs(mine.r + mine.p + mine.s - 1) < 0.001
wins = theirs.r * mine.p + theirs.p * mine.s + theirs.s * mine.r
losses = theirs.r * mine.s + theirs... | 92de2010287e0c027cb18c3dd01d95353e4653c4 | 11,047 |
def get_first_where(data, compare):
"""
Gets first dictionary in list that fit to compare-dictionary.
:param data: List with dictionarys
:param compare: Dictionary with keys for comparison {'key';'expected value'}
:return: list with dictionarys that fit to compare
"""
l = get_all_where(data, compare)
i... | fc961d7154aa265efd101a658f668ad2025c121f | 11,048 |
import numpy
def parse_megam_weights(s, features_count, explicit=True):
"""
Given the stdout output generated by ``megam`` when training a
model, return a ``numpy`` array containing the corresponding weight
vector. This function does not currently handle bias features.
"""
if numpy is None:
... | db172935fe7af892b420d515391565ccc2b44c55 | 11,049 |
from typing import Counter
def project_statistics(contributions):
"""Returns a dictionary containing statistics about all projects."""
projects = {}
for contribution in contributions:
# Don't count unreviewed contributions
if contribution["status"] == "unreviewed":
continue
... | 91c27b504fc974b26f4e76b8a3f78e3665a21efa | 11,050 |
def exportSDFVisual(visualobj, linkobj, visualdata, indentation, modelname):
"""Simple wrapper for visual data of links.
The visual object is required to determine the position (pose) of the
object.
If relative poses are used the data found in visualdata (key pose) is used.
Otherwise the pose of the... | f556a1eb1cef42adfde28c481a3443f149219518 | 11,051 |
import resource
def register_module():
"""Callback for module registration. Sets up URL routes."""
global custom_module # pylint: disable=global-statement
permissions = [
roles.Permission(EDIT_STUDENT_GROUPS_PERMISSION,
messages.EDIT_STUDENT_GROUPS_PERMISSION_DESCRIPTIO... | 82e8d57c2b0f73ae21b460da61ce047b4a25ebe3 | 11,052 |
import scipy
def KL_distance(image1, image2):
"""
Given two images, calculate the KL divergence between the two
2d array is not supported, so we have to flatten the array and compare each pixel in the image1 to the corresponding pixel in the image2.
"""
return scipy.stats.entropy(image1.ravel(), ... | 6419c2f6456365e027fc7eff6f4b171e5eb4fc5f | 11,055 |
def stop_all_bots():
"""
This function address RestAPI call to stop polling for all bots which
have ever started polling.
:return:
"""
bots_stopped = procedures.stop_all() # Stop all bots.
botapi_logger.info('Successfully stopped {count} bots for polling in '
's... | 7e0bdaa0ae631e631cfbc56966311e59fc510d52 | 11,056 |
def load_word_embedding_dict(embedding, embedding_path, normalize_digits=True):
"""
load word embeddings from file
:param embedding:
:param embedding_path:
:return: embedding dict, embedding dimention, caseless
"""
print "loading embedding: %s from %s" % (embedding, embedding_path)
if em... | 98cda8061aa49c708bc6986a6ab036e8941967f6 | 11,057 |
def random_exponential(shape=(40,60), a0=100, dtype=float) :
"""Returns numpy array of requested shape and type filled with exponential distribution for width a0.
"""
a = a0*np.random.standard_exponential(size=shape)
return a.astype(dtype) | 29d3e438145d4495191868c956942b9626b76918 | 11,059 |
import json
def get_mpi_components_from_files(fileList, threads=False):
"""
Given a list of files to read input data from, gets a percentage of time
spent in MPI, and a breakdown of that time in MPI
"""
percentDict = dict()
timeDict = dict()
for filename in fileList:
filename ... | 34549198676b823cf9e02ec927cb1e5fc30de2b8 | 11,060 |
import urllib
def get_character_url(name):
"""Gets a character's tibia.com URL"""
return url_character + urllib.parse.quote(name.encode('iso-8859-1')) | 62dc27528b7b9b303367551b8cba0a02204d0eb6 | 11,061 |
def parse_input(lines):
"""Parse the input document, which contains validity rules for the various
ticket fields, a representation of my ticket, and representations of a
number of other observed tickets.
Return a tuple of (rules, ticket, nearby_tickets)
"""
section = parse_sections(lines)
ru... | cccf2a9b47768428b2004caab1b3cab15a369a68 | 11,062 |
from dateutil import tz
def _cnv_prioritize(data):
"""Perform confidence interval based prioritization for CNVs.
"""
supported = {"cnvkit": {"inputs": ["call_file", "segmetrics"], "fn": _cnvkit_prioritize}}
pcall = None
priority_files = None
for call in data.get("sv", []):
if call["var... | a35c8b1d1fb7f38fc23439bbe5b9778062fc6aa7 | 11,063 |
from typing import Optional
def maximum(
left_node: NodeInput,
right_node: NodeInput,
auto_broadcast: str = "NUMPY",
name: Optional[str] = None,
) -> Node:
"""Return node which applies the maximum operation to input nodes elementwise."""
return _get_node_factory_opset1().create(
"Maxim... | 9ca2ac093059a9c7c2a1b310635c551d1982b1bb | 11,064 |
def create_template_error():
"""
Создает заготовку для генерации ошибок
"""
return {'response': False} | f15c27cc980cf1bda6b82353d01bbe7871fdbff1 | 11,065 |
def e_qest(model, m):
"""
Calculation of photocounting statistics estimation from
photon-number statistics estimation
Parameters
----------
model : InvPBaseModel
m : int
Photocount number.
"""
return quicksum(model.T[m, n] * model.PEST[n]
for n in model.... | b4b5f9fb4ba1c142af3d91d170fdb90ae960dd0e | 11,067 |
def load_input(fname):
"""Read in the data, return as a list."""
data = [""]
with open(fname, "r") as f:
for line in f.readlines():
if line.strip("\n"):
data[-1] += line.strip("\n") + " "
else:
data[-1] = data[-1].strip(" ")
dat... | f83021dd416e3a959996a16bb8d0a0e7352a471f | 11,068 |
import json
def parse_repo_layout_from_json(file_):
"""Parse the repo layout from a JSON file.
Args:
file_ (File): The source file.
Returns:
RepoLayout
Raises:
InvalidConfigFileError: The configuration file is invalid.
"""
def encode_dict(data):
new_data = {... | db1b7843c26ecc6796233e0cc193b41336fecf2d | 11,069 |
def SizeArray(input_matrix):
"""
Return the size of an array
"""
nrows=input_matrix.shape[0]
ncolumns=input_matrix.shape[1]
return nrows,ncolumns | 3ac45e126c1fea5a70d9d7b35e967896c5d3be0b | 11,070 |
def show_fun_elem_state_machine(fun_elem_str, xml_state_list, xml_transition_list,
xml_fun_elem_list):
"""Creates lists with desired objects for <functional_element> state, send them to
plantuml_adapter.py then returns url_diagram"""
new_fun_elem_list = set()
main_fun_el... | 3d8b1426e791bcc40c9850723da9bf350bea361f | 11,071 |
def get_bank_account_rows(*args, **kwargs):
"""
获取列表
:param args:
:param kwargs:
:return:
"""
return db_instance.get_rows(BankAccount, *args, **kwargs) | 0599b2bbae3b7bb044789db6c18f47604c3c9171 | 11,072 |
def pybo_mod(tokens, tag_codes=[]):
"""extract text/pos tuples from Token objects"""
txt_tags = []
for token in tokens:
tags = []
tags.append(token.text)
# Select and order the tags
for tag_code in tag_codes:
tags.append(get_tag(token, tag_code))
txt_tags.... | e96bb6a4774a0e983f2288536921e98207aeaa4b | 11,074 |
def acf(
da: xr.DataArray, *, lag: int = 1, group: str | Grouper = "time.season"
) -> xr.DataArray:
"""Autocorrelation function.
Autocorrelation with a lag over a time resolution and averaged over all years.
Parameters
----------
da : xr.DataArray
Variable on which to calculate the diagn... | 630eb27574edb40f363f41656a23801f11cefb1c | 11,075 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.