content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def proxyobj(bus, path, interface):
""" commodity to apply an interface to a proxy object """
obj = bus.get_object('org.bluez', path)
return dbus.Interface(obj, interface) | c715ed2cca3672cf019eb61df719052616a70dc6 | 3,622,800 |
def get_create_idea():
"""
Renvoie la vue pour créer une nouvelle Idée
:return:
"""
user = User.query.filter_by(id=session['uid']).first()
return render_template(
'create_idea.html',
title='Proposez une nouvelle idée de projet',
data={'user': user}
) | 7b8c0172ff820589f0f71cc251d7b6de6866e85f | 3,622,801 |
def scale_size(range=None, name=None, breaks=None, labels=None, limits=None, na_value=None, guide=None, trans=None,
format=None):
"""
Scale for size.
Parameters
----------
range : list
The range of the mapped aesthetics result.
name : str
The name of the scale - u... | 9dab561b80c960bd0b12f765cbd68366dffcbd22 | 3,622,802 |
def conv2d(input,
num_filters,
filter_size,
stride=1,
padding=0,
dilation=1,
groups=None,
param_attr=None,
bias_attr=None,
use_cudnn=True,
act=None,
name=None,
data_format="NCHW"):
"""... | 4b1ab3485258dda44dc75d0bb92325676847ea12 | 3,622,803 |
def modifies(repo, subset, x):
"""``modifies(pattern)``
Changesets modifying files matched by pattern.
The pattern without explicit kind like ``glob:`` is expected to be
relative to the current directory and match against a file or a
directory.
"""
# i18n: "modifies" is a keyword
pat = ... | 9e70f258dbbb22ef2ebdd9ba30176f2421005a92 | 3,622,804 |
def normalize_volume_and_number(volume, number):
"""
Padroniza os valores de `volume` e `number`
Args:
volume (None or str): volume se aplicável
number (None or str): número se aplicável
Notas:
- se `number` é igual a `ahead`, equivale a `None`
- se `00`, equivale a ... | 1ec42912b942f6c1b7e22d2e64c4d842af100877 | 3,622,805 |
def create_intersection_jo_losses(pos_3d, obj_2d_polys,
joints_active,
pos_3d_transform_indices,
obj_2d_poly_transform_indices,
independent, um, d_padding,
... | e938ecf231f8c5ff5b4fa91002e9c99b949d13f6 | 3,622,806 |
def multi_scale_like_flow(image, flow_ms):
"""
:param image: [batch, height, width, 3]
:param flow_ms: list of [batch, numsrc, height/scale, width/scale, 1]
:return: image_ms: list of [batch, height/scale, width/scale, 3]
"""
image_ms = []
for i, flow in enumerate(flow_ms):
batch, nu... | f8ced57511fd777c3d3fe3620e16b94bea059743 | 3,622,807 |
def pd_xlabels():
"""Create a DataFrame which uses the column labels as x-data."""
df = pd.DataFrame({"B": np.random.randint(0, 100, size=100)})
return df | 924ba89f50f8bad8d4106164067f4af7f733f6f6 | 3,622,808 |
def rotate(X,a=0):
"""Rotate around the origin a 2d matrix X by angle a in degrees"""
a = np.deg2rad(a) # Convert degrees to radians
return np.dot(X, [[np.cos(a), np.sin(a)], [-np.sin(a), np.cos(a)]]) | 272add751ff36272bfb5721833d6db6fa65fbe0f | 3,622,809 |
def __prepare_postcoder(directory: PathLike):
"""
Create an instance of PostCoder
Parameters
----------
directory: PathLike
The postalcode file directory.
If the file (ken_all.zip) doesn't exist, download it.
"""
postcoder = PostCoder.get_instance(directory)
return postc... | 0f9813343731b3a579ef643b3c40e5135b1d2398 | 3,622,810 |
def CalculateTransitionSolventAccessibility(ProteinSequence):
"""
###############################################################################################
A method used for calculating Transition descriptors based on SolventAccessibility
of AADs.
Usage:
result=CalculateTransitionSolve... | 448dd28b407b33d1d37eb8d0bbce40420bfb99ba | 3,622,811 |
def sSEZtoECEF(station_ecef:AbstractArray, sez:AbstractArray, conversion:str="geodetic") -> np.ndarray:
"""Compute the coordinates of an object in the topocentric frame of an
Earth-fixed frame
Args:
station_ecef (np.ndarray): Earth-fixed Cartesian station coordinates
sez (np.ndarray): SEZ c... | 17c3f7c0c421b017ca85529ff278651bc7065093 | 3,622,812 |
from onnx.helper import make_node
def convert_max(node, **kwargs):
"""Map MXNet's max operator attributes to onnx's ReduceMax operator
and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
mx_axis = str(attrs.get("axis", 'None'))
axes = convert_string_to_list(mx... | cc1a809d02cfe92d88c7972b244007d878da7627 | 3,622,813 |
import torch
def pairwise_cluster_raw(mat1=([0]), mat2=([0]), mat1T=([0]), mat2T=([0]), gpu=False): # the matrices (mat1 and mat2) are used to calculate the clusters and the lsts will be used to store the members of clusters
""" Takes a pair of matrices mat1 and mat2 as arguments. Both of the matrices shoul... | b1a1733156addfa390de640fba9d702dd4545cb8 | 3,622,814 |
import os
import urlparse
from IPython.display import clear_output
import sys
import boto
import requests
def cache_url(url):
"""Load a url to a local file, or return the file path if it already exists
This function will download the given URL to the current directory, with a file name of the
last path e... | bdc74a3e929b37bfab1bf5213f14fb02976cc9cc | 3,622,815 |
def tanimoto_sml(queryism, targetism):
"""
Returns the Tanimoto similarity between the two molecules in SMILES format.
"""
# no Unicode here
querymol = MolFromSmiles(str(queryism))
targetmol = MolFromSmiles(str(targetism))
if querymol and targetmol:
queryfp = RDKFingerprint(querymol... | c44ecbc5604d2cea0fa1aa0b000e571b7705356f | 3,622,816 |
from typing import List
from typing import Tuple
def style_close(style: List[Tuple[str, str]]) -> str:
"""
HTML tags to close a style.
>>> style = [
... ("font", 'color="red" size="32"'),
... ("b", ""),
... ("i", ""),
... ("u", ""),
... ]
>>> style_close(style)
... | 2043803e50230f139a6a60599b40c53461ed6ed8 | 3,622,817 |
from pathlib import Path
import os
def testrun(args):
"""testrun subcommand.
Runs the command with the tracer using a temporary sqlite3 database, then
reads it and dumps it out.
Not really useful, except for debugging.
"""
fd, database = Path.tempfile(prefix='reprozip_', suffix='.sqlite3')
... | 7add64eaab6c24c745425a6c7d8d5d006d925aaa | 3,622,818 |
def get_theta_hat_bw_imd_cm1(theta_star_bw_std):
"""制御モードcmの中間条件におけるM1スタンダードモード沸き上げ温度(℃)(27b-1)
Args:
theta_star_bw_std(float): 標準条件の沸き上げ温度(
Returns:
float: 制御モードcmの中間条件におけるM1スタンダードモード沸き上げ温度(
"""
# 制御モードがファーストモードの場合
return theta_star_bw_std | caf43cc7c9e17417e3b0096fe89e4a02d41dc0e6 | 3,622,819 |
import os
import tarfile
import time
def tar_directory(root, prefix, strip_times=False, tmpfile=None):
"""
Walk the directory specified by root, and tar files with new path prefix
"""
root = os.path.abspath(root)
tmpfile = tmpfile or utils.get_tmpfile()
tar = tarfile.open(dest, "w:gz")
for... | d0e09dff927ed372dc4c21bd1f2082b29dc3390d | 3,622,820 |
def crossGeneAvg(genea, geneb):
"""
A crossover startegy where the two genes are averaged, with no cut point
12347 => 33334
54321 33334
Parameters
----------
genea : 1D numpy array
An 1D numpy array of genes.
geneb : 1D numpy array
An 1D numpy... | 83c3307c440da1e42c47d6b924cba7f975dd4d40 | 3,622,821 |
def _oauth_url():
"""Creates the URL handling OAuth redirects."""
return url_for('oauth', _external=True) | 7adda3aa7edfe1bbad286824d1dabb5cbaddc2ac | 3,622,822 |
def join_as_guest():
"""
Generates Valid Token for Guest Users
"""
_uuid = security.create_guest_uuid()
access_token, expires = security.create_access_token(
subject=_uuid,
is_guest_user=True,
expires_delta=timedelta(hours=settings.ACCESS_GUEST_TOKEN_EXPIRE_HOURS)
)
r... | 2f9f783ce234feb8da1f3ab15fee1052258850fc | 3,622,823 |
import xml
def getServosFromURDF():
""" Get servo parameters from URDF. """
try:
description = rospy.get_param("robot_description")
robot = xml.dom.minidom.parseString(description).getElementsByTagName('robot')[0]
joints = {}
# Find all non-fixed joints
for child in rob... | 61bd443911ded11a47f08148784ebe8b158101ba | 3,622,824 |
def test_check_logs(monkeypatch):
"""
.
"""
log1 = Log(
revision1="abc123", message="foo", status="log", utc_unix_timestamp=1611608732
)
log2 = Log(
revision1="abc123",
message="bar",
status="success",
utc_unix_timestamp=1611608732,
)
db_file = ge... | 936cd9c2c0e76c9c4c99d6ebde3ad2b7ea6bc38e | 3,622,825 |
import os
def convert_checkpoint(checkpoint_file, output_dir):
"""Converts a given checkpoint into a new one.
The function does the following steps:
1. loads an existing checkpoint.
2. computes the new variable values from the variables in the checkpoint.
3. saves the new checkpoint in output_dir.
Args:... | 3053241fe01cccbf6cc50ca3176dc34b54988118 | 3,622,826 |
from typing import Sequence
from typing import Literal
from typing import Any
def spacegroup_sunburst(
spacegroups: Sequence[int] | pd.DataFrame,
sgp_col: str = None,
show_values: Literal["value", "percent", False] = False,
**kwargs: Any,
) -> Figure:
"""Generate a sunburst plot with crystal syste... | 0a422bfe6dd415edc70bb2a3e535f3bc1a4819cf | 3,622,827 |
def how_many_arrows(tcol):
"""Determines the number of colors that have arrows on them.
Args:
tcol (list): A 2D array of the labeling that contains the colors
and arrows for each site.
Returns:
arrows (int): The number of arrows in the system.
n_species (int): The number ... | bd42ee81d9a085eeae5f06afb6c93eec7764e37f | 3,622,828 |
import re
def CreateKwargHandler(endpoints, f):
"""
Create methods which contains kwargs
and return the remaining endpoints to handle
"""
index = 0
# endpoints = ["/v2/users", "/v2/users/:id"]
remainEndpoints = []
while index < len(endpoints) - 1:
firstMatches = re.fi... | a805b8c2b1c1593e973fa0ac781fa780fa4a6d1a | 3,622,829 |
def get_grid_cells_position(shapes, aspect_ratio=16/9., dim=None):
""" Constructs a XY-grid based on the cells content shape.
This function generates the coordinates of every grid cell. The width and
height of every cell correspond to the largest width and the largest height
respectively. The grid dime... | 953f6af6989ef6032d11973fa662e631ec4d5271 | 3,622,830 |
def _detect_start_end(true_values):
"""From ndarray of bool values, return intervals of True values.
Parameters
----------
true_values : ndarray (dtype='bool')
array with bool values
Returns
-------
ndarray (dtype='int')
N x 2 matrix with starting and ending times.
"""
... | d486bf0309882c4e1e330525cda5972d43802bfe | 3,622,831 |
def parse_debug(response):
"""
Parse the result of Redis's DEBUG command into a Python dict
:param bytearray response:
:return disc:
"""
info = {}
response = response.decode('utf8')
for line in response.split(','):
if line.find(':') != -1:
key, value = line.split(':'... | bd38d55ef7dab2c2c5329254f39a0b99e4268b57 | 3,622,832 |
def pow_many(power, *args):
"""
Функция складывает любое количество цифр и возводит результат в степень power (примеры использования ниже)
:param power: степень
:param args: любое количество цифр
:return: результат вычисления # True -> (1 + 2)**1
"""
rs = 0
for v in args:
rs +=... | da0404f24045f5818ffb2219153fccd9b864965b | 3,622,833 |
def register(request):
"""Summit registration form view
"""
class SummitForm(ModelForm):
class Meta:
model = SummitRegistration
SummitForm.base_fields['email'].label = 'Email address'
SummitForm.base_fields['phone'].label = 'Phone number'
SummitForm.base_fields['address'].l... | 11b3b774418f55be09132082d87a697b1c650cfd | 3,622,834 |
def _d_serialize_delper_switch_field(context, self, field, d_switch_variable, prefix):
"""
handle switch by calling _serialize() or _unpack(), depending on context
"""
# switch is handled by this function as a special case
param_fields, wire_fields, params = get_serialize_params(context, self)
f... | 632588f5b095496a7429a7c0b601adc3159a7744 | 3,622,835 |
import json
def generate_empty_conf_dict():
"""Generates an empty dictionary according to the conference template."""
with open(str(current_path) + "/confcrawler/ressources/conference_template.json", "r") as template:
return json.load(template) | a886ae77c42b55eaead3d68d990a98b0f6d411dc | 3,622,836 |
def lighr_head_model_fn(features, labels, mode, params):
"""Our model_fn for ResNet to be used with our Estimator."""
num_anchors_list = labels['num_anchors_list']
num_feature_layers = len(num_anchors_list)
shape = labels['targets'][-1]
if mode != tf.estimator.ModeKeys.TRAIN:
org_image = la... | 158f0263ee0221e806c9add2e3119e7cf543d085 | 3,622,837 |
def gaussianMI(x, y, constellation, M, dtype=tf.float64):
"""
Computes mutual information with Gaussian auxiliary channel assumption and constellation with uniform porbability distribution
x: (1, N), N normalized complex samples at the transmitter, where N is the batchSize/sampleSize
y: (1,... | e89ee7c36d19f1ae8e3e8ff66bd0d7d605976204 | 3,622,838 |
from datetime import datetime
def efun_get_jwt(mud: str, file: str) -> str:
"""
SYNOPSIS
string get_jwt(string mudname, string filename)
DESCRIPTION
Returns a JSON Web Token for accessing mudlib files
from the web.
This efun is only allowed to be called fr... | 0cd30ad2d3d14bd4ee6ce461a29cc0a0b2559a89 | 3,622,839 |
from bs4 import BeautifulSoup
import requests
def get_book_list():
"""Store information about the books in a list"""
wishlist = send_wishlist_request(f"https://www.bookdepository.com/wishlists/{WISH_LIST_CODE}")
if wishlist:
soup = BeautifulSoup(wishlist.content, "html.parser")
if not ver... | e6eb72c6687e852f4cc76c607c98cc10a12b62ad | 3,622,840 |
import shutil
def gunzip_merge(outfile, list_files):
"""
Merge gunzip files into final file
:param outfile: String for output file
:param list_files: List of files to merge
:type outfile: string
:type list_files: list
"""
list_files = list(list_files)
list_files.sort()
print ("\tMerging files into: "... | ae37753cc1f16d9fc4cb4cf50587e99ef045a938 | 3,622,841 |
def parse_id(method):
"""
Ensures the input experiment identifier is an experiment UUID string
Parameters
----------
method : function
An ONE method whose second arg is an experiment ID
Returns
-------
function
A wrapper function that parses the ID to the expected strin... | 94e3473b1cc5afa6278a1baba8d9849ff8f6b938 | 3,622,842 |
def shuffel_data(x, y, seed=None):
"""Random shuffle of the data"""
if seed:
np.random.seed(seed)
index = np.arange(x.shape[0])
np.random.shuffle(index)
return x[index], y[index] | 187100fc1b83ec78fca1f8912781aae75fdf4a6e | 3,622,843 |
def font_face(psname):
"""Return a Face tuple given a psname"""
fam = LIBRARY.parent_fam(psname)
for face in LIBRARY.list_fam(fam):
if face.psname == psname:
return face
notfound = 'Font: no matches for Postscript name "%s"'%basis
raise DeviceError(notfound) | b23421b33f565cc86c3ad22b395af707ca3e6f2b | 3,622,844 |
import subprocess
def _doSysExec(command: str, errorAsOut: bool = True) -> tuple[int, str]:
"""Execute a command and check for errors.
Args:
command (str): commands as a string
errorAsOut (bool, optional): redirect errors to stdout
Raises:
RuntimeWarning: throw a warning should there be a non exit code
R... | 4f6ae92628090c1f00be3268599dcef07c3818ac | 3,622,845 |
def modularity_density(
graph: nx.Graph, communities: object, lmbd: float = 0.5, **kwargs: dict
) -> object:
"""The modularity density is one of several propositions that envisioned to palliate the resolution limit issue of modularity based measures.
The idea of this metric is to include the information abo... | 085dfe9d03f92d98771521d07ecffb996b477461 | 3,622,846 |
def get_media_pool_clip_list_and_clip_name_list(project):
"""
Parametes
---------
project : Project
a Project instance
Returns
-------
clip_return_list : list
clip list
clip_name_list : list
clip name list
Examples
--------
>>> resolve, project_manag... | f69a67d1ae29e714bf8c153519b515238a93875d | 3,622,847 |
def get_instances():
"""returns array of instance names, array of corresponding n"""
data = np.genfromtxt('m2s_nqubits.csv', delimiter=',', skip_header=1, dtype=str)
return data[:, 0], data[:, 1].astype(int) | 0d9d91d7b50d5c27be6ac77dff5aff6743e796bd | 3,622,848 |
import os
import types
import tqdm
def data_inference(tensor_data, frozen_graph_path, show=False, out_folder=None, threshold=.5):
""" Returns results """
# NOTE Single datapoint inference at a time. Really not optimized. At all.
if out_folder:
os.makedirs(out_folder, exist_ok=True)
outputs = [... | 214f9be622160ee29b0a6c0b4a1ff9a71d602bad | 3,622,849 |
def stac_catalogs_item(catalogs, item_id):
"""Fetch catalog's single features
---
tags:
- Data
description: |-
Fetch the feature with id `featureId` in the given catalog provided.
with `catalogs`.
parameters:
- name: catalogs
in: path
required: true
... | 90e7fda5481cb5cdc2b94d9165ead80b6c0a754b | 3,622,850 |
import sys
def get_version():
"""Returns the version of Bladerunner and the python it's running on."""
return "Bladerunner {ver} on Python {pyv}. Released: {date}".format(
ver=__version__,
pyv="{0}.{1}.{2}".format(*sys.version_info[:3]),
date=__release_date__,
) | e56fc9301c9837e1b9f0baf647a7a99ba6969d51 | 3,622,851 |
import zipfile
def _generate_zip_package(target, sources, sources_dir):
"""Generate a zip archive containing all of the source files. """
zip = zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED)
manifest = _archive_package_sources(zip.write, sources, sources_dir)
zip.writestr(_PACKAGE_MANIFEST, '\n'.j... | fd16ea1ef48a37721e52d48cc5a9cd4eb8fc5cb0 | 3,622,852 |
from typing import List
import re
def match_phrases(phrases: List[str]):
"""
Compiles multiple phrases into a single predicate function that returns True if the input contain any of the
phrases surrounded by word boundaries.
"""
# escape regex metacharacters and ignore repeated whitespace in multi... | 0f1fb616060723285a124966b15fcc76659b363c | 3,622,853 |
def get_payment_request_with_payment_method(business_identifier: str = 'CP0001234', payment_method: str = 'CC'):
"""Return a payment request object."""
return {
'paymentInfo': {
'methodOfPayment': payment_method
},
'businessInfo': {
'businessIdentifier': business_... | c506f2750e0ffe5d1852116eab241e7e022d3b84 | 3,622,854 |
def empty_framework_version_warning(default_version, latest_version):
"""
Args:
default_version:
latest_version:
"""
msgs = [EMPTY_FRAMEWORK_VERSION_WARNING.format(default_version)]
if default_version != latest_version:
msgs.append(LATER_FRAMEWORK_VERSION_WARNING.format(lates... | d78f74087fe97b409b61d74bd26afc80749e6a79 | 3,622,855 |
def AddIamPolicyBinding(content_ref, member, role):
"""Adds iam policy binding request."""
policy = GetIamPolicy(content_ref)
iam_util.AddBindingToIamPolicy(
dataplex_api.GetMessageModule().GoogleIamV1Binding, policy, member, role)
return SetIamPolicy(content_ref, policy) | c135bd54654abcec1c95b995df0f1c09d3ca2805 | 3,622,856 |
def getLevelName(lvl):
"""
Return the textual representation of printing level 'lvl'. If the level is
one of the predefined levels (JOB, IMPORTANT, TERSE, NORMAL, VERBOSE) then
you get the corresponding string. If you have associated levels with names
using addLevelName then the name you have associ... | 9b60cefa53d6be0a0f40b456e569ad4df7babad8 | 3,622,857 |
def CIFAR100Config(argument_parser):
"""
Set CLI arguments
:param argument_parser: argument parser
:type argument_parser: ```ArgumentParser```
:return: argument_parser
:rtype: ```ArgumentParser```
"""
argument_parser.description = """`CIFAR100 <https://www.cs.toronto.edu/~kriz/cifar.ht... | 958052bf1db9b2f7a245f02a57832fa165fa1b4d | 3,622,858 |
def _get_cycle_factor_traversal(factor_size, num_frames):
"""
Cycles through the state space in a single cycle.
eg. num_indices=5, num_frames=7 returns: [0,1,3,4,3,2,1]
eg. num_indices=4, num_frames=7 returns: [0,1,2,3,2,2,0]
"""
grid = _get_interval_factor_traversal(factor_size=factor_size, num... | 5048d7d20a40b3d786dc9234735f9e5939ed0ba2 | 3,622,859 |
def get_links(text):
"""Extract all kind of links from text.
Ordanaty get arxivs, dois and urls from text.
Link of type doi and arxiv will never have same link,
but when extract urls, all of returned links will be
checked to ensure no repeat links.
Parameters
----------
text : text tha... | 10657f1cbe86f107df3c5f579df398777dd5f99b | 3,622,860 |
def get_fine_tune_var(exclude_variable_scope, if_freeze = True):
"""
if_freeze: Boolean, if True, optimizer will exclude gradient over the
var under variable_scope
"""
train_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
if (if_freeze):
final_vars = []
ex... | 0d43f16096f3246d1426e81e9dfe945cf63a2779 | 3,622,861 |
from typing import Optional
from typing import List
from enum import Enum
async def find_enums_by_topic(
topic_id: Optional[TopicId], principal_service: PrincipalService = Depends(get_console_principal)
) -> List[Enum]:
"""
find enumerations by given topic
"""
if is_blank(topic_id):
raise_400('Topic id is req... | 7cbd5baf247106f54c99a6fe16181ba29509f4be | 3,622,862 |
import time
def timing_function(some_function):
"""
Outputs the time a function takes
to execute.
"""
def wrapper():
t1 = time.time()
print(t1)
some_function()
t2 = time.time()
print(t2)
return "Time it took to run the function: " + str((t2 - t1)) ... | 7ff8cec2102f355d586d14e2e41c8a410beb5836 | 3,622,863 |
def all_close(x, y, msg, solver):
"""
Check to see if x and y are close
"""
try:
v = np.linalg.norm(x-y) <= 1.0e-03 * max([1, np.linalg.norm(x), np.linalg.norm(y)])
except:
print("""
check_failed
============
msg: %s
x: %s
y: %s
""" % (msg, x, y))
return False
v = v or np... | c7245e6b5a8cbc5b15d8180fd2a60e0ee281ac02 | 3,622,864 |
def term_matches(text, forms_list, options):
""" Counts the number of occurences of the words in forms_list in the text
The terms in forms_list can either be tokens or full terms. The
matching for tokens is contains and for full terms is equals.
"""
token_mode = options.get('token_mode', TM_TOKENS)
... | d40dffa610a2d6ecf210d2a27d6c9b3b5dfc9d73 | 3,622,865 |
def first_rows_close_as_set(a, b, k=None, rtol=1e-6, atol=1e-6):
"""Checks if first K entries of two lists are close, up to permutation.
Inputs to this assert are lists of items which can be compared via
numpy.allclose(...) and can be sorted.
Args:
a: list of items which can be compared via numpy.allclose... | 89b21b7653849fb4a24f61591f88b8896145db8b | 3,622,866 |
import logging
def rdt(df, *expr):
""" execute R style expression on pandas DataFrame
Args:
df: pandas DataFrame
*expr: each is a string expression such as
'region=="Europe", sales_fraction := sales / sum(sales), by="country"'
which conforms to R data.table syntax data.table[... | 888e54c62c77a70eb0c3e948705f37b55fcf465d | 3,622,867 |
import os
def _coffea_fn_as_file_wrapper(tmpdir):
""" Writes a wrapper script to run dilled python functions and arguments.
The wrapper takes as arguments the name of three files: function, argument, and output.
The files function and argument have the dilled function and argument, respectively.
The f... | d8beac710f818bdc01cd794c586c0f101ea26b9b | 3,622,868 |
import os
def get_info_file(fname):
"""
Construct the info file name from the project id.
Read the project id from the qmcpack input file.
"""
if fname.endswith('.info.xml'):
return fname
info_fname = ''
try:
tree = ET.parse(fname)
except IOError as e:
print('Assuming xml input fil... | dcde06d94d1fc544facdbe80342df4ace01c435c | 3,622,869 |
def process_categories(cat_path):
""" Returns the mapping between the identifier of a category in
Places365 and its corresponding name
Args:
cat_path: Path containing the information about the Places365
categories
"""
result = {}
with open(cat_path) as f:
lines = f.re... | f87741b990ee9ab9c8216112df73c7aa5bab8d49 | 3,622,870 |
def evalexpr(data, expr, exprvars=None, dtype=float):
""" evaluate expression based on the data and external variables
all np function can be used (log, exp, pi...)
Parameters
----------
data: dict or dict-like structure
data frame / dict-like structure containing named columns
exp... | 68deaceac6ae20ba178c28bd3046b31fb96e49fe | 3,622,871 |
def word_list_raw():
"""
Return the wordlist used for mnemonics.
"""
return """abandon
ability
able
about
above
absent
absorb
abstract
absurd
abuse
access
accident
account
accuse
achieve
acid
acoustic
acquire
across
act
action
actor
actress
actual
adapt
add
addict
address
adjust
admit
adult
advance
advi... | d85126435259c83dd481635c4d7940a5347ffe28 | 3,622,872 |
from typing import cast
def _ensure_data(values: ArrayLike) -> np.ndarray:
"""
routine to ensure that our data is of the correct
input dtype for lower-level routines
This will coerce:
- ints -> int64
- uint -> uint64
- bool -> uint64 (TODO this should be uint8)
- datetimelike -> i8
... | 271f3bc1d3d1bd0c995a17412d5a901c42e79a68 | 3,622,873 |
def _check_dthetapsi(
dtheta=None, psi=None,
extenthalf_psi=None, extenthalf_dtheta=None,
ntheta=None, npsi=None,
include_summit=None,
):
""" Return formatted dtheta and psi
They are returned with the same shape (at least 1d arrays)
They can be:
- 'envelop': if psi of dtheta = 'env... | 24c35d2c2ba8bb5dc888e7205e117ab8780b05e1 | 3,622,874 |
def find_beta_image_identifier(targetgrouparn):
"""Queries the tags on TargetGroups
Args:
targetgrouparn - Amazon ARN of the Target group that needs to be queried for the Tags
Returns:
identifier : tag key value of the target group , with KeyN... | 53185b64cbe7a05e85c36b19978344b700e5c9c0 | 3,622,875 |
import struct
def fread(f,byteLocation,structFormat=None,nBytes=1):
"""
Given an already-open (rb mode) file object, return a certain number of bytes at a specific location.
If a struct format is given, calculate the number of bytes required and return the object it represents.
"""
f.seek(byteLoca... | ae86bb1f3bc839053ca34c8bf2b4beb0af04aaee | 3,622,876 |
async def handle_post_projects(project: projects.schemas.project.ProjectCreate,
session: Session = Depends(session_scope)):
"""
Handles POST requests to /.
Parameters
----------
project : projects.schemas.project.ProjectCreate
session : sqlalchemy.orm.session.Sess... | efb943840c978976f3b8bd383df6c43bd4a946eb | 3,622,877 |
def _cast_types(args):
"""
This method performs casting to all types of inputs passed via cmd.
:param args: argparse.ArgumentParser object.
:return: argparse.ArgumentParser object.
"""
args.x_val = int(args.x_val) if args.x_val != 'None' else None
args.test_size = float(args.test_size)
# criterion (string)
# s... | 61438940cdc572b08ebd7ee0efe56cae65c1ddd7 | 3,622,878 |
def replace_and_concat(mac: str, vendor: str, python_option=True) -> str:
"""
Creates single string depending on the selected mode.
TODO: Make it simpler without the python_option flag
Args:
mac {str}: mac address
vendor {str}: vendor string
python_optio... | 4cb8aaa58fd08a409fa14be1a3e8ac4cd8fae1ea | 3,622,879 |
import logging
def bruteforce_method(p1, p2):
"""Метод полного перебора"""
e_cnt = pf.e_normalize(p2)
pf.s_to_c(p2)
logging.debug('BruteForce: ' + str(p1) + str(p2))
split_subs = SplitSubstitution(p1, p2, EPL_method).algorithm()
# for sub in split_subs:
# if pf.NePL_test(sub, p2):
... | f58ece7868c943f3f6565c8828f5b5301c4e0bc6 | 3,622,880 |
def prequalification(request, step):
"""
View for rendering pre-qualification questions.
If user is not authenticated with BCeID, temporarily store user responses to session
"""
template = 'prequalification/step_%s.html' % step
if not request.user.is_authenticated:
responses_dict = get_... | b1d58d71776fbd05a80d451b2d7764825abaddd7 | 3,622,881 |
def _read_netcdf_coordinate_units(root):
"""Get units for coodinate values.
Parameters
----------
root : netcdf_file
A NetCDF file.
Returns
-------
tuple of str
Units for each coordinate.
"""
units = []
for coordinate_name in _AXIS_COORDINATE_NAMES:
try:... | 25c3fe5db696430cd9bbcb9f587ca8a5b968fac1 | 3,622,882 |
def check(_user_id):
"""
checks whether it is a check.
"""
_board = boards[_user_id]
return _board.is_check() | 1ce2e9862468fd167b7d7aa5e45ccfba8d788f5c | 3,622,883 |
def angle_to_pixels(angle, screenDist, screenW, screenXY):
"""
Calculate the number of pixels which equals a specified angle in visual
degrees, given parameters. Calculates the pixels based on the width of
the screen. If the pixels are not square, a separate conversion needs
to be done with the heig... | 2c65599e54af9d7555bb05260070c80f072483f2 | 3,622,884 |
import os
import unicodedata
def toUrlsafe(filename):
"""Make a filename url-safe, keeping only the basename and killing all
potentially unfitting characters.
:returns: urlsafe basename of the file as string."""
filename = os.path.basename(filename)
filename = unicodedata.normalize('NFKD', filena... | 2fc07a8f159ea05e359060e7b36f3a2ff82accb3 | 3,622,885 |
import requests
def _delete_conn_info(self, switch, port, dir):
""" Deletes existed connection between ``port1`` and ``port2`` an the switch
``dir`` could be ``bi``,``in`` or ``out``
"""
cli = self._clients[switch]
ip = cli["ip"]
conn_port = cli["port"]
session = cli["session"]
... | eb5db24fb30ed09e09c7ad0b46a40ee28e99b802 | 3,622,886 |
from typing import List
def get_mask_for_tokens(tokens: List[str],
special_tokens: List[str] = []) -> List[int]:
"""Return a mask for a tokenized smiles, where atom tokens
are converted to 1 and other tokens to 0.
e.g. c1ccncc1 would give [1, 0, 1, 1, 1, 1, 1, 0]
Args:
... | 69b5757c294b9226987aa5e6643642e1b13c43d5 | 3,622,887 |
def fail_if_data_set_exists(zosmf_profile, dataset_name):
"""
Check whether data set exists and throw and exception if it does
"""
connection = {'plugin_profile': zosmf_profile}
files = Files(connection)
list_dsn = files.list_dsn(dataset_name)
if list_dsn['returnedRows'] == 0 :
retu... | baf7091527eaab2083fce89ca8be77183ef1d73b | 3,622,888 |
from pyoptsparse import Optimization
def snopt_opt(objfun, desvar, lb, ub, ncon=None, title=None, options=None,
sens='FD', jac=None):
"""
Find optimal values using SNOPT from pyoptsparse.
If SNOPT is not available, use other avaiilable optimizer. The desvar is an array of variables
name... | a53e7b8059104fb8aaef6f1f6ff0c40b526b4ee3 | 3,622,889 |
def yiq_to_web(yiq):
"""
Convert a YIQ color representation to a WEB color representation.
(y, i, q) :: y -> [0, 1]
i -> [-0.5957, 0.5957]
q -> [-0.5226, 0.5226]
:param yiq: A tuple of three numeric values corresponding to the
luma and chrominance.
:return: WEB r... | 2a8385bc86d5952b0ba386ead6692d71d3467e47 | 3,622,890 |
def post_processing(data, start, scaler_1, scaler_2, delta):
"""Post-processing"""
data = scaler_2.inverse_transform(data)
data = data * np.exp(0.5 * delta * data **2)
data = scaler_1.inverse_transform(data)
data = np.exp(data)
post_data = np.empty((data.shape[0], ))
post_data[0] = star... | 5d45cdce784d75600986efb68e0eb11b981accde | 3,622,891 |
def predict_accuracy(armas: tuple, sig: SwitchingArmaSignal) -> float:
""" Predict accuracy score from ARMA models.
Parameters
----------
armas
Pair of `Arma` models.
sig
Signal generated from the ARMA models.
Returns a predicted value for the expected accuracy score of... | 62e69fe7a751f26d040ca4b4a814ec11be0ebd30 | 3,622,892 |
def get_contours_inner_angles(contour):
"""
Given a closed contour, return a list of its inner angles in radians
:param contour: a 2D numpy array
:return: 1D numpy array of angles in radions
"""
# Unroll all points triplets to vectors
a = contour
b = np.tile(contour, reps=(2, 1))[1:1 + ... | 7c3811ab09a2523cf860ee1cd36883d0a95a0d78 | 3,622,893 |
def _get_year(obj):
"""
Get the year of the entry.
:param obj: year string object
:return: entry year or none if not valid value
"""
year = obj[0:4]
try:
year = int(year)
except ValueError:
year = None
return year | 6d3cbcc8759096ec3e798e90dc3a307b4a34b6ae | 3,622,894 |
def solve4y(x: float, m: float, b: float):
"""
y = m * x + b
"""
if m is np.nan:
return b
return m * x + b | ed56bdacc9c595e5c88bf86d1fb36479422f6ee7 | 3,622,895 |
import argparse
def _parse_arguments():
"""Return a parser context result."""
parser = argparse.ArgumentParser(description="CMake AST Dumper")
parser.add_argument("filename", nargs=1, metavar=("FILE"),
help="read FILE")
return parser.parse_args() | a811308be0fdb28294f8a0a0af80bf3a2cceae51 | 3,622,896 |
def c2():
"""Compound CID 175."""
return Compound.from_cid(175) | 5d40c16a22ecee39530eb6b43d85e6e35b9f9387 | 3,622,897 |
import json
def create_user(request):
""" Creates a new user with specified settings
URL: /admin/Users/Create/
:param request:
:return:
"""
post = request.POST.dict()
username = post.get('username')
if username is None:
response = {'status':-1, 'status_message':'No userna... | d820f7381cb02d171fc770b6da96e491d3e7587a | 3,622,898 |
import argparse
def parse_arguments() -> argparse.Namespace:
"""Parse given command line arguments."""
parser = argparse.ArgumentParser(
allow_abbrev=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
calculation = parser.add_argument_group("crafting options")
verbosity = par... | e55d694a1cb6b1d8beb14bb0231626fba568f78d | 3,622,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.