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 |
|---|---|---|---|---|---|---|
differential/plugins/pterclub.py | funqc/Differential | 52 | 41000 | <filename>differential/plugins/pterclub.py
import argparse
from differential.plugins.nexusphp import NexusPHP
class PTerClub(NexusPHP):
@classmethod
def get_aliases(cls):
return 'pter',
@classmethod
def get_help(cls):
return 'PTerClub插件,适用于PTerClub'
@classmethod
def add_par... | 2.296875 | 2 |
Python_Network_Automation/input_num_ports/input_port_num.py | yasser296/Python-Projects | 0 | 41001 | import getpass
import telnetlib
port_num = str(input("Enter the Number of Port and type: "))
HOST = "10.1.1.1"
user = input("\nEnter The Username: ")
password = getpass.getpass()
tn = telnetlib.Telnet(HOST)
tn.read_until(b"Username: ")
tn.write(user.encode('ascii') + b"\n")
if password:
tn... | 3.203125 | 3 |
odinw/download.py | microsoft/GLIP | 295 | 41002 | import argparse
import os
argparser = argparse.ArgumentParser()
argparser.add_argument("--dataset_names", default="all", type=str) # "all" or names joined by comma
argparser.add_argument("--dataset_path", default="DATASET/odinw", type=str)
args = argparser.parse_args()
root = "https://vlpdatasets.blob.core.windows.ne... | 2.46875 | 2 |
Analysis/check_for_bias/data_analysis_tool.py | cgeorgitsis/ai4netmon | 0 | 41003 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from iso3166 import countries
import pycountry_convert as pc
import pycountry
import re
from datetime import datetime
from statsmodels.distributions.empirical_distribution import ECDF
FINAL_DATAFRAME = '../aggregate_data/final_dataframe.csv'
PATH_R... | 2.625 | 3 |
transformers/script_tune_multi_pos.py | rizwan09/NLPDV | 2 | 41004 | import os, pdb
# ______________________________________NLPDV____________________________________
# _______________________________________________________________________
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from transformers import *
import _pickle as pkl
import shutil
import numpy... | 1.828125 | 2 |
gather/upload_poster_rooms.py | stephenfreund/PLDI-2021-Mini-Conf | 0 | 41005 | <filename>gather/upload_poster_rooms.py
import csv
import io
import json
import time
import zlib
import sys
import os
import requests
import yaml
from libgather import Gather
if __name__ == "__main__":
config = yaml.load(open("../admin/config.yml").read(), Loader=yaml.SafeLoader) | yaml.load(open("config.yml").r... | 2.25 | 2 |
Aulas Python/m03/aula18a.py | joaquimjfernandes/Curso-de-Python | 0 | 41006 | print('=' * 15, '\033[1;35mAULA 18 - Listas[Part #2]\033[m', '=' * 15)
# --------------------------------------------------------------------
dados = []
pessoas = []
galera = [['Miguel', 25], ['Berta', 59], ['Joaquim', 20]]
# --------------------------------------------------------------------
dados.append('Joaquim')
d... | 3.546875 | 4 |
src/azure/azure_test_run_experiment.py | ThordurPall/MLOpsExercises- | 0 | 41007 | # -*- coding: utf-8 -*-
from azureml.core import Environment, Experiment, ScriptRunConfig, Workspace
from azureml.core.conda_dependencies import CondaDependencies
def main():
# Create a Python environment for the experiment
# env = Environment("experiment_test_env")
env = Environment("experiment-test-MLFl... | 2.59375 | 3 |
Logger/Logger.py | ArthMx/Logger | 0 | 41008 | import pandas as pd
import time
import sys
class AverageMeter(object):
"""Sum values to compute the mean."""
def __init__(self):
self.reset()
def reset(self):
self.count = 0
self.sum = 0
def update(self, val):
self.count += 1
self.sum += val
... | 3.203125 | 3 |
optimization/prac1/tests/test_logistic.py | shaandesai1/AIMS | 0 | 41009 | import unittest
from sys import argv
import numpy as np
import torch
from objective.logistic import Logistic_Gradient
from .utils import Container, assert_all_close, assert_all_close_dict
class TestObj_Logistic_Gradient(unittest.TestCase):
def setUp(self):
np.random.seed(1234)
torch.manual_seed(... | 2.671875 | 3 |
mitmproxy/proxy/modes/tunnel_proxy.py | intfrr/mitmproxy | 6 | 41010 | <gh_stars>1-10
from mitmproxy import exceptions
from mitmproxy import platform
from mitmproxy.proxy import protocol
class TunnelProxy(protocol.Layer, protocol.ServerConnectionMixin):
def __init__(self, ctx):
super().__init__(ctx)
def __call__(self):
layer = self.ctx.next_layer(self)
... | 2.4375 | 2 |
tests/test_nafigator.py | DeNederlandscheBank/nafigator | 1 | 41011 | <filename>tests/test_nafigator.py<gh_stars>1-10
#!/usr/bin/env python
"""Tests for `nafigator` package."""
import unittest
unittest.TestLoader.sortTestMethodsUsing = None
from deepdiff import DeepDiff
from click.testing import CliRunner
from nafigator import NafDocument, parse2naf
from os.path import join
class ... | 2.515625 | 3 |
src/openpersonen/setup.py | maykinmedia/open-personen | 2 | 41012 | <filename>src/openpersonen/setup.py
"""
Bootstrap the environment.
Load the secrets from the .env file and store them in the environment, so
they are available for Django settings initialization.
.. warning::
do NOT import anything Django related here, as this file needs to be loaded
before Django is initial... | 2.03125 | 2 |
unisan/lemlit/migrations/0013_auto_20170901_0649.py | kurniantoska/ichsan_proj | 0 | 41013 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-31 22:49
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lemlit', '0012_remove_suratizinpenelitianmahasiswa_dosen'),
]
operations = [
... | 1.546875 | 2 |
PyAlgo4/src/UnionFind.py | QuDong/Algorithm4 | 6 | 41014 | <reponame>QuDong/Algorithm4
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 22/4/2016 10:57 AM
Author: <NAME>
"""
class QuikFindUF():
def __init__(self, N):
self.count = N
self.parent = list(range(N))
def count(self):
return self.count
def find(self, p):
sel... | 3.375 | 3 |
components/testers.py | Debutante/Graduation_Project | 0 | 41015 | from datasets.dataset_processors import ExtendedDataset
from models.model import IdentificationModel, ResNet50
from models.siamese import SiameseNet, MssNet
from base import BaseExecutor
from utils.utilities import type_error_msg, value_error_msg, timer, load_model
import torch
from torch.utils.data import DataLoader
f... | 2.28125 | 2 |
src/google_api/calendar.py | KaiWalter/family-board-py | 0 | 41016 | from datetime import timedelta
import app_config
import dateutil.parser
from googleapiclient.discovery import build
from injector import inject
from models import AllDayCalendarEntry, CalendarEntry
from google_api import GoogleAuthenication
class GoogleCalendar:
@inject
def __init__(self, auth: GoogleAuthe... | 2.421875 | 2 |
Utils.py | colinchen6512/share-analysis | 1 | 41017 | <filename>Utils.py
"""
Created on 2017年12月9日
@author: Colin
"""
import datetime
import math
import logging
import logging.config
import re
# china stock shanghai
startSH = 600001
MAXSH = 603999
startSZ = 1
MAXSZ = 2909
startCY = 300001
MAXCY = 300710
STEP = 1
LASTDAYS = 10
INCR_VOL = 5
PERCEN... | 2.5 | 2 |
Estrutura de dados/ArvoreBinaria/TreeUni.py | Kaioguilherme1/PythonCodigos | 0 | 41018 | <reponame>Kaioguilherme1/PythonCodigos
#AUTH <NAME>
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
root = Node(0)
root.left = Node(1)
root.right = Node(0)
root.right.left = Node(1)
root.right.right = Node(0)
root.right.left.right = Node(1)
root.righ... | 3.59375 | 4 |
gerrymandering/gerrymandering.py | omarchehab98/open.kattis.com-problems | 1 | 41019 | <reponame>omarchehab98/open.kattis.com-problems
P, D = list(map(int, input().split(' ')))
totA, totB = 0, 0
dis = [[0,0,0,0] for i in range(D)]
for i in range(P):
a, b, c = map(int, input().split(' '))
k = (b+c)//2 + 1
dis[a-1][0] += b
dis[a-1][1] += c
for i, (ta, tb, _, _) in enumerate(dis):
k = (ta ... | 2.640625 | 3 |
jobs/models.py | shifat151/portfolio | 0 | 41020 | from django.db import models
# Create your models here.
class Profile(models.Model):
pic=models.ImageField(upload_to='images/')
pub_date=models.DateTimeField(auto_now=True)
obj=models.TextField(blank=True)
# ctime() method is for converting datetime string into a string
def __str__(self):
... | 2.34375 | 2 |
snapshotgetter.py | membermatters/UniFiVideoSnapshotGetter | 3 | 41021 | <gh_stars>1-10
import requests
import json
import time
import os
default_output = "/usr/app/output/"
def validate_config():
if config.get("apiKey") and config.get("protocol") and config.get("port") and config.get("host") and config.get(
"cameras") and config.get("frequency"):
return True
... | 2.765625 | 3 |
app.py | ahensley3/yulesim | 0 | 41022 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 29 20:53:21 2020
@author: asherhensley
"""
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd
import yulesimon as ys
from plotly.subplots import make_subplots
import plo... | 2.390625 | 2 |
app/thumbnail.py | Kbman99/NetSecShare | 0 | 41023 | <reponame>Kbman99/NetSecShare
from PIL import Image
import os
import sys
from app import app
def generate_thumbnail(infile_name):
try:
size = 206.67, 256.29
target_dir = app.config['UPLOAD_PATH']
# found_file = ''
# for name in os.listdir(target_dir):
# if infile_name i... | 2.515625 | 3 |
resemblance/main/similarity/api/search/loadModel.py | Sorarinu/ProjectP2016_F | 0 | 41024 | # coding:utf-8
from gensim.models import word2vec
class LoadModelFlag(object):
def __init__(self, fname, folder_word):
self.fname = fname
self.folder_word = folder_word
def load_model_similar_flag(self):
# 分かち書きしてmodelファイルを生成する。
load = word2vec.Word2Vec.load(self.fname)
... | 2.859375 | 3 |
noodles/prov/workflow.py | BvB93/noodles | 22 | 41025 | <gh_stars>10-100
from ..workflow import (Workflow, is_node_ready, Empty)
from ..workflow.arguments import (serialize_arguments, ref_argument)
from ..serial import (Registry)
from .key import (prov_key)
def links(wf, i, deps):
for d in deps:
for l in wf.links[d]:
if l[0] == i:
y... | 2.328125 | 2 |
tests/test_experiment.py | movermeyer/pyexperiment | 220 | 41026 | <reponame>movermeyer/pyexperiment
"""Tests the experiment module of pyexperiment
Written by <NAME>
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
import unittest
import argparse
import io
import mock
import temp... | 2.34375 | 2 |
businessplots/_data.py | fvinas/businessplots | 2 | 41027 | <gh_stars>1-10
# -*- coding: utf-8 -*-
def _data_from_bar(ax, bar_label):
"""Given a matplotlib Axes object and a bar label,
returns (x,y,w,h) data underlying the bar plot.
Args:
ax: The Axes object the data will be extracted from.
bar_label: The bar label from which you want to extract t... | 3.5625 | 4 |
Programming basics/Exam Exercises/Test Exam/xmas_sweets.py | antonarnaudov/SoftUniProjects | 0 | 41028 | baklava_price = float(input())
muffin_price = float(input())
shtolen_kg = float(input())
candy_kg = float(input())
bisquits_kg = int(input())
shtolen_price = baklava_price + baklava_price * 0.6
candy_price = muffin_price + muffin_price * 0.8
busquits_price = 7.50
shtolen_sum = shtolen_kg * shtolen_price
candy_sum = ca... | 3.59375 | 4 |
adminmgr/media/code/python/red3/BD_204_219_1354_reducer.py | IamMayankThakur/test-bigdata | 9 | 41029 | <reponame>IamMayankThakur/test-bigdata<filename>adminmgr/media/code/python/red3/BD_204_219_1354_reducer.py
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import csv
from operator import itemgetter
import sys
res = {}
run = 0
for line in sys.stdin:
line = line.strip()
line_val = line.split('\t')
#print(line_va... | 2.171875 | 2 |
db/team.py | leaffan/pynhldb | 3 | 41030 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from .common import Base, session_scope
from sqlalchemy import and_, or_
from sqlalchemy.sql.expression import func
class Team(Base):
__tablename__ = 'teams'
__autoload__ = True
HUMAN_READABLE = 'team'
def __init__(self, team_data):
self.team_i... | 2.953125 | 3 |
Backend/flask_api/functions.py | STCVIT/LivStory | 4 | 41031 | <reponame>STCVIT/LivStory
import firebase_admin
from firebase_admin import credentials, firestore
# from firebase_admin import firestore
cred = credentials.Certificate('./creds/google-services.json')
firebase_admin.initialize_app(cred)
print("initializing storage access")
db = firestore.client()
def get_audio(keywo... | 2.84375 | 3 |
semanticeditor/utils/general.py | spookylukey/semanticeditor | 0 | 41032 | """
Generic utilities
"""
def any(seq):
for i in seq:
if i:
return True
return False
| 2.171875 | 2 |
study/curso-em-video/exercises/037.py | jhonatanmaia/python | 0 | 41033 | x=int(input('Enter the number to convert: '))
print('Select the convertion')
print('''
[ 1 ] Binary
[ 1 ] Octal
[ 3 ] HexaDeicmal
''')
y=int(input('1 - Binary 2 - Octal 3 - Hexadecimal'))
if y==1:
bin(x)[2:]
print('{}'.format(x))
elif y==2:
oct(x)
print('{}'.format(x))
elif y==3:
hex(x)
print(... | 3.96875 | 4 |
src/pipeline.py | latticetower/electra_cute | 0 | 41034 | """Main module with image processing pipeline with several stages:
1. Processing: simplyfy image to get better results.
Here we do color clustering and similar image transformations.
2. Select shapes: find similar shapes on image
3. Classify shapes
4. Connect shapes: find lines on image and make connections between sh... | 3.4375 | 3 |
other/q16.py | pengfei-chen/algorithm_qa | 79 | 41035 | <gh_stars>10-100
"""
给定一个整数n,返回从1到n的数字中1个出现的个数.
例如:
n=5,1~n为1,2,3,4,5.那么1出现了1次,所以返回1.
n=11,1~n为1,2,3,4,5,6,7,8,9,10,11.那么1出现的次数为1(出现
1次),10(出现1次),11(有两个1,所以出现了2次),所以返回4
"""
class OneCounter:
@classmethod
def get_nums_of_one(cls, n):
if n == 0:
return 0
n = abs(n)
high_pos... | 3.015625 | 3 |
temboo/core/Library/Dropbox/FilesAndMetadata/ListFolderContents.py | jordanemedlock/psychtruths | 7 | 41036 | <gh_stars>1-10
# -*- coding: utf-8 -*-
###############################################################################
#
# ListFolderContents
# Retrieves metadata (including folder contents) for a folder or file in Dropbox.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache... | 2.1875 | 2 |
_unittests/ut_module/test_code_style.py | sdpython/onnxcustom | 7 | 41037 | <filename>_unittests/ut_module/test_code_style.py
"""
@brief test log(time=0s)
"""
import os
import unittest
from pyquickhelper.loghelper import fLOG
from pyquickhelper.pycode import check_pep8, ExtTestCase
class TestCodeStyle(ExtTestCase):
"""Test style."""
def test_style_src(self):
thi = os.pa... | 2.5 | 2 |
alphabrew/GUI/MainWindow.py | jwjulien/alphabrew | 0 | 41038 | # ======================================================================================================================
# File: GUI/MainWindow.py
# Project: AlphaBrew
# Description: Extensions and functionality for the main GUI window.
# Author: <NAME> <<EMAIL>>
# Copyright: (c) 2020 <NAME>... | 1.3125 | 1 |
tests/mocks/meetup.py | PyColorado/boulderpython.org | 5 | 41039 | <reponame>PyColorado/boulderpython.org
# -*- coding: utf-8 -*-
"""
meetup.py
~~~~~~~~~
a mock for the Meetup APi client
"""
class MockMeetupGroup:
def __init__(self, *args, **kwargs):
self.name = "Mock Meetup Group"
self.link = "https://www.meetup.com/MeetupGroup/"
self.next_ev... | 2.296875 | 2 |
stytra/gui/parameter_widgets.py | mark-dawn/stytra | 0 | 41040 | from PyQt5.QtWidgets import QDoubleSpinBox, QWidget, QLabel
class ParameterSpinBox(QDoubleSpinBox):
""" """
def __init__(self, *args, parameter, **kwargs):
super().__init__(*args, **kwargs)
self.parameter = parameter
param_state = parameter.saveState()
self.setValue(param_stat... | 2.828125 | 3 |
test.py | tkianai/StylizePoseGAN | 1 | 41041 | <reponame>tkianai/StylizePoseGAN
import os
import math
from options.test_options import TestOptions
from utils import misc
from data.build import build_dataloader
from models import build_model
from collections import OrderedDict
def test(model, data_loader, save_dir):
dataset = data_loader.load_data()
step ... | 2.046875 | 2 |
accounts/views.py | manuggz/memes_telegram_bot | 0 | 41042 | from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from django.shortcuts import render, HttpResponseRedirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import views as auth_views
def crear_cuenta(request):
if request.user.is_authent... | 2.375 | 2 |
modeling/src/load_data.py | alyildiz/covid_19_xray | 0 | 41043 | <reponame>alyildiz/covid_19_xray
from sklearn.model_selection import train_test_split
from src.utils import load_dataset
def get_data():
train_list_file, train_list_class = load_dataset(data_part="train")
test_x, test_y = load_dataset(data_part="test")
train_x, val_x, train_y, val_y = train_test_split(
... | 2.90625 | 3 |
data-analysis/monitor.py | JakobHavtorn/es-rl | 1 | 41044 | import argparse
import os
import sys
import time
import warnings
from ast import literal_eval
warnings.filterwarnings("ignore")
import IPython
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torch
import context
from context import utils
import uti... | 2.0625 | 2 |
src/trt_packnet/src/packnet_trt.py | surfii3z/packnet-sfm | 10 | 41045 | import tensorrt as trt
import pycuda.driver as cuda
import cv2
import numpy as np
class TrtPacknet(object):
"""TrtPacknet class encapsulates things needed to run TRT Packnet (depth inference)."""
def _load_engine(self):
TRTbin = 'trt_%s.trt' % self.model
with open(TRTbin, 'rb') as f, trt.Runt... | 2.21875 | 2 |
day-3-if-condition.py | roshansinghbisht/hello-python | 0 | 41046 | # TASK:
# Given an integer, n, perform the following conditional actions:
# If n is odd, print Weird
# If n is even and in the inclusive range of 2 to 5, print Not Weird
# If n is even and in the inclusive range of 6 to 20, print Weird
# If n is even and greater than 20, print Not Weird
if __name__ == '__main__':
... | 4.5625 | 5 |
5.2_CUSTOM_LIBRARY/day_by_day_best_low_error_point_forecast_between_all_models.py | pedroMoya/M5_kaggle_accuracy_KAGGLE_M5_A_share | 2 | 41047 | # analyzing each point forecast and selecting the best, day by day, saving forecasts and making final forecast
import os
import sys
import datetime
import logging
import logging.handlers as handlers
import json
import itertools as it
import pandas as pd
import numpy as np
# open local settings
with open('./settings.js... | 2.34375 | 2 |
Day_20/part2.py | Uklusi/AdventOfCode2018 | 0 | 41048 | <filename>Day_20/part2.py
from AoCUtils import *
from collections import defaultdict
# import re
# Assumptions:
# NO LOOPS
# No things like "^N(E|W)N$" where we have two branching paths to control simultaneously
# The only things not excluded are "^N(EW|)N" where the bracked ends with | and the other option is nullpot... | 3.1875 | 3 |
tests/_event/test_mouse_up_interface.py | ynsnf/apysc | 16 | 41049 | from random import randint
from typing import Any
from typing import Dict
from retrying import retry
import apysc as ap
from apysc._event.mouse_up_interface import MouseUpInterface
from apysc._expression import expression_data_util
from apysc._type.variable_name_interface import VariableNameInterface
cl... | 2.40625 | 2 |
margen/segment02/pitch.py | DaviRaubach/la_otra_margen | 0 | 41050 | <gh_stars>0
import abjad
I_pitches = {
"matA": abjad.PitchSegment([1, 6, 11, -6, -1, 4]),
"matB": abjad.PitchSegment([1, 6, 11]),
}
II_pitches = {
"matA": abjad.PitchSegment([4, -1, -6, -10, -4, 1]),
"matB": abjad.PitchSegment([4, -1, -6])
}
III_pitches = {
"matA": abjad.PitchSegment([1, -4... | 1.796875 | 2 |
etc/compute_topics.py | learning2hash/learning2hash.github.io | 15 | 41051 | <filename>etc/compute_topics.py
import argparse
import json
import nltk
nltk.download('stopwords')
nltk.download('wordnet')
nltk.download('punkt')
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from gensim.corpora import Dictionary
from gensim.models import LdaModel
def parse_arguments()... | 2.859375 | 3 |
app/schema/token.py | jburckel/fastapi-login-example | 0 | 41052 | from .mixin import AppSchemaBase
class Token(AppSchemaBase):
access_token: str
token_type: str
| 1.59375 | 2 |
models/1-Tom/train/kaggle-hubmap-main/src/02_train/umap.py | navekshasood/HuBMAP---Hacking-the-Kidney | 0 | 41053 | <reponame>navekshasood/HuBMAP---Hacking-the-Kidney
import umap
# import umap.umap_ as umap
import pickle
train_data = pickle.load(open("feature_train", "rb"))
test_data = pickle.load(open("feature_test", "rb"))
embedding = umap.UMAP().fit_transform(train_data) | 2.1875 | 2 |
python/src/widget-play/simple_widgets.py | nagi49000/ipywidgets-play | 0 | 41054 | from ipywidgets import interact
import ipywidgets as widgets
from IPython.display import display
class SimpleWidgets():
def __init__(self):
self._int_slider_widget = None
self._clicked_next_widget = None
self._button = None
def do_stuff_on_click(self, b):
if self._clicked_next... | 3.125 | 3 |
utils/general.py | bfortuner/VOCdetect | 336 | 41055 | <reponame>bfortuner/VOCdetect
import uuid
def gen_unique_id(prefix='', length=5):
return prefix + str(uuid.uuid4()).upper().replace('-','')[:length]
def get_class_name(obj):
invalid_class_names = ['function']
classname = obj.__class__.__name__
if classname is None or classname in invalid_class_names:... | 2.703125 | 3 |
record.py | anuwish/sesame-melody | 0 | 41056 | import alsaaudio, wave
mixer = alsaaudio.Mixer(control='Mic', cardindex=0)
mixer.setrec(1)
mixer.setvolume(80, 0, alsaaudio.PCM_CAPTURE)
inp = alsaaudio.PCM(type=alsaaudio.PCM_CAPTURE, device='sysdefault:CARD=Headset')
inp.setchannels(1)
inp.setrate(44100)
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
inp.setperiodsize(1... | 2.40625 | 2 |
introcs-1.0/looppi.py | JaydenYL/Projects | 5 | 41057 | <reponame>JaydenYL/Projects<filename>introcs-1.0/looppi.py
import sys
import stdio
import random
import math
n = int(sys.argv[1])
a = 0
for i in range(n):
while True:
x = -1.0 + 2*random.random()
y = -1.0 + 2*random.random()
a += 1
if x*x +y*y <=1.0:
break
i +=1
st... | 2.953125 | 3 |
users/arxiv/users/legacy/cookies.py | SamanthaFeidFischer/arxiv-auth | 1 | 41058 | """Provides functions for working with legacy session cookies."""
from typing import Tuple
from base64 import b64encode, b64decode
import hashlib
from datetime import datetime, timedelta
from .exceptions import InvalidCookie
from . import util
def unpack(cookie: str) -> Tuple[str, str, str, datetime, str]:
"""
... | 3.078125 | 3 |
micro-ecommerce/payment_gateway/__init__.py | nelsonwenner/bookstore-api | 49 | 41059 | <reponame>nelsonwenner/bookstore-api<filename>micro-ecommerce/payment_gateway/__init__.py
default_app_config = 'payment_gateway.apps.PaymentGatewayConfig' | 0.847656 | 1 |
setup.py | prickles/geokey-checklist | 0 | 41060 | <reponame>prickles/geokey-checklist
#!/usr/bin/env python
from os.path import join
from setuptools import setup, find_packages
name = 'geokey-checklist'
version = __import__(name.replace('-', '_')).__version__
repository = join('https://github.com/ExCiteS', name)
setup(
name=name,
version=version,
descr... | 1.351563 | 1 |
dhalsim/physical_process.py | SimchaVos/DHALSIM | 0 | 41061 | import argparse
import csv
import os
import signal
import logging
from datetime import datetime
from decimal import Decimal
import pandas as pd
import progressbar
import sqlite3
import sys
import time
from pathlib import Path
from dhalsim.parser.file_generator import BatchReadmeGenerator, GeneralReadmeGenerator
from ... | 2.15625 | 2 |
aiida_vasp/utils/neb.py | DropD/aiida_vasp | 3 | 41062 | """
Utility functions for running NEB calculations
"""
import numpy as np
from aiida.orm import StructureData
from aiida.engine import calcfunction
from ase.neb import NEB
@calcfunction
def neb_interpolate(init_structure, final_strucrture, nimages):
"""
Interplate NEB frames using the starting and the final s... | 2.171875 | 2 |
generate_videos.py | weiqiao/pydrake_kuka | 5 | 41063 | import os
import random
# Fullscreen meshlab on right monitor for this to work
for k in range(100, 200):
n_objects = random.randint(5, 10)
os.system("python kuka_pydrake_sim.py -T 60 --seed %d --hacky_save_video -N %d" % (k, n_objects))
| 1.84375 | 2 |
article/views/product_views.py | rayenmhamdi/Kye_BackendAPI | 0 | 41064 | # Create your views here.
from rest_framework import generics
from rest_framework.permissions import IsAuthenticated
from article.models import Product
from article.serializers import ProductSerializer
class ProductListCreateView(generics.ListCreateAPIView):
"""Create Product"""
permission_classes = [IsAu... | 2.28125 | 2 |
django/pyrog/models.py | arkhn/fhir-river | 42 | 41065 | <reponame>arkhn/fhir-river
import uuid
from django.conf import settings
from django.db import models
from cuid import cuid
class Source(models.Model):
id_ = models.TextField(name="id", primary_key=True, default=cuid, editable=False)
name = models.TextField(unique=True)
version = models.TextField(blank=T... | 2.40625 | 2 |
算法设计与分析/作业/homework2T1.py | TD21forever/hdu-term-project-helper | 17 | 41066 | # -*- coding: utf-8 -*-
# @Author: TD21forever
# @Date: 2019-05-26 12:14:07
# @Last Modified by: TD21forever
# @Last Modified time: 2019-06-17 23:11:15
import numpy as np
'''
dp[item][cap]的意思是 从前item个物品中拿东西 放到容量为cap 的背包中 能拿到的最大价值
'''
def solution(num,waste,value,capacity):
dp = np.zeros([num+5,capacity+... | 3.171875 | 3 |
disentanglement_lib/visualize/visualize_scores.py | erow/disentanglement_lib | 0 | 41067 | # coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Un... | 2.453125 | 2 |
_00_pentaton_v02_w_cardContainers.py | ManuelKienast/pent | 0 | 41068 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 18 09:17:23 2018
@author: Manuel
the pentaton logic go around II
"""
import random
random.seed(0)
print(random.getrandbits(5))
# =============================================================================
#
# Variables
# =====================... | 3.671875 | 4 |
viewmodels/shared/viewmodel.py | PASTAplus/web-x | 0 | 41069 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:Mod: viewmodel
:Synopsis:
:Author:
servilla
:Created:
5/25/21
"""
from typing import Optional
from starlette.requests import Request
from services import cookie_auth
class ViewModelBase:
def __init__(self, request: Request):
sel... | 2.234375 | 2 |
packages/w3af/w3af/plugins/audit/frontpage.py | ZooAtmosphereGroup/HelloPackages | 3 | 41070 | <gh_stars>1-10
"""
frontpage.py
Copyright 2006 <NAME>
This file is part of w3af, http://w3af.org/ .
w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.
w3af is distributed in the hope... | 1.898438 | 2 |
example/example/spiders/javdb.py | hwpchn/AroayCloudScraper | 11 | 41071 | import scrapy
from aroay_cloudscraper import CloudScraperRequest
class JavdbSpider(scrapy.Spider):
name = 'javdb'
allowed_domains = ['javdb.com']
headers = {"Accept-Language": "zh-cn;q=0.8,en-US;q=0.6"}
def start_requests(self):
yield CloudScraperRequest("https://javdb.com/v/BOeQO", callback=... | 2.734375 | 3 |
lib/innvestigate/src/innvestigate/applications/imagenet.py | vwesselkamp/deepfake-fingerprint-atacks | 0 | 41072 | <gh_stars>0
"""Example applications for image classifcation.
Each function returns a pretrained ImageNet model.
The models are based on keras.applications models and
contain additionally pretrained patterns.
The returned dictionary contains the following
keys\: model, in, sm_out, out, image_shape, color_coding,
prepr... | 2.46875 | 2 |
ExpSettings/Dataset/SyntheticImages/Dataset.py | gokhangg/Uncertainix | 0 | 41073 | # *=========================================================================
# *
# * Copyright Erasmus MC Rotterdam and contributors
# * This software is licensed under the Apache 2 license, quoted below.
# * Copyright 2019 Erasmus MC Rotterdam.
# * Copyright 2019 <NAME> <<EMAIL>>
# * Licensed under the Apache L... | 1.859375 | 2 |
0x05-python-exceptions/2-safe_print_list_integers.py | C-distin/alx-higher_level_programming | 0 | 41074 | <gh_stars>0
#!/usr/bin/python3
def safe_print_list_integers(my_list=[], x=0):
i = 0
for index in range(x):
try:
print("{:d}".format(my_list[index]), end="")
i += 1
except (ValueError, TypeError):
pass
print()
return i
| 3.609375 | 4 |
devind_helpers/import_from_file/json_reader.py | devind-team/devind-django-helpers | 0 | 41075 | """Модуль считывателя из формата json."""
import json
from typing import Iterable
from .base_reader import BaseReader
class JsonReader(BaseReader):
"""Считыватель из формата json."""
def __init__(self, path: str):
"""Конструктор считывателя из формата json.
:param path: путь к файлу
... | 3.59375 | 4 |
emotion.py | JulienGremillot/human-pose-test | 0 | 41076 | import argparse
import cv2
import numpy as np
from inference import Network
from openvino.inference_engine import IENetwork, IECore
import pylab as plt
import math
import matplotlib
from scipy.ndimage.filters import gaussian_filter
INPUT_STREAM = "emotion.mp4"
CPU_EXTENSION = "C:\\Program Files (x86)\\IntelSWTools\\o... | 2.59375 | 3 |
digital/common/policies/__init__.py | knowx/digital | 0 | 41077 | <gh_stars>0
import itertools
def list_rules():
return itertools.chain() | 1.40625 | 1 |
warehouse/csrf.py | hickford/warehouse | 1 | 41078 | # Copyright 2014 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
... | 1.875 | 2 |
features/steps/backup.py | Zierman/tabsave | 0 | 41079 | <gh_stars>0
from io import StringIO
from behave import *
import tabsave
from features.environment import *
@given(u'there was no game save named "{game_save:w}"')
def step_impl(context, game_save):
remove_game_saves(game_save)
assert not game_save_exists(game_save), f'Expected {game_save} not to exist, but ... | 2.34375 | 2 |
gps_nav/nav_a2b.py | heng2j/delamain | 2 | 41080 | <gh_stars>1-10
import carla
import os
import math
import numpy as np
import pandas as pd
import networkx as nx
from scipy import spatial
import matplotlib.pyplot as plt
def gnss_live_location(event):
"""Get, print, and store the GNSS Measurements.
:return: Float values of Latitude, and Longitude, and Altitude... | 3.15625 | 3 |
gui/main_password.py | FrCln/password-manager | 0 | 41081 | <gh_stars>0
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainpassword.ui'
#
# Created by: PyQt5 UI code generator 5.15.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
import os
from... | 2.015625 | 2 |
votr/main.py | ned1313/flask-voting-gcp | 0 | 41082 | <reponame>ned1313/flask-voting-gcp<gh_stars>0
from flask import Flask, render_template, request, Response, redirect, url_for
import sqlalchemy
from werkzeug.exceptions import abort
from . import sql
# This global variable is declared with a value of `None`, instead of calling
# `init_connection_engine()` immediately... | 2.71875 | 3 |
model/mosesdecoder/contrib/moses-speedtest/check_for_regression.py | saeedesm/UNMT_AH | 3 | 41083 | """Checks if any of the latests tests has performed considerably different than
the previous ones. Takes the log directory as an argument."""
import os
import sys
from testsuite_common import Result, processLogLine, bcolors, getLastTwoLines
LOGDIR = sys.argv[1] #Get the log directory as an argument
PERCENTAGE = 5 #De... | 2.75 | 3 |
Darlington/phase1/python Basic 1/day 16 solution/qtn6.py | CodedLadiesInnovateTech/-python-challenge-solutions | 6 | 41084 | <filename>Darlington/phase1/python Basic 1/day 16 solution/qtn6.py
#program to find the location of Python module sources.
import sys
print("\nList of directories in sys module:")
print(sys.path)
print("\nList of directories in os module:")
import os
print(os.path) | 3.09375 | 3 |
src/spaceone/repository/info/schema_info.py | choonho/repository | 0 | 41085 | import functools
from spaceone.api.repository.v1 import schema_pb2
from spaceone.core.pygrpc.message_type import *
from spaceone.repository.model.schema_model import Schema
from spaceone.repository.info.repository_info import RepositoryInfo
__all__ = ['SchemaInfo', 'SchemasInfo']
def SchemaInfo(schema_vo: Schema, mi... | 2.09375 | 2 |
source/utils.py | ERUD1T3/artificial-neural-network | 0 | 41086 | ############################################################
# Dev: <NAME>
# Class: Machine Learning
# Date: 2/23/2022
# file: utils.py
# Description: utility functions for artificial neural
# network learning
#############################################################
import random
class Data:
'''c... | 3.328125 | 3 |
sim2real_docs/create_random_values.py | agchang-cgl/sim2real-docs | 38 | 41087 | # Copyright FMR LLC <<EMAIL>>
# SPDX-License-Identifier: Apache-2.0
"""
The script generates variations for the parameters using configuration file and stores them in respective named tuple
"""
import math
import random
from collections import namedtuple
import numpy as np
# configuration parameters
scene_options = [... | 2.34375 | 2 |
accounts/forms/__init__.py | BloodLagbe/blood_lagbe | 3 | 41088 | <reponame>BloodLagbe/blood_lagbe
from .forms import(
LoginForm,
RegistrationForm,
ProfileForm
)
from .search_doner import SearchDoner
__all__ = [
LoginForm,
RegistrationForm,
ProfileForm,
SearchDoner
]
| 1.015625 | 1 |
odoo-13.0/addons/sale_coupon/tests/test_program_multi_company.py | VaibhavBhujade/Blockchain-ERP-interoperability | 0 | 41089 | <reponame>VaibhavBhujade/Blockchain-ERP-interoperability<filename>odoo-13.0/addons/sale_coupon/tests/test_program_multi_company.py<gh_stars>0
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.sale_coupon.tests.common import TestSaleCouponCommon
from odo... | 1.90625 | 2 |
.nix/pkgs/development/python-modules/nsf-test-lib/src/nsft_pgp_utils/_colon_listing_impl.py | jraygauthier/nixos_secure_factory | 1 | 41090 | <reponame>jraygauthier/nixos_secure_factory
from typing import Iterator, Dict, List, Union, Optional, Any
from .ctx_auth_types import OptGpgAuthContext
from .ctx_proc_types import OptGpgProcContextSoftT
from .key_types import GpgKeyWExtInfo, GpgKeyExtInfo
from .process import gpg_stdout_it
from .trust_types import mk... | 2.234375 | 2 |
panther_ioc_rules/sunburst_sha256_iocs.py | panther-labs/panther-cli | 4 | 41091 | from panther_iocs import SUNBURST_SHA256_IOCS, ioc_match
def rule(event):
return any(ioc_match(event.get("p_any_sha256_hashes"), SUNBURST_SHA256_IOCS))
def title(event):
hashes = ",".join(ioc_match(event.get("p_any_sha256_hashes"), SUNBURST_SHA256_IOCS))
return f"Sunburst Indicator of Compromise Detecte... | 2.109375 | 2 |
setup.py | KevinMusgrave/pytorch-adapt | 131 | 41092 | import sys
import setuptools
sys.path.insert(0, "src")
import pytorch_adapt
with open("README.md", "r") as fh:
long_description = fh.read()
extras_require_ignite = ["pytorch-ignite == 0.5.0.dev20220221"]
extras_require_lightning = ["pytorch-lightning"]
extras_require_record_keeper = ["record-keeper >= 0.9.31"]... | 1.507813 | 2 |
bh_modules/erlangcase.py | jfcherng-sublime/ST-BracketHighlighter | 1,047 | 41093 | <gh_stars>1000+
"""
BracketHighlighter.
Copyright (c) 2013 - 2016 <NAME> <<EMAIL>>
License: MIT
"""
from BracketHighlighter.bh_plugin import import_module
lowercase = import_module("bh_modules.lowercase")
def validate(*args):
"""Check if bracket is lowercase."""
return lowercase.validate(*args)
| 2.390625 | 2 |
anet-video-captioning/model/modules.py | chihyaoma/cyclical-visual-captioning | 43 | 41094 |
import torch
import torch.nn as nn
import torch.nn.functional as F
class SoftAttention(nn.Module):
"""
Soft Attention module
"""
def __init__(self, rnn_hidden_size, attn_hidden_size, temp=1):
super(SoftAttention, self).__init__()
self.softmax = nn.Softmax(dim=1)
self.h2attn ... | 2.9375 | 3 |
CORE/rule/placement_rule_util.py | CMS0503/CodeOnBoard | 0 | 41095 | class PlacementRuleUtil:
def __init__(self, game_data, placement_data):
self.rule = int(game_data.rule[int(placement_data.obj_number)-1]["placementRule"])
self.placement = placement_data.placement
self.type = game_data.rule[int(placement_data.obj_number)-1]["type"]
self.placement_ty... | 3.390625 | 3 |
tutorials/01-basics/pytorch_basics/main.py | zhangyang1997/pytorch-tutorial | 0 | 41096 | import torch
import torchvision
import torch.nn as nn
import numpy as np
import torchvision.transforms as transforms
# ================================================================== #
# 目录 #
# ===========================================================... | 2.515625 | 3 |
tests/projects/flask1/main.py | mblackgeo/lambdarado_py | 4 | 41097 | from flask import Flask
from lambdarado import start
def get_app():
app = Flask(__name__)
@app.route('/a')
def get_a():
return 'AAA'
@app.route('/b')
def get_b():
return 'BBB'
return app
print("RUNNING main.py")
start(get_app)
| 2.359375 | 2 |
iati/tests/test_version.py | akmiller01/pyIATI | 5 | 41098 | """A module containing tests for the pyIATI representation of Standard metadata."""
import copy
import math
import operator
import pytest
import iati.tests.utilities
from iati.tests.fixtures.versions import iativer, semver, split_decimal, split_iativer, split_semver
class TestVersionInit:
"""A container for tests... | 2.421875 | 2 |
006 - Simple Netcat Replacement/victim_client.py | Danziger/Pluralsight-Network-Penetration-Testing-Using-Python-and-Kali-Linux | 5 | 41099 | <gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import socket
import argparse
def usage():
print '\n\nExample:'
print 'victim_client.py -a 192.168.0.33 -p 9999'
exit(0)
def execute_command(cmd):
cmd = cmd.rstrip() # Remove leading whitespaces
try:
result... | 2.890625 | 3 |