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 |
|---|---|---|---|---|
dmb/visualization/stereo/sparsification_plot.py | jiaw-z/DenseMatchingBenchmark | 160 | 11197215 | <gh_stars>100-1000
import warnings
import numpy as np
import torch
def mask_to_neg(x, mask):
# if mask=1, keep x, if mask=0, convert x to -1
x = x * mask + (mask - 1)
return x
def norm(x):
x = x / (x.max() - x.min())
# scale x to [0.05, 0.9] for counting convenient, it doesn't influence the fi... |
alipay/aop/api/domain/AlipayEcoMycarMaintainAftersaleSyncModel.py | snowxmas/alipay-sdk-python-all | 213 | 11197233 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayEcoMycarMaintainAftersaleSyncModel(object):
def __init__(self):
self._aftersale_no = None
self._refuse_reason = None
self._status = None
@property
def after... |
objectModel/Python/cdm/persistence/modeljson/argument_persistence.py | rt112000/CDM | 884 | 11197237 | <gh_stars>100-1000
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
from typing import Optional, TYPE_CHECKING
from cdm.enums import CdmObjectType
from .types import Annotation
if TYPE_CHECKING:
from cdm.o... |
compiler_gym/bin/validate.py | sahirgomez1/CompilerGym | 562 | 11197256 | <filename>compiler_gym/bin/validate.py<gh_stars>100-1000
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Validate environment states.
Example usage:
.. code-block::
$ cat << EOF |
... |
seahub/group/urls.py | weimens/seahub | 420 | 11197257 | # Copyright (c) 2012-2016 Seafile Ltd.
from django.conf.urls import url
from .views import group_remove
urlpatterns = [
url(r'^(?P<group_id>\d+)/remove/$', group_remove, name='group_remove'),
]
|
tests/conftest.py | vishalbelsare/voila-gridstack | 181 | 11197267 | <gh_stars>100-1000
import os
import voila.app
import pytest
BASE_DIR = os.path.dirname(__file__)
class VoilaTest(voila.app.Voila):
def listen(self):
pass # the ioloop is taken care of by the pytest-tornado framework
@pytest.fixture
def voila_app(voila_args, voila_config):
voila_app = VoilaTest.ins... |
convlab/modules/usr/multiwoz/vhus_usr/usermodule.py | ngduyanhece/ConvLab | 405 | 11197282 | <reponame>ngduyanhece/ConvLab
# Modified by Microsoft Corporation.
# Licensed under the MIT license.
# -*- coding: utf-8 -*-
from allennlp.modules import Attention
import random
import numpy as np
import torch
import torch.nn as nn
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def reparamet... |
angr/procedures/win32/system_paths.py | Kyle-Kyle/angr | 6,132 | 11197292 | import angr
import claripy
class GetTempPathA(angr.SimProcedure):
RESULT = claripy.BVV(b"C:\\Temp\\")
def run(self, nBufferLength, lpBuffer):
try:
length = self.state.solver.eval_one(nBufferLength)
except angr.errors.SimValueError:
raise angr.errors.SimProcedureError("C... |
inter/GetQueueCountAsync.py | middleprince/12306 | 33,601 | 11197308 | import TickerConfig
[]# coding=utf-8
import datetime
import sys
import time
from collections import OrderedDict
import wrapcache
from inter.ConfirmSingleForQueueAsys import confirmSingleForQueueAsys
class getQueueCountAsync:
"""
排队
"""
def __init__(self,
session,
t... |
Bio/PopGen/GenePop/EasyController.py | lukasz-kozlowski/biopython | 2,856 | 11197321 | <filename>Bio/PopGen/GenePop/EasyController.py
# Copyright 2009 by <NAME> <<EMAIL>>. All rights reserved.
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included as... |
neo/rawio/neuralynxrawio/ncssections.py | yger/python-neo | 199 | 11197387 | <filename>neo/rawio/neuralynxrawio/ncssections.py
import math
class NcsSections:
"""
Contains information regarding the contiguous sections of records in an Ncs file.
Methods of NcsSectionsFactory perform parsing of this information from an Ncs file and
produce these where the sections are discontiguo... |
graphgallery/nn/models/pytorch/graphat/utils.py | EdisonLeeeee/GraphGallery | 300 | 11197442 | <gh_stars>100-1000
import torch.nn.functional as F
def get_normalized_vector(d):
d = d / (1e-12 + d.abs().max(dim=1).values.view(-1, 1))
d = d / (1e-6 + d.pow(2.0).sum(dim=1).view(-1, 1))
return d
def kld_with_logits(logit_q, logit_p):
q = F.softmax(logit_q, dim=-1)
cross_entropy = so... |
cbox/__main__.py | shmuelamar/cbox | 164 | 11197445 | <gh_stars>100-1000
import argparse
import ast
import sys
from sys import stdin, stdout, stderr
import cbox
from cbox import concurrency
__all__ = ('get_inline_func', 'main', )
def _inline2func(inline_str, inline_globals, **stream_kwargs):
if stream_kwargs.get('worker_type') != concurrency.ASYNCIO:
@cbox... |
idaes/generic_models/properties/core/eos/tests/test_enrtl_verification_2_solvent.py | carldlaird/idaes-pse | 112 | 11197451 | <reponame>carldlaird/idaes-pse<filename>idaes/generic_models/properties/core/eos/tests/test_enrtl_verification_2_solvent.py
#################################################################################
# The Institute for the Design of Advanced Energy Systems Integrated Platform
# Framework (IDAES IP) was produced ... |
kivy/tools/packaging/cython_cfg.py | Galland/kivy | 13,889 | 11197453 | import configparser
from os.path import join, dirname
import textwrap
__all__ = ('get_cython_versions', 'get_cython_msg')
def get_cython_versions(setup_cfg=''):
_cython_config = configparser.ConfigParser()
if setup_cfg:
_cython_config.read(setup_cfg)
else:
_cython_config.read(
... |
astropy/modeling/setup_package.py | jayvdb/astropy | 445 | 11197459 | <reponame>jayvdb/astropy
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import os
from os.path import join
from distutils.core import Extension
from distutils import log
from astropy_helpers import setup_helpers, utils
from astropy_helpers.version_helpers import get_pkg_version_module
wcs_setup_pac... |
external/deep-object-reid/tests/sc_input_params_validation/test_ote_inference_task_input_params_validation.py | opencv/openvino_training_extensions | 775 | 11197483 | import pytest
from ote_sdk.configuration.configurable_parameters import ConfigurableParameters
from ote_sdk.entities.datasets import DatasetEntity
from ote_sdk.entities.inference_parameters import InferenceParameters
from ote_sdk.entities.label_schema import LabelSchemaEntity
from ote_sdk.entities.model import ModelCon... |
heron/tools/explorer/src/python/physicalplan.py | pjfanning/incubator-heron | 3,348 | 11197487 | <reponame>pjfanning/incubator-heron
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
# 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... |
neuralprophet/configure.py | yasirroni/neural_prophet | 2,144 | 11197502 | <filename>neuralprophet/configure.py
from collections import OrderedDict
from dataclasses import dataclass, field
import numpy as np
import pandas as pd
import logging
import inspect
import torch
import math
from neuralprophet import utils_torch, utils
log = logging.getLogger("NP.config")
def from_kwargs(cls, kwarg... |
fastrunner/utils/parser.py | FuxiongYang/faster | 227 | 11197526 | <reponame>FuxiongYang/faster<gh_stars>100-1000
import datetime
import json
import json5
import time
import requests
from tornado import ioloop, httpclient
from enum import Enum
from loguru import logger
from fastrunner import models
from fastrunner.utils.tree import get_tree_max_id, get_all_ycatid, get_tree_ycatid_... |
tests/samplers/test_frequency.py | heureka-labs/pyRDF2Vec | 154 | 11197531 | <reponame>heureka-labs/pyRDF2Vec<gh_stars>100-1000
import itertools
import pytest
from pyrdf2vec.graphs import KG, Vertex
from pyrdf2vec.samplers import ( # isort: skip
ObjFreqSampler,
ObjPredFreqSampler,
PredFreqSampler,
)
LOOP = [
["Alice", "knows", "Bob"],
["Alice", "knows", "Dean"],
["B... |
src/MoveNode.py | L4xus/termux-chess | 302 | 11197546 | class MoveNode:
def __init__(self, move, children, parent):
self.move = move
self.children = children
self.parent = parent
self.pointAdvantage = None
self.depth = 1
def __str__(self):
stringRep = "Move : " + str(self.move) + \
" Point advanta... |
tests/layer_tests/onnx_tests/test_transpose.py | pazamelin/openvino | 2,406 | 11197574 | # Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import itertools
import numpy as np
import pytest
from common.onnx_layer_test_class import Caffe2OnnxLayerTest
class TestTranspose(Caffe2OnnxLayerTest):
def create_net(self, shape, perm, ir_version):
"""
ONNX n... |
test-framework/test-suites/integration/tests/list/test_list_host_attr.py | sammeidinger/stack | 123 | 11197580 | import json
from operator import itemgetter
import os
from itertools import groupby
class TestListHostAttr:
def test_invalid(self, host):
result = host.run('stack list host attr test')
assert result.rc == 255
assert result.stderr.startswith('error - ')
def test_no_args_frontend_only(self, host):
result = h... |
torchkit/version.py | kevinzakka/torchkit | 144 | 11197582 | """Version file will be exec'd by setup.py and imported by __init__.py"""
# Semantic versioning.
_MAJOR_VERSION = "0"
_MINOR_VERSION = "0"
_PATCH_VERSION = "3"
__version__ = ".".join([_MAJOR_VERSION, _MINOR_VERSION, _PATCH_VERSION])
|
tests/framework/MCMC/likelihoods/likelihood_10D.py | rinelson456/raven | 159 | 11197593 | # Copyright 2017 Battelle Energy Alliance, LLC
#
# 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 t... |
examples/ports/multi_receive.py | fooker/mido | 658 | 11197609 | <filename>examples/ports/multi_receive.py
#!/usr/bin/env python
"""
Receive messages from multiple ports.
"""
import mido
from mido.ports import multi_receive
# Open all available inputs.
ports = [mido.open_input(name) for name in mido.get_input_names()]
for port in ports:
print('Using {}'.format(port))
print('Wai... |
dfirtrack_main/tests/note/test_note_views.py | stuhli/dfirtrack | 273 | 11197630 | <reponame>stuhli/dfirtrack<filename>dfirtrack_main/tests/note/test_note_views.py
import urllib.parse
from django.contrib.auth.models import User
from django.test import TestCase
from dfirtrack_main.models import (
Case,
Casepriority,
Casestatus,
Note,
Notestatus,
Tag,
Tagcolor,
)
class N... |
RecoJets/JetAnalyzers/test/runL2L3JetCorrectionOnTheFly_cfg.py | ckamtsikis/cmssw | 852 | 11197644 | # PYTHON configuration file for class: JetCorExample
# Description: Example of simple EDAnalyzer for correcting jets on the fly.
# Author: <NAME>
# Date: 02 - September - 2009
import FWCore.ParameterSet.Config as cms
process = cms.Process("Ana")
process.load("FWCore.MessageService.MessageLogger_cfi")
############# ... |
casbin/persist/adapters/update_adapter.py | abichinger/pycasbin | 915 | 11197651 | <gh_stars>100-1000
class UpdateAdapter:
"""UpdateAdapter is the interface for Casbin adapters with add update policy function."""
def update_policy(self, sec, ptype, old_rule, new_policy):
"""
update_policy updates a policy rule from storage.
This is part of the Auto-Save feature.
... |
leetcode.com/python/681_Next_Closest_Time.py | vansh-tiwari/coding-interview-gym | 713 | 11197652 | <filename>leetcode.com/python/681_Next_Closest_Time.py<gh_stars>100-1000
import bisect
# My initial solution. Not correct solution
class Solution(object):
def nextClosestTime(self, time):
"""
:type time: str
:rtype: str
"""
digits = list(time)
digits.pop(2)
s... |
ansible/roles/lib_gcloud/build/ansible/gcloud_dm_deployments.py | fahlmant/openshift-tools | 164 | 11197683 | <reponame>fahlmant/openshift-tools<gh_stars>100-1000
# pylint: skip-file
# vim: expandtab:tabstop=4:shiftwidth=4
#pylint: disable=too-many-branches
def main():
''' ansible module for gcloud deployment-manager deployments '''
module = AnsibleModule(
argument_spec=dict(
# credentials
... |
tests/test_download.py | pmaciel/climetlab | 182 | 11197701 | #!/usr/bin/env python3
# (C) Copyright 2020 ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its statu... |
orttraining/tools/scripts/pipeline_model_split.py | mszhanyi/onnxruntime | 669 | 11197706 | <reponame>mszhanyi/onnxruntime<filename>orttraining/tools/scripts/pipeline_model_split.py
import sys
import os
import onnx
from onnx import helper
from onnx import TensorProto
from onnx import OperatorSetIdProto
# Edge that needs to be cut for the split.
# If the edge is feeding into more than one nodes, and not all t... |
bowtie/_app.py | timgates42/bowtie | 813 | 11197714 | <filename>bowtie/_app.py
"""Defines the App class."""
from typing import ( # pylint: disable=unused-import
Any,
Callable,
Generator,
List,
Optional,
Set,
Tuple,
Union,
Dict,
Sequence,
)
import os
import json
import itertools
import shutil
from collections import namedtuple, def... |
snorkel/utils/lr_schedulers.py | melonwater211/snorkel | 2,323 | 11197719 | from snorkel.types import Config
class ExponentialLRSchedulerConfig(Config):
"""Settings for Exponential decay learning rate scheduler."""
gamma: float = 0.9
class StepLRSchedulerConfig(Config):
"""Settings for Step decay learning rate scheduler."""
gamma: float = 0.9
step_size: int = 5
clas... |
train/v4/vqa_data_provider_layer.py | minsuu/vqa_mcb | 214 | 11197752 | <reponame>minsuu/vqa_mcb
import caffe
import numpy as np
import re, json, random
import config
QID_KEY_SEPARATOR = '/'
class VQADataProvider:
def __init__(self, batchsize=64, max_length=15, mode='train'):
self.batchsize = batchsize
self.d_vocabulary = None
self.batch_index = None
... |
lib/bindings/samples/server/test/test_project_manager.py | tlalexander/stitchEm | 182 | 11197754 | <reponame>tlalexander/stitchEm
import unittest
import vs
from project_manager import ProjectManager
from utils.settings_manager import SETTINGS
TEST_PTV_FILEPATH = "./test_data/procedural-4K-nvenc.ptv"
TEST_PTV_SAVEPATH = "./test_data/project_manager_save.ptv"
class TestProjectManager(unittest.TestCase):
def set... |
modules/audio/asr/u2_conformer_librispeech/module.py | AK391/PaddleHub | 8,360 | 11197762 | <reponame>AK391/PaddleHub<filename>modules/audio/asr/u2_conformer_librispeech/module.py<gh_stars>1000+
# Copyright (c) 2021 PaddlePaddle 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... |
boto3_type_annotations_with_docs/boto3_type_annotations/health/client.py | cowboygneox/boto3_type_annotations | 119 | 11197765 | <reponame>cowboygneox/boto3_type_annotations
from typing import Optional
from botocore.client import BaseClient
from typing import Dict
from botocore.paginate import Paginator
from botocore.waiter import Waiter
from typing import Union
from typing import List
class Client(BaseClient):
def can_paginate(self, opera... |
sphinxbase/src/libsphinxbase/util/clapack_scrub.py | ejuacel/pocketsphinx.js | 560 | 11197771 | <reponame>ejuacel/pocketsphinx.js<filename>sphinxbase/src/libsphinxbase/util/clapack_scrub.py
#!/usr/bin/env python2.4
import sys, os
from cStringIO import StringIO
import re
from Plex import *
from Plex.Traditional import re as Re
class MyScanner(Scanner):
def __init__(self, info, name='<default>'):
Sca... |
src/deutschland/nina/__init__.py | andreasbossard/deutschland | 445 | 11197777 | # flake8: noqa
"""
Bundesamt für Bevölkerungsschutz: NINA API
Erhalten Sie wichtige Warnmeldungen des Bevölkerungsschutzes für Gefahrenlagen wie zum Beispiel Gefahrstoffausbreitung oder Unwetter per Programmierschnittstelle. # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https... |
scripts/update_thanks.py | ThePrez/gunicorn | 6,851 | 11197798 | <gh_stars>1000+
#!/usr/bin/env python
# Usage: git log --format="%an <%ae>" | python update_thanks.py
# You will get a result.txt file, you can work with the file (update, remove, ...)
#
# Install
# =======
# pip install validate_email pyDNS
#
import sys
from validate_email import validate_email
from email.utils impor... |
homeassistant/components/p1_monitor/diagnostics.py | MrDelik/core | 30,023 | 11197804 | """Diagnostics support for P1 Monitor."""
from __future__ import annotations
from dataclasses import asdict
from typing import Any
from homeassistant.components.diagnostics import async_redact_data
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST
from homeassistant.core i... |
tests/test_volume.py | stanik137/xtreemfs | 270 | 11197830 | <gh_stars>100-1000
# Copyright (c) 2009-2011 by <NAME>, <NAME>, Zuse Institute Berlin
# Licensed under the BSD License, see LICENSE file for details.
from time import sleep
import sys, os, subprocess, signal
DEBUG_LEVELS = [ 'EMERG', 'ALERT', 'CRIT', 'ERR', 'WARNING', 'NOTICE', 'INFO', 'DEBUG' ]
class Volume:
de... |
pyro/contrib/autoname/scoping.py | tianjuchen/pyro | 4,959 | 11197844 | <filename>pyro/contrib/autoname/scoping.py
# Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
"""
``pyro.contrib.autoname.scoping`` contains the implementation of
:func:`pyro.contrib.autoname.scope`, a tool for automatically appending
a semantically meaningful prefix to names of sa... |
lib/spack/spack/test/cmd/ci.py | BenWibking/spack | 2,360 | 11197856 | # 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)
import filecmp
import json
import os
import shutil
import pytest
from jsonschema import ValidationError, validate
import... |
hb_quant/huobi/model/etf/unitprice.py | wenli135/Binance-volatility-trading-bot | 611 | 11197861 | class UnitPrice:
def __init__(self):
self.currency = ""
self.amount = 0.0
def print_object(self, format_data=""):
from huobi.utils.print_mix_object import PrintBasic
PrintBasic.print_basic(self.currency, format_data + "Currency")
PrintBasic.print_basic(self.amount, form... |
tests/openbb_terminal/cryptocurrency/defi/test_terramoney_fcd_model.py | tehcoderer/GamestonkTerminal | 255 | 11197893 | <reponame>tehcoderer/GamestonkTerminal<filename>tests/openbb_terminal/cryptocurrency/defi/test_terramoney_fcd_model.py
# IMPORTATION STANDARD
# IMPORTATION THIRDPARTY
import pytest
# IMPORTATION INTERNAL
from openbb_terminal.cryptocurrency.defi import terramoney_fcd_model
@pytest.mark.vcr
def test_get_staking_accou... |
examples/rmi.py | pitmanst/jpype | 531 | 11197894 | <filename>examples/rmi.py
# *****************************************************************************
# Copyright 2004-2008 <NAME>
#
# 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
... |
ptstat/core.py | timmyzhao/ptstat | 116 | 11197895 | <gh_stars>100-1000
import torch
from torch.autograd import Variable
# TODO:
# Remove Variable() everywhere when auto-promotion implemented.
# Make size() method indexable.
# Option to remove asserts.
# Rename log_pdf to log_p ?
def _to_v(x, size=None, cuda=False):
if isinstance(x, Variable):
y = x
e... |
configs/_base_/schedules/imagenet_bs2048_coslr.py | YuxinZou/mmclassification | 1,190 | 11197906 | # optimizer
optimizer = dict(
type='SGD', lr=0.8, momentum=0.9, weight_decay=0.0001, nesterov=True)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(
policy='CosineAnnealing',
min_lr=0,
warmup='linear',
warmup_iters=2500,
warmup_ratio=0.25)
runner = dict(type='EpochBase... |
wouso/core/scoring/tests.py | ruxandraS/wouso | 117 | 11197920 | <gh_stars>100-1000
from django.test import TestCase
from django.db.models.query import QuerySet
from django.contrib.auth.models import User
from wouso.core.config.models import IntegerListSetting
from wouso.core.game.models import Game
from wouso.core import scoring, signals
from wouso.core.tests import WousoTest
from ... |
examples/dummy_plugin/dummy_plugin/jobs.py | psmware-ltd/nautobot | 384 | 11197921 | <filename>examples/dummy_plugin/dummy_plugin/jobs.py
import time
from nautobot.extras.jobs import IntegerVar, Job
name = "DummyPlugin jobs"
class DummyJob(Job):
class Meta:
name = "Dummy job, does nothing"
class DummyLoggingJob(Job):
interval = IntegerVar(default=4, description="The time in secon... |
wrappers/python/tests/did/test_set_endpoint_for_did.py | sklump/indy-sdk | 636 | 11197927 | <filename>wrappers/python/tests/did/test_set_endpoint_for_did.py
import pytest
from indy import did, error
@pytest.mark.asyncio
async def test_set_endpoint_for_did_works(wallet_handle, identity_trustee1, endpoint):
(_did, verkey) = identity_trustee1
await did.set_endpoint_for_did(wallet_handle, _did, endpoin... |
tests/contrib/test_dictionary_storage.py | anleo1000/oauth2client | 5,079 | 11197935 | <gh_stars>1000+
# Copyright 2016 Google Inc. 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 required by ap... |
chatbot_env/Lib/site-packages/sklearn/metrics/cluster/tests/test_unsupervised.py | rakmakan/Chatbot | 6,989 | 11197948 | import numpy as np
import scipy.sparse as sp
import pytest
from scipy.sparse import csr_matrix
from sklearn import datasets
from sklearn.utils._testing import assert_array_equal
from sklearn.utils._testing import assert_warns_message
from sklearn.metrics.cluster import silhouette_score
from sklearn.metrics.cluster imp... |
sympy/physics/mechanics/joint.py | shilpiprd/sympy | 8,323 | 11197955 | # coding=utf-8
from abc import ABC, abstractmethod
from sympy import pi
from sympy.physics.mechanics.body import Body
from sympy.physics.vector import Vector, dynamicsymbols, cross
from sympy.physics.vector.frame import ReferenceFrame
import warnings
__all__ = ['Joint', 'PinJoint', 'PrismaticJoint']
class Joint(A... |
scripts/automation/trex_control_plane/interactive/trex/emu/api.py | timgates42/trex-core | 956 | 11197964 | <filename>scripts/automation/trex_control_plane/interactive/trex/emu/api.py<gh_stars>100-1000
# some common data
from ..common.trex_exceptions import *
from ..common.trex_api_annotators import *
from ..common.trex_logger import Logger
# TRex Emu profile
from .trex_emu_profile import *
from .trex_emu_client import *
#... |
py/testdir_hosts/notest_short.py | gigliovale/h2o | 882 | 11197977 | import unittest, random, sys, time
sys.path.extend(['.','..','../..','py'])
import h2o, h2o_cmd, h2o_browse as h2b, h2o_import as h2i, h2o_glm, h2o_util
class Basic(unittest.TestCase):
def tearDown(self):
h2o.check_sandbox_for_errors()
@classmethod
def setUpClass(cls):
global SEED
... |
pyscf/adc/test/test_radc/test_dfadc_N2.py | QuESt-Calculator/pyscf | 501 | 11197984 | # Copyright 2014-2019 The PySCF Developers. 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 required by appl... |
vit/actions.py | kinifwyne/vit | 179 | 11197997 | class Actions(object):
def __init__(self, action_registry):
self.action_registry = action_registry
def register(self):
self.action_registrar = self.action_registry.get_registrar()
# Global.
self.action_registrar.register('QUIT', 'Quit the application')
self.action_regis... |
blender/arm/lightmapper/utility/denoiser/oidn.py | onelsonic/armory | 2,583 | 11198042 | import bpy, os, sys, re, platform, subprocess
import numpy as np
class TLM_OIDN_Denoise:
image_array = []
image_output_destination = ""
denoised_array = []
def __init__(self, oidnProperties, img_array, dirpath):
self.oidnProperties = oidnProperties
self.image_array = img_array
... |
caffe2/experiments/python/funhash_op_test.py | wenhaopeter/read_pytorch_code | 585 | 11198044 | # Copyright (c) 2016-present, Facebook, 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... |
popong/precinct/mismatch_case_precinct_map.py | Jooyaro/southkorea-maps | 404 | 11198050 | <filename>popong/precinct/mismatch_case_precinct_map.py
# -*- coding: utf-8 -*-
# 지도 파일과 선거구 파일 사이의 불일치
mismatches = {}
# 지도 파일에서 시 정보가 미반영된 구 (e.g., 성산구 -> 창원시성산구)
mismatches["municipality_rename"] = {
2012: {37012: u"포항시북구", 37011: u"포항시남구", 38111: u"창원시의창구", 38112: u"창원시성산구", 38113: u"창원시마산합포구", 38114: u"창... |
src/datasets/inspect.py | huggingface/nlp | 3,395 | 11198085 | # Copyright 2020 The HuggingFace Datasets 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 applicable law or ... |
session_encdec.py | sordonia/HierarchicalEncoderDecoder | 116 | 11198099 | <reponame>sordonia/HierarchicalEncoderDecoder<filename>session_encdec.py<gh_stars>100-1000
"""
Query suggestion hierarchical encoder-decoder code.
The code is inspired from nmt encdec code in groundhog
but we do not rely on groundhog infrastructure.
"""
__docformat__ = 'restructedtext en'
__authors__ = ("<NAME>")
__con... |
VMD 3D Pose Baseline Multi-Objects/packages/lifting/utils/__init__.py | kyapp69/OpenMMD | 717 | 11198100 | <reponame>kyapp69/OpenMMD
# -*- coding: utf-8 -*-
"""
Created on Mar 23 13:57 2017
@author: <NAME>'
"""
from .prob_model import *
from .draw import *
from .cpm import *
from .process import *
from . import config
from . import upright_fast
|
rlpytorch/runner/single_process.py | douglasrizzo/ELF | 2,230 | 11198120 | <filename>rlpytorch/runner/single_process.py<gh_stars>1000+
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from ..args_provider import ArgsProvider
import tqdm
class... |
Lib/test/test_compiler/test_static/patch.py | vdavalon01/cinder | 1,886 | 11198143 | import asyncio
import re
from compiler.pycodegen import PythonCodeGenerator
from unittest.mock import Mock, patch
from .common import StaticTestBase
class StaticPatchTests(StaticTestBase):
def test_patch_function(self):
codestr = """
def f():
return 42
def g():
... |
lagom/metric/returns.py | zuoxingdong/lagom | 383 | 11198148 | import numpy as np
from lagom.transform import geometric_cumsum
from lagom.utils import numpify
def returns(gamma, rewards):
return geometric_cumsum(gamma, rewards)[0, :].astype(np.float32)
def bootstrapped_returns(gamma, rewards, last_V, reach_terminal):
r"""Return (discounted) accumulated returns with bo... |
tensorflow_lite_support/metadata/python/tests/metadata_parser_test.py | khanhlvg/tflite-support | 242 | 11198161 | # Copyright 2020 The TensorFlow 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
#
# Unless required by applica... |
reinforcement_learning/rl_stock_trading_coach_customEnv/src/evaluate-coach.py | jerrypeng7773/amazon-sagemaker-examples | 2,610 | 11198170 | import argparse
import os
import rl_coach
from rl_coach.base_parameters import Frameworks, TaskParameters
from rl_coach.core_types import EnvironmentSteps
from sagemaker_rl.coach_launcher import CoachConfigurationList, SageMakerCoachPresetLauncher
def inplace_replace_in_file(filepath, old, new):
with open(filepa... |
pghoard/monitoring/statsd.py | pellcorp/pghoard | 731 | 11198177 | """
StatsD client
Supports telegraf's statsd protocol extension for 'key=value' tags:
https://github.com/influxdata/telegraf/tree/master/plugins/inputs/statsd
"""
import socket
class StatsClient:
def __init__(self, config):
self._dest_addr = (config.get("host", "127.0.0.1"), config.get("port", 8125))... |
instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py | open-telemetry/opentelemetry-python-contrib | 208 | 11198247 | <filename>instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py
# Copyright The OpenTelemetry 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 Lice... |
src/genie/libs/parser/iosxe/show_device_tracking.py | balmasea/genieparser | 204 | 11198253 | <filename>src/genie/libs/parser/iosxe/show_device_tracking.py
import re
from genie.metaparser import MetaParser
from genie.metaparser.util.schemaengine import Any, Optional, Or
from genie.libs.parser.utils.common import Common
# ==================================
# Schema for:
# * 'show device-tracking database'
# ... |
details_soup.py | Abhijeet-AR/Competitive_Programming_Score_API | 140 | 11198269 | <filename>details_soup.py
import json
import re
# DO NOT import this after requests
import grequests
import requests
import os
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from util import get_safe_nested_key
class UsernameError(Except... |
service/learner/brains/observation_preprocessor_test.py | lcrh/falken | 213 | 11198280 | <filename>service/learner/brains/observation_preprocessor_test.py
# Copyright 2021 Google LLC
#
# 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... |
ibis/backends/pandas/tests/test_dispatcher.py | GrapeBaBa/ibis | 986 | 11198313 | <gh_stars>100-1000
import pytest
from multipledispatch import Dispatcher
from multipledispatch.conflict import AmbiguityWarning
from ibis.backends.pandas.dispatcher import TwoLevelDispatcher
class A1:
pass
class A2(A1):
pass
class A3(A2):
pass
class B1:
pass
class B2(B1):
pass
class B3(... |
benchmarks/benchmarks/go_benchmark_functions/go_benchmark.py | Ennosigaeon/scipy | 9,095 | 11198314 | # -*- coding: utf-8 -*-
import numpy as np
from numpy import abs, asarray
from ..common import safe_import
with safe_import():
from scipy.special import factorial
class Benchmark:
"""
Defines a global optimization benchmark problem.
This abstract class defines the basic structure of a global
o... |
bots/stocks/dark_pool_shorts/pos.py | tehcoderer/GamestonkTerminal | 255 | 11198316 | <filename>bots/stocks/dark_pool_shorts/pos.py
import logging
import disnake
from bots import imps
from openbb_terminal.decorators import log_start_end
from openbb_terminal.helper_funcs import lambda_long_number_format
from openbb_terminal.stocks.dark_pool_shorts import stockgrid_model
logger = logging.getLogger(__na... |
lenstronomy/SimulationAPI/data_api.py | heather999/lenstronomy | 107 | 11198319 | from lenstronomy.SimulationAPI.observation_api import SingleBand
from lenstronomy.Data.imaging_data import ImageData
import lenstronomy.Util.util as util
import numpy as np
__all__ = ['DataAPI']
class DataAPI(SingleBand):
"""
This class is a wrapper of the general description of data in SingleBand() to trans... |
torch/ao/sparsity/experimental/pruner/parametrization.py | Hacky-DH/pytorch | 60,067 | 11198320 | <filename>torch/ao/sparsity/experimental/pruner/parametrization.py
import torch
from torch import nn
from typing import Any, List
class PruningParametrization(nn.Module):
def __init__(self, original_outputs):
super().__init__()
self.original_outputs = set(range(original_outputs.item()))
se... |
colour/models/tests/test_igpgtg.py | rift-labs-developer/colour | 1,380 | 11198327 | # -*- coding: utf-8 -*-
"""
Defines the unit tests for the :mod:`colour.models.igpgtg` module.
"""
import numpy as np
import unittest
from itertools import permutations
from colour.models import XYZ_to_IgPgTg, IgPgTg_to_XYZ
from colour.utilities import domain_range_scale, ignore_numpy_errors
__author__ = 'Colour Dev... |
WebMirror/management/rss_parser_funcs/feed_parse_extractAvaritiakun.py | fake-name/ReadableWebProxy | 193 | 11198329 | def extractAvaritiakun(item):
"""
Avaritia-kun
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
tagmap = [
('Divine protection', 'The divine protection that I got was a power that increase a girl le... |
pinball/scheduler/schedule.py | robinmaben/pinball | 1,143 | 11198339 | # Copyright 2015, Pinterest, 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 in writ... |
mseg/utils/mask_utils.py | mintar/mseg-api | 213 | 11198344 | <reponame>mintar/mseg-api
#!/usr/bin/python3
import cv2
import math
import numpy as np
import matplotlib.pyplot as plt
import pdb
from PIL import Image, ImageDraw
import torch
from typing import List, Mapping, Optional, Tuple
from mseg.utils.conn_comp import scipy_conn_comp
from mseg.utils.colormap import colormap
f... |
observations/r/attenu.py | hajime9652/observations | 199 | 11198371 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import numpy as np
import os
import sys
from observations.util import maybe_download_and_extract
def attenu(path):
"""The Joyner–Boore Attenuation Data
This data gives... |
src/account/signals.py | RogerTangos/datahub-stub | 192 | 11198375 | from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import pre_save
from psycopg2 import OperationalError
from django.db.utils import IntegrityError
from core.db.manager import DataHubManager
from core.db.rlsmanager import RowLevelSecurityManager
from django.c... |
src/python/pants/backend/docker/target_types.py | pantsbuild/pants | 1,806 | 11198391 | <gh_stars>1000+
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import os
import re
from abc import ABC, abstractmethod
from textwrap import dedent
from typing import Callable, ClassVar, Iterator, cas... |
backend/api/migrations/0031_auto_20220127_0032.py | alairice/doccano | 2,082 | 11198392 | # Generated by Django 3.2.11 on 2022-01-27 00:32
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("api", "0030_delete_autolabelingconfig"),
]
operations = [
migrations.SeparateDatabaseAndState(
state_operations=[
migra... |
release/stubs.min/System/Runtime/InteropServices/__init___parts/DllImportSearchPath.py | htlcnn/ironpython-stubs | 182 | 11198413 | class DllImportSearchPath(Enum,IComparable,IFormattable,IConvertible):
""" enum (flags) DllImportSearchPath,values: ApplicationDirectory (512),AssemblyDirectory (2),LegacyBehavior (0),SafeDirectories (4096),System32 (2048),UseDllDirectoryForDependencies (256),UserDirectories (1024) """
def __eq__(self,*args):
""... |
logbook/queues.py | YoavCohen/logbook | 771 | 11198422 | # -*- coding: utf-8 -*-
"""
logbook.queues
~~~~~~~~~~~~~~
This module implements queue backends.
:copyright: (c) 2010 by <NAME>, <NAME>.
:license: BSD, see LICENSE for more details.
"""
import json
import threading
from threading import Thread, Lock
import platform
from logbook.base import NOTSET,... |
exps/sudoku.py | locuslab/SATNet | 383 | 11198431 | #!/usr/bin/env python3
#
# Partly derived from:
# https://github.com/locuslab/optnet/blob/master/sudoku/train.py
import argparse
import os
import shutil
import csv
import numpy as np
import numpy.random as npr
#import setproctitle
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.fun... |
eve/tests/test_settings_env.py | pmwheatley/eve | 2,288 | 11198489 | # -*- coding: utf-8 -*-
# this is just a helper file which we are going
# to try to load with environmental variable in
# test_existing_env_config() test case
DOMAIN = {'env_domain': {}}
|
mobileFacenet_64_PReLU.py | GzuPark/EXTD_Pytorch | 190 | 11198494 | import torch.nn as nn
import math
import torch
import torch.nn.functional as F
def conv_bn(inp, oup, stride, k_size=3):
return nn.Sequential(
nn.Conv2d(inp, oup, k_size, stride, 1, bias=False),
nn.BatchNorm2d(oup),
nn.PReLU()
)
def conv_1x1_bn(inp, oup):
return nn.Sequential(
... |
tests/strategies/staggered_orders/test_staggered_orders_complex.py | fakegit/DEXBot | 249 | 11198513 | <gh_stars>100-1000
import logging
import math
import time
from datetime import datetime
import pytest
from bitshares.amount import Amount
# Turn on debug for dexbot logger
log = logging.getLogger("dexbot")
log.setLevel(logging.DEBUG)
MODES = ['mountain', 'valley', 'neutral', 'buy_slope', 'sell_slope']
############... |
insights/parsers/tests/test_vsftpd.py | mglantz/insights-core | 121 | 11198530 | from insights.parsers.vsftpd import VsftpdConf, VsftpdPamConf
from insights.tests import context_wrap
VSFTPD_PAM_CONF = """
#%PAM-1.0
session optional pam_keyinit.so force revoke
auth required pam_listfile.so item=user sense=deny file=/etc/vsftpd/ftpusers onerr=succeed
auth required pam_s... |
tests/test_timeline_event_control.py | rvega/isobar | 241 | 11198536 | """ Unit tests for events """
import isobar as iso
import pytest
import math
from . import dummy_timeline
def test_event_control_no_interpolation(dummy_timeline):
"""
Simple case: schedule a series of regularly-spaced control points.
Output device should receive discrete control events.
"""
contro... |
pase/utils.py | ishine/pase | 428 | 11198595 | import json
import shlex
import subprocess
import random
import torch
import torch.nn as nn
try:
from .losses import *
except ImportError:
from losses import *
import random
from random import shuffle
from pase.models.discriminator import *
import torch.optim as optim
from torch.autograd import Function
def p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.