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
analytics/duplicates_analyze.py
mattip/builder
225
11111916
#!/usr/bin/env python3 from typing import Dict, List from subprocess import check_output import os import sys def get_defined_symbols(fname: str, verbose: bool = False) -> Dict[str, int]: if verbose: print(f"Processing {fname}...", end='', flush=True) if sys.platform == 'darwin': lines = check...
examples/django_110/app/views.py
ascan-io/raven-python
1,108
11111934
<gh_stars>1000+ import logging logger = logging.getLogger('app') def home(request): logger.info('Doing some division') 1 / 0
polytester/parsers/unittest.py
skoczen/polytester
115
11111977
<gh_stars>100-1000 from .nose import NoseParser class UnittestParser(NoseParser): """Output when using `python -m unittest` is the same as nose output.""" name = "unittest" def command_matches(self, command): return "unittest" in command
common/mongo_db.py
seaglass-project/seaglass
211
11111987
<gh_stars>100-1000 from pprint import pprint import pymongo import time import sys import traceback import os import base64 import datetime import common.utils as utils import common.scan as scan DB_INSERT_TIMEOUT = 1 # Used to prevent timeouts on cursors BATCH_SIZE = 1000 # Nice to have some versioning VERSION = 0 ...
Algo and DSA/LeetCode-Solutions-master/Python/maximum-profit-in-job-scheduling.py
Sourav692/FAANG-Interview-Preparation
3,269
11111991
<filename>Algo and DSA/LeetCode-Solutions-master/Python/maximum-profit-in-job-scheduling.py # Time: O(nlogn) # Space: O(n) import itertools import bisect class Solution(object): def jobScheduling(self, startTime, endTime, profit): """ :type startTime: List[int] :type endTime: List[int] ...
scripts/converter/convert_geometries.py
HarpieRapace45/webots
1,561
11112020
<gh_stars>1000+ #!/usr/bin/env python3 # Copyright 1996-2021 Cyberbotics 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 re...
mapproxy/cache/__init__.py
cunha17/mapproxy
347
11112043
# This file is part of the MapProxy project. # Copyright (C) 2010 Omniscale <http://omniscale.de> # # 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...
tutorials/W0D3_LinearAlgebra/solutions/W0D3_Tutorial2_Solution_a86560cc.py
eduardojdiniz/CompNeuro
2,294
11112058
<reponame>eduardojdiniz/CompNeuro A = np.array([[-1, 0], [0, 1]]) # Uncomment to visualize transformation plot_linear_transformation(A)
ProofOfConcepts/Vision/OpenMvStereoVision/src/target_code/lens_correction.py
WoodData/EndpointAI
190
11112082
# Lens Correction import sensor, image, time sensor.reset() sensor.set_framesize(sensor.VGA) sensor.set_pixformat(sensor.RGB565) sensor.set_windowing((160,120,320,240)) sensor.skip_frames(time = 2000) data_fb = sensor.alloc_extra_fb(320, 240, sensor.RGB565) clock = time.clock() count = 0 remap = False while(True): ...
src/dal_select2_queryset_sequence/fields.py
epoiate/django-autocomplete-light
1,368
11112087
"""Autocomplete fields for Select2GenericForeignKey choices.""" from dal_queryset_sequence.fields import QuerySetSequenceModelField from dal_select2_queryset_sequence.views import Select2QuerySetSequenceAutoView from dal_select2_queryset_sequence.widgets import QuerySetSequenceSelect2 from django.conf.urls import ur...
desktop/core/ext-py/python-ldap-2.3.13/Tests/Lib/ldap/schema/test_tokenizer.py
kokosing/hue
5,079
11112103
<gh_stars>1000+ import ldap.schema from ldap.schema.tokenizer import split_tokens,extract_tokens testcases_split_tokens = ( (" BLUBBER DI BLUBB ", ["BLUBBER", "DI", "BLUBB"]), ("BLUBBER DI BLUBB",["BLUBBER","DI","BLUBB"]), ("BLUBBER DI BLUBB ",["BLUBBER","DI","BLUBB"]), ("BLUBBER DI 'BLUBB' ",["BLUBBER...
bcs-ui/backend/templatesets/legacy_apps/configuration/migrations/0034_auto_20200106_1455.py
laodiu/bk-bcs
599
11112118
<reponame>laodiu/bk-bcs<filename>bcs-ui/backend/templatesets/legacy_apps/configuration/migrations/0034_auto_20200106_1455.py # -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2021 THL A29 Limited, a...
examples/ConsPortfolioModel/example_ConsPortfolioModel.py
AMonninger/HARK
264
11112119
# %% """ Example implementations of HARK.ConsumptionSaving.ConsPortfolioModel """ from copy import copy from time import time import matplotlib.pyplot as plt import numpy as np from HARK.ConsumptionSaving.ConsIndShockModel import init_lifecycle from HARK.ConsumptionSaving.ConsPortfolioModel import ( PortfolioCons...
isaacgymenvs/rl_games/common/interval_summary_writer.py
ZaneZh/IsaacGymEnvs
193
11112151
<gh_stars>100-1000 import time class IntervalSummaryWriter: """ Summary writer wrapper designed to reduce the size of tf.events files. It will prevent the learner from writing the summaries more often than a specified interval, i.e. if the current interval is 20 seconds and we wrote our last summary f...
Stephanie/Modules/weather_report_module.py
JeremyARussell/stephanie-va
866
11112156
import datetime import pyowm from Stephanie.Modules.base_module import BaseModule from Stephanie.local_libs.numbers_format import NumberService class WeatherReportModule(BaseModule): def __init__(self, *args): super(WeatherReportModule, self).__init__(*args) self.api_key = self.get_configuration("...
hn/__init__.py
movermeyer/HackerNewsAPI
132
11112165
<filename>hn/__init__.py<gh_stars>100-1000 """ Python API for Hacker News. @author <NAME> @email <EMAIL> """ __title__ = 'hackernews' __author__ = '<NAME>' __license__ = 'MIT' __copyright__ = 'Copyright 2014 Karan Goel' from .hn import HN, Story
Configuration/AlCa/python/autoCondModifiers.py
malbouis/cmssw
852
11112208
## ## Append for 0T conditions ## from Configuration.StandardSequences.CondDBESSource_cff import GlobalTag as essource connectionString = essource.connect.value() # method called in autoCond def autoCond0T(autoCond): ConditionsFor0T = ','.join( ['RunInfo_0T_v1_mc', "RunInfoRcd", connectionString, "", "2020-0...
flow-python/examples/warehouse/detection_memd/onnx_model.py
chentyjpm/MegFlow
303
11112217
# MegFlow is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2019-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KI...
burp/blackboxprotobuf/__init__.py
nccgroup/blackboxprotobuf
261
11112239
<gh_stars>100-1000 import os import sys import inspect # Add correct directory to sys.path _BASE_DIR = os.path.abspath( os.path.dirname(inspect.getfile(inspect.currentframe())) + "../../../" ) sys.path.insert(0, _BASE_DIR + "/lib/") sys.path.insert(0, _BASE_DIR + "/burp/deps/six/") sys.path.insert(0, _BASE_DIR + ...
tests/mockapp/migrations/0005_mockperson_birthdate.py
fluxility/drf-haystack
201
11112251
<reponame>fluxility/drf-haystack # -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-04-16 07:05 from __future__ import unicode_literals from django.db import migrations, models import tests.mockapp.models class Migration(migrations.Migration): dependencies = [ ('mockapp', '0002_mockperson'), ...
Chapter02/callCalculator.pyw
houdinii/Qt5-Python-GUI-Programming-Cookbook
131
11112273
import sys from PyQt5.QtWidgets import QDialog, QApplication from demoCalculator import * class MyForm(QDialog): def __init__(self): super().__init__() self.ui = Ui_Dialog() self.ui.setupUi(self) self.ui.pushButtonPlus.clicked.connect(self.addtwonum) self.ui.pu...
tests/model_fields/test_floatfield.py
ni-ning/django
61,676
11112290
<filename>tests/model_fields/test_floatfield.py from django.db import transaction from django.test import TestCase from .models import FloatModel class TestFloatField(TestCase): def test_float_validates_object(self): instance = FloatModel(size=2.5) # Try setting float field to unsaved object ...
corehq/messaging/smsbackends/http/tests/test_models.py
akashkj/commcare-hq
471
11112292
<reponame>akashkj/commcare-hq from corehq.util.urlvalidate.urlvalidate import PossibleSSRFAttempt from datetime import datetime from unittest.mock import patch, ANY from django.test import SimpleTestCase from corehq.apps.sms.models import SMS, OUTGOING from corehq.util.urlvalidate.test.mockipinfo import hostname_resolv...
security_monkey/tests/auditors/rds/test_rds_snapshot.py
boladmin/security_monkey
4,258
11112299
# Copyright 2017 Netflix, 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...
rbac/proxy.py
eldorplus/simple-rbac
219
11112312
<filename>rbac/proxy.py<gh_stars>100-1000 from __future__ import absolute_import import functools import collections __all__ = ["dummy_factory", "model_role_factory", "model_resource_factory", "RegistryProxy"] # identity tuple identity = collections.namedtuple("identity", ["type", "cls", "id"]) role_iden...
jupyterlab_sql/connection_url.py
mwiewior/jupyterlab-sql
385
11112315
import sqlalchemy.engine.url def is_sqlite(url): backend = _to_sqlalchemy_url(url).get_backend_name() return backend == "sqlite" def is_mysql(url): backend = _to_sqlalchemy_url(url).get_backend_name() return backend == "mysql" def has_database(url): database = _to_sqlalchemy_url(url).database ...
torchelie/datasets/debug.py
Vermeille/Torchelie
117
11112332
import os from typing import Optional, Callable from typing_extensions import Literal import torch import torchvision.transforms as TF from torch.utils.data import Dataset from torchvision.datasets import ImageFolder from torchvision.datasets.utils import download_and_extract_archive __all__ = ['ColoredColumns', 'Col...
src/chapter-12/test_caching.py
luizyao/pytest-chinese-doc
283
11112354
<reponame>luizyao/pytest-chinese-doc<filename>src/chapter-12/test_caching.py #!/usr/bin/env python3 # -*- coding:utf-8 -*- ''' Author: luizyao (<EMAIL>) Created Date: 2019-11-30 20:35:07 ----- Modified: 2019-11-30 20:36:29 Modified By: luizyao (<EMAIL>) ----- THIS PROGRAM IS FREE SOFTWARE, IS LICENSED UNDER MIT. A sho...
examples/plot_hide.py
ipa-maa/UpSetPlot
175
11112388
""" ====================================== Hiding subsets based on size or degree ====================================== This illustrates the use of ``min_subset_size``, ``max_subset_size``, ``min_degree`` or ``max_degree``. """ from matplotlib import pyplot as plt from upsetplot import generate_counts, plot example...
archai/algos/gumbelsoftmax/gs_exp_runner.py
cclauss/archai
344
11112429
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from typing import Type from overrides import overrides from archai.nas.exp_runner import ExperimentRunner from archai.nas.arch_trainer import TArchTrainer from archai.nas.finalizers import Finalizers from .gs_model_desc_builder import GsModelD...
examples/select_loop.py
webcoast-dk/mitogen
1,526
11112441
<filename>examples/select_loop.py # # This demonstrates using a nested select.Select() to simultaneously watch for # in-progress events generated by a bunch of function calls, and the completion # of those function calls. # # We start 5 children and run a function in each of them in parallel. The # function writes the...
wtfml/logger/__init__.py
Mo5mami/wtfml
283
11112461
from .logger import logger
PyFin/tests/Math/Distributions/testDistribution.py
rpatil524/Finance-Python
325
11112468
# -*- coding: utf-8 -*- u""" Created on 2015-7-23 @author: cheng.li """ import unittest import math import copy import tempfile import pickle import os from PyFin.Math.Distributions import InverseCumulativeNormal from PyFin.Math.Distributions import NormalDistribution from PyFin.Math.Distributions import CumulativeNo...
buildroot/support/testing/tests/package/test_prosody.py
rbrenton/hassos
349
11112480
<filename>buildroot/support/testing/tests/package/test_prosody.py from tests.package.test_lua import TestLuaBase class TestProsody(TestLuaBase): def lua_dependencies_test(self): self.module_test('bit') # luabitop self.module_test('lfs') # luafilesystem self.module_test('lxp') #...
051-100/061-rotate-list.py
bbram10/leetcode-master
134
11112525
<filename>051-100/061-rotate-list.py """ STATEMENT Given a list, rotate the list to the right by k places, where k is non-negative. CLARIFICATIONS - Is the list given as an array? No, a linked list. - Each node in the linked list is an object of a custom data structure, right? Yes. Define them. - Can k be more than ...
rootpy/utils/hook.py
masonproffitt/rootpy
146
11112529
<reponame>masonproffitt/rootpy<gh_stars>100-1000 from __future__ import absolute_import import types import sys from .inject_closure import inject_closure_values from . import log; log = log[__name__] __all__ = [ 'super_overridden', 'uses_super', 'classhook', 'appendclass', ] # The below code is her...
csgomenumaker/component/debug.py
citrusCS/csgo-menu-maker
152
11112584
from .. import menu from ..param import * from .component import * from . import generic name_space( "debug", name="Debug", description=( "Debugging options that show different data on-screen, such as fps," " position, traces, etc." ) ) @Component("showpos", "show_pos") class ShowPo...
lgcn/train_lgcn.py
LLLjun/learn-to-cluster
620
11112598
<filename>lgcn/train_lgcn.py<gh_stars>100-1000 from __future__ import division from collections import OrderedDict import torch from mmcv.runner import Runner, obj_from_dict from mmcv.parallel import MMDataParallel from lgcn.datasets import build_dataset, build_dataloader from lgcn.online_evaluation import online_eva...
tests/db/test_password.py
Yurzs/boto
5,079
11112608
# Copyright (c) 2010 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribu...
scripts/ios/relpath.py
Son-Le-Goog/nimbus
2,787
11112619
<gh_stars>1000+ #!/usr/bin/env python # encoding: utf-8 """ relpath.py A method for calculating the relative path from one directory to another. Originally written by <NAME>: http://code.activestate.com/recipes/208993-compute-relative-path-from-one-directory-to-anothe/ Date: July 6, 2003 Modifications Copyright 2011...
Exec/gravity_tests/hse_convergence_general/hse.py
MargotF/Castro
178
11112653
#!/bin/env python import argparse import numpy as np import matplotlib.pyplot as plt import yt def doit(outfile="hse.png"): low = yt.load("flame_wave_128_plt01600") med = yt.load("flame_wave_256_plt03200") high = yt.load("flame_wave_512_plt06400") fig, ax = plt.subplots(1,1) for ds, l in [(lo...
alipay/aop/api/FileItem.py
articuly/alipay-sdk-python-all
213
11112666
<filename>alipay/aop/api/FileItem.py # -*- coding: utf-8 -*- ''' Created on 2017-12-20 @author: liuqun ''' from alipay.aop.api.util.CommonUtils import get_mime_type class FileItem(object): def __init__(self, file_name=None, file_content=None, mime_type=None): self._file_name = file_name self._fi...
codigo/Live43/exemplo_2.py
cassiasamp/live-de-python
572
11112668
<reponame>cassiasamp/live-de-python from sys import stdout class PrintMock: def __enter__(self): self.old_print = stdout.write self.file = open('log.txt', 'a') stdout.write = self.log def log(self, arg): self.file.write('{}'.format(arg)) def __exit__(self, type, value, tr...
src/pretix/base/migrations/0049_checkin.py
pajowu/pretix
1,248
11112669
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2016-12-08 16:47 from __future__ import unicode_literals import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pretixbase', '0048_auto_20161129_1330'), ('pretixdr...
recipes/Python/578465_longest_common_substring/recipe-578465.py
tdiprima/code
2,023
11112672
<reponame>tdiprima/code #!/usr/bin/env python3.2 import numpy as np def longest_common_substring(src, dst) : c = np.zeros((len(src), len(dst)), dtype=np.int) z = 0 src_m = None dst_m = None for i in range(len(src)) : for j in range(len(dst)) : if src[i] == dst[j] : if i == 0 or j == 0 : c[i,j] = 1 ...
suzieq/db/parquet/migratedb.py
foobug/suzieq
487
11112677
from typing import Callable, Union import pandas as pd from pandas.core.computation.ops import UndefinedVariableError def get_migrate_fn(table_name: str, from_vers: str, to_vers: str) -> Union[Callable, None]: """Return a migration function if one is present for the table specified :param...
app/magtape/test/test_routes.py
gitter-badger/magtape
140
11112683
<reponame>gitter-badger/magtape<filename>app/magtape/test/test_routes.py<gh_stars>100-1000 #!/usr/bin/env python # Copyright 2020 T-Mobile, USA, 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 Lic...
tartiflette/coercers/outputs/object_coercer.py
matt-koevort/tartiflette
530
11112698
from typing import Any, Dict, List from tartiflette.coercers.outputs.common import complete_object_value from tartiflette.coercers.outputs.null_coercer import null_coercer_wrapper __all__ = ("object_coercer",) @null_coercer_wrapper async def object_coercer( result: Any, info: "ResolveInfo", execution_co...
src/sh/run_all_python_tests.py
vb-wayne/paragraph
111
11112703
#! /usr/bin/env python3 import os import sys import unittest def main(): project_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "python")) testsuite = unittest.TestLoader().discover(os.path.join(project_dir, "test")) lib_results = unittest.TextTestRunner(verbosity=3).run(testsuite) ...
meshrcnn/utils/projtransform.py
MAYURGAIKWAD/meshrcnn
1,028
11112704
<gh_stars>1000+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch class ProjectiveTransform(object): """ Projective Transformation in PyTorch: Follows a similar design to skimage.ProjectiveTransform https://github.com/scikit-image/scikit-image/blob/master/skimage/tran...
projects/FastRetri/fastretri/config.py
NTU-ROSE/fast-reid
2,194
11112735
# encoding: utf-8 """ @author: <NAME> @contact: <EMAIL> """ def add_retri_config(cfg): _C = cfg _C.TEST.RECALLS = [1, 2, 4, 8, 16, 32]
linebot/models/imagemap.py
naotokuwa/line-bot-sdk-python
1,563
11112740
# -*- coding: utf-8 -*- # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
torch/optim/rprop.py
Hacky-DH/pytorch
60,067
11112748
import torch from . import _functional as F from .optimizer import Optimizer class Rprop(Optimizer): r"""Implements the resilient backpropagation algorithm. .. math:: \begin{aligned} &\rule{110mm}{0.4pt} \\ &\textb...
semtorch/models/archs/backbones/mobilenet.py
WaterKnight1998/SemTorch
145
11112778
"""MobileNet and MobileNetV2.""" import torch.nn as nn from .registry import BACKBONE_REGISTRY from ...modules import _ConvBNReLU, _DepthwiseConv, InvertedResidual from ...config import cfg __all__ = ['MobileNet', 'MobileNetV2'] class MobileNet(nn.Module): def __init__(self, num_classes=1000, norm_layer=nn.Batc...
tests/syntax/def_name_is_parameter_and_global.py
matan-h/friendly
287
11112850
<reponame>matan-h/friendly """Should raise SyntaxError: name 'x' is parameter and global """ def f(x): global x
data_collection/gazette/spiders/base/dosp.py
itepifanio/querido-diario
268
11112864
import base64 import datetime import json import dateparser import scrapy from gazette.items import Gazette from gazette.spiders.base import BaseGazetteSpider class DospGazetteSpider(BaseGazetteSpider): allowed_domains = ["dosp.com.br", "imprensaoficialmunicipal.com.br"] # Must be defined into child classe...
scripts/19-reshelve.py
jmviz/xd
179
11112866
#!/usr/bin/env python3 # Usage: $0 [-c <corpus>] <regex> <pubid> # # rewrites receipts.tsv and fills in any blanks based on regex # # git mv all .xd with pubid of <src> to have a pubid of <dest> (simple file rename) # # import re from xdfile import utils, metadatabase as metadb, catalog def main(): args = uti...
clinica/iotools/converters/oasis_to_bids/oasis_to_bids_cli.py
Raelag0112/clinica
135
11112868
import click from clinica.iotools.converters import cli_param @click.command(name="oasis-to-bids") @cli_param.dataset_directory @cli_param.clinical_data_directory @cli_param.bids_directory def cli( dataset_directory: str, clinical_data_directory: str, bids_directory: str, ) -> None: """OASIS to BIDS ...
omega_miya/database/model/bot_self.py
rinrini001/omega-miya
120
11112881
""" @Author : Ailitonia @Date : 2021/05/23 19:32 @FileName : bot_self.py @Project : nonebot2_miya @Description : BotSelf Table Model @GitHub : https://github.com/Ailitonia @Software : PyCharm """ from omega_miya.database.database import BaseDB from omega_miya.database....
examples/pyro/pyro_logregression.py
PGM-Lab/InferPy
140
11112894
### Setting up import torch import pyro from pyro.distributions import Normal, Binomial from pyro.infer import SVI, Trace_ELBO from pyro.optim import Adam from pyro.contrib.autoguide import AutoDiagonalNormal d = 2 N = 1000 ### 17 ### Model definition ### def log_reg(x_data=None, y_data=None): w = pyro.sa...
src/python/twitter/common/python/base.py
zhouyijiaren/commons
1,143
11112903
from __future__ import absolute_import from pex.base import *
examples/wide_form_violinplot.py
amirhosseindavoody/seaborn
8,852
11112917
""" Violinplot from a wide-form dataset =================================== _thumb: .6, .45 """ import seaborn as sns import matplotlib.pyplot as plt sns.set_theme(style="whitegrid") # Load the example dataset of brain network correlations df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0) # Pull...
mmfashion/models/backbones/__init__.py
RyanJiang0416/mmfashion
952
11112922
<reponame>RyanJiang0416/mmfashion from .resnet import ResNet from .vgg import Vgg __all__ = ['Vgg', 'ResNet']
tf_base/src/network/lenetem.py
borgr/active_learning_coreset
181
11112965
from network import Network class LeNetEm(Network): def setup(self): (self.feed('data') .reshape([-1,28,28,1], name='data_reshape') .conv(5, 5, 20, 1, 1, padding='VALID', relu=False, name='conv1') .max_pool(2, 2, 2, 2, name='pool1') .conv(5, 5, 50, 1, 1...
colossalai/zero/sharded_param/sharded_tensor.py
RichardoLuo/ColossalAI
1,630
11112972
import torch from colossalai.gemini.stateful_tensor import StatefulTensor, TensorState class ShardedTensor(StatefulTensor): def __init__(self, tensor: torch.Tensor, state: TensorState = TensorState.HOLD) -> None: r""" A tensor sharded in multiple processes. Constructed from an existing torch.Tens...
compiler/bon.py
cheery/lever
136
11112974
""" binary object notation A data-interchange format. Used here because it is simpler to decode than other similar formats and can contain custom encodings. """ import struct types = {} decoder = {} encoder = {} def load(fd): type_id = ord(fd.read(1)) return decoder[type_id](fd) def dump(fd, obj...
examples/plots/partial-dependence-plot-2D.py
samueljamesbell/scikit-optimize
2,404
11113035
""" =========================== Partial Dependence Plots 2D =========================== Hvass-Labs Dec 2017 <NAME> 2020 .. currentmodule:: skopt Simple example to show the new 2D plots. """ print(__doc__) import numpy as np from math import exp from skopt import gp_minimize from skopt.space import Real, Categorical...
tests/slack_sdk/web/test_slack_response.py
priya1puresoftware/python-slack-sdk
2,486
11113078
<filename>tests/slack_sdk/web/test_slack_response.py import unittest from slack_sdk.web import WebClient from slack_sdk.web.slack_response import SlackResponse class TestSlackResponse(unittest.TestCase): def setUp(self): pass def tearDown(self): pass # https://github.com/slackapi/python...
samcli/lib/init/template_modifiers/xray_tracing_template_modifier.py
praneetap/aws-sam-cli
2,285
11113131
<gh_stars>1000+ """ Class used to parse and update template when tracing is enabled """ import logging from samcli.lib.init.template_modifiers.cli_template_modifier import TemplateModifier LOG = logging.getLogger(__name__) class XRayTracingTemplateModifier(TemplateModifier): FIELD_NAME_FUNCTION_TRACING = "Traci...
evosax/strategies/gld.py
RobertTLange/evosax
102
11113136
<gh_stars>100-1000 import jax import jax.numpy as jnp import chex from typing import Tuple from ..strategy import Strategy class GLD(Strategy): def __init__(self, num_dims: int, popsize: int): """Gradientless Descent (Golovin et al., 2019) Reference: https://arxiv.org/pdf/1911.06317.pdf""" ...
minimongo/index.py
ricksore/minimongo
144
11113147
# -*- coding: utf-8 -*- class Index(object): """A simple wrapper for arguments to :meth:`pymongo.collection.Collection.ensure_index`.""" def __init__(self, *args, **kwargs): self._args = args self._kwargs = kwargs def __eq__(self, other): """Two indices are equal, when they ha...
src/hg/makeDb/genbank/src/lib/py/genbank/__init__.py
andypohl/kent
171
11113152
<filename>src/hg/makeDb/genbank/src/lib/py/genbank/__init__.py<gh_stars>100-1000 import sys, os # require 2.4 or newer if (sys.version_info[0] <= 2) and (sys.version_info[1] < 4): raise Exception("python 2.4 or newer required, using " + sys.version) def gbAbsBinDir(): "get the absolute path to the bin directo...
MDEQ-Vision/lib/config/models.py
ashwinipokle/deq
548
11113159
# Modified based on the HRNet repo. from __future__ import absolute_import from __future__ import division from __future__ import print_function from yacs.config import CfgNode as CN MDEQ = CN() MDEQ.FULL_STAGE = CN() MDEQ.FULL_STAGE.NUM_MODULES = 1 MDEQ.FULL_STAGE.NUM_BRANCHES = 4 MDEQ.FULL_STAGE.NUM_BLOCKS = [1, 1...
apps/venv/lib/python2.7/site-packages/MySQLdb/constants/CR.py
gmacchi93/serverInfoParaguay
5,079
11113163
"""MySQL Connection Errors Nearly all of these raise OperationalError. COMMANDS_OUT_OF_SYNC raises ProgrammingError. """ MIN_ERROR = 2000 MAX_ERROR = 2999 UNKNOWN_ERROR = 2000 SOCKET_CREATE_ERROR = 2001 CONNECTION_ERROR = 2002 CONN_HOST_ERROR = 2003 IPSOCK_ERROR = 2004 UNKNOWN_HOST = 2005 SERVER_GONE_ERROR = 2006 VE...
samples/RecurringTask.py
amih90/bacpypes
240
11113177
#!/usr/bin/env python """ This application demonstrates doing something at a regular interval. """ import sys from bacpypes.debugging import bacpypes_debugging, ModuleLogger from bacpypes.consolelogging import ArgumentParser from bacpypes.core import run from bacpypes.task import RecurringTask # some debugging _de...
test/test_metrics/test_commons.py
wangjunyan305/homura
102
11113211
import torch from homura.metrics import commons # pred: [2, 0, 2, 2] input = torch.tensor([[0, 0, 1], [1, 0, 0], [0, 0, 1], [0, 0, 1]], dtype=torch.float) target = torch.tensor([2, 0, 0, 1], dtype=torch.long) def test_confusion_matrix(): cm = com...
tests/components/xiaomi_miio/__init__.py
MrDelik/core
30,023
11113224
<gh_stars>1000+ """Tests for the Xiaomi Miio integration.""" TEST_MAC = "ab:cd:ef:gh:ij:kl"
src/robomaster/module.py
talb430/RoboMaster-SDK
204
11113282
<filename>src/robomaster/module.py # -*-coding:utf-8-*- # Copyright (c) 2020 DJI. # # 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 in the file LICENSE.txt or at # # http://www.apache.org/lice...
spec/settings_spec.py
kfischer-okarin/mamba
462
11113310
# -*- coding: utf-8 -*- from mamba import description, it, context, before from expects import expect, have_property, equal, be_false, be_none from mamba.settings import Settings IRRELEVANT_SLOW_TEST_THRESHOLD = 'irrelevant slow test threeshold' IRRELEVANT_ENABLE_CODE_COVERAGE = 'irrelevant enable code coverage' IRR...
Alfred/BilibiliSearch/Source/bilibiliSearch.py
Vespa314/bilibili-api
1,460
11113326
# -*- coding: utf-8 -*- import sys import re import zlib import urllib2 import xml.etree.ElementTree as et default_encoding = 'utf-8' if sys.getdefaultencoding() != default_encoding: reload(sys) sys.setdefaultencoding(default_encoding) class Feedback(): """Feeback used by Alfred Script Filter Usage:...
ioflo/base/deeding.py
BradyHammond/ioflo
128
11113339
<reponame>BradyHammond/ioflo<gh_stars>100-1000 """ deeding.py deed module Backwards compatibility module Future use doing module instead """ from . import doing # for backwards compatibility deedify = doing.doify class Deed(doing.Doer): pass class DeedParam(doing.DoerParam): pass class DeedSince(doing.Doe...
RecoLocalTracker/SubCollectionProducers/python/TopBottomClusterInfoProducer_cfi.py
ckamtsikis/cmssw
852
11113347
<reponame>ckamtsikis/cmssw import FWCore.ParameterSet.Config as cms topBottomClusterInfoProducer = cms.EDProducer("TopBottomClusterInfoProducer", stripClustersOld = cms.InputTag("siStripClusters"), pixelClustersOld = cms.InputTag("siPixelClusters"), stripClustersNew = cms.InputTag("siStripClustersTop"), ...
pliers/tests/converters/api/test_revai_converters.py
nickduran/pliers
229
11113372
<reponame>nickduran/pliers from os.path import join import pytest from ...utils import get_test_data_path from pliers.converters import RevAISpeechAPIConverter from pliers.stimuli import AudioStim, ComplexTextStim, TextStim AUDIO_DIR = join(get_test_data_path(), 'audio') @pytest.mark.requires_payment @pytest.mark....
omega_miya/plugins/omega_plugins_manager/__init__.py
rinrini001/omega-miya
120
11113419
<reponame>rinrini001/omega-miya """ @Author : Ailitonia @Date : 2021/09/12 14:02 @FileName : __init__.py.py @Project : nonebot2_miya @Description : 插件管理器 @GitHub : https://github.com/Ailitonia @Software : PyCharm """ import pathlib from nonebot import CommandGroup, get...
examples/LCD/main.py
ccccmagicboy2022/pikascript
228
11113439
<filename>examples/LCD/main.py from PikaObj import * import PikaStdLib import PikaPiZero import STM32G0 lcd = PikaPiZero.LCD() lcd.init() lcd.clear('white') mem = PikaStdLib.MemChecker() key = PikaPiZero.KEY() key.init() time = STM32G0.Time() h = 10 w = 10 x = 10 y = 10 x_last = x y_last = y is_update = 0 print('mem u...
tests/ut/python/dataset/test_random_lighting.py
PowerOlive/mindspore
3,200
11113441
<gh_stars>1000+ # Copyright 2021 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 ...
rls/envs/wrappers/vec.py
StepNeverStop/RLs
371
11113489
#!/usr/bin/env python3 # encoding: utf-8 from typing import Dict, List, Tuple, Union class VECEnv: def __init__(self, n, env_fn, config: Dict = {}): self.idxs = list(range(n)) self._envs = [env_fn(idx, **config) for idx in self.idxs] def run(self, attr: str, params: Union[Tuple, List, Dict]...
twistedcaldav/dropbox.py
backwardn/ccs-calendarserver
462
11113490
## # Copyright (c) 2006-2017 Apple 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 applicable l...
influx-test/writerow.py
1514louluo/influx-proxy
130
11113491
<reponame>1514louluo/influx-proxy<gh_stars>100-1000 import time import requests import multiprocessing as mlp from mytime import mytime def url(precision='ns'): return 'http://localhost:7076/write?db=test&precision='+precision def send(m, precision, number, init_time): t = init_time.t_p(precision) for i...
components/isceobj/IsceProc/runRgoffset_ampcor.py
vincentschut/isce2
1,133
11113508
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Copyright 2014 California Institute of Technology. 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 th...
tests/multi_net/uasyncio_tcp_close_write.py
sebastien-riou/micropython
13,648
11113512
<gh_stars>1000+ # Test uasyncio TCP stream closing then writing try: import uasyncio as asyncio except ImportError: try: import asyncio except ImportError: print("SKIP") raise SystemExit PORT = 8000 async def handle_connection(reader, writer): # Write data to ensure connectio...
examples/pxScene2d/external/libnode-v10.15.3/test/addons-napi/test_env_sharing/binding.gyp
madanagopaltcomcast/pxCore
1,144
11113513
<gh_stars>1000+ { "targets": [ { "target_name": "store_env", "sources": [ "store_env.c" ] }, { "target_name": "compare_env", "sources": [ "compare_env.c" ] } ] }
ci/docker/docker-in-docker-image/publish-docker-image/publish_docker_image/command.py
bugtsa/avito-android
347
11113535
import os import fire import yaml from .emulator import publish_emulator from .docker import publish, test CONFIG_FILE = 'image.yaml' # noinspection PyClassHasNoInit class Command: @staticmethod def publish(directory): config_file_path = Command._check_configuration(directory) with open(co...
webdataset/tests/test_utils.py
techthiyanes/webdataset
389
11113640
from webdataset import utils def test_repeatedly(): assert len(list(utils.repeatedly(range(3), nepochs=7))) == 21 def test_repeatedly2(): assert len(list(utils.repeatedly(range(3), nbatches=10))) == 10 def test_repeatedly3(): assert len(list(utils.repeatedly([[[1, 1], [2, 2]]] * 3, nsamples=10))) == 5...
AE_Datasets/O_A/datasets/__init__.py
MasterXin2020/DL-based-Intelligent-Diagnosis-Benchmark
200
11113667
<reponame>MasterXin2020/DL-based-Intelligent-Diagnosis-Benchmark<filename>AE_Datasets/O_A/datasets/__init__.py #!/usr/bin/python # -*- coding:utf-8 -*- from AE_Datasets.O_A.datasets.CWRU import CWRU from AE_Datasets.O_A.datasets.CWRUFFT import CWRUFFT from AE_Datasets.O_A.datasets.CWRUCWT import CWRUCWT from AE_Datase...
tests/ex01_compose_v2/models.py
RodrigoDeRosa/related
190
11113670
import related @related.immutable class Service(object): name = related.StringField() image = related.StringField(required=False) build = related.StringField(required=False) ports = related.SequenceField(str, required=False) volumes = related.SequenceField(str, required=False) command = relate...
the-basic-mq/python/app.py
mttfarmer/serverless
1,627
11113674
#!/usr/bin/env python3 from aws_cdk import core from the_basic_mq.the_basic_mq_stack import TheBasicMQStack app = core.App() TheBasicMQStack(app, "TheBasicMQStack", env=core.Environment(region="us-east-1")) app.synth()
mastermind/http.py
gap892003/mastermind
389
11113678
from __future__ import (absolute_import, print_function, division) from mitmproxy.models import Headers, HTTPResponse status_codes = {100: 'Continue', 101: 'Switching Protocols', 200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non-Autho...
docker/build_files/entrypoint-nvidia.py
PeihongYu/surreal
471
11113697
<gh_stars>100-1000 #!/usr/bin/env python import os import sys import shlex import shutil def init(): os.system('Xdummy > /dev/null 2>&1 &') if os.path.exists('/etc/secrets/mjkey.txt'): shutil.copy('/etc/secrets/mjkey.txt', '/root/.mujoco/mjkey.txt') os.system('python -c "import mujoco_py"') o...
ch13/ch13_part2.py
ericgarza70/machine-learning-book
655
11113698
<filename>ch13/ch13_part2.py # coding: utf-8 import sys from python_environment_check import check_packages import numpy as np import torch import torch.nn as nn import pandas as pd import sklearn import sklearn.model_selection from torch.nn.functional import one_hot from torch.utils.data import DataLoader, TensorDat...