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
25271283090
import numpy as np import os import wrapp_mct_photon_propagation as mctw import subprocess as sp import tempfile import json import matplotlib.pyplot as plt import matplotlib.colors as colors import plenopy as pl out_dir = os.path.join('examples', 'small_camera_lens_psf') os.makedirs(out_dir, exist_ok=True) # scener...
cherenkov-plenoscope/starter_kit
obsolete_examples/small_camera_lens_psf.py
small_camera_lens_psf.py
py
9,318
python
en
code
0
github-code
1
74718384033
import datetime import queue import logging import signal import time import threading import tkinter as tk from tkinter.scrolledtext import ScrolledText from tkinter import ttk, VERTICAL, HORIZONTAL, N, S, E, W logger = logging.getLogger(__name__) class Clock(threading.Thread): """Class to display the time eve...
beenje/tkinter-logging-text-widget
main.py
main.py
py
6,751
python
en
code
52
github-code
1
73248145635
import tensorflow as tf from tensorflow.python.framework import ops from tensorflow.python.ops import variable_scope as vs from tensorflow.contrib.cudnn_rnn.python.ops.cudnn_rnn_ops import CudnnRNNTanh from tensorflow.contrib.cudnn_rnn import CudnnRNNRelu import numpy as np from basic_op import map_fn_concat fro...
jzbjyb/rri_match
represent.py
represent.py
py
30,123
python
en
code
0
github-code
1
72264217634
#!/usr/bin/env python3 import re import signal import time from TestHarness import Cluster, TestHelper, Utils, WalletMgr ############################################################### # nodeos_read_terminate_at_block_test # # A few tests centered around read mode of irreversible, # and head with terminate-at-block ...
AntelopeIO/leap
tests/nodeos_read_terminate_at_block_test.py
nodeos_read_terminate_at_block_test.py
py
6,906
python
en
code
104
github-code
1
5269804326
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^$question_one/$', views.question_one, name='question_one'), url(r'^question_two/$',views.question_two, name='question_two'), url(r'^question_three/$', views.question_three, name = 'question_three'), ...
blondiebytes/Learn-It-Girl-Project
TravelMetrics/mysite/travelmetrics/urls.py
urls.py
py
321
python
en
code
2
github-code
1
37470543469
import random import os # Step 1: Prepare the data states = { 'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix', 'Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver', 'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee', 'Georgia': 'Atlanta', '...
Amisha-Ananda-Gowda/Python-Programs
case_study/quiz.py
quiz.py
py
2,943
python
en
code
0
github-code
1
19120450138
from sys import maxsize import copy from Helpers import find_best_move from BoardScanner import BoardScanner class MiniMax(BoardScanner): def __init__(self): super().__init__() """ The mini_max method iterates over all possible next moves of given TicTacToe board state, and evaluates the sta...
p4vl3n/TicTacToe
TicTac/MiniMax.py
MiniMax.py
py
2,395
python
en
code
0
github-code
1
41350841577
import math a = float(input("Enter multiplicand\n")) if a < 16: b = float(input("Enter multiplier\n")) else: print("Must be a 4-bit binary number\n") if b < 16: sum = 0 print(sum) count = 0 while True: if count == b: break else: count = cou...
Idaben/python-projects
binary-multiplier.py
binary-multiplier.py
py
455
python
en
code
0
github-code
1
1421544026
from .data import DataSet, Options, enums """ Example usage. """ if __name__ == '__main__': # load data: data = DataSet.Dataset("/path/to/data") #visualize with plt data.subfolders[0].datapoints[0].visualize() #save to location data.subfolders[0].datapoints[0].save("/home/path/to/save/to", "f...
JustusDroege/grasp_dataset_convenience_pack
main.py
main.py
py
931
python
en
code
4
github-code
1
21367676238
""" Compatibility shim to support Proton versions lower than 4.11-2 """ #pylint: disable=R0903,R1705 import os from .protonversion import semver_cmp, PROTON_VERSION OLD_PROTON = "4.11-1" PROTON_MAP = {'base_dir': 'basedir', 'bin_dir': 'bindir', 'lib_dir': 'libdir', 'lib64_d...
simons-public/protonfixes
protonfixes/protonmain_compat.py
protonmain_compat.py
py
1,915
python
en
code
226
github-code
1
11564982759
''' Faça um programa que leia o arquivo alice.txt e conte o número de ocorrências de cada palavra no texto. Obs.: para saber os caracteres especiais use import string e utilize string.punctuation ''' ''' Como tentei fazer.... Até contou direito, mas fudeu no lance de retirar as pontuações import string with open ('a...
MarcosOshiro/python-para-zumbis
TWP345_Word_Count_with_Dictionaries.py
TWP345_Word_Count_with_Dictionaries.py
py
1,060
python
pt
code
6
github-code
1
12037898208
from flask import jsonify from sqlalchemy.exc import IntegrityError from actor_libs.database.orm import db from actor_libs.errors import ReferencedError from actor_libs.utils import get_delete_ids from app import auth from app.models import Device, Group, GroupDevice, User, EndDevice, Gateway from app.schemas import G...
actorcloud/ActorCloud
server/app/services/devices/views/groups.py
groups.py
py
3,749
python
en
code
181
github-code
1
1782776232
import sympy import random def gcd(a, b): # greatest common divisor if b == 0: return a else: return gcd(b, a % b) def euler_func(n): # Euler's totient function count = 0 for number in range(n): if gcd(number, n) == 1: count += 1 return count def check(roo...
Timofey21/cryptography
Elgamal.py
Elgamal.py
py
1,436
python
en
code
0
github-code
1
2325246930
import os import shutil from flask import request, jsonify from flask_restful import Resource from flask_uploads import UploadNotAllowed from db import db from libs import image_helper from models.category import CategoryModel from models.subcategory import SubCategoryModel from models.provider import ProviderModel, ...
Emir99/city-service
resources/provider.py
provider.py
py
9,338
python
en
code
0
github-code
1
2549773164
#!/usr/bin/env python3 import torch import horovod.torch as hvd torch.backends.cudnn.benchmark=True # Initialize Horovod hvd.init() # Pin GPU to be used to process local rank (one GPU per process) torch.cuda.set_device(hvd.local_rank()) import argparse import sys import torch import logging import time import math i...
Yidi299/yy_moco
val_fc.py
val_fc.py
py
3,706
python
en
code
0
github-code
1
15620722484
def main(): """ ################################################## Complete your code here Use m_perc and f_perc for your results ################################################## """ male = int(input('Number males: ')) female = int(input('Number female: ')) total = male + female ...
DVC-COMSC/assignment-2-1-sanjanaj2
main.py
main.py
py
822
python
en
code
0
github-code
1
44611086686
import sys from ROOT import TFile, TH1F, TIter # Open the ROOT file root_file = TFile.Open(sys.argv[1]) # Get the list of keys in the top-level directory key_list = root_file.GetListOfKeys() # Loop over the keys for key in TIter(key_list): obj = key.ReadObj() if isinstance(obj, TH1F): name = obj.GetN...
alkaloge/METPaperRun2
Paper/MET/seeFile.py
seeFile.py
py
625
python
en
code
0
github-code
1
19514666953
import tensorflow as tf from tensorflow.keras.models import Model from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D, Conv2DTranspose, Concatenate from tensorflow.keras.losses import MeanSquaredError, MeanAbsoluteError from tensorflow.nn import max_pool_with_argmax import tensorflow_addons a...
pomtojoer/DeepCFD-TF
models.py
models.py
py
6,947
python
en
code
1
github-code
1
6202228261
from django.conf.urls import url from django.urls import path,include from blog import views urlpatterns =[ url(r'^about/$',views.AboutView.as_view(),name = "about"), url(r'^$',views.PostListView.as_view(), name ="post_list"), url(r'^posts/(?P<pk>\d+)$', views.PostDetailView.as_view(),name = "post_detail")...
AttalaKheireddine/bloggo
bloggo/blog/urls.py
urls.py
py
1,032
python
en
code
0
github-code
1
19003238865
#!/usr/bin/python import numpy as np from math import cos, sin """" velocity_verlet.py - velocity verlet is an algorithm used to integrate Newton's equations of motion author: Lexi Signoriello date: 3/31/16 Steps are described here: https://en.wikipedia.org/wiki/Verlet_integration Step 1: Get positions from curr...
alsignoriello/MD_hardDisks
velocity_verlet.py
velocity_verlet.py
py
2,858
python
en
code
0
github-code
1
3168634647
from collections import OrderedDict from typing import Tuple, Union from fvcore.common.registry import Registry from omegaconf.listconfig import ListConfig import copy import threading import numpy as np import torch import torch.nn.functional as F from torch import nn from timm.models.vision_transformer import _cfg ...
zhaoyanpeng/vipant
cvap/module/encoder/image_head.py
image_head.py
py
2,844
python
en
code
19
github-code
1
37015075272
''' BALANCED Given a binary tree, determine if it is height-balanced. Height-balanced binary tree : is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Return 0 / 1 ( 0 for false, 1 for true ) for this problem Example : Input : 1 / \ ...
jeffrelt/interviewbit
trees/BALANCED.py
BALANCED.py
py
2,105
python
en
code
1
github-code
1
15023496745
#!/usr/bin/env python3 #./call.py -f data.txt -u http://192.168.1.145:8080 -e dpm from argparse import ArgumentParser from time import sleep import requests import sys import json parser = ArgumentParser() parser.add_argument("-f", "--file", dest="file", help="Line separated file of qrcode value"...
syjer/alf.io-PI-test
call.py
call.py
py
1,318
python
en
code
0
github-code
1
26130539033
import telegram import os import sys import json #set bot token in enrionmental variable 'outlet_bot_token' before using TOKEN = os.environ.get('outlet_bot_token') BOT = telegram.Bot(token=TOKEN) CHAT_IDS_PATHNAME = 'data/chat_ids.json' def read_chat_ids(pathname): try: with open(pathname, 'r') as json_f...
vaarnio/OutletScraper
notifications.py
notifications.py
py
2,223
python
en
code
0
github-code
1
39412984487
import requests class YaUploader: def __init__(self, token: str): self.token = token def upload_file(self, loadfile, savefile, replace=False): """Загрузка файла. savefile: Путь к файлу на Диске loadfile: Путь к загружаемому файлу""" headers = {'Content-Type': '...
Thunderouse/HW_YandexDisk
main.py
main.py
py
1,165
python
ru
code
0
github-code
1
75061513312
import requests import xml.etree.ElementTree as ET from bs4 import BeautifulSoup import json def get_rail_data(): parsed_data = [] url = 'http://api.irishrail.ie/realtime/realtime.asmx/getStationDataBsoupCodeXML_WithNumMins?StationCode=ENFLD&NumMins=90&format=xml' data = requests.get(url) data = data...
benedictmc/CS402
Question 5/get_rail.py
get_rail.py
py
1,123
python
en
code
0
github-code
1
28392530534
class TreeNode: def __init__(self, value): self.value = value self.left = None self.right = None class Node: """ Node Instructor. This class will have only an __init__ method to create nodes. """ def __init__(self, value, next=None): """ Node Constructo...
Essa31/data-structures-and-algorithms
tree_intersection/tree_intersection.py
tree_intersection.py
py
4,524
python
en
code
0
github-code
1
3412980718
from tkinter import * #initialize the root window root = Tk() ############################# # 10. Dropdown Menu ############################# # initialize menu def someFunc(): print("This is some function") mainMenu = Menu(root) root.configure(menu=mainMenu) subMenu = Menu(mainMenu) mainMenu.add_cascade(l...
MadhuASingh/begginer-Python
1.py
1.py
py
1,018
python
en
code
0
github-code
1
41898501447
import matplotlib.pyplot as plt import numpy as np from load_store import db_indicies as dbi def plot_data(shard_dict, x_units, y_scale, show=False, append_to_title=""): """ Plot each shard in the shard dict. Parameters ---------- shards: dict Dictionary containing shards x_unit...
chrisleet/selenite
selenite/visualize/plot_data.py
plot_data.py
py
4,618
python
en
code
0
github-code
1
22933581629
import sys import subprocess import pandas as pd import numpy as np def cmd(cmd): return subprocess.getoutput(cmd) #get labels f = open('labels.txt','r') data = f.read() labels = data.split('\n') f.close() labels.pop() labels # folders dirs = cmd("ls " + sys.argv[1]) folders = dirs.splitlines() #copy images an...
La4La/Color-Sketch-Based-Illustration-Retrieval-Using-CNN
train/make_train_data2.py
make_train_data2.py
py
1,227
python
en
code
3
github-code
1
19117157583
from gridworld import * import simulateController as Simulator import copy import compute_all_vis import cv2 # mapname = 'BeliefTestEvasion' mapname = 'BelieEvasionTwenty' filename = 'figures/'+mapname+'.png' image = cv2.imread(filename, cv2.IMREAD_GRAYSCALE) image = cv2.resize(image,dsize=(15,15),interpolation=cv2.IN...
GTLIDAR/safe-nav-locomotion
task_planner/Bipedal_Locomotion_Task_Planner/safe-nav-loco/Block_sim.py
Block_sim.py
py
3,814
python
en
code
21
github-code
1
71727453794
""" Module for unit testing. """ import pygame import sys import unittest import graphics import piece import position class TestPosition(unittest.TestCase): FEN_POSITIONS = [ ('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR ' 'w KQkq - 0 1', [['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'], ...
cbak/chess-puzzler
test.py
test.py
py
16,534
python
en
code
0
github-code
1
11223446905
from hevc_predictor import Predictor import numpy as np from tqdm import tqdm import random import cv2 def offline_augmenter(odp_batch=None, output_path = None, mode_data=False): """ Computes structural similarity and mse metrics to return X best augmentation patches. specify X as multiplier. ...
Goluck-Konuko/hevc_data_augmenter
hevc_augmenter/augmenter.py
augmenter.py
py
3,347
python
en
code
1
github-code
1
6188821386
from flask import request, Flask, render_template, redirect, url_for import os from MathEquation import roomtypePrediction import time app = Flask(__name__, static_url_path='', static_folder='static') @app.route('/') def index(): return render_template('tool.html') @app.route('/tool.h...
OierGman/FlaskAPI-SDLC
app.py
app.py
py
1,631
python
en
code
0
github-code
1
70297287074
import glob import pandas as pd from tqdm import tqdm from collections import defaultdict from gensim.models import Word2Vec import numpy as np type_transform = {"clicks": 0, "carts": 1, "orders": 2} IS_TRAIN = True IS_Last_Month = True def load_data(path): dfs = [] # 只导入训练数据 for e, chunk_file in enumera...
niejianfei/Kaggle_OTTO_Multi-Objective_Recommender_System
preprocess/deepwalk_prepare.py
deepwalk_prepare.py
py
4,265
python
en
code
10
github-code
1
23395524746
''' Author: Michael Sherif Naguib Date: November 3, 2018 @: University of Tulsa Question #12: What is the value of the first triangle number to have over five hundred divisors? Example: The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number wou...
Michael-Naguib/ProjectEuler
12.py
12.py
py
8,139
python
en
code
0
github-code
1
71059334434
M,N = [ int(x) for x in input().split() ] moradores = [] total_cheques = 0 valor_minimo = 0 for i in range(N): moradores.append(0) for i in range(M): f,v,t = [ int(x) for x in input().split() ] total_cheques += v moradores[f-1] -= v moradores[t-1] += v for i in range(N): if (moradores[i] >...
lucasruchel/OBI
2018/nivel2/camara_compensacao.py
camara_compensacao.py
py
455
python
en
code
0
github-code
1
24618522486
""" This module contains machine learning model class """ import os import sys from datetime import datetime, timedelta import numpy as np import pandas as pd import tensorflow as tf import tensorflow.keras.backend as K from tensorflow.keras.callbacks import ( CSVLogger, EarlyStopping, History, ModelCh...
aleksei-mashlakov/parking-forecast
src/PMV4Cast/ml_model.py
ml_model.py
py
7,462
python
en
code
1
github-code
1
24441154566
from database import SessionLocal import models,schemas def get_db(): try: db=SessionLocal() yield db finally: db.close() def add_student_utilities(id,name,marks1,marks2,marks3,marks4,marks5,marks6,avg,status,chance,db): new_student=models.StudentDetails(id=id,name=name,marks1=mar...
karthik-28github/test
_10_2_22/Fastapi/Student_Complate_project/utilities.py
utilities.py
py
1,887
python
en
code
0
github-code
1
32159861991
from myplot import * import numpy as np ## example points x = np.linspace(0, 10, 100) y1 = np.sin(x) y2 = np.cos(x) y3 = np.cos(x)**2 def automatic(): ''' one subplot, adding second y axis ''' p = Plot((10,8)) p.add_axis('b') p.axes[0].plot(x, y1, label = 'y1', color = 'r') p.axes[1].plot(x, y2, ...
sagitta42/myplot
example_second_axis.py
example_second_axis.py
py
434
python
en
code
0
github-code
1
71145334433
T = int(input()) M = int(input()) mat = [[0]*(T+1) for _ in range(T+1)] visited = [[0]*(T+1) for _ in range(T+1)] cnt = 0 queue = [] for _ in range(M): S, G = map(int, input().split()) mat[S][G] = 1 mat[G][S] = 1 for x in range(len(mat)): if mat[1][x] == 1: visited[1][x] = 1 visited[x]...
danzzang/python_algorithm
백준/바이러스.py
바이러스.py
py
691
python
en
code
0
github-code
1
37460030953
#!/usr/bin/python3 __version__ = '0.0.1' # Time-stamp: <2021-01-15T17:44:23Z> ## Language: Japanese/UTF-8 """「大バクチ」の正規分布+マイナスのレヴィ分布のためのパラメータを計算しておく。""" ## ## License: ## ## Public Domain ## (Since this small code is close to be mathematically trivial.) ## ## Author: ## ## JRF ## http://jrf.coco...
JRF-2018/simbd
generate_normal_levy_csv.py
generate_normal_levy_csv.py
py
2,426
python
en
code
0
github-code
1
71861361633
import nonebot from nonebot import on_command, on_message # from nonebot.adapters import Bot, Event from nonebot.plugin import Plugin from typing import Dict, List, Tuple, Set, Union import datetime from .my_config import Config from ... import kit from ...kit.nb import message as mskit global_config = nonebot.get...
AntiLeaf/CirnoBot
src/plugins/wymz/__init__.py
__init__.py
py
2,072
python
en
code
2
github-code
1
17243696411
import sys sys.path.insert(0, "/home/adriano/projeto_mestrado/modules") import numpy as np import pickle from PIL import Image # This is a sample Python script. import vessel_analysis as va if __name__ == '__main__': imag = 'Experiment #1 (adults set #1)_20x_batch1 - Superfical layers@45-Image 4-20X' #i...
AdrianoCarvalh0/texture_codes
modules/Vessel_Analysis/main.py
main.py
py
1,482
python
pt
code
0
github-code
1
41279707209
import sys from PyQt5.QtWidgets import QMainWindow, QApplication from PyQt5.QtGui import QIcon from PyQt5.QtCore import QUrl from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEnginePage class Window(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("YouTube") ...
Precious13ui/SDYA
main.py
main.py
py
889
python
en
code
2
github-code
1
1070827302
from tenacity import retry, stop_after_attempt, wait_fixed from aio_pika import Message, connect_robust from aio_pika.abc import AbstractIncomingMessage import json import aiosqlite from config import Settings from loguru import logger class RemoteDictRpcServer: def __init__(self): self.channel = None ...
jaksklo/RemoteDictionary
src/rpc_server.py
rpc_server.py
py
4,799
python
en
code
0
github-code
1
32345652310
from ast import arg from cmath import inf from notears.locally_connected import LocallyConnected from notears.lbfgsb_scipy import LBFGSBScipy from plot_utils import * import torch import torch.nn as nn import numpy as np import torch.nn.functional as F from notears.loss_func import * from plot_utils import * import no...
anzhang314/ReScore
adaptive_model/baseModel.py
baseModel.py
py
40,511
python
en
code
10
github-code
1
10049156994
from flask import Flask, render_template_string app = Flask(__name__) app.config['JSON_AS_ASCII'] = False def filtered(template): blacklist = ["self.__dict__","url_for","config","getitems","../","process"] for b in blacklist: if b in template: template=template.replace(b,"") return template @app...
okayu1230z/simple_ssti
src/app.py
app.py
py
660
python
en
code
1
github-code
1
12037648038
import json __all__ = ['base_publish_json'] def base_publish_json(request_dict): """ Building client publish json of base protocol base protocol: MQTT(1), CoAP(2), WebSocket(6) """ # build publish payload publish_payload = { 'data_type': 'request', 'task_id': request_dict['ta...
actorcloud/ActorCloud
server/actor_libs/emqx/publish/protocol/base.py
base.py
py
661
python
en
code
181
github-code
1
43501313733
# DICIONARIO É IGUAL UM OBJETO # filmes = { # 'Tilulo': 'Star War', # 'ano': 1977, # 'diretor': 'George Lucas' # } # print(filmes) # print(filmes.values()) # print(filmes.keys()) # print(filmes.items()) # for k,v in filmes.items(): # print(f'O {k} é {v}') # aluno = {} # copyLista = [] # for c in rang...
evalente82/Treinamento-Python
exercicios/DICIONARIOS.PY
DICIONARIOS.PY
py
4,270
python
pt
code
0
github-code
1
13411858744
############################################################ # # retrive the 3' UTR of some genes from all the 3' UTR of a # whole genome in one file, and output the 3' UTR of each # gene to a new file with the gene name in fast format # # hgTables.txt: all the 3' UTR sequence of a whole genome # in fast format # # g...
hanmiltonxing/codingPractice
extractSeq.py
extractSeq.py
py
1,007
python
en
code
0
github-code
1
30046030399
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed unde...
openstack/senlin
senlin/tests/unit/db/test_profile_api.py
test_profile_api.py
py
14,167
python
en
code
44
github-code
1
34842079910
# Random Pick with Weight: https://leetcode.com/problems/random-pick-with-weight/ # You are given an array of positive integers w where w[i] describes the weight of ith index (0-indexed). # We need to call the function pickIndex() which randomly returns an integer in the range [0, w.length - 1]. pickIndex() should ret...
KevinKnott/Coding-Review
Month 01/Week 03/Day 01/c.py
c.py
py
2,393
python
en
code
0
github-code
1
15463801328
#this is a client module for main program ''' send cmds: "0" - upadate base "2" - finish session recv cmds: "0" - UOK(you okay) "1" - UNOK(you not okay) "J" - next file in jpeg format "P" - next file in png format ''' import socket import os if os.name == "nt": path = os.getcwd() + "\\variants" elif os.name == "po...
Lavabar/audream
audream_v0.9(for 2.7)/client.py
client.py
py
2,307
python
en
code
0
github-code
1
26692181436
__author__ = "Matthias Rost, Alexander Elvers (mrost / aelvers <AT> inet.tu-berlin.de)" import abc import enum import os import pickle import random class AlgorithmIdentifier: def __init__(self, key, properties=None): self.key = AlgorithmType(key) self.properties = properties self._hash =...
submodular-middlebox-depoyment/submodular-middlebox-deployment
src/experiments/abstract_experiment_manager.py
abstract_experiment_manager.py
py
5,747
python
en
code
3
github-code
1
101243705
import sqlite3 from lib.User import User from lib.utils.Format import Format class Profile: def __init__(self, loggedInUser: User): self.profileId = None self.loggedInUser = loggedInUser def getProfileId(self): return self.profileId def create(self): con = sqlite3.connect...
01sebar/incollege
lib/Profile.py
Profile.py
py
2,229
python
en
code
2
github-code
1
42589723848
# -*- coding: utf-8 -*- """ Created on Sun Aug 13 21:26:41 2017 @author: ice-fire """ # #import random as r # #class Fish: # def __init__(self): # self.x = r.randint(0, 10) # self.y = r.randint(0, 10) # def move(self): # #所有鱼都向西 # self.x -= 1 # print("我的位置是:", s...
saberly/qiyuezaixian
继承.py
继承.py
py
1,518
python
zh
code
0
github-code
1
72933881635
#Create 5 trees #Store the data of them in variables in your program #for every tree the program should store its' #type #leaf color #age #sex #you can use just variables, or lists and/or maps pine = ['pine', 'brown', 23, 'male'] maple =['maple', 'yellow', 2, 'female'] oak = ['oak', 'green', 5, 'male'] acacias = ['acac...
green-fox-academy/balintdorner
week-04/day-01/Doable_homework.py
Doable_homework.py
py
388
python
en
code
0
github-code
1
19892176264
from typing import Optional, Union from fretboard.core.collections import StrEnum from fretboard.data_structures import CircularArray from fretboard.music_theory.interval import ( AscMelodicMinorScaleIntervals, DescMelodicMinorScaleIntervals, HarmonicMinorScaleIntervals, Interval, MajorScaleInterva...
pavlotkk/fretboard
fretboard/music_theory/scale.py
scale.py
py
6,310
python
en
code
1
github-code
1
428880409
import logging from flask import Blueprint, render_template, request, flash, redirect from webapp.config import VALID_VALUES, REGRESSION_VALUES from webapp.utils.dataframe_util import get_enriched_dataframe, prepare_data from webapp.utils.enrich_sunspots import get_results_for_best_classifier from webapp.utils.trends_u...
bystrovpavelgit/solar_trends_prediction
webapp/stat/views.py
views.py
py
3,581
python
en
code
2
github-code
1
35152914797
def solution(cacheSize, cities): if not cacheSize: return len(cities) * 5 answer = 0 cache = ["" for i in range(cacheSize)] for i in cities: city = i.lower() if city in cache: if cache[-1] != city: cache.append(cache.pop(cache.index(city))) ...
ihaeeun/Algorithms
Python/Programmers/Level 2/cache.py
cache.py
py
692
python
en
code
0
github-code
1
10063185169
from abc import abstractmethod import numpy as np from keras.layers import Conv2D, Dense, Flatten from keras.models import Sequential class GA: def __init__(self, x_train, y_train, x_test, y_test, epochs): # 初始化参数 self.x_train = x_train self.y_train = y_train self.x_test = x_test ...
HavEWinTao/BIT-CS
人工智能基础/3/Ga.py
Ga.py
py
4,844
python
en
code
1
github-code
1
17716038891
"""Analysis for meniscus. Attributes: BOUNDS (dict): Upper bounds for quantitative values. """ import itertools import os import warnings import numpy as np import pandas as pd import scipy.ndimage as sni from dosma.core.device import get_array_module from dosma.core.med_volume import MedicalVolume from dosma.c...
ad12/DOSMA
dosma/tissues/meniscus.py
meniscus.py
py
14,454
python
en
code
49
github-code
1
13461053291
with open("inputs/day6.txt") as f: data = f.read() # Part one def do_thing(size): for i in range(size, len(data)): window = data[i-size:i] if len(set(window)) == size: return i print(do_thing(4)) # Part two print(do_thing(14))
kokestu/aoc-2022
day6.py
day6.py
py
265
python
en
code
2
github-code
1
30401371332
# -*- coding: utf-8 -*- """ Created on Wed Jul 13 19:04:50 2016 @author: jack DESCRIPTION ----- This script is for generating color background patterns for bidirectional S-BOS INSTRUCTIONS TO USE ----- options can be set in the code. the width and height, as well as the wavelegth and waveform in both directions ca...
jonathanrgross/Background-Oriented-Schlieren
generate_background/generate_plaid_background.py
generate_plaid_background.py
py
4,594
python
en
code
6
github-code
1
21733301111
"""Модуль для схемы записи истории.""" from dataclasses import dataclass from datetime import datetime @dataclass class HistoryDTO: """.""" before: int after: int changes: int datetime_utc: datetime @classmethod def from_alchemy(cls, record): """Метод создания схемы. Arg...
YanaShurinova/shift_credit_card
authorization/src/app/dto/history.py
history.py
py
653
python
en
code
0
github-code
1
18359330872
#!/usr/bin/python3 from selenium import webdriver from selenium.webdriver.common.keys import Keys from time import sleep browser = webdriver.Firefox(executable_path='/home/ashika/selenium/geckodriver') browser.set_window_size(900,900) browser.set_window_position(0,0) sleep(1) browser.get("https://en.wikipedia.org/wiki/...
Ashikav/demo-repo
demo.py
demo.py
py
543
python
en
code
0
github-code
1
38273906592
from typing import List class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ p1 = m - 1 p2 = n - 1 tail = n + m - 1 while p1 >= 0 or p2 >= 0: i...
qiaocco/learn-data-structure
刷题/88.py
88.py
py
818
python
en
code
1
github-code
1
9133908627
def pairProduct(numbers, targetProduct): if len(numbers) < 1: return numMap = {} for i, n in enumerate(numbers): quot = targetProduct / n if quot in numMap: return (numMap[quot], i) else: numMap[n] = i return print(pairProduct([1, 2, 3, 4,...
richardljohn/CodingChallenges
pairProduct.py
pairProduct.py
py
328
python
en
code
0
github-code
1
29012266087
import os from types import SimpleNamespace import unittest import pandas as pd import numpy as np from cbm3_python import toolbox_defaults from cbm3_python.cbm3data import cbm3_results from cbm3_python.cbm3data import cbm3_output_files_loader from test.integration import import_run_helper class OutputFilesIntegrati...
cat-cfs/cbm3_python
test/integration/output_files_integration_test.py
output_files_integration_test.py
py
2,906
python
en
code
6
github-code
1
413523110
# pylint: disable=W0621,C0114,C0116,W0212,W0613 import pathlib from typing import Optional import pytest from dae.utils.regions import Region from dae.testing import setup_pedigree, setup_vcf, \ vcf_study from dae.testing.foobar_import import foobar_gpf from dae.genotype_storage.genotype_storage import GenotypeSt...
iossifovlab/gpf
dae/tests/integration/study_query_variants/test_f1_omission.py
test_f1_omission.py
py
6,567
python
en
code
1
github-code
1
32113324994
from ciphers.Cipher import Cipher from collections import Counter from utils.const import ENGLISH_IOC class BitwiseXOR(Cipher): @classmethod def encrypt(cls, text, key): text = text.encode('ascii') key = key.encode('ascii') return cls._hexify_encryption_matrix( [ ...
piotrjedrzejczak/cryptography
src/ciphers/BitwiseXOR.py
BitwiseXOR.py
py
2,667
python
en
code
0
github-code
1
7968560356
from typing import Literal def isPrime(num): for i in range(2, num/2): #gets number and then sees if it is prime by using every single number and running modulus if num % i == 0: return False return True def addtofile(data): open("primes.txt", "a").write(str(data)) #Just stores data at...
Dingo418/Prime-Finder
prime.py
prime.py
py
1,742
python
en
code
0
github-code
1
34477334741
#!/usr/bin/env python3 import logging import functools import rpyc import threading import random import time THREAD_SAFE = True # Toggles thread safe and unsafe behavior def synchronize(lock): """ Decorator that invokes the lock acquire call before a function call and releases after """ def sync_func(func...
tomerfiliba-org/rpyc
demos/sharing/server.py
server.py
py
2,375
python
en
code
1,454
github-code
1
20292781823
from datetime import datetime from lorem_text import lorem as lorem_func import pyotp from flask import abort, Blueprint, make_response, redirect, \ render_template, Response, send_file, send_from_directory, url_for, request, session from flask_login import login_user, current_user # noinspection PyPackageRequirement...
mattl1598/open-amdram-portal
webapp/routes.py
routes.py
py
17,614
python
en
code
0
github-code
1
71015603555
# Title: 숫자 카드 2 # Link: https://www.acmicpc.net/problem/10816 import sys from collections import defaultdict sys.setrecursionlimit(10 ** 6) read_single_int = lambda: int(sys.stdin.readline().strip()) read_list_int = lambda: list(map(int, sys.stdin.readline().strip().split(' '))) def solution(n: in...
yskang/AlgorithmPractice
baekjoon/python/number_card_2_10816.py
number_card_2_10816.py
py
755
python
en
code
1
github-code
1
26998236363
import os import sys import json import shutil import tempfile import re import glob import traceback import pyodbc import requests import datetime import calendar import sqlalchemy from dateutil import relativedelta import pandas as pd pd.set_option('display.max_columns', None) BC_PERMIT_DB_NORTH_P...
smHooper/vistats
py/retrieve_data.py
retrieve_data.py
py
26,376
python
en
code
0
github-code
1
37954697741
# secondary and tertiary strucures of DNA # reverse compliment DNA = open("rosalind_revc.txt","r").readlines()[0].strip() product = "" for i in DNA: if i == "A": product += "T" if i == "C": product += "G" if i == "G": product += "C" if i == "T": product += "A" print(...
SamTang2004/ProjectRepo
python 练习册/GetReverseComplement.py
GetReverseComplement.py
py
335
python
en
code
0
github-code
1
20714729925
import datetime import json import random from datetime import datetime from django.contrib import messages from django.contrib.auth import authenticate, login, logout, update_session_auth_hash from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect, get_object_or_404 f...
Szaneron/Battlewind
Website/views.py
views.py
py
50,644
python
en
code
0
github-code
1
32178810526
from __future__ import absolute_import, division, print_function import pytest from lucent.optvis import param def test_pixel(): shape = (1, 1) params, image_f = param.pixel_image(shape) assert params[0].shape == shape assert image_f().shape == shape def test_fft(): shape = (1, 1, 1, 1) pa...
greentfrapp/lucent
tests/optvis/param/test_spatial.py
test_spatial.py
py
495
python
en
code
562
github-code
1
35086856464
# Declaring a function and local variables. def days_to_units(num_of_days, conversion_unit): if conversion_unit == "hours": return f"{num_of_days} days are {num_of_days * 24} hours" elif conversion_unit == "minutes": return f"{num_of_days} days are {num_of_days * 24 * 60} minutes" else...
Kirui-brian/Nov
using_dictionaries.py
using_dictionaries.py
py
1,607
python
en
code
0
github-code
1
27272987413
import subprocess from CollectSingleResults import CollectSingleResults from ProcessLabelData import ProcessLabelData def DesignToRandomNumber(design, base=4, npad=2): ''' Converts designs back into random number. \ Assumes padding''' scatter_object = design[npad:-npad, npad:-npad] int_in_base = ...
CLEANit/EGSnrc
egs_home/scatter-learn/Optimization_Comparisons/PyEGSnrc.py
PyEGSnrc.py
py
2,289
python
en
code
0
github-code
1
43963555187
from uncertainties.unumpy import * from uncertainties import ufloat from inspect import getsourcefile import os.path as path, sys current_dir = path.dirname(path.abspath(getsourcefile(lambda:0))) sys.path.insert(0, current_dir[:current_dir.rfind(path.sep)]) from AP import * from uncertainties import unumpy def calc...
brouwerb/AP3
OPA/aufg4.py
aufg4.py
py
1,352
python
en
code
0
github-code
1
15870540092
import torch import torch.nn as nn import torch.nn.functional as F def DoubleConv(in_channel, out_channel): conv = nn.Sequential( nn.Conv2d(in_channel, out_channel, kernel_size = 3), nn.ReLU(inplace = True), nn.Conv2d(out_channel, out_channel, kernel_size = 3), nn.ReLU(inplace = True) ) return conv def cr...
FlagArihant2000/unet
models/parts.py
parts.py
py
548
python
en
code
3
github-code
1
3571688023
class nodeX: def __init__(self, name): self.name = name self.connections = {} def prims(n, edges, start): graph = {} for i in edges: x, y, r = i if x not in graph: graph[x] = nodeX(x) if y not in graph: graph[y] = nodeX(y) graph[x].c...
hahoanglc97/hackerRank
primsmstsub-testcases/test.py
test.py
py
906
python
en
code
0
github-code
1
9244456948
import torch import torch.nn as nn import os class B2_VGG(nn.Module): # VGG16 with two branches # pooling layer at the front of block def __init__(self): super(B2_VGG, self).__init__() conv1 = nn.Sequential() conv1.add_module('conv1_1', nn.Conv2d(3, 64, 3, 1, 1)) conv1.add_...
dragonlee258079/DMT
B2_VGG.py
B2_VGG.py
py
4,700
python
en
code
8
github-code
1
20459031802
# Homework 3 - Q1: Collatz Conjecture (Redux) (10/06/22) # Write function called longest_collatz() that: # Takes in two numbers, start and stop from the user. # Returns (NOT prints) the number that the longest chain in that range started from # Note that you are not printing the length of the longest chain, only the n...
ninada25/cmsc140
Desktop/py_scripts/homework/austria_hw3_q1.py
austria_hw3_q1.py
py
1,399
python
en
code
0
github-code
1
14526624335
import folium, io, sys, json from PyQt5.QtWidgets import ( QApplication, QLabel, QLineEdit, QPushButton, QVBoxLayout, QWidget, QHBoxLayout ) from PyQt5.QtWebEngineWidgets import QWebEngineView # pip install PyQtWebEngine """ Folium in PyQt5 """ class MyApp(QWidget): ...
CameraTrack/backend
test.py
test.py
py
4,751
python
en
code
0
github-code
1
30324768203
def solution(answers): answer = [] arr1 = [1,2,3,4,5] arr2 = [2,1,2,3,2,4,2,5] arr3 = [3,3,1,1,2,2,4,4,5,5] a,b,c = 0,0,0 length = len(answers) for i in range(length): if answers[i] == arr1[i%5]: a +=1 if answers[i] == arr2[i%8]: b +=1 if answe...
sod723/Algorithm
프로그래머스/lv1/42840. 모의고사/모의고사.py
모의고사.py
py
509
python
en
code
0
github-code
1
41035420324
"""Test the TextClause and related constructs.""" from sqlalchemy import and_ from sqlalchemy import asc from sqlalchemy import bindparam from sqlalchemy import Column from sqlalchemy import desc from sqlalchemy import exc from sqlalchemy import extract from sqlalchemy import Float from sqlalchemy import func from sql...
sqlalchemy/sqlalchemy
test/sql/test_text.py
test_text.py
py
38,430
python
en
code
8,024
github-code
1
73270903715
from ast import Raise from optparse import Option from typing import List, Dict, Protocol, Tuple, Optional from config.constant import PROJECT_ROOT from dataclasses import dataclass, field from abc import ABC, abstractmethod, abstractproperty from config.exceptions import ScrapeConfigError from config.config_test impor...
johnalbert-dot-py/JScrapeON
jscrapeon_parser/config_parser.py
config_parser.py
py
3,329
python
en
code
0
github-code
1
11101433884
import openpyxl # Carregar o arquivo workbook = openpyxl.load_workbook('<FILE_NAME>.xlsx') # Selecionar a planilha ativa sheet = workbook.active headers = [] for cell in sheet[2]: headers.append(cell.value) # Iterar sobre as linhas a partir da terceira linha data = [] for row in sheet.iter_rows(min_row=3, value...
EduardoFelixNeto/Conversor_excel_to_xliff
main.py
main.py
py
1,155
python
en
code
0
github-code
1
24862884689
import datetime class Usuario: def __init__(self, id, nombre, apellido, telefono, username, email, contrasena, avatar): self.id = id self.nombre = nombre self.apellido = apellido self.telefono = telefono self.username = username self.email = email self.contras...
robertojulian/comision-6
desafio8.py
desafio8.py
py
20,842
python
es
code
1
github-code
1
26486178646
import tweepy import re import apiKey ######## Get Tweets and Clean def get_all_tweets(screen_name): # authorize twitter, initialize tweepy auth = tweepy.OAuthHandler(apiKey.twitter_customer, apiKey.twitter_customer_secret) auth.set_access_token(apiKey.twitter_token, apiKey.twitter_secret) api = tweepy.AP...
shanpy/aiCompetition
get_tweets.py
get_tweets.py
py
2,874
python
en
code
0
github-code
1
10686339907
from abc import ABCMeta, abstractmethod from typing import Dict, Any, Optional, List import torch from ...core.helpers import Namespace from ...core.logger import LOGGER as logging from ...core.observers import EventManager from ...core.exceptions import CheckpointNotFound class AbstractNetwork(torch.nn.Module, me...
elix-tech/kmol
src/kmol/model/architectures/abstract_network.py
abstract_network.py
py
4,940
python
en
code
33
github-code
1
5257120976
#!/usr/bin/env python3 import sys def main(argv): # Prologue print ("vramRowEndsMinusOne:",end="") v = 0x20a0 rowCount = 19 for jump in range(0,200): rowCount += 1 if (rowCount==20): print ("\n\t.word ", end="") rowCount=0 print ("$%x" % (v-1), end="") if (rowCount<19): print (",", end=""...
blondie7575/GSCats
GenerateVRAMTable.py
GenerateVRAMTable.py
py
384
python
en
code
3
github-code
1
21423808546
fileName = raw_input('input file name: ') url = fileName + '/' + fileName f = open(url + '.txt', 'r') fw = open(url + '-deal.txt', 'w') lines = f.readlines() arr = lines.pop(0).strip('\n').split(' ') N = arr[0] lamda = arr[1] fw.write(N + ' ' + lamda + '\n'); adjM = [] for i in range(int(N)): adjM....
atwxp/cluster
cluster/py/deal.py
deal.py
py
676
python
en
code
0
github-code
1
438039859
import numpy as np from core.relations import Relation from base import Base class PatternFeature(Base): def __init__(self, patterns, max_sentence_range=5): assert(type(patterns) == list) self.patterns = patterns self.max_sentence_range = max_sentence_range def create(self, relation...
nicolay-r/sentiment-relation-classifiers
classifiers/features/pattern.py
pattern.py
py
911
python
en
code
0
github-code
1
21035711313
""" Checks for configuration option values """ import collections.abc import grp import os import pwd import re import socket import textwrap import typing from typing import Sequence, Type, Union import netaddr from pyroute2.iproute import IPRoute from .base import ( Check, ConfigOptionError, OptionCheck...
agdsn/hades
src/hades/config/check.py
check.py
py
12,235
python
en
code
7
github-code
1
3561958374
#!/usr/bin/python3.6 #-*- coding: utf-8 -*- """ @Time : 2023/3/23 9:41 @Author : panrhenry """ import time from playwright.sync_api import sync_playwright as playwright pw = playwright().start() chrom = pw.chromium.launch(headless=False) context = chrom.new_context() # 需要创建一个 context page = context.new_page() ...
panrhenry/py_pro_1
pachong/getNovel_new_39/111.py
111.py
py
1,875
python
en
code
0
github-code
1