content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
def ext(f):
"""Changes the extension of the a give file to jpeg"""
return os.path.splitext(f)[0] + '.jpg' | 51e6acce6ff2a7116e4194aed425e5b81a5f15f1 | 36,400 |
import pytz
def display_timezone():
"""Displays the dialog for all"""
tzlist = pytz.common_timezones
tzlist.sort()
tag = tzlist
desc = []
for item in tag:
desc.append(item.split("/")[-1])
mytzlist = zip(tag, desc)
return DISPLAY.menu(
"Please select the system timezon... | 0709aae540f04baa267050066542c1f44477bd8a | 36,401 |
def operate_favorite(rid: int, type_: str, add_media_ids: list = None,
del_media_ids: list = None, verify: utils.Verify = None):
"""
操作收藏夹
:param rid:
:param type_:
:param add_media_ids: 要添加的收藏夹内容列表
:param del_media_ids: 要删除的收藏夹内容列表
:param verify:
:return:
"""
... | c2de969541f893312be8aed9b41ce99f8e4bb7a2 | 36,402 |
import logging
import sys
def mask_3D(hPa, sect, MBL=True, res='4x5', extra_mask=None,
M_all=False, use_multiply_method=True, trop_limit=False,
verbose=True, debug=False):
"""
Creates Maskes by pressure array (required shape: 72,46,47),
with conditions (lower and upper bounds) set... | 044e55b460e1b21a698a4e3b488b9bd782533064 | 36,403 |
import random
def kmeans_rand_centroids_1_d(data, k, max_error, max_iters):
"""Performs K-Means analysis on a one dimensional array, starting with centroids that are randomly distributed across the range of the input set."""
# Sanity check.
data_len = len(data)
if data_len <= 1:
return []
... | eb50fdcb4b05c5c99dd655d6c9b74b0d80c621d2 | 36,404 |
def _compute_fscores(a_stat, a_fscore_stat):
"""
Compute macro- and micro-averaged F-scores
@param a_stat - statistics disctionary on single classes
@param a_fscore_stat - verbose statistics with F-scores for each
particular class (will be updated in this method)
@return 6-tu... | a5e2cf4eff650e56a4c6b8c83955e3740d6bb937 | 36,405 |
def pseudonymize(collection, entry, pseudonymizer, config):
"""Pseudonymize an entry in the database."""
entry_out = entry
if collection in config['pseudonymize']:
entry_out = deepcopy(entry)
config_keys = config['pseudonymize'][collection]
entry_keys = entry_out.keys()
#... | b2db89029bc46d3fa358afa63f594d10fee69c55 | 36,406 |
import os
def info( request ):
""" Returns info page. """
log.debug( 'request.__dict__, ```%s```' % request.__dict__ )
context = {
u'email_general_help': os.environ[u'EZSCAN__EMAIL_GENERAL_HELP'],
u'phone_general_help': os.environ[u'EZSCAN__PHONE_GENERAL_HELP']
}
return render(... | 344382bc96ed87ac00134373c50bf153daae0aed | 36,407 |
def vector_layer_db(map, layer):
"""Return the database connection details for a vector map layer.
If db connection for given layer is not defined, fatal() is called.
:param str map: map name
:param layer: layer number
:return: parsed output
"""
try:
f = vector_db(map)[int(layer)]
... | 4bd25e62d635c02374bd27ce6cd885625697190a | 36,408 |
def _Flatten(nmap_list):
"""Flattens every `.NestedMap` in nmap_list and concatenate them."""
ret = []
for x in nmap_list:
ret += x.Flatten()
return ret | 10a13836353894524c1f6cea45296d854054e8a7 | 36,409 |
from typing import Union
from typing import Dict
def get_all_subscription_request(
from_position: Union[Dict[str, int], str] = constants.START,
resolve_link_to_s: bool = False,
filters: Dict = None,
) -> streams_pb2.ReadReq:
"""Returns a streams_pb2.ReadReq configured for subscription operations for t... | 20ce7be5217e6a076eb1e9dc635b1bb51679b197 | 36,410 |
def us2en(edate, **kwargs):
"""
Wrapper function for :func:`date2date` with English date format output
That means `date2date(edate, format='en', **kwargs)`;
but *format* given in call will overwrite *format='en'*.
Examples
--------
>>> edate = ['11/12/2014 12:00', '01.03.2015 17:56:00',
... | 2a96c89302abc24c25cecc36b2b7763b3cd3a2af | 36,411 |
def autosave_info(user, namespace_project):
"""Information about all autosaves for a project."""
if user.get_renku_project(namespace_project) is None:
return make_response(
jsonify(
{"messages": {"error": f"Cannot find project {namespace_project}"}}
),
... | 01754718eda2ec22ceeb739f079000058160156b | 36,412 |
def per_subgroup_fnr_diff_from_overall(df, subgroups, model_families, threshold,
squared_error):
"""Calculates the sum of differences between the per-subgroup false negative rate and the overall FNR."""
d = per_subgroup_nr_diff_from_overall(df, subgroups, model_families,
... | 3ce163a1a2faca9e84b0e919a75d38b831c7c56e | 36,413 |
import os
import pickle
def load_data(file_path=FILE_PATH):
"""If the data exist load the data from a db (represented by a dict(str[name] -> int[quantity])).
If not, return an empty dict."""
try:
with open(os.path.join(file_path, 'data.pk'),'rb') as fh:
data = pickle.load(fh)
excep... | e55f5ac23ed7c47821a6de60d732b4dec415ea0e | 36,414 |
def scaffold_split_from_smiles(
smiles_list, frac_train=0.8, frac_valid=0.1, frac_test=0.1,
):
""" The same algorithm as scaffold_split. Only take SMILES list as input and return
indices of the train, validation, and test samples.
Args:
smiles_list (list): list of SMILES to be splitted.
... | e302a1cf9106b04f76432dd051a8a1b2fd5ff021 | 36,415 |
def _get_transitive_values(values, deps, deps_accessor):
"""Returns the transitive values from "values" added to values from deps.
Args:
values: the values of to be added to the transitive values from deps.
deps: list of dependencies with GLSLInfo providers to add to the
transitive ... | 6184fc25819eacd2003ba7ad4481882e744c7892 | 36,416 |
from typing import Dict
from typing import Any
def get_common_config(
io_conf: ConfigType, mqtt_conf: ConfigType, mqtt_options: MQTTClientOptions
) -> Dict[str, Any]:
"""
Return config that's common across all HQ discovery announcements.
"""
disco_conf: ConfigType = mqtt_conf["ha_discovery"]
c... | b0f0109e114fdd2a2782eb2d6b4d1980f23bf9ae | 36,417 |
def compute_sampled_logits_css(
weights, # [V, d]
biases, # [V]
probable, # [B, P]
inputs, # [B, T, d]
num_sampled,
num_classes,
minval=1, # use this to control what's the first valid class
bias_correction=True
):
"""
:param weights: class... | 7b8ffc2bd0e7174cfb3ceac03e34a0be36c011ed | 36,418 |
def interp_weights(xyz, uvw, d=2):
"""
Fast interpolation of multiple datasets over the same grid
from: https://stackoverflow.com/a/20930910/2197375
Parameters:
---
xyz: ndarray, array of starting irregular grid coordinates
uvw: ndarray, array of target regular grid coordinates
d: int, ... | 405a75e2590f0b2d36a4922b53436f2ebd286909 | 36,419 |
def add_shopping_list_items(create_client_shopping_list, client, generate_token): # noqa
"""
add items to a shopping list
"""
shopping_list_id = create_client_shopping_list.data['data']['id']
token, _ = generate_token
url = reverse('shoppingItem:get shopping list items', args=[shopping_list_id]... | f1be8b5ef2b0ba99ff4f543c0c74cf8c32068f35 | 36,420 |
def _get_mode():
"""Get the current mode (0 is Graph mode, 1 is PyNative mode)"""
return context.get_context('mode') | 013789d9eae12710bc016bdb3191a35cac006dc6 | 36,421 |
def parse_xml(text:str):
"""Parse the given string as XML."""
return etree.fromstring(text) | 373d6cfb04b570a3212f7a830aa4055dfb9d9f14 | 36,422 |
def crop_anno(img_path, crop_position, df, im_w=None, im_h=None,
filesystem:FileMan=None):
"""Calculate annos for a crop-position in an image
Args:
img_path (str): image to calculate the crop-annos
crop_position (list): crop-position like: [xmin, ymin, xmax, ymax]
... | 91cd205ee1aa7b19eda552353d9bf4f55ae52905 | 36,423 |
def tab_listtable_details(p_engine, p_format, rulesetname, envname, metaname):
"""
List details of tables/file from ruleset
param1: p_engine: engine name from configuration
param2: p_format: output format
param3: rulesetname: ruleset name to display metadata from
param4: envname: environemnt nam... | f928d5d31ce59f1669c20080c8c18b239c1630aa | 36,424 |
def setup_system_tomograph(n_shots: np.int, n_rays: np.int, n_grid: np.int) -> (np.ndarray, np.ndarray):
"""
Set up the linear system describing the tomographic reconstruction
Arguments:
n_shots : number of different shot directions
n_rays : number of parallel rays per direction
n_grid : n... | c3ba41db44972056023c9938444bb9e53d4220eb | 36,425 |
from bs4 import BeautifulSoup
def parse_markdown_to_html_table():
""" Parse README.md, convert to HTML, return table """
readme = open("README.md", 'r').read()
html = markdown2.markdown(readme, extras=['tables'])
soup = BeautifulSoup(html, 'html.parser')
table = soup.find("table")
return table | dad43919c302b1124edac41a442e782c052de0b0 | 36,426 |
def get_relation_priority(relation: Relation) -> int:
"""This function helps resolve conflicts when multiple conditions apply
to the same factor transition.
"""
if isinstance(relation, And):
priorities = [get_relation_priority(rel) for rel in relation.relations]
priority = sum(prior... | bcde2220ddab1c75d316fbfa89c3e406275275fd | 36,427 |
def _int_size_to_type(size):
"""
Return the Catalyst datatype from the size of integers.
"""
if size <= 8:
return ByteType
if size <= 16:
return ShortType
if size <= 32:
return IntegerType
if size <= 64:
return LongType
return None | f80231a841461557fb79dc3bbd3ff1c1a77b5016 | 36,428 |
def Coordinate(coord: str) -> Coord:
"""Converts a coordinate string into float tuple"""
try:
split = coord.split(",")
return Coord(lat=Latitude(split[0]), lon=Longitude(split[1]), repr=coord)
except Exception as exc:
raise Invalid(f"{coord} is not a valid coordinate pair") from exc | 9bb79d4975427f31474aa97dde5004bc44133fda | 36,429 |
def getCollateralRepayQuote(coin, collateralCoin, amount, recvWindow=""):
"""# Get Collateral Repay Quote (USER_DATA)
#### `GET /sapi/v1/futures/loan/collateralRepay (HMAC SHA256)`
Get quote before repay with collateral is mandatory, the quote will be valid within 25 seconds.
###
### Parameters:
Name |Type |Manda... | 37d91a220af05098b481adb55d2499cf8179d99e | 36,430 |
import string
import re
def _remove_duplicate_punctuation(text: str) -> str:
"""
Remove duplicate punctuation, which may have been a feature of
gazette design.
"""
pattern = f"([{string.punctuation}])" + "{1,}"
pattern = re.compile(pattern)
text = re.sub(pattern, r"\1", text)
return te... | 8aacab404a8fe4c3b4feda899231d65967d91973 | 36,431 |
def coeffs_mydft(x, order):
"""Use DFT."""
coeffs = [my_dft(x, 0)]
for k in range(1, order+1):
coeffs.extend([my_dft(x, k), my_dft(x, -k)])
coeffs = np.array(coeffs) / len(coeffs)
return coeffs | b53980556e407424ea492317cf8c28469c61c0de | 36,432 |
def versionCompare(sVer1, sVer2):
"""
Compares to version strings in a fashion similar to RTStrVersionCompare.
"""
## @todo implement me!!
if sVer1 == sVer2:
return 0;
if sVer1 < sVer2:
return -1;
return 1; | 807e30d55138f3a082dfcba53400d1f7e1259271 | 36,433 |
import os
def list_languages(request):
"""
Lists the languages for the current project, the gettext catalog files
that can be translated and their translation progress
"""
languages = []
do_django = 'django' in request.GET
do_rosetta = 'rosetta' in request.GET
has_pos = False
for l... | 5d8f749ea9548213d65499c428a9f07a6f91019f | 36,434 |
def parse_employee_info(record_list):
""" Parses the employee record information
Example input:
[('3c7ca263-9383-4d61-b507-2c8bd367567f', 123456, 'Austin', 'Grover', <memory at 0x11059def0>, True, 1,
'00000000-0000-0000-0000-000000000000', datetime.datetime(2020, 2, 23, 16, 53, 25, 531305))]
Args... | a0c4e9fb57bc452119f362525e9c16f516911922 | 36,435 |
from typing import Union
from typing import Tuple
from typing import Callable
def make_request(
schema: Schema,
request_url: str,
endpoint_name: str,
method: str,
body: Union[Tuple[str, str], None],
after_error_occurred: Callable[[ErrorMessage], None] = None,
before_request_send: Union[Cal... | 7181a15a5dafa0c85d986edf2bd2ca2f497ab21b | 36,436 |
import math
def gas_release_rate(P1, P2, rho, k, CD, area):
"""
Gas massflow (kg/s) trough a hole at critical (sonic) or subcritical
flow conditions. The formula is based on Yellow Book equation 2.22.
Methods for the calculation of physical effects, CPR 14E, van den Bosch and Weterings (Eds.), 1996
... | 8749b85457e3f9e24e08f2a9f5f059066e3518b8 | 36,437 |
import copy
def kube_rootca_update_start(token, force=False, alarm_ignore_list=None):
"""
Ask System Inventory to start a kube rootca update
"""
api_cmd_payload = dict()
api_cmd_payload['force'] = force
if alarm_ignore_list is not None:
api_cmd_payload['alarm_ignore_list'] = copy.copy(... | 886d708c6fb45d96d89613b391c5bc11136b54e7 | 36,438 |
def email2words(email):
"""Return a slightly obfuscated version of the email address.
Replaces @ with ' at ', and . with ' dot '.
"""
return email.replace('@', ' at ').replace('.', ' dot ') | cd8dff104ace7eaad00164ba1161d1c49ce4a0e3 | 36,439 |
import requests
from typing import Union
from typing import Any
import json
def read_response_body(response: requests.Response) -> Union[dict[str, Any], str]:
""" Read response body as a ``dict`` if possible, else as a ``str`` """
body = response.content.decode('utf-8')
try:
body = json.loads(body... | bac5aee7ac68287826e56cd86cfbc28ce4767768 | 36,440 |
import random
def _augment_gain(audio, low=0.25, high=1.25):
"""Applies a random gain between `low` and `high`"""
g = random.uniform(0.25, 1.25)
return audio * g | e29aab98511168ce8fddb62c65a287f68fbc0e4e | 36,441 |
def gaussfit(data, err=None, params=(), autoderiv=True, return_error=False,
circle=False, fixed=np.repeat(False, 7),
limitedmin=[False, False, False, False, True, True, True],
limitedmax=[False, False, False, False, False, False, True],
usemoment=np.array([], dtype='b... | 882653f8186f4ec9c92a4236bfec4343edeb6c5e | 36,442 |
def check_level_number(tags: Tags, level: float) -> bool:
"""Check if element described by tags is no the specified level."""
if "level" in tags:
if level not in parse_levels(tags["level"]):
return False
else:
return False
return True | 752e030fd52ed7bf8603e18c6d221b3a4be8daa4 | 36,443 |
def read_eof_file(file):
"""wrapper for parse_eof to return a dictionary"""
D = dict()
potc,rforcec,zforcec,densc,potS,rforces,zforces,denss = parse_eof(file)
D['potC'] = potc
D['rforceC'] = rforcec
D['zforceC'] = zforcec
D['densC'] = densc
D['potS'] = pots
D['rforceS'] = rforces
... | 461cdad86e8782a1742e61c10a74108f3c56685e | 36,444 |
import glob
def test_train(args):
"""Trains the model."""
if args.verbose:
tf.logging.set_verbosity(tf.logging.INFO)
# Create input data pipeline.
with tf.device("/cpu:0"):
train_files = glob.glob(args.train_glob)
if not train_files:
raise RuntimeError(
"No training images found ... | aa5105598329d95cc2626d2fdce18841aa733ce9 | 36,445 |
def protocol_store(sql_engine: SQLEngine) -> ProtocolStore:
"""Return a `ProtocolStore` linked to the same database as the subject under test.
`ProtocolStore` is tested elsewhere.
We only need it here to prepare the database for our `AnalysisStore` tests.
An analysis always needs a protocol to link to.... | 225b9cba534a2c64aff2e8b7d22f6f3c304c03dd | 36,446 |
import traceback
def session_wrapper(addressed=True):
"""Allow to differentiate between addressed commands and all messages."""
def real_session_wrapper(func):
"""Wrap a telethon event to create a session and handle exceptions."""
async def wrapper(event):
if addressed:
... | c5852f3eaab335630ecba04c62552f2376d936a3 | 36,447 |
from typing import Union
from typing import Callable
def _get_callable_str(*, callable_: Union[Callable, str]) -> str:
"""
Get a callable string (label).
Parameters
----------
callable_ : Callable or str
Target function or method or property or dunder method name.
Returns
-------... | 2b968e3f5ff79701e6f63bb75548ecb228ec5ed7 | 36,448 |
def pad_lr(x, fsize, fshift):
"""Compute left and right padding
"""
m = num_frames(len(x), fsize, fshift)
pad = (fsize - fshift)
t = len(x) + 2 * pad
r = (m - 1) * fshift + fsize - t
return pad, pad + r | 409f2cb0b7604d54be5e60ec7923160493cfcf75 | 36,449 |
import tarfile
def setup_routes():
"""Setup dispatcher routes (i.e. URL paths)"""
root = CherryTarball()
d = cherrypy.dispatch.RoutesDispatcher()
d.connect('main', '/', controller=root)
# This enumerates the tarball and connects each file within to a URL in the dispatcher
tar = tarfile.open(ta... | 08ebf1040c852a6d9252a0635b4db37bcb0041a4 | 36,450 |
def check_voicehat_is_first_card():
"""Check that the voiceHAT is the first card on the system."""
cards = get_sound_cards()
return 0 in cards and VOICEHAT_ID in cards[0] | 525e0a976b1fe047b0e08a53ade7fc31b755875b | 36,451 |
def add_sylls_to_textgrid(voice, sc_utt):
""" Reconstruct syllable tier by getting segments based on word
alignments and re-running voice's syllabification algorithm on
(potentially) new pronunciations...
"""
#get phoneset map and invert to map back to native representations
#in ord... | ad40bce0a03af59f676d9e55ba497c0f0120856b | 36,452 |
def removeVM(vm):
"""Removes virtual machine. NOTE: This operation is undo-able.
@param vm: Virtual machine's name."""
return defer.maybeDeferred( _getController().removeVM, vm) | 927d92301cad20d133244dc002b90ac8da77b7a5 | 36,453 |
import itertools
def probablePosition(board):
"""
|x-pos_x|<3, |y-pos_y|<3
:param
board: the current board state
:return:
position: all position may be considered
"""
probable_list = []
for (pos_x, pos_y) in itertools.product(range(pp.width), range(pp.height)):
if n... | d4d603a731661b795a1cbc6cd0cae3086f1352d8 | 36,454 |
from typing import Tuple
from typing import List
def get_user_group_perms(
user_or_group: UserOrGroup, obj: models.Model
) -> Tuple[PermissionList, List[Tuple[int, str, PermissionList]]]:
"""Get permissions for the user/group on the given model.
This method is only used in Resolwe views and expects permi... | 61e1b5d3eea1c5cf103c1d9954899fef6d65336a | 36,455 |
def update_button(first_color, second_color, _button_state):
"""Updates button, and changes color depending on if the mouse is hovering over button.
Returns if the mouse is hovering over button or not"""
_mouse_hover = False
# noinspection PyChainedComparisons
if mouse[0] > 4 and mouse[0] < 381 and ... | 79d17afa5836588a587ec12bd83297a26cace385 | 36,456 |
import yaml
def get_configmap_fields_from_yaml(file) -> {}:
"""
Parse yaml file and return a dict of ConfigMap data fields.
:param file: an absolute path to a file
:return: {}
"""
with open(file) as f:
dep = yaml.load(f)
return dep['data'] | 08eef30d0d8e79824adefd36f5c753ba76b504ef | 36,457 |
def addfella():
"""
This endpoint is for adding fellas to the application.
Loadbalancer decids to go for which instances and based on that fella is added to it.
"""
instance_id = os.getenv("CF_INSTANCE_INDEX")
print 'Instance Id ****************%s'%instance_id
fella_count = int(db.hg... | 42ad81f91f6150f23bb7979ca227081203791ac0 | 36,458 |
def join_race_and_gender(c_id_string, artist_df):
"""
takes in a string of c_id(s), ex: "8210" or "8210, 5670"
returns a total count of male, female, white, black, asian, aian, mix, hispanic
"""
male = 0
female = 0
white = 0
black = 0
asian = 0
aian = 0
mix = 0
hispanic =... | 3793049d85a12d77058f9574be34b197b5a84760 | 36,459 |
def get_average(pixel, date, dataset):
"""
Return an N month average in the given dataset.
"""
N = 24
vals = []
bad_cnt = 0
# generate lists of month numbers and values
for i in range(N):
try:
vals.append(dataset[date][pixel])
except KeyError:
bad... | b436256c68dbc7b8dc3715ac337939dd54f1b6df | 36,460 |
import re
def to_mb(s):
"""Simple function to convert `disk_quota` or `memory` attribute string
values into MB integer values.
"""
if s is None:
return s
if s.endswith('M'):
return int(re.sub('M$', '', s))
elif s.endswith('G'):
return int(re.sub('G$', '', s)) * 1000
... | 870f276552ef90bbd5034551ea8ade0f5160491b | 36,461 |
from typing import Union
from typing import NoReturn
import re
def get_pattern(plate: str) -> Union[str, NoReturn]:
"""
Given a string that represents a plate, tries to return
its pattern. If the plate is not valid, raises a
PlateNotValidException
"""
if not valid_plate(plate):
raise P... | 0037aa3b64589def6df9aab32935fe8f666657da | 36,462 |
def Select(combinations, loads, max_number_of_workers):
"""This method selects the optimal combination of appointments.
This method uses Mixed Integer Programming to select the optimal mix of
appointments.
"""
solver = pywraplp.Solver('Select',
pywraplp.Solver.CBC_MIXED_INTEGER_PRO... | 80c375f0690effdaa631d5b9da8ba79d2fc0d9e1 | 36,463 |
def voter_stop_opposing_save_doc_view(request):
"""
Show documentation about voterStopSupportingSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_stop_opposing_save_doc.voter_stop_opposing_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api... | 2371bf6b7ebbf863256e71294810cef8c47c0762 | 36,464 |
from datetime import datetime
def first_date_in_time_dimensions() -> datetime.date:
"""The first date that should appear in time dimensions"""
return datetime.date.today() - datetime.timedelta(days=365) | cc0f626bba0cd5b650beb1c0e6ccea2b2f697260 | 36,465 |
def length_left(lumber):
"""
Convenience function for calculating the length left in a piece of lumber
:param lumber: a piece of Lumber
:return: length remaining
"""
return lumber.length_left() | 57dfd5e160abdc086759dd41df013181f1217f9d | 36,466 |
def create_spawn_point_prefab(team):
"""Return a team-specific spawn-point prefab."""
prefab = {
"name": "spawn_point",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "playerSpawnPoint",
"stateConfigs":... | 7874a6fa184b469acc836b9a965a35a33b4bd9ba | 36,467 |
def FindOrBuildDpa(dpas, options, grants):
"""Find or build DPA for simulation purpose.
If several DPA, select the one with most grants around (but DPA simulation
options always override the logic).
"""
if options.dpa:
dpa_kml_file = options.dpa_kml or None
dpa = dpa_mgr.BuildDpa(options.dpa, None, p... | b931b29b2b475fbdf520b4fe76b65269e511623c | 36,468 |
def register(request):
"""
A view that renders the register page for new users. This can only
be access by users that are not currently signed in.
**Context**
``form``
Registration form for new users
**Templates:**
`base/register.html`
... | df5ee67de73f253934cf28d0c2032c9022a1dc50 | 36,469 |
def masked_softmax_cross_entropy(preds, labels, mask):
"""Softmax cross-entropy loss with masking."""
loss = tf.nn.softmax_cross_entropy_with_logits(logits=preds, labels=labels)
mask = tf.cast(mask, dtype=tf.float32)
mask /= tf.reduce_mean(mask)
loss *= mask
fin_loss=tf.reduce_mean(loss)
var... | 2c05bfe1e6cc68fab156fbeeab08299aaaf5bf6e | 36,470 |
def find_matching_paren_pair(s):
"""
Find the first matching pair of parentheses and return their positions
"""
paren_level = -1
open_pos = 0
for i in range(0, len(s)):
if s[i] == "(":
paren_level += 1
if paren_level == 0:
open_pos = i
elif... | c50ce61ca96f1babb951d2c1051461be8633d783 | 36,471 |
import copy
def copy_mol(mol: Chem.rdchem.Mol) -> Chem.rdchem.Mol:
"""Copy a molecule and return a new one.
Args:
mol: a molecule to copy.
"""
return copy.deepcopy(mol) | a4ecabefcf5b8fc19961d5de912c3f055b5eb690 | 36,472 |
import logging
def convert_sync_bn(config, model):
"""
Convert the BatchNorm layers in the model to the SyncBatchNorm layers.
For SyncBatchNorm, we support two sources: Apex and PyTorch. The optimized
SyncBN kernels provided by apex run faster.
Args:
config (AttrDict): configuration file... | 5795bdc269a8b44c324298ebaba156a80a098c70 | 36,473 |
from . import nodes
def _(dbmodel, backend):
"""
get_backend_entity for DummyModel DbNode.
DummyModel instances are created when QueryBuilder queries the Django backend.
"""
djnode_instance = djmodels.DbNode(
id=dbmodel.id,
node_type=dbmodel.node_type,
process_type=dbmodel.... | b8b5ebb1f0c669cd9b7aa6848476cad65cfc9825 | 36,474 |
def update_job(function):
"""Decorator to update Task with result."""
@wraps(function)
def wrapper(task_id, *args, **kwargs):
task = Task.objects.get(id=task_id)
task.status = Task.STATUS[1][0]
task.save()
try:
result = function(*args, **kwargs)
task.... | ac8034db39f35e29c3c61da1912087b30158b44f | 36,475 |
def checkLogin():
"""
Check if user is logged in
"""
if current_user.is_authenticated:
return {"authenticated": True, "user": current_user.username}
else:
return {"authenticated": False} | 7c7d7f4ee05b036e50ce8462dd9e01751c044235 | 36,476 |
from typing import Tuple
from typing import Any
from typing import Optional
def _load_checkpoint(
checkpoint: Checkpoint, trainer_name: str
) -> Tuple[Any, Optional[Preprocessor]]:
"""Load a Ray Train Checkpoint.
This is a private API.
Args:
checkpoint: The checkpoint to load the weights and... | 0962a863b1759bdbff31d035c33d7106de4b14f2 | 36,477 |
def aoa_music_1D(steering_vec, rx_chirps, num_sources):
"""Implmentation of 1D MUltiple SIgnal Classification (MUSIC) algorithm on ULA (Uniformed Linear Array).
Current implementation assumes covariance matrix is not rank deficient and ULA spacing is half of the wavelength.
.. math::
P_{} (\\t... | 376adf8efea651fb915925e936c19e9741c45e0c | 36,478 |
def IsMerge(op):
"""Return true if `op` is a Merge."""
return op.type == "Merge" or op.type == "RefMerge" | 8b5c7373cd698d23bd1b0df78a5986dded8960ec | 36,479 |
import argparse
import sys
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Generate txt result file')
parser.add_argument('--dir', dest='base_dir',
help='result base dir',
default='/home/hezheqi/data/frame/result', typ... | 6f0ff842f7e7ce74d8b953a9c9164e45ecca76ac | 36,480 |
import re
def book_info(td):
"""given a BeautifulSoup <td> Tag representing a book,
extract the book's details and return a dict"""
title = td.find("div", "thumbheader").a.text
by_author = td.find('div', 'AuthorName').text
authors = [x.strip() for x in re.sub("^By ", "", by_author).split(",")]
... | aad47098c8b1ea4c3f6ac1b55d3197b14c94d173 | 36,481 |
def find_groups(groups=None, name=None, gid=None, member=None):
"""
Return groups that match the specified values.
Returns an empty list if no groups match.
'member' can be an array and is allowed to be a subset of the 'members' array
associated with a group, i.e. if member == ['a', 'b'] and a giv... | f08409c973408742405b5320e43128cafcc56574 | 36,482 |
def btran_helper(eta_list, a):
"""
Helper function for the Btran method.
:param eta_list: Eta vectors list.
:param a: Vector a.
:return: The resulting vector.
"""
if len(eta_list) == 1:
return a.dot(np.linalg.inv(eta_list[0]))
z = btran_helper(eta_list[1:], a)
return z.dot(np... | f10b7e1bf8b143b15521f8db99af8ff3ece8be42 | 36,483 |
from joblib import Parallel, delayed
from psutil import cpu_count
from multiprocessing import cpu_count
from scipy.stats import spearmanr
def permutation_spearman(xvals, yvals, trials=1e5, normalize=True, doparallel=True):
"""
given a list of xvals and yvals, returns a p-value that is
the fraction of the ... | dce8b6f72aa937c62304fe8852f57ad0d2b3cdf8 | 36,484 |
def to_binary(n):
"""Convert integer n to binary form."""
if n == 0:
return zero
elif n == 1:
return one
elif n % 2 == 0:
return bit0(to_binary(n // 2))
else:
return bit1(to_binary(n // 2)) | 6c04e15a9458ca285ab0e73ac27e4a3c7c552699 | 36,485 |
import requests
def get_short_interest_days_to_cover(sort_field: str) -> pd.DataFrame:
"""Get short interest and days to cover. [Source: Stockgrid]
Parameters
----------
sort_field : str
Field for which to sort by, where 'float': Float Short %%,
'dtc': Days to Cover, 'si': Short Inter... | edf8823cb96a31b07b359591337f196b47959583 | 36,486 |
import logging
def with_setup_factory(setup_funcs=(), teardown_funcs=(),
post_initialize=()):
"""Create different kinds of `@with_setup` decorators
to properly initialize and teardown things necessary to run test functions
`setup_funcs` - a list of functions that do things before a... | 80fd54fb63ac494ad727860422a6cf8e6a1d7389 | 36,487 |
def grab_stat_entries(stat_file_name,name):
""" stat_file_name: .stat.h5 file name, name: ex. gofr """
stat_file = h5py.File(stat_file_name)
data = []
# find entry and extract data
for estimator in stat_file.keys():
if estimator != name:
continue
# end if
ent... | ad9a49207a334cbbd791a23b66453ed666e49df5 | 36,488 |
import re
import argparse
def parse_chunksize(size):
"""Parse chunksize argument"""
match = re.fullmatch(r"(\d+)([KMGT]B)?", size)
if match is None:
raise argparse.ArgumentTypeError(
"invalid size value: '{}'".format(size)
)
num, suffix = match.groups("")
return int(num... | 9c3b33e7710cf3b5c5e1075e83733b794a7fbe6a | 36,489 |
def exception_handler(exc, context):
"""
自定义异常处理
"""
# 调用drf框架原生的异常处理方法
response = drf_exception_handler(exc, context)
if response is None:
view = context['view']
if isinstance(exc, DatabaseError) or isinstance(exc, RedisError):
# 数据库异常
logger.error('[%s]... | 5f2b5168f7f87d4cef5055f0620b328e7df63cd6 | 36,490 |
def can_view_email(user, obj=None):
"""
View staff emails or your own.
"""
return obj.is_staff or obj == user | 632412669bc163ce6316a3fd6891ba3930405e8c | 36,491 |
def calculateMatchValueWithRanges(incompleteObject, knownObject):
"""Calculate an integer match value, scoring +1 for each match"""
matchvalue = 0
for catkey, catval in incompleteObject.items():
if (catkey == 'cats' or catkey=='trees'):
if catval > knownObject[catkey]:
ma... | 6f9cf701eca03ee41266d0001da02072072c5191 | 36,492 |
import uu
def relativistic_waveshift(dv, units='km/s'):
"""
Relativistic offset in wavelength
default is dv in km/s
:param dv: float or numpy array, the dv values
:param units: string or astropy units, the units of dv
:return:
"""
# get c in correct units
# noinspection PyUnresolve... | f139eec659c178679a35fe6b18d81d1fd6b91acb | 36,493 |
def divisors(integer):
"""
Create a function named divisors/Divisors that takes an integer n > 1 and returns an array with all of the integer's
divisors(except for 1 and the number itself), from smallest to largest. If the number is prime return the string
'(integer) is prime' (null in C#) (use Either S... | 6fccf9c5ec49f8ddd852b5aad071f187739e5f0b | 36,494 |
def hex_to_binary_str(pdq_hex):
"""
Convert a hexadecimal string to a binary string. Requires input string to be length BITS_IN_PDQ / 4.
"""
assert len(pdq_hex) == BITS_IN_PDQ / 4
# padding to 4 bindigits each hexdigit
result = "".join(bin(int(c, 16))[2:].zfill(4) for c in pdq_hex)
assert le... | 906250590a9c19097babae1c2e8bde088cc94aff | 36,495 |
def hinge_loss(psample, qsample):
"""Point-wise hinge loss."""
loss = tf.nn.relu(1.0 - psample) + tf.nn.relu(1.0 + qsample)
return loss | 4f174601e8fdce5fa65b621de962744e4def2f5c | 36,496 |
from re import L
def l_spin(pdgid):
"""
Returns the orbital angular momentum L as 2L+1.
Notes
-----
- This is valid for mesons only. None is returned otherwise.
- Mesons with PDGIDs of the kind 9XXXXXX (N=9) are not experimentally well-known particles
and None is returned too.
"""
... | 8b5b6c332d7a52655d05f5877cbe101b72926c94 | 36,497 |
def with_metaclass(meta: type, *bases) -> type:
"""Create a base class with a metaclass."""
# This requires a bit of explanation: the basic idea is to make a dummy
# metaclass for one level of class instantiation that replaces itself with
# the actual metaclass.
class metaclass(meta): # type: ignor... | 629e2dce944b4338357843b1233b432257ab1de8 | 36,498 |
from re import A
def mod(a: protocols.SupportsMod[A, B], b: A) -> B:
"""
Return `a % b`, for _a_ and _b_.
Example:
>>> mod(2)(3)
2
Args:
a: left element of % expression
b: right element of % expression
Return:
a modulo b
"""
return a % b | bb6ef1dba0891b9ca5fa54205f86c65faa823513 | 36,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.