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 |
|---|---|---|---|---|---|---|
src/tests/test_inputCheck.py | retsilagracias/horoscope-cli | 0 | 41100 | <filename>src/tests/test_inputCheck.py<gh_stars>0
from horoscopecli.inputCheck import validInputCategoryOption, validInputSign, validInputDateOption
def test_belier_validInputSign():
resultWithoutAccent = validInputSign("belier")
resultWithAccent = validInputSign("bélier")
assert resultWithAccent[0] == Tru... | 2.703125 | 3 |
r_freeze/cli.py | tullur/r_freeze | 1 | 41101 | """Console script for r_freeze."""
import argparse
import sys
from r_freeze.r_freeze import get_packages, write_package_file
def main():
"""Console script for r_freeze."""
parser = argparse.ArgumentParser()
parser.add_argument("dir", type=str, help="Directory to look for")
parser.add_argument(
... | 3.171875 | 3 |
develop/models/Token.py | zero-shubham/permissions_system | 4 | 41102 | import sqlalchemy
from application import metadata
Token = sqlalchemy.Table(
"tokens",
metadata,
sqlalchemy.Column("user_id", sqlalchemy.ForeignKey(
'_ps_users.id', ondelete="CASCADE"), primary_key=True),
sqlalchemy.Column("token", sqlalchemy.String(length=1000),
nullable... | 2.5625 | 3 |
deep_recommend/recommend/ctr/fm/fm.py | yingxinff-source/DeepRecSys | 0 | 41103 | <filename>deep_recommend/recommend/ctr/fm/fm.py
"""
@Description: Factorization Machines
@version:
@License: MIT
@Author: <NAME>
@Date: 2020-12-03 18:01:05
@LastEditors: <NAME>
@LastEditTime: 2020-12-03 20:33:26
"""
import tensorflow as tf
from tensorflow.keras.layers import Layer
from tensorflow.keras.models import M... | 2.125 | 2 |
pyirf/irf/background.py | jsitarek/pyirf | 6 | 41104 | import astropy.units as u
import numpy as np
from ..utils import cone_solid_angle
#: Unit of the background rate IRF
BACKGROUND_UNIT = u.Unit('s-1 TeV-1 sr-1')
def background_2d(events, reco_energy_bins, fov_offset_bins, t_obs):
"""
Calculate background rates in radially symmetric bins in the field of view.... | 2.8125 | 3 |
flaskapp1.py | aamazie/RSSReader1 | 0 | 41105 | <gh_stars>0
import feedparser, redis
from flask import Flask, render_template
from flask_caching import Cache
config = {
"DEBUG": False, # some Flask specific configs
"CACHE_TYPE": "redis", # Flask-Caching related configs
"CACHE_DEFAULT_TIMEOUT": 300
}
app = Flask(__name__)
app.config.fr... | 2.578125 | 3 |
rex/rechunk_h5/__init__.py | psusmars/rex | 8 | 41106 | <reponame>psusmars/rex<filename>rex/rechunk_h5/__init__.py
# -*- coding: utf-8 -*-
"""
.h5 rechunking tool
"""
from .chunk_size import ArrayChunkSize, TimeseriesChunkSize
from .combine_h5 import CombineH5
from .rechunk_h5 import RechunkH5, get_dataset_attributes
| 1.007813 | 1 |
db/one_hour_candle_db.py | SpiralDevelopment/RSI-divergence-detector | 7 | 41107 | import pymysql
import pandas as pd
import logging
import traceback
logger = logging.getLogger(__name__)
TABLE_CANDLE_PATTERN = "CREATE TABLE IF NOT EXISTS {table}(" \
" id int(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, " \
" time DATETIME UNIQUE," \
... | 2.796875 | 3 |
etc/ChokudaiSpeedrun002/f.py | wotsushi/competitive-programming | 3 | 41108 | <filename>etc/ChokudaiSpeedrun002/f.py<gh_stars>1-10
N = int(input())
A, B = (
zip(*(map(int, input().split()) for _ in range(N))) if N else
((), ())
)
ans = len({(min(a, b), max(a, b)) for a, b in zip(A, B)})
print(ans)
| 2.6875 | 3 |
app/serializer.py | james-muriithi/django-api | 0 | 41109 | <reponame>james-muriithi/django-api
from rest_framework import serializers
from .models import News, User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
exclude = ['password']
class NewsSerializer(serializers.ModelSerializer):
user = UserSerializer(read_only=True... | 2.28125 | 2 |
edmunds/profiler/drivers/basedriver.py | LowieHuyghe/edmunds-python | 4 | 41110 |
from edmunds.globals import abc, ABC
class BaseDriver(ABC):
"""
The base driver for profiler-drivers
"""
def __init__(self, app):
"""
Initiate the instance
:param app: The application
:type app: Edmunds.Application
... | 2.734375 | 3 |
circles/migrations/0014_auto_20200506_2128.py | CoronaCircles/coronacircles | 1 | 41111 | <filename>circles/migrations/0014_auto_20200506_2128.py
# Generated by Django 3.0.6 on 2020-05-06 19:28
from django.conf import settings
from django.db import migrations, models
def create_through_relations(apps, schema_editor):
Event = apps.get_model("circles", "Event")
Participation = apps.get_model("circl... | 1.96875 | 2 |
tests/test_application.py | aibotsoft/python-micro-template | 0 | 41112 | <reponame>aibotsoft/python-micro-template
import pytest
from starlette.testclient import TestClient
from main import app
client = TestClient(app)
@pytest.mark.parametrize(
"path,expected_status,expected_response",
[
("/api_route", 200, {"message": "Hello World"}),
("/non_decorated_route", 20... | 2.4375 | 2 |
test.py | tesaho/vehicle_tracking | 3 | 41113 | <gh_stars>1-10
from __future__ import division
from models import Darknet
from utils.utils import *
from utils.data_loader import *
from utils.parse_config import *
from terminaltables import AsciiTable
import os
import time
import argparse
import json
import pandas as pd
import torch
from torch.utils.data import Dat... | 1.976563 | 2 |
src/secrets.template.py | Inciclopedia/status-monitors | 0 | 41114 | <reponame>Inciclopedia/status-monitors<filename>src/secrets.template.py
URLS = [
"url1"
]
STATUSPAGE_API_KEY = ""
STATUSPAGE_PAGE_ID = ""
STATUSPAGE_METRICS = {
"url": "metric_id"
}
STATUSPAGE_COMPONENTS = {
"url": "component_id"
}
PING_WEBHOOKS = []
STATUS_WEBHOOKS = []
ESCALATION_IDS = []
POLL_TIME = 60
O... | 1.242188 | 1 |
app.py | andrequeiroz2/api-tags | 0 | 41115 | <gh_stars>0
import os
from flask import Flask
from tags import database
from tags.api.tags.tags_route import init_tags_api
from flask_restful import Api
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = 'todo-api/api-tags:1.0'
app.config['MONGODB_SETTINGS'] = {
'db': 'tags'... | 2.046875 | 2 |
venv/Lib/site-packages/pymessenger/bot.py | shivamsahni/Bot-to-live | 0 | 41116 | import json
import requests
from requests_toolbelt import MultipartEncoder
from pymessenger.graph_api import FacebookGraphApi
import pymessenger.utils as utils
class Bot(FacebookGraphApi):
def __init__(self, *args, **kwargs):
super(Bot, self).__init__(*args, **kwargs)
def send_text_message(self, r... | 2.765625 | 3 |
tests/test_delete.py | ppinard/dataclasses-sql | 4 | 41117 | """"""
# Standard library modules.
# Third party modules.
import pytest
import sqlalchemy
# Local modules.
import dataclasses_sql
# Globals and constants variables.
@pytest.fixture
def metadata():
engine = sqlalchemy.create_engine("sqlite:///:memory:")
return sqlalchemy.MetaData(engine)
def test_delete_... | 2.171875 | 2 |
codigo/Live171/exemplo_04.py | BrunoPontesLira/live-de-python | 572 | 41118 | <gh_stars>100-1000
d = {'a': 1, 'c': 3}
match d:
case {'a': chave_a, 'b': _}:
print(f'chave A {chave_a=} + chave B')
case {'a': _} | {'c': _}:
print('chave A ou C')
case {}:
print('vazio')
case _:
print('Não sei')
| 2.859375 | 3 |
vb2py/PythonCard/samples/multicolumnexample/multicolumnexample.rsrc.py | ceprio/xl_vb2py | 0 | 41119 | <filename>vb2py/PythonCard/samples/multicolumnexample/multicolumnexample.rsrc.py
{ 'application':{ 'type':'Application',
'name':'MulticolumnExample',
'backgrounds':
[
{ 'type':'Background',
'name':'bgMulticolumnExample',
'title':'Multicolumn Example PythonCard Application',
'size':( 62... | 1.960938 | 2 |
Data_Science/grafico-bar-evitar.py | maledicente/cursos | 1 | 41120 | <filename>Data_Science/grafico-bar-evitar.py<gh_stars>1-10
from matplotlib import pyplot as plt
mentions = [500, 505]
years = [2013, 2014]
plt.bar([2012.6, 2013.6], mentions, 0.8)
plt.xticks(years)
plt.ylabel("# de vezes que ouvimos alguém dizer 'data science'")
plt.ticklabel_format(useOffset=False)
plt.axis([2012.... | 3 | 3 |
tests/_utils/uniqueue.py | ssfdust/smorest-sfs | 8 | 41121 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import annotations
import queue
from typing import TYPE_CHECKING, TypeVar
T = TypeVar("T")
if TYPE_CHECKING:
SimpleQueue = queue.SimpleQueue
else:
class FakeGenericMeta(type):
def __getitem__(self, item):
return self
clas... | 2.75 | 3 |
udp-client.py | fionahiklas/udp-broadcast-examples | 0 | 41122 | <filename>udp-client.py<gh_stars>0
import socket, traceback
host = '255.255.255.255' # Bind to all interfaces
port = 2081
print "Creating socker on port: ", port
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#print "Setting REUSEADDR option"
#s.setsockopt(socket.SOL_SOCKET, socke... | 2.78125 | 3 |
tournament.py | maxhuebner/scrim-tool | 1 | 41123 | <filename>tournament.py<gh_stars>1-10
import requests
import os
from dotenv import load_dotenv
load_dotenv()
RITO_API = os.getenv('RITO_API')
def get_summ_id(summoner_name, region="euw1"):
URL = f"https://{region}.api.riotgames.com/lol/summoner/v4/summoners/by-name/{summoner_name}?api_key={RITO_API}"
r = re... | 2.515625 | 3 |
imdb_id.py | chethan25/tv-series-file-renamer | 0 | 41124 | <filename>imdb_id.py<gh_stars>0
# -*- coding: utf-8 -*-
"""
Module to get imdb id of the tv series using omdbapi
"""
import json
import requests
from main import tv_series_name
# Omdbapi website url
url = f'https://www.omdbapi.com/?t={tv_series_name}&apikey=<KEY>'
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Ubu... | 3.21875 | 3 |
web/tracker/models.py | webisteme/punkmoney | 1 | 41125 | from django.db import models
class events(models.Model):
id = models.AutoField(primary_key=True)
note_id = models.BigIntegerField(null=True, blank=True)
tweet_id = models.BigIntegerField()
type = models.IntegerField(null=True, blank=True)
timestamp = models.DateTimeField()
from_user = models.Ch... | 2.046875 | 2 |
scanner/sample_port_scanner.py | andradjp/hacktools | 0 | 41126 | #! /usr/bin/python3
"""
__Version__: 0.1
__Author__: <NAME>
Data: 15/02/2020
Description: Sample scrip for scan host ports with only buit-in functions
This code just works with addresses of v4 family.
Python 3.x
"""
# Import modules
import socket
import sys
import errno
import os
import argparse
import ipaddress
# M... | 3.21875 | 3 |
Python_Network_Automation_II/chapter15_codes/print_hello_friend.py | yasser296/Python-Projects | 0 | 41127 | #print_hello_friend.py
from datetime import datetime
print(datetime.now())
print("G'day Mate!")
| 2.703125 | 3 |
kamera.py | ThomasHangstoerfer/pyHomeCtrl | 0 | 41128 | <gh_stars>0
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
import time
Builder.load_string('''
<CameraClick>:
orientation: 'vertical'
Camera:
id: camera
resolution: (640, 480)
play: False
ToggleButton:
text: 'Play'
on_... | 2.84375 | 3 |
sionna/channel/apply_time_channel.py | NVlabs/sionna | 163 | 41129 | <filename>sionna/channel/apply_time_channel.py
#
# SPDX-FileCopyrightText: Copyright (c) 2021-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
"""Layer for applying channel responses to channel inputs in the time domain"""
import tensorflow as tf
import numpy as np
i... | 2.71875 | 3 |
yolox_backbone/utils/utils.py | developer0hye/YOLOX-Backbone | 20 | 41130 | from urllib import request
def download_from_url(url, filename):
request.urlretrieve(url, filename) | 2.46875 | 2 |
testfore.py | eearrth/projectTelecom-4T | 0 | 41131 | <reponame>eearrth/projectTelecom-4T
import time
import numpy as np
import pickle
from numpy import *
from matplotlib import *
from scipy.io import *
from sklearn.metrics import mean_squared_error
from pylab import *
t = time.time()
from itertools import chain
# function Normalize
#seterr(divide='ignore', invalid='ignor... | 2.3125 | 2 |
boxplots.py | wrightaprilm/plaus | 0 | 41132 | <filename>boxplots.py
import pandas as pd
import os
import re
import dendropy
from dendropy.utility.fileutils import find_files
import matplotlib.pyplot as plt
plt.style.use('ggplot')
default = pd.read_csv('./d.csv')
uniform = pd.read_csv('./1.csv')
exp = pd.read_csv('./e.csv')
fixed = pd.read_csv('./2.csv')
uniform.... | 2.359375 | 2 |
src/transitions/sudden.py | Addono/TekniBridge | 0 | 41133 | from typing import List
from led import Led
from transitions import AbstractTransition
class Sudden(AbstractTransition):
def __init__(self, red: float, green: float, blue: float) -> None:
super().__init__()
self.target = Led(red, green, blue)
@AbstractTransition.brightness.setter
def b... | 3.15625 | 3 |
ktrain/graph/stellargraph/version.py | happy-machine/ktrain | 0 | 41134 | <reponame>happy-machine/ktrain<gh_stars>0
# Global version information
__version__ = "0.7.2"
| 0.820313 | 1 |
network.py | jackwang0108/mnist | 1 | 41135 | <gh_stars>1-10
import torch
import torch.nn as nn
class LeNet(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=6, kernel_size=(5, 5), padding=2, stride=1)
self.pool1 = nn.AvgPool2d(kernel_size=(2, 2), stride=(2, 2), padding=0)
se... | 2.546875 | 3 |
2015/21/solve.py | lamperi/aoc | 0 | 41136 | import operator as op
import itertools
with open("input.txt") as file:
data = file.read()
shop = """Weapons: Cost Damage Armor
Dagger 8 4 0
Shortsword 10 5 0
Warhammer 25 6 0
Longsword 40 7 0
Greataxe 74 8 0
Armor: Cost Damage Armor... | 3.640625 | 4 |
main.py | rtli/AccountBook | 0 | 41137 | import sys
import os
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox, QDialog
from PyQt5.QtCore import pyqtSignal
from mainUi import Ui_Form
from sortUi import sortUi
from functools import partial
import csvIssue
class MyMainForm(QMainWindow, Ui_Form):
def __init__(self, parent=None):
s... | 2.5625 | 3 |
back-end/src/handler/util/user_util_test.py | gfxcc/san11-platform-back-end | 1 | 41138 | import unittest
import uuid
from . import user_util
class TestUtilFuncs(unittest.TestCase):
def test_hash_and_verify_password(self):
passwords = [str(uuid.uuid4()) for i in range(10)]
for pw in passwords:
self.assertTrue(
user_util.verify_password(pw, user_util.hash_p... | 2.9375 | 3 |
ex042.py | ArthurCorrea/python-exercises | 0 | 41139 | # Refaça o desafio 035, acrescentando o recurso de mostrar que
# tipo de triângulo será formado:
# - Equilátero: todos os lados iguais;
# - Isósceles: dois lados iguais;
# - Escaleno: todos os lados diferentes.
n1 = float(input('\033[34mMedida 1:\033[m '))
n2 = float(input('\033[31mMedida 2:\033[m '))
n3 = float(input(... | 3.9375 | 4 |
yamtbx/dataproc/xds/xds_inp.py | harumome/kamo | 0 | 41140 | """
(c) RIKEN 2015. All rights reserved.
Author: <NAME>
This software is released under the new BSD License; see LICENSE.
"""
import os
from yamtbx.dataproc import XIO
from yamtbx.dataproc import cbf
from yamtbx.dataproc.dataset import group_img_files_template
def sensor_thickness_from_minicbf(img):
header = cb... | 1.773438 | 2 |
servicecheckerdb2prometheus.py | bitsofinfo/swarm-traefik-state-analyzer | 6 | 41141 | #!/usr/bin/env python
from prometheus_client import start_http_server, Summary
import random
import argparse
import time
from prometheus_client import Counter
from prometheus_client import Gauge
from prometheus_client import Summary
from prometheus_client import Histogram
import sys
import time
import json
import date... | 2.34375 | 2 |
coins.py | bmtgoncalves/UDD | 8 | 41142 | #!/usr/bin/env pythonw
import numpy as np
import matplotlib.pyplot as plt
def flip_coins(flips = 1000000, bins=100):
# Uninformative prior
prior = np.ones(bins, dtype='float')/bins
likelihood_heads = np.arange(bins)/float(bins)
likelihood_tails = 1-likelihood_heads
flips = np.random.choice(a=[True... | 3.390625 | 3 |
fbssdc/ast.py | Eijebong/binjs-ref | 391 | 41143 | <reponame>Eijebong/binjs-ref<gh_stars>100-1000
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import doctest
import json
import os
import subprocess
import idl
BIN... | 2.203125 | 2 |
nutrition_labels/ensemble_model.py | wellcometrust/nutrition-labels | 2 | 41144 | <gh_stars>1-10
"""
1. Ensemble model to predict unseen grants data
2. Calculate metrics for ensemble model
"""
import pandas as pd
import numpy as np
from sklearn.metrics import accuracy_score, classification_report, f1_score, precision_score, recall_score
import os
import re
import ast
from datetime import datetime... | 2.78125 | 3 |
examples/mnist.py | kellylab/Fireworks | 9 | 41145 | #%%
from fireworks import PyTorch_Model, Message, HookedPassThroughPipe, Experiment
from fireworks.toolbox import ShufflerPipe, TensorPipe, BatchingPipe, FunctionPipe
from fireworks.toolbox.preprocessing import train_test_split
from fireworks.extensions import IgniteJunction
from fireworks.core import PyTorch_Model
im... | 3 | 3 |
main.py | tigran-ericyan/Python-Organizer | 0 | 41146 | import os
import shutil
video_files = ['.webm', '.mkv', '.vob', '.gif', '.avi', '.amv', '.mp4',]
audio_files = ['.aif','.cda', '.mid', '.mp3', '.mpa', '.ogg', ]
image_files = ['.tif', '.tiff', '.bmp', '.jpg', '.jpeg', '.gif', '.png', '.eps', '.raw', '.cr2', '.nef', '.orf', '.sr2', '.ico']
setup_files = ['.... | 2.546875 | 3 |
zag/tests/unit/worker_based/test_dispatcher.py | ToolsForHumans/taskflow | 1 | 41147 | <reponame>ToolsForHumans/taskflow<filename>zag/tests/unit/worker_based/test_dispatcher.py
# -*- coding: utf-8 -*-
# Copyright (C) 2014 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may... | 1.960938 | 2 |
Histogram of Oriented Gradients (HOG)/Showing the HOG features.py | ahmadhabib5/Computer_Vision_Bootcamp_with_Python_OpenCV_YOLO_SSD | 0 | 41148 | <filename>Histogram of Oriented Gradients (HOG)/Showing the HOG features.py
from skimage import data, feature
import matplotlib.pyplot as plt
image = plt.imread('images/mohammad-salah.jpg')
hog_vector, hog_image = feature.hog(image, orientations=9, pixels_per_cell=(8,8),
cells_per_... | 3.390625 | 3 |
CountingGridsPy/tests/time_models/time_gpuvscpu.py | microsoft/browsecloud | 159 | 41149 | <filename>CountingGridsPy/tests/time_models/time_gpuvscpu.py
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import unittest
import numpy as np
import torch
import os
import cProfile
from CountingGridsPy.models import CountingGridModel, CountingGridModelWithGPU
class Tim... | 2.234375 | 2 |
make_standalone_html.py | peli-pro/coldcard_address_generator | 1 | 41150 | from pathlib import Path
'''
This script creates a new html that has placed the javascript code inline to make a standalone html
'''
src = Path.cwd() / 'coldcard_address_generator_html.html'
dest = Path.cwd() / 'coldcard_address_generator_html_standalone.html'
dest2 = Path.cwd() / 'index.html' # for github pages
... | 3.234375 | 3 |
cash-donations.py | davidciani/taxtools | 0 | 41151 | #!/usr/bin/env python
import argparse
import logging
from csv import DictReader
from datetime import date, datetime
from pathlib import Path
logger = logging.getLogger(__name__)
header = """V042
ATaxTool Donations 0.4
D{date:%Y-%m-%d}
^
"""
record_layout_1 = """TD
N280
C1
L1
${amount:0.2f}
X{payee} ({ein})
^
"""
r... | 2.984375 | 3 |
movieClass.py | qedseung/Movie-Classifier | 0 | 41152 | import sys, numpy
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.ensemble import RandomForestClassifier
from sklearn.naive_bayes import MultinomialNB
#0=drama,1=comedy,2=animated,3=action/adventure
def random_forest_class(raw_test_set):
x_train=[]
y_train=[]
count=0
vectorize... | 3.140625 | 3 |
calaccess_scraped/management/commands/scrapecalaccesscandidates.py | california-civic-data-coalition/django-calaccess-scraped-data | 1 | 41153 | <filename>calaccess_scraped/management/commands/scrapecalaccesscandidates.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Run all scraper commands.
"""
# Files
import re
import os
import csv
import glob
from bs4 import BeautifulSoup
from calaccess_scraped import get_data_directory, get_html_directory
# Django
fr... | 2.796875 | 3 |
rpi_client/run.py | daniellamb2208/Face-Recogniztion-and-Internet-of-Thing | 0 | 41154 | <reponame>daniellamb2208/Face-Recogniztion-and-Internet-of-Thing
import cv2
from picamera import PiCamera
from picamera.array import PiRGBArray
import numpy as np
import json
import requests
import time
import RPi.GPIO as io
import os
io.setmode(io.BOARD)
io.setup(11, io.OUT)
def success():
io.output(11, True)
... | 2.953125 | 3 |
api/views/view_users.py | AlanZhl/NodUleS | 0 | 41155 | from flask import Blueprint, jsonify, request, session
from pymongo import DESCENDING
from api.views import users
from api import collection_users
@users.route("/api/register", methods=["POST"])
def user_register():
if request.method == "POST":
data = request.get_json()
email = data['e... | 3.1875 | 3 |
journal_club/sound.py | philastrophist/journal_club | 0 | 41156 | import time
import os
import pyglet
from gtts import gTTS
from pydub import AudioSegment
import traceback
def play_text(*txts):
try:
sounds = []
fnames = []
for i, s in enumerate(txts):
g = gTTS(text=s, lang='en')
fname = 'voice{}.mp3'.format(i)
with open... | 2.890625 | 3 |
ansible-devel/test/units/utils/test_display.py | satishcarya/ansible | 0 | 41157 | <gh_stars>0
# -*- coding: utf-8 -*-
# (c) 2020 <NAME> <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from units.compat.mock import MagicMock
import pytest
from ansible.module... | 1.8125 | 2 |
plugins/modules/oci_network_byoip_range_actions.py | A7rMtWE57x/oci-ansible-collection | 0 | 41158 | <filename>plugins/modules/oci_network_byoip_range_actions.py<gh_stars>0
#!/usr/bin/python
# Copyright (c) 2017, 2020 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu... | 2.0625 | 2 |
vapor/fn.py | xiaket/vapor | 0 | 41159 | #!/usr/bin/env python3
"""
Models that maps to Cloudformation functions.
"""
def replace_fn(node):
"""Iteratively replace all Fn/Ref in the node"""
if isinstance(node, list):
return [replace_fn(item) for item in node]
if isinstance(node, dict):
return {name: replace_fn(value) for name, val... | 2.84375 | 3 |
adapters.py | umautobots/sim_traj | 1 | 41160 | import numpy as np
import pandas as pd
def batch_df2batch(df, evaluate_ids=(), n_obs=-1, tform=np.eye(3), is_vehicles_evaluated=False):
"""
Convert dataframe to SGAN input
:param df:
:param evaluate_ids:
:param n_obs: number of timesteps observed
:param tform:
:param is_vehicles_evaluat... | 2.421875 | 2 |
Beginner/SolutionByJagmeet_CheckEvenOdd.py | man21/IOSD-UIETKUK-HacktoberFest-Meetup-2019 | 22 | 41161 | <reponame>man21/IOSD-UIETKUK-HacktoberFest-Meetup-2019<filename>Beginner/SolutionByJagmeet_CheckEvenOdd.py
def checkEvenOdd(num):
if(num%2 == 0):
print("Number ",num," is even ")
elif(num %2 ==1):
print("Number ",num," is odd ")
checkEvenOdd(113)
| 3.140625 | 3 |
Speaker_Verification/src/run.py | TaeYoon2/KerasSpeakerEmbedding | 4 | 41162 | <filename>Speaker_Verification/src/run.py<gh_stars>1-10
import os
import json
import argparse
import configparser
import warnings
import datetime
from ge2e import *
warnings.simplefilter(action='ignore', category=FutureWarning)
# arguments
# ckpt example : '/path/to/your/ckpt/cp-{:06d}.ckpt'
parser = argparse.Argument... | 2.453125 | 2 |
service/build/openstack/s3p_openstack_tools.py | matt-welch/docker-devstack | 4 | 41163 | <gh_stars>1-10
#!/usr/bin/env python
from openstack import connection
import errno
import os
import hashlib
import pdb
from time import sleep
FLAVOR_NAME='cirros256'
SEC_GRP_NAME='s3p_secgrp'
IMAGE_NAME='cirros-0.3.4-x86_64-uec'
debug_mode=False
default_image=""
default_flavor=""
default_secgrp=""
""" Utilities """... | 2.203125 | 2 |
Task/XML-XPath/Python/xml-xpath-3.py | LaudateCorpus1/RosettaCodeData | 5 | 41164 | <gh_stars>1-10
from lxml import etree
xml = open('inventory.xml').read()
doc = etree.fromstring(xml)
doc = etree.parse('inventory.xml') # or load it directly
# Return first item
item1 = doc.xpath("//section[1]/item[1]")
# Print each price
for p in doc.xpath("//price"):
print "{0:0.2f}".format(float(p.text)) #... | 3.078125 | 3 |
src/landing/views.py | drwatson88/django-leon-shop | 0 | 41165 | <gh_stars>0
# coding: utf-8
from django.http import Http404
from .base import LandingBaseView, LandingParamsValidatorMixin
class ShopLandingView(LandingBaseView, LandingParamsValidatorMixin):
""" Landing View. Receives get params
and response neither arguments in get
request params.
GE... | 2.140625 | 2 |
lib/private/directory_path.bzl | alexeagle/bazel-lib | 16 | 41166 | """Rule and corresponding provider that joins a label pointing to a TreeArtifact
with a path nested within that directory
"""
load("//lib:utils.bzl", _to_label = "to_label")
DirectoryPathInfo = provider(
doc = "Joins a label pointing to a TreeArtifact with a path nested within that directory.",
fields = {
... | 2.546875 | 3 |
flashtext/flashtextDemo.py | polarbear0330/i_like_demos | 1 | 41167 | <reponame>polarbear0330/i_like_demos<filename>flashtext/flashtextDemo.py
from flashtext import KeywordProcessor
keywordProcessor = KeywordProcessor()
keywordProcessor.add_keyword_from_file("keywords.txt")
keywordProcessor.add_keyword("orange", "watermelon")
print(" ")
print(keywordProcessor.get_all_keywords())
pri... | 2.8125 | 3 |
scheduling/create_scheduling_data/agent.py | CORE-Robotics-Lab/Personalized_Neural_Trees | 3 | 41168 | <reponame>CORE-Robotics-Lab/Personalized_Neural_Trees
import random
import numpy as np
from scheduling.create_scheduling_data.constants import *
class Agent:
def __init__(self, v = None, z = None, name = ""):
if v == None:
self.v = random.randint(0,10) # velocity
else:
self... | 2.734375 | 3 |
rinnaicontrolr/base.py | explosivo22/rinnaicontrol-r | 7 | 41169 | """
base.py -- client for the base Rinnai API
"""
import datetime, json, logging, time
import requests
from rinnaicontrolr.aws_srp import AWSSRP
LOGGER = logging.getLogger('rinnaicontrolr')
from rinnaicontrolr.const import (
POOL_ID,
CLIENT_ID,
POOL_REGION,
GRAPHQL_ENDPOINT,
SHADOW_ENDPOINT,
... | 2.515625 | 3 |
0x07-Session_authentication/api/v1/auth/session_db_auth.py | JoseAVallejo12/holbertonschool-web_back_end | 0 | 41170 | <reponame>JoseAVallejo12/holbertonschool-web_back_end
#!/usr/bin/env python3
"""
SessionDBAuth class to manage API authentication
"""
from api.v1.auth.session_exp_auth import SessionExpAuth
from models.user_session import UserSession
from os import getenv
from datetime import datetime, timedelta
class SessionDBAuth(S... | 2.828125 | 3 |
profile/migrations/0003_globalalert.py | ritstudentgovernment/PawPrints | 15 | 41171 | # Generated by Django 2.1.3 on 2019-02-12 19:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('profile', '0002_auto_20180126_1900'),
]
operations = [
migrations.CreateModel(
name='GlobalAlert',
fields=[
... | 1.632813 | 2 |
agent/src/agent/pipeline/config/validators.py | eacherkan-aternity/daria | 0 | 41172 | import click
from agent.pipeline.validators import elastic_query, jdbc_query
from agent import source
class BaseValidator:
@staticmethod
def validate(pipeline):
pass
class ElasticValidator(BaseValidator):
@staticmethod
def validate(pipeline):
with open(pipeline.config['query_file'])... | 2.046875 | 2 |
recette/__init__.py | pennacchio/recette | 0 | 41173 | <reponame>pennacchio/recette
from recette.steps import prep_step_dummy, prep_step_other
from recette.utils import combine
# Package version single source of truth
__version__ = "0.2.1"
| 0.910156 | 1 |
others/process.py | MaxMorning/DigitalLogicFinalProject | 3 | 41174 | import numpy as npy
def convert(num):
if num < 0:
# num = -num
num *= 1024
# num += 32768
num = int(num - 0.5)
num = 65535 + num
n_str = str(hex(num))[2:]
if len(n_str) == 1:
n_str = 'fff' + n_str
elif len(n_str) == 2:
n_str = ... | 2.765625 | 3 |
src/illumidesk/spawners/spawner.py | 1kastner/illumidesk | 0 | 41175 | import os
import shutil
from dockerspawner import DockerSpawner
class IllumiDeskDockerSpawner(DockerSpawner):
"""
Custom DockerSpawner which assigns a user notebook image
based on the user's role. This spawner requires:
1. That the `Authenticator.enable_auth_state = True`
2. That the user's ... | 2.703125 | 3 |
app_code/models.py | sivarki/hjarnuc | 0 | 41176 | from django.db import models
from app_asset.models import Host
# Create your models here.
class Project(models.Model):
project_name = models.CharField(max_length=32,unique=True)
project_msg = models.CharField(max_length=64,null=True)
def __unicode__(self):
return self.project_name
class GitCode(... | 2.03125 | 2 |
validation_multi.py | angelnew/biblioeater | 4 | 41177 | <reponame>angelnew/biblioeater
import os
from constants import *
from the_logger import nlp_logger
from padder import pad
from book import Book
import pickle
import numpy as np
# Load the books
pym = Book("<NAME>")
tom = Book("<NAME>")
eureka = Book("Eureka")
huck = Book("H<NAME>")
pym.from_file(PYM_FILE)
tom.from_... | 2.765625 | 3 |
project/views.py | Ylmz42/asdfasdf | 0 | 41178 | <gh_stars>0
from django.contrib.auth import authenticate, login
from django.contrib.auth import logout
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, get_object_or_404
from django.db.models import Q
from .forms import ProjectForm, ApplicationForm, UserForm
from .models import Pr... | 2.21875 | 2 |
git_diff_ssr2_osm_wrapper.py | obtitus/ssr2_to_osm | 1 | 41179 | #/usr/bin/env python
import sys
import logging
logger = logging.getLogger('utility_to_osm.ssr2.git_diff')
import utility_to_osm.file_util as file_util
from osmapis_stedsnr import OSMstedsnr
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
# diff is called by git with 7 parameters:
... | 2.625 | 3 |
civismlext/test/test_hyperband.py | viacheslav-m/civisml-extensions | 0 | 41180 | <reponame>viacheslav-m/civisml-extensions<gh_stars>0
from __future__ import print_function
from __future__ import division
import pytest
from scipy.stats import expon, randint, rankdata
import numpy as np
from sklearn.base import BaseEstimator, ClassifierMixin
try:
from sklearn.utils._testing import assert_array... | 2.109375 | 2 |
test-data/mkpasswd.py | colorshifter/lsd-members | 1 | 41181 | #!/usr/bin/env python3
import uuid
from passlib.hash import pbkdf2_sha512
password = input('Enter password: ')
password_parts = pbkdf2_sha512.encrypt(password, salt_size=32).split('$')
password = password_parts[4]
salt = password_parts[3]
def convert_b64(input):
return input.replace('.', '+') + '='
print('Passw... | 3.234375 | 3 |
SVassembly/__init__.py | AV321/SVPackage | 0 | 41182 | <filename>SVassembly/__init__.py
from SVassembly import bedpe2window_f
from bedpe2window_f import bedpe2window
from SVassembly import get_shared_bcs_f
from get_shared_bcs_f import get_shared_bcs
from SVassembly import assign_sv_haps_f
from assign_sv_haps_f import assign_sv_haps
from SVassembly import count_bcs_f
fro... | 1.828125 | 2 |
setup.py | uofuseismo/shakemap-aqms | 0 | 41183 | <gh_stars>0
from distutils.core import setup
import os.path
setup(name='shakemap_aqms',
version='1.0',
description='AQMS Modules for ShakeMap',
author='<NAME>',
author_email='<EMAIL>',
url='http://github.com/cbworden/shakemap-aqms',
packages=['shakemap_aqms',
'shake... | 1.171875 | 1 |
exercicios-Python/ex071.py | pedrosimoes-programmer/exercicios-python | 0 | 41184 | # Programa Simulador de Caixa Eletrônico
# O caixa possui cédulas de 50, 20, 10 e 1
# Forma 1 = MINHA FORMA, COMPLICADA, MEIO NO CHUTE
print('=' * 50)
print('{:^50}'.format(' BANCO SIMÕES '))
print('=' * 50)
valor = int(input('Qual valor você quer sacar: R$'))
while True:
if valor % 50 != 1:
if valor // 5... | 3.796875 | 4 |
external/lemonade/dist/examples/calc/calc.py | almartin82/bayeslite | 964 | 41185 | <reponame>almartin82/bayeslite<filename>external/lemonade/dist/examples/calc/calc.py
import sys
def generateGrammar():
from lemonade.main import generate
from os.path import join, dirname
from StringIO import StringIO
inputFile = join(dirname(__file__), "gram.y")
outputStream = StringIO()
ge... | 2.859375 | 3 |
netlist.py | phdbreak/netlist_parser.py | 11 | 41186 | <gh_stars>10-100
# Parent tree
# design
# |---> module
# |-----> port/wire
# |-----> instance
# |-----> pin
class design_t:
def __init__(self):
self.modules = dict()
def add_module(self, module_name):
if (module_name in self.modules.keys()):
... | 3.296875 | 3 |
scripts/test_publisher_twist_stamped.py | nbfigueroa-rlic/robot_kinematics_kdl | 0 | 41187 | <filename>scripts/test_publisher_twist_stamped.py
#!/usr/bin/env python
#
# Copyright 2017 Fraunhofer Institute for Manufacturing Engineering and Automation (IPA)
#
# 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 cop... | 2.0625 | 2 |
vector_nba/nba_api.py | rsforbes/vector-nba | 1 | 41188 | <gh_stars>1-10
import datetime
from nba_api.stats.endpoints import Scoreboard
from nba_api.stats.library.parameters import LeagueID
from nba_api.stats.library.data import teams
def get_teams():
return dict((team[0],team[5]) for team in teams)
def get_games(date):
teams = get_teams()
gamefinder = Scoreboa... | 2.65625 | 3 |
code/parallel.py | RuthAngus/kepler_ages | 0 | 41189 | <filename>code/parallel.py
#!/usr/bin/python3
import os
import sys
import numpy as np
import pandas as pd
import h5py
import tqdm
import emcee
import stardate as sd
from stardate.lhf import age_model
from isochrones import get_ichrone
mist = get_ichrone('mist')
from multiprocessing import Pool
# Necessary to add cw... | 2.21875 | 2 |
Sort/20_stack_sort.py | Szymon-Budziak/ASD_exercises_solutions | 7 | 41190 | # Find algorithm that sorts the stack of size n in O(log(n)) time. It is allowed to use operations
# provided only by the stack interface: push(), pop(), top(), isEmpty() and additional stacks.
class Stack:
def __init__(self):
self.stack = []
def push(self, value):
self.stack.append(value)
... | 3.921875 | 4 |
nvc-core/nvc/libs/utils.py | BiznetGIO/nvc-lite | 0 | 41191 | import yaml
import os
import subprocess
import coloredlogs
import logging
import psutil
import shutil
import hashlib
import uuid
import fileinput
import requests
from nvc import __appname__
from dotenv import load_dotenv
import git
app_root = os.path.dirname(os.path.abspath(__file__))
app_home = os.path.expanduser("~... | 2.15625 | 2 |
weeby/overlays.py | asheeeshh/weeby.py | 5 | 41192 | <gh_stars>1-10
from . import config
from .util import make_request, image_request
class Overlay:
def __init__(self, token: str) -> None:
self.token = token
def overlay(self, type: str, image_url: str):
url = config.api_url + f"overlays/{type}?image={image_url}"
headers= {"Authorization... | 2.578125 | 3 |
tests/lib/bes/cli/test_cli.py | reconstruir/bes | 0 | 41193 | #!/usr/bin/env python
#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-
from collections import namedtuple
import os.path as path
from bes.testing.program_unit_test import program_unit_test
from bes.fs.file_util import file_util
from bes.system.host import host
class test_cli... | 2.3125 | 2 |
Linked Lists/palindrome.py | henryoliver/cracking-coding-interview-solutions | 2 | 41194 | import sys
sys.path.append('../../Data Structures')
from stack import Stack
def isPalindrome(linkedList={}):
'''
Solution 1 - Hash map
Complexity Analysis
O(n) time | O(n) space
Check if a linked list is a palindrome
dict: linkedList
return: True if its palindrome
'''
# Graceful... | 4.03125 | 4 |
monta_palavras/main.py | Lucas-Vini/useful_scripts | 1 | 41195 | <reponame>Lucas-Vini/useful_scripts
import unicodedata
import montapalavra as mp
def main():
'''
Funcionamento do programa:
- Inicialmente é solicitado que o usuário digite as letras disponíveis. (1)
- Para poder encerrar o programa, o usuário pode digitar apenas a letra
"q". (2)
- Depois ... | 3.546875 | 4 |
src/components/auth-server/lib/presentation/restapi.py | ars1004/practica-dms-2019-2020 | 0 | 41196 | <filename>src/components/auth-server/lib/presentation/restapi.py
from flask import Flask, escape, request, abort
from lib.data.db.schema.manager import Manager as SchemaManager
from lib.data.db.schema.recordsets.users import Users
from lib.data.db.schema.recordsets.userscores import UserScores
from lib.data.db.schema.... | 3 | 3 |
Sprint Challenge/acme_report.py | dylan0stewart/DS-Unit-3-Sprint-1-Software-Engineering | 0 | 41197 | """
Class Report: Part 4 of the Sprint Challenge
- Generate random Product list, and get an Inventory Report on that list
"""
from random import randint, sample, uniform
from acme import Product
ADJECTIVES = ['Awesome', 'Shiny', 'Impressive', 'Portable', 'Improved']
NOUNS = ['Anvil', 'Catapult', 'Disguise', 'Mousetra... | 3.78125 | 4 |
bikeshed/h/__init__.py | deniak/bikeshed | 1 | 41198 | <reponame>deniak/bikeshed
# -*- coding: utf-8 -*-
from .serializer import Serializer
from .dom import addClass
from .dom import addOldIDs
from .dom import appendChild
from .dom import appendContents
from .dom import approximateLineNumber
from .dom import childElements
from .dom import childNodes
from .dom import circ... | 1.140625 | 1 |
trainer/trainer_meta_learning.py | lixiaoyu0575/physionet_challenge2020_pytorch | 1 | 41199 | <reponame>lixiaoyu0575/physionet_challenge2020_pytorch<filename>trainer/trainer_meta_learning.py
import numpy as np
import torch
import torch.nn as nn
from torchvision.utils import make_grid
from base import BaseTrainer
from utils import inf_loop, MetricTracker, smooth_one_hot, mixup
import torch.nn.functional as F
fro... | 1.890625 | 2 |