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
40639476449
from pygame.locals import * import numpy as np import os import pygame import sys import time from source.core.game_objects.bomb.Bomb import Bomb from source.core.game_objects.bomb.Fire import Fire from source.core.game_objects.character.Cpu import Cpu from source.core.ui.GameOver import GameOver from source.core.ui.M...
asilvaigor/bomberboy
source/core/engine/Match.py
Match.py
py
10,719
python
en
code
1
github-code
1
39906386971
from sklearn.model_selection import train_test_split import tensorflow as tf import keras import os import numpy as np from PIL import Image import matplotlib.pyplot as plt from os import listdir from matplotlib import image import random from keras.utils import np_utils from keras import callbacks # batch_size = high...
jansowa/pneumonia-model
load_data.py
load_data.py
py
4,145
python
en
code
0
github-code
1
72827279715
import sys from collections import deque dx = [1,-1,0,0] dy = [0,0,1,-1] n,m = map(int,sys.stdin.readline().split()) arr = [] for _ in range(m): arr.append(list(sys.stdin.readline().strip())) visit = [[int(1e9)]*n for _ in range(m)] queue = deque([[0,0]]) visit[0][0] = 0 while queue: x,y = queue.popleft() ...
clapans/Algorithm_Study
박수근/all_code/1261.py
1261.py
py
767
python
en
code
0
github-code
1
36172478589
class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: intervals.sort(key=lambda x: x[0]) noIntervals = [intervals[0]] for idx in range(1, len(intervals)): left = noIntervals[-1] right = intervals[idx] if(left[1] < right[0...
HyeokminFrancis/LeetCode
0056-merge-intervals/0056-merge-intervals.py
0056-merge-intervals.py
py
603
python
en
code
0
github-code
1
33711265867
import pandas as pd from dateutil import parser import numpy as np def load_data(_file, pct_split): """Load test and train data into a DataFrame :return pd.DataFrame with ['test'/'train', features]""" # load train and test data data = pd.read_csv(_file) # split into train and test using pct_spli...
braddeutsch/example_pipeline
btc_battle/data/make_dataset.py
make_dataset.py
py
1,960
python
en
code
0
github-code
1
30603734654
from question_model import Question from question_data import quiz_questions_list from quiz_brain import QuizBrain question_bank = [] for question in quiz_questions_list: question_name = question['ask_question'] answer = question['the_answer'] new_question = Question(question_name, answer) question_b...
chanmyaemaung/quiz-python-question
main.py
main.py
py
552
python
en
code
3
github-code
1
41629028008
from jira import JIRA import pandas as pd from datetime import datetime import plotly import plotly.graph_objs as go import numpy as np from ast import literal_eval from IPython.display import display, HTML pd.set_option('display.max_columns', 999) plotly.offline.init_notebook_mode() def product_closed_time(version)...
matthewjwall/youi-product-flow-metrics
scripts/metrics_okrs.py
metrics_okrs.py
py
8,557
python
en
code
0
github-code
1
33524555484
from tkinter import * from tkinter.ttk import * from tkinter import scrolledtext import os import tkinter.filedialog as filedialog from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk # Implement the default Matplotlib key bindings. from matplotlib.backend_bases import key_press_handler...
JonathanCauchon/LunaUtils
GUI.py
GUI.py
py
11,420
python
en
code
1
github-code
1
12622362396
import face_recognition from PIL import Image, ImageDraw # This is an example of running face recognition on a single image # and drawing a box around each person that was identified. # Load a sample picture and learn how to recognize it. neutral_image = face_recognition.load_image_file("neutral.jpg") neutral_face_en...
VishalPatnaik/Facial-Emotion-Detection
expressions.py
expressions.py
py
3,370
python
en
code
4
github-code
1
1270621755
import requests import pandas as pd from alpha_vantage.timeseries import TimeSeries import numpy as np def sharpe_sortino_beta(ticker='TSLA', market_returns='SPY'): try: ts = TimeSeries(key='SWKZ23Y8HKIF4N4A', output_format='pandas') data, meta_data = ts.get_daily_adjusted(ticker) ...
HudsonHurtig/TamuHack2023
StockData.py
StockData.py
py
1,756
python
en
code
0
github-code
1
30328424004
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def rightSideView(self, root: Optional[TreeNode]) -> List[int]: self.d = {} def inorder(node...
simratsingh14/algorithmns
199-binary-tree-right-side-view/199-binary-tree-right-side-view.py
199-binary-tree-right-side-view.py
py
734
python
en
code
0
github-code
1
11451378496
"""Handle operations with files and directories""" import os import sys class FileDirectory: """Handle common operations with files and directories""" def __init__(self): pass @staticmethod def check_directory(directory: str, exit_operation: bool = False) -> None: """ Check i...
LEO-Satellites/satellite-tracking
leosTrack/utils/filedir.py
filedir.py
py
1,318
python
en
code
3
github-code
1
7045820241
#!/usr/bin/env python3 import re import unicodedata import gzip import sys class TokenStats: def __init__(self, tid, count): self.tid = tid self.count = count def transform(token): return unicodedata.normalize("NFKD", token).encode("ascii", "ignore").decode("ascii").lower() def process(infil...
burtgulash/diplomka
code/system/index.py
index.py
py
2,598
python
en
code
0
github-code
1
24551404115
from test09 import animal # 부모클래스 base class, super, parent # 자식클래스 derived class, child # self: 자기 자신 / super: 부모 class Rabbit(animal): def __init__(self,foots): super().__init__(foots) ###부모의 init을 불러온다!!!### print("토끼 초기화") # self.eyes=2 # self.mouth=1 # self.ears=2 ...
soli1101/python_workspace
d20200729/test04.py
test04.py
py
719
python
en
code
0
github-code
1
26112150368
# This files contains your custom actions which can be used to run # custom Python code. # # See this guide on how to implement these action: # https://rasa.com/docs/rasa/custom-actions # This is a simple example for a custom action which utters "Hello World!" from typing import Any, Text, Dict, List # from rasa_sdk...
RupakBiswas-2304/covid-bot
actions/actions.py
actions.py
py
2,360
python
en
code
1
github-code
1
1369223624
import os, sys from contextlib import contextmanager # yay -Sa --noprovides --answerdiff=None --answerclean=None vim-plug @contextmanager def cd(path): cwd = os.getcwd() os.chdir(path) yield os.chdir(cwd) def build(name): print('build', name) if not os.path.exists(name): if os.system(...
pawnhearts/aur
build.py
build.py
py
1,534
python
en
code
0
github-code
1
42654133120
#!/usr/bin/env python3 # Written by Telekrex import pygame import sys import os os.environ['SDL_VIDEO_CENTERED'] = '1' tps = 30 pygame.init() pygame.display.set_caption('Color Calibrator') monitor = (pygame.display.Info().current_w, pygame.display.Info().current_h) clock = pygame.time.Clock() void = pygame.display.set_...
telekrex/colorbase
source/colorbase.py
colorbase.py
py
1,018
python
en
code
1
github-code
1
19388016465
from audioop import ratecv from pathlib import Path import tkinter as tk from tkinter import ttk from tkinter.filedialog import askopenfilename import PIL.Image import PIL.ImageTk # Defining of global variables... _MODULE_DIR = Path(__file__).resolve().parent class GifAnimationWin(tk.Tk): def __init__( ...
megacodist/a-bit-more-of-an-interest
Image/gif-animation.pyw
gif-animation.pyw
pyw
4,641
python
en
code
0
github-code
1
5103258436
from datetime import date atual = date.today().year totalmenor = 0 totalmaior = 0 for ano in range(1, 8): pessoa = int(input('Em que ano a {}ª nasceu? '.format(ano))) idade = atual - pessoa print('Essa pessoa tem {} anos.'.format(idade)) if idade < 21: totalmenor += + 1 else: totalma...
RaphaelHenriqueOS/Exercicios_Guanabara
Desafio054.py
Desafio054.py
py
446
python
pt
code
0
github-code
1
39619159455
# This string is using the backslash t (\t) to create a tab in # the string when printing. tabby_cat = "\tI'm tabbed in." # the "\n" is creating a new line, splitting the text where inserted. persian_cat = "I'm split\non a line" # The backslash is saying to "escape" with the backslash? backslash_cat = "I'm \\ a \\ cat"...
MichealGarcia/code
py3hardway/ex10.py
ex10.py
py
674
python
en
code
0
github-code
1
13806395486
""" Yo que se ya """ import argparse import mido import logging from timeit import default_timer as timer from video import Video # from moviepy.editor import * DEBUG = True def print_d(msg): if DEBUG: print(msg) def maxSymNotes(notes): curr = max = 0 for note in notes: if note[2] == 0...
nestor98/pymidi2vid
editor.py
editor.py
py
12,213
python
en
code
1
github-code
1
13223932657
from reference_model.Lactose.LactoseCrystallizer import LactoseCrystallizer from data.Data import Data, Batch from domain.Domain import Domain import numpy as np import seaborn as sns from data.Illustration import Illustration import matplotlib.pyplot as plt sns.set() # Construct discretized domain object for hybrid m...
rfjoni/ParticleModel
reference_model/Lactose/demo.py
demo.py
py
1,694
python
en
code
7
github-code
1
36584247654
import subprocess def run_script_1(): subprocess.call(["bash", "gke-db-demo.sh"]) def run_script_2(): subprocess.call(["bash", "gke-hol.sh"]) def run_script_3(): subprocess.call(["bash", "k3s-db-demo.sh"]) def run_script_4(): subprocess.call(["bash", "se-demo-eks.sh"]) def main(): print("_____...
jdtate101/jdtate101
picker.py
picker.py
py
1,392
python
en
code
1
github-code
1
15279915711
''' APPROACH 1: FOLLOW THE RULES We can simply check if the string follows all the rules, and we can break the rules into groups. 1. Digits (one of ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]) Both decimal numbers and integers must contain at least one digit. 2. A sign ("+" or "-") Sign characters ar...
onyxolu/DSA
TunmiseFB/TopHardQuestions/validNumber.py
validNumber.py
py
3,233
python
en
code
0
github-code
1
10461388653
""" Модуль для работы с базой данных sqlite3. """ import sqlite3 from typing import Dict import os PATH = 'db' DATABASE = 'db.sqlite3' connect = sqlite3.connect(os.path.join(PATH, DATABASE)) cursor = connect.cursor() def create_db() -> None: """ Создает базу данных и таблицы в ней, если база и таблицы ...
darkus007/FlatScrapper
database/db_sqlite.py
db_sqlite.py
py
2,466
python
ru
code
0
github-code
1
26276689512
import pandas as pd import json import dash from dash import dcc,html, callback from dash.dependencies import Input, Output import plotly.graph_objs as go import plotly.express as px import dash_bootstrap_components as dbc import numpy as np import pathlib dash.register_page(__name__, path = '/', name="Accueil") ## D...
louislat/deployer
pages/pg0.py
pg0.py
py
2,800
python
fr
code
0
github-code
1
75108634913
#!/usr/bin/python3 """ Author: cg Date: 2020/7/11 14:49 """ from db.mapping.basemap import BaseMap from db.mapping.jiangxi_river.jiangxi_river_item import JiangxiRiverItem class JiangxiRiver(BaseMap): @staticmethod def is_instance(data): return isinstance(data, JiangxiRiverItem) @staticmeth...
0827cg/cgspiders
db/mapping/jiangxi_river/jiangxi_river.py
jiangxi_river.py
py
744
python
en
code
0
github-code
1
16625738937
""" GLPointCloudPlotItem.py - extension of pyqtgraph for plotting pointclouds This file implements an extension of pyqtgraph for visualizing PointClouds. Last update: 04/10/2013, Tadewos Somano(tadewos85@gmail.com) """ from OpenGL.GL import * from pyqtgraph.opengl.GLGraphicsItem import GLGraphicsItem __all__ =...
GeoDTN/Communication-Technologies-Multimedia
GLPointCloudPlotItem.py
GLPointCloudPlotItem.py
py
2,544
python
en
code
0
github-code
1
7426054522
f=open('two_cities_ascii.txt','r') lines=f.read() f.close() #convert words to binary form of length 7 import math def toBinary (a): k,n=[],[] for i in a : k.append(ord(i)) for i in k: n.append(int(bin(i)[2:])) return n binary=toBinary(lines) binarystr = [str(x) for x in bina...
glykeriak/ex35710
erg10.py
erg10.py
py
1,212
python
en
code
0
github-code
1
31589162522
import itertools from osgeo import ogr,osr import shapely.geometry # Convert Shapely type to OGR type shapely_to_ogr_type = { shapely.geometry.linestring.LineString: ogr.wkbLineString, shapely.geometry.polygon.Polygon: ogr.wkbPolygon, } def to_datasource(shape): """Converts an in-memory Shapely object t...
pism/uafgi
uafgi/util/shapelyutil.py
shapelyutil.py
py
1,095
python
en
code
1
github-code
1
2248926257
from cmp.automata import State from cmp.utils import Token from cmp.tools.my_regex import regex_automaton class Lexer: def __init__(self, table, eof): self.eof = eof self.regexs = self._build_regexs(table) self.automaton = self._build_automaton() def _build_regexs(self, table): ...
mavaldivie/Grammar-Analyser
Grammar Analyzer MIO/cmp/tools/Lexer.py
Lexer.py
py
2,324
python
en
code
3
github-code
1
15218879692
def calculate_frequencies(file_contents): # Here is a list of punctuations and uninteresting words you can use to process your text punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' uninteresting_words = ["the", "a", "to", "if", "is", "it", "of", "and", "or", "an", "as", "i", "me", "my", \ "we", "our", ...
noodels12/noodels12
final.py
final.py
py
1,368
python
en
code
0
github-code
1
18042327734
# -*- coding: utf-8 -*- from django import forms from ..models import Programacao class ProgramacaoForm(forms.ModelForm): class Meta: model = Programacao fields = ( 'programa', 'data_inicio', 'data_fim' ) def clean(self): cleaned_data = super(ProgramacaoForm, self...
rbiassusi/grade_programacao
grade_programacao/radio/forms/programacaoform.py
programacaoform.py
py
549
python
pt
code
0
github-code
1
17166477183
# -*- coding: utf-8 -*- """ Created on Thu Jun 3 15:50:28 2021 @author: mozhenling """ import copy import numpy as np import scipy.io as scio import matplotlib.pyplot as plt from dbtpy.filters.afilter import filter_fun from dbtpy.findexes.afindex import findex_fun from dbtpy.findexes.sigto import sig_real_to_env #--...
mozhenling/dbtree
dbtpy/funs/fun_diag.py
fun_diag.py
py
18,106
python
en
code
4
github-code
1
30500879987
from naulang.compiler.context import FunctionCompilerContext from naulang.compiler import ast from naulang.compiler.error import CompilerException from naulang.interpreter.bytecode import Bytecode from naulang.interpreter.objectspace.primitives.builtin_definitions import builtin_functions _builtin_functions = builtin...
samgiles/naulang
naulang/compiler/translator.py
translator.py
py
13,563
python
en
code
9
github-code
1
37714246796
from building import * Import('rtconfig') src = [] cwd = GetCurrentDir() # add mb85rs16 src files. if GetDepend('PKG_USING_MB85RS16'): src += Glob('src/mb85rs16.c') if GetDepend('PKG_USING_MB85RS16_SAMPLE'): src += Glob('examples/mb85rs16_sample.c') # add mb85rs16 include path. path = [cwd + '/inc'] # a...
XiaojieFan/mb85rs16
SConscript
SConscript
454
python
en
code
3
github-code
1
185545694
import pickle import struct from pathlib import Path from interact import interact as io from utils import Path_utils import samplelib.SampleHost from samplelib import Sample packed_faceset_filename = 'faceset.pak' class PackedFaceset(): VERSION = 1 @staticmethod def pack(samples_path): sample...
jem0101/BigSwag-SQA2022-AUBURN
TestOrchestrator4ML-main/resources/Data/supervised/GITLAB_REPOS/bytehackr@DeepFaceLab/samplelib/PackedFaceset.py
PackedFaceset.py
py
3,627
python
en
code
2
github-code
1
31379366652
from bs4 import BeautifulSoup as bs import csv import requests URL = 'https://kaktus.media/?lable=8&date=2022-10-15&order=time' dict_with_news = {} def get_html(url): response = requests.get(url) return response.text def get_soup(html): soup = bs(html, 'lxml') return soup def get_list_news(): ...
31nkmu/hackathon_bot_kaktus_media
parsing.py
parsing.py
py
1,183
python
en
code
1
github-code
1
24557090775
# Server Side # import socket import threading # 접속 정보 host = "127.0.0.1" port = 5000 # 서버 시작 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((host,port)) server.listen() # 여러 사용자의 접속 허용 clients = [] nicknames = [] # 접속중인 모든 사용자에게 메세지 전달 def broadcast(msg): for client in clients: ...
soli1101/python_workspace
d20200805/network09.py
network09.py
py
2,111
python
ko
code
0
github-code
1
26661499475
# -*- coding: utf-8 -*- from scrapy import Spider, Request, FormRequest from MobaiSpider.items import MobaispiderItem import numpy as np import json import time class MobaiSpider(Spider): name = 'mobai' # allowed_domains = ['mobike.com'] # start_urls = ['http://mobike.com/'] url = "https://mwx.mobike....
jllan/spiders_mess
MobaiSpider/MobaiSpider/spiders/mobai.py
mobai.py
py
2,846
python
en
code
0
github-code
1
72361933154
import numpy as np import pandas as pd import seaborn as sns from matplotlib import pyplot as plt def barplotter(df, ax, period='Q'): subdf = df[['time','predicted_sentiment']] subdf['y1'] = subdf['predicted_sentiment'].replace({-1:0}) subdf['y2'] = subdf['predicted_sentiment'].replace({1:0,-1:1}) subd...
kylejcaron/Text_Summarization
Dashboard/static/src/util.py
util.py
py
1,993
python
en
code
0
github-code
1
43687469628
# -*- coding: utf-8 -*- import os,sys,inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0,parentdir) from PyQt4 import QtGui from PyQt4 import QtCore import os import modules.filter as tableWidgetFilters import modules....
Doberm4n/POEStashJsonViewer
ui/main_layout.py
main_layout.py
py
8,943
python
en
code
0
github-code
1
10361363697
import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator ## 1d example # camera is at origin and looks right # objects have position, importance, transparency ## Formulas # extinction \mu(x) = \alpha_x # optical_depth \tau(d_i) = \sum_j^i - \ln(1-\alpha...
BETuncay/demo-doo
example1d.py
example1d.py
py
6,164
python
en
code
0
github-code
1
40010406506
def minRemoveToMakeValid(s: str) -> str: s = list(s) stack = [] for i in range(len(s)): if s[i] == '(': stack.append(i) elif s[i] == ')': if stack: stack.pop() else: s[i] = ''...
wyy1234567/leetcode_problems
string.py
string.py
py
10,276
python
en
code
0
github-code
1
24383408411
"""Script to gather IMDB keywords from 2013's top grossing movies.""" import sys from os import path import time from business_logic.compare_prices import ComparePrices import logging from business_logic.logic import Logic logger = logging.getLogger('ftpuploader') hdlr = logging.FileHandler('ftplog.log') formatter = lo...
life-of-pi-thon/crypto_carluccio
lukrative.py
lukrative.py
py
1,077
python
en
code
0
github-code
1
32437306078
# Continuous cart pole using policy gradients (PG) # Running this script does the trick! import gym import numpy as np from gym import wrappers # env = gym.make('InvertedPendulum-v1') env = gym.make('Pendulum-v0') # env = wrappers.Monitor(env, '/home/sid/ccp_pg', force=True) def simulate(policy, steps, graphics=Fal...
geyang/reinforcement_learning_learning_notes
gym-sessions/ge-baselines/simple_vpg.py
simple_vpg.py
py
3,296
python
en
code
3
github-code
1
30327998982
from time import sleep print('') print('-='*18) print('''Olá Seja Bem-Vindo ao código do Brayan''') print('-='*18) print('{:^35}'.format('Maior Que Menor Que')) print('') sleep(2) maior = 0 menor = 0 for c in range(1, 4): n = int(input('Digite o {}º número: '.format(c))) if c == 1: maior = n ...
BigBraim/exercicio-28-08
MaiorQueMenorQue.py
MaiorQueMenorQue.py
py
540
python
pt
code
0
github-code
1
2749664456
#!/usr/bin/env python import sys import ast last_pair = None cnt = 0 for line in sys.stdin: line = line.strip() pair1, sim, pair2, followee_list = line.split('\t') followee_list = ast.literal_eval(followee_list) if pair1 == last_pair: if cnt < 3: if pair1[-3:] =="531": ...
guswns00123/Community-Detection-in-SNS
topk.py
topk.py
py
848
python
en
code
0
github-code
1
27272075496
# 실버 5 # 7785. 회사에 있는 사람 import sys input = sys.stdin.readline dic = {} for _ in range(int(input())): s = input().split() dic[s[0]] = s[1] for k in sorted(dic.keys(), reverse=True): if dic[k] == 'enter': print(k)
honggom/TIL
problem-solving/baekjoon/hash/7785.py
7785.py
py
253
python
ko
code
0
github-code
1
1747709397
import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import plotly.graph_objs as go import numpy as np # input N=100 returns_input = np.array([0.04,0.06]) volas_input = np.array([0.06,0.10]) corr_input=0 def covariance(corr_c...
investeer-io/markowitz_bokeh
dashEfficientFrontierSlider.py
dashEfficientFrontierSlider.py
py
2,474
python
en
code
0
github-code
1
1101552482
import torch import torch.optim as optim from torch.autograd import Variable from torchvision import datasets, transforms import os import matplotlib.pyplot as plt from autoencoder import Autoencoder from gmmn import * from constants import * if not os.path.exists(root): os.mkdir(root) if not os.path.exists(mod...
Abhipanda4/GMMN-Pytorch
train.py
train.py
py
3,369
python
en
code
13
github-code
1
1911298880
import pandas as pd import numpy as np df = pd.read_csv('H:\GiantFrame.csv', error_bad_lines=False) x = df['vtti.left_marker_probability'] x = list(x.values) bins = [0, 1, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1024] hist, bins = np.histogram(x, bins=bins)
cschwarz68/DROW
utilities/OneSecondProbabilityHisto.py
OneSecondProbabilityHisto.py
py
266
python
en
code
0
github-code
1
1040586228
def factorial_recursive(n): if n==0 or n==1: return 1 else: return n * factorial_recursive(n-1) def factorial_iterative(n): fac = 1 for i in range(n): fac = fac * (i+1) return fac def fibonacci(n): if n==1: return 0 elif n==2: return 1 else: ...
salman-naheed/python
programs/factorial-fibonacci.py
factorial-fibonacci.py
py
615
python
en
code
0
github-code
1
5227372260
# 移动止盈止损策略 赢损比自定义 默认1.5:1 import pymysql as sql import pandas as pd import requests as req db = sql.connect(host="localhost", user="root", password="74110", database="quant-trade", port=3307, autocommit=True) sina_url = 'http://hq.sinajs.cn/list=' # 获取新浪财经的指定股票实时数据返回dateframe类型 #参考链接 https://www.jia...
ZHAOHUHU/quant-trade
com/quant/trade/zhao/tralling_stop.py
tralling_stop.py
py
1,024
python
en
code
0
github-code
1
21313047711
from sys import stdin import sys class treeNode: def __init__(self, data): self.data = data self.children = [] def __str__(self): return str(self.data) #main sys.setrecursionlimit(10**6) ## Read input as specified in the question. ## Print output as specified in the questi...
piyushkashyap07/Generic-Tree
height.py
height.py
py
1,109
python
en
code
0
github-code
1
29598602871
import numpy as np import keras # from keras.models import Sequential from keras.models import * from keras.layers import * import random from sklearn.model_selection import train_test_split #this one will be used for normalization and standardization from sklearn import preprocessing import scipy.io as sio # We us...
ell-hol/mpc-DL-controller
simulate_DL_controller.py
simulate_DL_controller.py
py
16,307
python
en
code
61
github-code
1
29062292111
from question_model import Question from data import question_data from quiz_brain import QuizBrain question_bank = [] for question in question_data: question_bank.append(Question(question["text"], question["answer"])) brain = QuizBrain(question_bank) while brain.stillHasQuestions(): brain.next_question() ...
miklealex/PythonProjects
TrueFalseQuiz/main.py
main.py
py
429
python
en
code
0
github-code
1
24402276077
import os import numpy as np import pandas as pd from catboost import CatBoost, Pool import matplotlib.pylab as plt from model import Model from util import Util class ModelCatBoost(Model): def train(self, tr_x, tr_y, va_x=None, va_y=None): # ハイパーパラメータの設定 params = dict(self.params) cat_...
riron1206/lgb_tuning
src/model_catboost.py
model_catboost.py
py
2,770
python
ja
code
0
github-code
1
15238963233
import json import pickle def getNumToTagsMap(): with open("./metadata/all_tags.cls") as fi: taglist = map(lambda x: x[:-1], fi.readlines()) with open("./metadata/mappings.json") as fi: mapping = json.loads(fi.read()) finalTag = list(map(lambda x: mapping[x], taglist)) return finalTa...
kyuyeonpooh/objects-that-sound
utils/util.py
util.py
py
1,765
python
en
code
31
github-code
1
27172359979
from django import forms from .models import Tag, Post from django.core.exceptions import ValidationError class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'slug', 'body', 'tags'] widgets = { 'title': forms.TextInput(attrs={'class': 'form-con...
HolidayMan/pinkerblog
blog/engine/forms.py
forms.py
py
2,745
python
en
code
0
github-code
1
7409145188
import pandas as pd import numpy as np import loaders as ld import analytics as an def cooc(opens,closes,costs=0.0001,cutoff=1,strength=10000,prec=2,ret=0,sw=0,inv=0): k = opens.shape[1]-opens.isnull().sum(axis=1) CO_ret = np.log(opens/closes.shift(1)) OC_ret = closes/opens-1 #OO_ret = np.log(opens/ope...
mlabedzki/Fortuna
strategies.py
strategies.py
py
6,008
python
en
code
0
github-code
1
916042016
from urllib import request from urllib import parse import json requestUrl = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule" # http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule # 去掉_o Form_data = {} Form_data["i"] = 'Hello' Form_data["from"] = "...
NotMyYida/AndroidBookNote
pycharmWS/webcrawler/JackCui_2.py
JackCui_2.py
py
844
python
en
code
0
github-code
1
22039745744
query_variables = { "wallet": "tz1NqA15BLrMFZNsGWBwrq8XkcXfGyCpapU1", "timestart": "2021-07-01", "timeend": "2022-06-30" } buys_start = "2019-01-01" currency = "AUD" import json import os import datetime import csv import requests # Prepare conversion rates # Using the RBA exchange rates spreadsheet cleaned up...
mattebb/tezos-nft-tax-report
report.py
report.py
py
8,757
python
en
code
2
github-code
1
70766232034
from stable_baselines3 import A2C from algos.PlaNet.planet import PlaNet from algos.PlaNet.policies import DiscreteMPCPlanner from algos.PlaNet.world_model import DreamerModel import os from buffers.chunk_buffer import ChunkReplayBuffer from buffers.introspective_buffer import IntrospectiveChunkReplayBuffer from algos...
GittiHab/mbrl-thesis-code
algos/setup.py
setup.py
py
3,496
python
en
code
1
github-code
1
15278137621
# Hashmap + list from collections import Counter class FindSumPairs: def __init__(self, nums1, nums2): self.n1, self.n2 = Counter(nums1), Counter(nums2) self.n = [i for i in nums2] def add(self, index: int, val: int) -> None: self.n2[self.n[index]] -= 1 # Remove the element from the ...
onyxolu/DSA
Bloomberg/Top 100/FindingPairsWithACertainSum.py
FindingPairsWithACertainSum.py
py
827
python
en
code
0
github-code
1
16556960935
# https://www.acmicpc.net/problem/10820 # Solving Date: 20.03.28. # strip()은 공백도 지우기 때문에 명시적으로 '\n'만 지우도록 만든다. # sys.stdin.readline은 input과 다르게 EOF가 입력되면 빈 string으로 인지한다. # 이는 sys.stdin이 file과 유사한 객체라고 한다. # https://cnpnote.tistory.com/에서 [PYTHON]-결말이없는-파이프에서-어떻게-파이썬으로-stdin을-읽는가?를 참고한다. import sys def string_count(...
imn00133/algorithm
BaekJoonOnlineJudge/CodePlus/200DataStructure/Appendix/baekjoon_10820.py
baekjoon_10820.py
py
1,510
python
ko
code
0
github-code
1
70335860194
class Node(): def __init__(self, data): self.data = data self.next = None self.prev = None class DoublyLinkedList(): def __init__(self): self.head = None self.tail = None self.size = 0 def insert_from_head(self,data): new_node = Node(dat...
JayashBhandary/DS
doublell.py
doublell.py
py
2,784
python
en
code
0
github-code
1
39496586821
from sys import stdin def dfs(x,y,n,m,maps): if x == n-1 and y == m-1: return 1 else: if dp[y][x] == -1: dp[y][x] = 0 for ni,nj in [[0,1],[1,0],[0,-1],[-1,0]]: dx = x + ni dy = y + nj ...
yundaehyuck/Python_Algorithm_Note
problem_code/dynamic_programming/1520.py
1520.py
py
758
python
en
code
0
github-code
1
38933917008
#!/usr/bin/env python # encoding: utf-8   """  @author: zzz_jq @contact: zhuangjq@stu.xmu.edu.cn @software: PyCharm  @file: data_process.py  @create: 2020/11/30 16:06  """ import re import os from pathlib import Path from tqdm import tqdm import numpy as np import pandas as pd from sklearn.feature_extraction.text imp...
TsinghuaDatabaseGroup/AI4DBCode
Spark-Tuning/prediction_ml/spark_tuning/by_stage/ml_baselines/data_process_one_line.py
data_process_one_line.py
py
3,683
python
en
code
56
github-code
1
11665650445
from __future__ import print_function '''Procedure''' a = 3 # 1-5 N/A '''Part 1: Conditionals''' # 6a Prediction assert((a**2 >= 9 and not a>3) == True) # 6b Prediction assert((a+2 == 5 or a-1 != 3) == True) # 7 Condition x, y = (90, 115) assert(40 < x and x < 130 and 100 <= y and y <= 120) '''Part 2: if-else S...
kabir-shah/cloud9-python
1.3.3/Shah_1.3.3.py
Shah_1.3.3.py
py
3,550
python
en
code
0
github-code
1
22652070617
# # Author: Tim Burns # License: Apache 2.0 # # A Testing Class to Validate Scraping the KEXP Playlist for the blog # https://www.owlmountain.net/ # If you like this, donate to KEXP: https://www.kexp.org/donate/ import unittest import os import fnmatch import reporting.layers.awslayer import spark_catalog class Spar...
timowlmtn/bigdataplatforms
src/kexp/pytest/test_kexp_1_api_raw_to_bronze_playlist.py
test_kexp_1_api_raw_to_bronze_playlist.py
py
1,965
python
en
code
3
github-code
1
37413122640
import torch import torch.nn as nn import torch.nn.functional as F from model.octconv import * import model.venconv as venconv from model.median_pooling import median_pool_2d class SNRom(nn.Module): def __init__(self, in_channels=1, hide_channels=64, out_channels=1, kernel_size=3, alpha_in=0.5, ...
StephenYang190/SpeckleNoisePytorch
model/SNRom.py
SNRom.py
py
4,128
python
en
code
0
github-code
1
74407308832
from fastapi import Depends, FastAPI app = FastAPI() """ # Dependency injection: a function that abstracts logic and can be provided to # other functions as dependency. Whenever a new request arrives to a function that includes a dependency, fastAPI runs the dependency function with the corresponding parameters, an...
jcaguirre89/learning-fastapi
another_app/dependency.py
dependency.py
py
1,980
python
en
code
0
github-code
1
70107487715
from django.urls import path from . import views urlpatterns = [ path('list_plants/', views.all_plants, name='list_plants'), path('add_plant/', views.add_plant, name='add_plant'), path('edit_plant/<int:plant_id>/', views.edit_plant, name='edit_plant'), path('plant_detail/<int:location_id>/<int:pk>/...
Stephen-J-Whitaker/wild-carbon
plants/urls.py
urls.py
py
1,029
python
en
code
0
github-code
1
27651236552
''' This code is based on https://github.com/ekwebb/fNRI which in turn is based on https://github.com/ethanfetaya/NRI (MIT licence) ''' from synthetic_sim_comperrors import * import time import numpy as np import argparse import os from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt parser = argpar...
vassilis-karavias/fNRIsigma-master
data/generate_dataset_comperrors.py
generate_dataset_comperrors.py
py
5,643
python
en
code
2
github-code
1
569319840
from rest_framework import serializers # from departamentos.api.serializers import DepartamentoSerializer # from municipios.api.serializers import MunicipioSerializer from usuarios.models import Usuario class UsuarioSerializer(serializers.ModelSerializer): # municipio = MunicipioSerializer() # departamento =...
OscarRuiz15/BackendTG
usuarios/api/serializers.py
serializers.py
py
727
python
es
code
0
github-code
1
15850354420
import pandas as pd from typing import Union, List, Optional, Tuple from bokeh.io import output_notebook from bokeh.resources import INLINE from bokeh.plotting import figure, gridplot from bokeh.plotting import show as _show from pandas.api.types import is_string_dtype from bokeh.palettes import Set1 output_notebook(I...
idiotekk/unknownlib
lib/unknownlib/plt/bk.py
bk.py
py
2,990
python
en
code
0
github-code
1
24154817598
#!/usr/bin/env python ''' Mizoo rename all your photos with a description of what is in them. It uses Microsoft Computer Vision API's to describe what it sees on the image and rename the file to that description. By naming your photos with a description of the content you will never have to dig up an old photo from y...
albertoqa/mizoo
mizoo/mizoo.py
mizoo.py
py
3,866
python
en
code
1
github-code
1
39278591910
import cv2 import numpy as np import imutils PATH_TEMPLATE_MSLOGO = r"C:\Users\ASUS\Desktop\Working\PROJECT\Mybotic Product\mySejahtera Scan\images\template images\mslogo.png" PATH_TEMPLATE_TICKMARK = r"C:\Users\ASUS\Desktop\Working\PROJECT\Mybotic Product\mySejahtera Scan\images\template images\tickmark.png" SIMILAR...
Awexander/mySejahtera-scanner
mysejahtera_scan_v1.py
mysejahtera_scan_v1.py
py
3,056
python
en
code
0
github-code
1
16673975835
class Trie: def __init__(self): self.children = [None] * 26 self.w = '' def insert(self, w): node = self for c in w: idx = ord(c) - ord('a') if node.children[idx] is None: node.children[idx] = Trie() node = node.children[idx] ...
QinHongZhe/hongzhe-leetcode
solution/0200-0299/0212.Word Search II/Solution.py
Solution.py
py
1,207
python
en
code
1
github-code
1
72185345314
QUANT_MASK = 0xf SEG_SHIFT = 4 seg_aend = [ 0x1F, 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF ] def find_aend(data, size=8): for i in range(size): if data <= seg_aend[i]: return i return size def linear_to_alaw(data): data = data >> 3 ...
alecwu44743/r-dap_pre-exam
testing_lab/convert.py
convert.py
py
935
python
en
code
0
github-code
1
27981377485
import requests import json import numpy as np import time import pandas as pd from pymysql import connect import csv from custom_send_email import sendEmail # 获取订单簿数据 class GetData(object): ''' 获取对应api bitmax数据,计算固定比例的数据,监控变化,发送邮件 ''' def __init__(self,url): self.url = url # self.da...
jackendoff/bilian_bitmax_data
BITMAX_jackendoff.py
BITMAX_jackendoff.py
py
10,355
python
en
code
1
github-code
1
17219238836
n = int(input()) input_str = input() rows = [input_str[n*i:n*(i+1)] for i in range(n)] # "IXIXX", "XXCXA", "XSXXP", ... goal = "ICPCASIASG" moves = ((1,2), (2, 1), (-1,2), (-2, 1), (1,-2), (2, -1), (-1,-2), (-2, -1)) def isvalid(x,y): return 0 <= x < n and 0 <= y < n def dfs(x,y, index_in_goal): if index_in_goal ...
MatthewFreestone/Kattis
knightsearch/knightsearch.py
knightsearch.py
py
649
python
en
code
0
github-code
1
36030957599
#Zadání cvičení: Využijte příklady z výkladu. Upravte je tak, aby #- se program zeptal uživatele i na věk, a ověřil, že má alespoň 13 let. Pokud nemá alespoň 13 let, nezeptá se už na počet lístků a skončí (tj. nákup neproběhne). #-bonus pro netrpělivé :slightly_smiling_face: viz výše + místo slevy 10% uplatní akci "při...
FSebestova/python-kurz-2023
procviceni1.py
procviceni1.py
py
877
python
cs
code
0
github-code
1
73320662115
import struct import numpy as np # Convert Blender identifiers to Photoshop ones dict_color_mode = {'BW': 1, 'RGB': 3, 'RGBA': 3} dict_blend_mode = {'REGULAR': b'norm', 'HARDLIGHT': b'hLit', 'ADD': b'lite', 'SUBTRACT': b'fsub', 'MULTIPLY': b'm...
chsh2/nijiGPen
file_formats.py
file_formats.py
py
14,262
python
en
code
157
github-code
1
19586982312
import os, pathlib from pydo import * this_dir = pathlib.Path(__file__).parent try: from . import config except ImportError: log.error('Error: Project is not configured.') exit(-1) try: jobs = int(os.environ['PYDOJOBS'], 10) except Exception: import multiprocessing jobs = multiprocessing.cpu...
ali1234/rpi-ramdisk
__init__.py
__init__.py
py
1,348
python
en
code
79
github-code
1
25561714496
""" File: algorithms.py Project 10.10 Updates to profile heap sort. The heap now needs a reference to the profiler so it can record comparisons and exchanges. Algorithms configured for profiling. """ from profiler import Profiler from arrayheap import ArrayHeap def heapSort(lyst, profiler): heap = ArrayHeap(...
hieugomeister/ASU
CST100/Chapter_10/Chapter_10/Ch_10_Solutions/Ch_10_Projects/10.10/algorithms.py
algorithms.py
py
447
python
en
code
0
github-code
1
8707312288
#---------------------------------------------------------------------- # Package Management #---------------------------------------------------------------------- import os import os.path as op import textwrap import argparse import pandas as pd import re import zipfile from tqdm import tqdm, trange import hashlib ...
muscbridge/comprssr
comprssr.py
comprssr.py
py
7,544
python
en
code
0
github-code
1
43751970541
#!/usr/bin/env python3 """ Scraper for the 'The Flavor Bible'. Created by Jon. """ import json import os import re import sqlite3 import sys import ebooklib from ebooklib import epub from bs4 import BeautifulSoup latest_id = 0 def createTables(c): c.execute('''CREATE TABLE ingredients( id int...
tristanchu/FlavorFinder
dev/scraper.py
scraper.py
py
11,938
python
en
code
2
github-code
1
9293506322
#this model aim to reduce number of rounds but will continue to use random method import random from datetime import datetime start_time = datetime.now() final_state = [1,2,3,4,5,6,7,8] initial_state = [0,0,0,0,0,0,0,0] #random initail state with different position of number while 0 in initial_state: rand = rand...
Tanisa124/AI-Practice
heuristic_lessRound.py
heuristic_lessRound.py
py
2,058
python
en
code
0
github-code
1
31223430043
'''______________________________________________________________________________________________________ Crie um pg que simule o funcionamento de um caixa eletrônico. no início pergunte ao usuário qual o valor a ser sacado e o pg vai informar quantas cédulas de cada valor serão entregues. Obs.: cedulas de 1, 10, 20 e ...
FrancisPaull/CursoemvideoPython
exercicios/ex071 interropendo rep while caixa eletronico.py
ex071 interropendo rep while caixa eletronico.py
py
1,314
python
pt
code
0
github-code
1
41495665790
import torch import torch.nn as nn class MASRModel(nn.Module): def __init__(self, **config): super().__init__() self.config = config @classmethod def load(cls, path): package = torch.load(path) state_dict = package["state_dict"] config = package["config"] m...
nobody132/masr
models/base.py
base.py
py
1,176
python
en
code
1,754
github-code
1
35465861402
import itertools import torch.nn as nn import decoder import encoder import modules from utils import MergeDict class Model(nn.Module): def __init__(self, sample_rate, vocab_size): super().__init__() self.spectra = modules.Spectrogram(sample_rate) # self.encoder = encoder.Conv2dRNNEnco...
vshmyhlo/listen-attend-and-speell-pytorch
model.py
model.py
py
2,131
python
en
code
11
github-code
1
6648609464
import logging import math import numpy as np import util.annotation import util.metadata_service import util.provenance_metadata_store from util.annotation import AnnotationStore from engine import app from ooi_data.postgres.model import Parameter, Stream, NominalDepth from util.asset_management import AssetManagemen...
oceanobservatories/stream_engine
util/stream_request.py
stream_request.py
py
36,193
python
en
code
1
github-code
1
16239780344
import os import sys import PIL import time import random import logging import datetime import os.path as osp import torch import torch.backends import torch.nn as nn import torch.backends.cudnn import torch.distributed as dist from utils.loss import OhemCELoss from utils.utils import prepare_seed from utils.utils i...
NoamRosenberg/autodeeplab
train_distributed.py
train_distributed.py
py
8,976
python
en
code
306
github-code
1
30296294545
import serial import sys import time def out_gpio(value): f_val = open('/sys/class/gpio/gpio18/value', 'w') f_val.write(value) f_val.close() # первый байт req - ожидаемая длина ответа def make_request(req): out_gpio('1') port.write(req[1:]) time.sleep(0.004) out_gpio('0') while(port.inWaiting() == 0): time....
almarkov/quest
test.py
test.py
py
651
python
ru
code
0
github-code
1
18455156740
#import libraries from sklearn.model_selection import train_test_split import numpy as np from imblearn.over_sampling import SMOTE from svm_constructdata import constructdata from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import RandomizedSearchCV #generate data features,labels = cons...
kksuresh25/Cancer-AI
Random Forest/rf_tunehyperparameters.py
rf_tunehyperparameters.py
py
2,420
python
en
code
1
github-code
1
14621398412
import os import tornado.web from .Util import * from .Core import * class IndexHandler(tornado.web.RequestHandler): def get(self): self.render("index.html", people="skipper") class LogIndexHandler(tornado.web.RequestHandler): def get(self): self.render("log/log_index.html") class LogList...
daddvted/arch1ve
python_code/log2chart_tornado/engine/Handler.py
Handler.py
py
3,264
python
en
code
0
github-code
1
39002643737
import sqlite3 DbName = "./db/timing_plan.db" class Cdb: def __init__(self,dbName): self.dbName = dbName #数据库名称 self.conn = None #文件与数据库的连接 self.cursor = None #文件与数据库的交互 self.__connect() def __connect(self): #将数据库与文件连接 try: self.conn = sqlite...
lx-dtbs/UI-base
sumo_liveUpdate_ui/DbBase.py
DbBase.py
py
2,777
python
en
code
1
github-code
1
19767607746
"""CSV操作 aws cliの初期設定 aws configure 設定の確認 ~/.aws/ boto3 Client APIとResource API Client API・・・リソースを操作する場合も参照系と同様に、対象のリソースIDを引数に加えてメソッドを実行する。 ex) s3 = boto3.client('s3') # バケット一覧を取得 s3.list_buckets() obj = client.get_object(Bucket='test_bucket', Key='test.text') print(obj['body'].read()) Resource API・・・リソースを操作する場合には対象の...
yoshikikasama/data_analytics
coding/boto3/tutorials/csv_from_s3.py
csv_from_s3.py
py
6,116
python
ja
code
0
github-code
1