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
postfixhelper.py
frankE/postfix-helper
0
53000
<reponame>frankE/postfix-helper #!/usr/bin/env python3 import re import math import sys import argparse import os import shutil import collections import subprocess if os.path.islink(__file__): sys.path.append(os.path.dirname(os.path.realpath(__file__))) import config import help try: del FILE_CONFIG except: ...
2.25
2
Kattis/erase.py
ruidazeng/online-judge
0
53001
N = int(input()) before = input() after = input() if N % 2 == 0: print("Deletion succeeded" if before == after else "Deletion failed") else: find = True for i in range(len(before)): if before[i] == after[i]: find = False break print("Deletion succeeded" if find else "Del...
3.859375
4
cride/betfriends/views/betfriends.py
albertoaldanar/betmatcherAPI
0
53002
<reponame>albertoaldanar/betmatcherAPI<filename>cride/betfriends/views/betfriends.py from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import generics from rest_framework import status, mixins, viewsets from rest_framework.decorators import api_view from rest_fram...
2.09375
2
config.py
menip/speech-to-text
21
53003
import os # system() def can_build(env, platform): if platform == "x11": has_pulse = os.system("pkg-config --exists libpulse-simple") == 0 has_alsa = os.system("pkg-config --exists alsa") == 0 return has_pulse or has_alsa elif platform in ["windows", "osx", "iphone", "android"]: ...
2.515625
3
ActorCritic/duplicate for DDPG train/Actor.py
bluemapleman/Maple-Reinforcement-Learning
9
53004
class Actor: def __init__(self, sess, learning_rate,action_dim,action_bound): self.sess = sess self.action_dim = action_dim self.action_bound = action_bound self.learning_rate = learning_rate # input current state, output action to be taken self.a = self.build_neural...
2.671875
3
rlpyt/algos/dqn/dsr/action_dsr.py
2016choang/sfl
2
53005
from collections import namedtuple import torch import torch.nn as nn from rlpyt.algos.dqn.dsr.dsr import DSR from rlpyt.algos.utils import valid_from_done from rlpyt.utils.tensor import select_at_indexes, valid_mean OptInfo = namedtuple("OptInfo", ["dsrLoss", "dsrGradNorm", "tdAbsErr"]) class ActionDSR(DSR): ...
2.234375
2
camp/Core/_UnstructuredGridClass.py
blakezim/CAMP
4
53006
import torch class UnstructuredGrid: def __init__(self, vertices, indices, per_vert_values=None, per_index_values=None, device='cpu', dtype=torch.float32): self.vertices = vertices self.indices = indices self.per_vert_value = per_vert_values self.per_index_value =...
2.546875
3
accounts/forms.py
knyghty/bord
0
53007
from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm class UserCreationForm(UserCreationForm): """A form that creates a user.""" class Meta(UserCreationForm.Meta): model = get_user_model() fields = ('username', 'email')
2.46875
2
cla/util/util.py
dickrd/cla_tool
1
53008
# coding=utf-8 def process_qq_history(path, skip_system=True, encoding="utf-8", strip=None, output_path=None): """ Process QQ chat history export text file to sentences. :param path: Path to QQ history txt file. :param skip_system: Skip system message if set. :param encoding: Encoding of the tx...
3.3125
3
riskiq-whoisiq/operations.py
cs-sujeet-ahirrao/connector-riskiq-whoisiq
0
53009
""" Copyright start Copyright (C) 2008 - 2021 Fortinet Inc. All rights reserved. FORTINET CONFIDENTIAL & FORTINET PROPRIETARY SOURCE CODE Copyright end """ import base64 import requests from connectors.core.connector import ConnectorError, get_logger logger = get_logger('riskiq-whoisiq') class RiskIQWHOIS...
2.53125
3
scripts/poc/structs2/s2-45.py
BenDerPan/POCs
7
53010
import http.client import urllib import requests from scripts.poc.poc_interface import PocInterface class Structs2_45(PocInterface): ''' Structs2 漏洞验证及利用实现 ''' def validate(self,url): ''' 验证指定URL是否存在Structs2 45漏洞 :param url: 需要验证的URL地址 :return: True-存在漏洞 False-不存在漏洞 ...
2.46875
2
tvdb_client/utils/utils.py
thilux/tvdb_client
9
53011
<gh_stars>1-10 # encoding=latin-1 __author__ = 'tsantana' import urllib def query_param_string_from_option_args(a2q_dict, args_dict): """ From a dictionary of arguments to query string parameters, loops through ad arguments list and makes a query string. :param a2q_dict: a dictionary containing argument_n...
3.609375
4
src/stdin-timer.py
infinity0/python-snippits
9
53012
#!/usr/bin/env python3 ''' Continuously reads data on stdin until there is no more data. Records how many bytes there were and how long it took to read them. Prints this information. ''' import time import sys import threading write_lock = threading.Lock() thread_done = threading.Event() def report(stop_ev, start_tim...
3.359375
3
chapter_3/exercise_43.py
Tobi-mmt/nltk-book
0
53013
# -*- coding: utf-8 -*- # Aufgaben 6, 7, 20, 21, 24, 30, 34, 39, 38, 41, 43 <NAME> # ----------------- # 43 detect language # ----------------- import nltk, re from nltk import word_tokenize languages = ['Chickasaw', 'English', 'German_Deutsch', 'Greenlandic_Inuktikut', 'Hungarian_Magyar', 'Ibibio_Efik'] def word_f...
3.421875
3
deciphon_api/api/api.py
EBI-Metagenomics/deciphon-api
0
53014
from fastapi import APIRouter, Request from starlette.status import HTTP_200_OK from deciphon_api.api import dbs, hmms, jobs, prods, scans, sched, seqs from deciphon_api.core.responses import PrettyJSONResponse router = APIRouter() router.include_router(dbs.router) router.include_router(hmms.router) router.include_r...
2.390625
2
apnet/gui.py
pzinemanas/APNet
8
53015
import numpy as np from io import BytesIO import wave import struct from dcase_models.util.gui import encode_audio #from .utils import save_model_weights,save_model_json, get_data_train, get_data_test #from .utils import init_model, evaluate_model, load_scaler, save, load #from .model import debugg_model, pr...
1.84375
2
PyFSM/pyfsm/utils/__init__.py
wafec/wafec-py-fsm
0
53016
<reponame>wafec/wafec-py-fsm from .list_utils import ListUtils __all__ = [ 'ListUtils' ]
1.070313
1
plotplayer/validators/__init__.py
Jman420/plotplayer
0
53017
""" PlotPlayer Validators Subpackage contains various modules to support input and type validations. Public Modules: * type_validation - Contains methods to validating various types """
1.335938
1
hallo/test/modules/channel_control/test_operator.py
joshcoales/Hallo
1
53018
<reponame>joshcoales/Hallo from hallo.events import EventMessage, EventMode from hallo.server import Server from hallo.test.server_mock import ServerMock def test_op_not_irc(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.typ...
2.15625
2
app.py
allanberry/cars
0
53019
import json from flask import Flask, Response from flask import render_template, request from bson.json_util import dumps from flask.ext.pymongo import PyMongo app = Flask( __name__, static_folder="view", ) app.config['MONGO_DBNAME'] = 'cars_db' mongo = PyMongo(app) @app.route("/") def home(): return...
2.765625
3
python/coursera_python/MICHIGAN/web/2/dict_fin.py
SayanGhoshBDA/code-backup
16
53020
import urllib.request, urllib.parse, urllib.error # http://www.py4e.com/code3/bs4.zip # and unzip it in the same directory as this file from urllib.request import urlopen import re from bs4 import BeautifulSoup import ssl import sqlite3 conn = sqlite3.connect('wiki2.sqlite') cur = conn.cursor() cur.executescript(...
3.125
3
npsn/models/svr.py
a-jd/npsn
5
53021
''' NPSN Support Vector Regression Class ''' import os from joblib import dump, load # Base model from .base import BaseModel # Import for SVR from sklearn.multioutput import MultiOutputRegressor as MOR from sklearn.metrics import mean_squared_error as sklmse from sklearn.svm import NuSVR # hyperopt imports from hy...
2.65625
3
MRS Models/IBCF_cos_similarity.py
skdhitman/Music-Recommender-System
0
53022
# -*- coding: utf-8 -*- """ Created on Thu Oct 22 09:00:08 2020 @author: SKD-HiTMAN """ import pandas as pd import numpy as np from sklearn.metrics.pairwise import cosine_similarity ratings = pd.read_csv('../Dataset/MovieLens/ml-latest-small/ratings.csv') songs = pd.read_csv('../Dataset/MovieLens/ml-la...
2.953125
3
demo_hierarchy_tutorial/models/models.py
digitalsatori/odoo-demo-addons-tutorial
57
53023
<reponame>digitalsatori/odoo-demo-addons-tutorial from odoo import models, fields, api class DemoHierarchyTutorial(models.Model): _name = 'demo.hierarchy' _description = 'Demo Hierarchy Tutorial' name = fields.Char(string='name', index=True) parent_id = fields.Many2one('demo.hierarchy', string='Relate...
1.96875
2
00-modules/data_science_visualization_modules/matplotlib_examples.py
cccaaannn/useful_functions
0
53024
import numpy as np import matplotlib.pyplot as plt # documentation # https://matplotlib.org/3.1.3/api/pyplot_summary.html # scatter plot x = np.random.randint(100, size=(100)) y = np.random.randint(100, size=(100)) plt.scatter(x, y, c='tab:blue', label='stuff') plt.legend(loc=2) # plt.show() # line plot x = np.a...
3.234375
3
plugin/taskmage2/utils/excepts.py
willjp/vim-taskmage
1
53025
<reponame>willjp/vim-taskmage class ParserError(Exception): pass
1.085938
1
pype/semantic_analysis.py
207leftovers/cs207project
0
53026
from pype.ast import * from pype.error import * class PrettyPrint(ASTVisitor): def __init__(self): pass def visit(self, node): print(node.__class__.__name__) class CheckSingleAssignment(ASTVisitor): def __init__(self): self.component_names = [] self.names_used = [] def visit(self, node): ...
2.9375
3
scripts/get-jars.py
Open-EO/openeo-geopyspark-driver
12
53027
<filename>scripts/get-jars.py """ Script to download (custom) geotrellis backend assemly and geotrellis extensions jars To be used instead of `geopyspark install-jar` """ import logging from pathlib import Path import subprocess import urllib.request logger = logging.getLogger("get-jars") def ensure_jar_dir(jar_d...
2.53125
3
unobase/api/constants.py
unomena/unobase
0
53028
''' Created on 15 Jan 2013 @author: euan ''' from django.conf import settings REQUEST_STATUS_CREATED = 0 REQUEST_STATUS_SUCCESS = 1 REQUEST_STATUS_ERROR = 2 REQUEST_STATUS_RETRY = 3 REQUEST_STATUS_ABORT = 4 REQUEST_STATUS_CHOICES = ((REQUEST_STATUS_CREATED,'Created'), (REQUEST_STATUS_SUCCE...
1.789063
2
yahoo_finance_pynterface/api.py
mellon85/yahoo-finance-pynterface
15
53029
from . import core import io import re import requests import pytz import time import datetime as dt import dateutil.parser as du import numpy as np import pandas as pd from typing import Tuple, Dict, List, Union, ClassVar, Any, Optional, Type import types class ...
2.703125
3
growth/microscopy/images.py
sebastianbernasek/growth
1
53030
import numpy as np import matplotlib.pyplot as plt from copy import deepcopy from ..measure import ConditionedLognormalSampler class ScalarImage: """ Class containing a scalar image. """ def __init__(self, height=1000, width=1000): """ Instantiate scalar image with shape (<height>, <width>)....
2.765625
3
PI/Platform/OpenGL/OpenGLBuffer.py
HotShot0901/PI
0
53031
from ...Renderer.Buffer import VertexBuffer, IndexBuffer, BufferLayout from OpenGL.GL import glGenBuffers, glBufferData, glDeleteBuffers, glBindBuffer, glBufferSubData from OpenGL.GL import GL_ARRAY_BUFFER, GL_STATIC_DRAW, GL_ELEMENT_ARRAY_BUFFER, GL_DYNAMIC_DRAW import ctypes import numpy as np from multipledispatch...
2.140625
2
src/shinymud/lib/shinymail.py
shinymud/ShinyMUD
35
53032
<gh_stars>10-100 from shinymud.data.config import EMAIL_HOST, EMAIL_PORT, EMAIL_HOST_USER,\ EMAIL_HOST_PASSWORD, EMAIL_USE_TLS from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import smtplib class ShinyMail(object): """ShinyMail constructs and se...
2.765625
3
meetings/datetime_func.py
isw4/Proj10-when2meet
0
53033
<reponame>isw4/Proj10-when2meet import arrow from dateutil import tz
1.132813
1
tensorflow_gnn/graph/tensor_utils.py
AnotherGroupChat/gnn
0
53034
<reponame>AnotherGroupChat/gnn """Utils for tensors and ragged tensors.""" from typing import List, Optional, Text, Union from keras.engine import keras_tensor as kt import tensorflow as tf Value = Union[tf.Tensor, tf.RaggedTensor] def dims_list(tensor: tf.Tensor) -> List[Union[int, tf.Tensor]]: """Lists tensor d...
2.546875
3
other/backpack.py
DanilaDanila/lessons
4
53035
r = int(input()) w = [int(x) for x in input().split()] c = [int(x) for x in input().split()] m = [0] for i in range(1, r + 1): m.append(max([x[0] + m[i - x[1]] for x in zip(c, w) if x[1] <= i], default = 0)) print(m)
2.71875
3
ffmpeg/filters/afilters.py
busterbeam/ffmpeg-generator
23
53036
<filename>ffmpeg/filters/afilters.py ''' Date: 2021.02-28 22:29:00 LastEditors: <NAME> LastEditTime: 2021.04.25 13:31:49 ''' from ..nodes import FilterableStream, Stream, filterable from .avfilters import filter __all__ = [] """Audio Filters https://ffmpeg.org/ffmpeg-filters.html#Audio-Filters """ @filterable() de...
2
2
web/app/lib/earthengine/__init__.py
geary/claslite
0
53037
<filename>web/app/lib/earthengine/__init__.py<gh_stars>0 # -*- coding: utf-8 -*- """ Earth Engine interface ~~~~~~~~~~~~~~~~~~~~ :By <NAME> - http://mg.to/ :See UNLICENSE or http://unlicense.org/ for public domain notice. """ import cgi, logging, sys, os import ee from oauth2client import appengine from google.ap...
2.375
2
tests/coworks/blueprint/test_mail.py
sidneyarcidiacono/coworks
0
53038
<reponame>sidneyarcidiacono/coworks import os import smtplib from email import message from io import BytesIO from unittest import mock import pytest from coworks import TechMicroService from coworks.blueprint.mail_blueprint import Mail from coworks.config import LocalConfig smtp_mock = mock.MagicMock() smtp_mock.re...
2.25
2
micro_shop/staff/views.py
SlavaSkvortsov/micro-shop
1
53039
from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.messages.views import SuccessMessageMixin from django.views.generic import UpdateView from staff.models import UserProfile class UserProfileUpdate(LoginRequiredMixin, SuccessMessageMixin, UpdateView): model = UserProfile success_me...
1.8125
2
Terucheese011.py
jwepkkrr/reversi2021
0
53040
# # オセロ(リバーシ) 6x6 # N = 6 # 大きさ EMPTY = 0 # 空 BLACK = 1 # 黒 WHITE = 2 # 白 STONE = ['□', '●', '○'] #石の文字 # # board = [0] * (N*N) # def xy(p): # 1次元から2次元へ return p % N, p // N #35の座標の出力(5,5) def p(x, y): # 2次元から1次元へ return x + y * N #35を出力 # リバーシの初期画面を生成する def init_board(): board = [EMPTY]...
3.6875
4
gcs_operations/permissions_issuer.py
openskies-sh/aerobridge
5
53041
<gh_stars>1-10 from gcs_operations.models import FlightOperation, FlightPermission import json import arrow from pki_framework import encrpytion_util from Crypto.Hash import SHA256 from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 from django.conf import settings from pki_framework.models import ...
2.28125
2
test_application.py
Rafagd/party_invite
0
53042
<gh_stars>0 import coords import customers import math import random import main # Test if coods are being created and if their # lats/lons are in radians after creation def test_coords(): for i in range(1000): lat = random.uniform(-90, 90) lon = random.uniform(-180, 180) cds = coords.Coord...
3.34375
3
reporting/tests/test_reports.py
flagshipenterprise/django-prickly-reports
1
53043
<gh_stars>1-10 from datetime import date from django.test import TestCase from django.forms import Form from reporting.base import Filter, Report from reporting.filters import CharFilter, DateFilter class ConcreteReportClass(Report): """ A sample report class, just for use within the tests module. It just ...
2.890625
3
silene/crawler_configuration.py
peterbencze/silene
0
53044
<reponame>peterbencze/silene<filename>silene/crawler_configuration.py # Copyright 2020 <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...
2.25
2
custom_components/meter_parser/sensor.py
junalmeida/ha-meterparser
2
53045
"""Meter Parser Image Processing component and sensor.""" # Copyright 2021 <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...
1.671875
2
irf/scripts/create_fact_exposure_map.py
fact-project/irf
0
53046
from irf import estimate_exposure_time, build_exposure_map import click import fact.io as fio import pandas as pd from astroquery.skyview import SkyView from astropy.wcs import WCS from astropy.visualization import ImageNormalize, ZScaleInterval, AsinhStretch import astropy.units as u from astropy.coordinates import Sk...
2.53125
3
benri/cloudpickle_wrapper.py
MaxOSmith/benri
0
53047
""" Class to serialize data for multiprocessing. Inspired by: https://github.com/openai/baselines/blob/master/baselines/common/vec_env/__init__.py """ import cloudpickle import pickle class CloudpickleWrapper(object): """ Uses `cloudpickle` to serialize contents. """ def __init__(self, data): self.d...
2.78125
3
crowd_anki/anki/adapters/anki_deck.py
ll-in-anki/CrowdAnki
391
53048
<filename>crowd_anki/anki/adapters/anki_deck.py from cached_property import cached_property from dataclasses import dataclass from typing import Callable @dataclass class AnkiDeck: _data: dict deck_name_separator = '::' @property def data(self): return self._data @property def is_d...
2.5625
3
semantic_segmentation/preprocessing/preprocessor.py
FMuenke/semantic_segmentation
0
53049
import numpy as np import cv2 from semantic_segmentation.data_structure.image_handler import ImageHandler class Preprocessor: def __init__(self, image_size): self.image_size = image_size self.min_height = 16 self.min_width = 16 self.max_height = 900 self.max_width = 900 ...
2.84375
3
whattowatch/core/models.py
svhenrique/What-To-Watch-backend
0
53050
<filename>whattowatch/core/models.py from tabnanny import verbose from embed_video.fields import EmbedVideoField from core.utils import get_file_path from django.db import models from pydoc import describe CHOICES_RATTING = [ (0, "L"), (10, "10"), (12, "12"), (14, "14"), (16, "16"), (18, "18"),...
2.28125
2
tron/Nubs/TUI.py
sdss/tron
0
53051
import socket import time from tron import g, hub from tron.Hub.Command.Decoders.ASCIICmdDecoder import ASCIICmdDecoder from tron.Hub.Nub.Commanders import AuthStdinNub from tron.Hub.Nub.Listeners import SocketListener from tron.Hub.Reply.Encoders.ASCIIReplyEncoder import ASCIIReplyEncoder name = 'TUI' listenPort = ...
2.21875
2
test/test_markdown_converter.py
wgroeneveld/dokuwiki-to-hugo
8
53052
from unittest import TestCase from pathlib import Path from src.markdown_converter import MarkdownConverter class TestMarkdownHeader(TestCase): def setUp(self): self.converter = MarkdownConverter("test/dokuwiki_example.txt") def test_acceptance_test_case(self): # python 3.5 and up e...
3.015625
3
environ/blog/views.py
CassandraTalbot32/Python-Django-CSS-HTML-JavaScript-webiste
0
53053
<filename>environ/blog/views.py<gh_stars>0 from django.shortcuts import render, get_object_or_404 from django.urls import reverse # Create your views here. from django.views.generic import ( CreateView, DetailView, ListView, UpdateView, ListView, DeleteView ) from .forms import ArticleModelForm from .models impo...
2.3125
2
import.py
Findus23/citybike
0
53054
#!/usr/bin/python3 import json import sys from pprint import pprint import requests from config import database import MySQLdb try: db = MySQLdb.connect(database["host"], database["user"], database["passwd"], database["db"]) cur = ...
2.5625
3
src/colour.py
alvaropp/keep-exploring
0
53055
import numpy as np def compute_intensity(pos, pos_list, radius): return (norm(np.array(pos_list) - np.array(pos), axis=1) < radius).sum() def compute_colours(all_pos): colours = [compute_intensity(pos, all_pos, 1e-4) for pos in all_pos] colours /= max(colours) return colours
2.84375
3
examples/Python_3.py
JStearsman/hello-worlds
81
53056
#prints hello world letter by letter on windows system import os,time def slowhello(): s = 'Hello World!' for i in range(len(s)): os.system('cls') print (s[:i+1]) time.sleep(0.5) slowhello()
3.46875
3
divideWords.py
MrElvin/opera-spider
0
53057
<filename>divideWords.py<gh_stars>0 # 导入所需要的包 # 其中 bs4, jieba, wordcloud, numpy, PIL 需要额外安装 import codecs import jieba import jieba.analyse from wordcloud import WordCloud import numpy as np from PIL import Image # 利用 TFIDF 或 TextRank 算法从 tex 中提取关键词 def get_keyword(text, mode, topK=20): if mode == "tfidf": retur...
2.734375
3
bke/bke_client/forms.py
Ntermast/BKE
0
53058
<reponame>Ntermast/BKE<filename>bke/bke_client/forms.py from django import forms from django.core.validators import FileExtensionValidator from .models import Channel, Podcast class ChannelForm(forms.ModelForm): image = forms.ImageField(required=True) class Meta: model = Channel fields = ('im...
1.953125
2
ovs/extensions/migration/migration.py
mflu/openvstorage_centos
1
53059
<reponame>mflu/openvstorage_centos # Copyright 2014 CloudFounders NV # # 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 ...
1.984375
2
src/oolongt/parser/parser_config.py
schmamps/textteaser
2
53060
"""Parser Configuration Reader""" import typing from json import JSONDecodeError from pathlib import Path from nltk.corpus import stopwords from ..constants import ( BUILTIN, DEFAULT_IDEAL_LENGTH, DEFAULT_IDIOM, DEFAULT_LANGUAGE, DEFAULT_NLTK_STOPS, DEFAULT_USER_STOPS) from ..io import load_json from ..repr_a...
2.65625
3
6.0_prs_random_forest.py.py
psohn/Forest_Fires_Regression
2
53061
<reponame>psohn/Forest_Fires_Regression ### because how can you not use random forest regression on a forest fire ### regression? this is lazily coded and uncommented. purely for entertainment ### and completion import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import r...
2.828125
3
code/aip/misc/misc.py
andymiller/ReducedVarianceReparamGradients
36
53062
<reponame>andymiller/ReducedVarianceReparamGradients import autograd.numpy as np from autograd.scipy.special import gammaln def sigmoid(a): return 1. / (1. + np.exp(-a)) def logit(a): return np.log(a) - np.log(1-a) def mvn_diag_logpdf(x, mean, log_std): D = len(mean) qterm = -.5 * np.sum((x - mean)...
2.59375
3
tno/mpc/encryption_schemes/utils/fixed_point.py
TNO-MPC/encryption_schemes.utils
0
53063
""" This is module implementing fixed point numbers for python. For a motivation, description and some examples, we refer to the docstring of the FixedPoint class. """ from __future__ import annotations import numbers from secrets import randbelow from typing import Optional, Tuple, Union # Add numpy support, if ava...
4.03125
4
FirstSteps/Rectangle.py
B3WD/python-oop
0
53064
from Point import Point class Rectangle: def __init__(self, p, w, h): self.CornerPoint = p self.width = w self.height = h def __str__(self): return f"Rectangle {self.width} by {self.height}, at {self.CornerPoint}." def transpose(self): self.width, self.height = s...
3.625
4
scripts/video.py
isamumu/GazeVechicle
2
53065
<reponame>isamumu/GazeVechicle import cv2 video_capture = cv2.VideoCapture(2) success, frame = video_capture.read() while(success): cv2.imshow("frame", frame) cv2.waitKey(10) success, frame = video_capture.read()
2.484375
2
sc2agents/learning/deep/keras/network.py
jawoszek/sc2-intelligent-agents
0
53066
<reponame>jawoszek/sc2-intelligent-agents from keras.utils import to_categorical from numpy import array import sc2agents.learning.deep.keras.parsers as parsers def train(model, input_data, output_data, epochs): x_train = array(input_data) y_train = to_categorical(array(output_data).T[0], num_classes=2) ...
2.75
3
genRandInputs.py
deehzee/affine-charform
2
53067
# genRandInput.py - Generate ranodom input def random_inputs(N = 5, maxvarn = 4, maxs = 3): # N = size of each sample size for each kind # maxvarn = maximum variation for n # maxs = maximum value for s_i # X = type (A, B, C, D, E or F) # n = subscript # r = superscript # S = specialization ...
2.984375
3
venv/Lib/site-packages/pyo/examples/06-filters/07-hilbert-transform.py
mintzer/pupillometry-rf-back
0
53068
""" 07-hilbert-transform.py - Barberpole-like phasing effect. This example uses two frequency shifters (based on complex modulation) linearly shifting the frequency content of a sound. Frequency shifting is similar to ring modulation, except the upper and lower sidebands are separated into individual outputs. """ fr...
3.5
4
bee_colony/continuous_test.py
srom/abc
0
53069
<gh_stars>0 import unittest import numpy as np from .continuous import ABC from .utils import uniform_init class TestArtificialBeeColony(unittest.TestCase): def setUp(self, *args, **kwargs): super().setUp(*args, **kwargs) np.random.seed(123) def test_univariate(self): def fitness_...
2.734375
3
src/aoc2015/day0.py
emauton/aoc2015
0
53070
'''"Template" day module for AoC 2015''' def run(args): print(f'day0: {args}')
1.4375
1
116.py
BYOUINZAKA/LeetCodeNotes
0
53071
''' @Author: Hata @Date: 2020-07-26 03:41:32 @LastEditors: Hata @LastEditTime: 2020-07-28 21:31:17 @FilePath: \LeetCode\116.py @Description: https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/ ''' class Solution: def connect(self, root: 'Node') -> 'Node': if root is None: ...
3.546875
4
app/test/send_data.py
gpp0725/EchoProxy
0
53072
<filename>app/test/send_data.py # !/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/3/3 0003 1:02 # @Author : Gpp # @File : send_data.py import requests data = {"local": "beijing"} proxy_data = {'proxy_data': [ {"v": "2", "ps": "BWG-LA", "add": "192.168.127.12", "port": "62860", ...
2.109375
2
xbox/nano/packet/control.py
arix-dev/xbox-smartglass-nano-python
100
53073
# flake8: noqa from construct import * from xbox.sg.utils.struct import XStruct from xbox.sg.utils.adapters import XSwitch, XEnum, PrefixedBytes from xbox.nano.enum import ControlPayloadType, ControllerEvent """ ControlProtocol Streamer Messages """ session_init = XStruct( 'unk3' / GreedyBytes ) session_create...
1.882813
2
examples/basic/mesh_map2cell.py
mikami520/vedo
1
53074
<reponame>mikami520/vedo """Map an array which is defined on the vertices of a mesh to its cells""" from vedo import * doc = Text2D(__doc__, pos="top-center") mesh1 = Mesh(dataurl+'icosahedron.vtk').lineWidth(0.1).flat() # let the scalar be the z coordinate of the mesh vertices msg1 = Text2D("Scalars originally defi...
2.6875
3
tests/test_mesh_transform_problem.py
gramaziokohler/integral_timber_joints
3
53075
import cProfile import compas from compas.datastructures import Mesh, mesh_transform from compas.geometry import Frame, Point, Transformation, Vector print('compas.__version__ : ', compas.__version__) f1 = Frame([2, 2, 2], [0.12, 0.58, 0.81], [-0.80, 0.53, -0.26]) f2 = Frame([1, 1, 1], [0.68, 0.68, 0.27], [-0.67, 0....
2.46875
2
find_conserved_blocks_v2.2.py
joldie/bioinformatics-tools
0
53076
#!/usr/bin/python3 # find_conserved_blocks_v*.py ########################### # Overview: # Script analyses DNA multi sequence alignment data and searches for areas # (blocks) which are conserved (i.e. identical or very similar). Required # input is any valid FASTA file with multiple sequences. # User can adjus...
3.09375
3
capture.py
svencan/motherdocker
0
53077
from selenium import webdriver class Capture: position_x = None position_y = None position_z = None yaw = None pitch = None roll = None def initiate(self, browser): self.position_x = browser.find_element_by_id('x-range').find_element_by_css_selector('div') self.position_y...
2.953125
3
archive/parallel_bfs_algo_mp.py
luishengjie/parallel-bfs
0
53078
__author__ = "<NAME>" __email__ = "<EMAIL>" """ Baseline parallel BFS implementation. Algorithm 1 Parallel BFS algorithm: High-level overview [1] was implemented. Reference: [1] https://www.researchgate.net/publication/220782745_Scalable_Graph_Exploration_on_Multicore_Processors """ import n...
3.046875
3
FusionIIIT/applications/eis/api/urls.py
29rj/Fusion
29
53079
from django.conf.urls import url from . import views urlpatterns = [ # generic profile endpoint url(r'^profile/(?P<username>\w+)/', views.profile, name='profile-api'), # current user profile url(r'^profile/', views.profile, name='profile-api'), ]
1.65625
2
dataset/.ipynb_checkpoints/dataset_seg-checkpoint.py
amri369/skin-lesion-segmentation
0
53080
from torch.utils.data import Dataset import torch import os import pandas as pd from PIL import Image class Dataset(Dataset): def __init__(self, csv_file, image_dir, mask_dir, img_col='image', mask_col='mask', transform=None, batch_size=32): """ Args: csv_file (P...
3.3125
3
main/SimulationSettings/FluctuationAmplitudePython/Simulation/FluctuationAmplitude.py
JulianoGianlupi/nh-cc3d-4x-base-tool
0
53081
<gh_stars>0 from cc3d import CompuCellSetup from .FluctuationAmplitudeSteppables import FluctuationAmplitude CompuCellSetup.register_steppable(steppable=FluctuationAmplitude(frequency=100)) CompuCellSetup.run()
1.335938
1
StockAnalysisSystem/porting/vnpy_chart/__init__.py
lifg2000/StockAnalysisSystem
138
53082
<gh_stars>100-1000 from .widget import ChartWidget from .item import CandleItem, VolumeItem, ChartItem, MemoItem from .data import BarData from .constant import *
1.117188
1
venv/lib/python3.9/site-packages/led/__init__.py
eniga/mqtt_trafficlight
0
53083
<gh_stars>0 """ LED is a Docker utility for Lets Encrypt. Copyright (C) 2019 <NAME> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any la...
2.75
3
bcc/toys/count_mkdir.py
XieGuochao/ebpf-examples
0
53084
#!/usr/bin/python3 # count_mkdir.py # Author: Guochao # Created on 17-01-2022 # Print timing of mkdir from bcc import BPF program = r""" #include <uapi/linux/ptrace.h> BPF_HASH(count); int do_trace(struct pt_regs *ctx) { u64 c1 = 1, *cnt, delta, key = 1; cnt = count.lookup(&key); if (cnt != NULL)...
2.34375
2
ZeroBot/database.py
ZeroKnight/ZeroBot
0
53085
<filename>ZeroBot/database.py """database.py Interface to ZeroBot's SQLite 3 database backend. """ from __future__ import annotations import asyncio import json import logging import re import sqlite3 from datetime import datetime from pathlib import Path from typing import AnyStr, Iterator, Optional, Union import ...
2.46875
2
scripts/protocol/ibp/exceptions.py
periscope-ps/unis
2
53086
<reponame>periscope-ps/unis # ============================================================================= # periscope-ps (unis) # # Copyright (c) 2012-2016, Trustees of Indiana University, # All rights reserved. # # This software may be modified and distributed under the terms of the BSD # license. See the COPY...
1.6875
2
BLE_Notifications.py
JyriLehtinen/Bluetooth
0
53087
<gh_stars>0 #!/usr/bin/python #This code scans for BLE advertising and decodes sensor data from a certain type of sensor module prototype import sys from bluepy.btle import Scanner, DefaultDelegate, Peripheral, BTLEException, Service, Characteristic import os import time class SensorDelegate(DefaultDelegate): m...
3.078125
3
src/fpm_tablut_player/utils/timer.py
contimatteo/PMF-Tablut-Player
0
53088
<reponame>contimatteo/PMF-Tablut-Player import time ### class Timer: start_time: float def __init__(self): self.start_time = None def start(self): if self.start_time is not None: raise Exception(f"Timer is running. Use .stop() to stop it") self.start_time = time.pe...
2.921875
3
california_housing_prices/room_density.py
Bartosz-D3V/ml-dataset-analysis
0
53089
from sklearn.base import BaseEstimator, TransformerMixin ''' Add new feature - proportion of rooms to households ''' class RoomDensity(BaseEstimator, TransformerMixin): def fit(self, X, y=None): return self def transform(self, X, y=None): X['room_density'] = X['total_rooms'] / X['households...
2.890625
3
tools/string_table_parser/string_table_reader.py
fingerco/sims-4-mac-modding-tools
3
53090
import struct import datetime from .constants import MAGIC_NUMBER from .string_table_file import StringTableFile from .string_table_header import StringTableHeader from .string_table_string import StringTableString from .constants import HEADER_SIZE, STRING_HEADER_SIZE class StringTableReader: def __init__(self, f...
2.734375
3
tests/unit/test_impulse_response_unit.py
sadielbartholomew/openscm-twolayermodel
6
53091
import numpy as np import numpy.testing as npt import pytest from openscm_units import unit_registry as ur from test_model_base import TwoLayerVariantTester from openscm_twolayermodel import ImpulseResponseModel, TwoLayerModel from openscm_twolayermodel.base import _calculate_geoffroy_helper_parameters from openscm_tw...
2.203125
2
parte 1/desafio06.py
BrunoSoares-DEV/Exercicios-python
2
53092
#pegando numero num = int(input('Digite um número qualquer: ')) numDob = num * 2 numTri = num * 3 numRaiz = num**(1/2) #Raiz quadrada é o mesmo que o numero elevado ao meio 1/2 print('O número digitado foi {}, seu dobro é {}, seu triplo é {}, e por fim sua raiz é {}'.format(num, numDob, numTri, numRaiz)) ''' A var...
4.375
4
app/study/filterEma.py
kyoungd/material-stock-finder-app
0
53093
import pandas as pd from util import StockAnalysis, AllStocks import talib import os import numpy as np class FilterEma: def __init__(self, barCount, showtCount=None, longCount=None): self.sa = StockAnalysis() self.jsonData = self.sa.GetJson self.trendLength = int(os.getenv('FILTER_TREND_LE...
2.859375
3
UnitTest/TestPyBulletEnv.py
stevenjj/PnC
1
53094
import os import sys import inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(os.path.dirname(currentdir)) os.sys.path.insert(0,parentdir) import os sys.path.append(os.getcwd()+'/ReinforcementLearning') import MyGym import gym import argparse impo...
2.390625
2
dev/Gems/CloudGemPlayerAccount/AWS/resource-manager-code/command.py
brianherrera/lumberyard
1,738
53095
<filename>dev/Gems/CloudGemPlayerAccount/AWS/resource-manager-code/command.py # # All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or # its licensors. # # For complete copyright and license terms please see the LICENSE at the root of this # distribution (the "License"). All use of this sof...
2.125
2
bin/reverseComplement.py
PapenfussLab/Mungo
1
53096
#!/usr/bin/env python """ reverse_comp.py <filename> Prints the reverse complement of a DNA string (in fasta format). """ import sys from mungo import fasta from mungo import sequence if len(sys.argv)!=2 or '-h' in sys.argv or '--help' in sys.argv: sys.exit(__doc__) for h,s in fasta.FastaFile(sys.argv[1]): ...
3.359375
3
package.py
OSS-Pipeline/rez-boost
0
53097
<reponame>OSS-Pipeline/rez-boost<filename>package.py name = "boost" version = "1.61.0" authors = [ "<NAME>", "<NAME>" ] description = \ """ Boost is a set of libraries for the C++ programming language that provide support for tasks and structures such as linear algebra, pseudorandom number genera...
1.4375
1
backend/tests/e2e/conftest.py
garytyler/uvp-web
0
53098
<filename>backend/tests/e2e/conftest.py import copy import os import tarfile from pathlib import Path import pytest @pytest.fixture(autouse=True) def xserver(pg_container, xserver_factory, pytestconfig, settings): _environ = copy.copy(os.environ) _environ.update( dict( PYTHONPATH=os.path....
2.0625
2
tests/migrations/0014_auto_20200327_1152.py
intellineers/django-bridger
2
53099
<filename>tests/migrations/0014_auto_20200327_1152.py # Generated by Django 2.2.11 on 2020-03-27 10:52 import django_fsm from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("tests", "0013_auto_20200219_1324"), ] operations = [ migrations.AlterField( ...
1.617188
2