max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 7 115 | max_stars_count int64 101 368k | id stringlengths 2 8 | content stringlengths 6 1.03M |
|---|---|---|---|---|
gengine/app/tests_old/test_groups.py | greck2908/gamification-engine | 347 | 6585 | # -*- coding: utf-8 -*-
from gengine.app.tests.base import BaseDBTest
from gengine.app.tests.helpers import create_user, update_user, delete_user, get_or_create_language
from gengine.metadata import DBSession
from gengine.app.model import AuthUser
class TestUserCreation(BaseDBTest):
def test_user_creation(self):... |
mycli/packages/special/main.py | lyrl/mycli | 10,997 | 6604 | <gh_stars>1000+
import logging
from collections import namedtuple
from . import export
log = logging.getLogger(__name__)
NO_QUERY = 0
PARSED_QUERY = 1
RAW_QUERY = 2
SpecialCommand = namedtuple('SpecialCommand',
['handler', 'command', 'shortcut', 'description', 'arg_type', 'hidden',
'case_sensiti... |
torchdrug/layers/flow.py | wconnell/torchdrug | 772 | 6610 | import torch
from torch import nn
from torch.nn import functional as F
from torchdrug import layers
class ConditionalFlow(nn.Module):
"""
Conditional flow transformation from `Masked Autoregressive Flow for Density Estimation`_.
.. _Masked Autoregressive Flow for Density Estimation:
https://arxi... |
smartnlp/utils/basic_log.py | msgi/nlp-tour | 1,559 | 6624 | import logging as log
class Log:
def __init__(self, level):
self.level = level
log.basicConfig(format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s',
level=level)
self.log = log
def info(self, msg):
self.log.info(msg)
de... |
applications/cli/commands/model/tests/test_export.py | nparkstar/nauta | 390 | 6632 | #
# Copyright (c) 2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
var/spack/repos/builtin/packages/py-mdanalysis/package.py | LiamBindle/spack | 2,360 | 6633 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyMdanalysis(PythonPackage):
"""MDAnalysis is a Python toolkit to analyze molecular dynami... |
lib/cherrypy/cherrypy/test/test_sessionauthenticate.py | MiCHiLU/google_appengine_sdk | 790 | 6642 | <gh_stars>100-1000
import cherrypy
from cherrypy.test import helper
class SessionAuthenticateTest(helper.CPWebCase):
def setup_server():
def check(username, password):
# Dummy check_username_and_password function
if username != 'test' or password != 'password':
... |
cmake/utils/gen-ninja-deps.py | stamhe/bitcoin-abc | 1,266 | 6660 | <filename>cmake/utils/gen-ninja-deps.py
#!/usr/bin/env python3
import argparse
import os
import subprocess
parser = argparse.ArgumentParser(description='Produce a dep file from ninja.')
parser.add_argument(
'--build-dir',
help='The build directory.',
required=True)
parser.add_argument(
'--base-dir',
... |
eve/workers/pykmip/bin/run_server.py | mmg-3/cloudserver | 762 | 6668 | #!/usr/bin/env python
# Copyright (c) 2016 The Johns Hopkins University/Applied Physics Laboratory
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.ap... |
tensorflow_quantum/python/differentiators/__init__.py | PyJedi/quantum | 1,501 | 6670 | <gh_stars>1000+
# Copyright 2020 The TensorFlow Quantum Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Un... |
harbor/tests/test_unit.py | tdimnet/integrations-core | 663 | 6689 | # (C) Datadog, Inc. 2019-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import pytest
from mock import MagicMock
from requests import HTTPError
from datadog_checks.base import AgentCheck
from datadog_checks.dev.http import MockResponse
from .common import HARBOR_COMPONENTS, ... |
source/vsm-dashboard/vsm_dashboard/test/test_data/swift_data.py | ramkrsna/virtual-storage-manager | 172 | 6692 | # Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... |
examples/multimedia/mmimdb_MFM.py | kapikantzari/MultiBench | 148 | 6714 | import torch
import sys
import os
sys.path.append(os.getcwd())
from utils.helper_modules import Sequential2
from unimodals.common_models import Linear, MLP, MaxOut_MLP
from datasets.imdb.get_data import get_dataloader
from fusions.common_fusions import Concat
from objective_functions.objectives_for_supervised_learnin... |
test/__init__.py | donbowman/rdflib | 1,424 | 6741 | #
import os
TEST_DIR = os.path.abspath(os.path.dirname(__file__))
|
fine-tune/inference_embedding.py | LinHuiqing/nonparaSeq2seqVC_code | 199 | 6754 | import os
import numpy as np
import torch
import argparse
from hparams import create_hparams
from model import lcm
from train import load_model
from torch.utils.data import DataLoader
from reader import TextMelIDLoader, TextMelIDCollate, id2sp
from inference_utils import plot_data
parser = argparse.ArgumentParser()
p... |
doc/samples/pos.py | m4ta1l/doit | 1,390 | 6821 | def task_pos_args():
def show_params(param1, pos):
print('param1 is: {0}'.format(param1))
for index, pos_arg in enumerate(pos):
print('positional-{0}: {1}'.format(index, pos_arg))
return {'actions':[(show_params,)],
'params':[{'name':'param1',
'shor... |
tests/test_flash_vl.py | andr1976/thermo | 380 | 6832 | <reponame>andr1976/thermo
# -*- coding: utf-8 -*-
'''Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2020, <NAME> <<EMAIL>>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to de... |
tessera-server/tessera/views_api.py | Dimas625/tessera | 379 | 6844 | <reponame>Dimas625/tessera<filename>tessera-server/tessera/views_api.py
# -*- mode:python -*-
import flask
import json
import logging
from datetime import datetime
import inflection
from functools import wraps
from flask import request, url_for
from werkzeug.exceptions import HTTPException
from .client.api.model imp... |
tests/test_metadata_options.py | Fatal1ty/mashumaro | 394 | 6852 | from dataclasses import dataclass, field
from datetime import date, datetime, time, timezone
from pathlib import Path
from typing import Any, Dict, Optional, Union
import ciso8601
import pytest
from mashumaro import DataClassDictMixin
from mashumaro.exceptions import UnserializableField
from mashumaro.types import Se... |
tests/test_dump.py | flaeppe/astunparse | 189 | 6854 | import ast
import re
import sys
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
import astunparse
from tests.common import AstunparseCommonTestCase
class DumpTestCase(AstunparseCommonTestCase, unittest.TestCase):
def assertASTEqual(self, dump1, dump2):
# undo the ... |
test/test_catalog_manager.py | weknowtraining/athena-glue-service-logs | 133 | 6869 | # pylint: skip-file
from athena_glue_service_logs.catalog_manager import BaseCatalogManager
def test_class_init(mocker):
mocker.patch.multiple(BaseCatalogManager, __abstractmethods__=set())
base_catalog = BaseCatalogManager('us-west-2', 'dbname', 'tablename', 's3://somewhere')
assert base_catalog.databas... |
data/benchmark.py | Gummary/denet | 343 | 6896 | <reponame>Gummary/denet
"""
CutBlur
Copyright 2020-present NAVER corp.
MIT license
"""
import os
import glob
import data
class BenchmarkSR(data.BaseDataset):
def __init__(self, phase, opt):
root = opt.dataset_root
self.scale = opt.scale
dir_HQ, dir_LQ = self.get_subdir()
self.HQ_pa... |
nn_dataflow/tests/unit_test/test_network.py | Pingziwalk/nn_dataflow | 170 | 6923 | """ $lic$
Copyright (C) 2016-2020 by Tsinghua University and The Board of Trustees of
Stanford University
This program is free software: you can redistribute it and/or modify it under
the terms of the Modified BSD-3 License as published by the Open Source
Initiative.
This program is distributed in the hope that it wi... |
sympy/solvers/tests/test_pde.py | nashalex/sympy | 8,323 | 6925 | <gh_stars>1000+
from sympy import (Derivative as D, Eq, exp, sin,
Function, Symbol, symbols, cos, log)
from sympy.core import S
from sympy.solvers.pde import (pde_separate, pde_separate_add, pde_separate_mul,
pdsolve, classify_pde, checkpdesol)
from sympy.testing.pytest import raises
a, b, c, x, y = symbols('... |
dataapi/AWS/getawsdata.py | gusamarante/Quantequim | 296 | 6932 | """
Author: <NAME>
"""
import numpy as np
import pandas as pd
from datetime import datetime
class TrackerFeeder(object):
"""
Feeder for the trackers of the FinanceHub database.
"""
def __init__(self, db_connect):
"""
Feeder construction
:param db_connect: sql connection engin... |
diagrams/outscale/__init__.py | analyticsftw/diagrams | 17,037 | 6959 | <reponame>analyticsftw/diagrams<filename>diagrams/outscale/__init__.py
from diagrams import Node
class _Outscale(Node):
_provider = "outscale"
_icon_dir = "resources/outscale"
fontcolor = "#ffffff"
|
deep_qa/layers/wrappers/output_mask.py | richarajpal/deep_qa | 459 | 6962 | <reponame>richarajpal/deep_qa
from overrides import overrides
from ..masked_layer import MaskedLayer
class OutputMask(MaskedLayer):
"""
This Layer is purely for debugging. You can wrap this on a layer's output to get the mask
output by that layer as a model output, for easier visualization of what the m... |
regipy/exceptions.py | kamnon/regipy | 190 | 6997 | class RegipyException(Exception):
"""
This is the parent exception for all regipy exceptions
"""
pass
class RegipyGeneralException(RegipyException):
"""
General exception
"""
pass
class RegistryValueNotFoundException(RegipyException):
pass
class NoRegistrySubkeysException(Regipy... |
histoGAN.py | mahmoudnafifi/HistoGAN | 169 | 7005 | <filename>histoGAN.py
"""
If you find this code useful, please cite our paper:
<NAME>, <NAME>, and <NAME>. "HistoGAN:
Controlling Colors of GAN-Generated and Real Images via Color Histograms."
In CVPR, 2021.
@inproceedings{afifi2021histogan,
title={Histo{GAN}: Controlling Colors of {GAN}-Generated and Real Ima... |
benchmark/python/ffi/benchmark_ffi.py | grygielski/incubator-mxnet | 211 | 7007 | <filename>benchmark/python/ffi/benchmark_ffi.py
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache Licen... |
decatt/model.py | achyudh/castor | 132 | 7043 | import sys
import math
import numpy as np
from datetime import datetime
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class DecAtt(nn.Module):
def __init__(self, num_units, num_classes, embedding_size, dropout, device=0,
training=True, p... |
basic_code/networks.py | J-asy/Emotion-FAN | 275 | 7044 | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
import torch.nn.functional as F
import torch
import numpy as np
import cv2
import pdb
def sigmoid(x):
return 1 / (1 + math.exp(-x))
def norm_angle(angle):
norm_angle = sigmoid(10 * (abs(angle) / 0.7853975 - 1))
return norm_angle
... |
keras_cv_attention_models/resnest/resnest.py | dcleres/keras_cv_attention_models | 140 | 7051 | <reponame>dcleres/keras_cv_attention_models
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import backend as K
from keras_cv_attention_models.aotnet import AotNet
from keras_cv_attention_models.download_and_load import reload_model_weights
from keras_cv_attention_models.attention_layers impo... |
continuum/datasets/dtd.py | oleksost/continuum | 282 | 7055 | <filename>continuum/datasets/dtd.py
import os
from typing import List
import numpy as np
from torchvision import datasets as torchdata
from continuum.datasets import ImageFolderDataset
from continuum import download
from continuum.tasks import TaskType
class DTD(ImageFolderDataset):
"""Describable Textures Data... |
algorithms/maths/chinese_remainder_theorem.py | hbqdev/algorithms | 22,426 | 7072 | <reponame>hbqdev/algorithms<filename>algorithms/maths/chinese_remainder_theorem.py
from algorithms.maths.gcd import gcd
from typing import List
def solve_chinese_remainder(num : List[int], rem : List[int]):
"""
Computes the smallest x that satisfies the chinese remainder theorem
for a system of equations.
... |
exercises/ja/exc_03_16_01.py | Jette16/spacy-course | 2,085 | 7073 | <reponame>Jette16/spacy-course<gh_stars>1000+
import spacy
nlp = spacy.load("ja_core_news_sm")
text = (
"チックフィレイはジョージア州カレッジパークに本社を置く、"
"チキンサンドを専門とするアメリカのファストフードレストランチェーンです。"
)
# トークナイズのみ行う
doc = nlp(text)
print([token.text for token in doc])
|
webium/controls/select.py | kejkz/webium | 152 | 7104 | from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.remote.webelement import WebElement
class Select(WebElement):
"""
Implements logic to work with Web List UI elements
"""
@property
def is_multiple(self):
value = self.get_attribute('multiple')
re... |
mindarmour/utils/logger.py | hboshnak/mindarmour | 139 | 7125 | # Copyright 2019 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
src/wormhole/__main__.py | dmgolembiowski/magic-wormhole | 2,801 | 7139 | from __future__ import absolute_import, print_function, unicode_literals
if __name__ == "__main__":
from .cli import cli
cli.wormhole()
else:
# raise ImportError('this module should not be imported')
pass
|
apex/contrib/multihead_attn/self_multihead_attn_func.py | Muflhi01/apex | 6,523 | 7148 | import torch
import torch.nn.functional as F
class SelfAttnFunc(torch.autograd.Function):
@staticmethod
def forward(
ctx,
use_time_mask,
is_training,
heads,
scale,
inputs,
input_weights,
output_weights,
input_biases,
output_biases... |
tests/test_app/library/loans/admin.py | Pijuli/django-jazzmin | 972 | 7154 | <gh_stars>100-1000
from django.contrib import admin
from django.urls import path
from .models import BookLoan, Library
from .views import CustomView
class BookLoanInline(admin.StackedInline):
model = BookLoan
extra = 1
readonly_fields = ("id", "duration")
fields = (
"book",
"imprint",... |
test/sanity_import_vpp_papi.py | amithbraj/vpp | 751 | 7162 | #!/usr/bin/env python3
""" sanity check script """
import vpp_papi
|
src/trusted/validator_arm/dgen_decoder_output.py | cohortfsllc/cohort-cocl2-sandbox | 2,151 | 7191 | <filename>src/trusted/validator_arm/dgen_decoder_output.py
#!/usr/bin/python
#
# Copyright (c) 2012 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
"""
Responsible for generating the decoder based on parsed
table re... |
logistic-regression/plot_binary_losses.py | eliben/deep-learning-samples | 183 | 7203 | # Helper code to plot binary losses.
#
# <NAME> (http://eli.thegreenplace.net)
# This code is in the public domain
from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np
if __name__ == '__main__':
fig, ax = plt.subplots()
fig.set_tight_layout(True)
xs = np.linspace(-2, 2... |
shapeshifter/tests/conftest.py | martinogden/django-shapeshifter | 164 | 7206 | <filename>shapeshifter/tests/conftest.py
from pytest_djangoapp import configure_djangoapp_plugin
pytest_plugins = configure_djangoapp_plugin(
extend_INSTALLED_APPS=[
'django.contrib.sessions',
'django.contrib.messages',
],
extend_MIDDLEWARE=[
'django.contrib.sessions.middleware.Sess... |
tests/zoo/tree.py | dynalz/odmantic | 486 | 7220 | <reponame>dynalz/odmantic
import enum
from typing import Dict, List
from odmantic.field import Field
from odmantic.model import Model
class TreeKind(str, enum.Enum):
BIG = "big"
SMALL = "small"
class TreeModel(Model):
name: str = Field(primary_key=True, default="<NAME> montagnes")
average_size: flo... |
examples/model_zoo/build_binaries.py | Embracing/unrealcv | 1,617 | 7226 | import subprocess, os
ue4_win = r"C:\Program Files\Epic Games\UE_4.16"
ue4_linux = "/home/qiuwch/workspace/UE416"
ue4_mac = '/Users/Shared/Epic Games/UE_4.16'
win_uprojects = [
r'C:\qiuwch\workspace\uprojects\UE4RealisticRendering\RealisticRendering.uproject',
r'C:\qiuwch\workspace\uprojects\UE4ArchinteriorsV... |
rigl/experimental/jax/pruning/pruning.py | vishalbelsare/rigl | 276 | 7229 | <filename>rigl/experimental/jax/pruning/pruning.py
# coding=utf-8
# Copyright 2021 RigL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE... |
snoopy/server/transforms/Maltego.py | aiddenkeli/Snoopy | 432 | 7254 | #!/usr/bin/python
#
# This might be horrible code...
# ...but it works
# Feel free to re-write in a better way
# And if you want to - send it to us, we'll update ;)
# <EMAIL> (2010/10/18)
#
import sys
from xml.dom import minidom
class MaltegoEntity(object):
value = "";
weight = 100;
displayInformation = "";
addit... |
tests/conftest.py | bbhunter/fuzz-lightyear | 169 | 7277 | import pytest
from fuzz_lightyear.datastore import _ALL_POST_FUZZ_HOOKS_BY_OPERATION
from fuzz_lightyear.datastore import _ALL_POST_FUZZ_HOOKS_BY_TAG
from fuzz_lightyear.datastore import _RERUN_POST_FUZZ_HOOKS_BY_OPERATION
from fuzz_lightyear.datastore import _RERUN_POST_FUZZ_HOOKS_BY_TAG
from fuzz_lightyear.datastore... |
src/tests/test_stop_at_task.py | francesco-p/FACIL | 243 | 7289 | <filename>src/tests/test_stop_at_task.py
from tests import run_main_and_assert
FAST_LOCAL_TEST_ARGS = "--exp-name local_test --datasets mnist" \
" --network LeNet --num-tasks 5 --seed 1 --batch-size 32" \
" --nepochs 2 --num-workers 0 --stop-at-task 3"
def test_finetunin... |
Python/contains-duplicate.py | shreyventure/LeetCode-Solutions | 388 | 7290 | <gh_stars>100-1000
# Autor: <NAME> (@optider)
# Github Profile: https://github.com/Optider/
# Problem Link: https://leetcode.com/problems/contains-duplicate/
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
count = {}
for n in nums :
if count.get(n) != None :
... |
build/android/gyp/dex.py | google-ar/chromium | 2,151 | 7291 | #!/usr/bin/env python
#
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import json
import logging
import optparse
import os
import sys
import tempfile
import zipfile
from util import build_utils
def _C... |
tests/test_utils_log.py | FingerCrunch/scrapy | 41,267 | 7298 | import sys
import logging
import unittest
from testfixtures import LogCapture
from twisted.python.failure import Failure
from scrapy.utils.log import (failure_to_exc_info, TopLevelFormatter,
LogCounterHandler, StreamLogger)
from scrapy.utils.test import get_crawler
from scrapy.extensions... |
demoproject/demoproject/urls.py | alvnary18/django-nvd3 | 302 | 7305 | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^piechart/', views.demo_piechart, name='demo_piechart'),
url(r'^linechart/', views.demo_linechart, name='demo_linechart'),
url(r'^linechart_without_date/', views.demo_linechart_without_date,... |
src/gui/tcltk/tcl/tests/langbench/proc.py | gspu/bitkeeper | 342 | 7344 | <reponame>gspu/bitkeeper<filename>src/gui/tcltk/tcl/tests/langbench/proc.py
#!/usr/bin/python
def a(val):
return b(val)
def b(val):
return c(val)
def c(val):
return d(val)
def d(val):
return e(val)
def e(val):
return f(val)
def f(val):
return g(val, 2)
def g(v1, v2):
return h(v1, v2, 3)
def h(v1, v2, v3):
r... |
azure-devops/azext_devops/test/common/test_format.py | doggy8088/azure-devops-cli-extension | 326 | 7349 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
tests/attr/test_kernel_shap.py | trsvchn/captum | 3,140 | 7398 | <filename>tests/attr/test_kernel_shap.py
#!/usr/bin/env python3
import io
import unittest
import unittest.mock
from typing import Any, Callable, List, Tuple, Union
import torch
from captum._utils.typing import BaselineType, TensorOrTupleOfTensorsGeneric
from captum.attr._core.kernel_shap import KernelShap
from tests.... |
tests/test_utils_obj_value.py | ZSD-tim/dayu_widgets | 157 | 7412 | <reponame>ZSD-tim/dayu_widgets
"""
Test get_obj_value set_obj_value has_obj_value
"""
import pytest
from dayu_widgets import utils
class _HasNameAgeObject(object):
def __init__(self, name, age):
super(_HasNameAgeObject, self).__init__()
self.name = name
self.age = age
@pytest.mark.parame... |
desktop/core/ext-py/PyYAML-3.12/tests/lib3/test_all.py | kokosing/hue | 5,079 | 7413 |
import sys, yaml, test_appliance
def main(args=None):
collections = []
import test_yaml
collections.append(test_yaml)
if yaml.__with_libyaml__:
import test_yaml_ext
collections.append(test_yaml_ext)
return test_appliance.run(collections, args)
if __name__ == '__main__':
main()... |
pajbot/apiwrappers/authentication/access_token.py | JoachimFlottorp/pajbot | 128 | 7447 | <gh_stars>100-1000
import datetime
from abc import ABC, abstractmethod
import pajbot
class AccessToken(ABC):
SHOULD_REFRESH_THRESHOLD = 0.9
"""Fraction between 0 and 1 indicating what fraction/percentage of the specified full validity period
should actually be utilized. E.g. if this is set to 0.9, the i... |
matchzoo/metrics/precision.py | ChrisRBXiong/MatchZoo-py | 468 | 7467 | <filename>matchzoo/metrics/precision.py
"""Precision for ranking."""
import numpy as np
from matchzoo.engine.base_metric import (
BaseMetric, sort_and_couple, RankingMetric
)
class Precision(RankingMetric):
"""Precision metric."""
ALIAS = 'precision'
def __init__(self, k: int = 1, threshold: float ... |
tests/test_table/test_pivot.py | andriyor/agate | 663 | 7503 | <gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf8 -*-
import sys
try:
from cdecimal import Decimal
except ImportError: # pragma: no cover
from decimal import Decimal
from agate import Table
from agate.aggregations import Sum
from agate.computations import Percent
from agate.data_types import Numbe... |
utils/data/dataset_catalog.py | rs9899/Parsing-R-CNN | 289 | 7538 | <gh_stars>100-1000
import os.path as osp
# Root directory of project
ROOT_DIR = osp.abspath(osp.join(osp.dirname(__file__), '..', '..'))
# Path to data dir
_DATA_DIR = osp.abspath(osp.join(ROOT_DIR, 'data'))
# Required dataset entry keys
_IM_DIR = 'image_directory'
_ANN_FN = 'annotation_file'
# Available datasets
C... |
sdk/python/pulumi_gcp/accesscontextmanager/service_perimeter.py | sisisin/pulumi-gcp | 121 | 7549 | <gh_stars>100-1000
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, over... |
selfdrive/boardd/tests/test_boardd_api.py | 919bot/Tessa | 114 | 7563 | <reponame>919bot/Tessa
import random
import numpy as np
import selfdrive.boardd.tests.boardd_old as boardd_old
import selfdrive.boardd.boardd as boardd
from common.realtime import sec_since_boot
from cereal import log
import unittest
def generate_random_can_data_list():
can_list = []
cnt = random.randint(1, 64)... |
saleor/product/migrations/0141_update_descritpion_fields.py | fairhopeweb/saleor | 15,337 | 7586 | # Generated by Django 3.1.5 on 2021-02-17 11:04
from django.db import migrations
import saleor.core.db.fields
import saleor.core.utils.editorjs
def update_empty_description_field(apps, schema_editor):
Category = apps.get_model("product", "Category")
CategoryTranslation = apps.get_model("product", "CategoryT... |
torch/_VF.py | Hacky-DH/pytorch | 60,067 | 7588 | """
This makes the functions in torch._C._VariableFunctions available as
torch._VF.<funcname>
without mypy being able to find them.
A subset of those functions are mapped to ATen functions in
torch/jit/_builtins.py
See https://github.com/pytorch/pytorch/issues/21478 for the reason for
introducing torch._VF
"""
i... |
transformers/tests/tokenization_xlnet_test.py | deepbluesea/transformers | 270 | 7616 | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... |
docker_squash/version.py | pombredanne/docker-scripts | 513 | 7622 | <reponame>pombredanne/docker-scripts
version = "1.0.10.dev0"
|
Algo and DSA/LeetCode-Solutions-master/Python/smallest-greater-multiple-made-of-two-digits.py | Sourav692/FAANG-Interview-Preparation | 3,269 | 7656 | # Time: sum(O(l * 2^l) for l in range(1, 11)) = O(20 * 2^10) = O(1)
# Space: O(1)
class Solution(object):
def findInteger(self, k, digit1, digit2):
"""
:type k: int
:type digit1: int
:type digit2: int
:rtype: int
"""
MAX_NUM_OF_DIGITS = 10
INT_MAX = ... |
turbo_transformers/python/tests/__init__.py | xcnick/TurboTransformers | 1,147 | 7658 | <gh_stars>1000+
# Copyright (C) 2020 THL A29 Limited, a Tencent company.
# All rights reserved.
# Licensed under the BSD 3-Clause License (the "License"); you may
# not use this file except in compliance with the License. You may
# obtain a copy of the License at
# https://opensource.org/licenses/BSD-3-Clause
# Unless ... |
lmdb/cffi.py | hirnimeshrampuresoftware/py-lmdb | 185 | 7683 | <reponame>hirnimeshrampuresoftware/py-lmdb
#
# Copyright 2013 The py-lmdb authors, all rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted only as authorized by the OpenLDAP
# Public License.
#
# A copy of this license is available in the file LICENSE in... |
test_scripts/pyfora2/containerTests.py | ufora/ufora | 571 | 7686 | # Copyright 2015 Ufora Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
tests/functional/controllers/test_group_controller_superuser.py | roscisz/TensorHive | 129 | 7762 | <filename>tests/functional/controllers/test_group_controller_superuser.py<gh_stars>100-1000
from tensorhive.models.Group import Group
from fixtures.controllers import API_URI as BASE_URI, HEADERS
from http import HTTPStatus
from importlib import reload
import json
import auth_patcher
ENDPOINT = BASE_URI + '/groups'
... |
test/mitmproxy/addons/test_proxyserver.py | KarlParkinson/mitmproxy | 24,939 | 7769 | <reponame>KarlParkinson/mitmproxy
import asyncio
from contextlib import asynccontextmanager
import pytest
from mitmproxy import exceptions
from mitmproxy.addons.proxyserver import Proxyserver
from mitmproxy.connection import Address
from mitmproxy.proxy import layers, server_hooks
from mitmproxy.proxy.layers.http imp... |
evennia/scripts/migrations/0013_auto_20191025_0831.py | Jaykingamez/evennia | 1,544 | 7773 | # Generated by Django 2.2.6 on 2019-10-25 12:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("scripts", "0012_auto_20190128_1820")]
operations = [
migrations.AlterField(
model_name="scriptdb",
name="db_typeclass_path",
... |
tests/test_pyqrcodeng_issue13.py | dbajar/segno | 254 | 7774 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2016 - 2020 -- <NAME>
# All rights reserved.
#
# License: BSD License
#
"""\
Test against issue <https://github.com/pyqrcode/pyqrcodeNG/pull/13/>.
The initial test was created by Mathieu <https://github.com/albatros69>,
see the above mentioned pull request.
Adapted for Segno ... |
osp/test/corpus/syllabus/test_text.py | davidmcclure/open-syllabus-project | 220 | 7787 | <reponame>davidmcclure/open-syllabus-project<gh_stars>100-1000
from osp.corpus.syllabus import Syllabus
from osp.test.utils import requires_tika
def test_empty(mock_osp):
"""
Should return None if the file is empty.
"""
path = mock_osp.add_file(content='', ftype='plain')
syllabus = Syllabus(pa... |
examples/hello-pt/custom/cifar10validator.py | ArnovanHilten/NVFlare | 155 | 7830 | # Copyright (c) 2021, NVIDIA CORPORATION.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
api-reference-examples/python/te-tag-query/api-example-update.py | b-bold/ThreatExchange | 997 | 7862 | #!/usr/bin/env python
# ================================================================
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# ================================================================
import sys
import json
import TE
TE.Net.setAppTokenFromEnvName("TX_ACCESS_TOKEN")
postPar... |
aliyun-python-sdk-ehpc/aliyunsdkehpc/request/v20180412/EditJobTemplateRequest.py | yndu13/aliyun-openapi-python-sdk | 1,001 | 7866 | <gh_stars>1000+
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"... |
machine_learning/deep_reinforcement_learning_grasping/drlgrasp/drlgrasp/pybullet_envs/kuka_reach_with_visual.py | Hinson-A/guyueclass | 227 | 7885 | import pybullet as p
import pybullet_data
import gym
from gym import spaces
from gym.utils import seeding
import numpy as np
from math import sqrt
import random
import time
import math
import cv2
import torch
import os
def random_crop(imgs, out):
"""
args:
imgs: shape (B,C,H,W)
... |
mne/io/cnt/tests/test_cnt.py | stevemats/mne-python | 1,953 | 7899 |
# Author: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# License: BSD-3-Clause
import os.path as op
import numpy as np
from numpy.testing import assert_array_equal
import pytest
from mne import pick_types
from mne.datasets import testing
from mne.io.tests.test_raw import _test_raw_reader
from mne.io.cnt import rea... |
packages/pyright-internal/src/tests/samples/unnecessaryCast1.py | sasano8/pyright | 4,391 | 7933 | # This sample tests the type checker's reportUnnecessaryCast feature.
from typing import cast, Union
def foo(a: int):
# This should generate an error if
# reportUnnecessaryCast is enabled.
b = cast(int, a)
c: Union[int, str] = "hello"
d = cast(int, c)
|
tests/ut/python/parallel/test_manual_gatherv2.py | PowerOlive/mindspore | 3,200 | 7938 | # Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
ClemBot.Bot/bot/api/tag_route.py | makayla-moster/ClemBot | 121 | 7939 | <gh_stars>100-1000
from bot.api.api_client import ApiClient
from bot.api.base_route import BaseRoute
import typing as t
from bot.models import Tag
class TagRoute(BaseRoute):
def __init__(self, api_client: ApiClient):
super().__init__(api_client)
async def create_tag(self, name: str, content: str, g... |
openfermioncirq/variational/ansatzes/swap_network_trotter_hubbard_test.py | unpilbaek/OpenFermion-Cirq | 278 | 7955 | <filename>openfermioncirq/variational/ansatzes/swap_network_trotter_hubbard_test.py
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
... |
targets/baremetal-sdk/curie-bsp/setup.py | ideas-detoxes/jerryscript | 4,324 | 7984 | #!/usr/bin/env python
# Copyright JS Foundation and other contributors, http://js.foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.... |
example/dec/dec.py | TheBurningCrusade/A_mxnet | 159 | 7991 | # pylint: skip-file
import sys
import os
# code to automatically download dataset
curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
sys.path = [os.path.join(curr_path, "../autoencoder")] + sys.path
import mxnet as mx
import numpy as np
import data
from scipy.spatial.distance import cdist
from s... |
telemetry/telemetry/testing/internal/fake_gpu_info.py | tingshao/catapult | 2,151 | 8008 | <reponame>tingshao/catapult<filename>telemetry/telemetry/testing/internal/fake_gpu_info.py
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# This dictionary of GPU information was captured from a run of
# ... |
src/vulnix/nvd.py | dermetfan/vulnix | 217 | 8012 | <filename>src/vulnix/nvd.py
from BTrees import OOBTree
from datetime import datetime, date, timedelta
from persistent import Persistent
from .vulnerability import Vulnerability
import fcntl
import glob
import gzip
import json
import logging
import os
import os.path as p
import requests
import transaction
import ZODB
im... |
autoindent_code_JASS_war3map_j.py | gil9red/SimplePyScripts | 117 | 8016 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
import re
DEBUG = False
def merge_str_literal(text: str) -> str:
def _on_match(m: re.Match):
return m.group().replace('"+"', '')
return re.sub(r'".+?"(\+".+?")+ ', _on_match, text)
lines = """
function II1I1_II takes real I... |
fmpy/cswrapper/__init__.py | CSchulzeTLK/FMPy | 225 | 8023 | <reponame>CSchulzeTLK/FMPy
def add_cswrapper(filename, outfilename=None):
from fmpy import read_model_description, extract, sharedLibraryExtension, platform, __version__
from lxml import etree
import os
from shutil import copyfile, rmtree
if outfilename is None:
outfilename = filename
... |
test/dict_parameter_test.py | shouldsee/luigi | 14,755 | 8024 | <gh_stars>1000+
# -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
tests/test_sentiments.py | rajeshkumargp/TextBlob | 6,608 | 8073 | <reponame>rajeshkumargp/TextBlob
from __future__ import unicode_literals
import unittest
from nose.tools import * # PEP8 asserts
from nose.plugins.attrib import attr
from textblob.sentiments import PatternAnalyzer, NaiveBayesAnalyzer, DISCRETE, CONTINUOUS
class TestPatternSentiment(unittest.TestCase):
def setU... |
tests/scripts/thread-cert/test_network_layer.py | AdityaHPatwardhan/openthread | 2,962 | 8076 | <gh_stars>1000+
#!/usr/bin/env python3
#
# Copyright (c) 2016, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the abov... |
salt/modules/kernelpkg_linux_apt.py | markgras/salt | 9,425 | 8077 | <filename>salt/modules/kernelpkg_linux_apt.py
"""
Manage Linux kernel packages on APT-based systems
"""
import functools
import logging
import re
try:
from salt.utils.versions import LooseVersion as _LooseVersion
from salt.exceptions import CommandExecutionError
HAS_REQUIRED_LIBS = True
except ImportErro... |
src/hammer-vlsi/technology/sky130/sram_compiler/__init__.py | httpsgithu/hammer | 138 | 8084 | <reponame>httpsgithu/hammer
import os, tempfile, subprocess
from hammer_vlsi import MMMCCorner, MMMCCornerType, HammerTool, HammerToolStep, HammerSRAMGeneratorTool, SRAMParameters
from hammer_vlsi.units import VoltageValue, TemperatureValue
from hammer_tech import Library, ExtraLibrary
from typing import NamedTuple, ... |
nemo/collections/tts/torch/data.py | MalikIdreesHasanKhan/NeMo | 4,145 | 8088 | # Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.