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
code/tests/__init__.py
teamiceberg/python-machine-learning-book-2nd-edition
6,947
11138410
# <NAME> 2016-2017 # # ann is a supporting package for the book # "Introduction to Artificial Neural Networks and Deep Learning: # A Practical Guide with Applications in Python" # # Author: <NAME> <<EMAIL>> # # License: MIT
dash-set-height-of-graph.py
oriolmirosa/dash-recipes
932
11138412
import dash import dash_core_components as dcc import dash_html_components as html import plotly.graph_objs as go import pandas as pd stats= { 'Goals': [43,32,19,32,20,15,20,19,19,21,19,8,14], 'Assists': [67, 55, 63, 39, 36, 34, 23, 21, 20, 16, 15, 26, 17], 'Points' : [110, 86, 82, 71, 56, 49, 43, 40, 39, ...
scikit_learn_bring_your_own_model_local_serving/scikit_learn_bring_your_own_model_local_serving.py
aws-samples/amazon-sagemaker-local-mode
111
11138437
# This is a sample Python program that serve a scikit-learn model pre-trained on the California Housing dataset. # This implementation will work on your *local computer* or in the *AWS Cloud*. # # Prerequisites: # 1. Install required Python packages: # `pip install -r requirements.txt` # 2. Docker Desktop inst...
openaerostruct/structures/disp.py
lamkina/OpenAeroStruct
114
11138448
<filename>openaerostruct/structures/disp.py import numpy as np import openmdao.api as om class Disp(om.ExplicitComponent): """ Reshape the flattened displacements from the linear system solution into a 2D array so we can more easily use the results. The solution to the linear system has meaingless e...
docs/examples/userguide/numpy_tutorial/compute_py.py
smok-serwis/cython
6,663
11138454
import numpy as np def clip(a, min_value, max_value): return min(max(a, min_value), max_value) def compute(array_1, array_2, a, b, c): """ This function must implement the formula np.clip(array_1, 2, 10) * a + array_2 * b + c array_1 and array_2 are 2D. """ x_max = array_1.shape[0] ...
crypto-primitive/solve.py
sixstars/starctf2018
140
11138458
<reponame>sixstars/starctf2018<gh_stars>100-1000 from pwn import * import string from hashlib import sha256 #context.log_level='debug' def dopow(): chal = c.recvline() post = chal[12:28] tar = chal[33:-1] c.recvuntil(':') found = iters.bruteforce(lambda x:sha256(x+post).hexdigest()==tar, string.asc...
adabins/evaluate.py
rosivbus/aphantasia
579
11138461
<filename>adabins/evaluate.py import argparse import os import sys import numpy as np import torch import torch.nn as nn from PIL import Image from tqdm import tqdm import model_io from dataloader import DepthDataLoader from models import UnetAdaptiveBins from utils import RunningAverageDict def compute_errors(gt, ...
demos/python/sdk_wireless_camera_control/tests/e2e/test_gopro_wifi_commands_e2e.py
Natureshadow/OpenGoPro
210
11138463
# test_gopro_wifi_commands_e2e.py/Open GoPro, Version 2.0 (C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro). # This copyright was auto-generated on Tue Sep 7 21:35:52 UTC 2021 """End to end testing of GoPro BLE functionality""" from pathlib import Path import pytest from open_gopro import GoPro from open...
concordia/migrations/0032_topic_ordering.py
juliecentofanti172/juliecentofanti.github.io
134
11138470
# Generated by Django 2.2 on 2019-05-29 18:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("concordia", "0031_auto_20190509_1142")] operations = [ migrations.AddField( model_name="topic", name="ordering", field=...
sqlacodegen/codegen.py
danerlt/flask-sqlacodegen
265
11138477
<gh_stars>100-1000 """Contains the code generation logic and helper functions.""" from __future__ import unicode_literals, division, print_function, absolute_import from collections import defaultdict from inspect import ArgSpec from keyword import iskeyword import inspect import sys import re from sqlalchemy import (...
DQMOffline/JetMET/test/run_PromptAna_GR108290_Calo.py
ckamtsikis/cmssw
852
11138482
# import FWCore.ParameterSet.Config as cms process = cms.Process("test") process.load("CondCore.DBCommon.CondDBSetup_cfi") # # DQM # process.load("DQMServices.Core.DQM_cfg") process.load("DQMServices.Components.MEtoEDMConverter_cfi") # HCALNoise module process.load("RecoMET.METProducers.hcalnoiseinfoproducer_cfi")...
ad_examples/aad/aad_stream.py
matwey/ad_examples
773
11138488
import os import logging import numpy as np from ..common.utils import ( logger, InstanceList, Timer, append_instance_lists, cbind, rbind, append, matrix, read_data_as_matrix, get_sample_feature_ranges, configure_logger ) from ..common.metrics import fn_auc from .aad_globals import ( STREAM_RETENTION_OVERWR...
tests/epyccel/test_epyccel_IfTernaryOperator.py
dina-fouad/pyccel
206
11138489
<reponame>dina-fouad/pyccel # pylint: disable=missing-function-docstring, missing-module-docstring/ import pytest from pyccel.epyccel import epyccel from pyccel.decorators import types # wp suffix means With Parentheses #------------------------------------------------------------------------------ def test_f1(langua...
numpy/_globals.py
leonarduschen/numpy
603
11138517
""" Module defining global singleton classes. This module raises a RuntimeError if an attempt to reload it is made. In that way the identities of the classes defined here are fixed and will remain so even if numpy itself is reloaded. In particular, a function like the following will still work correctly after numpy is...
sympy/physics/mechanics/tests/test_method.py
utkarshdeorah/sympy
8,323
11138521
<filename>sympy/physics/mechanics/tests/test_method.py from sympy.physics.mechanics.method import _Methods from sympy.testing.pytest import raises def test_method(): raises(TypeError, lambda: _Methods())
components/test/data/autofill/automated_integration/autofill_test/suite.py
zealoussnow/chromium
14,668
11138558
# Copyright 2016 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. """Chrome Autofill Test Flow Execute a set of autofill tasks in a fresh ChromeDriver instance that has been pre-loaded with some default profile. Requires:...
tests/guinea-pigs/nose/doctests/namespace1/d.py
djeebus/teamcity-python
105
11138566
<reponame>djeebus/teamcity-python<gh_stars>100-1000 def multiply(a, b): """ 'multiply' multiplies two numbers and returns the result. >>> multiply(5, 10) 50 >>> multiply(-1, 1) -1 >>> multiply(0.5, 1.5) 0.75 """ return a*b
python/oneflow/compatible/single_client/test/ops/test_unsorted_batch_segment_sum.py
wangyuyue/oneflow
3,285
11138572
""" Copyright 2020 The OneFlow 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 applicable law or agr...
opennmt/tests/api_test.py
gcervantes8/OpenNMT-tf
1,363
11138574
<gh_stars>1000+ import inspect import tensorflow as tf import opennmt class APITest(tf.test.TestCase): def testSubmodules(self): def _check(module): self.assertTrue(inspect.ismodule(module)) _check(opennmt.data) _check(opennmt.decoders) _check(opennmt.encoders) ...
src/amuse/io/gadget.py
rknop/amuse
131
11138595
<gh_stars>100-1000 import struct import numpy from collections import namedtuple from amuse.io import base from amuse.units import units from amuse.units import nbody_system from amuse.support.core import late from amuse import datamodel class GadgetFileFormatProcessor(base.FortranFileFormatProcessor): """ ...
docs/patch.py
gselzer/magicgui
185
11138623
from pathlib import Path from sphinx_jupyterbook_latex import transforms text = Path(transforms.__file__).read_text() text = text.replace('tocnode.attributes["hidden"]', 'tocnode.attributes.get("hidden")') Path(transforms.__file__).write_text(text)
insights/parsers/crypto_policies.py
lhuett/insights-core
121
11138624
""" crypto-policies - files in ``/etc/crypto-policies/back-ends/`` ============================================================== This is a collection of parsers that all deal with the generated configuration files under the ``/etc/crypto-policies/back-ends/`` folder. Parsers included in this module are: CryptoPolic...
lib/pytube/request.py
Rinka433/Fxc7-Api
119
11138646
# -*- coding: utf-8 -*- """Implements a simple wrapper around urlopen.""" import logging from functools import lru_cache from http.client import HTTPResponse from typing import Iterable, Dict, Optional from urllib.request import Request from urllib.request import urlopen logger = logging.getLogger(__name__) def _ex...
evan69/0004/0004.py
saurabh896/python-1
3,976
11138667
<filename>evan69/0004/0004.py import collections,re import sys def cal(filename = 'in.txt'): print 'now processing:' + filename + '......' f = open(filename,'r') data = f.read() dic = collections.defaultdict(lambda :0) data = re.sub(r'[\W\d]',' ',data) data = data.lower() datalist = data.split(' ') for item in ...
aiida/repository/common.py
azadoks/aiida-core
180
11138674
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # ...
dbaas/logical/models.py
globocom/database-as-a-service
303
11138678
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import simple_audit import logging import datetime from datetime import date, timedelta from django.db import models, transaction, Error from django.db.models.signals import pre_save, post_save, pre_delete from django.contrib.auth.models i...
reid/loss/triplet.py
zhangxinyu-tj/PAST
112
11138679
<filename>reid/loss/triplet.py from __future__ import absolute_import import torch from torch import nn from torch.autograd import Variable import torch.nn.functional as F class OnlineTripletLoss(nn.Module): def __init__(self, margin=0): super(OnlineTripletLoss, self).__init__() self.margin = mar...
cvxpy/expressions/constants/callback_param.py
hashstat/cvxpy
3,285
11138688
""" Copyright 2013 <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 http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distrib...
test/old_tests/_test_kv.py
syaiful6/aerospike-client-python
105
11138692
import unittest import sys import pytest from .test_base_class import TestBaseClass from aerospike import exception as e aerospike = pytest.importorskip("aerospike") try: import aerospike except: print("Please install aerospike python client.") sys.exit(1) config = {"hosts": [("127.0.0.1", 3000)]} # cou...
leet/strings/wordBreak.py
peterlamar/python-cp-cheatsheet
140
11138727
""" time: n^2 space: n """ class Solution: # go through word and check if slice matches subword, go until the end def wordBreak(self, s: str, wordDict: List[str]) -> bool: stk = [0] visited = set() while stk: i = stk.pop() visited.add(i) # che...
cvxpy/reductions/dgp2dcp/atom_canonicalizers/norm_inf_canon.py
QiuWJX/cvxpy
3,285
11138741
from cvxpy.atoms.max import max from cvxpy.reductions.eliminate_pwl.atom_canonicalizers.max_canon import ( max_canon,) def norm_inf_canon(expr, args): assert len(args) == 1 tmp = max(args[0], expr.axis, expr.keepdims) return max_canon(tmp, tmp.args)
python/src/stdbscan.py
eubr-bigsea/py-st-dbscan
126
11138742
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from datetime import timedelta import pyproj class STDBSCAN(object): def __init__(self, spatial_threshold=500.0, temporal_threshold=60.0, min_neighbors=15): """ Python ST-DBSCAN implementation. Because this al...
src/ralph/assets/migrations/0025_auto_20170331_1341.py
DoNnMyTh/ralph
1,668
11138755
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('assets', '0024_auto_20170322_1148'), ] operations = [ migrations.AlterField( mo...
synapse/mindmeld.py
ackroute/synapse
216
11138762
<gh_stars>100-1000 # reserved for future use
davarocr/davarocr/davar_det/models/losses/dice_loss.py
icedream2/DAVAR-Lab-OCR
387
11138768
""" ################################################################################################# # Copyright Info : Copyright (c) <NAME> @ Hikvision Research Institute. All rights reserved. # Filename : dice_loss.py # Abstract : Implements of dice loss. Refer to https://github.com/hubutui/Dice...
examples/core/geom/projective_ops.py
mli0603/lietorch
360
11138776
import torch import torch.nn.functional as F from lietorch import SE3, Sim3 MIN_DEPTH = 0.1 def extract_intrinsics(intrinsics): return intrinsics[...,None,None,:].unbind(dim=-1) def iproj(disps, intrinsics): """ pinhole camera inverse projection """ ht, wd = disps.shape[2:] fx, fy, cx, cy = extract_...
openstack-seeder/python/setup.py
kayrus/kubernetes-operators
127
11138789
<filename>openstack-seeder/python/setup.py from setuptools import setup setup( name='openstack_seeder', version='2.0.1', packages='.', install_requires=[ 'python-keystoneclient>=3.20.0', 'python-novaclient>=14.2.0', 'python-neutronclient>=6.12.0', 'python-designateclient...
research/object_detection/models/keras_models/resnet_v1_test.py
873040/Abhishek
153
11138794
<filename>research/object_detection/models/keras_models/resnet_v1_test.py # Copyright 2019 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 # # ...
hail/python/test/hail/utils/test_google_fs_utils.py
3vivekb/hail
789
11138808
import unittest import hail as hl from hail.utils import hadoop_open, hadoop_copy from hail.fs.hadoop_fs import HadoopFS from ..helpers import startTestHailContext, stopTestHailContext, resource, _initialized import os setUpModule = startTestHailContext tearDownModule = stopTestHailContext class Tests(unittest.Tes...
examples/dialogue/dialogue/Trainer.py
ZfSangkuan/ASER
256
11138809
<reponame>ZfSangkuan/ASER import os import torch from dialogue.models.constructor import construct_model from dialogue.toolbox.stats import Statistics class Trainer(object): def __init__(self, train_iter, valid_iter, vocabs, optimizer, train_opt, logger): self.train_iter = train_iter ...
member.py
YiWeiShen/v2ex
161
11138810
<filename>member.py #!/usr/bin/env python # coding=utf-8 import os import base64 import re import time import datetime import hashlib import httplib import string import pickle from StringIO import StringIO from django.utils import simplejson as json from google.appengine.ext import webapp from google.appengine.api...
homeassistant/components/home_plus_control/__init__.py
MrDelik/core
30,023
11138819
"""The Legrand Home+ Control integration.""" import asyncio from datetime import timedelta import logging import async_timeout from homepluscontrol.homeplusapi import HomePlusControlApiError import voluptuous as vol from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_CLIENT_ID, C...
boost/tools/build/v2/test/boostbook.py
randolphwong/mcsema
11,356
11138824
<filename>boost/tools/build/v2/test/boostbook.py #!/usr/bin/python # Copyright 2004, 2006 <NAME> # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) import BoostBuild import string t = BoostBuild.Tester() t.set_tree("boostboo...
eeauditor/auditors/aws/Amazon_CloudFront_Auditor.py
kbhagi/ElectricEye
442
11138828
<filename>eeauditor/auditors/aws/Amazon_CloudFront_Auditor.py<gh_stars>100-1000 #This file is part of ElectricEye. #SPDX-License-Identifier: Apache-2.0 #Licensed to the Apache Software Foundation (ASF) under one #or more contributor license agreements. See the NOTICE file #distributed with this work for additional in...
web/tests/functional/component/__init__.py
ryankurte/codechecker
1,601
11138873
# coding=utf-8 # ------------------------------------------------------------------------- # # Part of the CodeChecker project, under the Apache License v2.0 with # LLVM Exceptions. See LICENSE for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # # ------------------------------------...
examples/convert/agilent2pipe_3d/agilent2pipe_3d.py
genematx/nmrglue
150
11138876
#! /usr/bin/env python import nmrglue as ng # read in the Agilent data (any of the follow lines will work) #dic, data=ng.varian.read("agilent_3d") dic, data=ng.varian.read_lowmem("agilent_3d") # Set the spectral parameters udic = ng.varian.guess_udic(dic, data) # Direct Dimension udic[2]['size'] = 1250 udic[2][...
src/appier/request.py
BeeMargarida/appier
127
11138890
<filename>src/appier/request.py #!/usr/bin/python # -*- coding: utf-8 -*- # Hive Appier Framework # Copyright (c) 2008-2021 Hive Solutions Lda. # # This file is part of Hive Appier Framework. # # Hive Appier Framework is free software: you can redistribute it and/or modify # it under the terms of the Apache L...
setup.py
jmoon1506/python-sonic
263
11138896
<gh_stars>100-1000 from setuptools import setup # To use a consistent encoding # python setup.py sdist bdist_wheel # python -m twine upload dist/* from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.r...
tests/autocast_test.py
gglin001/poptorch
128
11138945
<gh_stars>100-1000 #!/usr/bin/env python3 # Copyright (c) 2020 Graphcore Ltd. All rights reserved. import pytest import torch import poptorch import helpers @pytest.mark.parametrize("setting", {"default", "true", "false"}) @helpers.printCapfdOnExit @helpers.overridePoptorchLogLevel("TRACE") def test_autocast_decorat...
stix_shifter_modules/trendmicro_vision_one/test/stix_translation/test_result_translator.py
pyromaneact/stix-shifter
129
11138967
<reponame>pyromaneact/stix-shifter<gh_stars>100-1000 # -*- coding: utf-8 -*- import json import unittest import uuid from datetime import datetime from stix_shifter_utils.stix_translation.src.utils.exceptions import LoadJsonResultsException, TranslationResultException from stix_shifter_modules.trendmicro_vision_one.e...
loopchain/blockchain/transactions/v3_issue/__init__.py
windies21/loopchain
105
11138968
<gh_stars>100-1000 from .transaction import Transaction, HASH_SALT from .transaction_serializer import TransactionSerializer from .transaction_verifier import TransactionVerifier version = Transaction.version
app/server/labml_app/analyses/computers/disk.py
vishalbelsare/labml
463
11138973
from typing import Dict, Any from fastapi import Request from fastapi.responses import JSONResponse from labml_db import Model, Index from labml_db.serializer.pickle import PickleSerializer from labml_app.logger import logger from labml_app.enums import COMPUTEREnums from ..analysis import Analysis from ..series impo...
testing/toy_model.py
chenw23/open_lth
509
11138999
# 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. import torch from models.base import Model class InnerProductModel(Model): @staticmethod def default_hparams(): raise NotImplemented...
tests/test_log_levels.py
rohankumardubey/structlog
1,751
11139006
<filename>tests/test_log_levels.py # SPDX-License-Identifier: MIT OR Apache-2.0 # This file is dual licensed under the terms of the Apache License, Version # 2.0, and the MIT License. See the LICENSE file in the root of this # repository for complete details. import logging import pickle import pytest from structlo...
architect/commands/__init__.py
dimagi/architect
352
11139013
""" Provides unified interface for all Architect commands. Each command should live in a separate module and define an "arguments" variable which should contain the command's arguments and a "run" function which implements the command's behaviour. """ import os import sys import pkgutil import argparse from .. import...
ultimatepython/data_structures/list.py
Mu-L/ultimate-python
3,678
11139038
""" Lists are a sequence of values that can be modified at runtime. This module shows how lists are created, iterated, accessed, extended and shortened. """ def main(): # This is a list of strings where # "a" is a string at index 0 and # "e" is a string at index 4 letters = ["a", "b", "c", "d", "e"] ...
foreman/data_refinery_foreman/foreman/management/commands/assoc_experiment_results.py
AlexsLemonade/refinebio
106
11139070
"""This command will go through ComputationalResult objects that are a result of the tximport Processor and associate them with the experiment that tximport was run on. It's purpose is to populate missing links in our data model, however once it does so there are additional PRs planned which will break an assumption th...
esmvaltool/diag_scripts/hydrology/derive_evspsblpot.py
cffbots/ESMValTool
148
11139104
"""Derive Potential Evapotransporation (evspsblpot) using De Bruin (2016). <NAME>., <NAME>., <NAME>., <NAME>.: A Thermodynamically Based Model for Actual Evapotranspiration of an Extensive Grass Field Close to FAO Reference, Suitable for Remote Sensing Application, American Meteorological Society, 17, 1373-1382, DOI: ...
modeller/transformation.py
SunGuo/500lines
134
11139130
<gh_stars>100-1000 import numpy def translation(displacement): t = numpy.identity(4) t[0, 3] = displacement[0] t[1, 3] = displacement[1] t[2, 3] = displacement[2] return t def scaling(scale): s = numpy.identity(4) s[0, 0] = scale[0] s[1, 1] = scale[1] s[2, 2] = scale[2] s[3, ...
slack_bolt/context/respond/async_respond.py
hirosassa/bolt-python
504
11139135
from typing import Optional, Union, Sequence from slack_sdk.models.attachments import Attachment from slack_sdk.models.blocks import Block from slack_sdk.webhook.async_client import AsyncWebhookClient, WebhookResponse from slack_bolt.context.respond.internals import _build_message class AsyncRespond: response_u...
elastalert/alerters/gitter.py
perceptron01/elastalert2
250
11139193
import json import requests from requests import RequestException from elastalert.alerts import Alerter, DateTimeEncoder from elastalert.util import EAException, elastalert_logger class GitterAlerter(Alerter): """ Creates a Gitter activity message for each alert """ required_options = frozenset(['gitter_web...
tdda/referencetest/tests/testregeneration.py
jjlee42/tdda
232
11139199
# -*- coding: utf-8 -*- # # Unit tests for reference data regeneration # from __future__ import absolute_import from __future__ import unicode_literals from __future__ import division import os import tempfile import unittest from tdda.referencetest.referencetest import ReferenceTest class TestRegenerate(unittest...
sdk/python/pulumi_azure/securitycenter/workspace.py
henriktao/pulumi-azure
109
11139205
# 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, overload from .. import...
lib/cherrypy/_cpnative_server.py
0x20Man/Watcher3
320
11139228
"""Native adapter for serving CherryPy via its builtin server.""" import logging import sys import io import cheroot.server import cherrypy from cherrypy._cperror import format_exc, bare_error from cherrypy.lib import httputil class NativeGateway(cheroot.server.Gateway): recursive = False def respond(sel...
neuralmonkey/trainers/__init__.py
kasnerz/neuralmonkey
446
11139243
from .cross_entropy_trainer import CrossEntropyTrainer from .delayed_update_trainer import DelayedUpdateTrainer from .multitask_trainer import MultitaskTrainer
deepsnap/dataset.py
ruth-ann/deepsnap
412
11139265
<reponame>ruth-ann/deepsnap import copy import math import types import random import networkx as nx import numpy as np import torch import deepsnap from deepsnap.graph import Graph from deepsnap.hetero_graph import HeteroGraph import pdb from typing import ( Dict, List, Union ) import warnings class Gene...
tests/tracer/runtime/test_container.py
p7g/dd-trace-py
308
11139277
import mock import pytest from ddtrace.internal.compat import PY2 from ddtrace.internal.runtime.container import CGroupInfo from ddtrace.internal.runtime.container import get_container_info from .utils import cgroup_line_valid_test_cases # Map expected Py2 exception to Py3 name if PY2: FileNotFoundError = IOErr...
scattertext/representations/CorpusSentenceIterator.py
shettyprithvi/scattertext
1,823
11139283
<gh_stars>1000+ import itertools from scattertext import ParsedCorpus class CorpusSentenceIterator(object): @staticmethod def get_sentences(corpus): ''' Parameters ---------- corpus, ParsedCorpus Returns ------- iter: [sentence1word1, ...], [sentence2word1, ...] ''' assert isinstance(corpus, Par...
tests/modeling/test_modeling_model_ema.py
wenliangzhao2018/d2go
687
11139288
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import copy import itertools import unittest import d2go.runner.default_runner as default_runner import torch from d2go.modeling import model_ema from d2go.utils.testing import helper class TestArch(torch.nn.Module): ...
botocore/retries/special.py
doc-E-brown/botocore
1,738
11139294
<gh_stars>1000+ """Special cased retries. These are additional retry cases we still have to handle from the legacy retry handler. They don't make sense as part of the standard mode retry module. Ideally we should be able to remove this module. """ import logging from binascii import crc32 from botocore.retries.base...
menpo/io/input/__init__.py
apapaion/menpo
311
11139296
<gh_stars>100-1000 from .base import ( import_image, import_images, image_paths, import_video, import_videos, video_paths, import_landmark_file, import_landmark_files, landmark_file_paths, import_pickle, import_pickles, pickle_paths, import_builtin_asset, menpo_da...
fbpic/particles/elementary_process/compton/inline_functions.py
fractional-ray/fbpic
131
11139325
<reponame>fractional-ray/fbpic """ This file is part of the Fourier-Bessel Particle-In-Cell code (FB-PIC) It defines inline functions that are used both on GPU and CPU, and used in the Compton scattering code. These functions are compiled for GPU or CPU respectively, when imported into the files numba_methods.py and c...
qiskit/utils/classtools.py
Roshan-Thomas/qiskit-terra
1,456
11139334
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
_old/ReplyDict/replydict.py
tigefa4u/reddit
444
11139353
#/u/GoldenSights import json import praw import random import sqlite3 import time import traceback '''USER CONFIGURATION''' APP_ID = "" APP_SECRET = "" APP_URI = "" APP_REFRESH = "" # https://www.reddit.com/comments/3cm1p8/how_to_make_your_bot_use_oauth2/ USERAGENT = "" #This is a short description of what the bot do...
pytorch_nlu/pytorch_sequencelabeling/slPredict.py
dumpmemory/Pytorch-NLU
115
11139388
<reponame>dumpmemory/Pytorch-NLU # !/usr/bin/python # -*- coding: utf-8 -*- # @time : 2021/7/25 19:30 # @author : Mo # @function: predict model, 预测模块 # 适配linux import sys import os path_root = os.path.abspath(os.path.join(os.path.dirname(__file__), ".")) sys.path.append(path_root) from tcConfig import model_confi...
1]. DSA/1]. Data Structures/06]. Linked List/Python/count_rotations.py
Utqrsh04/The-Complete-FAANG-Preparation
6,969
11139396
<reponame>Utqrsh04/The-Complete-FAANG-Preparation<filename>1]. DSA/1]. Data Structures/06]. Linked List/Python/count_rotations.py from insertion import node def push(head_ref, newdata): new_node = node(newdata) new_node.data = newdata new_node.next = head_ref head_ref = new_node return head_...
alex/utils/interface.py
oplatek/alex
184
11139397
import inspect def interface_method(f): f.abstract = True return f class Interface(object): def __new__(cls, *args, **kwargs): res = super(Interface, cls).__new__(cls, *args, **kwargs) missing_methods = [] for method in inspect.getmembers(res, predicate=inspect.ismethod): ...
mmf/datasets/builders/clevr/dataset.py
facebookresearch/pythia
3,252
11139404
<gh_stars>1000+ import json import os import numpy as np import torch from mmf.common.sample import Sample from mmf.datasets.base_dataset import BaseDataset from mmf.utils.distributed import is_main, synchronize from mmf.utils.general import get_mmf_root from mmf.utils.text import tokenize, VocabFromText from PIL impo...
gluoncv/auto/estimators/yolo/utils.py
Kh4L/gluon-cv
5,447
11139423
"""Utils for auto YOLO estimator""" import os from mxnet import gluon from ....data import MixupDetection from ....data.batchify import Tuple, Stack, Pad from ....data.dataloader import RandomTransformDataLoader from ....data.transforms.presets.yolo import YOLO3DefaultTrainTransform from ....data.transforms.presets.y...
osf/migrations/0176_pagecounter_data.py
gaybro8777/osf.io
628
11139444
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-11-12 17:18 from __future__ import unicode_literals import logging from django.db import migrations from osf.management.commands.migrate_pagecounter_data import FORWARD_SQL, REVERSE_SQL from website.settings import DEBUG_MODE logger = logging.getLogger(_...
examples/example_sim_grad_cloth.py
NVIDIA/warp
306
11139448
<gh_stars>100-1000 # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this ...
nhentai/__init__.py
xyzkljl1/nhentai
673
11139458
__version__ = '0.4.16' __author__ = 'RicterZ' __email__ = '<EMAIL>'
dbReports/iondb/rundb/data/dmfilestat_utils.py
konradotto/TS
125
11139487
#!/usr/bin/env python # Copyright (C) 2014 Ion Torrent Systems, Inc. All Rights Reserved from __future__ import absolute_import import os import errno from django.db.models import Sum from iondb.rundb.models import DMFileStat, FileServer, Chip from iondb.rundb.data import dmactions_types from iondb.rundb.data import ...
src/ros_comm/roswtf/src/roswtf/rules.py
jungleni/ros_code_reading
742
11139504
<reponame>jungleni/ros_code_reading<gh_stars>100-1000 # Software License Agreement (BSD License) # # Copyright (c) 2009, <NAME>, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redis...
robinhood/exceptions.py
mrklees/robinhood-python
106
11139507
<filename>robinhood/exceptions.py class NotFound(Exception): pass class NotLoggedIn(Exception): pass class MfaRequired(Exception): pass class BadRequest(Exception): pass class TooManyRequests(Exception): pass class Forbidden(Exception): pass
DPGAnalysis/Skims/python/RPCNoise_example.py
ckamtsikis/cmssw
852
11139531
import FWCore.ParameterSet.Config as cms process = cms.Process("USER") process.load("Configuration/StandardSequences/Geometry_cff") process.load("Configuration/StandardSequences/MagneticField_38T_cff") process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff") process.GlobalTag.globaltag = 'CRUZ...
problems/euler/47/euler_math.py
vidyadeepa/the-coding-interview
1,571
11139566
class Primes(object): """ A dynamic (growing) Sieve of Erathostenes """ def __init__(self, sieve_size = 2**22): self.primes = set() self.multiples = set() self.sieve_size = sieve_size # Initial sieve size self.curr = 2 # Start number to search for primes def all(self): return self.primes...
src/track_3d.py
noskill/JRMOT_ROS
112
11139583
<filename>src/track_3d.py<gh_stars>100-1000 # vim: expandtab:ts=4:sw=4 import numpy as np import pdb import torch class TrackState: """ Enumeration type for the single target track state. Newly created tracks are classified as `tentative` until enough evidence has been collected. Then, the track state ...
PyObjCTest/test_nsobjcruntime.py
Khan/pyobjc-framework-Cocoa
132
11139584
from PyObjCTools.TestSupport import * import sys from Foundation import * try: unicode except NameError: unicode = str try: long except NameError: long = int class TestNSObjCRuntime (TestCase): def testConstants(self): self.assertEqual(NSFoundationVersionNumber10_0, 397.40) se...
content/test/gpu/run_unittests.py
iridium-browser/iridium-browser
575
11139591
<filename>content/test/gpu/run_unittests.py #!/usr/bin/env vpython # 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 script runs unit tests of the code in the gpu_tests/ directory. This script DOES N...
fuzzinator/reduce/reducer.py
akosthekiss/fuzzinator
202
11139599
<filename>fuzzinator/reduce/reducer.py # Copyright (c) 2021 <NAME>, <NAME>. # # Licensed under the BSD 3-Clause License # <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>. # This file may not be copied, modified, or distributed except # according to those terms. class Reducer(object): """ Abstrac...
tests/slashless/api/resources.py
pavanv/django-tastypie
1,570
11139621
from django.contrib.auth.models import User from tastypie import fields from tastypie.resources import ModelResource from tastypie.authorization import Authorization from basic.models import Note class UserResource(ModelResource): class Meta: resource_name = 'users' queryset = User.objects.all() ...
libs/core/loss.py
zj1008/GALD-DGCNet
127
11139634
# CE-loss import torch.nn as nn import torch import torch.nn.functional as F class OhemCrossEntropy2dTensor(nn.Module): def __init__(self, ignore_label, reduction='elementwise_mean', thresh=0.6, min_kept=256, down_ratio=1, use_weight=False): super(OhemCrossEntropy2dTensor, self).__init__(...
tests/package/test_meta.py
franzbischoff/platformio-core
4,744
11139637
<filename>tests/package/test_meta.py # Copyright (c) 2014-present PlatformIO <<EMAIL>> # # 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...
venv/Lib/site-packages/statsmodels/tsa/statespace/cfa_simulation_smoother.py
EkremBayar/bayar
6,931
11139672
""" "Cholesky Factor Algorithm" (CFA) simulation smoothing for state space models Author: <NAME> License: BSD-3 """ import numpy as np from . import tools class CFASimulationSmoother(object): r""" "Cholesky Factor Algorithm" (CFA) simulation smoother Parameters ---------- model : Representatio...
social/tests/backends/test_evernote.py
raccoongang/python-social-auth
1,987
11139675
<gh_stars>1000+ from requests import HTTPError from social.p3 import urlencode from social.exceptions import AuthCanceled from social.tests.backends.oauth import OAuth1Test class EvernoteOAuth1Test(OAuth1Test): backend_path = 'social.backends.evernote.EvernoteOAuth' expected_username = '101010' access_t...
addons/box/views.py
gaybro8777/osf.io
628
11139702
<reponame>gaybro8777/osf.io """Views for the node settings page.""" # -*- coding: utf-8 -*- from flask import request from addons.base import generic_views from addons.box.serializer import BoxSerializer from website.project.decorators import must_have_addon, must_be_addon_authorizer SHORT_NAME = 'box' FULL_NAME = 'B...
tensorflow_federated/python/learning/metrics/finalizer.py
tensorflow/federated
1,918
11139711
<filename>tensorflow_federated/python/learning/metrics/finalizer.py # Copyright 2021, The TensorFlow Federated 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.apa...
thanks/thanks.py
phildini/thanks
168
11139749
<filename>thanks/thanks.py # -*- coding: utf-8 -*- from __future__ import print_function from collections import namedtuple from humanfriendly.tables import format_pretty_table import json import logging import os import requirements import requests import termcolor import toml from termcolor import colored from . im...
tests/dynamic_analysis/test_run_analysis_arm.py
jrespeto/LiSa
244
11139777
""" Unit tests for full run_analysis with QEMU emulation. """ import os import pytest from lisa.analysis.dynamic_analysis import DynamicAnalyzer from lisa.core.base import AnalyzedFile location = os.path.dirname(__file__) @pytest.fixture(scope='module') def analysis(): return {'output': None} def test_ru...