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
31977888925
# import libtcodpy as libtcod # import EngineSettings from Scene import Scene import Audio from core import EngineSettings from gui.MainWindow import MainWindow audio = None mainWin = None mainScene = None logWin = None def init(scene=None): global mainWin, mainScene, logWin, audio mainScene = scene if m...
grotus/fishsticks
core/Core.py
Core.py
py
520
python
en
code
0
github-code
13
40785686071
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Nov 28 17:02:32 2020 @author: elvinagovendasamy """ from scipy import spatial from sklearn.model_selection import KFold import numpy as np import pandas as pd from operator import itemgetter from sklearn.neighbors import KNeighborsClassifier from sklea...
elvinaeury/KNN_from_scratch
KNN_Bagging_final.py
KNN_Bagging_final.py
py
7,069
python
en
code
0
github-code
13
2303156517
import logging FORMAT = "%(asctime)s %(name)s %(message)s" logging.basicConfig(level=logging.INFO, format=FORMAT) log1 = logging.getLogger('s') log1.setLevel(logging.DEBUG) log2 = logging.getLogger('s.s1') # print(log2.getEffectiveLevel()) log2.debug('log2 debug') data = ["{}*{}={}".format(j,i,i*j) for i in range(1...
bujiliusu/first
L3903.py
L3903.py
py
358
python
en
code
0
github-code
13
6180657112
from twilio.rest import Client import os try: account_sid = os.environ['TWILIO_ACCOUNT_SID'] auth_token = os.environ['TWILIO_AUTH_TOKEN'] client = Client(account_sid, auth_token) message = client.messages \ .create( body="Hi Maaz.", ...
maazsabahuddin/Twilio-SMS-service
Twilio_sms.py
Twilio_sms.py
py
529
python
en
code
1
github-code
13
13779721509
import subprocess input_file = "ips.txt" output_file = "ping_results.txt" # Open the input file and read IP addresses with open(input_file, "r") as file: ip_addresses = file.read().splitlines() # Open the output file to write the results with open(output_file, "w") as file: # Loop through each IP address ...
kotha070/Thesis
ping_ips.py
ping_ips.py
py
832
python
en
code
0
github-code
13
41057607409
from locale import currency import sys from chatterbot import ChatBot from chatterbot.trainers import ListTrainer from chatterbot.trainers import ChatterBotCorpusTrainer import re import datetime import glob from sqlalchemy import false def get_corpus_from_file(filename): conversations = [] curr_conversation ...
volts-inventory/Kaladin
train.py
train.py
py
4,643
python
en
code
0
github-code
13
42960510720
from typing import List from cloudleak.app import create_app from cloudleak.models.objectid import PydanticObjectId from cloudleak.models.target import Scan from flask_pymongo import PyMongo from ..models.scan_status import ScanStatus app = create_app(register_blueprints=False) mongo_client = PyMongo(app, uri=app.co...
DanielAzulayy/CloudLeak
cloudleak_backend/cloudleak/common/scans.py
scans.py
py
1,118
python
en
code
2
github-code
13
21322648186
import sys import numpy import numpy.linalg class BaseImage(object): def __init__(self): self.points = {} def add_point(self, name, px, py): self.points[name] = px, py def union_points(self, other): d = dict(self.points) d.update(other.points) return d ...
ejrh/image-tools
montage/montage.py
montage.py
py
4,548
python
en
code
0
github-code
13
73207501138
import sys from load import load_strings names = load_strings(sys.argv[1]) search_names = ["Titus", "Harv", "Wolfgang", "Moshe", "Len", "Cosmo", "Bernd", "Tray", "Derrin", "Garry", "Tomlin", "Pace", "Wilfrid", "Ulysses", "Uli", "Ave", "Val", "Todd", "Chrissy", "Terry", "Mischa", "Elwood", "Earl", "Alec", "Demetrius",...
HazeeqHaikal/learning-data-structure-with-python
binary_search.py
binary_search.py
py
1,520
python
hr
code
0
github-code
13
1744887552
from ..config.Mongodb import Mongodb from ..models.entity.Restaurant import Restaurant from bson.objectid import ObjectId class Restaurant_dao: def __init__(self): self.mongodb = Mongodb.getInstance() self.client = self.mongodb.client def searchRestaurant(self, search): response = ...
Cochachin/demo-gastron-app-service
src/datasource/Restaurant_dao.py
Restaurant_dao.py
py
1,543
python
en
code
0
github-code
13
32484822203
#!/usr/bin/env python import numpy as np import logging import gomill import gomill.common from gomill import gtp_engine, gtp_states from gomble import MoveProbBot import kombilo_book from kombilo_book import MoveFinder, MoveFinderRet, MoveValue def make_engine(player): """Return a Gtp_engine_protocol which run...
jmoudrik/gomble
kombilo_player.py
kombilo_player.py
py
2,802
python
en
code
0
github-code
13
31625859389
import argparse from pyteomics import mzid parser = argparse.ArgumentParser(description='Filter an MzIdentML file by q-value') parser.add_argument('input', help='input mzid file') parser.add_argument('threshold', type=float, help='maximum q value') parser.add_argument('output', help='location of filtered mzid file') ...
mrForce/tiny_scripts
python/mzid_qvalue_filter/filter.py
filter.py
py
1,213
python
en
code
0
github-code
13
4320562471
############################################################################## # Copyright (C) 2018, 2019, 2020 Dominic O'Kane ############################################################################## from numba import njit, float64, int64 from scipy import integrate from math import exp, log, pi import nu...
domokane/FinancePy
financepy/models/heston.py
heston.py
py
14,264
python
en
code
1,701
github-code
13
5255652282
from numpy.typing import NDArray import numpy as np class NaiveBayes: def fit(self, X:NDArray, y:NDArray) -> None: n_samples, n_features = X.shape self._classes:NDArray = np.unique(y) n_classes = len(self._classes) # calculate mean, var, and prior for each class self._mea...
supertigim/ML-DL-Rewind
machine_learning/from_scratch/models/naive_bayes.py
naive_bayes.py
py
1,751
python
en
code
0
github-code
13
6200520072
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Mar 16 20:47:35 2020 @author: vijetadeshpande """ import torch import sys sys.path.insert(1, r'/Users/vijetadeshpande/Documents/GitHub/Sequence2Sequence model for CEPAC prediction/Data processing, runs generator and utility file') import utils import pa...
vijetadeshpande/meta-environment
Encoder decoder with attention/evaluate_EncDec.py
evaluate_EncDec.py
py
2,914
python
en
code
0
github-code
13
37921616089
#!/usr/bin/env python """Train foreground segmentation network.""" from __future__ import division import numpy as np import os from utils import logger from utils import BatchIterator, ConcurrentBatchIterator from utils import plot_utils as pu from utils.lazy_registerer import LazyRegisterer from utils.step_counter ...
renmengye/rec-attend-public
fg_model_train.py
fg_model_train.py
py
17,207
python
en
code
107
github-code
13
14957777310
# CBV 방식으로 변경하기 # from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView, UpdateView # Detail을 불러오겠음 # django -> views -> generic 안의 CreateView를 불러오겠음. # 로그인 관련해서 django에서 지원해주는 라이브러리 # 로그인되어있을때만 보여줌 from django.contrib.auth.mixins import LoginRequiredMixin, UserPasses...
Sgkeoi/Goorm_Django
blog/views.py
views.py
py
11,212
python
ko
code
0
github-code
13
3039568331
#! python3 # ExcelToCSV.py - Converts all excel spreadsheets in the working directory to CSV files import csv, openpyxl, os def main(): ExcelToCSV() def ExcelToCSV(): for excelFile in os.listdir('.'): # Skip non-xlsx files if not excelFile.endswith('.xlsx'): continue ...
cjam3/AutomateTheBoringStuffPractice
Chapter 16/ExcelToCSV.py
ExcelToCSV.py
py
1,161
python
en
code
0
github-code
13
39031703852
# Recursive implementation class Solution(object): def combo(self, n, ans, s=0, c=0, p=""): if c==n: # All starting parantheses have been closed with equal numbers of valid closing parantheses for current permutation ans.append(p) # Append latest calulated permutation to final answer...
sarvesh10491/Leetcode
Pattern_Based/3_Generate_Parentheses.py
3_Generate_Parentheses.py
py
829
python
en
code
0
github-code
13
29578613364
import math import os import pygame gameStage = 1 startMenuButtons = ["Continue", "New Game", "Settings", "Exit"] # Initializes PyGame # pygame.init() os.environ["SDL_VIDEO_CENTERED"] = "1" screen = pygame.display.set_mode((1088, 768)) pygame.display.set_caption("Menu Testing") font = pygame.font.SysFont("ariel", 35...
Benjamin-Fever/Box-Shifter-I
gameTesting/menu.py
menu.py
py
1,811
python
en
code
0
github-code
13
22561465809
from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, projection='3d') X = [1,2,3,4,5,6,7,8,9,10] Y = [5,6,2,3,13,4,1,2,4,8] Z = [2,3,3,3,5,7,9,11,9,10] label = [1,1,1,1,1,0,0,0,0,0] for i in xrange(10): if label[i]==1: ax.scatter(X[i],Y[i],Z[i], c='r...
xiawang/HPCDA
src/test5.py
test5.py
py
475
python
en
code
0
github-code
13
11188204995
import numpy as np #np.set_printoptions(suppress=True) import os import matplotlib.pyplot as plt import pandas as pd import matplotlib.pyplot as plt def resolution(path,n,savepath): dir = path data = np.loadtxt(dir) j = 1 label = [] x = data[:, 0] y = data[:, 1] for i in rang...
gym918/Air-Spectrum
预处理/Resolution.py
Resolution.py
py
1,598
python
en
code
0
github-code
13
10934043036
# -*- coding: utf-8 -*- from bson import ObjectId import models import logging import threading from qmongo import helpers logger = logging.getLogger(__name__) global lock lock = threading.Lock() def get_list_with_searchtext(args): searchText = args['data'].get('search', '') pageSize = args['data']...
nttlong2018/hr-python
apps/performance/api/HCSSYS_ExcelTemplate.py
HCSSYS_ExcelTemplate.py
py
6,552
python
en
code
0
github-code
13
17428779224
import pandas as pd import stanza nlp = stanza.Pipeline(lang='en', processors='tokenize, sentiment') df = pd.read_csv('researchGate_Covid19ImpactAcademic.csv') textsList = [] for comment in df['Comment']: textsList.append(comment) docList = [] for text in textsList: docList.append(nlp(text)) resultList = []...
j56810186/python_little_part_of_research_project
sentimentAnalysis.py
sentimentAnalysis.py
py
783
python
en
code
0
github-code
13
42027174869
# -*- coding: utf-8 -*- __author__ = 'Xuesong Wang' import sys from data_helper import * from sklearn.model_selection import train_test_split import json import logging import tensorflow as tf from text_cnn import TextCNN import time import os if __name__ == '__main__': """ Step 0: reload coding systems to disp...
xuesongwang/Chinese-forum-mining
CNN/inclassCNN_train.py
inclassCNN_train.py
py
8,330
python
en
code
0
github-code
13
33938347478
import glob, os, re def UtilObserver(sourcepath,file_mask): unreal_source_path = sourcepath+'/Content/SHOTS/EPWHH' all_native_assets = glob.glob(unreal_source_path + file_mask, recursive=True) #all_optimized_assets = glob.glob(unreal_source_path + '/**/OPT/**/*.fbx', recursive=True) name_assets = all_...
denfrost/UnrealPyClient
Content/Python/UtilObserver.py
UtilObserver.py
py
1,451
python
en
code
6
github-code
13
406574802
""" SIGNAL PROCESSING """ # import essentia from essentia.standard import FrameGenerator, Spectrum, Windowing import numpy as np from .utils import timer @timer def get_spectrogram(audio_data): spectrogram = [] spectrum = Spectrum() w = Windowing(type='hann') spectrogram = np.array(list(map( ...
conjectures/art-cgan
core/sp/signal_processing.py
signal_processing.py
py
1,619
python
en
code
0
github-code
13
22336199833
data = input() students_info = {} while not data == data.lower(): split = data.split(":") student_name = split[0] student_id = split[1] student_course = split[2] if student_course not in students_info: students_info[student_course] = {student_name: student_id} else: students_inf...
DimitarDimitr0v/Python-Fundamentals
06. Dictionaries/Lab/06. students.py
06. students.py
py
559
python
en
code
2
github-code
13
22244632338
import tensorflow as tf import pathlib import sys import datetime import time import yfinance as yf import copy from baseSignal import Signal import pandas as pd scriptpath = pathlib.Path(__file__).parent.resolve() sys.path.append(str(scriptpath.parent.parent/'utils')) from dict_utils import Df_to_Dict, get_future_day...
jamesyeogz/FYP_project
engine/engine/indicator_engine/MLSignal.py
MLSignal.py
py
3,382
python
en
code
0
github-code
13
37988597174
import sys def txt_importer(path_file: str): if not path_file.endswith(".txt"): print("Formato inválido", file=sys.stderr) return try: with open(f"{path_file}", "r") as file: stacked_text = file.read().split("\n") return stacked_text except FileNotFoundError...
JOAO-LEE/project_ting_trybe_is_not_google
ting_file_management/file_management.py
file_management.py
py
533
python
en
code
0
github-code
13
14423489517
import requests import tkinter as tk class Box(object): isChecked = False isSubmarine = False btnTxt = "" lblBox = "" def __init__(self, boxID, lblBox, GameBoard): self.boxID = boxID self.lblBox = lblBox self.GB = GameBoard def ShootBox(self, event): if self.G...
oniken18/SubmarineWar_Python
BoxClass.py
BoxClass.py
py
1,035
python
en
code
0
github-code
13
74638928016
from decouple import config ENVIRONMENT = config('ENVIRONMENT', default='DEVELOPMENT') if ENVIRONMENT.upper() == 'PRODUCTION': from project_name.settings.staging import * elif ENVIRONMENT.upper() == 'STAGING': from project_name.settings.production import * else: from project_name.settings.development impo...
CodingArmenia/django-rest-api-project-template
project_name/settings/__init__.py
__init__.py
py
670
python
en
code
0
github-code
13
21223774732
def add_to_inventory (inventory, added_items): for i in range(len(added_items)): inventory.setdefault(added_items[i], 0) inventory[added_items[i]] += 1 return inventory def display_inventory (display): print ("Inventory:") total_inv = 0 for k, v in display.items(): print...
kestena/automatetheboringstuffwithpython
chapter_5_add_to_inventory.py
chapter_5_add_to_inventory.py
py
599
python
en
code
0
github-code
13
11045600210
import logging import sys import time import json import jieba.analyse jieba.setLogLevel(logging.ERROR) jieba.initialize() from titletrigger.api import load_model, abs_summarize, tag_classify, extract_keywords, ext_summarize sys.path.append('titletrigger/textsum') sys.path.append('titletrigger/textclf') if __name__ ...
ScarletPan/ML-Camp-BurnMyGpu
example.py
example.py
py
3,029
python
zh
code
2
github-code
13
26530006772
import cv2 import time import sys import numpy as np sys.path.append('..') from libs import FaceGateway from libs import EyesGateway from libs import EyeDirectionGateway from libs import PupilsGateway #The issue with OpenCV track bars is that they require a function that will happen on each track bar # movement. We do...
ritamouraribeiro/eye-tracker-opencv
libs/WebCamGateway.py
WebCamGateway.py
py
1,287
python
en
code
0
github-code
13
1316905772
__all__ = ["AMTrainer", "build_model", "_parser", "main"] from ..shared import Manager from ..shared import coreutils from ..shared import encoder as model_zoo from ..shared.data import ( KaldiSpeechDataset, sortedPadCollateASR ) import os import argparse from typing import * import torch import torch.nn as ...
NLPvv/Transducer-dev-1
cat/ctc/train.py
train.py
py
6,089
python
en
code
0
github-code
13
73091567697
# These are primarily intended to be used with simulate.calc_lens import metrics import pandas import decimal from decimal import Decimal as D def calc_pwa0(annual_data): return metrics.pwa(1, 0, [n.returns_r for n in annual_data]) def calc_pwa1(annual_data): return metrics.pwa(1, 1, [n.returns_r for n in an...
hoostus/prime-harvesting
lens.py
lens.py
py
3,399
python
en
code
26
github-code
13
37296083485
import matplotlib.pyplot as plt import numpy as np import sys import json from util import Log, ConstellationToXY def main(): if len(sys.argv) != 3 and len(sys.argv) != 5: Log("ERR. Incorrent number of args.") return if sys.argv[1] != "-f": Log("ERR. No '-f' param given.") re...
skyhoffert/ENEE623_Project
report.py
report.py
py
961
python
en
code
0
github-code
13
31071192149
# -*- encoding: utf-8 -*- """ PyCharm show 2022年08月14日 by littlefean """ from typing import * 空 = None 真 = True def 主函数(): 打印 = print 打印(123) return 空 if __name__ == "__main__": 主函数()
Littlefean/SmartPython
python迷惑行为/中文编程/show.py
show.py
py
240
python
zh
code
173
github-code
13
672494652
import logging from sawtooth_sdk.protobuf import state_context_pb2 from sawtooth_sdk.processor.exceptions import InvalidTransaction from rbac_addressing import addresser from rbac_processor.common import get_state_entry from rbac_processor.common import is_in_role_attributes_container from rbac_processor.common impor...
hyperultra-zz/selenium
processor/rbac_processor/role/role_apply.py
role_apply.py
py
4,490
python
en
code
0
github-code
13
3873729152
def swap(mylist,i): # that sit at indices i and (i+1). if (i >= 0 and i+1 <= len(mylist) - 1): # testing that the two indices are valid for the list temp = mylist[i+1] mylist[i+1] = mylist[i] mylist[i] = temp else: print('error: index out of bounds') def scan_once(l): # it returns True if it has performe...
Nxumalo/Sort-Methods
Bubble Sort.py
Bubble Sort.py
py
4,675
python
en
code
0
github-code
13
28127352990
""" 最大值减去最小值小于或者等于num的子数组数量 题目: 给定数组arr和整数num,共返回有多少个子数组满足如下情况: max(arr[i..j]) - min(arr[i..j]) <=num max(arr[i..j]}表示子数组arr[i..j]中的最大值,min(arr[i..j])表示子数组arr[i..j]中的最小值 要求: 如果数组的长度为N,请实现时间复杂度为O(N)的解法 """ from development.chapter7.LinkedDeque import LinkedDeque def get_num(arr, num): """最大值减去最小值等于num的数量的具体实现""...
liruileay/data_structure_in_python
data_structure_python/question/chapter1_stack_queue_question/question11.py
question11.py
py
1,244
python
zh
code
0
github-code
13
9483519716
''' Created on 27 mar 2016 @author: linky ''' import Funzioni_PyTumblr import pytumblr from time import sleep from _Poster import _poster as ps from Funzioni_PyTumblr import * class Poster(ps): ''' classdocs Questa classe avra' il compito di gestire la ricezione delle immagini da postare...
Linkinax/PyTumblr
Poster/Poster.py
Poster.py
py
3,668
python
it
code
0
github-code
13
4693902191
import textwrap def merge_the_tools(string, n): # Calculate the length of each substring substring_length = n # Split the string into substrings substrings = textwrap.wrap(string, substring_length) result_list = [] for string in substrings: unique_chars = [] for char in string:...
ifte110/Python-hackerrank
merge_the_tools.py
merge_the_tools.py
py
930
python
en
code
0
github-code
13
35220089434
import torch import torch.nn as nn import torch.nn.functional as F class DuelingCNN(nn.Module): def __init__(self, img_dim, w, h, input_dim, output_dim, dueling_type='mean'): super().__init__() self.dueling_type = dueling_type self.device = torch.device('cuda' if torch.cuda.is_available() e...
vinaykudari/maze-solver
cnn_dueling.py
cnn_dueling.py
py
1,552
python
en
code
0
github-code
13
19124576657
# Note: This is a model directly from the https://pytorch.org/tutorials/intermediate/speech_command_classification_with_torchaudio_tutorial.html # This model reflects the model described in the following paper: https://arxiv.org/pdf/1610.00087.pdf import torch import torch.nn as nn import torch.nn.functional as F impor...
achandlr/Music-Genre-Classifier
src/models/M5_Audio_Classifier.py
M5_Audio_Classifier.py
py
1,963
python
en
code
0
github-code
13
19420524977
import shutil import subprocess from dataclasses import dataclass def does_program_exist(prog_name): if shutil.which(prog_name) is None: return False else: return True @dataclass(frozen=True, order=True) class Opts: steps: int = 1000000 sterics: bool = False extra_pdbs: str = "" ...
jyesselm/rnamake_ens_gen
rnamake_ens_gen/wrapper.py
wrapper.py
py
1,296
python
en
code
0
github-code
13
38190607909
from databases import Database from fastapi import HTTPException from sqlite3 import IntegrityError import json from models.term_definition import TermDefinition class LexicalException(Exception): pass # global cache of Lexicon class Lexicon(): resolve_query = "SELECT Params, Definition, Line FROM Term WHE...
rottytooth/Babble
lexicon_dao.py
lexicon_dao.py
py
2,955
python
en
code
0
github-code
13
7377922214
import numpy as np import scipy from matplotlib import pyplot as plt from numpy.random import randint from ikrlib import train_gmm, logpdf_gmm from projekt_lib import wav16khz2mfcc,png2fea train_n = wav16khz2mfcc('train_data/non_target_train').values() train_t = wav16khz2mfcc('train_data/target_train').values() tes...
xgalba03/SUR---person-recognition-NN-
IKR_demos_py/projekt.py
projekt.py
py
2,686
python
en
code
0
github-code
13
28008586690
# -*- coding: utf-8 -*- """ Created on Wed Mar 13 06:14:25 2019 #pythonprogramming.net python3.7 basics tutorial - Making a simple TicTacToe game. @author: RB """ import itertools def win(current_game): def all_same(l): if l.count(l[0]) == len(l) and l[0] != 0: return True ...
Ravenblack7575/Exercises-Testing
tictactoe4.py
tictactoe4.py
py
3,671
python
en
code
0
github-code
13
71606898577
MENU = { "espresso": { "ingredients": { "water": 50, "coffee": 18, }, "cost": 1.5, }, "latte": { "ingredients": { "water": 200, "milk": 150, "coffee": 24, }, "cost": 2.5, }, ...
hlee0995/Python_review
Coffee Machine.py
Coffee Machine.py
py
2,083
python
en
code
0
github-code
13
27802796412
# 이미 푼 문제 # 해결 방법만 떠올리고 skip # 브루트포스 # combination으로 팀을 뽑으면 쉬울거같은데? # 시간복잡도도 충분 20C10 # -- 이전 코드를 본 후 -- # 스타트, 링크팀 분리 후 각 팀의 능력치를 구할 때, set, permu를 사용하네 좋은 코드다 # 잘 살펴보자 #20c10 하면 20만 시간복잡도는 충분하다 from itertools import combinations,permutations N = int(input()) arr = [list(map(int, input().split())) for _ in range(N)]...
tkdgns8234/DataStructure-Algorithm
Algorithm/백준/백준강의/알고리즘_중급_1/브루트포스/순열-연습/스타트와_링크.py
스타트와_링크.py
py
815
python
ko
code
0
github-code
13
32674133645
import numpy as np from dt import * from datasets import * from sklearn.model_selection import cross_validate from plots import read_csv, write_csv import copy def eval(algorithm, dataset): cls = {"LocalInformationGain": LocalInformationGainDecisionTreeClassifier, "GlobalInformationGain": GlobalInform...
285714/DecisionTrees
Figures/treesize_bestof.py
treesize_bestof.py
py
1,697
python
en
code
2
github-code
13
71819385618
import numpy as np import tensorflow as tf def WALS(R,I,It,bm,bg,bu,_N): _GL, _UL = I.shape _IL = np.sum(I) _TL = np.sum(It) zero=np.zeros_like(R) bias = bm+np.expand_dims(bg,1)+bu idx=tf.where(I) print("idx ready") input_tensor = tf.SparseTensor(indices=idx, ...
greg3566/BoardgameRating
MF.py
MF.py
py
2,334
python
en
code
0
github-code
13
35230779392
#!/usr/bin/python3 """ This script lists all State objects from database passed into program Using SQLalchemy, this script connects to a MySQL server running on localhost at port 3306. This script takes 3 arguments: mysql username, mysql password, and database name. These arguments are used to connect to the MySQL se...
fernandogmo/holbertonschool-higher_level_programming
0x0F-python-object_relational_mapping/7-model_state_fetch_all.py
7-model_state_fetch_all.py
py
896
python
en
code
1
github-code
13
1346866891
import math from typing import Dict, List, Optional, Tuple import torch import torch.nn as nn import torch.nn.utils.rnn as rnn_utils from pyhealth.datasets import SampleEHRDataset from pyhealth.models import BaseModel from pyhealth.models.utils import get_last_visit class FinalAttentionQKV(nn.Module): def __ini...
sunlabuiuc/PyHealth
pyhealth/models/concare.py
concare.py
py
37,784
python
en
code
778
github-code
13
21575492145
#!usr/bin/env python3 from collections import defaultdict from collections import deque from heapq import heappush, heappop import sys import math import bisect import random def LI(): return list(map(int, sys.stdin.readline().split())) def I(): return int(sys.stdin.readline()) def LS():return list(map(list, sys.stdin....
hppRC/competitive-programming-solutions
ARC/ARC-B/ARC037B.py
ARC037B.py
py
1,848
python
en
code
3
github-code
13
42855737830
import torch from torch.nn import functional as F def scalar_to_support(x, support_size): """ Transform a scalar to a categorical representation with (2 * support_size + 1) categories See paper appendix Network Architecture """ x = torch.clamp(x, -support_size, support_size) floor = x.floor() ...
rlditr23/RL-DITR
ts/utils.py
utils.py
py
2,872
python
en
code
10
github-code
13
3743390771
from keycloakManager.keycloakConnection import Connection import asyncio class Login(Connection): """### Login (saljemo user creaditionale i dobijamo token) - `email` - `secret` ##### Ova klasa je child i nasledjuje objekte za konekciju od parnet klase i vraca keycloak token """...
mifa43/WebApp
auth/src/keycloakManager/keycloakLogin.py
keycloakLogin.py
py
834
python
en
code
0
github-code
13
22028708813
import world_of_supply_rllib as wsr import random import numpy as np import time import ray from ray.tune.logger import pretty_print from ray.rllib.utils import try_import_tf import ray.rllib.agents.trainer_template as tt from ray.rllib.models.tf.tf_action_dist import MultiCategorical from ray.rllib.models import Mod...
ikatsov/tensor-house
supply-chain/world_of_supply/world_of_supply_rllib_training.py
world_of_supply_rllib_training.py
py
7,774
python
en
code
1,049
github-code
13
10191613795
import heapq def solution(operations): heap = [] for x in operations: oper, num = x.split() num = int(num) if oper == "D" and num == 1: if heap: max_value = max(heap) heap.remove(max_value) elif oper == "D" and num == -1: ...
Jinnie-J/Algorithm-study
programmers/이중우선순위큐.py
이중우선순위큐.py
py
487
python
en
code
0
github-code
13
71165000659
import torch import torch.nn.functional as F from config import config _config = config() print('asdasd') def evaluate(golden_list, predict_list): num_list_1 = len(golden_list) num_list_2 = len(golden_list[0]) num_gt = 0 num_pre = 0 for i in range(num_list_1): for j in range(len(predi...
Elijahlen/Python_Project_BiLSTM_Hyponymy-Classification
todo.py
todo.py
py
3,960
python
en
code
1
github-code
13
17268390576
#! /usr/bin/env python3 '''Letters to words challenge assistant. This program takes a collection of letters entered as a string and returns all possible valid English words. ''' # Standard libraries: from collections import defaultdict from itertools import permutations from pathlib import Path import sys # Th...
sockduct/Weekly
letters2words.py
letters2words.py
py
2,285
python
en
code
0
github-code
13
23559722226
""" The "Reader" class was created for the conversion of JSON data to a dictionary Where the dictionary's keys are input strings and values are the "Result" class objects. """ import json from EGS_task.Result import Result class Reader: # Opening JSON file @staticmethod def json2dict(json_path): ...
Azatyan0/EGS-Task
EGS_task/Reader.py
Reader.py
py
632
python
en
code
0
github-code
13
29147914676
import datetime from transaction import Transaction from Crypto.Hash import SHA256 class Block: def __init__(self, transaction_list: [Transaction], hash_key: str = None, nonce: bytes = None, prev_hash: str = None): # When we create a block we know its previous block self.previous_hash = prev_hash...
LightingSpider/Blockchain-NBC
block.py
block.py
py
4,828
python
en
code
1
github-code
13
4067796509
# -*- coding: utf-8 -*- ''' Created on Mon Jun 17 11:34:02 2019 @author: Patrik_Zelena ''' from DatabaseHelper import DatabaseHelper from HotelKNNAlgorithm import HotelKNNAlgorithm from Evaluator import Evaluator from surprise import Dataset, Reader import random import numpy as np import logging log = ...
zeletrik/HRecSys
app/Recommender.py
Recommender.py
py
2,024
python
en
code
1
github-code
13
8489640134
# Fileneme: test001.py import string def reverse(text): return text[::-1] def is_palindrome(text): text = text.lower() print(text) text = text.replace(' ', '') print(text) for char in string.punctuation: text = text.replace(char, '') print(text) return text == reverse(text) d...
likaiharry/First
test001.py
test001.py
py
547
python
en
code
0
github-code
13
73019813459
import os import logging import time from logging import handlers LOG_FORMAT = "%(asctime)s - %(levelname)s: %(message)s" DATE_FORMAT = "%m/%d/%Y %H:%M:%S %p" debug_file_path = './data/track_{0}.log'.format(time.strftime('%Y%m%d_%H%M%S')) app_file_path = './data/app_{0}.log'.format(time.strftime('%Y%m%d_%H%M...
yiweisong/ins401-log
app/debug.py
debug.py
py
1,328
python
en
code
0
github-code
13
34560439464
#Joe Hester #Asteroids #final project import pygame from pygame.locals import * from math import cos,sin,pi,hypot import random class Ship(object): def __init__(self,x,y,vx,vy): self.x = x self.y = y self.vx = vx self.vy = vy self.angle = -pi/2 self....
csharrison/Student-Final-Projects
joseph_hester/asteroids_2.py
asteroids_2.py
py
5,462
python
en
code
1
github-code
13
21004127975
import numpy as np import random import time from math import sqrt import pandas as pd import glob from numpy import random import sys import pathlib import math from math import * import time import argparse import logging import apache_beam as beam from apache_beam.dataframe.convert import to_dataframe from apache_...
SaarucaK/cloud-project
project_combined_pipeline.py
project_combined_pipeline.py
py
3,148
python
en
code
0
github-code
13
17781804063
import requests from bs4 import BeautifulSoup url = 'https://news.ycombinator.com/news' url_htmltext_request = requests.get(url).text soup_object = BeautifulSoup(url_htmltext_request, 'html.parser') titlelink = soup_object.select('.titlelink') subtext = soup_object.select('.subtext') def my_news(links,...
adeagbaje/webscraping
webscraping.py
webscraping.py
py
748
python
en
code
0
github-code
13
17114961134
import logging from agr_literature_service.api.models import ReferenceModel, CrossReferenceModel, \ ReferencefileModel, AuthorModel, MeshDetailModel from agr_literature_service.lit_processing.utils.db_read_utils import \ get_references_by_curies, get_curie_to_title_mapping, \ get_pmid_list_without_pmc_packa...
alliance-genome/agr_literature_service
tests/lit_processing/utils/test_db_read_utils.py
test_db_read_utils.py
py
9,089
python
en
code
1
github-code
13
6810068590
#!/usr/bin/python3 import numpy as np import matplotlib.pyplot as plt def g1( v ): x,y=v[0],v[1] return 2*x**2+y**2-2 def g2(v ): x,y=v[0],v[1] return (x-1/2)**2+(y-1)**2-1/4 def g( v ): x,y=v[0],v[1] w=np.array([g1(v),g2(v)]) #print(w) return w def G(v): a=g(v) return 1/2*a.T.dot(a) def J(v): x,y=v[0],v[1]...
matstep0/metody_numeryczne
zad14/zad14.py
zad14.py
py
774
python
en
code
0
github-code
13
13344724191
from tkinter import * from datetime import datetime import pytz root = Tk() root.title('—') frame = Frame() Label(root, text='Choose any Timezone', fg='navyblue').pack() frame.pack() time_scrollbar = Scrollbar(frame, orient=VERTICAL) time_listbox = Listbox(frame, yscrollcommand=time_scrollbar.set) time_scrollbar.con...
aaravdave/YoungWonks
Level 3/Tkinter/4) Listbox and Notebook/Question 2.py
Question 2.py
py
908
python
en
code
0
github-code
13
73097435216
def custom_sort(string): return(string.swapcase()) def generator(text, sep="", option=None): """Option is an optional arg, sep is mandatory""" if not isinstance(text, str): yield("ERROR") return if not isinstance(sep, str) or not sep: yield("ERROR") return output = ...
Cizeur/Bootcamp_Python
day01/ex03/generator.py
generator.py
py
1,574
python
en
code
0
github-code
13
31724254292
def f(stack): result = stack.pop() if len(stack) == 0: return result else: last = f(stack) stack.append(result) return last def reverse(stack): if len(stack) == 0: return last = f(stack) reverse(stack) stack.append(last)
Zhouxinyu668/Algorithm
recurrent/reverse_stack.py
reverse_stack.py
py
292
python
en
code
1
github-code
13
6485178565
""" https://www.codeeval.com/open_challenges/82/ """ def isArmstrongNumber(line): """Determine if armstrong number """ squaredSum = 0 getNum = 0 for i in list(line): i = i.strip() if len(i) > 0: getNum = int(line) squaredSum += (int(i) ** len(line.strip()))...
elexie/Codeeval-python
easy/ArmstrongNumbers.py
ArmstrongNumbers.py
py
491
python
en
code
0
github-code
13
26963586445
# coding: utf-8 from http.client import IncompleteRead from typing import List, Tuple import tweepy from loguru import logger from tweepy import API, OAuthHandler, Stream from urllib3.exceptions import ProtocolError, ReadTimeoutError from .authapi import AuthApi from .listener import ListenerConsole, ListenerDB LOG...
Kydlaw/pumpy
pumpy/twitter_mining.py
twitter_mining.py
py
6,769
python
en
code
1
github-code
13
22477766653
from typing import Optional import pytorch_lightning as pl import segmentation_models_pytorch as smp import torch.nn as nn import torch.nn.functional from src.metric.detection_f1 import DetectionF1Metric from src.losses.negative_loss import NegativeLoss from src.losses.combine_loss import CombineLoss from src.losses....
PUTvision/UAV-DOT-DETECT
src/model/regressor.py
regressor.py
py
10,103
python
en
code
0
github-code
13
44466297211
from binance.client import Client import json from datetime import datetime, timedelta, time import time import schedule #Binance apì keys api_key= '' api_secret= '' client = Client(api_key, api_secret) # Symbol you wish to trade and price symbol = 'BNBUSDT' price = client.get_avg_price(symbol=symbol) # initialize b...
PixelNoob/copernico
twap.py
twap.py
py
975
python
en
code
0
github-code
13
41998448364
class TicTacToe: def __init__(self): self.numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] self.divider = '_+_+_' self.playerX = 'x' self.playerO = 'o' self.prompt = ' turn to chose a square (1-9): ' self.input = '' self.turns = 0 def clear_input(self): s...
vitorbarros/byu-cse210
w01/prove_developer_solo_code_submission.py
prove_developer_solo_code_submission.py
py
1,580
python
en
code
0
github-code
13
17387250812
import socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(('', 9999)) try : while True : data, addr = sock.recvfrom(1000) data = "Hello "+data sock.sendto(data, addr) except KeyboardInterrupt : sock.close()
bhawiyuga/sister2016
ipc/udp_simple_server.py
udp_simple_server.py
py
241
python
en
code
0
github-code
13
74176772179
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jan 15 09:49:22 2022 @author: gregz """ import numpy as np from astropy.io import fits import matplotlib.pyplot as plt import os.path as op from astropy.convolution import convolve, Gaussian2DKernel, Gaussian1DKernel from astropy.table import Table fro...
grzeimann/Panacea
sn_reduction_example.py
sn_reduction_example.py
py
12,577
python
en
code
8
github-code
13
72752780177
""" SJTU-AU333-数字图像处理-作业2边缘检测 """ import cv2 import numpy as np import matplotlib.pyplot as plt from numpy import * import os from Smoothing import medianSmooth # 支持中文标题 plt.rcParams['font.sans-serif']=['SimHei'] #显示中文标签 plt.rcParams['axes.unicode_minus']=False #这两行需要手动设置 # 输入输出目录与算子列表 srcpath = './MSGaussRes' resp...
hahhforest/SmallProjects
DigitalImageProcessing/边缘检测/EdgeDetect.py
EdgeDetect.py
py
5,706
python
en
code
0
github-code
13
41633358786
"""import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from collections import namedtuple n_groups = 3 means_alg = (20, 35, 30, 35, 27) std_men = (2, 3, 4, 1, 2) means_women = (25, 32, 34, 20, 25) std_women = (3, 5, 2, 3, 3) index = np.arange(n_groups) bar_width = 0.35 o...
MrSpadala/Epic_VANET
grafici/top_car/graph-TC-emitters.py
graph-TC-emitters.py
py
4,027
python
en
code
2
github-code
13
12653168420
from matplotlib import pyplot as plt from torchvision import transforms from PyTorch_2.Faces import Faces_dataset from PyTorch_2.Faces.Faces_show_landmarks import show_landmarks from PyTorch_2.Faces.models.Transform import Rescale, RandomCrop # 调用torchvision.transforms.Compose实现图片大小、数据格式转换 # 把图像的短边调整为256 scale = Resca...
Darling1116/Greeting_1116
PyTorch_2/Faces/Faces_transform_test1.py
Faces_transform_test1.py
py
986
python
en
code
0
github-code
13
12762850396
'''APARTMENT BUILDING ADMINISTRATOR undolist.append(deepcopy(l))''' def testInit(expenseslist): #10 items in the list at the begining of the execution expenseslist.append((1, "gas", 100)) expenseslist.append((2, "water", 80)) expenseslist.append((2, "heating", 200)) expenseslist.append((2, "elect...
danalrds/FP
ddd/functions.py
functions.py
py
15,070
python
en
code
0
github-code
13
6997733750
# Indexable skip list # __getitem__: returns k-th element, 0-indexed # update: will not be used outside the class # find: if used outside the class, returns the maximal element up to val # insert: insert val # remove: remove val # iterate: show the structure of the list, use this to debug class Node: def ...
hongjun7/PythonAlgorithms
SkipList&Index.py
SkipList&Index.py
py
2,925
python
en
code
null
github-code
13
10642385163
import pyglet from pyglet.window import key import ratcave as rc # Create Window window = pyglet.window.Window(resizable=True) keys = key.KeyStateHandler() window.push_handlers(keys) def update(dt): pass pyglet.clock.schedule(update) # Insert filename into WavefrontReader. obj_filename = rc.resources.obj_primit...
ratcave/ratcave
examples/solar_system.py
solar_system.py
py
2,102
python
en
code
110
github-code
13
219611823
""" import sys from collections import deque # sys.stdin = open("input.txt", 'r') must = input() n = int(input()) for i in range(1, n + 1): course = input() queue = deque() for x in course: if x in must and x not in queue: queue.append(x) if len(queue) != len(must): print(...
ignis535/baekjoon
자료구조(스택, 큐, 해쉬, 힙)/교육과정 설계.py
교육과정 설계.py
py
948
python
en
code
0
github-code
13
29204065835
from math import sqrt def is_square_pairs(n: int, cuts: list, squares: list) -> bool: prev = cuts[-1] if n == len(cuts): # 全要素が埋まった if (1 + prev) in squares: # 最初の一つ(固定 1)と最後の一つの合計がが平方数である print(f'Count: {n}, Cuts: {cuts}') return True else: # 接続...
Sunao-Yoshii/StudyDocs
Books/math_pazzle/18_cut_cake.py
18_cut_cake.py
py
901
python
ja
code
0
github-code
13
27302787185
import re from converter.markdown.tabular import Tabular class Tabularx(Tabular): def __init__(self, latex_str, caret_token): super().__init__(latex_str, caret_token) self._table_re = re.compile(r"""\\begin{(?P<block_name>tabularx)}{(?P<settings>.*?)} (?P<bloc...
codio/book-converter
converter/markdown/tabularx.py
tabularx.py
py
465
python
en
code
2
github-code
13
2040469946
import random import time import pygame import numpy as np # CONSTANTS BLUE = (0,0,255) WHITE = (0, 0, 0) BACKGROUND = WHITE FRAME_REFRESH_RATE = 60 DISPLAY_WIDTH = 640 DISPLAY_HEIGHT = 480 STARSHIP_SPEED = 3 max_meteor_speed = 4 INITIAL_NUMBER_OF_METEORS = 10 MAX_NUMBER_OF_CYCLES = 1000 NEW_METEOR_CYCLE_INTERVAL = ...
s276842/python-playground
pygame/Starship Meteors.py
Starship Meteors.py
py
6,689
python
en
code
0
github-code
13
40918582748
#Max Millar #SoftDev1 pd06 #k25 -- Getting More REST #2018-11-14 from flask import Flask, render_template import json from urllib import request app = Flask(__name__) @app.route('/') def render_test(): data = json.loads((request.urlopen("https://en.wikipedia.org/w/api.php?action=parse&page=Barack_Obama&format=js...
stuymmillar/SoftDev
25_rest/app.py
app.py
py
635
python
en
code
0
github-code
13
5835105101
import os import sys from dataclasses import dataclass from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from exception import CustomException from logger import logging from utils import save_object,evaluate_models @dataclass class ModelTrainerConfig: ...
pras-ops/Bank_Card_Prediction_Project
src/components/model_trainer.py
model_trainer.py
py
2,310
python
en
code
0
github-code
13
41231002119
import os import nextcord from nextcord.ext import commands PREFIX = os.environ['PREFIX'] intents = nextcord.Intents.default() intents.members = True bot = commands.Bot(command_prefix=PREFIX, intents=intents) @bot.event async def on_ready(): print(f'{bot.user} is online!') @bot.command() async def ping(ctx):...
uhIgnacio-zz/heroku-example
src/main.py
main.py
py
381
python
en
code
3
github-code
13
37451127020
#defining data #x colour is V-z k-corrected to z=0.9 #y colour is J-[3.6] k-corrected to z=0.9 #xcolour = (geec2['MAG_V']-geec2['KCORR09_V'])-(geec2['MAG_z']-geec2['KCORR09_z']) #ycolour = (geec2['MAG_J']-geec2['KCORR09_J'])-(geec2['MAG_I1']-geec2['KCORR09_I1']) xcolour = balogh_photoz['V-z'] ycolour = balogh_p...
PiercingDan/cosmos-analysis
Paste Scripts/Graphs/Old/balogh2geec2colour.py
balogh2geec2colour.py
py
3,583
python
en
code
0
github-code
13
71948829457
# 데이터 삽입 구현 katok = ['a','b','c','d','e'] def insert_data(position, friend) : # 삽입 함수 katok.append(None) kLen = len(katok) for i in range(kLen-1, position, -1) : katok[i] = katok[i-1] katok[i-1] = None katok[position] = friend insert_data(2, '솔라') # 2등 위치에 솔라를 넣어라 print(katok) insert_...
handhak0/2021_python_multicampus
00.Special_Lecture/Algorithm/Code03_02.py
Code03_02.py
py
440
python
ko
code
1
github-code
13
28609562473
#Question Link: https://takeuforward.org/data-structure/fractional-knapsack-problem-greedy-approach/ #Solution Link (Python3): https://practice.geeksforgeeks.org/viewSol.php?subId=05e09acc984333ecb672d8168ef5d475&pid=701365&user=tiabhi1999 #For complete code snippet and question, please refer GFG link (https://pra...
AbhiWorkswithFlutter/StriverSDESheet-Python3-Solutions
Striver SDE Sheet/Day 8/Fractional Knapsack Problem.py
Fractional Knapsack Problem.py
py
1,174
python
en
code
3
github-code
13
11732811823
from userProfileHandler import * import userProfile import time class controller: firstName = userProfile.getFirstName() lastName = userProfile.getLastName() phone = userProfile.getPhoneNumber() address = userProfile.getAddress() email = userProfile.getEmail() user = makeUserProfile(firstName...
Oddant1/QR-MeNow
qrCodeController.py
qrCodeController.py
py
829
python
en
code
0
github-code
13