seq_id
stringlengths
4
11
text
stringlengths
113
2.92M
repo_name
stringlengths
4
125
sub_path
stringlengths
3
214
file_name
stringlengths
3
160
file_ext
stringclasses
18 values
file_size_in_byte
int64
113
2.92M
program_lang
stringclasses
1 value
lang
stringclasses
93 values
doc_type
stringclasses
1 value
stars
int64
0
179k
dataset
stringclasses
3 values
pt
stringclasses
78 values
73648313937
def lukuLaskeminen(luvut): laskuTulos = 0 for luku in luvut: laskuTulos += luku return laskuTulos lista = [] laskemaan = False while laskemaan != True: uusiLuku = int(input("Anna kokonaisluku: ")) print("Listaan lisätty uusi luku, jos annoit 0 luvun lista lasketaan läpi.") lista.appe...
Xanp0/NoelS_Ohjelmisto1
moduuli_06/teht4_ListaKokonaislukuja.py
teht4_ListaKokonaislukuja.py
py
456
python
fi
code
0
github-code
13
37562347758
# The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. # Find the sum of all the primes below two million. import math def prime_finder(x): if x == 1: return False,int(x) elif x == 2: return True,int(x) else: for i in range(2,int(math.sqrt(x)+1)): if (x%i == 0)...
mertsengil/Project_Euler_with_Python
Problem_10.py
Problem_10.py
py
592
python
en
code
0
github-code
13
1114757556
import pygame, random from Globals import WINDOWWIDTH, WINDOWHEIGHT class Sprite: sprites = [] def __init__(self, parent, coordinates: tuple, scale: float, randscale: tuple, ticker: int = 0, sprite_n: int = 0...
TheoDaizer/Fiy_me_to_the_Moon
BaseObjects.py
BaseObjects.py
py
7,702
python
en
code
0
github-code
13
72512467218
import sqlite3 as lite # Conecta con la base de datos que origina OpenWPM como resultado wpm_db = "crawl-data.sqlite" conn = lite.connect(wpm_db) cur = conn.cursor() # Define los valores que permiten comprobar las condiciones de fingerprinting por objetos informativos de JS info_ob= ["window.navigator.appCodeName", "...
jdanml/Web-Fingerprinting-Detection-Tool
Scripts/script_informativeJS_RC_v3.py
script_informativeJS_RC_v3.py
py
2,156
python
en
code
0
github-code
13
21104602164
from django.conf.urls import patterns, include, url from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), #Sessions url(r'^accounts/', include('allauth.urls')), #il8n (r'^i18n/', include('django...
AryGit/arytest
arytest/urls.py
urls.py
py
399
python
en
code
0
github-code
13
70234340497
""" This script is a leet speak convertissor. It takes a string and it returns the string written in leet speak. """ def permutation(letter): """Function that transforms letter in leet speak equivalent""" if letter == "a": new_letter = "4" elif letter == "b": new_letter = "8" ...
AlexBardDev/Funny_Python
leet_speak_convertissor.py
leet_speak_convertissor.py
py
1,188
python
en
code
0
github-code
13
70436968979
## Website:: Interviewbit ## Link:: https://www.interviewbit.com/problems/redundant-braces/ ## Topic:: Stacks ## Sub-topic:: Simple ## Difficulty:: Medium ## Approach:: ## Time complexity:: O(N) ## Space complexity:: O(N) ## Notes:: class Solution: # @param A : string # @return an integer def braces(self...
anujkhare/algorithms
solutions/Stacks and queues/RedundantBraces.py
RedundantBraces.py
py
836
python
en
code
1
github-code
13
5174083226
from __future__ import with_statement import argparse from functools import wraps import os import sys import errno import logging from fuse import FUSE, FuseOSError, Operations import inspect log = logging.getLogger(__name__) def logged(f): @wraps(f) def wrapped(*args, **kwargs): log.info('%s(%s...
claydegruchy/vtt-image-tag
custom_fs.py
custom_fs.py
py
8,907
python
en
code
0
github-code
13
3454987611
from datetime import datetime import pandas as pd from privacy.base import suppress_only from privacy.bayardo import BayardoAnonymizer class BayardoExtendedAnonymizer: """ Optimal k-Anonymity [Bayardo et al.] to generate fairness """ def __init__(self, df, quasi_identifier, grouping_keys, use_suppr...
johnruth96/privacy-justifiable-fairness
privacy/bayardoext.py
bayardoext.py
py
3,771
python
en
code
0
github-code
13
37313915498
from django.urls import path from users.views import ( DepositView, UserCreateView, UserDetailView, UserLoginView, UserLogoutView ) urlpatterns = [ path('login', UserLoginView.as_view(), name='login'), path('logout', UserLogoutView.as_view(), name='logout'), path('register', UserCreat...
coldwhiskeyman/fry_shop
users/urls.py
urls.py
py
497
python
en
code
0
github-code
13
13514006086
from ebcli.core import fileoperations, io from ebcli.core.abstractcontroller import AbstractBaseController from ebcli.operations import platformops, platform_version_ops from ebcli.resources.strings import strings, flag_text, prompts class GenericPlatformDeleteController(AbstractBaseController): class Meta: ...
aws/aws-elastic-beanstalk-cli
ebcli/controllers/platform/delete.py
delete.py
py
3,695
python
en
code
150
github-code
13
23905384621
#!/usr/bin/env python3 """1-rnn.py""" import numpy as np def rnn(rnn_cell, X, h_0): """function that performs forward propagation for the RNN""" t = X.shape[0] m = X.shape[1] h = h_0.shape[1] H = np.zeros((t + 1, m, h)) Y = np.zeros((t, m, rnn_cell.Wy.shape[1])) for i in range(t): ...
diego0096/holbertonschool-machine_learning
supervised_learning/0x0D-RNNs/1-rnn.py
1-rnn.py
py
426
python
en
code
0
github-code
13
73498366417
script_select_todos_idiomas = lambda dados = {}: """ SELECT DISTINCT nome from Idiomas; """ ''' Requer { "nome_idioma" : str } ''' script_select_idioma_por_nome = lambda dados = {}: """ SELECT nome FROM Idiomas WHERE nome = :nome_idioma """ ''' Requer { "nome_idioma" : str } ''' script_select_idioma...
LeandroLFE/capmon
db/scripts/script_select/select_idiomas.py
select_idiomas.py
py
492
python
pt
code
0
github-code
13
8641224415
# Huffman coding is used to reduce the size of the file import heapq import os class BinaryTreeNode: def __init__(self,value,frequency): self.value = value self.frequency = frequency self.left = None self.right = None def __lt__(self,other): return self.frequency < oth...
codemistic/General-Projects
Python Basic Project/Huffman coding.py
Huffman coding.py
py
3,966
python
en
code
47
github-code
13
8525121236
import os import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix, classification_report from .util import * def tr_plot(tr_data, start_epoch): # 绘制训练数据和验证数据 tacc = tr_data.history["accuracy"] tloss = tr_data.history["loss"] vacc = tr_data.history["val_accuracy...
NCcoco/kaggle-project
Bird-Species/util/report_util.py
report_util.py
py
5,677
python
en
code
0
github-code
13
42447226254
def find_error_nums(nums: list[int]): range_list = set(list(range(1, len(nums)+1))) set_nums = set(nums) result_list = [] result_list.extend(set([i for i in nums if nums.count(i) > 1])) for i in range_list: if i not in set_nums: result_list.append(i) return result_list prin...
Dimaaap/Leetcode
Easy/645.) Set Mismatch.py
645.) Set Mismatch.py
py
385
python
en
code
0
github-code
13
28248341016
import pyautogui import editdistance import pyscreenshot as ImageGrab import win32api, win32con from gui.wxpython_gui import WxPythonGUI from ocr.tesseract import TesseractEngine class Navigator: def __init__(self): self.current_gui = WxPythonGUI self.current_ocr_engine = TesseractEngine ...
avjves/TypeNavi
run.py
run.py
py
4,223
python
en
code
1
github-code
13
32859057689
import pandas as pd import numpy as np from tkinter import ttk from tkinter.filedialog import * import tkinter.scrolledtext as st from tkinter import * from pandas.api.types import is_string_dtype from pandas.api.types import is_numeric_dtype import matplotlib.pyplot as plt from sklearn.preprocessing impo...
SoufiyaneOuali/Data_Quality_App
appcomple.py
appcomple.py
py
55,203
python
en
code
1
github-code
13
21207314620
# https://www.youtube.com/watch?v=zU0TxGyMUs4&list=PLlWXhlUMyooawilqK4lPXRvxtbYiw34S8&index=8 """ # ===== Генераторы и Событийный цикл Карусель (Round Robin) Часть 2 =================================================== Суть карусели - престановка первого элемента в конец очереди. 1. Создаем 2 генератора (или более) и ...
VadimVolynkin/learning_python3
multi_async/x_3_async_gen_simple.py
x_3_async_gen_simple.py
py
2,667
python
ru
code
0
github-code
13
10291493681
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render,redirect from ....productos.inventario.forms import * from ....request_session import * # Create your views here. from django.views.generic import TemplateView class menu(TemplateView): template_view="facturacion/mo...
corporacionrst/software_RST
app/sistema/ventas/modificar/views.py
views.py
py
1,911
python
es
code
0
github-code
13
31426218429
import mailchimp_marketing as MailchimpMarketing from mailchimp_marketing.api_client import ApiClientError from pprint import pprint from bs4 import BeautifulSoup try: client = MailchimpMarketing.Client() client.set_config({ "api_key": "b80d7ce5bd37f1f133f5b4202e16e76e-us8", "server": "us8" ...
eclubutd/eclub-bot
src/mailchimp.py
mailchimp.py
py
749
python
en
code
0
github-code
13
13865333347
import torch import torch.nn as nn # Based on https://towardsdatascience.com/building-a-convolutional-neural-network-from-scratch-using-numpy-a22808a00a40 def _overlapping_patch_generator(image_batch, kernel_size): batch_size, image_h, image_w = image_batch.shape for h in range(image_h - kernel_size + 1): ...
tomchaplin/JankAI
JankAI/cnn/_convolution.py
_convolution.py
py
4,791
python
en
code
0
github-code
13
41562504181
# coding reverse backdoor in python # the main function is to let the user try to connect to us instead to we trying to coonnect to user # ------------------------------- start of code ----------------------------- import os import sys import json import socket import base64 import shutil import subprocess class Su...
vijay2249/random-stuff
Backdoor/reverseBackdoor.py
reverseBackdoor.py
py
5,337
python
en
code
0
github-code
13
4743037723
#!/usr/bin/python # -*- coding: utf-8 -*- ''' Unit tests for testing the GalleryItem class. ''' import os import unittest from app.classes.gallery_item import GalleryItem class TestClassGalleryItem(unittest.TestCase): ''' Performs tests on the GalleryItem class. ''' def setUp(self): self.keys = [ ...
luiscape/hdx-monitor-sql-collect
tests/test_class_gallery_item.py
test_class_gallery_item.py
py
695
python
en
code
0
github-code
13
18190764572
from __future__ import division import time import sys import serial import os import math import datetime as dt import threading from threading import Timer import numpy as np #--------------------------- HELP MENU------------ import argparse parser = argparse.ArgumentParser(description='Script para Adquisicion de da...
Platypunk2/TomaMuestrasRFPowerMeter002
Codigos/RFPM002-cp_us.py
RFPM002-cp_us.py
py
6,513
python
es
code
0
github-code
13
29905292430
import os from configparser import ConfigParser, NoOptionError, NoSectionError from pathlib import Path from typing import Any, Literal, Union NumberType = Union[int, float] SIZES = ["teensy", "small", "big", "huge"] TIMES = ["15", "30", "60", "120"] SpeedType = Literal["low", "med", "high"] DEFAULTS = { "difficu...
kraanzu/termtyper
termtyper/utils/parser.py
parser.py
py
5,815
python
en
code
975
github-code
13
20056839286
from dnd_bot.logic.prototype.entity import Entity class Corpse(Entity): entity_name = "Corpse" sprite_path = "dnd_bot/assets/gfx/entities/corpse.png" def __init__(self, x=0, y=0, game_token="", creature_name="", dropped_money=0, dropped_items=None, sprite_path=None): """creates corpse entity wit...
esoviscode/discord-dnd-bot
dnd-bot/dnd_bot/logic/prototype/entities/misc/corpse.py
corpse.py
py
778
python
en
code
4
github-code
13
33484738152
#Write a program to check whether the no is Armstrong or not a=eval(input("enter the no\n")) s=a result=0 while a > 0: num = a % 10 result = result + num**(3) a = int(a/10) if(s==result): print(s,"is amstrong no") else: print(s,"is not a amstrong no")
snehasurna1875/100-days-of-code
Day-39/Amstrongno.py
Amstrongno.py
py
275
python
en
code
0
github-code
13
31942722448
from flask import Flask, Response from flask import jsonify, request import os.path import osmnx as ox from networkx.readwrite import json_graph app = Flask(__name__) def root_dir(): # pragma: no cover return os.path.abspath(os.path.dirname(__file__)) def get_file(filename): # pragma: no cover try: ...
cosmycx/fdns-ms-snxa
app.py
app.py
py
3,508
python
en
code
0
github-code
13
219552643
""" import sys # sys.stdin = open("input.txt", 'r') if __name__ == "__main__": n = int(input()) arr = list(map(int, input().split())) memo = [1] * (n) for i in range(1, n): maximum = 1 idx = 0 for j in range(i - 1, -1, -1): if arr[j] < arr[i]: if mem...
ignis535/baekjoon
동적계획법/최대 부분 증가수열.py
최대 부분 증가수열.py
py
915
python
en
code
0
github-code
13
12983887589
import re import os from urllib import unquote from functools import partial from tempfile import NamedTemporaryFile from thumbor.loaders import LoaderResult from tornado.process import Subprocess from thumbor.utils import logger from wikimedia_thumbor_base_engine import BaseWikimediaEngine uri_scheme = 'http://' ...
wikimedia/thumbor-video-loader
wikimedia_thumbor_video_loader/__init__.py
__init__.py
py
3,111
python
en
code
0
github-code
13
32826185805
import math def is_prime(n): for num in range(2, int(math.sqrt(n)) + 1): if n % num == 0: return False return True def prime_factors(n): result = "" number = n if n == 1: return "(1)" for num in range(2, n): count = 0 while number % nu...
RealMrSnuggles/Python
CodeWars/Primes in numbers.py
Primes in numbers.py
py
743
python
en
code
0
github-code
13
37844902665
import openpyxl def excel_writer(data, path): # data: {sheet_name: tuple of tuple(rows)} wb = openpyxl.Workbook() for sheet_name in data: ws = wb.create_sheet(sheet_name) for row in data[sheet_name]: ws.append(row) del wb["Sheet"] wb.save(path) data = {"sheet1": ((1,2)...
RoyalSkye/AGH
Improvement_based/decomposition_cplex/excel_test.py
excel_test.py
py
378
python
en
code
13
github-code
13
26135171161
from textblob import TextBlob from nltk.sentiment.vader import SentimentIntensityAnalyzer from pycorenlp import StanfordCoreNLP from helper_functions import * import pickle import logging from time import time from multiprocessing.dummy import Pool as ThreadPool from AOP import * import unittest ''' in...
AndreiIacob/SuperView
src/SentimentAnalysis.py
SentimentAnalysis.py
py
11,071
python
en
code
1
github-code
13
40268625031
from utils import time_to_int import numpy as np import os import pandas as pd import pdb class FeatureExtractor: def __init__(self, limit_order_filename, feature_filename, time_interval, n_level): self.limit_order_filename = limit_order_filename self.limit_order_df = None ...
ChenZheng-Zero/OrderBook_ML
feature_extractor.py
feature_extractor.py
py
9,994
python
en
code
1
github-code
13
1320650346
''' Your task is to convert a number between 1 and 31 to a sequence of actions in the secret handshake. The sequence of actions is chosen by looking at the rightmost five digits of the number once it's been converted to binary. Start at the right-most digit and move left. The actions for each number place are: 00001...
antmrgn/100-days-of-devops
Python/exercism/40-secret_handshake.py
40-secret_handshake.py
py
756
python
en
code
1
github-code
13
70872787857
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings import django.core.validators class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations...
bitsnbytes7c8/django-site
user_profile/migrations/0001_initial.py
0001_initial.py
py
973
python
en
code
0
github-code
13
5945187963
#Dylan Miller #Uses the TwoStack class to implement a queue where the first item #in is the first one out #imports the TwoStacks class from Lab01TwoStacks import * #creates a Queue class that can add items to the back of the queue #and remove items from the front class Queue(TwoStacks): """class that can add ite...
dylmill8/Python-Programming
ATCS/Lab01/Lab01Queue.py
Lab01Queue.py
py
1,837
python
en
code
0
github-code
13
14095597448
from django import template from django.template.base import token_kwargs from feincms3_cookiecontrol.embedding import embed, wrap from feincms3_cookiecontrol.models import cookiecontrol_data register = template.Library() @register.inclusion_tag("feincms3_cookiecontrol/banner.html") def feincms3_cookiecontrol(*, h...
feinheit/feincms3-cookiecontrol
feincms3_cookiecontrol/templatetags/feincms3_cookiecontrol.py
feincms3_cookiecontrol.py
py
1,495
python
en
code
8
github-code
13
34608122595
# Задание №7 # ✔ Создайте функцию для сортировки файлов по директориям: # видео, изображения, текст и т.п. # ✔ Каждая группа включает файлы с несколькими расширениями. # ✔ В исходной папке должны остаться только те файлы, # которые не подошли для сортировки from string import ascii_lowercase, digits from random import...
e6ton1set/specialization
python/homework/homework_7/home_1.py
home_1.py
py
1,670
python
ru
code
0
github-code
13
32729168269
import datetime import dateutil from odoo import _, models class Product(models.Model): _inherit = "product.product" def can_rent(self, start_date, stop_date, qty=None): return self.env["website.rentals.scheduling"].can_rent( self, start_date, stop_date, qty=qty ) def get_ava...
ScopeaFrance/rental-1
website_rentals/models/product.py
product.py
py
2,535
python
en
code
null
github-code
13
40783571731
def perception(tx, agent): """ Provides the local environment for the given agent :param tx: write transaction for neo4j database :param agent: id number for agent :return: Node the agent is located at followed by the outgoing edges of that node and those edges end nodes. """ results = tx....
faulknerrainford/SPmodelling
SPmodelling/Interface.py
Interface.py
py
11,458
python
en
code
0
github-code
13
24388798956
# -*- coding: utf-8 -*- from django.db import models class Exam(models.Model): class Meta(object): verbose_name = u"Іспит" verbose_name_plural = u"Іспити" title = models.CharField( max_length=256, blank=False, verbose_name=u"Назва предмету") datetime = models.DateField( ...
anna777/new-work
students/models/exams.py
exams.py
py
757
python
uk
code
0
github-code
13
5619410036
from auto_server import settings import hashlib import rsa import base64 def gen_key(time): s = '{}|{}'.format(settings.KEY, time) md5 = hashlib.md5() md5.update(s.encode('utf-8')) return md5.hexdigest() def decrypt(value): key_str = base64.standard_b64decode(settings.PRIV_KEY) ...
wkiii/CMDB-oldboy
auto_server/utils/security.py
security.py
py
584
python
en
code
0
github-code
13
2250494489
"""Adversarial Inverse Reinforcement Learning (AIRL).""" from typing import Optional import torch as th from stable_baselines3.common import base_class, policies, vec_env from stable_baselines3.sac import policies as sac_policies from imitation.algorithms import base from imitation.algorithms.adversarial import commo...
HumanCompatibleAI/imitation
src/imitation/algorithms/adversarial/airl.py
airl.py
py
5,092
python
en
code
1,004
github-code
13
8235553584
import pandas as pd from funciones import sql def indicadores(semestres): """ Test. """ columnas = [ 'orden', 'escuela_id', 'escuela', 'semestre', 'proceso', # 'orden', 'departamento_id', 'departamento', 'semestre', 'proceso', 'a_tiempo', 'fuera_tiempo', 'total', 'fecha_inicio...
LeninElio/moodle_api
data_test.py
data_test.py
py
1,852
python
es
code
0
github-code
13
73155932816
# -*- coding: utf-8 -*- """ Created on Mon Jun 14 13:01:03 2021 @author: danaukes """ import glob import os import argparse from pdf2image import convert_from_path, convert_from_bytes from pdf2image.exceptions import ( PDFInfoNotInstalledError, PDFPageCountError, PDFSyntaxError ) def extract(path): ...
danb0b/code_media_tools
python/media_tools/pdf_tools/pdf_to_png.py
pdf_to_png.py
py
1,284
python
en
code
0
github-code
13
28475560036
from collections import defaultdict import math def find(arr, option = 2): arr.sort(key = lambda x : int(x[2])) # print(arr) uniqueVisitors = dict() visits = dict() allVisitors = defaultdict(set) Time = dict() highestTimeSpent = dict() entryVisit = dict() highVisit = dict() room...
therealharish/Full-Stack-Open
Python Answers/5th.py
5th.py
py
2,735
python
en
code
0
github-code
13
47190419964
from diffop_experiments import MNISTRotModule def process_dataset(module): module.setup("fit") loader = module.train_dataloader() # See https://discuss.pytorch.org/t/about-normalization-using-pre-trained-vgg16-networks/23560/6 mean = 0. std = 0. nb_samples = 0. for data, _ in loader: ...
ejnnr/steerable_pdo_experiments
calculate_dataset_stats.py
calculate_dataset_stats.py
py
1,043
python
en
code
0
github-code
13
72943533458
wagons = int(input()) trains = [0]*wagons command = input() while not command == "End": data = command.split() if data[0] == 'add': people = int(data[1]) trains[-1] += people if data[0] == 'insert': index = int(data[1]) people = int(data[2]) trains[index] += peopl...
Andon-ov/Python-Fundamentals
13_lists_advanced_lab/02_trains.py
02_trains.py
py
479
python
en
code
0
github-code
13
39575732053
# cook your dish here for _ in range(int(input())): N, X, Y = list(map(int, input().split())) S = input() zeros = S.count('0') ones = S.count('1') if ones > 0 and zeros > 0: if X > Y: print(Y) else: print(X) else: print(0)
KillerStrike17/CP-Journey
Codechef/Starters/Starters 32/BSCOST.py
BSCOST.py
py
296
python
en
code
0
github-code
13
16345290072
"""user tokens Revision ID: bb5ed0594ba7 Revises: 3ec18dbfc7ff Create Date: 2018-06-13 21:54:36.866578 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'bb5ed0594ba7' down_revision = '3ec18dbfc7ff' branch_labels = None depends_on = None def upgrade(): # ##...
grbarker/GardenApp
migrations/versions/bb5ed0594ba7_user_tokens.py
bb5ed0594ba7_user_tokens.py
py
1,347
python
en
code
0
github-code
13
37190237266
""" File: extension.py ------------------ This is a file for creating an optional extension program, if you'd like to do so. """ import random MIN_ANSWER = 1 MAX_ANSWER = 20 def main(): while question() != "": create_random_answer() def question(): ask = input("Ask a yes or no question: ") return...
moura-pedro/CS106A
assignment02/8ball.py
8ball.py
py
1,689
python
en
code
0
github-code
13
7158477497
'''Crie um programa que leia um numero inteiro e mostre na tela se ele e par ou impar. r1 (amarelo) r2 (azul) r3 (laranja) ''' num = int(input('Digite um numero: ')) resultado = num % 2 if resultado == 0: print('O numero {} e PAR'.format(num)) else: print('O numero {} e IMPAR'.format(num))
maxrscarvalho/Python---Curso-em-video---Professor-Guanabara
Modulo_1/Desafio_030.py
Desafio_030.py
py
306
python
pt
code
0
github-code
13
12229756958
import numpy as np import pandas as pd from sklearn.linear_model import Lasso from sklearn.metrics import r2_score from sklearn.model_selection import train_test_split import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from joblib import dump def plotting(income,lim,rating,cards,r2): ...
chaitanya1chawla/Practicum_Python_for_AI_ML
chapter_8/ex1_lasso/main.py
main.py
py
2,237
python
en
code
0
github-code
13
14511721612
from scipy.stats import norm ''' Given 0 < alpha < 1 and quantiles q_0 < q1 returns mean and std. deviation of normal distribution X ~ Normal(mu, sigma) such that P(q_0 < X < q_1) = alpha mu: since normal distribution is symmetric, mu is midway between q_0 and q_1 sigma: X = mu + sigma*Z ~ N(mu, sigma) (Z ~ N(0,1))...
leeds-indoor-air/QMRA
helper_functions/fit_normal_to_quantiles.py
fit_normal_to_quantiles.py
py
785
python
en
code
0
github-code
13
42929190864
# 데이터과학 group 2 # 데이터 정제 (load file and make word2idx) from __future__ import unicode_literals, print_function, division from io import open import unicodedata import string import re import random import torch import torch.nn as nn from torch import optim import torch.nn.functional as F from hparams import hparams ...
lmhljhlmhljh/pytorch_practice
RNNATTENTION/dataset.py
dataset.py
py
3,050
python
en
code
1
github-code
13
17464098832
# -*- coding: utf-8 -*- """ __author__ = 'sunny' __mtime__ = '2017/2/13' # code is far away from bugs with the god animal protecting I love animals. They taste delicious. ┏┓ ┏┓ ┏┛┻━━━┛┻┓ ┃ ☃ ┃ ┃ ┳┛ ┗┳ ┃ ┃ ┻...
zgj0607/Py-store
controller/view_service/view_service.py
view_service.py
py
27,490
python
en
code
3
github-code
13
15710019861
import tkinter as tk from CharacterInfo import CharacterInfo import UI class IntroUIFirstPage(tk.Frame): def __init__(self, parent, root): tk.Frame.__init__(self, parent, background="white") self.parent = parent self.root = root self.characterInfo = CharacterInfo() self.na...
xooberon/harry-potter-game
IntroUIFirstPage.py
IntroUIFirstPage.py
py
1,920
python
en
code
0
github-code
13
42235205938
import os,warnings,json,shutil from bs4 import BeautifulSoup warnings.filterwarnings("ignore") base_path=os.getcwd() os.chdir('data/') listdir=os.listdir() def make_json(path,name,ep,ii): json_dict={ "settings": {"reportId":ii}, "offline": { "instance": name,"epUri": ep,"taxLocationRoot": "2023-03-31" },"...
TakunNineone/makePackageForXW7Server
main.py
main.py
py
1,459
python
en
code
0
github-code
13
11080034904
your_age = input("Enter your current age (years): ") wife_age = input("Enter your wife's age (years): ") your_life = 90 - int(your_age) wife_life = 90 - int(wife_age) your_month = your_life * 12 wife_month = wife_life * 12 your_week = your_life * 52 wife_week = wife_life * 52 your_day = your_life * 365 wife_day = w...
aburifat/Small-Python-Projects
003_90_years_to_live.py
003_90_years_to_live.py
py
889
python
en
code
0
github-code
13
17382034900
import numpy as np import energy import findSeam import reduceImage def findTranspose(image, shapeReduction): ''' Compute the bitmask which gives the order in which the seams must be removed. Parameters: image: Image to be reduced. shapeReduction: Tuple with 2 elements reduc...
PabitraBansal/Content-Aware-Image-Resizing
findTranspose.py
findTranspose.py
py
2,556
python
en
code
0
github-code
13
9216063877
# -*- coding: utf-8 -*- # _author_ = 'hou' # _project_: add_layer # _date_ = 16/10/23 下午1:35 # about matrix multply: http://baike.baidu.com/view/2455255.htm import tensorflow as tf # activation_function=None : means 为线性函数 def add_layer(inputs, in_size, out_size, activation_function=None): # Weights = tf.Variabl...
houweitao/TensorFlow
tensorFlowStudy/add_layer.py
add_layer.py
py
715
python
en
code
0
github-code
13
16679842785
import numpy as np import cv2 import mxnet as mx import argparse import os import time start = time.time() path = "/Users/p439/Desktop/CapOFF/" saved_model_path = os.getcwd() + "/saved_model/" prefix = saved_model_path + 'mymodel-new-ft' ctx = mx.cpu() batch_size = 1 epoch = 130 net, arg_params, aux_params = mx.mod...
khan-farhan/Capon-Vs-Capoff
main.py
main.py
py
1,443
python
en
code
0
github-code
13
3108079836
""" In this exercise you will create a program that reads a letter of the alphabet from the user. If the user enters a, e, i, o or u then your program should display a message indicating that the entered letter is a VOWEL. If the user enters y then your program should display a message indicating that sometimes y is a ...
aleattene/python-workbook
chap_02/exe_037_vowel_consonant.py
exe_037_vowel_consonant.py
py
1,541
python
en
code
1
github-code
13
8841879388
import os from datetime import timedelta from django.conf import settings from django.core.files.storage import default_storage from django.test import override_settings from django.test import TestCase from django.utils.timezone import now from djmoney.money import Money from helpers.seed import get_or_create_defaul...
vasilistotskas/grooveshop-django-api
tests/integration/slider/test_model_slide.py
test_model_slide.py
py
4,545
python
en
code
4
github-code
13
31322322372
from __future__ import absolute_import, print_function import os import threading import makerbot_driver class ReturnObject(object): def __init__(self): pass class MachineFactory(object): """This class is a factory for building machine drivers from a port connection. This class will take a con...
AstroPrint/AstroBox
src/ext/makerbot_driver/MachineFactory.py
MachineFactory.py
py
7,180
python
en
code
158
github-code
13
72963580179
import argparse import os.path as op import json import math import sys import pandas as pd from collections import Counter from multiprocessing import Pool, cpu_count from . import __version__ from .meta import TREDsRepo from .utils import DefaultHelpParser def left_truncate_text(a, maxcol=30): trim = lambda t...
humanlongevity/tredparse
tredparse/tredreport.py
tredreport.py
py
9,762
python
en
code
22
github-code
13
73755944339
import random as rnd # # x0 = 1 #входные числа x0 и y0 # y0 = 2 # # r0 = 5 #радиус окружности # # # ExpNmb = int(input("Напишите нужное количество экспериментов: ")) #ДЛЯ ЗАДАНИЯ 1 # # def CALC_PI(x0, y0, r0, ExpNmb): # m = 0 # обнуляем количество положителяных экспериментов # # xmin = x0 - r0 # x...
AdastroAgni/Modeling_Of_Systems
lab_1/main.py
main.py
py
5,805
python
ru
code
0
github-code
13
20273919398
from django.shortcuts import render from django.contrib.contenttypes.models import ContentType from .models import ReadDetail from blog.models import Blog import datetime import pytz # Create your views here. def get_week_data(request): now = datetime.datetime.now() now_day = datetime.datetime(now.year, now....
wangcai-a/django_blog
data/views.py
views.py
py
998
python
en
code
0
github-code
13
74653480657
from fastapi import HTTPException from starlette import status from api.schemas.common import Pagination from api.schemas.order import ( CreateOrder, CreateOrderItem, CreateOrderResponse, Order, OrderItem, OrderRequest, ) from api.schemas.product import Product from api.schemas.user import User...
SergueiMoscow/MongoDB_study
services/orders.py
orders.py
py
3,534
python
en
code
0
github-code
13
25288273270
#!/usr/bin/env python3 from collections import namedtuple Instruction = namedtuple('Instruction', ('operation', 'argument')) def run_program(program, force_jmp=None, force_nop=None): index = 0 acc = 0 visited = set() while index not in visited: visited.add(index) try: ins...
erijpkema/advent_of_code_2020
day8.py
day8.py
py
1,494
python
en
code
0
github-code
13
40571368391
#!/bin/env python3 # Este script cria o índice das dicas no README. import os import os.path import re from typing import Dict, List, Tuple def obtem_topicos() -> Dict[str, List[Tuple]]: topicos: Dict[str, List[Tuple]] = {} for item_dir in sorted(os.listdir(".")): if not os.path.isdir(item_dir): ...
zanardo/tips
index.py
index.py
py
1,822
python
pt
code
0
github-code
13
22035974505
# # @lc app=leetcode.cn id=337 lang=python3 # # [337] 打家劫舍 III # from typing import List, Optional from collections import deque from leetcode_tool import * # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # ...
revang/leetcode
337.打家劫舍-iii.py
337.打家劫舍-iii.py
py
1,350
python
en
code
0
github-code
13
71473261137
import os from collections import defaultdict from typing import Any, Dict, List, NamedTuple, Sequence, Set, Tuple import numpy as np from onnx import defs, helper from onnx.backend.sample.ops import collect_sample_implementations from onnx.backend.test.case import collect_snippets from onnx.defs import ONNX_ML_DOMAI...
onnx/onnx
onnx/defs/gen_doc.py
gen_doc.py
py
16,292
python
en
code
15,924
github-code
13
34774507074
import os import zipfile from urllib.parse import urlsplit import requests from django.contrib.gis.gdal import DataSource, OGRGeomType from django.contrib.gis.geos import MultiPolygon from django.db import transaction from signals.apps.dataset.base import AreaLoader from signals.apps.signals.models import Area, AreaT...
Shoaib0023/signals
api/app/signals/apps/dataset/sources/cbs.py
cbs.py
py
4,713
python
en
code
0
github-code
13
12653068890
import cv2 as cv # 加载两张图片 img1 = cv.imread('D:/PycharmProjects/pythonProject1/Opencv 4.5/images/color2.jpg') img2 = cv.imread('D:/PycharmProjects/pythonProject1/Opencv 4.5/images/add2.jpg') # 我想把logo放在左上角,所以我创建了ROI rows, cols, channels = img2.shape roi = img1[0:rows, 0:cols] # 现在创建logo的掩码,并同时创建其相反掩码 img2gray = cv....
Darling1116/Greeting_1116
Opencv/lesson_3/Add_2.py
Add_2.py
py
1,684
python
zh
code
0
github-code
13
41767926122
class Solution: def f(self, i, j, k): if (i,j,k) in self.dp: return self.dp[(i,j,k)] if i == len(self.s1) and j == len(self.s2) and k == len(self.s3): return True r1 = False r2 = False if i < len(self.s1) and k ...
ritwik-deshpande/LeetCode
97-interleaving-string/97-interleaving-string.py
97-interleaving-string.py
py
849
python
en
code
0
github-code
13
21840373651
#!/usr/bin/env python3 import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * def main(): app = QApplication(sys.argv) win = QWidget() label = QLabel(f"Welcome to Python Gui programming with PyQt {PYQT_VERSION_STR}") btn = QPushButton("Quit!") btn.setDefault...
mjbhobe/Image_Resources
Gnome/hello.py
hello.py
py
615
python
en
code
0
github-code
13
73910573139
import logging import os import sys from collections import OrderedDict from pathlib import Path import click import git import inquirer import ruamel.yaml from ruamel.yaml.representer import RoundTripRepresenter from dataherb.flora import Flora from dataherb.parse.utils import ( IGNORED_FOLDERS_AND_FILES, ME...
DataHerb/dataherb-python
dataherb/deprecation/command.py
command.py
py
8,475
python
en
code
3
github-code
13
23750440540
# 1. Напишите программу, удаляющую из текста все слова, содержащие "абв". В тексте используется разделитель пробел. # in # Number of words: 10 # out # авб абв бав абв вба бав вба абв абв абв # авб бав вба бав вба # in # Number of words: 6 # out # ваб вба абв ваб бва абв # ваб вба ваб бва import random txt = input('Ка...
YuliyaBorovaya/PythonHomework
HomeWork5/Task1.py
Task1.py
py
887
python
ru
code
0
github-code
13
35654405968
# -*- coding: utf-8 -*- class BankNote(object): """Represent a note with a value""" def __init__(self, value, front, back): self.value = value self.sides = [front, back] note_10 = BankNote(10, 'img/10f.jpg', 'img/10b.jpg') note_20 = BankNote(20, 'img/20f.jpg', 'img/20b.jpg') note_50 = BankNot...
Blondwolf/NoteCounterCHF
src/aborted/standalone/banknote.py
banknote.py
py
511
python
en
code
0
github-code
13
3214482974
from fastapi import FastAPI from pydantic import BaseModel, Field from uuid import UUID import uvicorn from typing import Optional app = FastAPI() #Field is for extra validation for our columns to gets input as expected. class Book(BaseModel): id: UUID title: str = Field(min_length=1) # minimum length of tit...
nvp1394/fast-api
Code Source/FastAPI/practice2.py
practice2.py
py
3,159
python
en
code
0
github-code
13
74024440979
import Levenshtein import sys import os import re PATH_OUTPUT_AUDIO_TEST = './' + sys.argv[1] + '/' num_editops_list = [] num_normal_editops_list = [] num_wav_files = 0 dir_dict = {} def calculate_edit_distance(path_output_audio_test, prediction_file_ending='prediction', max_number_points_to_plot=-1): num_edito...
Fraunhofer-AISEC/towards-resistant-audio-adversarial-examples
score.py
score.py
py
2,845
python
en
code
9
github-code
13
18162686545
# REF : https://leetcode.com/problems/validate-binary-search-tree/ # NOTES : # Need to compare given node with updated UPPER BOUND and LOWER BOUND # Like "Count good nodes in BT" deque stack will have now two more elements # [node, low, high] to implement iterative DFS/BFS solution from collections i...
PawanKmr470/dsa
py_drill/Problems/TR01_ValidateBST.py
TR01_ValidateBST.py
py
1,601
python
en
code
0
github-code
13
32810860961
import json from optparse import make_option import sys from socket import error as socket_error import codecs import unicodedata import requests from django.core.management.base import BaseCommand, CommandError from ui.models import TwitterUser, TwitterUserItem, TwitterUserItemUrl from ui.utils import make_date_awa...
gwu-libraries/social-feed-manager
sfm/ui/management/commands/fetch_urls.py
fetch_urls.py
py
6,563
python
en
code
87
github-code
13
72387988177
import json from helpers import request_helper from web import cache from libs.socnet.socnet_base import SocnetBase from models.soc_token import SocToken from models.payment_loyalty_sharing import PaymentLoyaltySharing class VkApi(SocnetBase): API_PATH = 'https://api.vk.com/method/' MAX_LIKES_COUNT = 1000...
bigbag/archive_term-flask
libs/socnet/vk.py
vk.py
py
4,962
python
en
code
0
github-code
13
17053793224
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class ItemQueryInfo(object): def __init__(self): self._brand = None self._buy_url = None self._currency_type = None self._goods_id = None self._goods_name = None...
alipay/alipay-sdk-python-all
alipay/aop/api/domain/ItemQueryInfo.py
ItemQueryInfo.py
py
6,130
python
en
code
241
github-code
13
74901464016
import pytest from utilities import * from polynomial_interpolation_tools import * from numpy import random import numpy as np @pytest.mark.parametrize('m, n', [(10,11), (7,11), (5,10)]) def test_coefficients_solve(m, n): """ Test to see if obtained coefficients match that of a true polynomial these points cam...
jameswawright/NLA
scripts/test_polynomial_interpolation.py
test_polynomial_interpolation.py
py
2,172
python
en
code
1
github-code
13
3848523959
import requests from bs4 import BeautifulSoup # response = requests.get("https://news.ycombinator.com/news") response.raise_for_status() web_page = response.text soup = BeautifulSoup(web_page, "html.parser") titles = soup.find_all(name="a", class_="titlelink") article_links = [] article_titles = [] for title in tit...
gteachey/100daysofcode_python
day045/bs4-start/main.py
main.py
py
1,876
python
en
code
0
github-code
13
21681639441
import typer import pytest import uvicorn import subprocess app = typer.Typer( help="cli tool stuff thing", context_settings={"help_option_names": ["-h", "--help"]}, no_args_is_help=True, ) @app.command(help="Serve the main uvicorn application") def runserver(prod: bool = typer.Option( False, help="U...
Braden-Preston/fastapi-htmx
manage.py
manage.py
py
672
python
en
code
0
github-code
13
17042061944
a = int(input("Введите результат спортсмена в первый день: ")) b = int(input("Введите предпочтительный результат спортсмена: ")) k = 1 print(f"{k}-й день: {a}") while a <= b: a = a + (a / 100 * 10) k = k + 1 print(f"{k}-й день: {a:.2f}") print(f"На {k}-й день спортсмен достиг результата - не менее {b} км") ...
TerryNight/HomeworkPython
Homework6.py
Homework6.py
py
451
python
ru
code
0
github-code
13
73252757779
def cipher(text, shift, encrypt=True): """ This function will encrypt or decrypt text using caesar cipher method. Parameters ---------- text : str A string to encrypt or decrypt. shift : int An integer for how many digits to shift down the alphabet. encrypt : bool, optional ...
QMSS-G5072-2022/Cipher_Han_Shauna
src/cipher_shh2145_2/cipher_shh2145_2.py
cipher_shh2145_2.py
py
1,071
python
en
code
0
github-code
13
27749964817
# -*- coding: utf-8 -*- # @Time : 2021/5/15 9:49 # @Author : WANGWEILI # @FileName: 3.py # @Software: PyCharm """ 输入一个字符串s,只能包括英文括号( 和 ),且左右括号匹配。回车符结束输入。 字符串s长度:2<=s.length()<=50 """ SYMBOLS = {'}': '{', ']': '[', ')': '(', '>': '<'} SYMBOLS_L, SYMBOLS_R = SYMBOLS.values(), SYMBOLS.keys() def check(s): count...
Echowwlwz123/learn7
浦发机试题/3.py
3.py
py
861
python
en
code
0
github-code
13
26412155082
''' 0123456789 0 2199943210 1 3987894921 2 9856789892 3 8767896789 4 9899965678 ''' import Inputs # ADYACENT POSITIONS AS VALUES def val_up(val_map, row, col): # check up if row != 0: val_up = int(val_map[row-1][col]) else: val_up = 10 # If it's a corner/boundary situation, it's...
GastonBC/AdventOfCode
2021/python/Day09_2.py
Day09_2.py
py
4,426
python
en
code
0
github-code
13
24621126374
#!/usr/bin/env python ''' Reservation and CompoundReservation classes for scheduling. Author: Sotiria Lampoudi (slampoud@gmail.com) December 2012 Reservation does not associate a single resource with each reservation. Instead, the possible_windows field has become possible_windows_dict, a dictionary mapping : resourc...
observatorycontrolsystem/adaptive_scheduler
adaptive_scheduler/kernel/reservation.py
reservation.py
py
8,702
python
en
code
4
github-code
13
34785899118
from rct229.utils.assertions import assert_, getattr_ from rct229.utils.jsonpath_utils import find_all, find_exactly_one_with_field_value LEAP_YEAR_HRS = 8784 NON_LEAP_YEAR_HRS = 8760 def get_min_oa_cfm_sch_zone(rmi, zone_id, is_leap_year: bool = False): """Each zone can have multiple terminal units sering it in...
pnnl/ruleset-checking-tool
rct229/rulesets/ashrae9012019/ruleset_functions/get_min_oa_cfm_sch_zone.py
get_min_oa_cfm_sch_zone.py
py
3,133
python
en
code
6
github-code
13
15418291967
def yn_checker(question): error = "Please choose yes or no (y / n) " valid = False while not valid: response = input(question).lower() print() if response == "yes" or response == "y": return "Yes" elif response == "no" or response == "n": return "No" ...
williamsj71169/ZZ_Assessment
Re_start_board_evidence.py
Re_start_board_evidence.py
py
667
python
en
code
0
github-code
13
21555868489
from pykafka import KafkaClient import time client = KafkaClient("127.0.0.1:9093") geostream = client.topics["geostream"] with geostream.get_sync_producer() as producer: i = 0 for _ in range(10): producer.produce(("Kafka is not just an author " + str(i)).encode('ascii')) i += 1 time....
singhujjwal/fastapi-test
kafka/test_kafka/MV_producer.py
MV_producer.py
py
367
python
en
code
2
github-code
13
17035436664
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AccessPurchaseOrderSendResult(object): def __init__(self): self._asset_item_id = None self._asset_order_id = None self._asset_purchase_id = None self._error_code =...
alipay/alipay-sdk-python-all
alipay/aop/api/domain/AccessPurchaseOrderSendResult.py
AccessPurchaseOrderSendResult.py
py
4,074
python
en
code
241
github-code
13