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 |
|---|---|---|---|---|---|---|
autopilot.py | SpeedrunnerG55/EDAutopilot | 5 | 24100 | import cv2
from dev_autopilot import autopilot
from emulation import get_bindings, clear_input
import threading
import kthread
from pynput import keyboard
from programInfo import showInfo
STATE = 0
def start_action():
stop_action()
kthread.KThread(target = autopilot, name = "EDAutopilot").start()
... | 2.5625 | 3 |
colour/examples/temperature/examples_cct.py | soma2000-lang/colour | 1 | 24101 | """
Showcases correlated colour temperature computations.
"""
import colour
from colour.utilities import message_box
message_box("Correlated Colour Temperature Computations")
cmfs = colour.MSDS_CMFS["CIE 1931 2 Degree Standard Observer"]
illuminant = colour.SDS_ILLUMINANTS["D65"]
xy = colour.XYZ_to_xy(colour.sd_to_X... | 2.828125 | 3 |
qsync.py | Bibliome/misc-utils | 1 | 24102 | #!/usr/bin/env python
import drmaa
import shlex
from optparse import OptionParser
from sys import stderr, stdin, exit
from datetime import datetime
import traceback
def Stop(pool, jt, info):
'''Job failure function that stops synchronization.'''
pool.shall_stop = True
pool.all_done = False
pool.failed... | 2.5 | 2 |
setup.py | Bpowers4/jupyterlab-heroku | 0 | 24103 | <filename>setup.py
import os
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
here = os.path.dirname(os.path.abspath(__file__))
version_ns = {}
with open(os.path.join(here, "jupyterlab_heroku", "_version.py")) as f:
exec(f.read(), {}, version_ns)
setuptools.setup(
name="j... | 1.679688 | 2 |
placement/serializers.py | uditpd3000/SCP-Backend | 5 | 24104 | <filename>placement/serializers.py<gh_stars>1-10
from rest_framework import serializers
from .models import Placement
class PlacementSerializer(serializers.ModelSerializer):
class Meta:
model = Placement
fields = ("key", "placement_name", "company", "role", "description", "deadline")
| 2.109375 | 2 |
tutorials/W0D1_PythonWorkshop1/solutions/W0D1_Tutorial1_Solution_695309c2.py | liuxiaomiao123/NeuroMathAcademy | 26 | 24105 |
# set random number generator
np.random.seed(2020)
# initialize step_end and v
step_end = int(t_max / dt)
v = el
t = 0
with plt.xkcd():
# initialize the figure
plt.figure()
plt.title('$V_m$ with random I(t)')
plt.xlabel('time (s)')
plt.ylabel(r'$V_m$ (V)')
# loop for step_end steps
for step in range(s... | 3.15625 | 3 |
varclr/utils/similarity_search.py | qibinc/VarCLR | 28 | 24106 | import sys
from collections import defaultdict
import torch
from varclr.utils.infer import MockArgs
from varclr.data.preprocessor import CodePreprocessor
if __name__ == "__main__":
ret = torch.load(sys.argv[2])
vars, embs = ret["vars"], ret["embs"]
embs /= embs.norm(dim=1, keepdim=True)
embs = embs.c... | 2.125 | 2 |
plugin/CustomerSupportArchive/chipDiagnostics/tools/flowcorr.py | iontorrent/TS | 125 | 24107 | import os
import numpy as np
from . import imtools, datprops
from .datfile import DatFile
from .chiptype import ChipType
moduleDir = os.path.abspath( os.path.dirname( __file__ ) )
class FlowCorr:
def __init__( self, chiptype, xblock=None, yblock=None, rootdir='.', method='' ):
'''
Initialize a fl... | 2.484375 | 2 |
classifier/cal.py | EnviewFulda/SeagrassExplorer | 0 | 24108 | <gh_stars>0
#!/usr/bin/env python
import numpy as np
def ini():
'''initialization
Args:
Returns:
'''
pass
def accuracy(Yte_predict, Yte):
'''verification of the correct label with the predicted one
Args:
Yte_predict (list): predicted labels (by computer)
Yte (list): ... | 2.90625 | 3 |
recohut/models/dnn.py | sparsh-ai/recohut | 0 | 24109 | # AUTOGENERATED! DO NOT EDIT! File to edit: nbs/models/models.dnn.ipynb (unless otherwise specified).
__all__ = ['Multi_Layer_Perceptron', 'CollabFNet']
# Cell
import torch
import torch.nn as nn
import torch.nn.functional as F
# Cell
class Multi_Layer_Perceptron(nn.Module):
def __init__(self, args, num_users, nu... | 2.3125 | 2 |
src/features/test_outlier_correction.py | KennedyMurphy/elomerchant | 0 | 24110 | <reponame>KennedyMurphy/elomerchant
import unittest
import pandas as pd
import numpy as np
import src.features.outlier_correction as oc
class TestFlagNormalOutliers(unittest.TestCase):
def setUp(self):
self.series = pd.Series(np.random.normal(0, 0.1, 1000))
self.series.loc[500] = -5
self.... | 2.84375 | 3 |
Practica2/ejercicio1.1.py | martapastor/GIW-Practicas | 0 | 24111 | import csv
import operator
if __name__ == "__main__":
# We use try-except statements to properly handle errors, as in case the
# input file does not exist in the directory.
try:
# We open the .csv file loading the filds separated by a ; delimiter:
csv_archivo_locales = open("Locales.csv", e... | 3.96875 | 4 |
sensor_test.py | YoungYoung619/driving-desicion-in-carla | 1 | 24112 | <filename>sensor_test.py
"""
Copyright (c) College of Mechatronics and Control Engineering, Shenzhen University.
All rights reserved.
Description :
Author:<NAME>
"""
import glob, os, sys, time
from threading import Thread
import cv2
from carla_utils.world_ops import *
from carla_utils.sensor_ops import *
try:
... | 2.46875 | 2 |
config.py | aEnigmatic/nwwatch | 0 | 24113 | #!/usr/bin/env python
import os
if not os.path.isfile("/proc/sys/fs/binfmt_misc/WSLInterop"):
# windows
LOGFILE = os.environ['LOCALAPPDATA'] + "\\AGS\\New World\\Game.log"
else:
# wsl
LOGFILE = os.popen('cmd.exe /c "echo %LocalAppData%"').read().strip() + "\\AGS\\New World\\Game.log"
LOGFILE = os.popen("wslpath ... | 2.015625 | 2 |
Python/Arrays/Solution.py | chessmastersan/HackerRank | 2 | 24114 | <reponame>chessmastersan/HackerRank
#author <NAME>
def arrays(arr):
arr.reverse()
l = numpy.array(arr, float)
return l
| 2.1875 | 2 |
test/connect/test_KafkaConnection.py | pip-services3-python/pip-services3-kafka-python | 0 | 24115 | # -*- coding: utf-8 -*-
import os
import time
import pytest
from pip_services3_commons.config import ConfigParams
from pip_services3_kafka.connect.KafkaConnection import KafkaConnection
broker_host = os.environ.get('KAFKA_SERVICE_HOST') or 'localhost'
broker_port = os.environ.get('KAFKA_SERVICE_PORT') or 9092
broke... | 2.15625 | 2 |
src/command_modules/azure-cli-monitor/azure/cli/command_modules/monitor/operations/actions.py | mickeymitic/azure-cli | 1 | 24116 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | 2.453125 | 2 |
tests/test_gremlin_pl.py | joshim5/mogwai | 24 | 24117 | <filename>tests/test_gremlin_pl.py
import itertools
import numpy as np
import torch
import unittest
from mogwai.data_loading import one_hot
from mogwai.models import GremlinPseudolikelihood
class TestGremlinPL(unittest.TestCase):
def setUp(self):
torch.manual_seed(0)
N = 100
L = 20
... | 2.546875 | 3 |
autograd_cupy/cupy_jvps.py | ericmjl/autograd-cupy | 3 | 24118 | <gh_stars>1-10
from . import cupy_wrapper as acp
from .cupy_vjps import (
untake,
balanced_eq,
match_complex,
replace_zero,
dot_adjoint_0,
dot_adjoint_1,
tensordot_adjoint_0,
tensordot_adjoint_1,
nograd_functions,
)
from autograd.extend import (
defjvp,
defjvp_argnum,
def... | 1.84375 | 2 |
testAppium/conf/getStartActivityConfig.py | moulage/appium-android | 0 | 24119 | # !/usr/bin/env python
# -*- coding = utf-8 -*-
# @Author:wanghui
# @Time:
# @File:getStartActivityConfig.py
import configparser
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
class GetStartActivityConfig(object):
def __init__(self):
self.config = configparser.ConfigParser()
s... | 2.65625 | 3 |
Sudoku/norvig_solver.py | ancientHacker/sudoku-generator | 4 | 24120 | <reponame>ancientHacker/sudoku-generator
# MIT License
#
# Copyright (c) 2019 <NAME>
#
# Portions copyright (c) 2017 by <NAME> and <NAME>
# (See https://towardsdatascience.com/peter-norvigs-sudoku-solver-25779bb349ce)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software an... | 2.4375 | 2 |
deserialize/decorators/default.py | KrzysztofSajko/deserialize | 18 | 24121 | """Decorators used for adding functionality to the library."""
from deserialize.exceptions import NoDefaultSpecifiedException
def default(key_name, default_value):
"""A decorator function for mapping default values to key names."""
def store_defaults_map(class_reference):
"""Store the defaults map."... | 3.484375 | 3 |
doc/source/notebooks/regression.py | codelover-without-talent/GPflow | 1 | 24122 | from matplotlib import pyplot as plt
import gpflow
import tensorflow as tf
import os
import numpy as np
import cProfile
def outputGraph(model, dirName, fileName):
model.compile()
if not(os.path.isdir(dirName)):
os.mkdir(dirName)
fullFileName = os.path.join(dirName, fileName)
if os.path.isfile(f... | 2.875 | 3 |
agnosia_tools/pointcloud.py | adurdin/agnosia-blender | 0 | 24123 | <reponame>adurdin/agnosia-blender<gh_stars>0
import bpy
import bmesh
import base64
import math
import mathutils
import random
import struct
import zlib
from array import array
from itertools import islice
from bpy.props import IntProperty, PointerProperty, StringProperty
from bpy.types import Object, Operator, Panel, ... | 2.0625 | 2 |
database/__init__.py | eddycheong/skeleton-flask-sqlalchemy | 0 | 24124 | import configparser
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
config = configparser.ConfigParser()
config.read('alembic.ini')
connection_url = config['alembic']['sqlalchemy.url']
Engine = create_engine(connection_url, connect_args={'check_same_thread': False})
Session = sessionmaker... | 2.1875 | 2 |
wlauto/workloads/octaned8/__init__.py | joesavage/workload-automation | 5 | 24125 | # Copyright 2014-2016 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | 1.875 | 2 |
mrplot/modules/design/variable_design.py | enzofabricio/mrplot | 0 | 24126 | <reponame>enzofabricio/mrplot
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'variable_design.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
... | 1.882813 | 2 |
4-2/TextMining/Class_/week7/LanguageModelWithN_gram.py | define16/Class | 0 | 24127 | '''
n-gram은 이와 같은 확률적 언어 모델의 대표적인 것으로서,
n개 단어의 연쇄를 확률적으로 표현해 두면 실제로
발성된 문장의 기록을 계산할 수 있다.
'''
# Step 1 : Bag of Words
from nltk.corpus import reuters
from collections import Counter, defaultdict
counts = Counter(reuters.words())
total_count = len(reuters.words())
# 공통적으로 가장 많이 나타나는 20개의 단어
print(counts.most_commo... | 3.3125 | 3 |
testing/composite.py | aheadley/pynemap | 6 | 24128 | <reponame>aheadley/pynemap
#!/usr/bin/python
import numpy
class Color(object):
lower_bound = 0
upper_bound = 255
def __init__(self, r, g, b, a):
self.r = r
self.g = g
self.b = b
self.a = a
def __str__(self):
return '(%s, %s, %s, %s)' % (self.r, self.g, self.b, self.a)
def composite_pixels(src, dest):
... | 3.078125 | 3 |
util.py | tudat-team/webservices-dispatch-action | 0 | 24129 | import os
import requests
import urllib3.util.retry
import logging
import subprocess
import re
import pprint
from datetime import datetime, timedelta
import pygit2
from github import Github
from github.GithubException import UnknownObjectException
# Create logger with logging level set to all
LOGGER = logging.getLogg... | 2.796875 | 3 |
ptxt/journal/models.py | mvasilkov/scrapheap | 2 | 24130 | from django.core.validators import MinLengthValidator
from django.contrib.auth.models import User
from django.contrib.auth.validators import UnicodeUsernameValidator
from django.db import models
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.utils.encoding import iri_to_u... | 2.046875 | 2 |
autocomplete/survey.py | converj/reasonSurvey | 0 | 24131 | # Import external modules.
from google.appengine.ext import ndb
import logging
# Import local modules.
from configAutocomplete import const as conf
from constants import Constants
class Survey(ndb.Model):
surveyId = ndb.StringProperty() # Primary key
title = ndb.StringProperty()
introduction = ndb.Str... | 1.9375 | 2 |
app/__init__.py | SLB974/GrandPyBot-dev | 0 | 24132 | <filename>app/__init__.py
from flask import Flask
from app.views import app
| 1.335938 | 1 |
wavenetlike/examples/analyzer_example.py | redwrasse/wavenetlike | 0 | 24133 | <reponame>redwrasse/wavenetlike
from wavenetlike.analyzers import DatasetAnalyzer
from wavenetlike.datasetid import TorchAudioDataSetId
def analyzer_example():
dataset = TorchAudioDataSetId("SPEECHCOMMANDS")
data_analyzer = DatasetAnalyzer(dataset)
data_analyzer.analyze_dataset()
analysis_res = data_a... | 2.140625 | 2 |
python/cuspatial/cuspatial/utils/traj_utils.py | kkraus14/cuspatial | 2 | 24134 | <reponame>kkraus14/cuspatial<filename>python/cuspatial/cuspatial/utils/traj_utils.py
def get_ts_struct(ts):
y=ts&0x3f
ts=ts>>6
m=ts&0xf
ts=ts>>4
d=ts&0x1f
ts=ts>>5
hh=ts&0x1f
ts=ts>>5
mm=ts&0x3f
ts=ts>>6
ss=ts&0x3f
ts=ts>>6
wd=ts&0x8
ts=ts>>3
yd=ts&0x1ff
ts=ts>>9
ms=ts&0x3ff
ts=ts>>10
pid=ts&0x3ff
... | 1.882813 | 2 |
accounts/models.py | asandeep/pseudo-electronics | 0 | 24135 | from django.contrib.auth import models as auth_models
from django.db import models
from django.urls import reverse
class User(auth_models.AbstractUser):
"""Extends default model to add project specific fields."""
birth_date = models.DateField(help_text="Employee Date of birth.")
address = models.TextFiel... | 2.453125 | 2 |
pytorch_trainmodel/pytorch_train.py | hoangcaobao/projectube-nlp | 5 | 24136 | <filename>pytorch_trainmodel/pytorch_train.py<gh_stars>1-10
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from pytorch_model import *
from pytorch_clean import *
from sklearn.metrics import classification_report
from torch.optim import optimizer
from transformers import AutoModel, AutoTokeni... | 2.453125 | 2 |
tests/basics/builtin_sorted.py | 84KaliPleXon3/micropython-esp32 | 1 | 24137 | # test builtin sorted
try:
sorted
set
except:
import sys
print("SKIP")
sys.exit()
print(sorted(set(range(100))))
print(sorted(set(range(100)), key=lambda x: x + 100*(x % 2)))
# need to use keyword argument
try:
sorted([], None)
except TypeError:
print("TypeError")
| 3.1875 | 3 |
addons/mendeley/tests/test_serializer.py | gaybro8777/osf.io | 628 | 24138 | # -*- coding: utf-8 -*-
"""Serializer tests for the Mendeley addon."""
import pytest
from addons.base.tests.serializers import CitationAddonSerializerTestSuiteMixin
from addons.base.tests.utils import MockFolder
from addons.mendeley.tests.factories import MendeleyAccountFactory
from addons.mendeley.serializer import M... | 1.734375 | 2 |
src/project/_tests/base.py | pviojo/boilerplate-flask-api | 0 | 24139 | <filename>src/project/_tests/base.py<gh_stars>0
from app import run_migration
from flask import current_app as app
from flask_testing import TestCase
from project import db
class BaseTestCase(TestCase):
def create_app(self):
app.config.from_object('project.configs.TestingConfig')
return app
d... | 2.0625 | 2 |
models/three_layers_nn.py | erwanlecarpentier/optimistic-regressor | 0 | 24140 | <gh_stars>0
"""
N layers optimistic neural network
"""
import torch
class ThreeLayersNN(torch.nn.Module):
def __init__(self, in_dim, out_dim, h_dim, activation='relu'):
"""
:param in_dim: (int) input dimension
:param out_dim: (int) output dimension
"""
super(ThreeLayersNN... | 2.890625 | 3 |
helper/trap.py | shivaroast/AidenBot | 0 | 24141 | <gh_stars>0
'''
?
(c) 2018 - laymonage
'''
import os
import random
import requests
from .dropson import dbx_dl, get_json
def surprise(safe=False):
'''
?
'''
cat_api = 'http://thecatapi.com/api/images/get'
prev_url = requests.get(cat_api)
prev_url = prev_url.url.replace('http://', 'https://')
... | 2.484375 | 2 |
defaulter.py | tipabu/swift_defaulter | 4 | 24142 | <filename>defaulter.py
# Copyright 2015-2016 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | 1.882813 | 2 |
src/sage/coding/information_set_decoder.py | UCD4IDS/sage | 1,742 | 24143 | # -*- coding: utf-8 -*-
r"""
Information-set decoding for linear codes
Information-set decoding is a probabilistic decoding strategy that
essentially tries to guess `k` correct positions in the received word,
where `k` is the dimension of the code. A codeword agreeing with the
received word on the guessed position can... | 2.75 | 3 |
satelitedl/__init__.py | RyosukeDTomita/satelite-dl | 0 | 24144 | <gh_stars>0
# coding: utf-8
"""
Usage: python3 -m satelitedl --date 19900101
Authore: <NAME>
Date: 2021/11/02
"""
import os
from os.path import abspath, dirname, join
from datetime import datetime
from typing import Union
from .options import parse_args
from .scrapeimg import ScrapingImg
def judge_date_type(date: str... | 2.984375 | 3 |
ostrawling/event/particle.py | JacobRawling/OstrawlingMC | 0 | 24145 | from .four_momentum import FourMomentum
class Particle:
def __init__(self, pdg_id, momentum):
self.pdg_id = pdg_id
self.momentum = momentum
self.momentum.set_basis(
(momentum.px,momentum.py, momentum.pz,
Particle.get_mass(pdg_id)),
'x,y,z,m'
... | 2.6875 | 3 |
src/icolos/core/workflow_steps/gromacs/genion.py | jharrymoore/Icolos | 0 | 24146 | <gh_stars>0
from icolos.utils.enums.step_enums import StepBaseEnum, StepGromacsEnum
from icolos.utils.enums.program_parameters import GromacsEnum
from icolos.core.workflow_steps.gromacs.base import StepGromacsBase
from icolos.utils.execute_external.gromacs import GromacsExecutor
from pydantic import BaseModel
from icol... | 2.0625 | 2 |
mayo/session/train.py | deep-fry/mayo | 110 | 24147 | import math
import tensorflow as tf
from mayo.log import log
from mayo.util import (
Percent, memoize_method, memoize_property, object_from_params)
from mayo.session.base import SessionBase
class Train(SessionBase):
mode = 'train'
def __init__(self, config):
super().__init__(config)
sel... | 2.390625 | 2 |
lazysignup/utils.py | yoccodog/django-lazysignup | 0 | 24148 | def is_lazy_user(user):
""" Return True if the passed user is a lazy user. """
# Anonymous users are not lazy.
if user.is_anonymous:
return False
# Check the user backend. If the lazy signup backend
# authenticated them, then the user is lazy.
backend = getattr(user, 'backend', None)
... | 2.984375 | 3 |
md/obs-tntq_md2md.py | unfoldingWord-dev/tools | 6 | 24149 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# This script copies a directory of OBS-tQ or OBS-tN markdown files to a second location.
# It cleans up the files in these ways:
# Ensures blank lines surrounding markdown headers.
# Fixes links of this form [[:en:...]]
# Removes leading spaces.
# Global variables
sourc... | 2.890625 | 3 |
hw10_conine/thomas.py | gconine88/MATH_6204 | 0 | 24150 | <reponame>gconine88/MATH_6204<filename>hw10_conine/thomas.py
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 20 23:06:49 2017
@author: Grant
An implementation of the Thomas algorithm in Python, using just-in-time
compiling from numba for additional speed
"""
import numpy as np
from numba import njit, f8
... | 3.078125 | 3 |
chemreg/auth/tests/test_views.py | Chemical-Curation/chemcurator | 1 | 24151 | from base64 import b64encode
import pytest
@pytest.mark.django_db
def test_login_view(user, client, settings):
"""Test that the login view can login and logout."""
login_url = f"/{settings.LOGIN_URL.strip('/')}/"
# Django doesn't store the raw password, so we need to set one we know.
password = "<P... | 2.453125 | 2 |
vnpy/app/cta_strategy/strategies/tsmyo_polyfit_strategy.py | TheSuperMyo/vnpy | 0 | 24152 | <reponame>TheSuperMyo/vnpy<gh_stars>0
from datetime import time
from vnpy.app.cta_strategy import (
CtaTemplate,
StopOrder,
TickData,
BarData,
TradeData,
OrderData,
BarGenerator,
ArrayManager
)
from vnpy.app.cta_strategy.base import (
EngineType,
STOPORDER_PREFIX,
StopOrder,
... | 2.109375 | 2 |
run.py | GpNico/KernelMethods_MVA_Kaggle | 0 | 24153 | # run.py
"""
Script for running a specific pipeline from a given yaml config file
"""
import os
import argparse
import yaml
from importlib import import_module
import numpy as np
import time
import pandas as pd
def import_from_path(path_to_module, obj_name = None):
"""
Import an object from a module based o... | 2.9375 | 3 |
alien_invasion.py | shtiyu/biubiubiu | 3 | 24154 | import pygame
from pygame.sprite import Group
from button import Button
from game_stats import GameStats
from settings import Settings
from ship import Ship
from scoreboard import Scoreboard
import game_funcitons as gf
def run_game():
pygame.init()
pygame.mixer.init()
ai_settings = Settings()
screen =... | 3.09375 | 3 |
insights_messaging/downloaders/localfs.py | dpensi/insights-core-messaging | 6 | 24155 | <filename>insights_messaging/downloaders/localfs.py<gh_stars>1-10
import os
from contextlib import contextmanager
class LocalFS:
@contextmanager
def get(self, src):
path = os.path.realpath(os.path.expanduser(src))
yield path
| 1.5625 | 2 |
tests/test_utilities/test_manifest_parser.py | QualiSystems/DevBox | 0 | 24156 | <gh_stars>0
import os
from pyfakefs import fake_filesystem_unittest
from devbox.utilities.manifest_parser import ManifestParser
class TestManifestParser(fake_filesystem_unittest.TestCase):
def setUp(self):
self.setUpPyfakefs()
def test_manifest_parser(self):
# Arrange
self.fs.CreateF... | 2.359375 | 2 |
messages.py | Pyprohly/batch-bot | 0 | 24157 |
from enum import Enum, auto
from string import Template
class MessageRegister:
def __init__(self, dispatch_table=None):
self.dispatch = dict() if dispatch_table is None else dispatch_table
def register(self, ref):
def decorator(func):
self.dispatch[ref] = func
return func
return decorator
def get(sel... | 3.15625 | 3 |
siem_integrations/clx_query_service/clxquery/apps.py | mdemoret-nv/clx | 143 | 24158 | <reponame>mdemoret-nv/clx<gh_stars>100-1000
from django.apps import AppConfig
class ClxQueryConfig(AppConfig):
name = "clxquery"
| 1.242188 | 1 |
tests/test_code_vasp.py | petavazohi/PyChemia | 67 | 24159 | import os
import shutil
import pychemia
import tempfile
import unittest
class MyTestCase(unittest.TestCase):
def test_incar(self):
"""
Test (pychemia.code.vasp) [INCAR parsing and writing] :
"""
print(os.getcwd())
iv = pychemia.code.vasp.read_incar('tests/data/vasp_0... | 2.578125 | 3 |
generateResources.py | shisi1/libVulpes | 0 | 24160 | import os
class Material:
def __init__(self, name, color, outputs):
self.name = name
self.color = color
self.outputs = outputs
materials = [Material("dilithium", 0xddcecb, ("DUST", "GEM")),
Material("iron", 0xafafaf, ("SHEET", "STICK", "DUST", "PLATE")),
Material("gold", 0xffff5d, ("D... | 2.640625 | 3 |
SOGM-3D-2D-Net/slam/dev_slam.py | liuxinren456852/Deep-Collison-Checker | 7 | 24161 | <reponame>liuxinren456852/Deep-Collison-Checker
#
#
# 0=================================0
# | Kernel Point Convolutions |
# 0=================================0
#
#
# ----------------------------------------------------------------------------------------------------------------------
#
# ... | 1.539063 | 2 |
src/3-all_together/parse_vectors.py | bt3gl/Tool-NetClean_Complex_Networks_Data_Cleanser | 5 | 24162 | #!/usr/bin/env python
__author__ = "<NAME>"
__copyright__ = "Copyright 2014, The Cogent Project"
__credits__ = ["<NAME>"]
__license__ = "GPL"
__version__ = "2.0"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
import os
from constants import SUBFOLDERS, FEATURES
def create_input_files(subfolder):
return ... | 2.515625 | 3 |
monitoring/tests/unit/gapic/v3/test_service_monitoring_service_client_v3.py | q-logic/google-cloud-python | 0 | 24163 | # -*- coding: utf-8 -*-
#
# Copyright 2020 Google 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | 2.125 | 2 |
bin/ripple/util/Database.py | tdfischer/rippled | 89 | 24164 | <gh_stars>10-100
from __future__ import absolute_import, division, print_function, unicode_literals
import sqlite3
def fetchall(database, query, kwds):
conn = sqlite3.connect(database)
try:
cursor = conn.execute(query, kwds)
return cursor.fetchall()
finally:
conn.close()
| 2.390625 | 2 |
backend/utils/__init__.py | szkkteam/agrosys | 0 | 24165 | <filename>backend/utils/__init__.py<gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Common Python library imports
import re
import unicodedata
# Pip package imports
from flask_sqlalchemy.model import camel_to_snake_case
from flask import current_app
from itsdangerous import URLSafeSerializer, BadData
from ... | 2.1875 | 2 |
aadi/roi_heads.py | WanXiaopei/aadi | 4 | 24166 | from typing import List
import torch
from detectron2.structures import ImageList, Boxes, Instances, pairwise_iou
from detectron2.modeling.box_regression import Box2BoxTransform
from detectron2.modeling.roi_heads import ROI_HEADS_REGISTRY, StandardROIHeads
from detectron2.modeling.roi_heads.cascade_rcnn import CascadeR... | 2.0625 | 2 |
TF/tensorflow--tutorial/tf.contrib.data.py | STHSF/DeepLearning | 6 | 24167 | # coding=utf-8
# tensorflow tf.contrib.data api test
import tensorflow as tf
# file path
filename = ''
batch_size = 100
aa = (tf.contrib.data.TextLineDataset(filename)
.map((lambda line: tf.decode_csv(line, record_defaults=[['1'], ['1'], ['1']], field_delim='\t')))
.shuffle(buffer_size=1000)
.bat... | 2.34375 | 2 |
哥伦布(STM32F407)/4.拓展实验/3.音频播放/01-物理按键版/main.py | 01studio-lab/MicroPython_Examples | 73 | 24168 | '''
实验名称:音频播放
版本:v1.0
日期:2020.12
作者:01Studio
说明:MP3/WAV音频文件播放。使用物理按键控制
'''
#导入相关模块
import audio,time
from pyb import Switch
from machine import Pin
#构建音频对象
wm=audio.WM8978()
vol = 80 #音量初始化,80
######################
# 播放 USR按键
######################
play_flag = 0
def music_play():
global play_flag
play_fla... | 2.84375 | 3 |
mir_navigation/nodes/min_max_finder.py | xneomac/mir_robot | 3 | 24169 | #!/usr/bin/env python
import rospy
from nav_msgs.msg import Odometry
lin_min = 0.0
lin_max = 0.0
ang_min = 0.0
ang_max = 0.0
def odom_cb(msg):
global lin_min, lin_max, ang_min, ang_max
if lin_min > msg.twist.twist.linear.x:
lin_min = msg.twist.twist.linear.x
if lin_max < msg.twist.twist.linear.x... | 2.46875 | 2 |
classes.py | cheng-zeng35/lyricsync | 0 | 24170 | # this file is to store all custom classes
import tkinter as tk
# class to store tkinter window properties
# font: tk font dictionary {family, size, weight, slant, underline, overstrike}
# font color: string
# nrows: the number of rows of lyric displayed (integer greater than 0)
# width: window width (int greater tha... | 3.0625 | 3 |
test/unit/unittest_utils/utility.py | tsungjui/fusionline | 1 | 24171 | """
Unit test utilities.
"""
import textwrap
def clean_multiline_string( multiline_string, sep='\n' ):
"""
Dedent, split, remove first and last empty lines, rejoin.
"""
multiline_string = textwrap.dedent( multiline_string )
string_list = multiline_string.split( sep )
if not string_list[0]:
... | 3.21875 | 3 |
tests/test_chunk_messages.py | UncleGoogle/galaxy-integrations-python-api | 0 | 24172 | import asyncio
import json
def test_chunked_messages(plugin, read):
request = {
"jsonrpc": "2.0",
"method": "install_game",
"params": {
"game_id": "3"
}
}
message = json.dumps(request).encode() + b"\n"
read.side_effect = [message[:5], message[5:], b""]
a... | 2.3125 | 2 |
test/Crawler/Fs/Image/ImageCrawlerTest.py | paulondc/chilopoda | 2 | 24173 | import os
import unittest
from ....BaseTestCase import BaseTestCase
from kombi.Crawler import Crawler
from kombi.Crawler.Fs.Image import ImageCrawler
from kombi.Crawler.PathHolder import PathHolder
class ImageCrawlerTest(BaseTestCase):
"""Test Image crawler."""
__singleFile = os.path.join(BaseTestCase.dataTes... | 2.640625 | 3 |
test/test_websocket_server.py | markkorput/pyRemoteParams | 0 | 24174 |
#!/usr/bin/env python
import unittest, asyncio, asynctest, websockets, json
from remote_params import HttpServer, Params, Server, Remote, create_sync_params, schema_list
from remote_params.WebsocketServer import WebsocketServer
class MockSocket:
def __init__(self):
self.close_count = 0
self.msgs = []
de... | 2.640625 | 3 |
analyzer/com_classfiction.py | mt-group-1/social-react | 0 | 24175 | import warnings
import pandas as pd
from nltk.sentiment.vader import SentimentIntensityAnalyzer
warnings.filterwarnings("ignore")
def classify_comments(text_file, page_name):
"""
Description:
This function recives a text file and convert it into csv file to enable to label the comments inside that file, ... | 3.5 | 4 |
tests/test_android_here.py | b3b/pythonhere | 2 | 24176 | <reponame>b3b/pythonhere<filename>tests/test_android_here.py<gh_stars>1-10
import pytest
@pytest.mark.parametrize(
"script", (None, "test.py"),
)
def test_restart_app(mocked_android_modules, app_instance, test_py_script, script):
from android_here import restart_app
restart_app(script)
def test_script_p... | 2.15625 | 2 |
Example/facenet_example.py | generalized-intelligence/Tegu | 11 | 24177 | <filename>Example/facenet_example.py<gh_stars>10-100
import sys
sys.path.append('..')
from Network.facenet.API import build_face_manager, detetion_and_recongnize
'''
You have to build face manager before you start detection and recongnize.
'''
face_manager = build_face_manager(r"face/dataset/path")
result = detetion... | 2.390625 | 2 |
Fundamentos/mundo_pc/dispositivo_entrada.py | ijchavez/python | 0 | 24178 | <reponame>ijchavez/python
class DispositivoEntrada:
def __init__(self, marca, tipo_entrada):
self._marca = marca
self.tipo_entrada = tipo_entrada
| 2.84375 | 3 |
src/clarityv2/homepage/urls.py | Clarity-89/clarityv2 | 0 | 24179 | <reponame>Clarity-89/clarityv2<gh_stars>0
from django.urls import path
from .views import HomepageView
urlpatterns = [
path('', HomepageView.as_view(), name='home'),
]
| 1.617188 | 2 |
kolibri/plugins/utils/options.py | MBKayro/kolibri | 545 | 24180 | import copy
import logging
import warnings
from kolibri.plugins.registry import registered_plugins
logger = logging.getLogger(__name__)
def __validate_config_option(
section, name, base_config_spec, plugin_specs, module_path
):
# Raise an error if someone tries to overwrite a base option
# except for th... | 2.125 | 2 |
utils.py | yzhhome/seq2seq_chatbot | 0 | 24181 | from io import open
import time
import math
import torch
import torch.nn.functional as F
from config import MAX_LENGTH
from config import SOS_token
from config import EOS_token
from config import device
class Lang:
def __init__(self, name):
self.name = name
self.word2index = {}
self.word2co... | 2.453125 | 2 |
src/archive-comments-lambda/main.py | knotsrepus/knotsrepus-archiver | 1 | 24182 | <filename>src/archive-comments-lambda/main.py
import asyncio
import json
import os
from datetime import datetime
from src.common import log_utils, pushshift
from src.common.filesystem import S3FileSystem, StubFileSystem
from src.common.lambda_context import local_lambda_invocation
def handler(event, context):
lo... | 2.4375 | 2 |
cpc/criterion/clustering/clustering_quantization.py | anuragkumar95/CPC_audio | 6 | 24183 | import os
import sys
import json
import argparse
import progressbar
from pathlib import Path
from random import shuffle
from time import time
import torch
from cpc.dataset import findAllSeqs
from cpc.feature_loader import buildFeature, FeatureModule, loadModel, buildFeature_batch
from cpc.criterion.clustering import kM... | 2.15625 | 2 |
workflows/pipe-common/pipeline/autoscaling/cloudprovider.py | NShaforostov/cloud-pipeline | 0 | 24184 | <reponame>NShaforostov/cloud-pipeline
# Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.com/)
#
# 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/LI... | 1.726563 | 2 |
setup.py | gokceneraslan/ProDy | 0 | 24185 | import glob
import os
import os.path
import sys
import shutil
import cPickle
from types import StringType, UnicodeType
from distutils.core import setup
from distutils.extension import Extension
from distutils.command.install import install
PY3K = sys.version_info[0] > 2
with open('README.rst') as inp:
long_descr... | 1.90625 | 2 |
rabbitai/migrations/versions/d7c1a0d6f2da_remove_limit_used_from_query_model.py | psbsgic/rabbitai | 0 | 24186 | <gh_stars>0
"""Remove limit used from query model
Revision ID: d7c1a0d6f2da
Revises: afc69274c25a
Create Date: 2019-06-04 10:12:36.675369
"""
# revision identifiers, used by Alembic.
revision = "d7c1a0d6f2da"
down_revision = "afc69274c25a"
import sqlalchemy as sa
from alembic import op
def upgrade():
with op.... | 0.882813 | 1 |
realworld_benchmark/nets/eig_layer.py | DomInvivo/pna | 0 | 24187 | <reponame>DomInvivo/pna
EPS = 1e-5
import threading
import torch
import torch.nn as nn
import torch.nn.functional as F
from .aggregators import AGGREGATORS
from .layers import MLP, FCLayer
from .scalers import SCALERS
class EIGLayerComplex(nn.Module):
def __init__(self, in_dim, out_dim, dropout, graph_norm, bat... | 1.835938 | 2 |
NLPEngine/utils/nlp_config.py | hmi-digital/bot_platform | 0 | 24188 | <gh_stars>0
# -*- coding: utf-8 -*-
import os
import json
import hashlib
from warnings import simplefilter
from utils import log_util
# ignore all warnings
simplefilter(action='ignore')
##Global parameters
scriptDir = os.path.dirname(__file__)
dataPath = os.path.join(scriptDir, '..', 'training_data', 'intents')
pr... | 2.171875 | 2 |
flow/core/gcp_credentials.py | hwknsj/synergy_flow | 0 | 24189 | import io
import json
from google.auth import compute_engine
from google.oauth2 import service_account
def gcp_credentials(service_account_file):
if service_account_file:
with io.open(service_account_file, 'r', encoding='utf-8') as json_fi:
credentials_info = json.load(json_fi)
creden... | 2.984375 | 3 |
main.py | tremor6916/sakugabooru-bot | 1 | 24190 | import requests
import tweepy
import random
import time
import os
import bs4
from bs4 import BeautifulSoup
from pybooru import Moebooru
siteurl='https://www.sakugabooru.com/post/show/'
header = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/53... | 2.96875 | 3 |
demos/template/src/urls.py | akornatskyy/wheezy.web | 17 | 24191 | """
"""
from membership.web.urls import membership_urls
from public.web.urls import error_urls, public_urls, static_urls
from public.web.views import home
from wheezy.routing import url
locale_pattern = "{locale:(en|ru)}/"
locale_defaults = {"locale": "en"}
locale_urls = public_urls + membership_urls
locale_urls.app... | 2.21875 | 2 |
olmm.py | wesselb/olmm | 2 | 24192 | from stheno import (
B, # Linear algebra backend
Graph, # Graph that keep track of the graphical model
GP, # Gaussian process
EQ, # Squared-exponential kernel
Matern12, # Matern-1/2 kernel
Matern52, # Matern-5/2 kernel
Delta, # Noise kernel
Normal, # Gaussian distribution
Dia... | 2.59375 | 3 |
tests/molecular/molecules/utilities/building_block.py | andrewtarzia/stk | 21 | 24193 | <gh_stars>10-100
import itertools as it
from tests.utilities import (
is_equivalent_atom,
is_equivalent_molecule,
)
def are_equivalent_functional_groups(
functional_groups1,
functional_groups2,
):
functional_groups = it.zip_longest(
functional_groups1,
functional_groups2,
)
... | 2.5 | 2 |
pydeps/__main__.py | miketheman/pydeps | 981 | 24194 | <filename>pydeps/__main__.py<gh_stars>100-1000
from .pydeps import pydeps
pydeps()
| 0.945313 | 1 |
fileInfo.py | Jiaoma/fileStr | 0 | 24195 | from os import listdir
from os.path import join
import os, errno
def getImageNum(rootDir):
return len(listdir(join(rootDir)))
def safeMkdir(path:str):
try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise | 2.734375 | 3 |
text-classify/test.py | ubear/MachineLearn | 0 | 24196 | #coding:utf-8
import re
import math
from docclass import Classifier
def test_infc_func():
c = Classifier(getfeatures=None)
c.infc("python", "good")
c.infc("python", "good")
c.infc("the", "bad")
c.infc("the", "good")
print c.fc
if __name__ == "__main__":
test_infc_func()
| 2.59375 | 3 |
libs/hermes/hermes.cloudbreak/hermes/cloudbreak/kubernetes/base.py | KAGRA-TW-ML/gw-iaas | 2 | 24197 | <reponame>KAGRA-TW-ML/gw-iaas
import abc
import time
from dataclasses import dataclass
from functools import partial
from typing import TYPE_CHECKING
import kubernetes
from kubernetes.utils.create_from_yaml import FailToCreateError
from urllib3.exceptions import MaxRetryError
from hermes.cloudbreak.utils import snake... | 2.0625 | 2 |
src/chapter2/exercise7.py | group6BCS1/BCS-2021 | 0 | 24198 | c = float(input("Enter Amount Between 0-99 :"))
print(c // 20, "Twenties")
c = c % 20
print(c // 10, "Tens")
c = c % 10
print(c // 5, "Fives")
c = c % 5
print(c // 1, "Ones")
c = c % 1
print(c // 0.25, "Quarters")
c = c % 0.25
print(c // 0.1, "Dimes")
c = c % 0.1
print(c // 0.05, "Nickles")
c = c % 0.05
print(c // 0.01... | 3.671875 | 4 |
gmn/src/d1_gmn/tests/test_content_disposition.py | DataONEorg/d1_python | 15 | 24199 | <gh_stars>10-100
#!/usr/bin/env python
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# Licensed under the Apache Licens... | 2.03125 | 2 |