max_stars_repo_path
stringlengths
3
269
max_stars_repo_name
stringlengths
4
119
max_stars_count
int64
0
191k
id
stringlengths
1
7
content
stringlengths
6
1.05M
score
float64
0.23
5.13
int_score
int64
0
5
phi/math/backend/_backend.py
marc-gav/PhiFlow
0
4000
<filename>phi/math/backend/_backend.py from collections import namedtuple from contextlib import contextmanager from threading import Barrier from typing import List, Callable import numpy from ._dtype import DType, combine_types SolveResult = namedtuple('SolveResult', [ 'method', 'x', 'residual', 'iterations',...
2.859375
3
bpython/curtsiesfrontend/parse.py
dtrodrigues/bpython
2,168
4001
import re from curtsies.formatstring import fmtstr, FmtStr from curtsies.termformatconstants import ( FG_COLORS, BG_COLORS, colors as CURTSIES_COLORS, ) from functools import partial from ..lazyre import LazyReCompile COLORS = CURTSIES_COLORS + ("default",) CNAMES = dict(zip("krgybmcwd", COLORS)) # hack...
2.53125
3
sarpy/io/general/nitf_elements/tres/unclass/BANDSA.py
pressler-vsc/sarpy
1
4002
<reponame>pressler-vsc/sarpy # -*- coding: utf-8 -*- from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "<NAME>" class BAND(TREElement): def __init__(self, value): super(BAND, self).__init__() self.add_field('BANDPEAK', 's', 5, value) sel...
2.03125
2
ktrain/graph/learner.py
husmen/ktrain
1,013
4003
from ..imports import * from .. import utils as U from ..core import GenLearner class NodeClassLearner(GenLearner): """ ``` Main class used to tune and train Keras models for node classification Main parameters are: model (Model): A compiled instance of keras.engine.training.Model train_dat...
2.890625
3
VegaZero2VegaLite.py
Thanksyy/Vega-Zero
5
4004
__author__ = "<NAME>" import json import pandas class VegaZero2VegaLite(object): def __init__(self): pass def parse_vegaZero(self, vega_zero): self.parsed_vegaZero = { 'mark': '', 'data': '', 'encoding': { 'x': '', 'y': { ...
2.984375
3
utils/dancer.py
kmzbrnoI/ac-python
0
4005
"""Library for executing user-defined dance.""" import logging from typing import Any, Dict, Optional, Callable import datetime import ac import ac.blocks from ac import ACs, AC JC = Dict[str, Any] class DanceStartException(Exception): pass class Step: """Base class for all specific dance steps.""" ...
2.640625
3
praw/models/reddit/mixins/reportable.py
zachwylde00/praw
38
4006
<gh_stars>10-100 """Provide the ReportableMixin class.""" from ....const import API_PATH class ReportableMixin: """Interface for RedditBase classes that can be reported.""" def report(self, reason): """Report this object to the moderators of its subreddit. :param reason: The reason for repor...
2.8125
3
defense/jpeg_compress.py
TrustworthyDL/LeBA
19
4007
def _jpeg_compression(im): assert torch.is_tensor(im) im = ToPILImage()(im) savepath = BytesIO() im.save(savepath, 'JPEG', quality=75) im = Image.open(savepath) im = ToTensor()(im) return im
2.53125
3
mellon/factories/filesystem/file.py
LaudateCorpus1/mellon
5
4008
<reponame>LaudateCorpus1/mellon import collections import os.path from zope import component from zope import interface from zope.component.factory import Factory from sparc.configuration import container import mellon @interface.implementer(mellon.IByteMellonFile) class MellonByteFileFromFilePathAndConfig(object): ...
2.09375
2
dltb/thirdparty/datasource/__init__.py
CogSciUOS/DeepLearningToolbox
2
4009
<gh_stars>1-10 """Predefined Datasources. """ # toolbox imports from ...datasource import Datasource Datasource.register_instance('imagenet-val', __name__ + '.imagenet', 'ImageNet', section='val') # section='train' Datasource.register_instance('dogsandcats', __name__ + '.dogsandcats', ...
1.601563
2
tests/test_results.py
babinyurii/RECAN
7
4010
<reponame>babinyurii/RECAN # -*- coding: utf-8 -*- """ Created on Tue Oct 22 15:58:44 2019 @author: babin """ posits_def = [251, 501, 751, 1001, 1251, 1501, 1751, 2001, 2251, 2501, 2751, 3001, 3215] dist_whole_align_ref = {'AB048704.1_genotype_C_': [0.88, 0.938, 0.914, 0.886, 0.89, 0.908, 0.938, 0.9...
1.328125
1
lxmls/readers/simple_data_set.py
SimonSuster/lxmls-toolkit
1
4011
import numpy as np # This class generates a 2D dataset with two classes, "positive" and "negative". # Each class follows a Gaussian distribution. class SimpleDataSet(): ''' A simple two dimentional dataset for visualization purposes. The date set contains points from two gaussians with mean u_i and std_i''' d...
3.40625
3
set1/c06_attack_repeating_key_xor.py
kangtastic/cryptopals
1
4012
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Break repeating-key XOR # # It is officially on, now. # # This challenge isn't conceptually hard, but it involves actual # error-prone coding. The other challenges in this set are there to bring # you up to speed. This one is there to qualify you. If you can do t...
3.6875
4
c2nl/models/transformer.py
kopf-yhs/ncscos
22
4013
import torch import torch.nn as nn import torch.nn.functional as f from prettytable import PrettyTable from c2nl.modules.char_embedding import CharEmbedding from c2nl.modules.embeddings import Embeddings from c2nl.modules.highway import Highway from c2nl.encoders.transformer import TransformerEncoder from c2nl.decoder...
1.929688
2
cattle/plugins/docker/delegate.py
cjellick/python-agent
8
4014
import logging from cattle import Config from cattle.utils import reply, popen from .compute import DockerCompute from cattle.agent.handler import BaseHandler from cattle.progress import Progress from cattle.type_manager import get_type, MARSHALLER from . import docker_client import subprocess import os import time ...
1.90625
2
bitraider/strategy.py
ehickox2012/bitraider
2
4015
import sys import pytz #import xml.utils.iso8601 import time import numpy from datetime import date, datetime, timedelta from matplotlib import pyplot as plt from exchange import cb_exchange as cb_exchange from exchange import CoinbaseExchangeAuth from abc import ABCMeta, abstractmethod class strategy(object): """...
3.40625
3
neural-networks.py
PacktPublishing/Python-Deep-Learning-for-Beginners-
7
4016
<filename>neural-networks.py import numpy as np # Perceptron def predict_perceptron(inputs, weights): if np.dot(inputs, weights) > 0: return 1 else: return 0 def predict_perceptron_proper(inputs, weights): def step_function(input): return 1 if input > 0 else 0 def linear_mode...
3.59375
4
biggan_discovery/orojar_discover.py
andreasjansson/OroJaR
47
4017
""" Learns a matrix of Z-Space directions using a pre-trained BigGAN Generator. Modified from train.py in the PyTorch BigGAN repo. """ import os from tqdm import tqdm import torch import torch.nn as nn import torch.optim import utils import train_fns from sync_batchnorm import patch_replication_callback from torch.u...
2.359375
2
file_importer0.py
Alva789ro/Regional-Comprehensive-Economic-Partnership-RCEP-Economic-Default-Risk-Analysis
1
4018
import xlsxwriter import pandas as pd import numpy as np import mysql.connector australia=pd.read_excel(r'\Users\jesica\Desktop\RCEP_economic_analysis.xlsx', sheet_name='Australia') brunei=pd.read_excel(r'\Users\jesica\Desktop\RCEP_economic_analysis.xlsx', sheet_name='Brunei') cambodia=pd.read_excel(r'\Users\jesica\De...
2.25
2
packer/resources/bootstrap_node.py
VIOOH/nile
4
4019
#!/usr/bin/env python3 import os import re import glob import boto3 import requests import subprocess from time import sleep AWS_REGION = os.environ['AWS_REGION'] DEPLOY_UUID = os.environ['DEPLOY_UUID'] SERVICE_NAME = os.environ['SERVICE_NAME'] MOUNT_POINT = "/var/lib/" + SERVICE_NAME...
2.03125
2
parsers/srum_parser.py
otoriocyber/Chronos
12
4020
import csv import datetime import random import os from parsers.parser_base import ParserBase FILE_TIME_EPOCH = datetime.datetime(1601, 1, 1) FILE_TIME_MICROSECOND = 10 def filetime_to_epoch_datetime(file_time): if isinstance(file_time, int): microseconds_since_file_time_epoch = file_time / FILE_TIME_MIC...
2.34375
2
tests/csrf_tests/test_context_processor.py
Yoann-Vie/esgi-hearthstone
0
4021
from django.http import HttpRequest from django.middleware.csrf import _compare_salted_tokens as equivalent_tokens from django.template.context_processors import csrf from django.test import SimpleTestCase class TestContextProcessor(SimpleTestCase): def test_force_token_to_string(self): request ...
2.328125
2
python/das/types.py
marza-animation-planet/das
4
4022
<filename>python/das/types.py import sys import das import traceback class ReservedNameError(Exception): def __init__(self, name): super(ReservedNameError, self).__init__("'%s' is a reserved name" % name) class VersionError(Exception): def __init__(self, msg=None, current_version=None, required_version=...
2.40625
2
track.py
AliabbasMerchant/fileTrackAndBackup
6
4023
#! /usr/bin/python3 from help import * import time # short-forms are used, so as to reduce the .json file size # t : type - d or f # d : directory # f : file # ts : timestamp # dirs : The dictionary containing info about directory contents # time : edit time of the file/folder # s : size of the file/folder # p : full ...
2.703125
3
clang/tools/scan-build-py/libscanbuild/analyze.py
Kvarnefalk/llvm-project
1
4024
<filename>clang/tools/scan-build-py/libscanbuild/analyze.py<gh_stars>1-10 # -*- coding: utf-8 -*- # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception """ This module implemen...
1.992188
2
tableborder.py
PIRXrav/pyhack
0
4025
<gh_stars>0 #!/usr/bin/env python3 # pylint: disable=C0103 # pylint: disable=R0902 # pylint: disable=R0903 # pylint: disable=R0913 """ Définie la classe TableBorder """ class TableBorder: """ Facillite l'usage de l'UNICODE """ def __init__(self, top_left, top_split, top_right, ...
2.5
2
app/urls.py
tkf2019/Vue-Django-SAST-Search
0
4026
<gh_stars>0 from django.conf.urls import url from . import views urlpatterns = [ url(r'^register/', views.register), url(r'^login/', views.login), url(r'logout/', views.logout), url(r'search/', views.search) ]
1.554688
2
custom_components/hasl/sensor.py
Ziqqo/hasl-platform
0
4027
#!/usr/bin/python # -*- coding: utf-8 -*- """Simple service for SL (Storstockholms Lokaltrafik).""" import datetime import json import logging from datetime import timedelta import homeassistant.helpers.config_validation as cv import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from ho...
1.9375
2
simbad_tools.py
ishivvers/astro
1
4028
""" A quick library to deal with searching simbad for info about a SN and parsing the results. Author: <NAME>, <EMAIL>, 2014 example SIMBAD uri query: http://simbad.u-strasbg.fr/simbad/sim-id?output.format=ASCII&Ident=sn%201998S """ import re from urllib2 import urlopen def get_SN_info( name ): """ Querie...
3.15625
3
robots/environments.py
StanfordASL/soft-robot-control
5
4029
import os from math import cos from math import sin import Sofa.Core from splib.numerics import Quat, Vec3 from sofacontrol import measurement_models path = os.path.dirname(os.path.abspath(__file__)) class TemplateEnvironment: def __init__(self, name='Template', rayleighMass=0.1, rayleighStiffness=0.1, dt=0.01...
2.109375
2
default.py
SimonPreissner/get-shifty
0
4030
""" This file contains meta information and default configurations of the project """ RSC_YEARS = [1660, 1670, 1680, 1690, 1700, 1710, 1720, 1730, 1740, 1750, 1760, 1770, 1780, 1790, 1800, 1810, 1820, 1830, 1840, 1850, 1860, 1870, 1880, 1890, 1900, 1910, 1920] # cf. Chapter 4....
1.65625
2
generate_training_data_drb.py
SimonTopp/Graph-WaveNet
0
4031
<reponame>SimonTopp/Graph-WaveNet from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import numpy as np import os import pandas as pd import util import os.path import pandas as pd import n...
2.875
3
Phase-1/Python Basic 1/Day-3.py
CodedLadiesInnovateTech/python-challenges
11
4032
<reponame>CodedLadiesInnovateTech/python-challenges <<<<<<< HEAD """ 1. Write a Python program to print the documents (syntax, description etc.) of Python built-in function(s). Sample function : abs() Expected Result : abs(number) -> number Return the absolute value of the argument. ...
4.40625
4
tests/python/metaclass_inheritance.py
gmgunter/pyre
25
4033
<filename>tests/python/metaclass_inheritance.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- # # <NAME>. aïvázis # orthologue # (c) 1998-2021 all rights reserved # # """ When a metaclass understands the extra keywords that can be passed during class declaration, it has to override all these to accommodate the chang...
2.9375
3
cs101/module8/8-1/chroma1.py
idsdlab/basicai_sp21
1
4034
from cs1media import * import math def dist(c1, c2): r1, g1, b1 = c1 r2, g2, b2 = c2 return math.sqrt((r1-r2)**2 + (g1-g2)**2 + (b1-b2)**2) def chroma(img, key, threshold): w, h = img.size() for y in range(h): for x in range(w): p = img.get(x, y) if dist(p, key) < threshold: img.set...
3.40625
3
wfirst_stars/mklc.py
RuthAngus/wfirst_stars
0
4035
import numpy as np import scipy import scipy.io import pylab import numpy import glob import pyfits def mklc(t, nspot=200, incl=(scipy.pi)*5./12., amp=1., tau=30.5, p=10.0): diffrot = 0. ''' This is a simplified version of the class-based routines in spot_model.py. It generates a light curves for dark, p...
2.625
3
bin/sort.py
pelavarre/pybashish
4
4036
<filename>bin/sort.py #!/usr/bin/env python3 """ usage: sort.py [-h] sort lines options: -h, --help show this help message and exit quirks: sorts tabs as different than spaces sorts some spaces ending a line as different than none ending a line examples: Oh no! No examples disclosed!! 💥 💔 💥 """ # FIXME...
3.21875
3
davan/http/service/telldus/tdtool.py
davandev/davanserver
0
4037
<reponame>davandev/davanserver<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- import sys, getopt, httplib, urllib, json, os import oauth.oauth as oauth import datetime from configobj import ConfigObj import logging global logger logger = logging.getLogger(os.path.basename(__file__)) import davan.util.appli...
2.171875
2
ichnaea/data/export.py
rajreet/ichnaea
348
4038
from collections import defaultdict import json import re import time from urllib.parse import urlparse import uuid import boto3 import boto3.exceptions import botocore.exceptions import markus import redis.exceptions import requests import requests.exceptions from sqlalchemy import select import sqlalchemy.exc from ...
2.171875
2
test/inference_correctness/dcn_multi_hot.py
x-y-z/HugeCTR
130
4039
<filename>test/inference_correctness/dcn_multi_hot.py import hugectr from mpi4py import MPI solver = hugectr.CreateSolver(model_name = "dcn", max_eval_batches = 1, batchsize_eval = 16384, batchsize = 16384, ...
1.859375
2
bindings/pydrake/systems/perception.py
RobotLocomotion/drake-python3.7
2
4040
<reponame>RobotLocomotion/drake-python3.7 import numpy as np from pydrake.common.value import AbstractValue from pydrake.math import RigidTransform from pydrake.perception import BaseField, Fields, PointCloud from pydrake.systems.framework import LeafSystem def _TransformPoints(points_Ci, X_CiSi): # Make homogen...
2.328125
2
experiments/db_test.py
mit-ll/CATAN
15
4041
<gh_stars>10-100 #!/usr/bin/env python """ @author <NAME> © 2015 Massachusetts Institute of Technology """ import argparse import random import catan.db from catan.data import NodeMessage # test data STATUS_LIST = ['ok', 'injured', 'deceased'] # nodes def gen_nodes(n, db, start_lat, stop_lat, start_long, stop_long...
2.6875
3
Medium/200.py
Hellofafar/Leetcode
6
4042
<gh_stars>1-10 # ------------------------------ # 200. Number of Islands # # Description: # Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid...
3.828125
4
tests/formatters/fseventsd.py
SamuelePilleri/plaso
0
4043
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the fseventsd record event formatter.""" from __future__ import unicode_literals import unittest from plaso.formatters import fseventsd from tests.formatters import test_lib class FseventsdFormatterTest(test_lib.EventFormatterTestCase): """Tests for the...
2.484375
2
train.py
Farzin-Negahbani/PathoNet
0
4044
from keras.callbacks import ModelCheckpoint,Callback,LearningRateScheduler,TensorBoard from keras.models import load_model import random import numpy as np from scipy import misc import gc from keras.optimizers import Adam from imageio import imread from datetime import datetime import os import json import models from...
2.03125
2
tests/chainer_tests/functions_tests/array_tests/test_flatten.py
mingxiaoh/chainer-v3
7
4045
import unittest import numpy import chainer from chainer import cuda from chainer import functions from chainer import gradient_check from chainer import testing from chainer.testing import attr @testing.parameterize(*testing.product({ 'shape': [(3, 4), ()], 'dtype': [numpy.float16, numpy.float32, numpy.flo...
2.59375
3
categories/migrations/0001_initial.py
snoop2head/exercise_curation_django
3
4046
# Generated by Django 3.0.3 on 2020-03-24 09:59 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('exercises', '0018_photo_file'), ] operations = [ migrations.CreateModel( na...
1.78125
2
src/metarl/envs/dm_control/dm_control_env.py
neurips2020submission11699/metarl
2
4047
<filename>src/metarl/envs/dm_control/dm_control_env.py<gh_stars>1-10 from dm_control import suite from dm_control.rl.control import flatten_observation from dm_env import StepType import gym import numpy as np from metarl.envs import Step from metarl.envs.dm_control.dm_control_viewer import DmControlViewer class DmC...
2.296875
2
python_modules/lakehouse/lakehouse/snowflake_table.py
vatervonacht/dagster
3
4048
from dagster import check from .house import Lakehouse from .table import create_lakehouse_table_def class SnowflakeLakehouse(Lakehouse): def __init__(self): pass def hydrate(self, _context, _table_type, _table_metadata, table_handle, _dest_metadata): return None def materialize(self, c...
2.265625
2
pype/plugins/maya/publish/validate_look_no_default_shaders.py
tokejepsen/pype
0
4049
<reponame>tokejepsen/pype from maya import cmds import pyblish.api import pype.api import pype.maya.action class ValidateLookNoDefaultShaders(pyblish.api.InstancePlugin): """Validate if any node has a connection to a default shader. This checks whether the look has any members of: - lambert1 - initi...
2.390625
2
data_science_app/app.py
Johne-DuChene/data_science_learning_app
0
4050
<gh_stars>0 from flask import Flask # initialize the app app = Flask(__name__) # execute iris function at /iris route @app.route("/iris") def iris(): from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression X, y = load_iris(return_X_y=True) clf = LogisticRegression( ...
2.515625
3
vbdiar/scoring/normalization.py
VarunSrivastava19/VBDiarization
101
4051
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2018 Brno University of Technology FIT # Author: <NAME> <<EMAIL>> # All Rights Reserved import os import logging import pickle import multiprocessing import numpy as np from sklearn.metrics.pairwise import cosine_similarity from vbdiar.features.segments...
2.046875
2
agent_based_models/abm_allelopathy/plot_data.py
mattsmart/biomodels
0
4052
<filename>agent_based_models/abm_allelopathy/plot_data.py import matplotlib.pyplot as plt import os def data_plotter(lattice_dict, datafile_dir, plot_dir): # total spaces on grid implies grid size total_cells = lattice_dict['E'][0] + lattice_dict['D_a'][0] + lattice_dict['D_b'][0] + lattice_dict['B'][0] ...
2.34375
2
azure-mgmt-network/azure/mgmt/network/v2018_10_01/models/virtual_wan_security_providers.py
JonathanGailliez/azure-sdk-for-python
1
4053
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
1.867188
2
jsonresume_theme_stackoverflow/filters.py
flowgunso/jsonresume-theme-stackoverflow
0
4054
import datetime import re from .exceptions import ObjectIsNotADate def format_date(value, format="%d %M %Y"): regex = re.match(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})", value) if regex is not None: date = datetime.date( int(regex.group("year")), int(regex.group("mont...
3.484375
3
ipec/data/core.py
wwwbbb8510/ippso
9
4055
import numpy as np import os import logging from sklearn.model_selection import train_test_split DATASET_ROOT_FOLDER = os.path.abspath('datasets') class DataLoader: train = None validation = None test = None mode = None partial_dataset = None @staticmethod def load(train_path=None, valid...
2.625
3
FOR/Analisador-completo/main.py
lucasf5/Python
1
4056
<filename>FOR/Analisador-completo/main.py<gh_stars>1-10 # Exercício Python 56: Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa, mostre: a média de idade do grupo, qual é o nome do homem mais velho e quantas mulheres têm menos de 20 anos. mediaidade = '' nomelista = [] idadelista...
3.71875
4
test/python/quantum_info/operators/test_operator.py
EnriqueL8/qiskit-terra
2
4057
<reponame>EnriqueL8/qiskit-terra<filename>test/python/quantum_info/operators/test_operator.py # -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # 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 ...
2.046875
2
pages/feature_modal.py
jack-skerrett-bluefruit/Python-ScreenPlay
0
4058
<gh_stars>0 from selenium.webdriver.common.by import By class feature_modal: title_textbox = (By.ID, "feature-name") description_textbox = (By.ID, "description") save_button = (By.XPATH, "/html/body/app/div[3]/div[2]/div/div/div/button[1]")
2.046875
2
liststations.py
CrookedY/AirPollutionBot
1
4059
from urllib2 import Request, urlopen, URLError import json request = Request('https://uk-air.defra.gov.uk/sos-ukair/api/v1/stations/') try: response = urlopen(request) data = response.read() except URLError, e: print 'error:', e stations= json.loads (data) #extract out station 2 stations2 = stations [7] prope...
3.125
3
pyfinancials/engine.py
kmiller96/PyFinancials
1
4060
<filename>pyfinancials/engine.py def hello_world(): """Tests the import.""" return "Hello world!"
1.453125
1
core/migrations/0002_auto_20180702_1913.py
mertyildiran/echo
5
4061
<reponame>mertyildiran/echo<gh_stars>1-10 # Generated by Django 2.0.6 on 2018-07-02 19:13 import core.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0001_initial'), ] operations = [ migrations.RenameField( mo...
1.734375
2
tests/test_helpers.py
ajdavis/aiohttp
1
4062
<filename>tests/test_helpers.py import pytest from unittest import mock from aiohttp import helpers import datetime def test_parse_mimetype_1(): assert helpers.parse_mimetype('') == ('', '', '', {}) def test_parse_mimetype_2(): assert helpers.parse_mimetype('*') == ('*', '*', '', {}) def test_parse_mimety...
2.421875
2
GenConfigs.py
truls/faas-profiler
0
4063
from os.path import join FAAS_ROOT="/lhome/trulsas/faas-profiler" WORKLOAD_SPECS=join(FAAS_ROOT, "specs", "workloads") #FAAS_ROOT="/home/truls/uni/phd/faas-profiler" WSK_PATH = "wsk" OPENWHISK_PATH = "/lhome/trulsas/openwhisk" #: Location of output data DATA_DIR = join(FAAS_ROOT, "..", "profiler_results") SYSTEM_CPU...
1.476563
1
Chapter09/calc.py
LuisPereda/Learning_Python
0
4064
def sum1(a,b): try: c = a+b return c except : print "Error in sum1 function" def divide(a,b): try: c = a/b return c except : print "Error in divide function" print divide(10,0) print sum1(10,0)
3.53125
4
radssh/hostkey.py
Eli-Tarrago/radssh
39
4065
<gh_stars>10-100 # # Copyright (c) 2014, 2016, 2018, 2020 LexisNexis Risk Data Management Inc. # # This file is part of the RadSSH software package. # # RadSSH is free software, released under the Revised BSD License. # You are permitted to use, modify, and redsitribute this software # according to the Revised BSD Lice...
2.09375
2
nuke/pymmh3.py
jfpanisset/Cryptomatte
543
4066
''' pymmh3 was written by <NAME> and enhanced by <NAME>, and is placed in the public domain. The authors hereby disclaim copyright to this source code. pure python implementation of the murmur3 hash algorithm https://code.google.com/p/smhasher/wiki/MurmurHash3 This was written for the times when you do not want to c...
3.46875
3
bindings/python/tests/test_factory.py
pscff/dlite
10
4067
<reponame>pscff/dlite<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- import os import dlite thisdir = os.path.abspath(os.path.dirname(__file__)) class Person: def __init__(self, name, age, skills): self.name = name self.age = age self.skills = skills def __repr__(self):...
2.8125
3
week_11_DS_N_Algorithm/03_Thr_Lecture/실습6_연속 부분 최대합.py
bky373/elice-racer-1st
1
4068
''' 연속 부분 최대합 nn개의 숫자가 주어질 때, 연속 부분을 선택하여 그 합을 최대화 하는 프로그램을 작성하시오. 예를 들어, 다음과 같이 8개의 숫자가 있다고 하자. 1 2 -4 5 3 -2 9 -10 이 때, 연속 부분이란 연속하여 숫자를 선택하는 것을 말한다. 가능한 연속 부분으로써 [1, 2, -4], [5, 3, -2, 9], [9, -10] 등이 있을 수 있다. 이 연속 부분들 중에서 가장 합이 큰 연속 부분은 [5, 3, -2, 9] 이며, 이보다 더 합을 크게 할 수는 없다. 따라서 연속 부분 최대합은 5+3+(-2)+9 = 15 이다...
2.8125
3
tests/test_dns.py
jensstein/mockdock
0
4069
<reponame>jensstein/mockdock #!/usr/bin/env python3 import unittest from mockdock import dns class DNSTest(unittest.TestCase): def test_build_packet(self): data = b"^4\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x06google\x03com\x00\x00\x01\x00\x01" packet = dns.build_packet(data, "192.168.0.1") ...
2.78125
3
tests/conftest.py
zhongnansu/es-cli
6
4070
<filename>tests/conftest.py """ Copyright 2019, Amazon Web Services 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 ...
2.046875
2
Cogs/ServerStats.py
Damiian1/techwizardshardware
0
4071
import asyncio import discord from datetime import datetime from operator import itemgetter from discord.ext import commands from Cogs import Nullify from Cogs import DisplayName from Cogs import UserTime from Cogs import Message def setup(bot): # Add the bot...
2.546875
3
chess_commentary_model/transformers_model/dataset_preprocessing.py
Rseiji/TCC-2020
0
4072
<filename>chess_commentary_model/transformers_model/dataset_preprocessing.py """Métodos de preprocessamento de testes individuais """ import pandas as pd import numpy as np import math def test_1(df, seed=0): """training: balanced; test: balanced training: 80k (40k 0, 40k 1) test: 20k (10k 0, 10k...
2.78125
3
venv/Lib/site-packages/CoolProp/constants.py
kubakoziczak/gasSteamPowerPlant
0
4073
# This file is automatically generated by the generate_constants_module.py script in wrappers/Python. # DO NOT MODIFY THE CONTENTS OF THIS FILE! from __future__ import absolute_import from . import _constants INVALID_PARAMETER = _constants.INVALID_PARAMETER igas_constant = _constants.igas_constant imolar_mass = _cons...
1.210938
1
torch_datasets/samplers/balanced_batch_sampler.py
mingruimingrui/torch-datasets
0
4074
import random import torch.utils.data.sampler class BalancedBatchSampler(torch.utils.data.sampler.BatchSampler): def __init__( self, dataset_labels, batch_size=1, steps=None, n_classes=0, n_samples=2 ): """ Create a balanced batch sampler for label based...
3.15625
3
ambari-common/src/main/python/resource_management/libraries/functions/get_bare_principal.py
likenamehaojie/Apache-Ambari-ZH
1,664
4075
#!/usr/bin/env python """ 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");...
2.296875
2
04/cross_validation.01.py
study-machine-learning/dongheon.shin
2
4076
<filename>04/cross_validation.01.py<gh_stars>1-10 from sklearn import svm, metrics import random import re def split(rows): data = [] labels = [] for row in rows: data.append(row[0:4]) labels.append(row[4]) return (data, labels) def calculate_score(train, test): train_data,...
2.875
3
third_party/org_specs2.bzl
wix/wix-oss-infra
3
4077
<gh_stars>1-10 load("@wix_oss_infra//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external") def dependencies(): import_external( name = "org_specs2_specs2_fp_2_12", artifact = "org.specs2:specs2-fp_2.12:4.8.3", artifact_sha256 = "777962ca58054a9ea86e294e025453ecf3...
1.46875
1
task/w2/trenirovka/12-rivnist 2.py
beregok/pythontask
1
4078
a = int(input()) b = int(input()) c = int(input()) d = int(input()) if a == 0 and b == 0: print("INF") else: if (d - b * c / a) != 0 and (- b / a) == (- b // a): print(- b // a) else: print("NO")
3.546875
4
src/reg_resampler.py
atif-hassan/Regression_ReSampling
15
4079
class resampler: def __init__(self): import pandas as pd from sklearn.preprocessing import LabelEncoder from collections import Counter import numpy as np self.bins = 3 self.pd = pd self.LabelEncoder = LabelEncoder self.Counter = Counter ...
3.203125
3
get_data/speech_commands.py
patrick-kidger/generalised_shapelets
32
4080
<reponame>patrick-kidger/generalised_shapelets import os import pathlib import sklearn.model_selection import tarfile import torch import torchaudio import urllib.request here = pathlib.Path(__file__).resolve().parent def _split_data(tensor, stratify): # 0.7/0.15/0.15 train/val/test split (train_tensor, test...
2.796875
3
app/endpoints/products.py
duch94/spark_crud_test
0
4081
<reponame>duch94/spark_crud_test from datetime import datetime from typing import List from flask import Blueprint, jsonify, request, json from app.models.products import Product, Category, products_categories from app import db products_blueprint = Blueprint('products', __name__) def create_or_get_cate...
2.703125
3
util/config/validators/test/test_validate_bitbucket_trigger.py
giuseppe/quay
2,027
4082
import pytest from httmock import urlmatch, HTTMock from util.config import URLSchemeAndHostname from util.config.validator import ValidatorContext from util.config.validators import ConfigValidationException from util.config.validators.validate_bitbucket_trigger import BitbucketTriggerValidator from test.fixtures i...
2.0625
2
Refraction.py
silkoch42/Geometric-Optics-from-QM
0
4083
<reponame>silkoch42/Geometric-Optics-from-QM # -*- coding: utf-8 -*- """ Created on Fri Mar 15 16:51:16 2019 @author: Silvan """ import numpy as np import scipy import matplotlib.pyplot as plt k=1000 n1=2.0 n2=1.0 alpha=np.pi/6.0 beta=np.arcsin(n2/n1*np.sin(alpha)) ya=1.0 xa=-ya*np.tan(alpha) ...
2.390625
2
readthedocs/docsitalia/management/commands/clear_elasticsearch.py
italia/readthedocs.org
19
4084
<reponame>italia/readthedocs.org<gh_stars>10-100 """Remove the readthedocs elasticsearch index.""" from __future__ import absolute_import from django.conf import settings from django.core.management.base import BaseCommand from elasticsearch import Elasticsearch class Command(BaseCommand): """Clear elasticsea...
1.585938
2
train.py
vnbot2/BigGAN-PyTorch
0
4085
""" BigGAN: The Authorized Unofficial PyTorch release Code by <NAME> and <NAME> This code is an unofficial reimplementation of "Large-Scale GAN Training for High Fidelity Natural Image Synthesis," by <NAME>, <NAME>, and <NAME> (arXiv 1809.11096). Let's go. """ import datetime import time import torc...
2.453125
2
geocamUtil/tempfiles.py
geocam/geocamUtilWeb
4
4086
<reponame>geocam/geocamUtilWeb<gh_stars>1-10 # __BEGIN_LICENSE__ #Copyright (c) 2015, United States Government, as represented by the #Administrator of the National Aeronautics and Space Administration. #All rights reserved. # __END_LICENSE__ import os import time import random import shutil from glob import glob im...
2
2
Ex1:Tests/ex2.py
Lludion/Exercises-SE
0
4087
# Ce fichier contient (au moins) cinq erreurs. # Instructions: # - tester jusqu'à atteindre 100% de couverture; # - corriger les bugs;" # - envoyer le diff ou le dépôt git par email.""" import hypothesis from hypothesis import given, settings from hypothesis.strategies import integers, lists class BinHeap: #st...
3.5625
4
python/snewpy/snowglobes.py
svalder/snewpy
0
4088
<gh_stars>0 # -*- coding: utf-8 -*- """The ``snewpy.snowglobes`` module contains functions for interacting with SNOwGLoBES. `SNOwGLoBES <https://github.com/SNOwGLoBES/snowglobes>`_ can estimate detected event rates from a given input supernova neutrino flux. It supports many different neutrino detectors, detector mate...
2.453125
2
rlcycle/dqn_base/loss.py
cyoon1729/Rlcycle
128
4089
from typing import List, Tuple from omegaconf import DictConfig import torch import torch.nn as nn import torch.nn.functional as F from rlcycle.common.abstract.loss import Loss class DQNLoss(Loss): """Compute double DQN loss""" def __init__(self, hyper_params: DictConfig, use_cuda: bool): Loss.__in...
2.34375
2
scripts/gap_filling_viewer.py
raphischer/probgf
3
4090
<gh_stars>1-10 """viewer application which allows to interactively view spatio-temporal gap filling results""" import os import argparse from datetime import datetime, timedelta from tkinter import Canvas, Tk, Button, RAISED, DISABLED, SUNKEN, NORMAL import numpy as np from PIL import Image, ImageTk import probgf.media...
2.46875
2
paypal/pro/tests.py
pdfcrowd/django-paypal
1
4091
<gh_stars>1-10 #!/usr/bin/python # -*- coding: utf-8 -*- from django.conf import settings from django.core.handlers.wsgi import WSGIRequest from django.forms import ValidationError from django.http import QueryDict from django.test import TestCase from django.test.client import Client from paypal.pro.fields import Cre...
2.15625
2
Hackerrank_Bot_Saves_Princess.py
madhurgupta96/Algorithmic-Journey
0
4092
# -*- coding: utf-8 -*- """ Created on Mon Dec 7 19:46:40 2020 @author: Intel """ def displayPathtoPrincess(n,grid): me_i=n//2 me_j=n//2 for i in range(n): if 'p' in grid[i]: pe_i=i for j in range(n): if 'p'==grid[i][j]: pe...
3.6875
4
gelviz/basic.py
HiDiHlabs/gelviz
0
4093
<gh_stars>0 import matplotlib.pyplot as plt import pybedtools import pandas as pnd import numpy as np import tabix import matplotlib.ticker as ticker from matplotlib.patches import Rectangle from matplotlib.patches import Arrow from matplotlib.path import Path from matplotlib.patches import PathPatch import matplotlib....
2.546875
3
toc/fsa/fsa.py
djrochford/toc
0
4094
<filename>toc/fsa/fsa.py<gh_stars>0 """ File containing DFA and NFA public classes """ import collections.abc from itertools import product, chain, combinations from string import printable from typing import ( AbstractSet, Container, FrozenSet, Iterable, List, Mapping, MutableMapping, O...
2.671875
3
Numbers/Roman Number Generator/tests.py
fossabot/IdeaBag2-Solutions
10
4095
<reponame>fossabot/IdeaBag2-Solutions<filename>Numbers/Roman Number Generator/tests.py #!/usr/bin/env python3 import unittest from roman_number_generator import arabic_to_roman class Test(unittest.TestCase): def _start_arabic_to_roman(self): self.assertRaises(ValueError, arabic_to_roman, 4000) s...
2.9375
3
modules/moduleBase.py
saintaardvark/glouton-satnogs-data-downloader
0
4096
from infrastructure.satnogClient import SatnogClient import os class ModuleBase: def __init__(self, working_dir): self.working_dir = working_dir def runAfterDownload(self, file_name, full_path, observation): raise NotImplementedError()
1.960938
2
oregano_plugins/fusion/server.py
MrNaif2018/Oregano
0
4097
<reponame>MrNaif2018/Oregano #!/usr/bin/env python3 # # Oregano - a lightweight Ergon client # CashFusion - an advanced coin anonymizer # # Copyright (C) 2020 <NAME> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"),...
1.4375
1
Excercici4Package/ex4.py
jtorrenth/CienciaDades
0
4098
<gh_stars>0 import matplotlib.pyplot as plt def countvalues(dataframe, subject): # Filtrem i tractem el dataset economydf = filtrar(dataframe, "economy") # el printem printar(economydf, subject) # Filtrem ara per subject infected i ho desem en un altre df infectedf = filtrar(dataframe, "infe...
3.078125
3
build/rules.bzl
filmil/bazel-ebook
9
4099
<gh_stars>1-10 # Copyright (C) 2020 Google Inc. # # This file has been licensed under Apache 2.0 license. Please see the LICENSE # file at the root of the repository. # Build rules for building ebooks. # This is the container CONTAINER = "filipfilmar/ebook-buildenv:1.1" # Use this for quick local runs. #CONTAINER =...
2.484375
2