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 |
|---|---|---|---|---|---|---|
join.py | florisdenhengst/pydial-benchmark-stopos | 0 | 44100 | import argparse
parser = argparse.ArgumentParser(description="Generate path to config file given input")
parser.add_argument('vars', nargs='+')
args = parser.parse_args()
# The last item of vars contains the random seed
result = '-'.join(args.vars[:-1])
print(result)
| 3.3125 | 3 |
colors.py | kevinyjiang/movie-colors | 0 | 44101 | <filename>colors.py
import numpy as np
import cv2
import sys
import random
import argparse
import os
"""
TODO:
Progress bar
Option to name output
"""
# Average of every pixel in a frame
def average_regular(img):
channels = [0,0,0]
for x in range(0, img.shape[0]):
for y in range(0, img.shape[1]):
for i in rang... | 3.3125 | 3 |
bug-dist-not-found/setup.py | maphew/scraps | 0 | 44102 | from setuptools import setup
setup(name='my_project',
version='0.1.0',
packages=['my_project'],
entry_points={
'console_scripts': [
'my_project = my_project.__main__:main'
]
},
)
| 1.117188 | 1 |
exante/endpoints/payloads/orders.py | denisvolokh/exante-python-api | 0 | 44103 | <filename>exante/endpoints/payloads/orders.py
from exante.endpoints.payloads.basepayload import BasePayload
from exante.definitions.orders import OrderSide, OrderType, OrderDuration
class MarketOrder(BasePayload):
def __init__(
self, account: str, instrument: str, side: str, quantity: str, duration: str
... | 2.34375 | 2 |
simple_xntwist_ui/__init__.py | xn-twist/demo-ui | 0 | 44104 | <gh_stars>0
from . import simple_xntwist_ui | 1.007813 | 1 |
evaluation/eval_1v1.py | KaenChan/ProbFace | 28 | 44105 | import os
import sys
import imp
import argparse
import time
import math
import numpy as np
from utils import utils
from utils.imageprocessing import preprocess
from utils.dataset import Dataset
from network import Network
from evaluation.lfw import LFWTest
def main(args):
paths = [
r'F:\data\face-recog... | 2.3125 | 2 |
mysite/personal/urls.py | salimab/library1 | 0 | 44106 | from django.conf.urls import url
from personal.models import Book
from . import views
from django.contrib.auth.views import login
from django.views.generic import ListView, DetailView
urlpatterns = [
url(r'^$', views.index , name='index'),
url(r'^login/$', login, {'template_name': 'personal/login.html'}),
... | 1.96875 | 2 |
carbon/lib/carbon/log.py | ehazlett/graphite | 1 | 44107 | <reponame>ehazlett/graphite
import time
from sys import stdout, stderr
from zope.interface import implements
from twisted.python.log import startLoggingWithObserver, textFromEventDict, msg, err, ILogObserver
from twisted.python.logfile import DailyLogFile
class CarbonLogObserver(object):
implements(ILogObserver)
... | 2.203125 | 2 |
view/alertview.py | firebird631/siis | 0 | 44108 | <reponame>firebird631/siis<filename>view/alertview.py
# @date 2019-06-28
# @author <NAME>, All rights reserved without prejudices.
# @license Copyright (c) 2019 Dream Overflow
# Alerts view.
from __future__ import annotations
from typing import List
import copy
import threading
import hashlib
from datetime import d... | 2.0625 | 2 |
mindware/utils/constant.py | aman-gupta-1995/Machine-Learning-Mindware | 27 | 44109 | """Constants used in Integer.
"""
MAX_INT = 2 ** 31 - 1
FAILED = -2147483646.0
| 1.226563 | 1 |
riemann/vc_elasticity_2D_constants.py | ranocha/riemann | 27 | 44110 | <reponame>ranocha/riemann
num_waves = 4
num_eqn = 5
num_aux = 5
# Conserved quantities
sigma_11 = 0
sigma_22 = 1
sigma_12 = 2
u = 3
v = 4
# Auxiliary variables
density = 0
lamda = 1
mu = 2
cp = 3
cs = 4
| 1.351563 | 1 |
__main__.py | luluci/utilCParse | 0 | 44111 | <reponame>luluci/utilCParse<filename>__main__.py
import pathlib
import utilCParse
if True:
# file
# path = pathlib.Path("./test/test_c_src/test1.c")
path = pathlib.Path("./test/test_c_src")
analyzer = utilCParse.analyzer.analyzer()
analyzer.analyze_dir(path)
| 1.914063 | 2 |
Agent.py | leonjovanovic/drl-ppo-bipedal-walker | 1 | 44112 | import AgentControl
import Config
import Memory
import numpy as np
import itertools
class Agent:
# Role of Agent class is to coordinate between AgentControll where we do all calculations
# and Memory where we store all of the data
def __init__(self, state_size, action_size, batch_size):
s... | 3.078125 | 3 |
supports/pyload/src/pyload/plugins/accounts/EuroshareEu.py | LuckyNicky/pycrawler | 1 | 44113 | # -*- coding: utf-8 -*-
import json
import re
import time
from ..base.account import BaseAccount
class EuroshareEu(BaseAccount):
__name__ = "EuroshareEu"
__type__ = "account"
__version__ = "0.12"
__status__ = "testing"
__pyload_version__ = "0.5"
__description__ = """Euroshare.eu account pl... | 2.453125 | 2 |
2021/d13.py | shubham-goel/advent_of_code | 1 | 44114 | <reponame>shubham-goel/advent_of_code<gh_stars>1-10
import numpy as np
from functools import reduce
from collections import defaultdict
from pprint import pprint
file = '2021/inputs/d13.txt'
# Read the file
with open(file) as f:
lines = [line.strip() for line in f if line.strip()]
dots = np.array([list(map(int, ... | 2.859375 | 3 |
tests/test_get_updates.py | concretesolutions/mysql-anonymous | 0 | 44115 | <filename>tests/test_get_updates.py
from anonymize.anonymize import AnonymizeUpdate, AnonymizeScheme
def test_should_get_the_update_list():
data = AnonymizeUpdate(AnonymizeScheme("default", {
"tables": {
"user": {
"nullify": ["phone", ],
"random_email": ["email"... | 2.125 | 2 |
day13/test_day13.py | hmcc/advent-of-code-2021 | 0 | 44116 | <reponame>hmcc/advent-of-code-2021
import pytest
from day13 import day13
@pytest.mark.parametrize('line, point', [
('6,10',(6, 10)),
('0,14',(0, 14)),
])
def test_parse_plot(line, point):
assert day13.parse_plot(line) == point
@pytest.mark.parametrize('line, fold', [
('fold along y=7', ('y', 7)),
... | 2.734375 | 3 |
CrossLanguageOPMining-bert-3languageTrain-PGNAdapter/data/SRL.py | zenRRan/Chinese-ORL-with-Corpus-Translation | 1 | 44117 | <gh_stars>1-10
# encoding:utf-8
class Word:
def __init__(self, id, form, label):
self.id = id
self.org_form = form
self.form = form.lower()
self.label = label
def __str__(self):
values = [str(self.id), self.org_form, self.label]
return '\t'.join(values)
class ... | 3.015625 | 3 |
machine-learning/shape-detection/live_shape_detector.py | gizzmo25/pythoncode-tutorials | 0 | 44118 | <reponame>gizzmo25/pythoncode-tutorials<filename>machine-learning/shape-detection/live_shape_detector.py
import numpy as np
import matplotlib.pyplot as plt
import cv2
cap = cv2.VideoCapture(0)
while True:
_, image = cap.read()
# convert to grayscale
grayscale = cv2.cvtColor(image, cv2.COLOR_BGR2G... | 3.4375 | 3 |
TWLight/applications/factories.py | jajodiaraghav/TWLight | 1 | 44119 | # -*- coding: utf-8 -*-
import factory
from TWLight.resources.factories import PartnerFactory
from TWLight.users.factories import EditorFactory
from TWLight.applications.models import Application
class ApplicationFactory(factory.django.DjangoModelFactory):
class Meta:
model = Application
strat... | 1.601563 | 2 |
tests/unit/state_machines/ansible/machine.py | tessia-project/tessia | 5 | 44120 | <reponame>tessia-project/tessia<filename>tests/unit/state_machines/ansible/machine.py
# Copyright 2018 IBM Corp.
#
# 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/l... | 1.929688 | 2 |
adv/marty.py | mattkw/dl | 0 | 44121 | import adv_test
import adv
def module():
return Marty
class Marty(adv.Adv):
a1 = ('sp',0.05)
#comment = 'reach 100 resist with Saintly Delivery'
#conf = {}
#import slot
#conf['slots.a'] = slot.a.Saintly_Delivery()+slot.a.RR()
if __name__ == '__main__':
conf = {}
conf['acl'] = """
... | 2.328125 | 2 |
python_project/DeleteElasticsearchIndices.py | wangyuqianily/bbotte.github.io | 2 | 44122 | #!/usr/bin/env python
#ecoding=utf8
#自动删除elasticsearch数据库保留较久的数据
#普通数据保留时间为daysToKeep,access日志保留时间为access_date
#pip install elasticsearch 安装elasticsearch包
import datetime
import re
from elasticsearch import Elasticsearch
daysToKeep = 30
es = Elasticsearch('localhost:9200',timeout=60.0)
keep_time = (datetime.datetime... | 2.625 | 3 |
cowait/cli/commands/cluster.py | backtick-se/cowa | 51 | 44123 | <reponame>backtick-se/cowa<filename>cowait/cli/commands/cluster.py
from ..config import Config
ADDABLE_PROVIDERS = {
'api': ['url', 'token'],
'kubernetes': ['context'],
}
def cluster_get(config: Config, name: str) -> None:
if name not in config.clusters:
print('Unknown cluster', name)
re... | 2.484375 | 2 |
nhefner_pygame_menus/menus.py | noahhefner/nhefner_pygame_menus | 0 | 44124 | """
<NAME>
Pygame Menu System
Last Edit: 1 January 2021
"""
# Imports
import pygame
import string
# Initialize pygame
pygame.init()
# Settings
menu_manager_settings = {
"element_colorkey" : [0, 0, 0],
"menu_background_color" : [0, 0, 0],
"menu_fps" : 60
}
class Action:
"""
Holds function and a... | 3.765625 | 4 |
vbdiar/kaldi/python_mfcc_features_extraction.py | Honghe/VBDiarization | 0 | 44125 | # -*- coding: utf-8 -*-
import numpy as np
import speechpy
from scipy.io import wavfile
from python_speech_features import mfcc
class PythonMFCCFeatureExtraction():
def __init__(self):
pass
def audio2features(self, input_path):
(rate, sig) = wavfile.read(input_path)
mfcc_feat = mfcc(... | 2.640625 | 3 |
blatann/nrf/nrf_types/smp.py | eriknyquist/blatann | 1 | 44126 | from enum import Enum
import logging
from blatann.nrf.nrf_dll_load import driver
import blatann.nrf.nrf_driver_types as util
from blatann.nrf.nrf_types.enums import *
logger = logging.getLogger(__name__)
class BLEGapSecMode(object):
def __init__(self, sec_mode, level):
self.sm = sec_mode
... | 2.125 | 2 |
dcm_anon/__main__.py | LilMit/pl-dcm_anon | 0 | 44127 | <filename>dcm_anon/__main__.py
from dcm_anon.dcm_anon import dcm_anon
def main():
chris_app = dcm_anon()
chris_app.launch()
if __name__ == "__main__":
main()
| 1.539063 | 2 |
app/resources/users/resources/__init__.py | admiralobvious/falcon-boilerplate | 34 | 44128 | <reponame>admiralobvious/falcon-boilerplate
import falcon
from app.data.db import setup
from .user import User, UserSchema
from .users import Users
def get_routes(app: falcon.App):
db = setup()
app.add_route("/users", Users(db))
app.add_route("/users/{user_id}", User(db))
app.add_route("/user.schem... | 2.03125 | 2 |
Menu.py | Irish-Gambit73/Python-Project | 0 | 44129 | from direct.showbase.ShowBase import ShowBase
from panda3d.core import CardMaker, NodePath, loadPrcFileData
from panda3d.core import *
import sys
configVars = """
win-size 1920 1080
show-frame-rate-meter 0
"""
loadPrcFileData("", configVars)
class mymenu(ShowBase):
def __init__(self):
Sho... | 2.15625 | 2 |
src/tmdb/api_testing.py | kierrez/movie-website | 1 | 44130 | import django
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
django.setup()
from django.contrib.auth import get_user_model
from importer.utils import import_ratings_from_csv
from titles.models import Title
from tmdb.api import TmdbWrapper, TitleDetailsGetter
User = get_user_model()
d... | 2.140625 | 2 |
cuhk01/constants.py | hashknot/person-reid | 0 | 44131 | BATCH_SIZE = 100
# Constants describing the training process.
MOVING_AVERAGE_DECAY = 0.9999 # The decay to use for the moving average.
NUM_EPOCHS_PER_DECAY = 50 # Epochs after which learning rate decays.
LEARNING_RATE_DECAY_FACTOR = 0.1 # Learning rate decay factor.
INITIAL_LEARNING_RATE = 0.001 # Ini... | 2.515625 | 3 |
music.py | konsou/autsball | 0 | 44132 | # -*- coding: utf-8 -*-
import pygame
import random
import tinytag
import groups
from constants import *
"""
Pitää sisällään seuraavaa:
class MusicPlayer(pygame.sprite.Sprite): taustamusiikin soittajaclass, osaa näyttää infoblurbin biisistä
class MusicFile(object): lukee tiedoston tagit ja tallettaa tiedon siitä, mi... | 2.765625 | 3 |
tensorflow/python/data/experimental/ops/take_while_ops.py | ashutom/tensorflow-upstream | 8 | 44133 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 2.609375 | 3 |
tests/e2e/dags/__init__.py | meaningfy-ws/ted-xml-2-rdf | 0 | 44134 | from datetime import timezone
from airflow.models import DagRun, TaskInstance
from airflow.utils.types import DagRunType
NORMALISE_NOTICE_METADATA_TASK_ID = "normalise_notice_metadata"
CHECK_ELIGIBILITY_FOR_TRANSFORMATION_TASK_ID = "check_eligibility_for_transformation"
PREPROCESS_XML_MANIFESTATION_TASK_ID = "preproc... | 1.859375 | 2 |
ustack_etl/mongo.py | ustudio/ustack-etl | 1 | 44135 | <reponame>ustudio/ustack-etl
import logging
def etl_collection(mongo_db, collection_name, fn):
documents = mongo_db[collection_name].find()
count = mongo_db[collection_name].count_documents({})
logging.info(
f"Processing {count} documents in collection "
f"'{collection_name}'")
for d... | 2.59375 | 3 |
tiler.py | arancaytar/mcmap-web | 5 | 44136 | import os
import re
import math
import subprocess
import argparse
from wand.image import Image
class Tiler:
'''Scale a tile map up and down in powers of 2.'''
def __init__(self, filename='{x},{z}.png', path='.', zoomOut=4, zoomIn=1, verbose=False):
self.path = path
if not os.path.isdir(self.pat... | 2.796875 | 3 |
axonius_api_client/api/system/users.py | rwils83/axonius_api_client | 0 | 44137 | # -*- coding: utf-8 -*-
"""API model for working with system configuration."""
from typing import List, Optional
from ...exceptions import ApiError, NotFoundError
from ..mixins import ChildMixins
from ..parsers import parse_unchanged
class Users(ChildMixins): # pragma: no cover
"""User Role controls."""
de... | 2.453125 | 2 |
comparisontool/tests/test_views.py | mikiec84/django-college-costs-comparison | 0 | 44138 | <gh_stars>0
import json
import uuid
from django.core import mail
from django.core.urlresolvers import reverse
from django.test import RequestFactory, TestCase
from comparisontool.models import BAHRate, School, Worksheet
from comparisontool.views import (
DataStorageView, WorksheetJsonValidationError, bah_lookup_a... | 2.0625 | 2 |
Employee_Retention_Prediction-main/apps/tuning/model_tuner.py | jrderek/Deployment- | 0 | 44139 | <filename>Employee_Retention_Prediction-main/apps/tuning/model_tuner.py
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier
from xgboost import XGBClassifier
from sklearn.metrics import roc_auc_score,accuracy_score
from apps.core.logger import Logger
from sklearn... | 2.859375 | 3 |
CSCA48 - Introduction to CS 2/ex5.py | zaind6/University-CS-Exercises | 1 | 44140 | <gh_stars>1-10
def rsum(any_list):
'''(list of int) -> int
REQ: Length of the list must be greater than 0
This function will add up all the integers in the given list of integers
>>>rsum([9,1000,-1000,57,78,0])
144
>>>rsum([1])
1
'''
# Base case for one element
if len(any_list) =... | 3.703125 | 4 |
src/data/dataloader.py | TencentYoutuResearch/SelfSupervisedLearning-DSM | 27 | 44141 | <filename>src/data/dataloader.py<gh_stars>10-100
import torch
def pt_data_loader_init(args, data_length, image_tmpl, train_transforms, test_transforms, eval_transforms):
if args.pt_dataset in ['ucf101', 'hmdb51', 'diving48', 'sth_v1']:
from data.dataset import DataSet as DataSet
elif args.pt_dataset =... | 2.296875 | 2 |
plot_results.py | freedmanlab/Context-Dependent-Gating | 0 | 44142 | <reponame>freedmanlab/Context-Dependent-Gating<filename>plot_results.py
import numpy as np
import matplotlib.pyplot as plt
import pickle
import os
import matplotlib
from itertools import product
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_i... | 2.359375 | 2 |
code/lib/warn/constants/api_constants.py | JaspervanRooijen/covid-apps-observer | 2 | 44143 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This file is part of Androwarn.
#
# Copyright (C) 2012, 2019, <NAME> <<EMAIL>>
# All rights reserved.
#
# Androwarn is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software ... | 1.546875 | 2 |
pudzu/sandbox/tinytim.py | Udzu/pudzu | 119 | 44144 | from collections import namedtuple
from turtle import fd, heading, lt, pd, position, pu, rt, setheading, setposition # pylint: disable=no-name-in-module
from pudzu.utils import weighted_choice
class LSystem:
Rule = namedtuple("Rule", "predecessor successor weight", defaults=(1.0,))
def __init__(self, axio... | 3.140625 | 3 |
modules/nyc_taxi/cleanse.py | likebupt/aml-modules | 0 | 44145 | <reponame>likebupt/aml-modules<gh_stars>0
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license.
import sys
import os
import subprocess
import pandas as pd
from azureml.pipeline.wrapper import dsl
from azureml.pipeline.wrapper.dsl.module import ModuleExecutor, InputDirectory, OutputDirectory... | 2.515625 | 3 |
1301-1400/1363-Largest Multiple of Three/1363-Largest Multiple of Three.py | jiadaizhao/LeetCode | 49 | 44146 | <gh_stars>10-100
import collections
class Solution:
def largestMultipleOfThree(self, digits: List[int]) -> str:
count = collections.Counter(digits)
remain1Count = count[1] + count[4] + count[7]
remain2Count = count[2] + count[5] + count[8]
total = sum(digits)
if total... | 3.171875 | 3 |
Megatron-LM-v1.1.5-3D_parallelism/megatron/configs/realm.py | Ezra-H/DeepSpeedExamples | 0 | 44147 | <filename>Megatron-LM-v1.1.5-3D_parallelism/megatron/configs/realm.py
# network size
ict_head_size = None
# checkpointing
ict_load = None
bert_load = None
# data
titles_data_path = None
query_in_block_prob = 0.1
use_one_sent_docs = False
# training
report_topk_accuracies = []
# faiss index
faiss_use_gpu = False
bl... | 1.078125 | 1 |
nao_dcm_apps/nao_dcm_rqt_dashboard/src/nao_dcm_rqt_dashboard/stiffness.py | HeeroYui/nao_dcm | 0 | 44148 | # Copyright (c) 2014, <NAME>
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following dis... | 1.242188 | 1 |
testdemo/pytest_project/run.py | gottaegbert/penter | 13 | 44149 | <filename>testdemo/pytest_project/run.py<gh_stars>10-100
import pytest
if __name__ == '__main__':
pytest.main(["-s", "../pytest_project/"])
# 执行顺序先当前 在 子目录 | 0.886719 | 1 |
layers/hsm.py | ryanai3/TooMuchData | 0 | 44150 | import torch
from torch import nn
import torch.nn.functional as nf
from torch.nn import init
from torch.autograd import Variable
import numpy as np
from chainer.links.loss.hierarchical_softmax import TreeParser
#class HSM(nn.Module):
# def __init__(self, input_size, vocab_size):
class HSBad(nn.Module):
def __ini... | 2.328125 | 2 |
trypython/advanced/generator/yield01.py | devlights/try-python | 4 | 44151 | # coding: utf-8
"""yieldについてのサンプルです。
元ネタは、stackoverflowの以下のページ。
https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python/231855#231855
回答がとてもわかり易いので、自分用のメモとしても残しておく。
"""
import time
from datetime import datetime
from trypython.common.commoncls import SampleBase
from trypython.common.common... | 2.890625 | 3 |
rqalpha/model/benchmark_portfolio.py | HaidongHe/rqalpha | 1 | 44152 | # -*- coding: utf-8 -*-
# 版权所有 2019 深圳米筐科技有限公司(下称“米筐科技”)
#
# 除非遵守当前许可,否则不得使用本软件。
#
# * 非商业用途(非商业用途指个人出于非商业目的使用本软件,或者高校、研究所等非营利机构出于教育、科研等目的使用本软件):
# 遵守 Apache License 2.0(下称“Apache 2.0 许可”),您可以在以下位置获得 Apache 2.0 许可的副本:http://www.apache.org/licenses/LICENSE-2.0。
# 除非法律有要求或以书面形式达成协议,否则本软件分发时需保持当前许可“原样”... | 1.976563 | 2 |
diagnostics/GHIplot.py | amcmahon01/SolarForecasting | 2 | 44153 | # plot daily box-whisker graphs of GHI data
# Use standard config_handler with .yaml config to parse arguments
from config_handler import handle_config
from datetime import datetime,timezone,date
import pandas as pd
import matplotlib.pyplot as plt
import pysolar.solar as ps
import sys
import time
# note: pathlibs Path ... | 2.578125 | 3 |
back-end/curso-em-video/python3/Mundo I/Desafios/15F - (Aluguel de Carros).py | gustavocamalionti/cursos-e-linguagens | 0 | 44154 | #Desafio 015: escreva um programa que pergunte a quantidade de km percorridos por um carro alugado e a quantidade de dias pelos quais ele foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$60 por dia e R$0.15 por km rodado.
from math import ceil
n1 = float(input('Quantos dias você ficou com o carro? '))... | 3.65625 | 4 |
starling_sim/basemodel/output/kpi_output.py | tellae/starling | 19 | 44155 | from starling_sim.basemodel.output.kpis import KPI
import logging
import pandas as pd
class KpiOutput:
def __init__(self, population_names, kpi_list, kpi_name=None):
# name of the kpi, will compose the kpi filename : <kpi_name>.csv
if kpi_name is None:
if isinstance(population_names... | 2.859375 | 3 |
examples/pytorch/diffpool/model/tensorized_layers/assignment.py | ketyi/dgl | 9,516 | 44156 | import torch
from torch import nn as nn
from torch.nn import functional as F
from torch.autograd import Variable
from model.tensorized_layers.graphsage import BatchedGraphSAGE
class DiffPoolAssignment(nn.Module):
def __init__(self, nfeat, nnext):
super().__init__()
self.assign_mat = BatchedGraph... | 2.609375 | 3 |
openpype/hosts/webpublisher/plugins/publish/integrate_context_to_log.py | yosuperdope/OpenPype | 44 | 44157 | import os
import pyblish.api
from openpype.lib import OpenPypeMongoConnection
class IntegrateContextToLog(pyblish.api.ContextPlugin):
""" Adds context information to log document for displaying in front end"""
label = "Integrate Context to Log"
order = pyblish.api.IntegratorOrder - 0.1
hosts = ["web... | 2.34375 | 2 |
demo/myKNN-2.py | wei1224hf/photo-MES | 2 | 44158 | <gh_stars>1-10
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
import glob
from imutils import contours
import imutils
def KNN():
files = glob.glob("digits/*.jpg")
train = []
train_labels = []
for iii,f in enumerate(files):
img = cv.imread(f)
grayImage = cv.cvtC... | 2.75 | 3 |
gameball/exceptions/gameball_exception.py | aaelfiky/gameball-python | 1 | 44159 | from __future__ import absolute_import, division, print_function
class GameballException(Exception):
def __init__(
self,
message=None,
http_body=None,
json_body=None,
headers=None,
code=None,
):
super(GameballException, self).__init__(message)
... | 2.84375 | 3 |
priority.py | donkirkby/domiculture | 4 | 44160 | from heapq import heappush, heappop
class PriorityQueue:
def __init__(self):
self.item_heap = [] # [ [priority, item] ]
self.dummy = '<dummy entry>'
self.item_dict = {} # { item: [priority, item] }
def __bool__(self):
return bool(self.item_dict)
def add(self, item, prio... | 3.484375 | 3 |
speed_friending_matcher/exporter/cliqueexporter.py | machinekoder/speed-friending-matcher | 4 | 44161 | <reponame>machinekoder/speed-friending-matcher
# -*- coding: utf-8 -*-
from .exporter import Exporter
from .export_tools import create_person_simple_string
HEADER = '''\
Following cliques have been found:
'''
GROUP_TEMPLATE = '''\
TEAM {number}: {count} friends
{friends}
'''
class CliqueExporter(Exporter):
de... | 2.53125 | 3 |
plugins/avro-java/register.py | arron-green/pants-avro | 0 | 44162 | <gh_stars>0
from pants.build_graph.build_file_aliases import BuildFileAliases
from .targets import AvroJava
from .gen import AvroJavaGen
from pants.goal.task_registrar import TaskRegistrar as task
def build_file_aliases():
return BuildFileAliases(targets={'avro_java': AvroJava})
def register_goals():
task(n... | 1.914063 | 2 |
comments/models.py | chench53/jquery-comments-server | 2 | 44163 | from django.db import models
from django.utils import timezone
# Create your models here.
class Creator(models.Model):
fullname = models.CharField(max_length=30)
profile_picture_url = models.URLField()
def __str__(self):
return self.fullname
class Customer(models.Model):
pass
class File(m... | 2.390625 | 2 |
ana/fresnel.py | hanswenzel/opticks | 11 | 44164 | <filename>ana/fresnel.py
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Lice... | 2.453125 | 2 |
examples/api-samples/inc_samples/sample31.py | groupdocs-legacy-sdk/python | 0 | 44165 | ### This sample will show how to Create and Upload Envelop to GroupDocs account using Python SDK
# Import of classes from libraries
import os, time, random
from pyramid.renderers import render_to_response
from groupdocs.ApiClient import ApiClient
from groupdocs.StorageApi import StorageApi
from groupdocs.SignatureAp... | 2.265625 | 2 |
tests/test_data.py | hhsecond/stockroom | 0 | 44166 | <gh_stars>0
import pytest
import numpy as np
def test_save_data(stock):
arr = np.arange(20).reshape(4, 5)
stock.data['aset', 1] = arr
stock.commit("added data")
assert np.allclose(stock.data['aset', 1], arr)
del stock
def test_save_to_non_existing_column(stock):
arr = np.arange(20).reshape(4... | 2.34375 | 2 |
pandas_market_calendars/holidays_jp.py | mgellman-radix/pandas_market_calendars | 0 | 44167 | <reponame>mgellman-radix/pandas_market_calendars
from pandas import (
Timestamp
)
# Apr. 30 (Tue.) Abdication Day
# May 1 (Wed.) Accession Day
# May 2 (Thu.) National Holiday
# May 3 (Fri.) Constitution Memorial Day
# May 4 (Sat.) Greenery Day
# May 6 (Mon.) Children's Day (May 5) observed
Ascens... | 2.25 | 2 |
data/dataframes.py | MichaelVerdegaal/hotel-reviews-sentiment-analysis | 0 | 44168 | <reponame>MichaelVerdegaal/hotel-reviews-sentiment-analysis
import os
import re
import nltk
import pandas as pd
from langdetect import detect
from textblob import TextBlob
from config import ROOT_DIR
from data.file_util import (read_scraped_reviews, read_kaggle_reviews, read_manual_reviews, file_exists,
... | 3.09375 | 3 |
starter_bundle/ch20-out_of_the_box/imagenet_pretrained.py | romanroson/pis_code | 1 | 44169 | # -*- coding: utf-8 -*-
"""Classifying Images with Pre-trained ImageNet CNNs.
Let’s learn how to classify images with pre-trained Convolutional Neural Networks
using the Keras library.
Example:
$ python imagenet_pretrained.py --image example_images/example_01.jpg --model vgg16
$ python imagenet_pretrained.py ... | 3.96875 | 4 |
Programmieren_in_Python_2/NumPy_matplotlib/plot_random_numbers.py | ThomasGrafCode/EF_WF_Informatik | 0 | 44170 | import numpy as np
from matplotlib import pyplot as plt
N = 30
y = np.random.rand(N)
plt.plot(y,'bo') | 2.84375 | 3 |
Algo and DSA/LeetCode-Solutions-master/Python/insert-delete-getrandom-o1.py | Sourav692/FAANG-Interview-Preparation | 3,269 | 44171 | # Time: O(1)
# Space: O(n)
from random import randint
class RandomizedSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.__set = []
self.__used = {}
def insert(self, val):
"""
Inserts a value to the set. Returns true i... | 3.984375 | 4 |
lingvo/jax/layers/__init__.py | drpngx/lingvo | 0 | 44172 | # Lint as: python3
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | 1.695313 | 2 |
iter2/utils.py | ramon93i7/iter2 | 1 | 44173 | import functools
import types
def define_module_exporter():
all_list = []
def export(obj):
all_list.append(obj.__name__)
return obj
return export, all_list
def copy_func(fn):
if type(fn) is not types.FunctionType:
return functools.wraps(fn)(lambda *args, **kwargs: fn(*args, *... | 2.484375 | 2 |
hp4controller/virtualdevice/archive/hp4loader.py | MNCHr/Hyper4-Controller | 0 | 44174 | <filename>hp4controller/virtualdevice/archive/hp4loader.py<gh_stars>0
from virtualdevice import VirtualDevice
import hp4compiler
from hp4translator import InterpretationGuide
class CompileError(Exception):
pass
class VirtualDeviceFactory():
def __init__(self):
compiled_programs = {} # {program_path (str) : cr... | 2.453125 | 2 |
autotweet/twitter.py | Kjwon15/autotweet | 5 | 44175 | """:mod:`autotweet.twitter` --- Twitter utilities
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module contains Twitter API key and some useful methods.
"""
from __future__ import unicode_literals
import cgi
import re
import tweepy
import webbrowser
try:
from HTMLParser import HTMLParser
except ImportErr... | 3.046875 | 3 |
main.py | Clemson-Esports/ReactionBot | 0 | 44176 | import json
import discord
import os
from discord.ext import commands
import discord_components
import ErrorHandling
import Reactions
import Help
with open('Bot_Secrets.json', 'r') as botSecrets:
settings = json.load(botSecrets)
TOKEN = settings['BotToken']
intents = discord.Intents.default()
intents.members ... | 2.484375 | 2 |
test/integration/test_attributename.py | immijimmi/managedState | 0 | 44177 | <reponame>immijimmi/managedState
from managedstate import State, AttributeName
class TestAttributeName:
def test_get_uses_attributename_correctly(self, res):
state = State(res.value_4)
assert state.get(["key_2", AttributeName("attribute_1"), "key_3"]) == 7
def test_set_applies_attributename_... | 2.453125 | 2 |
restdf/utils/exceptions.py | Mukhopadhyay/restdf | 3 | 44178 | """
Exceptions for RestDF
"""
from typing import Union, List
class Error(Exception):
"""
Base class for exceptions in this module.
"""
pass
class PathError(Error):
"""
Exception raised when there's an error in the given path.
Attributes:
path: Union[str, list]: Path whi... | 3.015625 | 3 |
tarefas-poo/lista-04/matriz_de_inteiros/model/matriz_de_inteiros.py | victoriaduarte/POO_UFSC | 0 | 44179 | # -------------------------------
# UFSC - CTC - INE - INE5663
# Exercício da Matriz de Inteiros
# -------------------------------
# Classe que representa uma matriz de números inteiros.
#
class MatrizDeInteiros:
def __init__(self, dimensoes_ou_numeros):
'''Cria uma matriz de números inteiros. Há duas form... | 3.484375 | 3 |
Python/python_logging/aula/app.py | wendrewdevelop/Estudos | 0 | 44180 | '''
Etapas do logger
'''
import logging
# Instancia do objeto getLogger()
logger = logging.getLogger()
# Definindo o level do logger
logger.setLevel(logging.DEBUG)
# formatador do log
formatter = logging.Formatter(
'Data/Hora: %(asctime)s | level: %(levelname)s | file: %(filename)s | mensagem: %(message)s',
... | 2.796875 | 3 |
submissions/joi2009yo/d.py | m-star18/atcoder | 1 | 44181 | import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
m = int(readline())
n = int(readline())
a = [list(map(int, readline().split())) for _ in range(n)]
ans = 0
def dfs(y, x, cnt):
a[y][x] = 0
v = cnt + 1
for dy,... | 2.421875 | 2 |
BuildSimHubAPI/measures/hvac_template.py | ruijis/buildsimhub_python_api | 19 | 44182 | from .model_action import ModelAction
class HVACTemplate(ModelAction):
# this shows the ip to si conversion rate
# if unit is 'ip', then multiply this rate.
# for window it is the U-value
# convert U-value IP to SI
# The conversion will change w/ft2 to w/m2 if ip shows
NUM_HVAC = 14
def _... | 2.5625 | 3 |
test/mc_init_test.py | lechat/multiconf | 0 | 44183 | # Copyright (c) 2012 <NAME>, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
# pylint: disable=E0611
from pytest import xfail
from .. import ConfigRoot, ConfigItem
from ..envs import EnvFactory
ef = EnvFactory()
dev1 = ef.Env('dev1')
dev2 = ef.Env('dev2')
g_dev = ef.EnvGroup('... | 2.0625 | 2 |
app.py | wisemuffin/San_Francisco_Police_Reports | 1 | 44184 | <reponame>wisemuffin/San_Francisco_Police_Reports
# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html
# from dash.dependencies import Input, Output
#
# import plotly.plotly as py
# import plotly.graph_objs as go
#
# import pandas as pd
# import numpy as np
# from d... | 2.21875 | 2 |
pythonSublib/visao_comp/classificacao.py | leohmcs/AVANTLink | 5 | 44185 | <reponame>leohmcs/AVANTLink
import cv2
import numpy as np
import math
import matplotlib.pyplot as plt
from PIL import Image
nome = "triangulo"
img_original = cv2.imread("entradas/" + nome + ".png")
#cv2.imshow('Imagem Original',img_original)
imagem_cinza = cv2.cvtColor(img_original, cv2.COLOR_BGR2GRAY)
#cv2.imshow('... | 2.859375 | 3 |
test/observer/index_file_test.py | SpotlightKid/PluginsManager | 9 | 44186 | # Copyright 2017 SrMouraSilva
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | 2.421875 | 2 |
plotly/run_funcs.py | NREL/MetMastVis | 1 | 44187 | <gh_stars>1-10
import vis
import utils
import met_funcs
import plotly_vis
import MetMastData
import pandas as pd
import matplotlib.pyplot as plt
from colour import Color
import plotly
from plotly import tools
#import plotly.tools as tls
import plotly.plotly as py
import plotly.graph_objs as go
# Place input files here... | 2.3125 | 2 |
Tools/imgfunc/convert_img.py | ka10ryu1/jpegcomp2 | 1 | 44188 | <reponame>ka10ryu1/jpegcomp2<filename>Tools/imgfunc/convert_img.py
#!/usr/bin/env python3
# -*-coding: utf-8 -*-
#
help = '[imgfunc] 画像処理部'
#
import os
import sys
import cv2
import numpy as np
from logging import getLogger
logger = getLogger(__name__)
[sys.path.append(d) for d in ['./Tools/', '../Tools/'] if os.path.... | 2.6875 | 3 |
c15/p449_httplib2_test2.py | HiAwesome/dive-into-python3-practice | 0 | 44189 | from pprint import pprint
import httplib2
from file_path_collect import output_cache_path_dir as cache
httplib2.debuglevel = 1
h = httplib2.Http(cache)
# 网址换成简书
jianshu = 'https://www.jianshu.com/'
# 首先 cache 一遍
response0, content0 = h.request(jianshu)
print()
response, content = h.request(jianshu)
print()
print(... | 2.8125 | 3 |
spikey/snn/readout/__init__.py | SpikeyCNS/spikey | 4 | 44190 | """
Readout __init__.
"""
try:
from spikey.snn.readout.threshold import Threshold
from spikey.snn.readout.neuron_rates import NeuronRates
from spikey.snn.readout.population_vector import PopulationVector
from spikey.snn.readout.topaction import TopAction
except ImportError as e:
raise ImportError(f"... | 1.898438 | 2 |
robust_offline_contextual_bandits/test/named_results_test.py | dmorrill10/research2018 | 0 | 44191 | import tensorflow as tf
from robust_offline_contextual_bandits.named_results import NamedResults
import numpy as np
class NamedResultsTest(tf.test.TestCase):
def setUp(self):
np.random.seed(42)
def test_creation(self):
patient = NamedResults(np.random.normal(size=[10, 3]))
assert pati... | 2.421875 | 2 |
examples/pubsub_broadcaster_server_example.py | sondrelg/fastapi_websocket_pubsub | 125 | 44192 | """
Multiple Servers linked via broadcaster example.
To run this example.
- 0. Setup a broadcast medium and pass its configuration to the endpoint (e.g. postgres on 'postgres://localhost:5432/' )
- 1. run this script for the servers (as many instances as you'd like) - use the PORT env-variable to run them on differ... | 3.015625 | 3 |
tests/test_utils_sizing.py | lcsgrlch/oap | 0 | 44193 | """
Testing all methods from oap.utils.sizing
"""
import unittest
import oap
from tests.data import array01_original as array
class TestUtilsSizing(unittest.TestCase):
def test_xy_diameter(self):
x, y = oap.xy_diameter(array)
self.assertEqual(x, 43)
self.assertEqual(y, 45)
def test... | 2.921875 | 3 |
advent_of_code/day_04/solution.py | novotl/advent_of_code | 0 | 44194 | from typing import Iterable
from copy import deepcopy
from advent_of_code.runner import PuzzleTemplate
from dataclasses import dataclass, field
@dataclass
class Board:
# board juts for visualization purpose
board: list[list[int]] = field(default_factory=lambda: [[None] * 5 for _ in range(5)])
# number can... | 3.5 | 4 |
pandaserver/test/testSimulReco14.py | rybkine/panda-server | 1 | 44195 | <gh_stars>1-10
import sys
import time
import random
import commands
import userinterface.Client as Client
from taskbuffer.JobSpec import JobSpec
from taskbuffer.FileSpec import FileSpec
if len(sys.argv)>1:
site = sys.argv[1]
cloud = None
else:
site = None
cloud = 'US'
#cloud = 'TW'
#Recent chang... | 1.898438 | 2 |
TweakApi/models/billing_source_sofort.py | tweak-com-public/tweak-api-client-python | 0 | 44196 | <reponame>tweak-com-public/tweak-api-client-python
# coding: utf-8
"""
tweak-api
Tweak API to integrate with all the Tweak services. You can find out more about Tweak at <a href='https://www.tweak.com'>https://www.tweak.com</a>, #tweak.
OpenAPI spec version: 1.0.8-beta.0
Generated by: http... | 1.46875 | 1 |
mnt/airflow/dags/product_lookup_pipeline.py | dataength/automating-your-data-pipeline-with-apache-airflow | 30 | 44197 | <reponame>dataength/automating-your-data-pipeline-with-apache-airflow
import csv
import logging
from airflow import DAG
from airflow.operators.bash import BashOperator
from airflow.operators.dummy import DummyOperator
from airflow.providers.apache.hive.operators.hive import HiveOperator
from airflow.operators.python i... | 2.734375 | 3 |
clovars/bio/treatment.py | jfaccioni/clovars | 0 | 44198 | from __future__ import annotations
from typing import TYPE_CHECKING, Any
from clovars.scientific import Gaussian, get_curve
if TYPE_CHECKING:
from clovars.scientific import Curve
class Treatment:
"""Class representing a Treatment that influences Cells."""
def __init__(
self,
na... | 3.140625 | 3 |
lookup_api_v1/api_handler/types.py | markspolakovs/coronavirus-dashboard-api-v1 | 0 | 44199 | #!/usr/bin python3
"""
Type definitions
----------------
Custom type hint definitions used across the API service.
Author: <NAME> <<EMAIL>>
Created: 23 May 2020
License: MIT
Contributors: <NAME>
"""
# Imports
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... | 1.71875 | 2 |