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 |
|---|---|---|---|---|---|---|
tests/test_params.py | matthewjohnpayne/MPCData | 0 | 38900 | # mpcdata/tests/test_query.py
# import pytest
# Third-party imports
import os
# Import the specific package/module/function we are testing
import mpcdata.params as params
# from .context import mpcdata
def test_required_dictionaries_exist():
"""
Does params.py contain all of the required dictionaries ?
"... | 2.421875 | 2 |
Week 3/Python Track/Permituation.py | Dawit-Getachew/A2SV_Practice | 0 | 38901 | <filename>Week 3/Python Track/Permituation.py
# Enter your code here. Read input from STDIN. Print output to STDOUT
from itertools import permutations
s1 = input().split()
S2 = sorted(tuple(s1[0]))
out = tuple(permutations(S2,int(s1[1])))
for i in out:
print("".join(i))
| 3.859375 | 4 |
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... | 2.3125 | 2 |
python/exercicios mundo 2/ex36_45.py/ex011.py | LEXW3B/PYTHON | 1 | 38903 | #45-crie um programa que faça o computador jogar jokenpo com voce.
print('=====JOKENPO=====')
print('')
from random import randint
from time import sleep
itens = ('pedra','papel','tesoura')
computador = randint(0, 2)
print('''FAÇA SUA ESCOLHA
[ 0 ] pedra
[ 1 ] papel
[ 2 ] tesoura
''')
jogador = int(input('Qual a sua j... | 3.921875 | 4 |
pyvcloud/vcd/vm.py | pacogomez/pyvcloud | 0 | 38904 | <filename>pyvcloud/vcd/vm.py
# VMware vCloud Director Python SDK
# Copyright (c) 2017 VMware, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apac... | 2.40625 | 2 |
backend/api/models.py | ezequielaranda/solservicios | 0 | 38905 | <reponame>ezequielaranda/solservicios<filename>backend/api/models.py
from django.db import models
from rest_framework import serializers
from django.utils import timezone
from django.contrib.auth.models import User
class Empresa(models.Model):
nombre = models.CharField(max_length=150, null=True)
domicilio = mo... | 2.265625 | 2 |
Leak #5 - Lost In Translation/windows/Resources/Dsz/PyScripts/Lib/dsz/mca/survey/cmd/passworddump/errors.py | bidhata/EquationGroupLeaks | 9 | 38906 | # uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: errors.py
import mcl.status
ERR_SUCCESS = mcl.status.MCL_SUCCESS
ERR_INVALID_PARAM = mcl.status.framework.ERR_START
ERR_NOT_IMPLEMENTED = mcl.status.... | 1.609375 | 2 |
meep/__init__.py | mtander/meep | 0 | 38907 | from flask import Flask
from config import DefaultConfig
# factory method for creating app objects
def create_app(config=DefaultConfig()):
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(config)
# initialize database and migrations
from meep.models import db, migrate
... | 2.125 | 2 |
inversehaar.py | matthewearl/inversehaar | 20 | 38908 | #!/usr/bin/env python
# Copyright (c) 2015 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge... | 1.726563 | 2 |
users/urls.py | a-vek/news-aggregator | 0 | 38909 | from django.urls import path
from news.views import scrape, news_list
from . import views
urlpatterns = [
# path('', views.index, name="home"),
# path('newslist', news_list, name="home"),
]
| 1.820313 | 2 |
communication/socket_util.py | compix/MetadataManagerCore | 0 | 38910 | <gh_stars>0
import socket
import json
import struct
from concurrent.futures import ThreadPoolExecutor
import time
import logging
logger = logging.getLogger(__name__)
def readBlob(sock, size):
chunks = []
bytes_recd = 0
while bytes_recd < size:
chunk = sock.recv(min(size - bytes_recd, 2048))
... | 2.46875 | 2 |
src/api/migrations/0003_auto_20190604_1058.py | pradipta/back-end | 17 | 38911 | <filename>src/api/migrations/0003_auto_20190604_1058.py
# Generated by Django 2.2.2 on 2019-06-04 15:58
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("api", "0002_auto_20190522_1618")]
operations = [
migrations.DeleteModel(name="ActiveAdminComment"),
... | 1.429688 | 1 |
Software 1/Practical/Week 09/Practical 14/vector.py | KristoffLiu/YorkCSSolution | 3 | 38912 | <gh_stars>1-10
class Vector:
#exercise 01
def __init__(self,inputlist):
self._vector = []
_vector = inputlist
#exercise 02
def __str__(self):
return "<" + str(self._vector).strip("[]") + ">"
#exercise 03
def dim(self):
return len(self._vector)
#exercise... | 3.71875 | 4 |
Stomp/Utils/util.py | phan91/STOMP_agilis | 0 | 38913 | <reponame>phan91/STOMP_agilis
import re
def replace_all(repls, str):
"""
Applies replacements as described in the repls dictionary on input str.
:param repls: Dictionary of replacements
:param str: The string to be changed
:return: The changed string
"""
return re.sub('|'.join(re.escape(ke... | 3.25 | 3 |
ex048.py | CarlosEduardoAS/Python-exercicios | 0 | 38914 | s = 0
cont = 0
for c in range(1, 501, 2):
if c % 3 == 0:
cont += 1
s += c
print('A soma ente todos os {} ímpares múltiplos de 3 entre 1 e 500 é {}.'.format(cont, s)) | 3.6875 | 4 |
source/casual/make/compiler/gcc.py | casualcore/casual-make | 0 | 38915 | <gh_stars>0
import platform
import casual.make.platform.common as common
import casual.make.tools.environment as environment
CXX = common.cxx()
COMPILER = CXX
def warning_directive():
return ["-Wall",
"-Wextra",
"-Werror",
"-Wsign-compare",
"-Wuninitialized",
... | 2 | 2 |
modificar_pacientes.py | Ratius9919/TP-programacion | 0 | 38916 | import os
def crear_dni(): #Se solicita un valor y tras las validaciones para verificar si es un dni, se lo devuelve.
valor = False
while valor == False:
try:
dni = input("[?] Por favor, ingrese su DNI: ")
if int(dni) > 1000000 and int(dni) < 200000000:
... | 3.375 | 3 |
solutions/pybasic_ex1_4_1.py | mfernandes61/python-basic | 40 | 38917 | # Protein sequence given
seq = "MPISEPTFFEIF"
# Split the sequence into its component amino acids
seq_list = list(seq)
# Use a set to establish the unique amino acids
unique_amino_acids = set(seq_list)
# Print out the unique amino acids
print(unique_amino_acids)
| 3.515625 | 4 |
campy/private/backends/backend_interactive_console.py | TristenSeth/campy | 0 | 38918 | <gh_stars>0
from campy.private.backend_base import ConsoleBackendBase
class InteractiveConsoleBackend(ConsoleBackendBase):
def clear_console(self):
pass
def set_console_font(self, font):
pass
def set_console_size(self, console_size):
pass
def get_console_line(self):
r... | 2.0625 | 2 |
apps/examples/simple-example/test/integration/test_it_collect_spawn.py | pcanto-hopeit/hopeit.engine | 15 | 38919 | import os
import uuid
import pytest # type: ignore
from hopeit.testing.apps import execute_event
from hopeit.server.version import APPS_API_VERSION
from model import Something
from simple_example.collector.collect_spawn import ItemsInfo, ItemsCollected
APP_VERSION = APPS_API_VERSION.replace('.', "x")
@pytest.fix... | 1.984375 | 2 |
app.py | ruturajshete1008/Heart-health-prediction | 3 | 38920 | from flask import Flask, jsonify, render_template
import pandas as pd
import os
import pymongo
from flask import send_from_directory
from pymongo import MongoClient
# initialize flask app
app = Flask(__name__)
app.config['JSON_SORT_KEYS'] = False
# read the data and merge it
df_labels = pd.read_csv('train_labels.csv... | 2.703125 | 3 |
tests/test_transform.py | braedon/kong-log-bridge | 2 | 38921 | <reponame>braedon/kong-log-bridge
import unittest
from kong_log_bridge.transform import transform_log
class Test(unittest.TestCase):
maxDiff = None
def test_transform(self):
test_log = {
"latencies": {
"request": 191,
"kong": 0,
"proxy": 19... | 2.234375 | 2 |
tests/utils.py | ilyarogozin/homework_bot | 0 | 38922 | <gh_stars>0
from inspect import signature
from types import ModuleType
def check_function(scope: ModuleType, func_name: str, params_qty: int = 0):
"""Checks if scope has a function with specific name and params with qty"""
assert hasattr(scope, func_name), (
f'Не найдена функция `{func_name}`. '
... | 2.734375 | 3 |
train.py | ex7763/pytorch-HED | 0 | 38923 | import torch
import yaml
import argparse
from dataset.BSD500 import BSD500Dataset
from models.HED import HED
###############
# parse cfg
###############
parser = argparse.ArgumentParser()
parser.add_argument('--cfg', dest='cfg', required=True, help='path to config file')
args = parser.parse_known_args()
args = pars... | 2.375 | 2 |
tests/unit/hypernode_vagrant_runner/commands/test_parse_start_runner_arguments.py | vdloo/hypernode-vagrant-runner | 0 | 38924 | <filename>tests/unit/hypernode_vagrant_runner/commands/test_parse_start_runner_arguments.py
from mock import ANY, call
from hypernode_vagrant_runner.commands import parse_start_runner_arguments
from hypernode_vagrant_runner.settings import HYPERNODE_VAGRANT_PHP_VERSIONS, \
HYPERNODE_VAGRANT_DEFAULT_USER, HYPERNODE... | 2.421875 | 2 |
Configs/UNet_Configs.py | zeeshanalipnhwr/Semantic-Segmentation-Keras | 3 | 38925 | DEPTH = 16 # the number of filters of the first conv layer of the encoder of the UNet
# Training hyperparameters
BATCHSIZE = 16
EPOCHS = 100
OPTIMIZER = "adam"
| 1.585938 | 2 |
geinos/app/core/radius/radius.py | falhenaki/GEINOS | 3 | 38926 | <gh_stars>1-10
from sqlalchemy import *
from sqlalchemy import Column, String
from sqlalchemy.ext.declarative import declarative_base
from app.core.sqlalchemy_base.augmented_base import CustomMixin
Base = declarative_base()
class Radius(CustomMixin, Base):
__tablename__ = "Radius"
host = Column(String, primary... | 2.484375 | 2 |
FCN.py | xinming365/DL-exercise | 0 | 38927 | <filename>FCN.py<gh_stars>0
# Author : xinming
# Time : 2020/06/27
# Imports
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
import torchvision.datasets as datasets
import torchvision.transforms as transforms
#Create fully connecte... | 2.78125 | 3 |
skexplain/common/utils.py | monte-flora/scikit-explain | 0 | 38928 | <reponame>monte-flora/scikit-explain
import numpy as np
import xarray as xr
import pandas as pd
from collections import ChainMap
from statsmodels.distributions.empirical_distribution import ECDF
from scipy.stats import t
class MissingFeaturesError(Exception):
""" Raised when features are missing.
E.g., A... | 2.921875 | 3 |
recipes/recipe_modules/powershell/resources/psinvoke.py | xswz8015/infra | 0 | 38929 | <reponame>xswz8015/infra
# Copyright 2021 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 subprocess
import argparse
import sys
import os
import re
import json
import codecs
import platform
# Used to run commands t... | 2.09375 | 2 |
Cinema 4D/Clean.py | FitchOpenSource/C4D-To-Unity | 2 | 38930 | <reponame>FitchOpenSource/C4D-To-Unity
import c4d
from c4d import gui, documents
#Welcome to the world of Python
def findNameMaterial(string, materials, cnt):
cnt = cnt + 1
string = string + "_" + str(cnt)
if materials.count(string) == 0:
return string
else:
string = findNameMater... | 2.390625 | 2 |
templates/flask/flaskRest/app/configs/config.py | david-osas/create-basic-app | 2 | 38931 | <reponame>david-osas/create-basic-app
from .development_config import DevelopmentConfig
from .production_config import ProductionConfig
from .testing_config import TestingConfig
ENVIRONMENT_MAPPING = {
"production": ProductionConfig,
"development": DevelopmentConfig,
"testing": TestingConfig
}
| 1.421875 | 1 |
LeetCode/Python/160.intersection-of-two-linked-lists.py | Alfonsxh/LeetCode-Challenge-python | 0 | 38932 | <reponame>Alfonsxh/LeetCode-Challenge-python
#
# @lc app=leetcode id=160 lang=python
#
# [160] Intersection of Two Linked Lists
#
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# 参考:https://leetcode-cn.com/problems/intersec... | 3.390625 | 3 |
test/client/test_utils.py | DobromirM/swim-system-python | 8 | 38933 | <gh_stars>1-10
# Copyright 2015-2021 SWIM.AI 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 la... | 2.296875 | 2 |
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... | 3.28125 | 3 |
src/test/test.py | ntalabot/base_dl_project_struct | 0 | 38935 | <reponame>ntalabot/base_dl_project_struct
"""
Module for testing models (evaluation, predictions).
"""
import numpy as np
import matplotlib.pyplot as plt
import torch
import torchvision
def predict_dataloader(model, dataloader, discard_target=True):
"""
Return predictions for the given dataloader and model.... | 3.03125 | 3 |
forums/migrations/0007_auto_20191203_0820.py | phiratio/django-forums-app | 22 | 38936 | # Generated by Django 2.2.5 on 2019-12-03 08:20
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('forums', '0006_auto_20191203_0758'),
]
operations = [
migrations.AlterField(
model_name='post',
... | 1.445313 | 1 |
hw4/generate.py | anthonywchen/uci-statnlp | 16 | 38937 | <filename>hw4/generate.py
import argparse
import json
import random
import jsonlines
import tqdm
from transformers import BartTokenizer, BartForConditionalGeneration
import decoders
from models import TransformerModel
random.seed(0)
def generate_summary(model, tokenizer, document, decoder):
""" Generates a sum... | 2.6875 | 3 |
xain/grpc/test_grpc.py | skade/xain | 0 | 38938 | <filename>xain/grpc/test_grpc.py
from concurrent import futures
import grpc
import numpy as np
import pytest
from numproto import ndarray_to_proto, proto_to_ndarray
from xain.grpc import hellonumproto_pb2, hellonumproto_pb2_grpc
from xain.grpc.numproto_server import NumProtoServer
@pytest.fixture
def greeter_server... | 2.015625 | 2 |
AffluenceCounter/app/tracker.py | dvalladaresv/AIVA_2021_Deteccion_de_actividad_grupo_F | 0 | 38939 | import cv2
OPENCV_OBJECT_TRACKERS = {
"csrt": cv2.TrackerCSRT_create,
"kcf": cv2.TrackerKCF_create,
"mil": cv2.TrackerMIL_create
}
class Track:
"""
Seguimiento de una persona
"""
def __init__(self, tracker_name, first_frame, bbox, id, references):
self._tracker... | 2.90625 | 3 |
app/middlewares/apikey_auth.py | meongbego/IOT_ADRINI | 1 | 38940 | <reponame>meongbego/IOT_ADRINI<filename>app/middlewares/apikey_auth.py<gh_stars>1-10
from functools import wraps
from app.helpers.rest import *
from app import redis_store
from flask import request
from app.models import model as db
import hashlib
def apikey_required(f):
@wraps(f)
def decorated_function(*arg... | 2.140625 | 2 |
tests/recog_tests.py | anthonys01/snip2fumen | 0 | 38941 | <gh_stars>0
"""
Test image to fumen conversion
"""
import unittest
from snip2fumen.recog import BoardRecognizer, FumenEncoder
class RegogTests(unittest.TestCase):
"""
Test class
"""
def test_jstris1(self):
"""
Test jstris 1
"""
board_recog = BoardRecognizer()
gr... | 2.609375 | 3 |
src/utility.py | wadinj/out_of_many_one | 0 | 38942 | """ General purpose functions """
import hashlib
LOGGING_FORMAT = '%(asctime)s %(levelname)s: %(message)s'
def hash_from_strings(items):
""" Produce a hash value from the combination of all str elements """
JOIN_KEY = '+|+'
item_text = JOIN_KEY.join(items).encode('utf-8')
return hashlib.sha256(item_t... | 3.21875 | 3 |
gqa/data/datasets/gqa.py | xiling42/VL-BERT | 0 | 38943 | <reponame>xiling42/VL-BERT
import json
import os
import pickle
import numpy as np
from PIL import Image
import torch
from torch.utils.data import Dataset
from torchvision import transforms
import h5py
from .transforms import Scale
img = None
img_info = {}
def gqa_feature_loader(root):
global img, img_info
if... | 2.28125 | 2 |
progressivis/core/changemanager_dict.py | jdfekete/progressivis | 51 | 38944 |
from .changemanager_base import BaseChangeManager
from ..utils.psdict import PsDict
from ..table.tablechanges import TableChanges
from .slot import Slot
import copy
class DictChangeManager(BaseChangeManager):
"""
Manage changes that occured in a DataFrame between runs.
"""
def __init__(self,
... | 2.4375 | 2 |
classifier/classes/data/loaders/Loader.py | canary-for-cognition/multimodal-dl-framework | 2 | 38945 | import os
import torch
from classifier.classes.utils.Params import Params
class Loader:
def __init__(self, modality: str, for_submodule: bool = False):
self._modality = modality
self._modality_params = Params.load_modality_params(self._modality)
experiment_params = Params.load_experime... | 2.5 | 2 |
rel2/bluecat_app/bin/bluecat/entity.py | mheidir/BlueCatSG-SplunkApp-UnOfficial | 1 | 38946 | <filename>rel2/bluecat_app/bin/bluecat/entity.py
from suds import WebFault
from api_exception import api_exception
from util import *
from version import version
from wrappers.generic_setters import *
class entity(object):
"""Instantiate an entity. Entities are hashable and comparable with the = operator.
:... | 2.296875 | 2 |
users/admin.py | rossm6/accounts | 11 | 38947 | <filename>users/admin.py
from django.contrib import admin
from users.models import Lock, UserSession
admin.site.register(Lock)
admin.site.register(UserSession)
| 1.351563 | 1 |
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>
... | 3.359375 | 3 |
Python_codes/palindrome_string/palindrome.py | latedeveloper08/hacktober2021 | 0 | 38949 | <filename>Python_codes/palindrome_string/palindrome.py
string=input("Enter a string:")
length=len(string)
mid=length//2
rev=-1
for a in range(mid):
if string[a]==string[rev]:
a+=1
rev=-1
else:
print(string,"is a palindrome")
break
else:
print(string,"is not a palindrome")
| 4.25 | 4 |
PythonClient/Framework/ModCameraGimble.py | SweetShot/AirSim | 0 | 38950 | <gh_stars>0
from ModBase import *
import setup_path
import airsim
import copy
class CameraOrientations:
def __init__(self, id, pitch = 0, roll = 0, yaw = 0): # wrt body
self.id = id
self.pitch = pitch * 3.14/180
self.roll = roll * 3.14/180
self.yaw = yaw * 3.14/180
self.use... | 2.328125 | 2 |
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 *
| 1.070313 | 1 |
CAV Test and Evaluation/Scaled-vehicle-in-the-loop/catkin_ws/src/tongjirc/script/talker.py | tongjirc/Intelligent-Vehicle-and-Road | 3 | 38952 | <filename>CAV Test and Evaluation/Scaled-vehicle-in-the-loop/catkin_ws/src/tongjirc/script/talker.py
#!/usr/bin/env python2
#created by <NAME>irc
#Oct. 1th 2018
import rospy
import time
from std_msgs.msg import String,Duration
from trajectory_msgs.msg import JointTrajectoryPoint
jp=JointTrajectoryPoint()
def talker... | 2.234375 | 2 |
problems/greedy/Solution870.py | akalu/cs-problems-python | 0 | 38953 | <gh_stars>0
""" Given two arrays A and B of equal size, the advantage of A with respect to B
is the number of indices i for which A[i] > B[i].
Return any permutation of A that maximizes its advantage with respect to B.
Example 1:
Input: A = [2,7,11,15], B = [1,10,4,11] Output: [2,11,7,... | 3.25 | 3 |
src/authentication/migrations/0003_user_additional_fiels_nullable.py | Alirezaja1384/MajazAmooz | 3 | 38954 | <gh_stars>1-10
# Generated by Django 3.1.7 on 2021-03-27 10:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("authentication", "0002_auto_20210326_1814"),
]
operations = [
migrations.AlterField(
model_name="user",
... | 1.515625 | 2 |
src/hyperloop/Python/mission/tests/test_lat_long.py | jcchin/Hyperloop_v2 | 1 | 38955 | import pytest
from hyperloop.Python.mission import lat_long
import numpy as np
from openmdao.api import Group, Problem
def create_problem(component):
root = Group()
prob = Problem(root)
prob.root.add('comp', component)
return prob
class TestMissionDrag(object):
def test_case1_vs_npss(self):
... | 2.28125 | 2 |
answers/ex10.py | metmirr/project-euler | 1 | 38956 | <reponame>metmirr/project-euler<gh_stars>1-10
"""
Problem 10:
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.Find the sum of
all the primes below two million.
"""
sum = 0
size = 2000000
slots = [True for i in range(size)]
slots[0] = False
slots[1] = False
for stride in range(2, size // 2):
pos ... | 3.28125 | 3 |
src/oci_cli/cli_clients.py | honzajavorek/oci-cli | 0 | 38957 | # coding: utf-8
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
import os
import pkgutil
from os.path import abspath
from inspect import getsourcefile
CLIENT_MAP = {}
MODULE_TO_TYPE_MAPPINGS = {}
ALL_SERVICES_DIR = "services"
this_file_path = abspath(getsourcefile(lambda: 0))
if "site-p... | 2.0625 | 2 |
testing/unittest_analysis.py | dsg-bielefeld/mumodo | 1 | 38958 | <reponame>dsg-bielefeld/mumodo<gh_stars>1-10
import unittest
import pandas as pd
from mumodo.mumodoIO import open_intervalframe_from_textgrid, \
open_streamframe_from_xiofile
from mumodo.analysis import intervalframe_overlaps, intervalframe_union, \
invert_interva... | 2.21875 | 2 |
main.py | neohanju/GoogleImageSearchDownload | 0 | 38959 | # reference: http://icrawler.readthedocs.io/en/latest/usage.html
from icrawler.builtin import GoogleImageCrawler
import os
dataset_base_dir = 'D:/Workspace/Dataset/fake_image_detection/task_2'
keyword_lists = ['snapchat face swap', 'MSQRD']
for keyword in keyword_lists:
folder_path = dataset_base_dir + '/' + ke... | 2.640625 | 3 |
Chapter 3/Q19_Match_output.py | inshaal/CBSE_NCERT_SOLUTIONS | 0 | 38960 | ''' Q19 Predict the output'''
class Match:
''"Runs and Wickets"''
runs=281
wickets=5
def __init__(self,runs,wickets):
self.runs=runs
self.wickets=wickets
print "Runs scored are : ",runs
print "Wickets taken are : ",wickets
print "Test.__do__ :",Match.__doc__
pr... | 2.75 | 3 |
src/daipeproject/silver/01_some_notebook.py | DataSentics/daipe-bad-practices-1 | 0 | 38961 | # Databricks notebook source
# MAGIC %run ../app/bootstrap
# COMMAND ----------
from pyspark.sql.dataframe import DataFrame
from datalakebundle.imports import transformation
# COMMAND ----------
datasets = [
{
"id": "123",
"name": "knihydobrovsky_cz",
"custom_attrs": {
105: "... | 2.40625 | 2 |
tests/pyspark_utils/test_convert_cerberus_schema_to_pyspark.py | ONS-SST/cis_households | 0 | 38962 | from pyspark.sql.types import StructField
from cishouseholds.pyspark_utils import convert_cerberus_schema_to_pyspark
def test_conversion():
cerberus_schema = {"id": {"type": "string"}, "whole_number": {"type": "integer"}}
pyspark_schema = convert_cerberus_schema_to_pyspark(cerberus_schema)
assert len(p... | 2.75 | 3 |
bus_schedule.py | 32-52/LanitBusScheduleBot | 3 | 38963 | <reponame>32-52/LanitBusScheduleBot
from models import Destinations, Locations
from settings import logging
from datetime import datetime
import requests
import settings
class LanitBusInfo:
@staticmethod
def get_nearest_bus(location: Locations, destination: Destinations) -> str:
logging.info('Getting ... | 2.59375 | 3 |
test/unit/controllers/logging_api_test.py | beer-garden/brew-view | 5 | 38964 | <filename>test/unit/controllers/logging_api_test.py
import unittest
import json
from . import TestHandlerBase
from mock import patch
class LoggingApiTest(TestHandlerBase):
def setUp(self):
super(LoggingApiTest, self).setUp()
@patch("brew_view.controllers.logging_api.MongoParser.serialize_logging_con... | 2.703125 | 3 |
src/sparkcleaner/functions/string_cleaning.py | IvoWnds/sparkcleaner-git | 0 | 38965 | from typing import List, Optional, Type
import pyspark.sql.functions as F
from pyspark.sql import DataFrame as SparkDataFrame
from pyspark.sql.types import DataType
import src.sparkcleaner.helpers.verify as verify
def remove_leading_zeros(df: SparkDataFrame,
col_name: str,
... | 3.390625 | 3 |
src/unifi_api/utils/decorators.py | r4mmer/unifi_python_client | 1 | 38966 | <gh_stars>1-10
# custom decorators
from functools import wraps
import trafaret as t
from .exceptions import UnifiLoginError
from .models import JsonResponse
def call_requires_login(func):
def validate(resp):
if resp.status_code == 401 and 'application/json' in resp.headers.get('Content-Type'):
... | 2.484375 | 2 |
examples/another_simple_example.py | Inzilkin/vk.py | 2 | 38967 | <filename>examples/another_simple_example.py<gh_stars>1-10
from vk import VK
from vk.utils import TaskManager
import asyncio
import logging
logging.basicConfig(level="DEBUG")
token = "TOKEN"
vk = VK(access_token=token)
task_manager = TaskManager(vk.loop)
api = vk.get_api()
async def send_message():
resp = awai... | 2.484375 | 2 |
Ambience/display/EmulatedDisplay.py | Matchstic/automated-ambience | 1 | 38968 | from tkinter import Tk, Canvas
# This is an emulated display with the same API interface as for the Unicorn HAT/pHAT hardware.
# Thus, it relies upon (in part) code from: https://github.com/pimoroni/unicorn-hat/blob/master/library/UnicornHat/unicornhat.py
# Note that only the pHAT is supported, and rotation of the di... | 3.296875 | 3 |
pyowb/open_work_bench.py | fifoforlifo/pyowb | 0 | 38969 | # Python plan -> Open Workbench XML converter.
#
# Python plan defines a Work Breakdown Structure where
# tasks are dictionaries and children are defined in a list.
# Children can contain sequences, to simplify data input;
# sequenced tasks are automatically chained (dependencies).
import sys
import math
from ... | 2.828125 | 3 |
utils/data_utils.py | junsu-kim97/self_improved_retro | 9 | 38970 | import rdkit.Chem as Chem
import pickle
def smi_tokenizer(smi):
"""
Tokenize a SMILES molecule or reaction
"""
import re
pattern = "(\[[^\]]+]|Br?|Cl?|N|O|S|P|F|I|b|c|n|o|s|p|\(|\)|\.|=|#|-|\+|\\\\|\/|:|~|@|\?|>|\*|\$|\%[0-9]{2}|[0-9])"
regex = re.compile(pattern)
tokens = [token for token... | 2.890625 | 3 |
src/scraping/newslists_scrapers/ukrnet.py | mstrechen/news-scraper | 0 | 38971 | from queue import Queue
from datetime import datetime, timedelta
from .INewslistScraper import INewslistScraper
from .. import article
from .. import driver
class Scraper(INewslistScraper):
def __init__(self, limit: int = 100):
INewslistScraper.__init__(self, limit)
self._tag_to_url = {
... | 2.90625 | 3 |
inference.py | andreasr27/bidding_simulator | 0 | 38972 | #!/usr/bin/python
import regret as r
import sys
import os
n=int(sys.argv[1])
fout=open(sys.argv[3],'w')
print >>fout, n
for i in range(0,n):
print >>fout, i, r.mult_valuation(sys.argv[2],i)
| 2.75 | 3 |
TAR/dataset.py | jiyanggao/CTAP | 49 | 38973 |
import numpy as np
from math import sqrt
import os
import random
import pickle
def calculate_IoU(i0,i1):
union=(min(i0[0],i1[0]) , max(i0[1],i1[1]))
inter=(max(i0[0],i1[0]) , min(i0[1],i1[1]))
iou=1.0*(inter[1]-inter[0])/(union[1]-union[0])
return iou
'''
A class that handles the training set
'''
cla... | 2.46875 | 2 |
github_status/util.py | alfredodeza/github-status | 0 | 38974 | from __future__ import print_function
import os
def build_is_triggered():
"""
If a build is being triggered via Github directly (either by a comment, or
automatically) then the ``ghprb`` will probably be involded. When that is
the case, that plugin injects a wealth of environment variables, which can
... | 2.296875 | 2 |
tests/__init__.py | jfardello/dyn53 | 0 | 38975 | <reponame>jfardello/dyn53
import unittest
from . import test_cli, test_client
def suite():
test_suite = unittest.TestSuite()
test_suite.addTests(unittest.makeSuite(test_cli.TestCli))
test_suite.addTests(unittest.makeSuite(test_client.TestClient))
return test_suite
if __name__ == '__main__':
unitt... | 2.09375 | 2 |
OLD.dir/module2.py | romchegue/Python | 0 | 38976 | print('starting to load...')
import sys
name = 42
def func(): pass
class klass: pass
print('done loading.')
| 1.96875 | 2 |
src/real_q_voter/visualization.py | robertjankowski/real-q-voter | 0 | 38977 | <gh_stars>0
import os
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import glob
from src.real_q_voter.logger import get_logger
from itertools import accumulate
from PIL import Image
logger = get_logger('REAL-Q-VOTER-VISUALIZATION-LOGGER')
def plot_degree_distribution(g: nx.Graph, bins=50, ... | 2.8125 | 3 |
tests/entity/test_entity_validate_implementation.py | MacHu-GWU/crawlib-project | 1 | 38978 | <reponame>MacHu-GWU/crawlib-project
# -*- coding: utf-8 -*-
import pytest
from pytest import raises
from crawlib.entity.base import Entity, RelationshipConfig, Relationship
def test_validate_implementation():
# validate abstract method
class Country(Entity):
pass
with raises(NotImplementedError... | 2.53125 | 3 |
subt/dummy_darpa_server.py | m3d/osgar_archive_2020 | 12 | 38979 | #!/usr/bin/env python
"""
Dummy DARPA scoring server
"""
import os
import sys
import csv
import math
import json
import logging
from collections import defaultdict
from http.server import BaseHTTPRequestHandler, HTTPServer
from mimetypes import guess_type
g_logger = logging.getLogger(__name__)
def dist3d(xyz, xy... | 2.78125 | 3 |
app/models/item.py | mtawil/item-catalog | 1 | 38980 | <filename>app/models/item.py<gh_stars>1-10
from orator import mutator
from slugify import slugify
from app import db
from orator.orm import belongs_to
class Item(db.Model):
__table__ = 'items'
__fillable__ = ['title', 'description']
__hidden__ = ['slug', 'category_id', 'user_id']
__timestamps__ = Fals... | 2.4375 | 2 |
tests/test_retry_middleware.py | 0xfede7c8/scrapy-fake-useragent | 0 | 38981 | import pytest
from scrapy import Request
from scrapy.http import Response
from scrapy.spiders import Spider
from scrapy.utils.test import get_crawler
from twisted.internet.error import DNSLookupError
from scrapy_fake_useragent.middleware import RetryUserAgentMiddleware
@pytest.fixture
def retry_middleware_response(... | 2.4375 | 2 |
tests/gateway/test_virtonomica.py | xlam/autovirt | 0 | 38982 | <reponame>xlam/autovirt
from autovirt.gateway.virtonomica.shopgateway import ShopGateway
def data(shop_id: int) -> list[dict]:
return [
{
"shop_unit_id": shop_id,
"sales_volume": 100,
"purchased_amount": 100,
"quantity": 100,
"goods_category_id":... | 2.15625 | 2 |
tests/python/physics_cloth.py | gunslingster/CSC581-assignement1 | 39 | 38983 | <reponame>gunslingster/CSC581-assignement1
# ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 ... | 2.265625 | 2 |
nowcasting_dataset/manager/base.py | JanEbbing/nowcasting_dataset | 0 | 38984 | """Base Manager class."""
import logging
from pathlib import Path
from typing import Optional
import nowcasting_dataset.utils as nd_utils
from nowcasting_dataset import config
from nowcasting_dataset.data_sources import ALL_DATA_SOURCE_NAMES, MAP_DATA_SOURCE_NAME_TO_CLASS
logger = logging.getLogger(__name__)
class... | 2.5 | 2 |
GatewayServis/API/ImageAPI.py | CommName/WildeLifeWatcher | 0 | 38985 | import cherrypy
import requests
import json
from CommunicationLayer import ServiceRegistry
@cherrypy.popargs('imageName')
class ImageAPI(object):
address = "http://127.0.0.1:8761/"
@cherrypy.expose()
def index(self, imageName):
#Get data centaras
servicesArray = ServiceRegistry.getServi... | 2.828125 | 3 |
tests/seahub/invitations/test_views.py | Xandersoft/seahub | 0 | 38986 | <gh_stars>0
from django.utils import timezone
from django.core.urlresolvers import reverse
from seahub.invitations.models import Invitation
from seahub.test_utils import BaseTestCase
class TokenViewTest(BaseTestCase):
def setUp(self):
self.accepter = '<EMAIL>'
self.iv = Invitation.objects.add(inv... | 2.421875 | 2 |
projects/seeker/tasks/search_decision.py | DrMatters/ParlAI | 1 | 38987 | #!/usr/bin/env python3
# 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.
"""
SeeKeR Search Decision Tasks.
"""
from typing import Optional
from parlai.core.opt import Opt
from parlai.core.param... | 1.914063 | 2 |
django101/django101/urls.py | nrgxtra/web_basics | 0 | 38988 |
from django.contrib import admin
from django.urls import path, include
from django101 import cities
from django101.cities.views import index, list_phones, test_index, create_person
urlpatterns = [
path('admin/', admin.site.urls),
path('test/', test_index),
path('create/', create_person, name='c... | 1.734375 | 2 |
helpers.py | gyhor/redmein | 0 | 38989 | from __future__ import print_function
from datetime import date, datetime, timedelta
import os
import tempfile
PERIODS = {
'y': {'name': 'yesterday', 'description': 'Yesterday'},
'lw': {'name': 'lastweek', 'description': 'Last work week'},
'cw': {'name': 'currentweek', 'description': 'Current work week'},
'fl... | 2.65625 | 3 |
GeneratebestpolTextMaxAverageReturn.py | TakuyaHiraoka/Learning-Robust-Options-by-Conditional-Value-at-Risk-Optimization | 9 | 38990 | import os
import re
import statistics
def find_all_key_files_path(directory, keyfile_name):
fn = re.compile(".*"+keyfile_name + ".*")
path=[]
for root, dirs, files in os.walk(directory):
for file in files:
if fn.match(file) is not None:
#print(file)
path.... | 2.734375 | 3 |
examples/2_commit-simple.py | sgibson91/github_api_test | 1 | 38991 | <filename>examples/2_commit-simple.py
import argparse
import base64
import os
import subprocess
import sys
import tempfile
import requests
def parse_args(args):
parser = argparse.ArgumentParser(
description="""
A simplified script to make a commit to the default branch of a repository over
the GitHub API... | 3.5 | 4 |
src/parruc/flexslider/interfaces.py | parruc/parruc.flexslider | 0 | 38992 | # -*- coding: utf-8 -*-
"""Module where all interfaces, events and exceptions live."""
from . import _
from plone.app.vocabularies.catalog import CatalogSource
from plone.namedfile.field import NamedBlobImage
from plone.supermodel import model
from z3c.relationfield.schema import RelationChoice
from zope import schema... | 1.789063 | 2 |
eth_data_collector/block.py | Whitecoin-XWC/Whitecoin-CrosschainMidware | 0 | 38993 | #!/usr/bin/env python
# encoding: utf-8
__author__ = 'hasee'
import json
from datetime import datetime
class BlockInfo(object):
def __init__(self):
# 块hash
self.block_id = ''
# 块高度
self.block_num = 0
# 块大小
self.block_size = 0
# 上个块的块hash
self.pre... | 2.59375 | 3 |
tests/cmdline.py | robertschulze/dirsync | 65 | 38994 | """
Command line options tests
"""
import os
import re
from six import iteritems, StringIO
try:
# Python 3
from unittest.mock import patch
except ImportError:
from mock import patch
from dirsync.options import ArgParser
from dirsync.run import sync
from ._base import DirSyncTestCase
fr... | 2.34375 | 2 |
ocean_provider/routes/decrypt.py | oceanprotocol/provider-service-py | 1 | 38995 | #
# Copyright 2021 Ocean Protocol Foundation
# SPDX-License-Identifier: Apache-2.0
#
import logging
import lzma
from hashlib import sha256
from typing import Optional, Tuple
from eth_typing.encoding import HexStr
from flask import Response, request
from flask_sieve import validate
from ocean_provider.requests_session ... | 2.0625 | 2 |
aries_cloudagent/protocols/connections/v1_0/role.py | ankita-p17/aries-cloudagent-python | 0 | 38996 | <reponame>ankita-p17/aries-cloudagent-python<gh_stars>0
from enum import Enum
class Role(Enum):
AUTHOR = (1,)
ENDORSER = (2,) | 1.75 | 2 |
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... | 1.921875 | 2 |
gui.py | Skezzowski/Rock-Paper-Scissors-Recognizer | 0 | 38998 | <filename>gui.py
import cv2
from PIL import Image, ImageTk
from appJar import gui
from segmentation import segment_hand_with_background
import recognize as rec
import skeleton as sk
def opencv_image_to_appjar_image(image):
b, g, r = cv2.split(image)
im = Image.fromarray(cv2.merge((r, g, b)))
return ImageT... | 2.84375 | 3 |
eval/HighlightBins/hist.py | mkirsche/sapling | 20 | 38999 | import sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
fn = sys.argv[1]
pal = sns.color_palette()
with open(fn) as f:
toPlot = []
names = []
goodness = []
xs = []
ys = []
ps = []
sns.set()
for line in f:
tokens = line.split(' ')
if len(tokens) ==... | 2.375 | 2 |