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
python/ts/flint/utils.py
mattomatic/flint
972
38501
<filename>python/ts/flint/utils.py # # Copyright 2017 TWO SIGMA OPEN SOURCE, 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 # # Unl...
sympy/diffgeom/tests/test_class_structure.py
shilpiprd/sympy
8,323
38550
<reponame>shilpiprd/sympy from sympy.diffgeom import Manifold, Patch, CoordSystem, Point from sympy import symbols, Function from sympy.testing.pytest import warns_deprecated_sympy m = Manifold('m', 2) p = Patch('p', m) a, b = symbols('a b') cs = CoordSystem('cs', p, [a, b]) x, y = symbols('x y') f = Function('f') s1,...
datrie/run_test.py
nikicc/anaconda-recipes
130
38556
<reponame>nikicc/anaconda-recipes import string import datrie trie = datrie.Trie(string.ascii_lowercase) trie[u'foo'] = 5 assert u'foo' in trie
tests/vision/metrics/vqa_test.py
shunk031/allennlp-models
402
38559
<reponame>shunk031/allennlp-models<filename>tests/vision/metrics/vqa_test.py from typing import Any, Dict, List, Tuple, Union import pytest import torch from allennlp.common.testing import ( AllenNlpTestCase, multi_device, global_distributed_metric, run_distributed_test, ) from allennlp_models.vision ...
tests/epyccel/test_epyccel_transpose.py
dina-fouad/pyccel
206
38562
<reponame>dina-fouad/pyccel<filename>tests/epyccel/test_epyccel_transpose.py # pylint: disable=missing-function-docstring, missing-module-docstring/ from numpy.random import randint from pyccel.epyccel import epyccel def test_transpose_shape(language): def f1(x : 'int[:,:]'): from numpy import transpose ...
examples/example.py
jakevdp/Mmani
303
38586
<gh_stars>100-1000 import sys import numpy as np import scipy as sp import scipy.sparse as sparse from megaman.geometry import Geometry from sklearn import datasets from megaman.embedding import (Isomap, LocallyLinearEmbedding, LTSA, SpectralEmbedding) # Generate an example data set N = ...
chrome/test/pyautolib/generate_docs.py
nagineni/chromium-crosswalk
231
38593
#!/usr/bin/env python # Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import optparse import os import pydoc import shutil import sys def main(): parser = optparse.OptionParser() parser.add_optio...
d2/detr/__init__.py
reubenwenisch/detr_custom
8,849
38617
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from .config import add_detr_config from .detr import Detr from .dataset_mapper import DetrDatasetMapper
code_legacy/PostfixLogSummary.py
rhymeswithmogul/starttls-everywhere
339
38650
<filename>code_legacy/PostfixLogSummary.py #!/usr/bin/env python import argparse import collections import os import re import sys import time import Config TIME_FORMAT = "%b %d %H:%M:%S" # TODO: There's more to be learned from postfix logs! Here's one sample # observed during failures from the sender vagrant vm: ...
experiments/plot.py
henrytseng/srcnn
125
38662
from pathlib import Path import matplotlib.pyplot as plt import pandas as pd results_dir = Path('results') results_dir.mkdir(exist_ok=True) # Performance plot for scale in [3, 4]: for test_set in ['Set5', 'Set14']: time = [] psnr = [] model = [] for save_dir in sorted(Path('.').g...
dni/mlp.py
DingKe/pytorch_workplace
184
38677
<gh_stars>100-1000 import torch import torch.nn as nn import torchvision.datasets as dsets import torchvision.transforms as transforms from torch.autograd import Variable # Hyper Parameters input_size = 784 hidden_size = 256 dni_size = 1024 num_classes = 10 num_epochs = 50 batch_size = 500 learning_rate = 1e-3 use_c...
train-xception.py
jGsch/kaggle-dfdc
124
38679
<filename>train-xception.py<gh_stars>100-1000 import os import csv import shutil import random from PIL import Image import numpy as np import torch from torch import nn, optim from torch.utils.data import Dataset, DataLoader import xception_conf as config from model_def import xception from augmentation...
corehq/apps/hqadmin/management/commands/static_analysis.py
andyasne/commcare-hq
471
38684
import os import re import subprocess from collections import Counter from django.conf import settings from django.core.management.base import BaseCommand import datadog from dimagi.ext.couchdbkit import Document from corehq.feature_previews import all_previews from corehq.toggles import all_toggles class Datadog...
scripts/artifacts/installedappsGass.py
Krypterry/ALEAPP
187
38720
import sqlite3 from scripts.artifact_report import ArtifactHtmlReport from scripts.ilapfuncs import logfunc, tsv, open_sqlite_db_readonly def get_installedappsGass(files_found, report_folder, seeker, wrap_text): for file_found in files_found: file_found = str(file_found) if file_found.endswith('.d...
RecoVertex/BeamSpotProducer/scripts/copyFromCastor.py
ckamtsikis/cmssw
852
38797
#!/usr/bin/env python import sys,os,commands from CommonMethods import * def main(): if len(sys.argv) < 3: error = "Usage: cpFromCastor fromDir toDir (optional filter)" exit(error) user = os.getenv("USER") castorDir = "/castor/cern.ch/cms/store/caf/user/" + user + "/" + sys.argv[1] + "/" ...
mmfashion/apis/test_fashion_recommender.py
RyanJiang0416/mmfashion
952
38803
<reponame>RyanJiang0416/mmfashion<gh_stars>100-1000 from __future__ import division import torch from mmcv.parallel import MMDataParallel from ..datasets import build_dataloader from .env import get_root_logger def test_fashion_recommender(model, dataset, cf...
context_cache/context_cache.py
tervay/the-blue-alliance
266
38850
from google.appengine.ext import ndb CACHE_DATA = {} def get(cache_key): full_cache_key = '{}:{}'.format(cache_key, ndb.get_context().__hash__()) return CACHE_DATA.get(full_cache_key, None) def set(cache_key, value): full_cache_key = '{}:{}'.format(cache_key, ndb.get_context().__hash__()) CACHE_DA...
src/beanmachine/applications/hme/interface.py
horizon-blue/beanmachine-1
177
38854
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Tuple import pandas as pd from .configs import InferConfig, ModelConfig from .null_mixture_model import NullMixtureMixe...
tests/utils/test_string_utils.py
PeterSulcs/mlflow
10,351
38858
<filename>tests/utils/test_string_utils.py import pytest from mlflow.utils.string_utils import strip_prefix, strip_suffix, is_string_type @pytest.mark.parametrize( "original,prefix,expected", [("smoketest", "smoke", "test"), ("", "test", ""), ("", "", ""), ("test", "", "test")], ) def test_strip_prefix(origi...
tests/data/samplecfg.py
glebshevchukk/gradslam
1,048
38867
import os import sys from gradslam.config import CfgNode as CN cfg = CN() cfg.TRAIN = CN() cfg.TRAIN.HYPERPARAM_1 = 0.9
tests/chainer_tests/functions_tests/math_tests/test_linear_interpolate.py
zaltoprofen/chainer
3,705
38902
<reponame>zaltoprofen/chainer import numpy from chainer import functions from chainer import testing from chainer import utils @testing.parameterize(*testing.product({ 'shape': [(3, 4), ()], 'dtype': [numpy.float16, numpy.float32, numpy.float64], })) @testing.fix_random() @testing.inject_backend_tests( N...
regtests/list/slice.py
ahakingdom/Rusthon
622
38934
<reponame>ahakingdom/Rusthon from runtime import * """list slice""" class XXX: def __init__(self): self.v = range(10) def method(self, a): return a def main(): a = range(10)[:-5] assert( len(a)==5 ) assert( a[4]==4 ) print '--------' b = range(10)[::2] print b assert( len(b)==5 ) assert( b[0]==0 ) ass...
selenium/load-html-from-string-instead-of-url/main.py
whitmans-max/python-examples
140
38948
#!/usr/bin/env python3 # date: 2019.11.24 import selenium.webdriver driver = selenium.webdriver.Firefox() html_content = """ <div class=div1> <ul> <li> <a href='path/to/div1stuff/1'>Generic string 1</a> <a href='path/to/div1stuff/2'>Generic string 2</a> ...
gluoncv/data/video_custom/__init__.py
Kh4L/gluon-cv
5,447
38951
# pylint: disable=wildcard-import """ Customized data loader for video classification related tasks. """ from __future__ import absolute_import from .classification import *
src/cowrie/output/csirtg.py
uwacyber/cowrie
2,316
38997
from __future__ import annotations import os from datetime import datetime from twisted.python import log import cowrie.core.output from cowrie.core.config import CowrieConfig token = CowrieConfig.get("output_csirtg", "token", fallback="<PASSWORD>") if token == "<PASSWORD>": log.msg("output_csirtg: token not fou...
main/api/fields.py
lipis/gae-init-magic
465
39012
<gh_stars>100-1000 # coding: utf-8 import urllib from flask_restful import fields from flask_restful.fields import * class BlobKey(fields.Raw): def format(self, value): return urllib.quote(str(value)) class Blob(fields.Raw): def format(self, value): return repr(value) class DateTime(fields.DateTime)...
xero/filesmanager.py
Ian2020/pyxero
246
39015
<filename>xero/filesmanager.py from __future__ import unicode_literals import os import requests from six.moves.urllib.parse import parse_qs from .constants import XERO_FILES_URL from .exceptions import ( XeroBadRequest, XeroExceptionUnknown, XeroForbidden, XeroInternalError, XeroNotAvailable, ...
hermione/module_templates/__IMPLEMENTED_BASE__/src/ml/preprocessing/preprocessing.py
RodrigoATorres/hermione
183
39030
<filename>hermione/module_templates/__IMPLEMENTED_BASE__/src/ml/preprocessing/preprocessing.py import pandas as pd from ml.preprocessing.normalization import Normalizer from category_encoders import * import logging logging.getLogger().setLevel(logging.INFO) class Preprocessing: """ Class to perform data pre...
DevTools/lineCount.py
spiiin/CadEditor
164
39032
#!/usr/bin/env python2 #Script for calculate LoC of all source files of project import os,string import sys extension_list = ['h','hpp','cpp','c','pas','dpr','asm','py','q3asm','def','sh','bat','cs','java','cl','lisp','ui',"nut"] comment_sims = {'asm' : ';', 'py' : '#', 'cl':';','lisp':';'} source_files = { } ...
doc2json/jats2json/pmc_utils/back_tag_utils.py
josephcc/s2orc-doc2json
132
39081
<reponame>josephcc/s2orc-doc2json from typing import Dict, List def _wrap_text(tag): return tag.text if tag else '' def parse_authors(authors_tag) -> List: """The PMC XML has a slightly different format than authors listed in front tag.""" if not authors_tag: return [] authors =...
matrixprofile/io/protobuf/protobuf_utils.py
MORE-EU/matrixprofile
262
39103
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals range = getattr(__builtins__, 'xrange', range) # end of py2 compatability boilerplate import numpy as np from matrixprofile import core from ma...
moe/optimal_learning/python/interfaces/domain_interface.py
misokg/Cornell-MOE
218
39133
# -*- coding: utf-8 -*- """Interface for a domain: in/out test, random point generation, and update limiting (for constrained optimization).""" from builtins import object from abc import ABCMeta, abstractmethod, abstractproperty from future.utils import with_metaclass class DomainInterface(with_metaclass(ABCMeta, ob...
RecoPPS/Local/python/ctppsDiamondLocalReconstruction_cff.py
ckamtsikis/cmssw
852
39143
<gh_stars>100-1000 import FWCore.ParameterSet.Config as cms # reco hit production from RecoPPS.Local.ctppsDiamondRecHits_cfi import ctppsDiamondRecHits # local track fitting from RecoPPS.Local.ctppsDiamondLocalTracks_cfi import ctppsDiamondLocalTracks ctppsDiamondLocalReconstructionTask = cms.Task( ctppsDiamondR...
text/opencv_dnn_detect.py
kingemma/invoice
1,017
39174
<filename>text/opencv_dnn_detect.py from config import yoloCfg,yoloWeights,opencvFlag from config import AngleModelPb,AngleModelPbtxt from config import IMGSIZE from PIL import Image import numpy as np import cv2 if opencvFlag=='keras': ##转换为tf模型,以便GPU调用 import tensorflow as tf from tensorflow.python.platf...
016 3Sum Closest.py
ChiFire/legend_LeetCode
872
39211
<filename>016 3Sum Closest.py<gh_stars>100-1000 """ Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. For example, given array S = {-1 2 1 -4}, an...
tests/spec/cms/blogs/test_blogs.py
fakepop/hubspot-api-python
117
39227
<reponame>fakepop/hubspot-api-python from hubspot import HubSpot from hubspot.discovery.cms.blogs.discovery import Discovery def test_is_discoverable(): apis = HubSpot().cms assert isinstance(apis.blogs, Discovery)
notebooks/pixel_cnn/pixelcnn_helpers.py
bjlkeng/sandbox
158
39256
<gh_stars>100-1000 import math import numpy as np from keras import backend as K from keras.layers import Conv2D, Concatenate, Activation, Add from keras.engine import InputSpec def logsoftmax(x): ''' Numerically stable log(softmax(x)) ''' m = K.max(x, axis=-1, keepdims=True) return x - m - K.log(K.sum(...
terrascript/data/logicmonitor.py
hugovk/python-terrascript
507
39260
# terrascript/data/logicmonitor.py import terrascript class logicmonitor_collectors(terrascript.Data): pass class logicmonitor_dashboard(terrascript.Data): pass class logicmonitor_dashboard_group(terrascript.Data): pass class logicmonitor_device_group(terrascript.Data): pass __all__ = [ "l...
api/v2/serializers/fields/identity.py
simpsonw/atmosphere
197
39292
<reponame>simpsonw/atmosphere from rest_framework import exceptions, serializers from api.v2.serializers.summaries import IdentitySummarySerializer from core.models import Identity class IdentityRelatedField(serializers.RelatedField): def get_queryset(self): return Identity.objects.all() def to_repre...
opps/core/tags/views.py
jeanmask/opps
159
39311
<reponame>jeanmask/opps # -*- encoding: utf-8 -*- from django.utils import timezone from django.contrib.sites.models import get_current_site from django.conf import settings from haystack.query import SearchQuerySet from opps.views.generic.list import ListView from opps.containers.models import Container from opps.c...
aiida/cmdline/groups/__init__.py
aiidateam/aiida_core
153
39332
<filename>aiida/cmdline/groups/__init__.py # -*- coding: utf-8 -*- """Module with custom implementations of :class:`click.Group`.""" # AUTO-GENERATED # yapf: disable # pylint: disable=wildcard-import from .dynamic import * from .verdi import * __all__ = ( 'DynamicEntryPointCommandGroup', 'VerdiCommandGroup'...
src/storage-preview/azext_storage_preview/tests/latest/test_storage_file_scenarios.py
haroonf/azure-cli-extensions
207
39336
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
plugins/lucid/ui/explorer.py
gaasedelen/lucid
342
39359
import ctypes import ida_ida import ida_funcs import ida_graph import ida_idaapi import ida_kernwin import ida_hexrays from PyQt5 import QtWidgets, QtGui, QtCore, sip from lucid.ui.sync import MicroCursorHighlight from lucid.ui.subtree import MicroSubtreeView from lucid.util.python import register_callback, notify_c...
third_party/libtcod/.ci/conan_build.py
csb6/libtcod-ada
686
39363
<reponame>csb6/libtcod-ada<filename>third_party/libtcod/.ci/conan_build.py<gh_stars>100-1000 #!/usr/bin/env python3 """Build script for conan-package-tools: https://github.com/conan-io/conan-package-tools """ import os import subprocess from cpt.packager import ConanMultiPackager try: version = subprocess.check_...
scripts/mnpr_system.py
semontesdeoca/MNPR
218
39390
""" @license: MIT @repository: https://github.com/semontesdeoca/MNPR _ _ __ ___ _ __ _ __ _ __ ___ _ _ ___| |_ ___ _ __ ___ | '_ ` _ \| '_ \| '_ \| '__| / __| | | / __| __/ _ \ '_ ` _ \ | | | | | | | | | |_) | | \__ \ |_| \__ \ || __/ | | | | ...
python/dgl/contrib/data/__init__.py
ketyi/dgl
9,516
39392
<filename>python/dgl/contrib/data/__init__.py from __future__ import absolute_import from . import knowledge_graph as knwlgrh def load_data(dataset, bfs_level=3, relabel=False): if dataset in ['aifb', 'mutag', 'bgs', 'am']: return knwlgrh.load_entity(dataset, bfs_level, relabel) elif dataset in ['FB15k...
tests/chem/test_mol.py
ShantamShorewala/aizynthfinder
219
39400
import pytest from rdkit import Chem from aizynthfinder.chem import MoleculeException, Molecule def test_no_input(): with pytest.raises(MoleculeException): Molecule() def test_create_with_mol(): rd_mol = Chem.MolFromSmiles("O") mol = Molecule(rd_mol=rd_mol) assert mol.smiles == "O" def ...
tests/test_tree.py
tgragnato/geneva
1,182
39444
import logging import os from scapy.all import IP, TCP import actions.tree import actions.drop import actions.tamper import actions.duplicate import actions.utils import layers.packet def test_init(): """ Tests initialization """ print(actions.action.Action.get_actions("out")) def test_count_leaves...
ide/tests/test_import_archive.py
Ramonrlb/cloudpebble
147
39474
""" These tests check basic operation of ide.tasks.archive.do_import_archive """ import mock from django.core.exceptions import ValidationError from ide.tasks.archive import do_import_archive, InvalidProjectArchiveException from ide.utils.cloudpebble_test import CloudpebbleTestCase, make_package, make_appinfo, build_...
fairlearn/metrics/__init__.py
alliesaizan/fairlearn
1,142
39491
<filename>fairlearn/metrics/__init__.py # Copyright (c) Microsoft Corporation and Fairlearn contributors. # Licensed under the MIT License. """Functionality for computing metrics, with a particular focus on disaggregated metrics. For our purpose, a metric is a function with signature ``f(y_true, y_pred, ....)`` where...
Projects/Healthcare/breast-cancer/src/data_loading/augmentations.py
DanielMabadeje/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
3,266
39506
# Copyright (C) 2019 <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, # <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, # <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, # <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, # <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, # <NAME>, <NAME> # # This file is pa...
data_pipeline/_kafka_producer.py
poros/data_pipeline
110
39512
# -*- coding: utf-8 -*- # Copyright 2016 Yelp 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 ag...
stackimpact/utils.py
timgates42/stackimpact-python
742
39544
import time import uuid import base64 import hashlib def millis(): return int(round(time.time() * 1000)) def timestamp(): return int(time.time()) def base64_encode(s): return base64.b64encode(s.encode('utf-8')).decode('utf-8') def base64_decode(b): return base64.b64decode(b).decode('utf-8') ...
example/app/views.py
aolkin/django-bootstrap-form
324
39545
<gh_stars>100-1000 from django.shortcuts import render from app.forms import ExampleForm def index(request): form = ExampleForm() return render(request, 'index.html', {'form': form})
myia/operations/op_array_getitem_wrap.py
strint/myia
222
39617
"""Implementation of the 'array_getitem_wrap' operation.""" from ..lib import Slice, core, myia_static from ..operations import array_getitem, reshape def _dim_explicit(dim, dim_size): if dim < 0: dim = dim_size + dim assert dim >= 0 return dim @myia_static def _build_slices(a_shp, item): b...
django_tutorial/views/error_views.py
twtrubiks/django-tutorial
431
39628
<reponame>twtrubiks/django-tutorial from django.shortcuts import render def view_404(request): return render(request, 'django_tutorial/error_pages/page_404.html', status=404) def view_500(request): return render(request, 'django_tutorial/error_pages/page_500.html', status=500)
examples/anagrams_demo.py
aathi2002/open-tamil
218
39641
import codecs from solthiruthi.dictionary import * from tamil import wordutils TVU, TVU_size = DictionaryBuilder.create(TamilVU) ag, ag2 = wordutils.anagrams_in_dictionary(TVU) with codecs.open("demo.txt", "w", "utf-8") as fp: itr = 1 for k, c in ag: v = ag2[k] fp.write("%03d) %s\n" % (itr, " ...
data/kitti_raw_loader.py
infinityofspace/SfmLearner-Pytorch
908
39647
from __future__ import division import numpy as np from path import Path from imageio import imread from skimage.transform import resize as imresize from kitti_util import pose_from_oxts_packet, generate_depth_map, read_calib_file, transform_from_rot_trans from datetime import datetime class KittiRawLoader(object): ...
cloudtunes-server/cloudtunes/async.py
skymemoryGit/cloudtunes
529
39676
"""Asynchronous MongoDB and Redis connections.""" from functools import partial import motor import tornadoredis from cloudtunes import settings RedisClient = partial(tornadoredis.Client, **settings.REDIS) mongo = motor.MotorClient(**settings.MONGODB).cloudtunes redis = RedisClient()
code/applications/qs_predict_probablistic.py
ninamiolane/quicksilver
126
39682
# add LDDMM shooting code into path import sys sys.path.append('../vectormomentum/Code/Python'); sys.path.append('../library') from subprocess import call import argparse import os.path #Add deep learning related libraries from collections import Counter import torch import prediction_network import util import numpy...
tods/sk_interface/detection_algorithm/SOD_skinterface.py
ZhuangweiKang/tods
544
39739
import numpy as np from ..base import BaseSKI from tods.detection_algorithm.PyodSOD import SODPrimitive class SODSKI(BaseSKI): def __init__(self, **hyperparams): super().__init__(primitive=SODPrimitive, **hyperparams) self.fit_available = True self.predict_available = True self.produce_available = False
munjong/remove_sejong_period_error.py
cjdans5545/khaiii
1,235
39758
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ remove wrong sentence breaking marks after period error eojeol __author__ = 'Jamie (<EMAIL>)' __copyright__ = 'Copyright (C) 2017-, Kakao Corp. All rights reserved.' """ ########### # imports # ########### from argparse import ArgumentParser import logging import o...
src/pretalx/event/migrations/0023_update_featured_visibility.py
lili668668/pretalx
418
39779
<filename>src/pretalx/event/migrations/0023_update_featured_visibility.py # Generated by Django 3.0.5 on 2020-07-26 15:45 from django.db import migrations def update_show_featured(apps, schema_editor): Event = apps.get_model("event", "Event") EventSettings = apps.get_model("event", "Event_SettingsStore") ...
dash_docs/chapters/dash_bio/examples/ideogram.py
joelostblom/dash-docs
379
39829
import dash import dash_bio as dashbio import dash_html_components as html import dash_core_components as dcc external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) app.layout = html.Div([ 'Select which chromosomes to display on ...
objectModel/Python/tests/storage/test_github.py
rt112000/CDM
884
39869
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. import json import unittest import unittest.mock as mock import random from tests.common import async_test from cdm.storage.github import GithubAdapter class Gi...
speedTester/logs/average.py
saurabhcommand/Hello-world
1,428
39870
<reponame>saurabhcommand/Hello-world file1 = open("./logs/pythonlog.txt", 'r+') avg1 = 0.0 lines1 = 0.0 for line in file1: lines1 = lines1 + 1.0 avg1 = (avg1 + float(line)) avg1 = avg1/lines1 print(avg1, "for Python with", lines1, "lines") file2 = open("./logs/clog.txt", 'r+') avg2 = 0.0 lines2 = 0.0 for line...
tensorflow_ranking/python/keras/estimator_test.py
renyi533/ranking
2,482
39878
<filename>tensorflow_ranking/python/keras/estimator_test.py # Copyright 2021 The TensorFlow Ranking 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/lice...
tools/Polygraphy/tests/backend/trt/test_profile.py
KaliberAI/TensorRT
5,249
39915
<filename>tools/Polygraphy/tests/backend/trt/test_profile.py # # Copyright (c) 2021, NVIDIA CORPORATION. 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://ww...
tests/attention/test_attention_layer.py
SamuelCahyawijaya/fast-transformers
1,171
39922
# # Copyright (c) 2020 Idiap Research Institute, http://www.idiap.ch/ # Written by <NAME> <<EMAIL>>, # <NAME> <<EMAIL>> # import unittest import torch from fast_transformers.attention.attention_layer import AttentionLayer class TestAttentionLayer(unittest.TestCase): def _assert_sizes_attention(self, qshape, k...
pulsar/async/_subprocess.py
PyCN/pulsar
1,410
39940
if __name__ == '__main__': import sys import pickle from multiprocessing import current_process from multiprocessing.spawn import import_main_path data = pickle.load(sys.stdin.buffer) current_process().authkey = data['authkey'] sys.path = data['path'] import_main_path(data['main']) ...
django_slack/templatetags/django_slack.py
lociii/django-slack
237
39961
<gh_stars>100-1000 from django import template from django.utils.encoding import force_str from django.utils.functional import keep_lazy from django.utils.safestring import SafeText, mark_safe from django.template.defaultfilters import stringfilter register = template.Library() _slack_escapes = { ord('&'): u'&amp...
python/tests/utils/test_environment_decorator_test.py
xuyanbo03/lab
7,407
39991
<reponame>xuyanbo03/lab # Copyright 2018 Google Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program ...
roles/openshift_openstack/library/os_service_catalog.py
Roscoe198/Ansible-Openshift
164
40022
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2018 Red Hat, Inc. and/or its affiliates # and other contributors as indicated by the @author tags. # # 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...
trainModel.py
NYUMedML/DeepEHR
242
40023
<reponame>NYUMedML/DeepEHR<filename>trainModel.py import torch # import torch.nn as nn # import torch.nn.functional as F import numpy as np from torch.autograd import Variable # import torchwordemb import torch.optim as optim import sys import time import gc import pickle import os import models2 as m import enc_mode...
packages/dcos-integration-test/extra/test_applications.py
timgates42/dcos
2,577
40040
import logging import uuid from typing import Any import pytest import requests import test_helpers from dcos_test_utils import marathon from dcos_test_utils.dcos_api import DcosApiSession __maintainer__ = 'kensipe' __contact__ = '<EMAIL>' log = logging.getLogger(__name__) def deploy_test_app_and_check(dcos_api_...
dataloader/stereo_kittilist15.py
ne3x7/VCN
148
40068
<reponame>ne3x7/VCN import torch.utils.data as data import pdb from PIL import Image import os import os.path import numpy as np IMG_EXTENSIONS = [ '.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP', ] def is_image_file(filename): return any(filename.endswith(extension) for...
src/textacy/extract/keyterms/__init__.py
austinjp/textacy
1,929
40086
""" Keyterms -------- :mod:`textacy.extract.keyterms`: Extract keyterms from documents using a variety of rule-based algorithms. """ from .scake import scake from .sgrank import sgrank from .textrank import textrank from .yake import yake
tests/settings/imagemagick.py
apahomov/sorl-thumbnail
630
40095
<filename>tests/settings/imagemagick.py from .default import * THUMBNAIL_ENGINE = 'sorl.thumbnail.engines.convert_engine.Engine' THUMBNAIL_CONVERT = 'convert'
app/oauth_office365/tests.py
ricardojba/PwnAuth
304
40110
<filename>app/oauth_office365/tests.py<gh_stars>100-1000 from django.test import TestCase # Create your tests here. # TODO add test to validate application scopes are enforced when creating # TODO add test to validate that application redirect and refresh URL match the site's base url # TODO add unicode handling test...
kolibri/core/content/zip_wsgi.py
MBKayro/kolibri
545
40151
<filename>kolibri/core/content/zip_wsgi.py from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import logging import mimetypes import os import re import time import zipfile import html5lib from cheroot import wsgi from django.core.cache import cache fr...
mamonsu/tools/report/format.py
sgrinko/mamonsu
188
40176
<filename>mamonsu/tools/report/format.py # -*- coding: utf-8 -*- import re import sys import mamonsu.lib.platform as platform class color(object): mapping = { 'BOLD': '\033[0;0m\033[1;1m', 'RED': '\033[1;31m', 'GRAY': '\033[1;30m', 'PURPLE': '\033[1;35m', 'BLUE': '\033[1;...
contrib/report_builders/__init__.py
berndonline/flan
3,711
40182
<gh_stars>1000+ from .report_builder import ReportBuilder from .latex_report_builder import LatexReportBuilder from .markdown_report_builder import MarkdownReportBuilder from .json_report_builder import JsonReportBuilder from .html_report_builder import JinjaHtmlReportBuilder
hnn/src/apps/training_utils.py
anlewy/mt-dnn
2,075
40267
# # Author: <EMAIL> # Date: 01/25/2019 # """ Utils for training and optimization """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import utils logger=utils.get_logger() import numpy as np import torch from bert.optimization import BertAdam def zero_grad...
src/hobbits-plugins/analyzers/KaitaiStruct/ksy_py/hardware/mifare/mifare_classic.py
SabheeR/hobbits
304
40282
<gh_stars>100-1000 # This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild from pkg_resources import parse_version import kaitaistruct from kaitaistruct import KaitaiStruct, KaitaiStream, BytesIO import collections if parse_version(kaitaistruct.__version__) < parse_version(...
leetcode/coding/editor.py
chishui/terminal-leetcode
254
40389
import os import subprocess from pathlib import Path from ..views.viewhelper import delay_refresh_detail from ..helper.config import config def edit(filepath: Path, loop): if isinstance(filepath, str): filepath = Path(filepath) editor = os.environ.get('EDITOR', 'vi').lower() # vim if editor ==...
setup.py
nad2000/swagger_to_uml
190
40393
<gh_stars>100-1000 from setuptools import setup, find_packages requires = [ 'PyYAML==5.1' ] setup( name='swagger_to_uml', version='0.1', description='swagger_to_uml', classifiers=[ "Programming Language :: Python" ], author='<NAME>', author_email='<EMAIL>', license='MIT', ...
multimedia/gui/lvgl/lvgl_multiple_screens.py
708yamaguchi/MaixPy_scripts
485
40402
<reponame>708yamaguchi/MaixPy_scripts<filename>multimedia/gui/lvgl/lvgl_multiple_screens.py #this demo shows how to create multiple screens, load and unload them properly without causing memory leak import lvgl as lv import lvgl_helper as lv_h import lcd import time from machine import Timer from machine import I2C fr...
quantecon/markov/utilities.py
Smit-create/QuantEcon.py
1,462
40415
<reponame>Smit-create/QuantEcon.py<gh_stars>1000+ """ Utility routines for the markov submodule """ import numpy as np from numba import jit @jit(nopython=True, cache=True) def sa_indices(num_states, num_actions): """ Generate `s_indices` and `a_indices` for `DiscreteDP`, for the case where all the actio...
examples/run_bidaf/cmrc_bidaf.py
ishine/SMRCToolkit
1,238
40437
<reponame>ishine/SMRCToolkit<gh_stars>1000+ # coding: utf-8 from sogou_mrc.data.vocabulary import Vocabulary from sogou_mrc.dataset.squad import SquadReader, SquadEvaluator from sogou_mrc.dataset.cmrc import CMRCReader,CMRCEvaluator from sogou_mrc.model.bidaf import BiDAF import tensorflow as tf import logging from sog...
pynes/examples/mario.py
timgates42/pyNES
1,046
40438
<filename>pynes/examples/mario.py import pynes from pynes.bitbag import * if __name__ == "__main__": pynes.press_start() exit() palette = [ 0x22,0x29, 0x1A,0x0F, 0x22,0x36,0x17,0x0F, 0x22,0x30,0x21,0x0F, 0x22,0x27,0x17,0x0F, 0x22,0x16,0x27,0x18, 0x22,0x1A,0x30,0x27, 0x22,0x16,0x30,0x27, 0x22,...
tests/__init__.py
Kua-Fu/rally
1,577
40461
<filename>tests/__init__.py # Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you under # the Apache License, Version 2.0 (the "License...
alipay/aop/api/domain/ItapDeviceInfo.py
antopen/alipay-sdk-python-all
213
40463
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class ItapDeviceInfo(object): def __init__(self): self._fw_version = None self._hw_version = None self._manufacturer = None self._model = None self._product_name...
synapse/servers/aha.py
ackroute/synapse
216
40464
<gh_stars>100-1000 # pragma: no cover import sys import asyncio import synapse.lib.aha as s_aha if __name__ == '__main__': # pragma: no cover asyncio.run(s_aha.AhaCell.execmain(sys.argv[1:]))
tests/python/contrib/test_ethosu/cascader/test_integration.py
shengxinhu/tvm
4,640
40466
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
pymterm/term_pylibui/key_translate.py
stonewell/pymterm
102
40467
<gh_stars>100-1000 __key_mapping = { 'return' : 'enter', 'up_arrow' : 'up', 'down_arrow' : 'down', 'left_arrow' : 'left', 'right_arrow' : 'right', 'page_up' : 'pageup', 'page_down' : 'pagedown', } def translate_key(e): if len(e.key) > 0: return __key_mapping[e.key] if e.key...
tests/test_core.py
srdjanrosic/supervisor
597
40475
"""Testing handling with CoreState.""" from supervisor.const import CoreState from supervisor.coresys import CoreSys def test_write_state(run_dir, coresys: CoreSys): """Test write corestate to /run/supervisor.""" coresys.core.state = CoreState.RUNNING assert run_dir.read_text() == CoreState.RUNNING.val...
faceQuality/get_quality.py
awesome-archive/MaskInsightface
269
40490
# -*- coding: utf-8 -*- from keras.models import load_model import numpy as np import os import cv2 from FaceQNet import load_Qnet_model, face_quality # Loading the pretrained model model = load_Qnet_model() IMG_PATH = '/home/sai/YANG/image/video/nanning/haha' dir = os.listdir(IMG_PATH) count = len(dir) print('count:...
imagetagger/imagetagger/administration/forms.py
jbargu/imagetagger
212
40500
<reponame>jbargu/imagetagger from django import forms from imagetagger.annotations.models import AnnotationType class AnnotationTypeCreationForm(forms.ModelForm): class Meta: model = AnnotationType fields = [ 'name', 'active', 'node_count', 'vector_...
tenkit/lib/python/striped_smith_waterman/pyssw.py
qiangli/cellranger
239
40523
<gh_stars>100-1000 #!/usr/bin/env python # -*- coding: utf-8 -*- """ @package pyssw @brief Python standalone program for ssw alignment using the C library Complete-Striped-Smith-Waterman-Library Biopython module is require for fastq/fastq parsing @copyright [The MIT licence](http://opensource.org/licenses/MIT) @autho...
pyclustering/cluster/tests/rock_templates.py
JosephChataignon/pyclustering
1,013
40547
"""! @brief Test templates for ROCK clustering module. @authors <NAME> (<EMAIL>) @date 2014-2020 @copyright BSD-3-Clause """ from pyclustering.cluster.rock import rock; from pyclustering.utils import read_sample; from random import random; class RockTestTemplates: @staticmethod def ...