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 |
|---|---|---|---|---|---|---|
application/file/routes.py | h4k1m0u/flask-webapp | 0 | 37800 | <gh_stars>0
from flask import Blueprint, render_template, url_for, redirect
from flask import current_app as app
from .forms import UploadForm
from werkzeug.utils import secure_filename
import os
file_bp = Blueprint('file', __name__,
template_folder='templates', static_folder='static')
@file_bp.... | 2.359375 | 2 |
src/operator/transformer/align.py | k-harada/abstraction-and-reasoning-challenge | 3 | 37801 | <filename>src/operator/transformer/align.py<gh_stars>1-10
from heapq import heappop, heappush
import numpy as np
from src.data import Problem, Case, Matter
from src.operator.mapper.map_connect import MapConnect
def align_xy(x0_arr: np.array, y0_arr: np.array, x1_arr: np.array, y1_arr: np.array, c_arr: np.array) -> np... | 2.109375 | 2 |
python_experiments/paper_figures/tkde/data_legacy/eval_varying_eps_c_pcg.py | RapidsAtHKUST/SimRank | 8 | 37802 | <reponame>RapidsAtHKUST/SimRank
import json
if __name__ == '__main__':
with open('varying_eps_c.dicts') as ifs:
pcg_varying_eps_cpu = eval(ifs.readline())
pcg_varying_eps_mem = eval(ifs.readline())
pcg_varying_c_cpu = eval(ifs.readline())
pcg_varying_c_mem = eval(ifs.readline())
... | 2.40625 | 2 |
mir/tools/utils.py | fenrir-z/ymir-cmd | 1 | 37803 | import logging
import os
import pathlib
import requests
import shutil
from typing import Dict, List, Optional, Union
from PIL import Image, UnidentifiedImageError
from mir import scm
# project
def project_root() -> str:
root = str(pathlib.Path(__file__).parent.parent.parent.absolute())
return root
# mir r... | 2.296875 | 2 |
seniorproject/preprocessing/preprocess_sample.py | teammanicotti/writingstyle | 0 | 37804 | """Preprocessing Sample."""
__author__ = '<NAME>'
def preprocess(req, resp, resource, params): # pylint: disable=unused-argument
"""Preprocess skeleton."""
| 1.695313 | 2 |
Topic08-plots/rp-debt.py | mizydorek/pands-problems-2020 | 0 | 37805 | <reponame>mizydorek/pands-problems-2020
import matplotlib.pyplot as plt
import numpy as np
def main():
rng = np.arange(50)
rnd = np.random.randint(0, 10, size=(3, rng.size))
yrs = 1950 + rng
fig, ax = plt.subplots(figsize=(5, 3))
ax.stackplot(yrs, rng + rnd, labels=['Eastasia', 'Eurasia', 'Oceani... | 3.0625 | 3 |
src/plot_results.py | andrea-gasparini/backdoor-federated-learning | 2 | 37806 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Load in the data
df = pd.read_csv("results.txt", header=None)
df.columns = ["poison_perc", "success_rate", "auc"]
# Plot the data
plt.plot(df['poison_perc'], df['success_rate'], label="Success rate")
plt.plot(df['poison_perc'], df['auc'], label=... | 3.3125 | 3 |
src/richie/apps/courses/migrations/0017_auto_20200827_1011.py | leduong/richie | 174 | 37807 | <reponame>leduong/richie
# Generated by Django 2.2.15 on 2020-08-27 08:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("courses", "0016_auto_20200417_1237"),
]
operations = [
migrations.AlterField(
model_name="courserun",
... | 1.375 | 1 |
proxyclient/experiments/timer_test.py | EricRabil/m1n1 | 1,604 | 37808 | <filename>proxyclient/experiments/timer_test.py
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
import sys, pathlib
sys.path.append(str(pathlib.Path(__file__).resolve().parents[1]))
from m1n1.setup import *
HV_VTMR_CTL = (3, 5, 15, 1, 3)
HV_VTMR_CTL_VMASK = (1 << 0)
HV_VTMR_CTL_PMASK = (1 << 1)
HV_VTMR_LIST = ... | 2.046875 | 2 |
nrf5_mesh/CMake/SES/SESGenerator.py | aberke/city-science-bike-swarm | 15 | 37809 | #!/usr/bin/env python3
# Usage: python SESGenerator.py <target_configuration>.json <output_directory>
#
# <target_configuration>.json is a json file generated from CMake on the form:
# {
# "target": {
# "name": "light_control_client_nrf52832_xxAA_s132_5.0.0",
# "sources": "main.c;provisioner.c;..",... | 1.859375 | 2 |
PythonFIAP/Capitulo5_Manipula_Arquivos/Boston.py | DanielGMesquita/StudyPath | 0 | 37810 | <gh_stars>0
#Análise do relatório de vôos e viagens do aeroporto de Boston com base nos relatórios econômicos oficiais
with open('economic-indicators.csv', 'r') as boston:
total_voos = 0
maior = 0
total_passageiros = 0
maior_media_diaria = 0
ano_usuario = input('Qual ano deseja pesquisar?: ')
#... | 3.921875 | 4 |
source/rttov_test/profile-datasets-py/div52/011.py | bucricket/projectMAScorrection | 0 | 37811 | """
Profile ../profile-datasets-py/div52/011.py
file automaticaly created by prof_gen.py script
"""
self["ID"] = "../profile-datasets-py/div52/011.py"
self["Q"] = numpy.array([ 1.60776800e+00, 5.75602400e+00, 7.00189400e+00,
7.33717600e+00, 6.76175900e+00, 8.41951900e+00,
6.5464... | 1.648438 | 2 |
Tag_17.py | Gravitar64/Advent-of-Code-2015 | 0 | 37812 | <filename>Tag_17.py
from time import perf_counter as pfc
from itertools import combinations
def load_puzzle(datei):
with open(datei) as f:
return [int(x) for x in f]
def solve(puzzle):
part2 = counter = 0
for i in range(1,len(puzzle)):
for v in combinations(puzzle,i):
if sum(v) != 150: continue
... | 2.859375 | 3 |
blog/templatetags/blog_tags.py | josephdubon/boilerplate_dubon_django_blog | 0 | 37813 | from django import template
from django.db.models import Count
from django.utils.safestring import mark_safe
import markdown
from ..models import Post
register = template.Library()
####
# Register as simple tags
####
# A simple template tag that returns the number of posts published so far.=
@register.simple_tag
d... | 2.53125 | 3 |
gpt/config.py | jimth001/formality_emnlp19 | 22 | 37814 | <reponame>jimth001/formality_emnlp19<filename>gpt/config.py
from gpt.src import encoder
text_enc = encoder.get_encoder('./models/117M')
config_path='./models/117M'
| 1.554688 | 2 |
epann/EStool.py | WorldEditors/ProjectNuwa | 0 | 37815 | <gh_stars>0
"""
Tookits for Evolution Strategies
"""
import pickle
import sys
import os
import time
from copy import deepcopy
import numpy
import math
import numpy.random as random
FLOAT_MAX = 1.0e+8
def compute_ranks(x):
"""
Returns rank as a vector of len(x) with integers from 0 to len(x)
"""
asser... | 2.734375 | 3 |
zeppos_root/root.py | changrunner/zeppos_root | 0 | 37816 | <reponame>changrunner/zeppos_root
from pathlib import Path
from os import path
from zeppos_logging.app_logger import AppLogger
class Root:
@staticmethod
def find_root_of_project(current_module_filename,
root_marker_filename_list=[".root", "manage.py", "Pipfile"]):
AppLogge... | 2.3125 | 2 |
weather_board_log.py | petervdb/weather_monitor | 0 | 37817 | <gh_stars>0
#!/usr/bin/python
import SI1132
import BME280
import sys
import time
import os
if len(sys.argv) != 2:
print("Usage: weather_board.py <i2c device file>")
sys.exit()
si1132 = SI1132.SI1132(sys.argv[1])
bme280 = BME280.BME280(sys.argv[1], 0x03, 0x02, 0x02, 0x02)
def get_altitude(pressure, seaLevel):... | 2.78125 | 3 |
UTrackGUI/widgets/video_widget.py | uetke/UTrack | 0 | 37818 | from PyQt5.QtWidgets import QWidget, QHBoxLayout
from pyqtgraph import GraphicsLayoutWidget
import pyqtgraph as pg
class VideoWidget(QWidget):
def __init__(self, parent=None):
super().__init__(parent=parent)
self.layout = QHBoxLayout(self)
# Settings for the image
self.imv = pg.Ima... | 2.625 | 3 |
tablas.py | yakairi/Tienda.py | 0 | 37819 | <filename>tablas.py
# Tienda
CREATE TABLE `cliente` (
`idCliente` int NOT NULL AUTO_INCREMENT,
`nombre` varchar(45) DEFAULT NULL,
`apellido` varchar(45) DEFAULT NULL,
`telefono` varchar(45) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
`ciudad` varchar(45) DEFAULT NULL,
`pais` varchar(45) DEFAULT NULL,
... | 2.28125 | 2 |
Python POO/Getters e Setters/exemplo02/pessoa.py | luccasocastro/Curso-Python | 0 | 37820 | <reponame>luccasocastro/Curso-Python<filename>Python POO/Getters e Setters/exemplo02/pessoa.py
class Pessoa: #substantivo
def __init__(self, nome: str, idade: int) -> None:
self.nome = nome #substantivo
self.idade = idade #substantivo
def dirigir(self, veiculo: str) -> None: #verbos
pri... | 3.3125 | 3 |
tpdatasrc/tpgamefiles/scr/tpModifiers/duelist.py | edoipi/TemplePlus | 69 | 37821 | from templeplus.pymod import PythonModifier
from toee import *
import tpdp
import char_class_utils
import d20_action_utils
###################################################
def GetConditionName():
return "Duelist"
print "Registering " + GetConditionName()
classEnum = stat_level_duelist
preciseStrikeEnum = 2400
#... | 2.15625 | 2 |
bot/__main__.py | ThatFarziGamer/YouNeedSnek | 0 | 37822 | <reponame>ThatFarziGamer/YouNeedSnek
import logging
import datetime
import os
import sys
import yaml
from pathlib import Path
import discord
from discord.ext import commands
def setup_logger() -> logging.Logger:
"""Create and return the root Logger object for the bot."""
LOGDIR = Path('logs')
LOGDIR.mkdi... | 2.6875 | 3 |
sdk/python/pulumi_aws_native/emr/outputs.py | AaronFriel/pulumi-aws-native | 29 | 37823 | <gh_stars>10-100
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. impor... | 1.179688 | 1 |
434-number-of-segments-in-a-string/434-number-of-segments-in-a-string.py | hyeseonko/LeetCode | 2 | 37824 | <reponame>hyeseonko/LeetCode
class Solution:
def countSegments(self, s: str) -> int:
return sum([1 for letter in s.strip().split(" ") if letter]) | 3.390625 | 3 |
riskfolio/RiskFunctions.py | xiaolongguo/Riskfolio-Lib | 2 | 37825 | <gh_stars>1-10
import numpy as np
from scipy.optimize import minimize
from scipy.optimize import Bounds
__all__ = [
"MAD",
"SemiDeviation",
"VaR_Hist",
"CVaR_Hist",
"WR",
"LPM",
"Entropic_RM",
"EVaR_Hist",
"MaxAbsDD",
"AvgAbsDD",
"ConAbsDD",
"MaxRelDD",
"AvgRelDD",
... | 2.78125 | 3 |
qSonify/sonify/song.py | jiosue/qSonify | 0 | 37826 | from midiutil.MidiFile import MIDIFile
import os
def _create_midi_mapping():
""" Create a dictionary that maps note name to midi note integer """
middle_c = 60
notes = "c", "c#", "d", "d#", "e", "f", "f#", "g", "g#", "a", "a#", "b"
equiv = (("c#", "db"), ("d#", "eb"),
("f#", "gb"... | 3.234375 | 3 |
src/fora/connectors/tunnel_dispatcher.py | oddlama/forge | 14 | 37827 | #!/usr/bin/env python3
# pylint: disable=too-many-lines
"""
Provides a stdin/stdout based protocol to safely dispatch commands and return their
results over any connection that forwards both stdin/stdout, as well as some other
needed remote system related utilities.
"""
import errno as sys_errno
import hashlib
import... | 2.15625 | 2 |
events/importer/fill_events_language.py | Anthon98/linkedevents | 1 | 37828 | # -*- coding: utf-8 -*-
import logging
from django import db
from django.conf import settings
from django.core.management import call_command, BaseCommand, CommandError
from django.utils.module_loading import import_string
from django_orghierarchy.models import Organization
from django.db import transaction
from e... | 2.015625 | 2 |
megatron/logging.py | coreweave/gpt-neox | 1 | 37829 | <filename>megatron/logging.py<gh_stars>1-10
# coding=utf-8
# Copyright (c) 2021, EleutherAI contributors
# This file is based on code by the authors denoted below and has been modified from its original version.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in co... | 2.46875 | 2 |
Code/set.py | chelseacastelli/CS-1.3-Core-Data-Structures | 0 | 37830 | from hashtable import HashTable
class Set:
def __init__(self, elements=None):
"""Initialize this new set and add the given elements"""
self.hash_set = HashTable()
if elements is not None:
for element in elements:
self.add(element)
def size(self):
"... | 4.1875 | 4 |
openmdao/solvers/test/test_brent_multicomp.py | naylor-b/OpenMDAO1 | 17 | 37831 | <filename>openmdao/solvers/test/test_brent_multicomp.py<gh_stars>10-100
""" Unit test for the Brent, one variable nonlinear solver. In this case, the
system has multiple components."""
import unittest
from openmdao.api import Group, Problem, Component, Brent, ScipyGMRES
from openmdao.test.util import assert_rel_error... | 2.765625 | 3 |
src/afterpay/merchant.py | nyneava/afterpay-python | 0 | 37832 | from afterpay.attribute_getter import AttributeGetter
from afterpay.exceptions import AfterpayError
class Merchant(AttributeGetter):
"""
Merchant object
Attributes:
redirectConfirmUrl: The consumer is redirected to this URL when the payment process is completed.
redirectCancelUrl: The cons... | 2.703125 | 3 |
src/tou/tou_optimization.py | NREL/EFFORT | 0 | 37833 | <reponame>NREL/EFFORT<filename>src/tou/tou_optimization.py<gh_stars>0
# Standard imports
import os
import logging
import json
# Third-party imports
from pyomo.environ import SolverFactory
import pandas as pd
import matplotlib.pyplot as plt
# Internal imports
#from tou_model import model
from tou.tou_model_price impor... | 1.945313 | 2 |
limonero/util/upload.py | eubr-bigsea/limonero | 1 | 37834 | # -*- coding: utf-8 -*-
import logging
import uuid
from gettext import gettext
from py4j.compat import bytearray2
from urllib.parse import urlparse
from limonero.py4j_init import create_gateway
WRONG_HDFS_CONFIG = gettext(
"Limonero HDFS access not correctly configured (see "
"config 'dfs.client.use.datanode.... | 2.34375 | 2 |
DailyProgrammer/DP20160722C.py | DayGitH/Python-Challenges | 2 | 37835 | """
[2016-07-22] Challenge #276 [Hard] ∞ Loop solver part 2
https://www.reddit.com/r/dailyprogrammer/comments/4u3e96/20160722_challenge_276_hard_loop_solver_part_2/
This is the same challenge as /u/jnazario's excellent [∞ Loop
solver](https://www.reddit.com/r/dailyprogrammer/comments/4rug59/20160708_challenge_274_har... | 2.421875 | 2 |
account/urls.py | bopopescu/storyboard | 0 | 37836 | <filename>account/urls.py
#!/usr/bin/env python
# encoding: utf-8
"""
urls.py
Created by <NAME> on 2012-03-03.
Copyright (c) 2012 Close To U. All rights reserved.
"""
from django.conf.urls import *
from django.contrib.auth import views as auth_views
urlpatterns = patterns('account.views',
(r'^$','index'),... | 1.75 | 2 |
webdriver_setup/opera.py | xloem/webdriver-setup | 1 | 37837 | from selenium import webdriver
from webdriver_manager.opera import OperaDriverManager
from webdriver_setup.driver import DriverBase
class OperaDriver(DriverBase):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def create_driver(self, **kwargs):
"""Create Opera webdriver
... | 2.65625 | 3 |
python/vtool/maya_lib/core.py | louisVottero/vtool | 3 | 37838 | <filename>python/vtool/maya_lib/core.py
# Copyright (C) 2022 <NAME> <EMAIL> All rights reserved.
from __future__ import absolute_import
import os
import string
import traceback
from functools import wraps
from .. import util, util_file
from . import api
from vtool.util import get_log_tabs
in_may... | 1.890625 | 2 |
soap/flopoco/common.py | gitter-badger/soap | 22 | 37839 | import math
import os
import tempfile
from contextlib import contextmanager
from soap import logger
from soap.common.cache import cached
from soap.expression import operators, OutputVariableTuple
from soap.semantics.error import IntegerInterval, ErrorSemantics
flopoco_command_map = {
'IntAdder': ('{wi}', ),
... | 2.09375 | 2 |
coralquant/taskmanage.py | dabuc/CoralQuant | 0 | 37840 | # -*- coding: utf-8 -*-
from coralquant.models.odl_model import BS_Stock_Basic, BS_SZ50_Stocks, TS_Stock_Basic, TS_TradeCal
from coralquant.spider.bs_stock_basic import get_stock_basic
from coralquant import logger
from datetime import date, datetime, timedelta
from sqlalchemy import MetaData
from coralquant.database i... | 2.125 | 2 |
Scripts13/Script104.py | jonfisik/ScriptsPython | 1 | 37841 | '''Exercício Python 104: Crie um programa que tenha a função leiaInt(), que vai funcionar de forma semelhante 'a função input() do Python, só que fazendo a validação para aceitar apenas um valor numérico.
Ex: n = leiaInt('Digite um n: ')'''
def leiaInt(msg):
ok = False
valor = 0
while True:
n = str... | 4.125 | 4 |
pgctl/timestamp.py | struys/pgctl | 0 | 37842 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
Format stolen from daemontools' tai64nlocal:
2015-10-19 17:43:37.772152500
We'd usually use the s6 tool, but there's a problem:
http://www.mail-archive.com/skaware@list.skarnet.org/msg00575.html
"""
from __future__ import absolute_import
from __future__ import print_fun... | 2.09375 | 2 |
scripts/Figures and Videos/Figure 2D/produce_fig_2D.py | jfaccioni/clovars | 0 | 37843 | <reponame>jfaccioni/clovars
from pathlib import Path
import random
import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from clovars.main import main as clovars_main
sns.set()
RANDOMNESS_SEED = 42
def main():
"""Main function of this script."""
random.seed... | 2.703125 | 3 |
numba_celltree/geometry_utils.py | Huite/numba_celltree | 2 | 37844 | <reponame>Huite/numba_celltree
from typing import Sequence, Tuple
import numba as nb
import numpy as np
from .constants import (
FILL_VALUE,
NDIM,
PARALLEL,
TOLERANCE_ON_EDGE,
Box,
FloatArray,
FloatDType,
IntArray,
Point,
Vector,
)
from .utils import allocate_box_polygon, alloc... | 2.65625 | 3 |
Study/src/com/company/test/favorite_languages.py | guptasuresh2004/python_handson | 0 | 37845 | <reponame>guptasuresh2004/python_handson<gh_stars>0
from collections import OrderedDict
favorite_languages = OrderedDict()
favorite_languages["Suresh"]="python"
favorite_languages["Kumar"]="Java"
favorite_languages["Gupta"]="c"
for key in favorite_languages.keys():
print(key+" like to use :"+favorite_languages[key... | 3.125 | 3 |
demo_zinnia_wordpress/__init__.py | django-blog-zinnia/wordpress2zinnia | 7 | 37846 | <reponame>django-blog-zinnia/wordpress2zinnia
"""Demo of Zinnia with wordpress import"""
| 0.894531 | 1 |
helper.py | vanashimko/discrete-fourier-transform | 1 | 37847 | <filename>helper.py
from itertools import repeat
from random import randrange
def randoms_from(values, length=None):
_range = range(length) if length is not None else repeat(0)
values_len = len(values)
for _ in _range:
yield values[randrange(0, values_len)]
| 3.296875 | 3 |
azure/cart_svc_serverless/getCartTotal/__init__.py | ishrivatsa/lambda-samples | 0 | 37848 | <gh_stars>0
import logging
import os
from os import environ
import redis
import json
import azure.functions as func
redisHost= ""
redisPort = 6379
redisPassword = ""
def connectRedis(host, port, password):
try:
logging.info("Connecting to Redis ")
redisConnection = redis.StrictRedis(... | 2.578125 | 3 |
resources/files/__init__.py | vishu221b/bookme-flask-REST-API-Collection | 0 | 37849 | <gh_stars>0
from .documentFileUpload import DocumentFileUploadResource
from .documentFileDownload import DocumentFileDownloadResource
| 1.085938 | 1 |
src/waldur_core/core/api_groups_mapping.py | ahti87/waldur-mastermind | 0 | 37850 | API_GROUPS = {
'authentication': ['/api-auth/', '/api/auth-valimo/',],
'user': ['/api/users/', '/api/user-invitations/', '/api/user-counters/',],
'organization': [
'/api/customers/',
'/api/customer-permissions-log/',
'/api/customer-permissions-reviews/',
'/api/customer-permis... | 1.054688 | 1 |
python/345.py | kylekanos/project-euler-1 | 0 | 37851 | <filename>python/345.py
#!/usr/bin/env python
s="""
7 53 183 439 863 497 383 563 79 973 287 63 343 169 583
627 343 773 959 943 767 473 103 699 303 957 703 583 639 913
447 283 463 29 23 487 463 993 119 883 327 493 423 159 743
217 623 3 399 853 407 103 983 89 463 290 516 212 462 350
960 376 682 962 300 780 486 502 912 8... | 2.78125 | 3 |
utils/logger.py | awesome-archive/deep-q-learning | 1 | 37852 | from tensorboardX import SummaryWriter
class Logger:
def __init__(self, log_dir):
self.env_name = 'Pong-v0'
# TensorBoard
self.writer = SummaryWriter(log_dir=log_dir)
# Episode Values
self.ep = 0
self.ep_rewards = []
self.ep_max_reward = 0.0
self.ep... | 2.25 | 2 |
docs/html_docs/manual/notebook_to_markdown.py | jtran10/pyNastran | 0 | 37853 | from __future__ import print_function
import os
import shutil
import pyNastran
from pyNastran.utils import print_bad_path
pkg_path = pyNastran.__path__[0]
def create_rst_from_ipython_notebooks():
#curdir = os.getcwd()
notebook_dir = os.path.join(pkg_path, '..', 'docs', 'quick_start', 'demo')
pydocs_dir =... | 2.359375 | 2 |
src/generator_ui.py | WillMorrison/JouleQuest | 0 | 37854 | import pygame
import pygame_gui
from rules_python.python.runfiles import runfiles
class GeneratorWindow(pygame_gui.elements.ui_window.UIWindow):
def __init__(self, position, ui_manager, generator):
super().__init__(pygame.Rect(position, (320, 120)), ui_manager,
window_display_tit... | 2.515625 | 3 |
compliance_suite/functions/update_server_settings.py | alextsaihi/rnaget-compliance-suite | 1 | 37855 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""Module compliance_suite.functions.update_server_settings.py
Functions to update server config/settings based on the response of a previous
API request. Each function should accept a Runner object and modify its
"retrieved_server_settings" attribute
"""
def update_supported_f... | 2.5625 | 3 |
rnacentral_pipeline/rnacentral/ftp_export/fasta.py | RNAcentral/rnacentral-import-pipeline | 1 | 37856 | # -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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... | 2.75 | 3 |
setup.py | RicoViking9000/profanityfilter | 63 | 37857 | <reponame>RicoViking9000/profanityfilter
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
setup(
name='profanityfilter',
version='2.0.6.',
description='A universal Python library for detecting and/or filtering profane word... | 1.703125 | 2 |
src/boids_core/boids.py | v-hill/advanced-computational-physics | 0 | 37858 | """
This script contains the code implementing my version of the Boids artificial
life programme.
"""
# ---------------------------------- Imports ----------------------------------
# Allow imports from parent folder
import sys, os
sys.path.insert(0, os.path.abspath('..'))
# Standard library imports
impor... | 3.15625 | 3 |
chateau/session/session.py | softwerks/chateau | 0 | 37859 | # Copyright 2021 Softwerks 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 agreed to in writing... | 2.34375 | 2 |
RDS/Service.py | Sciebo-RDS/py-research-data-services-common | 0 | 37860 | from .Token import Token, OAuth2Token
from .User import User
from .Informations import LoginMode, FileTransferMode, FileTransferArchive
from urllib.parse import urlparse, urlunparse
import requests
import json
from datetime import datetime, timedelta
from typing import Union
import logging
import mimetypes
import base6... | 2.28125 | 2 |
mBusi/serializers.py | hellohufan/beautyServer | 0 | 37861 | <filename>mBusi/serializers.py
from rest_framework import serializers
from ic_shop import models as model
from django.contrib.auth import get_user_model
from mBusi import settings as setting
from django.http import request
User = get_user_model()
class LoginSerializer(serializers.ModelSerializer):
username = se... | 2.28125 | 2 |
Python/alexandrian_integers.py | chathu1996/hacktoberfest2020 | 71 | 37862 | <gh_stars>10-100
import itertools
import sys
# The numbers are of the form p(p+d)(p+(p^2+1)/d), where d runs over divisors
# of p^2+1 and p runs over all positive integers.
class Problem():
def __init__(self):
self.bound = 100000
self.primes = []
self._sieve()
def _sieve(sel... | 2.84375 | 3 |
src/myastro/orb_deter.py | benitocm/practical-astronomy | 0 | 37863 | <gh_stars>0
"""
This module contains functions related to orbit calculations
"""
# Standard library imports
from typing import Any,Dict,List,Tuple,Sequence
#https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html
from functools import partial
from math import isclose
import sys
from io import StringIO
... | 2.15625 | 2 |
process.py | SuperMaxine/Gaze_Tracking_Exp | 0 | 37864 | # -*- coding: UTF-8 -*-
"""
opencv实现人脸识别
参考:
1、https://github.com/opencv/opencv/tree/master/data/haarcascades
2、http://www.cnblogs.com/hanson1/p/7105265.html
"""
import cv2
def detect_face(image):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
'''
# 获取人脸识别训练数据
对于人脸特征的一些描述,opencv在读取完数据后很据训练中的样品数据,... | 3 | 3 |
userbot/modules/warn.py | akborana/Devil | 1 | 37865 | <reponame>akborana/Devil
import re
import hashlib
import asyncio
import datetime
import logging
from userbot import CMD_HELP
import os
import math
import html
import os.path
import sys
import time
from typing import Tuple, Union
from userbot import bot
from telethon import errors
from telethon import events
from telet... | 1.992188 | 2 |
eis_pointing/eis_aia_registration.py | gpelouze/eis_pointing | 3 | 37866 | #!/usr/bin/env python3
import datetime
import os
import warnings
import numpy as np
import scipy.interpolate as si
import matplotlib as mpl
from matplotlib.backends import backend_pdf
import matplotlib.pyplot as plt
from .utils import aia_raster
from .utils import cli
from .utils import eis
from .utils import num
f... | 2.203125 | 2 |
src/olympia/accounts/urls.py | mstriemer/olympia | 0 | 37867 | <reponame>mstriemer/olympia
from django.conf.urls import include, url
from rest_framework.routers import SimpleRouter
from rest_framework_nested.routers import NestedSimpleRouter
from olympia.reviews.views import ReviewViewSet
from . import views
accounts = SimpleRouter()
accounts.register(r'account', views.Account... | 1.828125 | 2 |
plotting/plotly.py | TPei/jawbone_visualizer | 0 | 37868 | <gh_stars>0
__author__ = 'TPei'
from plotting.plotly.graph_objs import *
from data.DataHandler import get_all_the_data
"""
Working with the plotly api to create more interactive diagrams
"""
def sleep():
data = get_all_the_data()
traces = []
categories = ['bed', 'sleep', 'sound', 'light', 'awake', '... | 2.734375 | 3 |
faddr/database.py | kido5217/faddr | 1 | 37869 | <reponame>kido5217/faddr
from tinydb import TinyDB
# TODO: redo this, maybe use SQL
class Database:
def __init__(self, db_file):
"""Create database file, erase previous one if exists."""
self.db = TinyDB(db_file)
# TODO: implement db files rotation, for now just replace all data
se... | 2.9375 | 3 |
passing/HelloWorld/test_hello.py | RubenRubens/cq-testing | 0 | 37870 | import unittest
class TestHelloWorld(unittest.TestCase):
# Import and validate HW1
def test_HW1(self):
import HelloWorld.HW1
global R1
R1 = HelloWorld.HW1.result
self.assertTrue(R1.val().isValid())
# Import and validate HW2
def test_HW2(self):
import HelloWorld... | 3.265625 | 3 |
examples/cifar10.py | Fragile-azalea/homura | 1 | 37871 | <gh_stars>1-10
import hydra
import torch
import torch.nn.functional as F
from homura import optim, lr_scheduler, callbacks, reporters, trainers
from homura.vision.data import vision_loaders
from homura.vision.models.classification import resnet20, wrn28_10
@hydra.main('config/cifar10.yaml')
def main(cfg):
model ... | 1.90625 | 2 |
payments/domain/tests/test_paypal_payment.py | anandrgit/snet-marketplace-service | 0 | 37872 | import unittest
from unittest.mock import patch, Mock
from payments.domain.paypal_payment import PaypalPayment
class TestPaypal(unittest.TestCase):
@patch("paypalrestsdk.Payment", return_value=Mock(links=[Mock(rel="approval_url", href="url")],
id="PAYID-123",... | 3.046875 | 3 |
software-defined-networks/Topo2.py | hasithsen/CSNE | 0 | 37873 | <gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Create below topology in Mininet.
[c1]
/\
/ \
/ \
/ \
[s1]--------[s2]
/\ /\
[h1] [h2] [h3] [h4]
[cX] - controller
[sX] - switch
[hX] - host
"""
from mininet.n... | 2.421875 | 2 |
pymap/bytes/__init__.py | BoniLindsley/pymap | 0 | 37874 | """Defines useful types and utilities for working with bytestrings."""
from __future__ import annotations
import zlib
from abc import abstractmethod, ABCMeta
from collections.abc import Iterable, Sequence
from io import BytesIO
from itertools import chain
from typing import cast, final, Any, Final, TypeVar, SupportsB... | 3.03125 | 3 |
_solutions/pandas/dataframe/pandas_df_sample_a.py | sages-pl/2022-01-pythonsqlalchemy-aptiv | 0 | 37875 | <reponame>sages-pl/2022-01-pythonsqlalchemy-aptiv
df = pd.read_csv(DATA)
df = df.sample(frac=1.0)
df.reset_index(drop=True, inplace=True)
result = df.tail(n=10)
| 2.65625 | 3 |
Informatik1/Midterms Prep/midterms hs19/to_binary.py | Queentaker/uzh | 8 | 37876 | def to_binary(number):
binarynumber=""
if (number!=0):
while (number>=1):
if (number %2==0):
binarynumber=binarynumber+"0"
number=number/2
else:
binarynumber=binarynumber+"1"
number=(number-1)/2
else:
bi... | 4.125 | 4 |
coursework1/task6/reducer.py | foundnet/UOE_EP_coursework1 | 0 | 37877 | <gh_stars>0
#!/usr/bin/python
import sys
import math
prev_key = ""
hresult = 0.0
totalcnt = 0
cntlist = []
for line in sys.stdin:
key,info = line.strip().split("\t",1)
if key != prev_key:
if prev_key != "":
hresult = 0.0
cntlist = strinfo.split(",")
cntlist = map(int,... | 2.796875 | 3 |
opmd_viewer/__init__.py | soerenjalas/openPMD-viewer | 0 | 37878 | # Make the OpenPMDTimeSeries object accessible from outside the package
from .openpmd_timeseries import OpenPMDTimeSeries, FieldMetaInformation
__all__ = ['OpenPMDTimeSeries', 'FieldMetaInformation']
| 1.3125 | 1 |
utilities/send_custom_mail.py | stefanos90/Utilities | 3 | 37879 | <reponame>stefanos90/Utilities<filename>utilities/send_custom_mail.py
# In order to use this function you have to create a Django project
from django.conf import settings
from django.template import Context
from django.template.loader import render_to_string, get_template
from django.core.mail import EmailMultiAlterna... | 2.640625 | 3 |
farmrisk_needs.py | chum8/farmrisk.v2 | 0 | 37880 | <reponame>chum8/farmrisk.v2
# this class exists to extract data from a csv file
# and return it formatted for persistence into a MySql database
# import needed libraries
import csv
from farmrisk_lib import *
# define Product class
class Need():
# def __init__(self):
#----data functions----#
... | 3.171875 | 3 |
torchrl/agents/ddpg_agent.py | srikarym/torchrl | 3 | 37881 | <gh_stars>1-10
from copy import deepcopy
import numpy as np
import torch.nn.functional as F
from torch import nn
from torch.optim import Adam
from .base_agent import BaseAgent
from ..policies import OUNoise
from ..models import DDPGActorNet, DDPGCriticNet
def polyak_average_(source, target, tau=1e-3):
"""
In-pla... | 2.109375 | 2 |
model.py | Pontohi/GoIndex | 0 | 37882 | #A template for when we actually build the model.
import numpy as np
from sklearn.model_selection import train_test_split
from tensorflow.keras.layers import Dense, LSTM, Dropout
from tensorflow.keras import Sequential
categories = [] #List out category string names here
reproducibility = 7 #Constant seed for reproduci... | 3.109375 | 3 |
tf_coder/value_search/search_space_from_weight.py | hstrohm/PyTorch-Coder-cheat | 245 | 37883 | <reponame>hstrohm/PyTorch-Coder-cheat<gh_stars>100-1000
# Copyright 2021 The TF-Coder 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... | 2.109375 | 2 |
train.py | tamasandacian/twitter-sentiment-analysis | 1 | 37884 | # Create FastText model using from raw train data
import fastText
TRAIN_FILE = './datasets/raw_data/tweets.train'
su_model = fastText.train_supervised(input=TRAIN_FILE, wordNgrams=3)
su_model.save_model('model_sentiment.bin') | 2.265625 | 2 |
test.py | Carmen0645/stylegan-jt | 1 | 37885 | <filename>test.py<gh_stars>1-10
import numpy as np
import math
import jittor as jt
from model.model import StyledGenerator
jt.flags.use_cuda = True
import argparse
import pathlib
import os
@jt.no_grad()
def style_mixing(generator, step, mean_style, n_source, n_target):
source_code = jt.randn(n_source, 512)
tar... | 1.898438 | 2 |
snippets/urls.py | rudra012/django_rest | 0 | 37886 | <reponame>rudra012/django_rest
from django.conf.urls import url
from api.snippets import snippets_api
urlpatterns = [
url(r'^$', snippets_api.snippet_list),
url(r'^(?P<pk>[0-9]+)/$', snippets_api.snippet_detail),
]
| 1.90625 | 2 |
models/peak.py | anva-kn/ramanflow | 0 | 37887 | <reponame>anva-kn/ramanflow<gh_stars>0
import numpy as np
from dataclasses import dataclass, field
from spectrum_component import SpectrumComponent
from scipy.optimize import minimize
from typing import List, Optional
@dataclass
class Peak(SpectrumComponent):
__beta_fit: np.ndarray = field(init=False)
__yhat... | 2.40625 | 2 |
backend/media/migrations/0010_auto_20210613_0444.py | LakesideMiners/rt911 | 8 | 37888 | # Generated by Django 3.1.12 on 2021-06-13 04:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('media', '0009_auto_20210611_1441'),
]
operations = [
migrations.RemoveField(
model_name='collection',
name='media_i... | 1.484375 | 1 |
aioinflux/compat.py | slazarov/aioinflux | 0 | 37889 | import warnings
no_pandas_warning = "Pandas/Numpy is not available. Support for 'dataframe' mode is disabled."
no_redis_warning = "Redis dependencies not available. Support for caching is disabled."
try:
import pandas as pd
import numpy as np
except ModuleNotFoundError:
pd = None
np = None
warning... | 1.953125 | 2 |
station/controller/handlers/read_letters_handler.py | GLO3013-E4/COViRondelle2021 | 0 | 37890 | import json
import rospy
from std_msgs.msg import String
from handlers.handler import Handler
from mapping.command_panel import CommandPanel
from mapping.resistance import Resistance
class ReadLettersHandler(Handler):
def initialize(self):
self.sub = rospy.Subscriber('letters', String, self.read_letters)... | 2.5 | 2 |
python/testData/editing/enterAfterColonOfCaseClauseWithoutBody.py | 06needhamt/intellij-community | 0 | 37891 | <reponame>06needhamt/intellij-community
match x:
case 42:<caret> | 0.902344 | 1 |
Fundamentos/variables.py | ijchavez/python | 0 | 37892 | <filename>Fundamentos/variables.py
x = 5
y = 3
z = x + y
print(x)
print(y)
print(x + y)
print(z)
w = z
print(w) | 2.546875 | 3 |
gisimulation/interferometer/gratings.py | mariabuechner/gi_simulation | 0 | 37893 | """
@author: buechner_m <<EMAIL>>
"""
import sys
sys.path.append('..') # To allow importing from neighbouring folder
import simulation.materials as materials
import logging
logger = logging.getLogger(__name__)
class Grating(object):
"""
Parent class for gratings.
Parameters
==========
pitch: g... | 2.71875 | 3 |
Exercicios/Todos/ex049.py | Edson921/exerciciosResolvidos | 0 | 37894 | #Calculadora de tabuada
n = int(input('Deseja ver tabuada de que numero?'))
for c in range(1, 13):
print('{} X {:2}= {} '. format(n, c, n * c))
| 3.921875 | 4 |
rede/eevc/models/RegistroTotalizadorMatriz.py | marcioinfo/edi_reader | 0 | 37895 | COLUMNS = [
'tipo_registro',
'nro_pv_matriz',
'vl_total_bruto',
'qtde_cvnsu',
'vl_total_rejeitado',
'vl_total_rotativo',
'vl_total_parcelado_sem_juros',
'vl_total_parcelado_iata',
'vl_total_dolar',
'vl_total_desconto',
'vl_total_liquido',
'vl_total_gorjeta',
'vl_total... | 1.164063 | 1 |
openslides_backend/action/action_handler.py | r-peschke/openslides-backend | 0 | 37896 | from copy import deepcopy
from typing import Dict, Iterable, List, Optional, Tuple, Union
import fastjsonschema
from ..shared.exceptions import ActionException, DatastoreException, EventStoreException
from ..shared.handlers.base_handler import BaseHandler
from ..shared.interfaces.write_request_element import WriteReq... | 1.9375 | 2 |
2020/examples-in-class-2020-10-22/list_vs_dictionary1.py | ati-ozgur/course-python | 1 | 37897 | # Ask user to enter their country name.
# print out their phone code.
l_country_phone_code = ["China","86","Germany","49","Turkey","90"]
def country_name_to_phone_code_list(country_name):
for index in range(len(l_country_phone_code)):
if l_country_phone_code[index] == country_name:
return l_country_phone_code[... | 4.03125 | 4 |
defects_dlmbl/disc_loss.py | bbarad/defects_DLMBL | 0 | 37898 | <reponame>bbarad/defects_DLMBL
import torch
from torch import nn
import torch.nn.functional as F
class DiscriminativeLoss(nn.Module):
""" This class computes the loss
The process happens in two steps:
1) we compute hungarian assignment between ground truth boxes and the outputs of the model
2) ... | 2.484375 | 2 |
tests/test_cache.py | cdusold/DriveLink | 0 | 37899 | import unittest as ut
from tests._utils._timer import Timer
from drivelink import cached
#from Process import freeze_support
def uncachedFib(a):
if a in [0, 1]:
return a
if a < 0:
raise Exception("Reverse fibonacci sequence not implemented.")
return uncachedFib(a - 1) + uncachedFib(a - 2)... | 2.84375 | 3 |