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 |
|---|---|---|---|---|---|---|
docs/basic_usage/bu01.py | jviide/htm.py | 112 | 12765351 | from htm import htm
@htm
def html(tag, props, children):
return tag, props, children
result01 = html("""
<div>Hello World</div>
""")
| 2.65625 | 3 |
tests/test_process_raw_data.py | ayorkshireworrall/Forex-Predictor | 5 | 12765352 | from decimal import Decimal
import unittest, sys
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from unittest.mock import patch
from forex_predictor.data_extraction.process_raw_data import create_relevant_data_row, create_row, find_start_date_index, get_dataframe_from_dates, get_dates, ... | 2.453125 | 2 |
python/allergies/allergies.py | tamireinhorn/exercism | 0 | 12765353 | ALLERGIES_SCORE = ['eggs', 'peanuts', 'shellfish', 'strawberries',
'tomatoes', 'chocolate', 'pollen', 'cats']
class Allergies:
def __init__(self, score: int):
self.score = score
self.lst = self.list_of_allergies()
def allergic_to(self, item: str) -> bool:
retur... | 4 | 4 |
craftassist/test/test_dialogue_manager.py | kandluis/droidlet | 0 | 12765354 | """
Copyright (c) Facebook, Inc. and its affiliates.
"""
import os
import unittest
import logging
from base_agent.nsp_dialogue_manager import NSPDialogueManager
from base_agent.loco_mc_agent import LocoMCAgent
from base_agent.test.all_test_commands import *
from fake_agent import MockOpt
class AttributeDict(dict):
... | 2.125 | 2 |
server/models.py | pastgift/web-app-template-py | 0 | 12765355 | # -*- coding: utf-8 -*-
import uuid
import hashlib
from datetime import datetime
from flask import current_app, request
from flask.ext.login import UserMixin, AnonymousUserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from itsdangerous import TimedJSONWebSignatureSerializer as Serial... | 2.375 | 2 |
python02/PythonExample3.py | zhayangtao/HelloPython | 0 | 12765356 | class Number:
def __init__(self, start):
self.data = start
def __sub__(self, other):
return Number(self.data - other)
class Indexer:
data = [5, 6, 7, 8, 9]
def __getitem__(self, item):
print('getitem:', item)
return self.data[item]
def __setitem__(self, index, va... | 3.640625 | 4 |
pkg_classes/led8x8motion.py | parttimehacker/clock | 0 | 12765357 | <filename>pkg_classes/led8x8motion.py
#!/usr/bin/python3
""" Display full screen flash color pattern on an Adafruit 8x8 LED backpack """
import time
from PIL import Image
from PIL import ImageDraw
BRIGHTNESS = 5
UPDATE_RATE_SECONDS = 1.0
BLACK = 0
GREEN = 1
YELLOW = 3
RED = 2
class Led8x8Motion:
""" Display m... | 3.171875 | 3 |
jacdac/matrix_keypad/__init__.py | microsoft/jacdac-python | 1 | 12765358 | <filename>jacdac/matrix_keypad/__init__.py<gh_stars>1-10
# Autogenerated file.
from .client import MatrixKeypadClient # type: ignore
| 1.21875 | 1 |
docs/lectures/lecture31/notebook/helper.py | DavidAssaraf106/2021-CS109B | 0 | 12765359 | # This helper file, setups the rules and rewards for the mouse grid system
# State = 1, start point
# Action - 1: Top, 2:Left, 3:Right, 4:Down
def transition_rules(state, action):
# For state 1
if state == 1 and (action == 3 or action == 4):
state = 1
elif state == 1 and action == 1:
state... | 2.671875 | 3 |
website/migrations/0004_auto_20180602_1043.py | pomo-mondreganto/CTForces-old | 0 | 12765360 | <filename>website/migrations/0004_auto_20180602_1043.py
# Generated by Django 2.0.5 on 2018-06-02 07:43
from django.db import migrations, models
import website.models_auxiliary
class Migration(migrations.Migration):
dependencies = [
('website', '0003_auto_20180601_2313'),
]
operations = [
... | 1.59375 | 2 |
template/predict_template.py | HamletWantToCode/machine_learning_kinetic_energy | 2 | 12765361 | # data predicting
import pickle
import numpy as np
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
from MLEK.main.optimizer import Minimizer
from MLEK.tools.plot_tools import plot_prediction
with open('/Users/hongbinren/Documents/program/MLEK/example_demo/demo_best_estimator', 'rb') ... | 2.453125 | 2 |
convert_RAW.py | wuhuangwanshui/Learning-to-See-in-the-Dark | 1 | 12765362 | <reponame>wuhuangwanshui/Learning-to-See-in-the-Dark<gh_stars>1-10
import os
import numpy as np
import rawpy
import glob
from matplotlib import pyplot as plt
import multiprocessing
input_dir = './dataset/Sony/short/'
output_dir = './dataset/Sony/short/JPEG'
if not os.path.exists(output_dir):
os.makedirs(output_di... | 2.296875 | 2 |
Index_Create.py | Chendemo12/KnowledgeGraph | 13 | 12765363 | <gh_stars>10-100
# -*- encoding: utf-8 -*-
# @Author: LiChenguang
# @Data : 2020/03/12
# @Email : <EMAIL>
# @sys : Ubuntu 18.04
# @WebSite: www.searcher.ltd
# @Last Modified time: 2020/03/12
import os
import get_FileInfo as F
def web_indexCreate(folder):
"""
生成 _**Index.md 文件
folder:文件保存文件夹
... | 2.46875 | 2 |
ecommerce/apps/charts/urls.py | margolek/electronic-ecommerce | 0 | 12765364 | from django.urls import path
from . import views
app_name = "charts"
urlpatterns = [
path("", views.home, name="dashboard"),
]
| 1.59375 | 2 |
taskwpomo/misc.py | fsimkovic/taskwarrior-pomodoro | 0 | 12765365 | __author__ = '<NAME>'
__date__ = '2019-05-11'
__license__ = 'MIT License'
import logging
log = logging.getLogger(__name__)
def log_call(fn):
def inner(*args, **kwargs):
log.debug('Function %s called with %s and %s', fn.__name__, args, kwargs)
return fn(*args, **kwargs)
return inner
| 2.53125 | 3 |
API/path.py | Elaina-Alex/LaoMaoAppNovelDownloader | 2 | 12765366 | from instance import *
def SAVE_FILE(bookName, number, book_title)
return os.path.join(Vars.cfg.data.get('save_dir'), bookName, f"{}.{}.txt"),
def OUT_FILE(bookName)
return os.path.join(Vars.cfg.data.get('output_dir'), f'{bookName}.txt'), 'a', line)
| 2.53125 | 3 |
scqubits/core/hilbert_space.py | zlatko-minev/scqubits | 7 | 12765367 | <reponame>zlatko-minev/scqubits
# hilbert_space.py
#
# This file is part of scqubits.
#
# Copyright (c) 2019, <NAME> and <NAME>
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
#########################... | 1.664063 | 2 |
tests/test_entropies.py | klgunst/sloth | 0 | 12765368 | <reponame>klgunst/sloth
from sloth.network import read_h5
from sloth.utils import flatten_svals
import pickle
import pytest
import os
@pytest.fixture()
def checkvals():
picklefile = os.path.join(os.path.dirname(__file__), 'N2_svals.pickle')
with open(picklefile, 'rb') as f:
checkvals = pickle.load(f)
... | 2.078125 | 2 |
aos/catalog.py | davidthomas5412/ActiveOpticsSimulator | 4 | 12765369 | <reponame>davidthomas5412/ActiveOpticsSimulator
import os
from aos import catDir
from aos.constant import h,c
from astropy.table import Table, vstack
from astroquery.gaia import Gaia
class GaiaCatalog:
"""
Class for gaia catalog tables.
Parameters
----------
table: astropy.table.Table
The ... | 2.34375 | 2 |
get-page.py | cristianounix/python-scripts | 0 | 12765370 | import pycurl
import thread
from StringIO import StringIO
def request_url(thread_name, start, end):
buffer = StringIO()
for x in range(start, end):
c = pycurl.Curl()
print(str(thread_name)+"Processando --> "+str(x))
c.setopt(c.URL, 'http://www.site.com.br/?id='+str(x))
c.setopt... | 3.09375 | 3 |
2 - Tipos de dados/2.7 - Binário/bytes.py | SamuelHDieterich/Walkthrough-Python | 3 | 12765371 | # A variável "oi" recebe o valor "Hi" em bytes
oi = b'Hi'
# Retorna o valor da variável
print(oi) # b'Hi'
# Retorna o tipo
print(type(oi)) # <class 'bytes'> | 3.171875 | 3 |
python/dazl/prim/complex.py | DACH-NY/dazl-client | 0 | 12765372 | # Copyright (c) 2017-2022 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Contains functions for working with "native" Python types as they correspond to types over the
Ledger API.
"""
from typing import Any, Dict, Mapping, Tuple
__all__ = ["to_r... | 2.25 | 2 |
openml_data_integration/protobuf_generator/openml_40646/myconstants.py | tuix/tutorials | 8 | 12765373 | <filename>openml_data_integration/protobuf_generator/openml_40646/myconstants.py
DATA_ID = 40646
| 0.902344 | 1 |
common/past/arguments.py | punk95/Hierarchical-constrained-RL | 0 | 12765374 | import argparse
def get_args():
"""
Utility for getting the arguments from the user for running the experiment
:return: parsed arguments
"""
# Env
parser = argparse.ArgumentParser(description='collect arguments')
parser.add_argument('--save_dir', type=str, default="results/grid/sarsa/")... | 3.25 | 3 |
nicos_mlz/kompass/setups/aircontrol.py | jkrueger1/nicos | 0 | 12765375 | description = 'Aircontrol PLC devices'
group = 'optional'
tango_base = 'tango://kompasshw.kompass.frm2:10000/kompass/aircontrol/plc_'
devices = dict(
spare_motor_x2 = device('nicos.devices.entangle.Motor',
description = 'spare motor',
tangodevice = tango_base + 'spare_mot_x2',
fmtstr = '%... | 1.867188 | 2 |
pyrosenv/sensor_msgs/__init__.py | omrirz/pyrosenv | 7 | 12765376 | import sensor_msgs.msg
from sensor_msgs.msg import *
from . import point_cloud2
import importlib
msg = importlib.import_module('sensor_msgs.msg')
point_cloud2 = importlib.import_module('sensor_msgs.point_cloud2')
__all__ = ['msg', 'point_cloud2']
| 1.539063 | 2 |
SimulateCNVs.py | YJulyXing/SimulateCNVs | 3 | 12765377 | <filename>SimulateCNVs.py
#!/usr/bin/python
'''
<NAME>
06/27/2018
'''
import argparse
import random
import os
import subprocess
import math
import sys
import time
from WES_simulator import *
from WGS_simulator import *
from Common import *
def main():
parser = argparse.ArgumentParser(description='Simulator for WE... | 2.484375 | 2 |
jdxapi/wait_for_db.py | jobdataexchange/jdx-api | 0 | 12765378 | <gh_stars>0
import psycopg2
# TODO pull from env
dbname = 'jdx_reference_backend_application'
user = 'postgres'
host = 'jdx-postgres'
password = 'password'
try:
db = psycopg2.connect(
f"dbname={dbname} user={user} host={host} password={password}"
)
print("Established connection with database!")
e... | 2.890625 | 3 |
ex8.py | ppedraum/infosatc-lp-avaliativo-02 | 0 | 12765379 | #8 - LISTA DE COMPONENTES -> PC GAMER
comp = ["Nvidia GeForce GTX 2080Ti", "Gabinete Cooler Master", "Kit RAM GSkill DDR4 3.6GHz 8x2GB",
"Placa Mãe ASUSTeK ROG MAXIMUS XI EXTREME", "Processador Intel i9", "SSD NVMe Samsung 970 1TB"]
del comp[0]
del comp[0]
print(comp)
| 2.34375 | 2 |
exiftoolwrap.py | DanyJoly/photorename | 0 | 12765380 | """Basic facade for the exiftool executable"""
# Public
import os.path
import shlex
import subprocess
import sys
# Internal
import exiftoolinst
class ExiftoolWrap:
_path = None
_path_to_binary = None
def __init__(self, path=""):
self._path = path
self._detect_installation()
#
... | 2.78125 | 3 |
WebScrapy/spiders/alonhadat.py | phamvanhanh6720/Bigdata | 2 | 12765381 | <filename>WebScrapy/spiders/alonhadat.py
from typing import List
import scrapy
import pymongo
from scrapy.crawler import CrawlerProcess
from confluent_kafka import Producer
from scrapy.utils.project import get_project_settings
from WebScrapy.items import AlonhadatItem
import logging
from selenium.webdriver.remote.re... | 2.421875 | 2 |
testing/util.py | bbhunter/fuzz-lightyear | 169 | 12765382 | <gh_stars>100-1000
import re
# Source: https://stackoverflow.com/a/14693789
_ansi_escape = re.compile(r'\x1b\[[0-?]*[ -/]*[@-~]')
def uncolor(text):
return _ansi_escape.sub('', text)
| 2.46875 | 2 |
python-tests/basic.py | FjolleJagt/rust-emcee | 7 | 12765383 | #!/usr/bin/env python
import numpy as np
np.random.seed(42)
import emcee
def lnprior(params):
return 0.0
def lnlike(params, x, y):
model = params[0] * x + params[1]
residuals = y - model
return -np.sum(residuals ** 2)
def lnprob(params, x, y):
lnp = lnprior(params)
if np.isfinite(lnp):
... | 2.09375 | 2 |
examples/rpc_client.py | alephzero/playground | 3 | 12765384 | import a0
import time
def callback(pkt):
print(f'Recieved reply: {pkt.payload.decode("utf-8")}')
print("Waiting 1ms for response")
client = a0.RpcClient("topic")
client.send("client msg", callback)
time.sleep(0.001)
print("Done!")
| 2.65625 | 3 |
submodule/template_lib/trainer/train.py | AnonymousGFR/wbgan.pytorch | 1 | 12765385 |
def main(trainer, args, myargs):
config = myargs.config
from template_lib.utils import seed_utils
seed_utils.set_random_seed(config.seed)
if args.evaluate:
trainer.evaluate()
return
if args.resume:
trainer.resume()
elif args.finetune:
trainer.finetune()
# Load dataset
trainer.datas... | 2.03125 | 2 |
TeacherTree/venv/Lib/site-packages/flask_boost/templates/model.py | intuile/teacher-tree-website | 543 | 12765386 | # coding: utf-8
from datetime import datetime
from ._base import db
class #{model|title}(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), unique=True)
created_at = db.Column(db.DateTime, default=datetime.now)
def __repr__(self):
return '<#{model|title} %... | 2.625 | 3 |
snmpagent_unity/tests/test_agent.py | factioninc/snmp-unity-agent | 2 | 12765387 | import collections
import unittest
from snmpagent_unity import agent, enums
from snmpagent_unity import exceptions as snmp_ex
from snmpagent_unity.tests import patches
from pysnmp.smi import error as smi_ex
SERVICE_ID_MD5 = (1, 3, 6, 1, 6, 3, 10, 1, 1, 2)
SERVICE_ID_SHA = (1, 3, 6, 1, 6, 3, 10, 1, 1, 3)
SERVICE_ID_D... | 2.15625 | 2 |
common/util.py | Marina-chan/course_reexplainer_api | 0 | 12765388 | import re
import sre_constants
from functools import wraps
from html import unescape
import requests
import redis
import lxml
from bs4 import BeautifulSoup
from flask import request
class RedisDict:
def __init__(self, **redis_kwargs):
self.__db = redis.Redis(**redis_kwargs)
def __len__(self):
... | 2.640625 | 3 |
cli/test/test_runner_slurm.py | vipulchhabra99/popper | 0 | 12765389 | import os
import unittest
import tempfile
from testfixtures import compare, Replacer, replace
from testfixtures.popen import MockPopen
from testfixtures.mock import call
from popper.config import ConfigLoader
from popper.runner import WorkflowRunner
from popper.parser import WorkflowParser
from popper.runner_slurm im... | 2.0625 | 2 |
aula14/exercicio4.py | ArseniumGX/bluemer-modulo1-python | 0 | 12765390 | <filename>aula14/exercicio4.py
# 4. Faça um programa que calcule o salário de um colaborador na empresa XYZ. O salário
# é pago conforme a quantidade de horas trabalhadas. Quando um funcionário trabalha
# mais de 40 horas ele recebe um adicional de 1.5 nas horas extras trabalhadas.
def calcSalario(salario:float, horaEx... | 4.0625 | 4 |
PlayerInterFace.py | theLamentingGirl/AI-tictactoe | 0 | 12765391 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 9 21:17:04 2020
@author: gaGzy
@author: wridhdhi
"""
'''BUGS FIXED COMPLETELY'''
from GameEngine import *
class playerInterface(playTicTacToe):
def __init__(self):
super().__init__()
self.player=0
self.parent=Tk()
#partition1 for othe... | 2.59375 | 3 |
tensornetwork/linalg/krylov.py | khanhgithead/TensorNetwork | 1,681 | 12765392 | # Copyright 2019 The TensorNetwork Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | 2.296875 | 2 |
blueqat/backends/cuquantum.py | mdrft/Blueqat | 25 | 12765393 | <gh_stars>10-100
from .backendbase import Backend
from ..circuit import Circuit
from ..gate import *
import numpy as np
class cuTN(Backend):
def _preprocess_run(self, gates, n_qubits, args, kwargs):
import opt_einsum as oe
arr_tensor = []
arr_arm = []
arr_state = []
... | 1.882813 | 2 |
bel/schemas/nanopubs.py | belbio/bel | 6 | 12765394 | <reponame>belbio/bel
# Standard Library
import enum
from typing import Any, List, Mapping, Optional, Union
# Third Party
import pydantic
from pydantic import AnyUrl, BaseModel, Field, HttpUrl, validator
# Local
from bel.schemas.bel import ValidationErrors
class NanopubType(BaseModel):
name: str = "BEL"
vers... | 2.3125 | 2 |
swagger_server/uas_lib/vault.py | Cray-HPE/uas-mgr | 0 | 12765395 | <reponame>Cray-HPE/uas-mgr
# MIT License
#
# (C) Copyright [2022] Hewlett Packard Enterprise Development LP
#
# 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 wi... | 1.898438 | 2 |
pipeline.py | NLP-Discourse-SoochowU/sota_end2end_parser | 1 | 12765396 | <filename>pipeline.py
# -*- coding: utf-8 -*-
"""
@Author: Lyzhang
@Date:
@Description: Implementation of ELMo and bert in RST-style Segmentation.
"""
from util.file_util import *
from config_segment import *
from config import UNK_ids
from path_config import *
from stanfordcorenlp import StanfordCoreNLP
from allennlp... | 2.0625 | 2 |
h/traversal/organization.py | bibliotechie/h | 0 | 12765397 | from dataclasses import dataclass
from functools import cached_property
from pyramid.request import Request
from h.models import Organization
from h.traversal.root import Root, RootFactory
class OrganizationRoot(RootFactory):
"""Root factory for routes which deal with organizations."""
def __getitem__(self... | 2.4375 | 2 |
BurnySC2/local/rush_agent/run.py | PhoenixNest/Hello-PySC2 | 0 | 12765398 | import random
import sc2
from sc2.player import Bot, Computer
import protoss_agent
if __name__ == '__main__':
enemy_race = random.choice([sc2.Race.Protoss, sc2.Race.Terran, sc2.Race.Zerg, sc2.Race.Random])
sc2.run_game(sc2.maps.get("Simple128"),
[Bot(sc2.Race.Protoss, protoss_agent.ProtossRu... | 2.09375 | 2 |
vitrage/tests/mocks/mock_transformer.py | HoonMinJeongUm/Hunmin-vitrage | 0 | 12765399 | <reponame>HoonMinJeongUm/Hunmin-vitrage<filename>vitrage/tests/mocks/mock_transformer.py
# Copyright 2015 - Alcatel-Lucent
#
# 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.apach... | 2.390625 | 2 |
WDJN/bt_beam/data_prepare/extract_dialogue_text.py | silverriver/Stylized_Dialog | 21 | 12765400 | import random
if __name__ == '__main__':
sentences = []
with open('../data/crowded_300k.txt', encoding='utf-8') as f:
for line in f:
line = line.strip().split('\t')
sentences.append(line[1])
sentences.append(line[2])
random.shuffle(sentences)
sentences = sen... | 2.5 | 2 |
unittests/libtests/feassemble/data/ElasticityImplicit.py | joegeisz/pylith | 1 | 12765401 | #!/usr/bin/env python
#
# ----------------------------------------------------------------------
#
# <NAME>, U.S. Geological Survey
# <NAME>, GNS Science
# <NAME>, University of Chicago
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://geodynamics.org).
#
# Copyright (c) ... | 2.28125 | 2 |
main.py | KleinYuan/eigenvectors-from-eigenvalues | 7 | 12765402 | import numpy as np
from pprint import pprint
def cal_eigenvalues_and_eigenvectors(A):
"""
:param A: n x n Hermitian matrix
:return:
"""
eigenvalues, normed_eigenvectors = np.linalg.eig(A)
# Below two steps are redounding for readability
lmd = eigenvalues
v = normed_eigenvectors
re... | 3.234375 | 3 |
core/pythontests/sparkel/core/test_nlp_words.py | tanthml/spark_bazel | 13 | 12765403 | import unittest
from sparkel.nlp.words import word_count
class WordsTestCase(unittest.TestCase):
def setUp(self):
self.text = u"This is an simple test case for Spark and Bazel!"
# <prefix>_<function_name>
def test_word_count(self):
expectation = 10
actual = word_count(self.text)... | 3.078125 | 3 |
run_mul copy.py | biechuyangwang/UniversalAutomaticAnswer | 2 | 12765404 | <reponame>biechuyangwang/UniversalAutomaticAnswer<filename>run_mul copy.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
sys.path.append(r"C:\\Users\\SAT") # 添加自定义包的路径
from UniversalAutomaticAnswer.conf.confImp import get_yaml_file
from UniversalAutomaticAnswer.screen.screenImp import ScreenImp # 加入自定义包
fr... | 2.53125 | 3 |
tests/project/operations/test_costs.py | souissim/gridpath | 0 | 12765405 | # Copyright 2016-2020 Blue Marble Analytics LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | 1.90625 | 2 |
peerscout/shared/logging_config.py | elifesciences/peerscout | 3 | 12765406 | import logging
from logging.handlers import TimedRotatingFileHandler
import os
def configure_logging(name):
logging.getLogger().setLevel(logging.DEBUG)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
logging.getLogger().addHandler(console_handler)
log_filename = ... | 2.59375 | 3 |
xml2epub/chapter.py | dfface/xml2epub | 1 | 12765407 | #!usr/bin/python3
# -*- coding: utf-8 -*-
# Included modules
import html
import codecs
import imghdr
import os
import shutil
import tempfile
from urllib.request import urlretrieve
from urllib.parse import urljoin
from hashlib import md5
# Third party modules
import requests
import bs4
from bs4 import... | 2.78125 | 3 |
abc/abc215/abc215d.py | c-yan/atcoder | 1 | 12765408 | <filename>abc/abc215/abc215d.py
def make_prime_table(n):
sieve = list(range(n + 1))
sieve[0] = -1
sieve[1] = -1
for i in range(4, n + 1, 2):
sieve[i] = 2
for i in range(3, int(n ** 0.5) + 1, 2):
if sieve[i] != i:
continue
for j in range(i * i, n + 1, i * 2):
... | 3.65625 | 4 |
main/settings_for_script.py | nmota/public-contracts | 0 | 12765409 |
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'publics',
'USER': 'publics_read_only',
'PASSWORD': r'<PASSWORD>',
'HOST': '172.16.31.10',
'PORT': '5432',
}
}
INSTALLED_APPS = (
'contracts',
'law',
'deputies'
)
... | 1.492188 | 1 |
alttprbot_discord/cogs/racetime_tools.py | skyscooby/sahasrahbot | 15 | 12765410 | <reponame>skyscooby/sahasrahbot
import json
import aiohttp
import discord
from discord.ext import commands
from alttprbot import models
class RacetimeTools(commands.Cog):
def __init__(self, bot):
self.bot: commands.Bot = bot
@commands.Cog.listener()
async def on_racetime_open(self, handler, dat... | 2.40625 | 2 |
workalendar/tests/test_mozambique.py | taiyeoguns/workalendar | 405 | 12765411 | from datetime import date
from . import GenericCalendarTest
from ..africa.mozambique import Mozambique
class MozambiqueTest(GenericCalendarTest):
cal_class = Mozambique
def test_year_new_year_shift(self):
holidays = self.cal.holidays_set(2019)
self.assertIn(date(2019, 1, 1), holidays)
... | 3.0625 | 3 |
replace/RegexReplacer.py | eshanMewantha/natural-language-processing | 1 | 12765412 | <filename>replace/RegexReplacer.py<gh_stars>1-10
import re
replacement_patterns = [
(r'I\'m', 'I am'),
(r'(\w+)\'ll', '\g<1> will'),
]
class RegexReplacer:
def __init__(self, patterns=replacement_patterns):
self.patterns = [(re.compile(regex), repl) for (regex, repl) in patterns]
def replace... | 2.96875 | 3 |
cycy/__main__.py | Magnetic/cycy | 26 | 12765413 | <gh_stars>10-100
import sys
from cycy.target import main
main(sys.argv)
| 1.03125 | 1 |
fairseq/modules/knowledge_guide.py | xwjim/fairseq | 0 | 12765414 | <filename>fairseq/modules/knowledge_guide.py
import torch
import torch.nn as nn
import numpy as np
from fairseq import utils
class Knowledge_Infer(nn.Module):
def __init__(self,input_size,select_num=7,ie_dropout=0.3):
super().__init__()
self.select_num = select_num
self.cate_size = 8
... | 2.4375 | 2 |
workers.py | kaapstorm/aiohttp_workers | 0 | 12765415 | <filename>workers.py
import asyncio
import multiprocessing
import time
from concurrent.futures import ProcessPoolExecutor, as_completed
from math import ceil
from queue import Empty
import aiohttp
NUM_PROCESSES = multiprocessing.cpu_count()
TASKS_PER_PROCESS = 16
NUM_ITEMS = 1023
def get_all_items():
"""
Ge... | 3.078125 | 3 |
yellowbrick/utils/helpers.py | drwaterman/yellowbrick | 1 | 12765416 | # yellowbrick.utils.helpers
# Helper functions and generic utilities for use in Yellowbrick code.
#
# Author: <NAME> <<EMAIL>>
# Created: Fri May 19 10:39:30 2017 -0700
#
# Copyright (C) 2017 District Data Labs
# For license information, see LICENSE.txt
#
# ID: helpers.py [79cd8cf] <EMAIL> $
"""
Helper functions an... | 2.296875 | 2 |
core/config/base_config.py | Wr490046178/fast-api-frame | 0 | 12765417 | import os
def str2bool(v):
if v is None or isinstance(v, bool):
return v
return v.lower() in ("yes", "true", "t", "1")
def str2int(v):
if v is None:
return v
if v == "":
return None
return int(v)
def str2float(v):
if v is None:
return v
return int(v)
c... | 2.859375 | 3 |
src/oidcservice/oidc/add_on/status_check.py | IdentityPython/oiccli | 3 | 12765418 | from cryptojwt.utils import as_bytes
def get_session_status_page(service_context, looked_for_state):
"""
Constructs the session status check page
:param service_context: The relying party's service context
:param looked_for_state: Expecting state to be ? (changed/unchanged)
"""
_msg = open(se... | 2.28125 | 2 |
devel/lib/python2.7/dist-packages/beginner_tutorials/msg/__init__.py | samuel100u/dashgo | 0 | 12765419 | <reponame>samuel100u/dashgo<gh_stars>0
from ._DoDishesAction import *
from ._DoDishesActionFeedback import *
from ._DoDishesActionGoal import *
from ._DoDishesActionResult import *
from ._DoDishesFeedback import *
from ._DoDishesGoal import *
from ._DoDishesResult import *
from ._Hello import *
| 1.148438 | 1 |
OutlineHelper/oh_adjust.py | FelineEntity/Outline-Helper | 5 | 12765420 | <gh_stars>1-10
import bpy
from bpy.props import *
from bpy.types import (Panel,Menu,Operator,PropertyGroup)
class OH_OT_Adjust_Operator(bpy.types.Operator):
bl_idname = "object.oh_adjust"
bl_label = "Adjust Outline"
bl_description = "Adjust geometry outline of selected objects"
bl_options = { "REGISTE... | 2.265625 | 2 |
code/AST/PrintAST.py | antuniooh/Dattebayo-compiler | 0 | 12765421 | <reponame>antuniooh/Dattebayo-compiler
from .AST import AST
class PrintAST(AST):
def __init__(self, value):
self.value = value
| 2.1875 | 2 |
examples/gridworld_example.py | omardrwch/rl_exploration_benchmark | 1 | 12765422 | from rlxp.envs import GridWorld
from rlxp.rendering import render_env2d
env = GridWorld(7, 10, walls=((2,2), (3,3)))
env.enable_rendering()
for tt in range(50):
env.step(env.action_space.sample())
render_env2d(env) | 1.953125 | 2 |
one_fm/templates/pages/applicant_docs.py | mohsinalimat/One-FM | 0 | 12765423 | <filename>one_fm/templates/pages/applicant_docs.py
from google.cloud import vision
import os, io
import frappe
from frappe.utils import cstr
import json
import frappe.sessions
import base64
import datetime
import hashlib
from dateutil.parser import parse
from frappe import _
from frappe.model.document import Document
... | 2.1875 | 2 |
MIT_Introduction_to_Computational_Thinking_and_Data_Science-master/07_Confidence_Intervals/lecture7_MINE.py | zhen5636/MIT6.0002 | 0 | 12765424 | import random, pylab
random.seed(1)
def getMeanAndStd(X):
mean = sum(X)/float(len(X))
tot = 0.0
for x in X:
tot += (x - mean)**2
std = (tot/len(X))**0.5
return mean, std
# GENERATING NORMALLY DISTRIBUTED DATA
#==============================================================================
... | 3.25 | 3 |
bot.py | Delivery-Klad/DiscordMusicBot | 9 | 12765425 | import discord
import youtube_dl
import os
from discord.ext import commands
from discord.utils import get
from discord import FFmpegPCMAudio
bot = commands.Bot(command_prefix='.')
vol = 100
@bot.event
async def on_ready():
print("Logged in as: " + bot.user.name + "\n")
game = discord.Game("поиск дома")
a... | 2.46875 | 2 |
cerebralcortex/data_processor/test/test_rip.py | MD2Korg/CerebralCortex-2.0-legacy | 0 | 12765426 | # Copyright (c) 2016, MD2K Center of Excellence
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditio... | 1.25 | 1 |
trelloengine/structures/search.py | MrFizban/TrelloEngine | 0 | 12765427 | #!/usr/bin/env python3
from .base import Base
class Search(Base):
def __init__(self, app_key: str, token: str, id=None , use_log = False):
super(Search, self).__init__(app_key=app_key, token=token, id=None, use_log=use_log)
self.base_url = self.base_url + "/search"
def serach_trello(... | 2.171875 | 2 |
Syshub/syshub_example_slave.py | voussoir/else | 13 | 12765428 | '''
Notice how this file does not import syshub or know about it
in any way.
'''
import sys
def say_something():
print('hello')
def input_something():
print('prompt: ', end='')
print(sys.stdin.readline())
def raise_something():
raise ValueError | 2.296875 | 2 |
grr/server/grr_response_server/bin/__init__.py | nkrios/grr | 4,238 | 12765429 | #!/usr/bin/env python
"""GRR server entry points."""
| 1.015625 | 1 |
overhave/admin/views/index/login_form.py | TinkoffCreditSystems/overhave | 33 | 12765430 | import logging
import flask
from flask_wtf import FlaskForm as Form
from pydantic import SecretStr
from werkzeug import Response
from wtforms import PasswordField, StringField, validators
from overhave.authorization import IAdminAuthorizationManager
from overhave.entities import SystemUserModel
logger = logging.getL... | 2.59375 | 3 |
skiplist/test.py | Skymemory/Data-Structure | 1 | 12765431 | import unittest
import random
from skiplist import SkipList
class SkipListTest(unittest.TestCase):
def setUp(self):
self.sl = SkipList()
def test_insert(self):
key, data = random.randint(0, 1 << 20), 'SkipList'
self.sl[key] = data
self.assertEqual(self.sl[key], data)
de... | 3.125 | 3 |
Tutorials/GLGlutDemos/GLTEST2.py | fovtran/PyGame_samples | 0 | 12765432 | <gh_stars>0
import sys, time
import math as m
import numpy as np
import scipy as sc
import sympy as sy
import OpenGL
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import OpenGL.GL
import OpenGL.GLUT
import OpenGL.GLU
def display():
# Clear off-screen buffer
glClear(GL_COLOR_BUFFER_BI... | 3.140625 | 3 |
jam_image_filter/tats.py | phuedx/jam-image-filter | 0 | 12765433 | <reponame>phuedx/jam-image-filter
import os
import sys
import math
from PIL import Image, ImageOps
import util
import colorsys
import random
def tats(image):
image = image.convert('RGB')
colours = util.get_dominant_colours(image, 9)
colours = util.order_colours_by_brightness(colours)
bg = random.choic... | 2.203125 | 2 |
Books/code/chapter_29/02_kfold_decision_tree.py | Mikma03/Optimization_in_Machine_Learning | 1 | 12765434 | # evaluate a decision tree on the entire small dataset
from numpy import mean
from numpy import std
from sklearn.datasets import make_classification
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import RepeatedStratifiedKFold
from sklearn.tree import DecisionTreeClassifier
# define da... | 3.375 | 3 |
aiida/backends/sqlalchemy/tests/testbase.py | odarbelaeze/aiida_core | 1 | 12765435 | # -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... | 1.828125 | 2 |
tipcalc.py | eXeler0n/tipcalc | 0 | 12765436 | <filename>tipcalc.py
# Tip calculator GUI by eXeler0n
from tkinter import *
from tkinter.ttk import *
# Basic window properties
window = Tk()
window.title('Trinkgeldrechner')
window.geometry('350x150')
# Calculation and fill results
def calculate():
amount = float(inp_amount.get().replace(',', '.')) ... | 3.53125 | 4 |
classifier.py | Wingxvii/SENet-TFslim | 0 | 12765437 | import os
import tensorflow as tf
import os
from PIL import Image
import numpy as np
import cv2
from preprocessing import preprocessing_factory
from google.protobuf import text_format
def main(_):
labels = []
'''
# Let's read our pbtxt file into a Graph protobuf
f = open("C:/Users/turnt/OneDrive/Des... | 2.796875 | 3 |
alphatwirl/binning/RoundLog.py | shane-breeze/AlphaTwirl | 0 | 12765438 | # <NAME> <<EMAIL>>
import math
from .Round import Round
##__________________________________________________________________||
class RoundLog(object):
"""Binning with equal width in log scale
Parameters
----------
width : float or int, default 1
The common logarithm (log10) of the width.
... | 3.46875 | 3 |
EGGS_labrad/clients/stability_client/stability_gui.py | EGGS-Experiment/EGGS_Control | 0 | 12765439 | import numpy as np
import pyqtgraph as pg
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont, QColor
from PyQt5.QtWidgets import QFrame, QWidget, QLabel, QGridLayout, QGroupBox, QDoubleSpinBox, QPushButton,\
QTabWidget, QComboBox, QRadioButton, QHBoxLayout, QVBoxLayout, QTreeWidget, QTreeWidgetItem
from EG... | 2.5625 | 3 |
python/coffer/ticker/baseprice.py | Steve132/wallet_standard | 0 | 12765440 | import logging
import time
import bisect
class PriceLookupBoundsError(Exception):
def __init__(self,requested_timestamp,nearest_timestamp,nearest_price):
super(PriceLookupBoundsError, self).__init__("Requested price lookup at time %s is out of bounds of the available data" % (requested_timestamp))
self.request... | 3.046875 | 3 |
war.py | JoshPorterDev/War | 0 | 12765441 | """
Dev: <NAME>
Date: 11/17/19
Program: Cpu vs Cpu War game
"""
import random
def victoryScreen(player, hands):
"""Prints a personalized victory screen to the terminal"""
print('~~~~~~~~~~~~~~~~~~~~~~~~~~')
print(f'~~~~~ {player} wins!! ~~~~~')
print(f'~~~~~~ In {hands} hands ~~~~~~~... | 3.921875 | 4 |
neutron/tests/unit/plugins/ml2/drivers/test_type_gre.py | cleo4zheng/neutron | 4 | 12765442 | # Copyright (c) 2013 OpenStack Foundation
# 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.921875 | 2 |
Camera_Caliberation_and_Fundamental_Matrix/code/student_code.py | dasdristanta13/Computer-vision | 0 | 12765443 | <filename>Camera_Caliberation_and_Fundamental_Matrix/code/student_code.py
import numpy as np
def calculate_projection_matrix(points_2d, points_3d):
"""
To solve for the projection matrix. You need to set up a system of
equations using the corresponding 2D and 3D points:
... | 3.75 | 4 |
manager/test_request.py | SIOTLAB/EdgeAP | 1 | 12765444 | <reponame>SIOTLAB/EdgeAP<gh_stars>1-10
import socket
import sys
import os
import json
import time
manager_ip = "192.168.3.11"
request_port = 60001
shutdown_port = 60002
def create_connection(ip, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((ip, port))
except (Connect... | 2.34375 | 2 |
backend/radar/validation.py | me-anton/radar-app | 0 | 12765445 | body_max_width = 15
body_max_height = 15
def validate_body_str_profile(body: str):
body_lines = body.splitlines()
width = len(body_lines[0])
height = len(body_lines)
if width > body_max_width or height > body_max_height:
raise ValueError("Body string is too big")
| 3.0625 | 3 |
tests/v2/test_0958-new-forms-must-accept-old-form-json.py | colesbury/awkward-1.0 | 0 | 12765446 | <gh_stars>0
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
import json
import pytest # noqa: F401
import numpy as np # noqa: F401
import awkward as ak # noqa: F401
def test_EmptyArray():
v1 = json.loads(
'{"class":"EmptyArray","has_identities":false,"paramete... | 2.171875 | 2 |
write_file.py | jayagascon/pos-chair | 0 | 12765447 | <filename>write_file.py<gh_stars>0
# adapted from https://learn.adafruit.com/mcp3008-spi-adc/python-circuitpython
import busio
import digitalio
import board
import time
import adafruit_mcp3xxx.mcp3008 as MCP
from adafruit_mcp3xxx.analog_in import AnalogIn
import csv
from datetime import datetime
# create the spi bus
... | 3.0625 | 3 |
compose/connectors/urls.py | lijc210/compose | 0 | 12765448 | # -- coding: utf-8 --
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... | 1.507813 | 2 |
server/engine_grs/manager.py | Teddywonseokyoo/-GRS | 0 | 12765449 | import preprocessorV2
import gaugedetectorV2
import colorbalance
import gaugeocr
import sys
import cv2
def main(argv):
path = '/home/pi/GRS/aeye_grs/storage/org_files/'
outfile = ""
imgfile = ""
if len(argv) > 1:
outfile = argv[1]
imgfile = argv[1]
image = cv2.imread(path+imgfile)
cb =... | 2.78125 | 3 |
assignment/assignment/views.py | artemiy312/exness | 1 | 12765450 | from django.shortcuts import render
from assignment.forms import CalculationForm
from assignment.logic import calculate
def calculator(request):
ctx = {}
if request.method == 'POST':
form = CalculationForm(request.POST)
if form.is_valid():
ctx.update(calculate(**form.cleaned_data... | 2.140625 | 2 |