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
42917236725
"""A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ # Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding # from codecs import open from os import path # from agentml i...
rainyDayDevs/AgentML
setup.py
setup.py
py
2,107
python
en
code
4
github-code
1
8971658666
from kafka import KafkaConsumer from kpong.serde import ping_pong_deserializer consumer = KafkaConsumer( "pingpong", group_id="kpong-1", client_id="kpong", bootstrap_servers='localhost:9092', auto_offset_reset='earliest', value_deserializer=ping_pong_deserializer ) def consume_ping_pong(): ...
apmaros/kpong
src/kpong/consumer.py
consumer.py
py
446
python
en
code
0
github-code
1
33764452546
from easyprocess import EasyProcess from pyvirtualdisplay.abstractdisplay import AbstractDisplay import logging log = logging.getLogger(__name__) PROGRAM = 'Xvfb' URL = None PACKAGE = 'xvfb' class XvfbDisplay(AbstractDisplay): ''' Xvfb wrapper Xvfb is an X server that can run on machines with no displa...
tawfiqul-islam/RM_DeepRL
venv/lib/python3.6/site-packages/pyvirtualdisplay/xvfb.py
xvfb.py
py
1,872
python
en
code
12
github-code
1
16817075767
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 15 04:18:20 2018 @author: sadievrenseker """ #1. kutuphaneler import numpy as np import matplotlib.pyplot as plt import pandas as pd #2. Veri Onisleme #2.1. Veri Yukleme veriler = pd.read_csv('veriler.csv') #encoder: Kategorik -> Numeric ulke =...
erkanzileli/learning-ml
cokluveriler.py
cokluveriler.py
py
1,789
python
tr
code
0
github-code
1
34519823291
from random import choice from sys import argv from base64 import b64encode b = 22 def dwfregrgre(x, z): wdef = [] for a in range(x, z + 1): for i in range(2, a): if (a % i) == 0: break else: wdef.append(a) return wdef def sdsd(edefefef): fv...
p4-team/ctf
2017-10-06-klctf/bad_computations/crypt.py
crypt.py
py
2,426
python
en
code
1,716
github-code
1
28106266111
import os os.environ['CUDA_VISIBLE_DEVICES'] = '0' #'3,2' #'3,2,1,0' import numpy as np import pickle import cv2 import time from timeit import default_timer as timer # torch libs import torch from torch.autograd import Variable from torch.utils.data import DataLoader from torch.utils.data.sampler import SequentialS...
shvetsiya/mask-rcnn
train.py
train.py
py
14,440
python
en
code
12
github-code
1
37165623904
from tkinter import * obj=Tk() def name(): print ("ajay pandit") def profilepic(): root=Tk() root.geometry("0x0") root.title("ajay pandit") photo=PhotoImage(file="4.png") aj=Label(image=photo) aj.pack() root.mainloop() def aboutus(): print('''\n\n The computer scien...
ajayoneness/tkinter
button.py
button.py
py
1,226
python
en
code
1
github-code
1
3018338966
from setuptools import setup install_requires=[ 'cython >= 0.13', 'jinja2 >= 2.5', 'argparse', ] setup(name='protocyt', version='0.1.5', description="Fast python port of protobuf", long_description="Compiles protobuf files into python extension modules using cython", classifiers=[ ...
Evgenus/protocyt
setup.py
setup.py
py
1,136
python
en
code
24
github-code
1
36148042629
import turtle t = turtle.Pen() t.speed(100) def left_spiral(): global size t_pencolor() t_size() for x in range (size): t.forward(x) t.left(91) def right_spiral(): global size t_pencolor() t_size() for x in range (size): t.forward(x) ...
19baileyhawkins/comp_sci_19
TurtleDraw.py
TurtleDraw.py
py
1,357
python
en
code
0
github-code
1
27833537769
from pyzbar import pyzbar import cv2 import time import argparse import keras_ocr # # import os # os.environ["CUDA_VISIBLE_DEVICES"] = "-1" class NpImageBarcode: def predict(self, path): image = cv2.imread(path) barcodes = pyzbar.decode(image) if len(barcodes) == 0: return None...
cyrilvincent/3CE
np_image_barcode.py
np_image_barcode.py
py
1,182
python
en
code
0
github-code
1
4313095146
# -*- coding: utf-8 -*- """ Created on Sun Apr 12 16:45:32 2020 @author: hitar """ import collections nums = [0,0,1] c = 0 l = len(nums) co = collections.Counter(nums) for i in range(co[0]): nums.remove(0) for i in range(co[0]): nums.append(0) print(nums)
smarthitarth/python-scripts
MoveZeroes.py
MoveZeroes.py
py
265
python
en
code
0
github-code
1
28452183977
from PIL import Image from requests import get # to make GET request from torch.utils.data import DataLoader import codecs import copy import errno import gzip import hashlib import numpy as np import os import os.path import torch import torch.utils.data as data import torchvision.transforms as transforms import scip...
lokhande-vishnu/DeepHermites
Code/3-semisupervised_setting/aws_costestimates/epoch_measurements/norb/4hermites_v2l/lib/datasets/norb.py
norb.py
py
5,587
python
en
code
8
github-code
1
36061072150
import functools import uuid import datetime from dataclasses import asdict from flask import ( Blueprint, current_app, flash, redirect, render_template, session, url_for, request, ) from movie_library.forms import LoginForm, RegisterForm, MovieForm, ExtendedMovieForm from movie_library...
ashereth/Movie-Watchlist
movie_library/routes.py
routes.py
py
7,094
python
en
code
0
github-code
1
3565853497
from PyQt5 import QtCore, QtWidgets, QtGui from sys import exit import os import time import csv from multiprocessing import Process, Pipe, Queue import datetime import BACModbus from setup import read_setup from jbdMain import JBD from ampy import Ui_MainWindow import serial import logging # logging import modbus_tk_a...
cwkowalski/ASI_AmpyDisplay
main.py
main.py
py
123,655
python
en
code
10
github-code
1
71936376673
import json import sys from colorcet import bmw import dask import pandas as pd import datashader as ds from datashader import transfer_functions as tf from datashader.utils import lnglat_to_meters as webm from datashader_fix.tiles import render_tiles # use version of render tiles with this fix: https://github.com/hol...
tomwhite/inaturalist-datashader-map
generate_tiles.py
generate_tiles.py
py
1,636
python
en
code
5
github-code
1
26047068428
from easygui import * import os way = fileopenbox('请查找显示的文本',default='*.txt') print(way) with open(way,encoding='utf-8') as file_name: txt = file_name.read() title = os.path.basename(way) msg = ('文件【%s】的内容如下:' % title) textbox(msg,title,txt)
Qiren-Wise/Python-FishC-learning
36/动动手2.py
动动手2.py
py
312
python
en
code
0
github-code
1
21749274335
#!/usr/bin/env python # -*- coding: utf-8 -*- """ .. _log Basic stdout log classes: Error, Verbose and Warning. **Content** """ # *credits*: `gjacopo <jacopo.grazzini@ec.europa.eu>`_ # *since*: Fri May 8 15:21:31 2020 ...
eurostat/pyDatUtils
pydatutils/log.py
log.py
py
9,469
python
en
code
0
github-code
1
38951988250
from flask import Flask, request, jsonify from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow import os from flask_cors import CORS app = Flask(__name__) CORS(app) basedir = os.path.abspath(os.path.dirname(__file__)) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \ os.path.jo...
AgentIsaacson/rate-my-professor
app.py
app.py
py
1,697
python
en
code
0
github-code
1
17561869695
from fastapi import FastAPI import random from typing import Optional, List from models import User, Gender, Role from uuid import uuid4 app = FastAPI() db: List[User] = [ User( id=uuid4(), first_name="Daniel", last_name="Villery", gender=Gender.male, roles=[Role.user, Role...
villeryd/beatsAPI
main.py
main.py
py
1,031
python
en
code
0
github-code
1
12246305957
from string import ascii_lowercase def checkio(words: str) -> bool: word_split = words.split(' ') word_count = 0 for word in word_split: if word[0].lower() in ascii_lowercase: word_count += 1 if word_count == 3: return True else: word_coun...
krkmn/checkio
elementary/three_words.py
three_words.py
py
799
python
en
code
0
github-code
1
8493615897
from models import Course from models.tests import BaseTestCase class CourseTest(BaseTestCase): def test_creation(self): self.assertIsNotNone( Course.create(self.teacher, '', ''), 'Empty course name' ) self.assertIsNone( Course.create(self.teacher, 'pub'...
matts1/MajorWork-appengine
oldmodels/tests/courses.py
courses.py
py
2,587
python
en
code
0
github-code
1
20128360861
import pybg.ql import pybg.curves as curves import pybg.instruments.bulletbond as bb import pybg.instruments.sinkingfundbond as sf from pybg.enums import ( DayCounters, Frequencies, BusinessDayConventions, Calendars ) from datetime import date dt0 = date(2008, 9, 15) print("\nSetting eval date: %s" %...
bondgeek/pybg
pybg_examples/demos/sinker.py
sinker.py
py
2,295
python
en
code
9
github-code
1
27487724730
def read_last(lines, file): if lines > 0: with open(file) as text: file_lines = text.readlines()[-lines:] for line in file_lines: print(line.strip()) else: print('только положительное число') read_last(2, 'spisok.txt') read_last(-1, 'spisok.txt')
VladymyrLu/AreaOfTriangle
dz_13/dz_13_4.py
dz_13_4.py
py
336
python
ru
code
0
github-code
1
15122760531
#!/usr/bin/env python # -*- coding: utf-8 -*- # tabla-del-n.py n = input("Tabla del n: ") # regresa un str n = int(n) # str -> int for i in range(1,11): r = n * i print("{} x {} = {}".format(n, i, r))
PerlaGCastillo/PythonParaPrincipiantes
Clase-01/tabla-de-n.py
tabla-de-n.py
py
213
python
en
code
0
github-code
1
38681629975
import re import itertools import collections reg = re.compile("(\\w+) would (\\w+) (\\d+) happiness units by sitting next to (\\w+).") people = collections.defaultdict(dict) arrangement_happiness = [] def parse_data(line): match = re.match(reg, line) if match: attendee = match.group(1) action = match.group(2) ...
nemo-0/advent-of-code
2015/day13/solution.py
solution.py
py
1,436
python
en
code
0
github-code
1
39773377152
import numpy as np from allfunctions import myCost, RouletteWheelSelection, Crossover, Mutation, Cumulative import copy import time def GAKH(inputdata): tic = time.time() MaxIt, MaxDuration, nPop, crossNumber, muteNumber, muteRate, elitismProb, beta, nClusters, nModules, w_ij, d_i, crossRate, Dependencies, Code...
hasansozer/MOSARCH
GA/GAKH.py
GAKH.py
py
3,807
python
en
code
2
github-code
1
73477199714
import xml.etree.ElementTree as ET import json # Parse the KML file tree = ET.parse('tests/places.kml') # Get the root element root = tree.getroot() # Find all Placemark elements placemarks = root.findall('.//{http://www.opengis.net/kml/2.2}Placemark') # Loop through the placemarks and print the name and coordinate...
bipinkrish/campusmap
tests/places.py
places.py
py
731
python
en
code
0
github-code
1
35235288051
__author__ = "Rohan Pandit" from algo import algorithm, triTueAlgo, withDelay import numpy as np from time import time from random import randint from flask import Flask, abort, jsonify, request from flask_cors import CORS screenSize = 700 app = Flask(__name__) CORS(app) @app.route('/optimize_route', methods=['POS...
petrpan26/ShipDirect
server/salesman.py
salesman.py
py
826
python
en
code
0
github-code
1
10823546127
""" Python3: Save single page of pdf as a new pdf file """ import PyPDF2 # Initialize input pdf file in_pdf = open(r'/path/to/input.pdf', 'rb') pdf_reader = PyPDF2.PdfFileReader(in_pdf) # Reader element pdf_writer = PyPDF2.PdfFileWriter() # Writer element pdf_writer.addPage(pdf_reader.getPage(n)) # Ch...
CRTejaswi/Python3
Text Processing/PyPDF2/1.py
1.py
py
502
python
en
code
0
github-code
1
74807329952
from playwright.sync_api import Playwright, sync_playwright from main.pages.app import App app = App() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False, slow_mo=1000) context = browser.new_context() page = context.new_page() app.login_ui(page) page.clos...
Lexamenrf44/ABarashkov_Python_Playwright_SauceDemo_project
main/specs/smoke/e2e.py
e2e.py
py
424
python
en
code
0
github-code
1
2422070701
from tensorboard.backend.event_processing import event_accumulator import matplotlib.pyplot as plt from os import listdir from os.path import isfile, join import math import numpy as np import sys import tuneConfigurations import warnings from ray.tune import Analysis plt.rcParams['figure.dpi'] = 200 def plot(configs...
trianam/quantumNoiseClassification
funPlot.py
funPlot.py
py
9,824
python
en
code
1
github-code
1
7300614348
from http import HTTPStatus from uuid import UUID from fastapi import APIRouter, Depends, HTTPException from core.constants.exception_details import GENRE_NOT_FOUND from core.utils import verify_auth_tokens from models.genre import Genre from services.genre import GenreService, get_genre_service router = APIRouter()...
Moralex45/middle-python
asyncapi-service/src/api/v1/genres.py
genres.py
py
1,661
python
ru
code
0
github-code
1
15636101304
#!/usr/bin/env python3 from socket import socket from venomsrc.malware.malwarebase import MalwareGenerator from venomsrc.endpoints.raw_server.polls.basepoll import Poll from venomsrc.colored import Colors class ModulePoll(Poll): def __init__(self, writer: object, reader: object, sess_key: str, malware_generator: ...
blueudp/backvenom
server/venomsrc/endpoints/raw_server/polls/module_poll.py
module_poll.py
py
3,079
python
en
code
8
github-code
1
15189440155
from typing import Any, Callable, Dict, List, Optional, Tuple, Union import numpy as np from Orange.data import ContinuousVariable, Domain, Table, Variable from Orange.misc.utils.embedder_utils import EmbedderCache from Orange.util import dummy_callback from orangecontrib.imageanalytics.local_embedder import LocalEmb...
biolab/orange3-imageanalytics
orangecontrib/imageanalytics/image_embedder.py
image_embedder.py
py
11,435
python
en
code
32
github-code
1
1061377237
import os import pandas as pd import numpy as np from sklearn.impute import KNNImputer from sklearn.preprocessing import OrdinalEncoder from sklearn.pipeline import Pipeline from sklearn.compose import ColumnTransformer from imblearn.over_sampling import RandomOverSampler import warnings warnings.filterwarnings("ignor...
guptadikshant/DetectionOfThyroid
DataPreprocessing/data_preprocess.py
data_preprocess.py
py
5,631
python
en
code
1
github-code
1
14656758384
from jax_sandbox.common.dataset import TransitionBatch import jax import jax.numpy as jnp @jax.jit def returns_to_go(batch: TransitionBatch, gamma: float = 1.0) -> jnp.ndarray: ''' Computes returns to go, optionally discounted by gamma. Rewards are of shape (B,). ''' rewards = batch.rewards ...
dhruvsreenivas/jax_sandbox
jax_sandbox/policy_gradient/pg_utils.py
pg_utils.py
py
491
python
en
code
1
github-code
1
39094130632
from details.algprog.calc_lis import calc # картонная крышка def lid_cb(width, length, lid_hight, thickness_cb): indent = 5 width = (lid_hight*2)+width+(thickness_cb*2)+2+indent length = (lid_hight*2)+length+(thickness_cb*2)+2+indent return [width, length] # расход материала def expence_pap(width, l...
7eleron/BestBoxCalc
details/lid/lid_flat_cardboard.py
lid_flat_cardboard.py
py
586
python
en
code
0
github-code
1
12135803446
# exercício 16: Faça um programa que leia um ângulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse ângulo import math # from math import radians, sin, cos, tan a = int(input('Ângulo: ')) x = math.radians(a) s = math.sin(x) c = math.cos(x) t = math.tan(x) print('Seno: {:.2f}'. format(s)) print('Co...
danyfragas/python_modulos
16sen_cos_tg.py
16sen_cos_tg.py
py
389
python
pt
code
0
github-code
1
72969920354
import gettext import os def get_(language): """ Returns the function for localizing text for the given language, which is normally assigned to the function name ``_``. Typical usage:: _ = get_('en') print _("localizable string") :param language: :return: """ locale_dir ...
ArdanaCLM/opsconsole-server
bll/common/i18n.py
i18n.py
py
662
python
en
code
1
github-code
1
36064808560
import FeatureProject from sklearn.linear_model import LogisticRegression import os import ROCX from sklearn.model_selection import cross_val_score from sklearn.metrics import classification_report, confusion_matrix import pandas as pd from sklearn.decomposition import PCA import time import numpy as np '''进行模型的保存和加载''...
asd567/HC-MCI-AD-classification-ML
code/LogisticRegressionX.py
LogisticRegressionX.py
py
9,482
python
en
code
1
github-code
1
10926944262
import sublime import sublime_plugin import re autocompletes = { "Alert": [ ["Prompt", "Prompt(${1:title}, ${2:message})"], ["Alert", "Alert(${1:title}, ${2:message})"], ["Confirm", "Confirm(${1:title}, ${2:message})"], ], "SMAlert": [ ["Prompt", "Prompt(${1:title}, ${2:message})"], ["Alert", "Alert(${1...
gebeto/python
ReactNativeAutocomplete.py
ReactNativeAutocomplete.py
py
902
python
en
code
2
github-code
1
8607037151
import os import pygame from battle2.model import Direction from battle2.model import State import battle2.eventmanager as evm SCREENWIDTH = 1600 SCREENHEIGHT = 800 # 1600, 800 # 1920, 1080 WINDOWWIDTH = 800 WINDOWHEIGHT = 600 WINDOWPOS = 100, 100 TILESIZE = 32 PLAYERLAYER = 2 GRIDLAYER = 4 FPS = 60 BLACK = p...
henkburgstra/pyRPG
battle2/view.py
view.py
py
19,976
python
en
code
0
github-code
1
26407571543
import discord import logging from dotenv import load_dotenv import os load_dotenv() KEY = os.getenv('DISCORD_KEY') #logging set up logger = logging.getLogger('discord') logger.setLevel(logging.DEBUG) handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w') handler.setFormatter(logging.Forma...
julianjohnson10/Discord-Bot
DiscordBot.py
DiscordBot.py
py
674
python
en
code
0
github-code
1
6756925090
#!/usr/bin/env python # -*- coding: utf-8 -*- import time import numpy as np import traceback def get_spa_labels(path=""): """ 返回特征值和数字化的标签 0 dislike 1, little, 2 ok""" if not path: path = "data/kNndata1.txt" with open(path) as f: try: each_line = f.readlines() list_...
liuvzzvuil/len_machine
kNN/format_data.py
format_data.py
py
1,666
python
en
code
0
github-code
1
32937853207
import decimal import re import lxml.html class Base(object): fetched = False def __init__(self, mal_id, mal): self.mal_id = mal_id self.mal = mal def _get_url(self): return self.base_url % self.mal_id def fetch(self): if not self.fetched: return self.ma...
JohnDoee/web-parsers
myanimelist/malparser/base.py
base.py
py
6,592
python
en
code
1
github-code
1
75136158434
import pandas as pd import matplotlib.pyplot as plt import matplotlib.mlab as mlab import statistics as st from math import pow import math import os import numpy as np from scipy.stats import norm FILE_PATH=str(os.getcwd()) + '\Data\heart.csv' df = pd.read_csv(FILE_PATH) #list of all the column headings col_heads = ...
hrishitchaudhuri/sds
scripts/normalisation.py
normalisation.py
py
2,076
python
en
code
0
github-code
1
72989251553
import cv2 import os import numpy as np import multiprocessing from concurrent.futures import ThreadPoolExecutor def apply_clahe(image): lab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB) l, a, b = cv2.split(lab) clahe = cv2.createCLAHE(clipLimit=4.0, tileGridSize=(8, 8)) cl = clahe.apply(l) ...
Muawizodux/Multi-class-Segmentation-and-Classification-for-Skin-Disease
pix2pix-GANs/Data-Preprocessing(Non-Melanoma).py
Data-Preprocessing(Non-Melanoma).py
py
2,364
python
en
code
1
github-code
1
210457700
from django.shortcuts import render from django.contrib import messages from polls.forms import RegistrationForm def index(request): context_dict = {'form': None} form = RegistrationForm() if request.method == 'GET': context_dict['form'] = form elif request.method == 'POST': form = Re...
slow999/DjangoAndReactComponentForm
polls/views.py
views.py
py
704
python
en
code
1
github-code
1
36159117274
import os import json class Config: @staticmethod def getConfig(name: str): fname = name if not os.path.exists(fname): return None with open(fname, "r") as fp: raw = fp.read() return json.loads(raw) @staticmethod def saveConfig(name: st...
dhy2000/CO_Judger
configs/config.py
config.py
py
1,085
python
en
code
0
github-code
1
27290499486
import socket from select import select ''' Каждый запущенный процесс в UNIX - тоже файл. При вызове .bind() создается файл сокета. Select необходима для отслеживания изменений в любых объектах, у которых есть метод: .fileno() - номер файла, возвращает файловый дескриптор (номер файла, как бы адрес, выделенный ОС). Т...
cactusFriday/python-learning
async_python/1_select.py
1_select.py
py
3,530
python
ru
code
0
github-code
1
13415632812
import copy from SPARQLWrapper import SPARQLWrapper, JSON from slot_recognition import * from SPARQL_generation import * class QueryManager: def __init__(self, verbose=False): self.__conn = SPARQLWrapper(ENDPOINT_URL) self.__verbose = verbose def set_verbose(self, verbose): ...
btyu/R3K_KBQA
R3K-KBQA/query_management.py
query_management.py
py
4,858
python
en
code
12
github-code
1
72574849315
# Author: Radoslaw Rezler # Date: 2023-04-14 # Description: Program that asks user to choose a dog or a cat and then asks some questions. # Then it gives them a list of the best breeds based on their answers. # Define the class for the animals class Animal: def __init__(self, name, size, acti...
rrezler93/Portfolio
Graded Unit Project/YourBestPet - developer version/YourBestPet - console version.py
YourBestPet - console version.py
py
38,403
python
en
code
0
github-code
1
1402617285
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import QFileDialog, QMessageBox from PyQt5.QtCore import QTimer import sys import time import csv import os import winsound from libs import Track, getShiftRPM, fuelSavingOptimiser, rollOut from libs.IDDU import IDDUThread, IDDUItem from libs.auxiliaries i...
MarcMatten/iDDU
gui/iDDUgui.py
iDDUgui.py
py
78,820
python
en
code
2
github-code
1
13149683279
from src.datamodules.common.generic_datamodule import GenericDatamodule from src.utils.hydra import instantiate_delayed import os from torchvision.utils import save_image import torch from src.utils.audio import save_mp3_to_tensor class AudioDataModule(GenericDatamodule): def __init__( self, batch...
radziminski/audio-key-classification
src/datamodules/audio_datamodule.py
audio_datamodule.py
py
4,037
python
en
code
0
github-code
1
13617183674
import os from yt_dlp import YoutubeDL def download_url(path,URL): option = { "outtmpl":f"{path}"+"%(title)s.%(ext)s" }#パスは実行する環境に合わせて URLs=[] ydl = YoutubeDL(option) URLs.append(URL) result = ydl.download(URLs) return f"{path}"+"%(title)s.%(ext)s" download_url(os.getcwd(),f"https:/...
haru-mikann/DiscordBot
test.py
test.py
py
429
python
en
code
0
github-code
1
36510945058
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from dao.character_dao import CharacterDao from dao.weapon_dao import WeaponDao class Genshin: character_dao = None weapon_dao = None __instance = None @staticmethod def get_instance(): """Static method access"""...
bemyXmas/genshin-dao
genshin.py
genshin.py
py
1,161
python
en
code
0
github-code
1
33821068894
'''Budujemy moduł służący do obliczeń na ciągach geometrycznych ZADANIE 1 Zaimportuj moduł math Przygotuj funkcję GiveGeomSeqElement, która: -przyjmuje 3 parametry a1 - o domyślnej wartości 2, która oznacza pierwszy element ciągu, factor - o domyślnej wartości 2, która oznacza współczynnik ciągu geometrycznego, in...
sineczek/NaukaPythona
Funkcje/52_implementacja_switch_lab.py
52_implementacja_switch_lab.py
py
4,333
python
pl
code
0
github-code
1
12060803554
""" Hi, here's your problem today. This problem was recently asked by Microsoft: Given the root of a binary tree, print its level-order traversal. For example: 1 / \ 2 3 / \ 4 5 The following tree should output 1, 2, 3, 4, 5. class Node: def __init__(self, val, left=None, right=None): self.val = v...
winkitee/coding-interview-problems
81-90/87_level_order_traversal_of_binary_tree.py
87_level_order_traversal_of_binary_tree.py
py
1,096
python
en
code
0
github-code
1
19093601252
import pygame import config from CentipedeComponent import CentipedeComponent from Direction import Direction from threading import Timer from PendingMovement import PendingMovement def backwards(dir): if dir == Direction.up: return Direction.down elif dir == Direction.right: return Direction.left elif dir...
justinoboyle/learn-python
Centipede.py
Centipede.py
py
3,265
python
en
code
0
github-code
1
12711675778
with open("one_col_ingestrtt.txt", mode="r", encoding="utf-8") as file: line = file.read().splitlines() ingestrtt = [0]*82 for i in range(82): ingestrtt[i] = float(line[i]) with open("avpn.txt", mode="r", encoding="utf-8") as file: vpn = file.read().splitlines() sortedvpn = [0]*82 sorted_ingestrt...
LeoLee0403/Thesis
4Program/Step3_Implement_Geo_Method/1Shortest_ping/sort.py
sort.py
py
726
python
en
code
3
github-code
1
36502272504
from __future__ import print_function import argparse import os import random import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim as optim import torch.utils.data import torchvision.datasets as dset import torchvision.transforms as transforms import torchv...
ppooiiuuyh/-PyTorch-implementations
DCGAN/train_and_valiate.py
train_and_valiate.py
py
4,890
python
en
code
1
github-code
1
7214972998
import sys sys.stdin = open('부분합_input.txt') n, s = map(int, sys.stdin.readline().rstrip().split()) arr = list(map(int, sys.stdin.readline().rstrip().split())) cnt = 0 ans = 100001 value = 0 left, right = 0 , 0 while True : if value >= s : ans = min(right - left, ans) value -= arr[left] lef...
HyunSeok0328/Algo
슬라이딩윈도우,투포인터/부분합.py
부분합.py
py
469
python
en
code
0
github-code
1
18057701170
import tensorflow as tf from tf_agents.networks import network from tf_agents.agents.dqn import dqn_agent from tf_agents.environments import tf_py_environment from tf_agents.policies import random_tf_policy from tf_agents.replay_buffers import tf_uniform_replay_buffer from tf_agents.trajectories import trajectory from...
emla2805/rl-sudoku
train.py
train.py
py
5,909
python
en
code
1
github-code
1
23070045502
import os import time from flask import Flask, render_template, request from flask_socketio import SocketIO, emit, disconnect from collections import deque app = Flask(__name__) # socket-io configure app.config["SECRET_KEY"] = os.getenv("SECRET_KEY") socketio = SocketIO(app) # in-memory data USERS = {} CHANNELS = ...
muedie/flack
application.py
application.py
py
1,388
python
en
code
1
github-code
1
37469284557
import csv import logging import json import math import random import re import time import urllib.request from pathlib import Path import sys from bs4 import BeautifulSoup import requests import get_edgar.common.my_csv as mc import get_edgar.common.utils as utils logger = logging.getLogger(__name__) EDGAR_PREFIX =...
linbaiwh/Get_EDGAR
get_edgar/extractor/fileinfo_extractor.py
fileinfo_extractor.py
py
9,826
python
en
code
1
github-code
1
22254776273
import math from PyQt5.QtWidgets import QGraphicsView, QGraphicsLineItem, QApplication, QMenu, QAction from PyQt5.QtGui import QColor, QBrush, QPen from PyQt5.QtCore import pyqtSlot, QLineF, QRectF, QPoint, QPointF, Qt from pyqtgraph import GraphicsLayoutWidget, PlotItem, ViewBox, GraphicsItem, GraphicsView, PlotDataIt...
mattgibbs/simui
steering/orbit_view.py
orbit_view.py
py
10,566
python
en
code
0
github-code
1
42603908137
from django import forms from .models import Post from django.core.validators import FileExtensionValidator class PostForm(forms.ModelForm): thumbnail = forms.FileField(required=False, widget=forms.ClearableFileInput(attrs={'class': 'input'})) video = forms.FileField(required=False, validators=[FileExtensionVa...
Varad-13/django-crowdfund
crowdfunding/forms.py
forms.py
py
1,207
python
en
code
1
github-code
1
32971093458
input_file = open('day-8/input.txt', 'r') lines = input_file.readlines() lines = [line.rstrip() for line in lines if line.rstrip()] lines = [[*line] for line in lines] column = 1 row = 1 up = True down = True left = True right = True visible_trees = 0 while row <= len(lines) - 2: while column <= len(lines[row]) -...
CodySalyi/advent-of-code-2022
day-8/treetops.py
treetops.py
py
1,264
python
en
code
0
github-code
1
74525949792
import argparse import collections import glob import json import math import numpy as np import random from ordered_set import OrderedSet import os import pickle import shutil from sklearn.metrics import average_precision_score import sys import termcolor import time import torch import torch.nn as nn ...
acproject/GNNs
NAACL/backoffnet.py
backoffnet.py
py
38,944
python
en
code
1
github-code
1
38127398338
import requests import discord from webdriver import keep_alive from bs4 import BeautifulSoup import pandas as pd from discord.ext import commands bot = commands.Bot(command_prefix='!') bot.remove_command("help") @bot.event async def on_ready(): await bot.change_presence(status=discord.Status.online, activity=disco...
mukuln-official/Target-and-walmart-stock-check
main.py
main.py
py
6,458
python
en
code
1
github-code
1
269449406
from collections import defaultdict import os from pathlib import Path from urllib.request import urlretrieve import xml.etree.ElementTree as ET # import the countries xml file tmp = Path(os.getenv("TMP", "/tmp")) countries = tmp / 'countries.xml' if not countries.exists(): urlretrieve( 'https...
rhelmstedter/pybites
190/income.py
income.py
py
975
python
en
code
0
github-code
1
6307202826
import numpy as np import torch import torch.nn as nn class RNNBaseSTFTMask(nn.Module): def __init__(self, num_spk=2, audio_channels=2, n_fft=512, hop_length=256, sample_rate=16000, rnn_hidden=256, rn...
ooshyun/Speech-Enhancement-Pytorch
src/model/stft_rnn.py
stft_rnn.py
py
7,628
python
en
code
9
github-code
1
73751992994
import threading import socket import sys import time host = '' port = 9000 locaddr = (host, port) # Create a UDP socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(locaddr) tello_address = ('192.168.10.1', 8889) COMMANDS = [] ALL_COMMANDS = 0 NEXT = True def _recv(): w...
guladam/dji_tello_edu_py
dron.py
dron.py
py
1,936
python
en
code
0
github-code
1
6612090016
import os import numpy as np from mtuq import read, open_db, download_greens_tensors from mtuq.event import Origin from mtuq.graphics import plot_data_greens2, plot_beachball, plot_misfit_dc from mtuq.grid import DoubleCoupleGridRegular from mtuq.grid_search import grid_search from mtuq.misfit import Misfit from mtuq...
uafgeotools/mtuq
mtuq/util/gallery.py
gallery.py
py
2,939
python
en
code
57
github-code
1
4489123362
import tensorflow as tf from tensorflow.keras.models import Sequential,Model from tensorflow.keras.layers import Conv2D,BatchNormalization,Dropout,Activation,LeakyReLU,UpSampling2D,Input,Dense,Reshape,Flatten,Conv2DTranspose,ReLU,concatenate,ZeroPadding2D import numpy as np def BaseUnet_modeling(kernel_size=4,dropout=0...
Taerimmm/ML
AE/unet.py
unet.py
py
4,234
python
en
code
3
github-code
1
39820204674
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def __str__(self): return str(self.data) class BST: def __init__(self): self.root = None def insert(self, data): if self.root is None: self.root = ...
16sakuraa/OOD-Lab
64010860-Lab7/64010860-2.py
64010860-2.py
py
2,111
python
en
code
0
github-code
1
25784868828
from __future__ import print_function import asyncio import random import threading import time import numpy as np import websockets from websocket import create_connection from robot_dqnagent import DQNAgent from robot_arena import Arena class MSGWorker (threading.Thread): def __init__(self): self.coords ...
SundayLab/robot_dqn
robot_server_execute.py
robot_server_execute.py
py
3,002
python
en
code
0
github-code
1
37297581932
from abc import ABC, abstractmethod import json import os from datetime import datetime import requests from utils import get_USD_conversion_rate, get_from_and_up_salary class JobSiteAPI(ABC): @abstractmethod def get_vacancies(self, filter_word): pass class HeadHunterAPI(JobSiteAPI): def get_v...
SkyLanser/vacancy_parser
classes.py
classes.py
py
7,485
python
en
code
1
github-code
1
74209156834
import socket import time # # Orange Pi Pins imports from pyA20.gpio import gpio from pyA20.gpio import port # #initialize the gpio module gpio.init() # #initialize GPIO pin gpio.setcfg(port.PA12,gpio.INPUT) gpio.pullup(port.PA12,gpio.PULLUP) gpio.pullup(port.PA12,gpio.PULLDOWN) def read_gpio(): return gpio.inp...
fragnatic62/drive-thru-app
api/test_stream.py
test_stream.py
py
833
python
en
code
0
github-code
1
20520643564
import argparse import os import PyInstaller.building.makespec import PyInstaller.log try: from argcomplete import autocomplete except ImportError: def autocomplete(parser): return None def generate_parser(): p = argparse.ArgumentParser() PyInstaller.building.makespec.__add_options(p) P...
pyinstaller/pyinstaller
PyInstaller/utils/cliutils/makespec.py
makespec.py
py
1,049
python
en
code
10,769
github-code
1
11920686834
import scipy from scipy.integrate import quad import random import numpy as np mink = 2 maxk = 20 coeff_mu = 0 coeff_sigma = 1 def mk_coeff(): return random.normalvariate(coeff_mu, coeff_sigma) offset_sigma = 1 def mk_offset(): return random.normalvariate(0, offset_sigma) def calc_poly(coeffs, x): return su...
aidatorajiro/misc
bzzz_mat.py
bzzz_mat.py
py
2,267
python
en
code
0
github-code
1
1704717638
import itertools def solution(users, emoticons): answer = [0, 0] sale = [10, 20, 30, 40] sale_rate = list(itertools.product(sale, repeat=len(emoticons))) for i in sale_rate: plus = 0 earn_money = 0 for user in users: rate, money = user tmp = 0 ...
SunghunKim98/Algorithm_Study
sprint10/KMS/실시간/이모티콘 할인행사.py
이모티콘 할인행사.py
py
839
python
en
code
0
github-code
1
9625126741
import uuid import json import logging import sqlite3 import threading import time from datetime import datetime from .const import (LIST_TYPE_CHANNEL_BRAND, LIST_MODEL_DEVICE_BRAND, NAME_TYPE_CHANNEL, TYPE_DEVICE) from .config import DATABASE LOGGER = logging.getLogger("Database") DB_VERSION = 0x00...
minhtan58/HomeGate
dbsync.py
dbsync.py
py
64,592
python
en
code
0
github-code
1
70122758115
"""mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based ...
Lifanna/geology_proj
geology_proj/main/urls.py
urls.py
py
5,981
python
en
code
0
github-code
1
11481471531
#! /usr/bin/python2.7 # -*- coding: utf-8 -*- import re try: import jpype except ImportError: pass from .. import jvm from .. import utils __all__ = ['Kkma'] class Kkma(): """Wrapper for `Kkma <http://kkma.snu.ac.kr>`_. Kkma is a morphological analyzer and natural language processing system writt...
kanghyojun/konlpy
konlpy/tag/_kkma.py
_kkma.py
py
2,284
python
en
code
null
github-code
1
35228705628
import cs50 def main(): num_of_letters = 0 num_of_words = 0 num_of_sentences = 0 index = 0 user_input = cs50.get_string("Text: ") if (user_input is None): main() for char in user_input: # loop through the text and use ctype to count only letters if (char.isalpha()...
RaymondMik/python-algorithms
pset6/readability/readability.py
readability.py
py
1,479
python
en
code
0
github-code
1
72964937634
#%% import numpy as np import pandas as pd from pandas import DataFrame from retrying import retry import random import pickle class Player(object): def __init__(self, name): self.name=name #%% class CpuPlayer(Player): taken_choice=[1,2,3] def __init__(self,name='cpu',learning_mode=True, learning_rat...
CrystalWindSnake/Creative
python/rl_learning_stone/models.py
models.py
py
3,830
python
en
code
7
github-code
1
2716397144
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def recursion(n): if n == 1: return 1 return n + recursion(n - 1) if __name__ == '__main__': n = int(input("Enter n: ")) summary = 0 for i in range(1, n + 1): summary += i print("Iterative sum: " +str(summary) ) print("Recurs...
GravityC4T/LR12
Progs/задание1.py
задание1.py
py
351
python
en
code
0
github-code
1
13415070526
import numpy as np import sys from decimal import * ''' Naming convention Files ending without _ are my files Files ending with _ are Sneh's files ''' ''' Without DP Hold out and cross validation vip_cleaned.csv vip_cleaned_.csv With DP Hold out and cross validation vip_cleaned_dp_0_1.csv vip_cleaned_dp_1.csv vip_cl...
NiramayVaidya/Differential_Privacy_Hemodialysis_SBP_Prediction
train_test_helper_funcs.py
train_test_helper_funcs.py
py
12,065
python
en
code
2
github-code
1
11831798394
from flask import Flask from flask import render_template,request from pymongo import MongoClient import json from bson import json_util from bson.json_util import dumps app = Flask(__name__,template_folder='/home/sri/Downloads/AAL-94_dataset/AALtorch/template') print(app) MONGOD_HOST = 'localhost' MONGOD_PORT = 27017...
srinidhi17/HealthMonitoring-System-
test.py
test.py
py
1,299
python
en
code
0
github-code
1
73910144034
__author__ = 'Victor Olaya' __date__ = 'August 2012' __copyright__ = '(C) 2012, Victor Olaya' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import os from qgis.PyQt.QtGui import QIcon from processing.core.ProcessingConfig import ProcessingConfig, Setting from proce...
nextgis/nextgisqgis
python/plugins/processing/algs/r/RAlgorithmProvider.py
RAlgorithmProvider.py
py
4,020
python
en
code
27
github-code
1
3194291784
import bibtexparser import re import os from os import path if path.exists('mytitles.txt'): os.remove('mytitles.txt') with open('MyCollection.bib') as bibtex_file: bib_database = bibtexparser.load(bibtex_file) with open("mytitles.txt","a") as file1: for entry in bib_database.entries: title = entry[...
ShenWang9202/bibfileGenerator
getTitles.py
getTitles.py
py
463
python
en
code
0
github-code
1
6479965465
from django.conf.urls import url from ..views.oj import (SearchGroupByKeyWordAPI, JoinGroupBySearchAPI, GroupListAndDetailAPI, HomeWorkListAndDetailAPI ) urlpatterns = [ url(r"^search_group/?$", SearchGroupByKeyWordAPI...
PUANEY/OnlineJudge
groups/urls/oj.py
oj.py
py
600
python
en
code
0
github-code
1
71607967713
from selenium import webdriver import pandas as pd from IPython.display import display from selenium.webdriver.chrome.options import Options # inicializa o programa sem aparecer na tela, em segundo plano chrome_options = Options() chrome_options.headless = True # abre o navegador com as opções definidas acima navegad...
jpc963/cotacao-e-automacao
main.py
main.py
py
2,323
python
pt
code
0
github-code
1
43064648639
from django.test import TestCase, tag from django.urls.base import reverse from edc_model_wrapper import ModelWrapper from ..models import ActionItem, ActionType from ..templatetags.action_item_extras import add_action_item_popover from ..view_mixins import ActionItemViewMixin from .models import SubjectIdentifierMode...
botswana-harvard/edc-action-item
edc_action_item/tests/test_view.py
test_view.py
py
2,034
python
en
code
0
github-code
1
28323298008
from glob import glob from langchain.agents import load_tools from langchain.agents import initialize_agent from langchain.agents import AgentType from langchain.llms import OpenAI import os, sys, openai from dotenv import load_dotenv from langchain.tools import tool, Tool from retrieval import Retrieval from pyepsilla...
epsilla-cloud/app-gallery
documents-agent/docagent.py
docagent.py
py
5,739
python
en
code
4
github-code
1
27277520150
#!/usr/bin/env python3 import requests from bs4 import BeautifulSoup from urllib.parse import urlparse import sys # crawling def download_page(url): resp = requests.get(url) while resp.status_code != 200: resp = requests.get(url) return resp.text def parse_html(url, html): path = urlparse(url...
TeddyHartanto/searchreddit
search_engine.py
search_engine.py
py
643
python
en
code
0
github-code
1
24606124104
#!/usr/bin/env python # coding: utf-8 # In[3]: ''' 1부터 n까지의 수 중 짝수의 합을 구하시오.. ''' a=int(input()) b=[] for i in range(1,a+1): if i%2==0: b.append(i) print(sum(b)) # In[ ]:
smilesunho/practice-for-codeup
1259.py
1259.py
py
229
python
ko
code
0
github-code
1
11145947833
# Author: Baozi #-*- codeing:utf-8 -*- """题目描述 将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0), 要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。 输入描述:输入一个字符串,包括数字字母符号,可以为空 输出描述:如果是合法的数值表达则返回该数字,否则返回0 """ """解题思路: Python中str无相减,所以要利用ord()函数,将其转换成ascii码 """ class Solution: def StrToInt(self, s): # w...
dashayudabao/practise_jianzhioffer
jianzhi_offer/day48把字符串转成整数demo.py
day48把字符串转成整数demo.py
py
1,236
python
zh
code
0
github-code
1
26373497314
import copy class Optimizer: def __init__(self, fitness_function, population_size=20, max_iterations=100,**kwargs): #set paramaters for users problem self.fitness_function = fitness_function self.additional_parameters = kwargs #parameters for the users fitness function #set genera...
DrMustafa/GOA-Arabic-Text-Summarization
optimizer.py
optimizer.py
py
3,321
python
en
code
0
github-code
1