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
9001276762
from time import time from gurobipy import Model class MDSP: def __init__(self, d: list, filename: str, optimize=False, time_limit=3600): self.D = d self.B = sum(d) self.k = len(self.D) self.D_ = self.get_unique_distances() self.M = self.get_mult() self.P = list(ra...
cleberoli/mdsp
model/mdsp.py
mdsp.py
py
1,706
python
en
code
0
github-code
6
23565353773
# -*- coding: utf-8 -*- '''Polynomial basis linear model data generator''' import numpy as np import hw3_1a def polynomial(basis,var,weights,n=1): noise = hw3_1a.normal_generating(0, var) x = np.random.uniform(-1, 1, n) X=[] for power in range(basis): X.append( x[:] ** power) ...
n860404/Machine_learning_2019
HW3/hw3_1b.py
hw3_1b.py
py
736
python
en
code
0
github-code
6
41211514297
import rabacus as ra import pylab as plt import numpy as np z = 3.0 Nnu = 100 q_min = 1.0e-2 q_max = 1.0e6 uvb = ra.BackgroundSource( q_min, q_max, 'hm12', z=z, Nnu=Nnu ) NT=100 T = np.logspace( 4.0, 5.0, NT ) * ra.u.K nH = np.ones( NT ) * 1.0e-2 / ra.u.cm**3 nHe = nH * 10**(-1.0701) H1i = np.ones(T.size) * uvb.th...
galtay/rabacus
cloudy/cooling/rabacus_confirm.py
rabacus_confirm.py
py
1,097
python
en
code
4
github-code
6
13879303932
#!/usr/local/bin/python3.7 # -*- coding: utf-8 -*- # @Time : 2020-06-20 16:15 # @Author : 小凌 # @Email : 296054210@qq.com # @File : test_06_audit.py # @Software: PyCharm import json import unittest import ddt from common.excel_handler import ExcelHandler from common.http_handler import visit from middlerware.h...
galaxyling/api-framework
testcases/test_06_audit.py
test_06_audit.py
py
3,807
python
en
code
1
github-code
6
20209358126
n , k = [int(s) for s in input().split()] s = set([str(s) for s in range(n + 1)]) mm = set() for i in range(k): a_i, b_i = [int(s) for s in input().split()] j = 0 while a_i + j * b_i <= n: m = a_i + j * b_i mm.update(str(m)) s.remove(m) j += 1 print(len(s))
Nayassyl/22B050835
pt/sets/100.py
100.py
py
301
python
en
code
0
github-code
6
73025036669
from enum import Enum from typing import List import sqlalchemy as sa from sqlalchemy import orm as so from .base import BaseMixin, db, IdentityMixin, TimestampMixin __all__ = ['Chat', 'ChatEntry'] class Chat(BaseMixin, IdentityMixin, TimestampMixin, db.Model): """Chat Model. Represents a chat conversatio...
sergeyklay/promptly
backend/promptly/models/chat.py
chat.py
py
2,313
python
en
code
1
github-code
6
70506428347
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def kthSmallest(self, root, k): """ :type root: TreeNode :type k: int :rtype: int ...
yangh9596/Algo-Leetcode
Leetcode/230_Kth Smallest Element in a BST.py
230_Kth Smallest Element in a BST.py
py
1,178
python
en
code
0
github-code
6
22019313936
# -*- coding: utf-8 -*- import numpy as np from progbar import progress import sys def findBchange(initialPDB, multiDoseList, Bmetric, relative=True): # function to determine the Bfactor/Bdamage (specified by Bmetric) # change between the initial and later datasets --> becomes an # object attribute for th...
GarmanGroup/RIDL
lib/findMetricChange.py
findMetricChange.py
py
1,686
python
en
code
3
github-code
6
40759032093
from utilities.Constants import Constants from indicators.Indicator import Indicator import pandas as pd class MACD(Indicator): # price is DataFrame, = adj_close def __init__(self, df=None, fast_period=12, slow_period=26, signal_period=9): super().__init__() self.fast_period = fast_period ...
alejandropriv/stocksAnalysis
indicators/MACD.py
MACD.py
py
2,625
python
en
code
0
github-code
6
41584638888
"""Celery를 사용하는 예제""" import random import time from os import path from urllib import parse import requests from celery import Celery from pydub import AudioSegment from my_logging import get_my_logger logger = get_my_logger(__name__) # 크롤링 요청 간격 리스트 정의 RANDOM_SLEEP_TIMES = [x * 0.1 for x in range(10, 4...
JSJeong-me/2021-K-Digital-Training
Web_Crawling/python-crawler/chapter_5/crawler_with_celery_sample.py
crawler_with_celery_sample.py
py
5,058
python
ko
code
7
github-code
6
72492708988
import pytest from pytest_persistence import plugin plg = plugin.Plugin() @pytest.mark.parametrize("scope", ["session", "package", "module", "class", "function"]) @pytest.mark.parametrize("result", ["result", 42]) def test_store_fixture(result, scope): fixture_id = ('fixture1', scope, 'tests/test_mock.py') ...
JaurbanRH/pytest-persistence
tests/test_unit.py
test_unit.py
py
1,367
python
en
code
0
github-code
6
2246643792
testname = 'TestCase apwds_1.2.1' avoiderror(testname) printTimer(testname,'Start','Check Ac basic wds configuration in open mode') ############################################################################### #Step 1 #操作 # AC上show wireless network 2 #预期 # 显示WDS Mode....................................... Disable ##...
guotaosun/waffirm
autoTests/module/apwds/apwds_1.2.1.py
apwds_1.2.1.py
py
5,416
python
de
code
0
github-code
6
12702052399
""" To render html web pages """ import random from django.http import HttpResponse from django.template.loader import render_to_string from articles.models import Article def home_view(request, id=None, *args, **kwargs): """ Take in a request (Django send request) return HTML as a response (We pic...
L1verly/djproject-private
djproject/views.py
views.py
py
832
python
en
code
0
github-code
6
34313307894
import os import subprocess import time import sys import tracemalloc import concurrent.futures import threading stopProcessing = False def get_all_pids(): ps_cmd = ['ps', '-e', '-o', 'pid'] out = subprocess.Popen(ps_cmd, stdout = subprocess.PIPE).communicate()[0] out = ''.join(map(chr,out)) out = ou...
noman-bashir/CarbonTop
code/power_model/powerTrial.py
powerTrial.py
py
3,096
python
en
code
0
github-code
6
19239217812
# tree ! 트리 나라 관광 가이드 # 부모 도시 없다면 만들어주기 K = int(input()) A = list(map(int, input().split())) N = max(A) parent = [-2] * (N+1) # 루트 도시의 부모는 -1이니 존재하지 않는 값인 -2로 통일 parent[A[0]] = -1 # 루트 도시가 0번이 아닌 경우도 있다! for i in range(K-1): # 만약 아직 부모가 없는 도시라면 바로 전 도시를 부모로 하기 if parent[A[i+1]] == -2: parent[A[i+1]] = A[i...
sdh98429/dj2_alg_study
BAEKJOON/tree/b15805.py
b15805.py
py
508
python
ko
code
0
github-code
6
34097968081
#!/usr/bin/python import curses import sys import RPi.GPIO as GPIO def main(stdscr): # do not wait for input when calling getch stdscr.nodelay(1) initGPIO() while True: # get keyboard input, returns -1 if none available c = stdscr.getch() if c != -1: # print numer...
tophsic/gpio
one_led_controled_by_s.py
one_led_controled_by_s.py
py
914
python
en
code
0
github-code
6
36733301943
import re import json from collections import defaultdict def file_paths(file_path= 'logs_2/postcts.log1'): with open(file_path, 'r') as file: file_data = file.read() return file_data def parse_log_file(): file_contents = file_paths() # Compile regex patterns for improved ...
DavidJose2000/Log_parse
Zpharse.py
Zpharse.py
py
6,755
python
en
code
0
github-code
6
5153764381
import pandas as pd import numpy as np import matplotlib.pyplot as plt import sklearn from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix, classification_report import xlsxwriter #Reading the file into the system file1 = ...
Royston2708/Loan_Defaulter_Project
Models/Decision Trees and Random Forrest.py
Decision Trees and Random Forrest.py
py
2,138
python
en
code
0
github-code
6
13446768071
""" Отсортируйте по убыванию методом пузырька одномерный целочисленный массив, заданный случайными числами на промежутке [-100; 100). Выведите на экран исходный и отсортированный массивы. """ import random, math def bubble_sort(array): n = 1 while n < len(array): change = 0 for i in ra...
byTariel/Algoritms
dz_7_task_1.py
dz_7_task_1.py
py
860
python
ru
code
0
github-code
6
36651552794
#!/usr/bin/python3 # Codeforces - Educational Round #90 # Author: frostD # Problem B - 01 Game def read_int(): n = int(input()) return n def read_ints(): ints = [int(x) for x in input().split(" ")] return ints #--- def solve(s): moves = 0 ms1 = s.split('10') # move set 1 ms2 = s.split('01') # move set 2...
thaReal/MasterChef
codeforces/ed_round_90/game.py
game.py
py
709
python
en
code
1
github-code
6
19570224957
def read_cook_book(file, cook_book_): list_temp = [] line1 = str(file.readline().strip()) num2 = int(file.readline()) i = 0 while i < num2: line = file.readline() list_line = line.split(' | ') dict_ingr = {'ingredient_name': list_line[0], 'quantity': int...
IlAnSi/DZ_2_8
Cook_Book.py
Cook_Book.py
py
1,706
python
en
code
0
github-code
6
32756126137
# !/usr/bin/python import os import sys # Logging configuration import logging class logger(logging.Logger): def __init__(self): """Initializer.""" super().__init__() logging.basicConfig(filename="errlog.log", filemode="a", format="(%(asctime)s)...
MohdFarag/Musical-Instruments-Equalizer
src/logger.py
logger.py
py
478
python
en
code
0
github-code
6
26023698980
import matplotlib.pyplot as plt import numpy as np #plot 1 x=np.arange(-8,8,0.1) y=x**3 plt.subplot(2,2,1) plt.plot(x,y) plt.title("plot 1") #plot 2 x=np.linspace(0,3*np.pi,400) y=x/(1+(x**4)*(np.sin(x))**2) plt.subplot(2,2,2) plt.plot(x,y) plt.title("plot 2") #plot 3 x=np.linspace(1,10,400) y=np.sin(1/(x**(1/2))) p...
suanhaitech/pythonstudy2023
Wangwenbin/Matplotlib4.py
Matplotlib4.py
py
492
python
uk
code
2
github-code
6
6794457250
from __future__ import annotations import typing from dataclasses import dataclass from anchorpy.borsh_extension import EnumForCodegen import borsh_construct as borsh class UninitializedJSON(typing.TypedDict): kind: typing.Literal["Uninitialized"] class ActiveJSON(typing.TypedDict): kind: typing.Literal["Ac...
Ellipsis-Labs/phoenixpy
phoenix/types/market_status.py
market_status.py
py
4,121
python
en
code
5
github-code
6
24883752413
from django.conf.urls import patterns, include, url urlpatterns = patterns('', url(r'^$', 'informes.views.home', name='i_home'), url(r'^pendientes/$', 'informes.views.informes_pendientes', name='i_pend'), url(r'^arreglados/$', 'informes.views.informes_arreglados', name='i_fixed'), url(r'^noarreglados/...
efylan/ccreservas
informes/urls.py
urls.py
py
592
python
es
code
0
github-code
6
31559622204
num = input() #First Method for python print(num[::-1]) #Second Method for c num,a = int(num),0 while num > 0: a = a*10 + num%10 num = num//10 print(a)
Shobhit0109/programing
EveryOther/python/Codes/New codes/Rev num in 2 ays.py
Rev num in 2 ays.py
py
166
python
en
code
0
github-code
6
38336203002
#!/usr/bin/python from websocket import create_connection import unittest from common import read_info from common import read_message from common import check_action as c import time import json class websocket_request(unittest.TestCase): """32. 安装脚本""" def setUp(self): rt=read_info.ReadInfo() ...
leen0910/websocket_api
websocket_api/test_case/test10_InstallScript.py
test10_InstallScript.py
py
2,199
python
en
code
0
github-code
6
5897258860
import pickle import numpy as np from flask import Flask, request, jsonify # Load the pickled model with open('model.pkl', 'rb') as file: model = pickle.load(file) app = Flask(__name__) # Endpoint for making predictions @app.route('/predict', methods=['POST']) def predict(): try: data = request.get_j...
mdalamin706688/copd-ml-model
app.py
app.py
py
1,327
python
en
code
0
github-code
6
75114039226
from timeit import default_timer as timer import re start = timer() file = open('input.txt') # exponential growth, every 7 days, after 0 # unsynchronized # +2 day before first cycle memo = {} # global const def solve_babies(days, initial_clock, spawn_clock, cycle): if initial_clock > days: return 0 key = (days,...
kmckenna525/advent-of-code
2021/day06/part2.py
part2.py
py
1,044
python
en
code
2
github-code
6
10691788495
import logging from sentry.client.handlers import SentryHandler logger = logging.getLogger() # ensure we havent already registered the handler if SentryHandler not in map(lambda x: x.__class__, logger.handlers): logger.addHandler(SentryHandler(logging.WARNING)) # Add StreamHandler to sentry's default so y...
8planes/langolab
django/web/sentry_logger.py
sentry_logger.py
py
475
python
en
code
3
github-code
6
73080806907
from NaiveTruthReader import NaiveTruthReader from headbytes import HeadBytes import numpy as np feature_maker = HeadBytes(10) reader = NaiveTruthReader(feature_maker, "test.csv") reader.run() data = [line for line in reader.data] split_index = int(0.5 * len(data)) train_data = data[:split_index] # split% of data. ...
xtracthub/XtractPredictor
features/reader_test.py
reader_test.py
py
967
python
en
code
0
github-code
6
72743745468
from app.shared.common.recaptcha import CaptchaValidation from app.shared.database.dynamodb_client import DynamodbClient from app.shared.models import CustomerReviewModel def main(object_id: str) -> dict: dynamodb = DynamodbClient() try: dynamodb.contact_us.delete(object_id) except Exception as err...
ishwar2303/graphidot-serverless-backend
app/functions/contact_us/delete_customer_message.py
delete_customer_message.py
py
428
python
en
code
0
github-code
6
12483191239
# reference: J. P. Tignol # "Galois Thoery of Algebraic Equations" chapter 12 import numpy as np from sympy import factorint,root,expand class Period:# Gaussian periods @classmethod def init(cls,p):# p must be prime n = p-1 g = 2 # generator mod p f = factorint(n) ...
tt-nakamura/cyclo
cyclo.py
cyclo.py
py
5,447
python
en
code
0
github-code
6
20216419382
from model.flyweight import Flyweight from model.static.database import database class Operation(Flyweight): def __init__(self,activity_id): #prevents reinitializing if "_inited" in self.__dict__: return self._inited = None #prevents reinitializing self.activity...
Iconik/eve-suite
src/model/static/sta/operation.py
operation.py
py
1,189
python
en
code
0
github-code
6
18002323535
from hydra import compose, initialize import logging import torch from torch.utils.tensorboard import SummaryWriter from data.dataset import get_dex_dataloader from trainer import Trainer from utils.global_utils import log_loss_summary, add_dict from omegaconf import OmegaConf from omegaconf.omegaconf import open_dict...
PKU-EPIC/UniDexGrasp
dexgrasp_generation/network/train.py
train.py
py
4,171
python
en
code
63
github-code
6
1999311786
import os from enum import Enum, auto from random import randint import pygame class Main: @staticmethod def start(): pygame.font.init() os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (400, 100) surface = pygame.display.set_mode((1200, 900)) pygame.display.set_caption('Mineswe...
MaximCosta/messy-pypi
messy_pypi/done/main_minesweeper.py
main_minesweeper.py
py
7,807
python
en
code
2
github-code
6
3885504768
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.utils.html import mark_safe from rooms.models import Room from .models import User # admin.ModelAdmin을 상속받는 경우 # @admin.register(User) # class CustomUserAdmin(admin.ModelAdmin): # """ Custom User Admin """ # list_di...
Odreystella/Pinkbnb
users/admin.py
admin.py
py
1,838
python
en
code
0
github-code
6
42660213870
# read the sequence file to python n = 0 for line in open("ampR.fastq"): line = line.strip() if not line: continue n += 1 # starts with '@' if line.startswith("@") and n != 4: name = line[1:].split(" ", maxsplit=1)[0] seq = score = "" n = 1 elif n == 2: s...
FlyPythons/Python-and-Biology
data/1/read_fastq.py
read_fastq.py
py
647
python
en
code
2
github-code
6
11844211331
from flask import Flask, render_template, request from mbta_helper import find_stop_near app = Flask(__name__, template_folder="templates") @app.route("/") def index(): """ This function asks for the user's location """ return render_template("index.html") @app.route("/POST/nearest", methods=["POST...
nandini363/Assignment-3
app.py
app.py
py
917
python
en
code
0
github-code
6
17372597106
# LinearlyVariableInfill """ Linearly Variable Infill for 3D prints. Author: Barnabas Nemeth Version: 1.5 """ from ..Script import Script from UM.Logger import Logger from UM.Application import Application import re #To perform the search from cura.Settings.ExtruderManager import ExtruderManager from collections imp...
vaxbarn/LinearlyVariableInfill
LinearlyVariableInfill.py
LinearlyVariableInfill.py
py
21,725
python
en
code
0
github-code
6
20040130347
from random import choice def get_binary(): output = [] for i in range(8): output.append(choice([0,1])) return output def get_binary_sum(): output = [] for i in range(8): output.append(choice([0,1])) return sum(output) samps = [] counts = 0 while 0 not in samps: samps.app...
mwboiss/DSI-Prep
intro_py/binary_sum.py
binary_sum.py
py
385
python
en
code
0
github-code
6
35160550288
from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from django.db.models import Q from .models import Employee from .forms import AddEmployeeForm @login_required(login_url='authapp:login') def index(request): context = dict(...
somukhan9/django-employee-management-system
employee/views.py
views.py
py
3,206
python
en
code
0
github-code
6
7848372415
import time import numpy as np import json from simplex_algorithm.Interaction import Interaction class SimplexSolver(): ''' Class is responsable to solve maximization Linear Programming Problems. @author: Matheus Phelipe ''' def __init__(self, matrix_a, matrix_b, matrix_c, max_iteractions, has_...
matheusphalves/simplex-algorithm
simplex_algorithm/SimplexSolver.py
SimplexSolver.py
py
4,877
python
en
code
0
github-code
6
35560642063
import numpy as np import matplotlib.pyplot as plt import matplotlib from mayavi import mlab from scipy.ndimage import map_coordinates from scipy import signal, interpolate from PIL import Image, ImageDraw from matplotlib.colors import ListedColormap from tqdm import tqdm, trange def create_block_diagram(strat, prop, ...
zsylvester/stratigraph
stratigraph/stratigraph.py
stratigraph.py
py
50,938
python
en
code
8
github-code
6
582921826
import numpy as np import argparse # parser = argparse.ArgumentParser(description='Keypoints distance computing script') # parser.add_argument( # '--origin_image_file', type=str, required=False, # help='path to a file containing the keypoints and descriptors of the first image' # ) # parser.add_argument( #...
vqlion/PTIR-Image-Processing
test_keypoints_distance.py
test_keypoints_distance.py
py
2,595
python
en
code
0
github-code
6
5308746110
from copy import deepcopy arr = [[None]*4 for _ in range(4)] for i in range(4): row = list(map(int, input().split())) for j in range(4): # (번호, 방향) arr[i][j] = [row[j*2], row[j*2+1]-1] dirs = [(-1, 0), (-1, -1), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1)] # 현재 위치에서 왼쪽으로 회전된 결과...
louisuss/Algorithms-Code-Upload
Python/DongbinBook/simulation/kid_shark_solution.py
kid_shark_solution.py
py
2,490
python
ko
code
0
github-code
6
37076357644
""" Find the LCA of Binary Tree. https://www.youtube.com/watch?v=13m9ZCB8gjw """ def lca(root, n1, n2): if root is None: return None if root.data == n1 or root.data == n2: return root node_left = lca(root.left, n1, n2) node_right = lca(root.right, n1, n2) if node_left is not Non...
piyush9194/data_structures_with_python
data_structures/trees/lowest_common_ancestor_bt.py
lowest_common_ancestor_bt.py
py
502
python
en
code
0
github-code
6
41039585752
import logging import random import string import time import sys from decimal import Decimal from typing import Any, Callable, Optional, TypeVar, Union import requests from vega_sim.grpc.client import VegaCoreClient, VegaTradingDataClientV2 from vega_sim.proto.data_node.api.v2.trading_data_pb2 import GetVegaTimeReque...
vegaprotocol/vega-market-sim
vega_sim/api/helpers.py
helpers.py
py
6,261
python
en
code
19
github-code
6
34465917082
import torch from torch.utils.data import DataLoader from .coco_dataset import build_dataset def batch_collator(batch): images, boxmgrs = list(zip(*batch)) images = torch.stack(images, dim=0) return images, boxmgrs def build_dataloader(cfg, is_train=True): dataset = build_dataset(cfg, is_train=is_t...
lmyybh/computer-vision
yolo/yolo/data/dataloader.py
dataloader.py
py
558
python
en
code
0
github-code
6
15018597005
from utils.utils import OS import sys if OS.Linux: import matplotlib matplotlib.use("agg") import json import math import multiprocessing import random from multiprocessing import Pool from threading import Thread from typing import Union, Callable from uuid import UUID import networkx from Model.Computatio...
Moni5656/npba
Model/ModelFacade.py
ModelFacade.py
py
30,489
python
en
code
0
github-code
6
33040837881
import io import struct from typing import Any, BinaryIO class StructStream(int): PACK = "" """ Create a class that can parse and stream itself based on a struct.pack template string. """ def __new__(cls: Any, value: int): value = int(value) try: v1 = struct.unpack(cl...
snight1983/chia-rosechain
chia/util/struct_stream.py
struct_stream.py
py
1,440
python
en
code
369
github-code
36
34098196022
import uvicorn from pyroute2 import IPRoute from fastapi import FastAPI ipr = IPRoute() ipr.bind() app = FastAPI() @app.get("/iface/{iface_name}") async def iface_id(iface_name): with IPRoute() as ipr: iface = ipr.link_lookup(ifname=iface_name) return {"iface": iface[0]}
andreagarbugli/iaac-tc-quic
tc-daemon/router.py
router.py
py
293
python
en
code
0
github-code
36
23442724105
inp = input("Enter you input here ") len = len(inp) decoding = True if(decoding): if(len<3): print(inp[::-1]) else: random=inp[3:-3] #ll=random[-1] newStr=random[-1]+random[:-1] print(newStr)
somya143/python_learning
decoding.py
decoding.py
py
240
python
en
code
1
github-code
36
39908117264
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient import logging import time import argparse import json import ast AllowedActions = ['both', 'publish', 'subscribe'] file_path = "../History.log" faults = [] fault_type = "" # Read in command-line parameters parser = argparse.ArgumentParser() parser.add_argument("-e...
ngonza27/ctp-ngv-23
src/py/send_data.py
send_data.py
py
5,270
python
en
code
0
github-code
36
11503756221
def fizz_buzz(max_val=100): '''fizz_buzz is an implementation of a popular programming question. It is an illustration in the futility of a language without switch/case statements. Arguments: -- max_val: fizz_buzz runs from [0,max_val] (default: 100) ''' for num in range(0, max...
alextoombs/learning-python
fizzbuzz/fizzbuzz.py
fizzbuzz.py
py
680
python
en
code
0
github-code
36
14007737341
import torch import torch.nn as nn import torch.nn.functional as F import torchvision from torchvision import datasets, transforms from torchvision.utils import save_image import matplotlib.pyplot as plt import numpy as np import random class AutoEncoderNet(torch.nn.Module): def __init__(self, n_channels, dim_last...
s183920/02582_Computational_Data_Analysis_Case2
autoencoder/ae.py
ae.py
py
1,937
python
en
code
0
github-code
36
6198323090
''' 1.입력받은 문자의 길이별 + 문자별 조건식? 2.BruteForce니까 로직만 짜서 1씩 증가? <- 이래도 되는게 가장 큰 수 해봐야 5^5임 시간초과는 안날걸 2번으로 진행해보도록 하고, 로직은 어떻게 하느냐가 문제일듯 ''' from itertools import product def solution(word): answer = [] for i in range(1,6): for v in product(["A","E","I","O","U"],repeat = i): answer.append("".join(v...
byeong-chang/Baekjoon-programmers
프로그래머스/lv2/84512. 모음 사전/모음 사전.py
모음 사전.py
py
518
python
ko
code
2
github-code
36
34212427030
lista_idades = [] lista_pessoas = [] nome = input("Digite um nome: ") while (nome.lower() != 'fim'): idade = int(input("Digite uma idade: ")) lista_idades.append(idade) lista_pessoas.append(nome) nome = input("Digite um nome: ") print("\n\nNomes digitados\n===========") print(lista_pessoas) print("\n...
robsondejesus1996/Pos-Graduacao-Python
EstruturaRepeticao/ComandoWhile.py
ComandoWhile.py
py
366
python
pt
code
0
github-code
36
6620739257
import random def avalia(sequencia,matriz): distancia_atual = 0 print("o caminho atual é:"+str(sequencia)) for linha in range(len(sequencia)): for posicao in range(len(sequencia)): if linha+1<len(sequencia) and posicao==sequencia[linha+1]: print("A proxima posica...
Igao2/CodigosRandom
exemplojorge.py
exemplojorge.py
py
899
python
pt
code
0
github-code
36
22579941668
import sys import heapq INF = sys.maxsize V, E = map(int, input().split()) K = int(input()) node = [[] for _ in range(V+1)] for _ in range(E): start, end, value = map(int, input().split()) node[start].append((value, end)) def dijkstra(): hq = [] distLi = [INF for _ in range(V+1)] heapq.heappush(hq,...
heisje/Algorithm
baekjoon/1753_최단경로.py
1753_최단경로.py
py
721
python
en
code
0
github-code
36
22382283158
import shutil import tempfile from django.contrib.auth import get_user_model from django.test import Client, TestCase, override_settings from django.urls import reverse from django import forms from django.conf import settings from django.core.files.uploadedfile import SimpleUploadedFile from django.core.cache import ...
krankir/Social-network
yatube/posts/tests/test_views.py
test_views.py
py
12,656
python
en
code
0
github-code
36
73256078825
# add CBAM注意力机制模块 import torch from torch import nn class ChannelAttention(nn.Module): def __init__(self, channel, ratio=16): super(ChannelAttention, self).__init__() self.max_pool = nn.AdaptiveMaxPool2d(1) self.avg_pool = nn.AdaptiveAvgPool2d(1) self.fc = nn.Sequen...
DickensKP/Yolov3-vehicle-pedestrian-trafficsign-detection-system
CBAM.py
CBAM.py
py
2,002
python
en
code
4
github-code
36
17887863275
""" 集成了流式布局、按钮排布的窗口。 """ from PySide2.QtWidgets import QScrollArea, QWidget, QToolButton, QVBoxLayout, QSpacerItem, QSizePolicy from PySide2.QtCore import Qt, QSize from typing import TYPE_CHECKING if TYPE_CHECKING: from PySide2.QtGui import QResizeEvent from widgets import PMFlowLayout class PMFlowAreaWidge...
pyminer/pyminer
pyminer/widgets/widgets/basic/containers/flowarea.py
flowarea.py
py
2,813
python
en
code
77
github-code
36
1416947614
#Duc Nguyen #15/02/2023 #This code draws 3 shapes, square, triangle and a hexagon with a variety of colour fill and colour outlined + #pen size changed import turtle # Allows us to use turtles alex = turtle.Turtle() # Create a turtle, assign to alex wn = turtle.Screen() # create a window for our design #be...
Kaizuu08/PythonShowcase2023Semester1
Week 3/colours.py
colours.py
py
1,041
python
en
code
0
github-code
36
38072028175
from migen import * from migen.genlib.io import * from migen.genlib.misc import BitSlip, WaitTimer from litex.soc.interconnect import stream from litex.soc.cores.code_8b10b import Encoder, Decoder from liteiclink.serwb.datapath import TXDatapath, RXDatapath class _KUSerdesClocking(Module): def __init__(self, pa...
kamejoko80/linux-on-litex-vexriscv-legacy
liteiclink/liteiclink/serwb/kuserdes.py
kuserdes.py
py
4,841
python
en
code
0
github-code
36
38105669317
#!/usr/bin/env python3 from manim import * import numpy as np FONT_COLOR= "#282828" NO_TEX_FONT = "Bookerly" # NO_TEX_FONT = "JetBrains Mono" # NO_TEX_FONT = "JuliaMono" TEX_TEMPLATE = TexTemplate() TEX_TEMPLATE.add_to_preamble(r"\usepackage{amsbsy}") TEX_TEMPLATE.add_to_preamble(r"\usepackage{amsmath}") TEX_TEMPLATE...
Cardoso1994/manim_videos
associative_memories/lernmatrix/src/lernmatrix.py
lernmatrix.py
py
17,164
python
en
code
0
github-code
36
73507098983
from django import forms from .Config import EffectType class ChooseEffectRadioForm(forms.Form): def __init__(self, effect_type, effect_label, *args, **kwargs): super(ChooseEffectRadioForm, self).__init__(*args, **kwargs) self.fields["pref-effect"] = forms.BooleanField(label=effect_label,...
gwolan/pic_convolving_website
upload_pic/src/ChooseEffectRadioForm.py
ChooseEffectRadioForm.py
py
932
python
en
code
0
github-code
36
43712557365
nu1,nu2=map(int,input().split()) if nu1<=nu2: u=nu1 else: u=nu2 m=[] for i in range(0,u): m.append(sorted(list(map(int,input().split())))) m=sorted(m) for i in range(0,len(m[0])): for j in range(0,len(m)-1): if m[j][i]>m[j+1][i]: m[j][i],m[j+1][i]=m[j+1][i],m[j][i] for i in m: print(*i)
sriramkiddo/guvi-programs
pro4_2.py
pro4_2.py
py
308
python
en
code
0
github-code
36
72045569703
import re puzzle = open('puzzle', 'r').read().splitlines() puzzle = [tuple(map(int, re.findall(r'\d+', i))) for i in puzzle] def is_close_enough(x, y): distances = sum(abs(i[0]-x) + abs(i[1]-y) for i in puzzle) if distances < 10000: return 1 return 0 x1, x2, y1, y2 = puzzle[0][0], puzzle[0][0], puzzle[0][1], pu...
filipmlynarski/Advent-of-Code-2018
day_06/day_6_part_2.py
day_6_part_2.py
py
720
python
en
code
0
github-code
36
907918850
# Write a program to check if two strings are a rotation of each other? def checkRotation(str1, str2): temp = '' # Check if lengths of two strings are equal or not if len(str1) != len(str2): return False # storing concatenated string temp = str1 + str1 ...
Atulj01/DSA-assignment
3_problem.py
3_problem.py
py
700
python
en
code
0
github-code
36
14373956629
import random def merge_list(): first_list = [] second_list = [] seed_list(first_list) seed_list(second_list) print(first_list) print(second_list) output_list = [] for x in range(6): if x % 2 == 0: output_list.insert(x, first_list[x]) elif x % 2 == 1: ...
GGerginov/Python-Eexercises-TU-Sofia
Exercise/05|11|2021/MergeLists.py
MergeLists.py
py
507
python
en
code
0
github-code
36
32975944321
#Scripts for the search import mysql.connector import json class carrier(): Name = "" Email = "" Location = [] class seller(): Firstname = "" Surname = "" Email = "" Graduate = False Location = "" Products = [] class product(): menteeName = "" menteeGraduate = F...
Team-14-CodeForGood2014/Cherie-Blair-Foundation-Marketplace
Django/cbfm/searchEngine/scripts.py
scripts.py
py
6,321
python
en
code
0
github-code
36
11352228515
import os clear = lambda : os.system('cls') import datetime from time import process_time_ns x = datetime.datetime.now() ulang = "y" while ulang=="y" or ulang=="Y": kodeGolongan = [1,2,3] gajiPokok = [2500000, 4500000, 6500000] tunjanganIstri = [0.01, 0.03, 0.05] kodeJK =[1,2] JK = ['...
20083000169RianHudaMaulana/Uas-
UAS_20083000169_Rian Huda Maulana_2G.py
UAS_20083000169_Rian Huda Maulana_2G.py
py
8,062
python
en
code
0
github-code
36
6798077511
import logging from django.core.management.base import BaseCommand from django.core.exceptions import ObjectDoesNotExist from embed_video.backends import detect_backend from ...clients import VimeoClient from ...models import Resource from ...conf import settings logger = logging.getLogger('vimeo') class Command(...
tomasgarzon/exo-services
service-exo-medialibrary/resource/management/commands/import_vimeo_resources.py
import_vimeo_resources.py
py
5,577
python
en
code
0
github-code
36
21993890104
from typing import List from unittest import TestCase import torch from torch import Tensor from attnganw import config from attnganw.randomutils import get_vector_interpolation class TestInterpolation(TestCase): def test_get_noise_interpolation(self): batch_size = 1 noise_vector_size = 3 ...
cptanalatriste/birds-of-british-empire
tests/test_train.py
test_train.py
py
2,304
python
en
code
null
github-code
36
33245288481
#!/usr/bin/env python import rospy import matplotlib.pyplot as plt import matplotlib.animation import numpy as np from ti_mmwave_rospkg.msg import RadarScan class MySimpleClass(object): def __init__(self): self.sub = rospy.Subscriber('/ti_mmwave/radar_scan',RadarScan,self.sub_callback) self.tmp_x ...
YiShan8787/mm-2sensor
src/micro_doppler_pkg/scripts/test3.py
test3.py
py
1,420
python
en
code
0
github-code
36
69833302503
list = [1,2,3,4,5,6,7,8,23,435,545] string = 'hailo' int = 123 def adarsh_loop(object): try: iter_list = iter(object) while True: try: print(next(iter_list)) except: break except: print("object not iterable, f*ck off") adarsh_loop(l...
Adarsh1o1/python-initials
iter_and_generators.py
iter_and_generators.py
py
582
python
en
code
1
github-code
36
42390357735
from opspec import Spec import sys from braindead import log, info, error, die from syntax import * log.enable() s = Spec() s.parse(sys.argv[1]) info('loaded %s rules', len(s.rules)) lut = ['"\\x01invalid"']*256 for pattern, asm, action in s.rules: b = int(pattern[0], 16) asm = asm.replace('xxyy', '\\x02""') asm =...
braindead/ctf-writeups
2019/X-MAS/CHIP9/gen_disasm.py
gen_disasm.py
py
545
python
en
code
11
github-code
36
74605387945
from petalo_calib.tdc_corrections import correct_tfine_wrap_around from petalo_calib.qdc_corrections import correct_efine_wrap_around from petalo_calib.tdc_corrections import apply_tdc_correction_tot from petalo_calib.tdc_corrections import compute_integration_window_size from petalo_calib.tdc_corrections import add_...
jmbenlloch/petalo_calib
petalo_calib/scripts/process_files_tot_new_clusters.py
process_files_tot_new_clusters.py
py
4,761
python
en
code
0
github-code
36
42887542436
from collections import OrderedDict class Cache: """ A python class which used ordered dictionary (OrderedDict) to implement the LRU cache. Each entry of the dictinoary will be a key/value pair. The search would be by key. LRU Cache will have its maximum size defined at initiation. When adding n...
harsimrit/task1
cacheLRU.py
cacheLRU.py
py
4,971
python
en
code
0
github-code
36
21928404743
# css selector 활용 크롤링 ''' # css란? Cascading Style Sheets html로 잡힌 골격에 스타일링(색, 크기 등)을 하는 것 스타일의 이름으로 구조가 특정지어질 수 있음(css selector) CSS selector - 웹 구성 시 CSS Selector을 직접 활용해 이름을 붙혀 만들기 때문에 CSS Selector로 찾아질 가능성이 높다 - Element Type 방식 태그 값들이 selector의 기준이 된다 - ID 방식 태그 내 id 값이 존재하면 id값이 selector의 기준이 된다 - Class 방식 태그 ...
sh95fit/Python_study
Python_Crawling/Crawling_Static/Static_Study06.py
Static_Study06.py
py
1,717
python
ko
code
1
github-code
36
73642772264
# ----------------------------------------------------------- # --------- Assignment 4 - PCA analysis with Python ------------------ # ----------------------------------------------------------- # Author: Tomas Milla-Koch # Purpose: The following script is script for clipping a scene to vector boundary and performing...
tomasmk/Remote-Sensing-Automation
PCA.py
PCA.py
py
4,658
python
en
code
0
github-code
36
71116093224
from common.httphandler import HttpHander from common.yml_util import YmlUtil import pytest, json http = HttpHander() YmlUt = YmlUtil() class TestCaseSingle: def get_case_all(self, case_data, url_map, header): if case_data.get("method") == 'get': resp = http.get(url=url_map, headers=header) ...
itol220/testapi
testcases/test_single.py
test_single.py
py
1,385
python
en
code
0
github-code
36
29719072387
import numpy as np def cast(s): triple = s.split('<')[1][:-1].split(',') triple = [int(t) for t in triple] return np.array(triple) class Point(object): def __init__(self, split): """initalize""" self.loc = cast(split[0]) self.vel = cast(split[1]) self.acc = cast(split...
yknot/adventOfCode
2017/20_02.py
20_02.py
py
1,461
python
en
code
0
github-code
36
25321444319
import pandas as pd from glob import glob from datetime import datetime import os def removeDups(file): df = pd.read_excel(file) # Keep only FIRST record from set of duplicates df_first_record = df.drop_duplicates(subset="Date/Time", keep="first") #creates an excel file with sorted times if glob("n...
OliverSolomon/flaskExcel
reporter.py
reporter.py
py
3,444
python
en
code
0
github-code
36
43157370954
#!/usr/bin/python3 import sys, pygame from pygame.locals import * black = (0, 0, 0) white = (255,255,255) red = (255,0,0) green = (0, 255, 0) blue = (0, 0, 255) pygame.init() pygame.display.set_caption("drawing") # set the title of the window surface = pygame.display.set_mode((400, 300)) # return pygame.Surface su...
minskeyguo/mylib
python-edu/17-pygame-basic/02-geometry.py
02-geometry.py
py
1,223
python
en
code
0
github-code
36
34547412730
from PIL import Image import cv2 # 選擇第二隻攝影機 cap = cv2.VideoCapture(0) while(True): # 從攝影機擷取一張影像 ret, frame = cap.read() frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(frame, 100 , 200) # img_fc, contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE...
Amenoimi/Simple_OCR
QR_GET.py
QR_GET.py
py
1,322
python
en
code
0
github-code
36
73902282025
from abc import ABC, abstractmethod from app.schemas.base import BaseModel class BaseRepository(ABC): def __init__(self, model: BaseModel, *args, **kwargs): self.model = model @abstractmethod async def get_all(self): raise NotImplementedError
kirakulakov/wbmp_redis_stat
app/repositories/base.py
base.py
py
275
python
en
code
0
github-code
36
17704956797
import numpy as np from PyQt5.QtWidgets import QWidget, QApplication, QVBoxLayout from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg from matplotlib.figure import Figure from SO3 import SO3 from rotation import Ui_Form class My_window(QWidget, Ui_Form): def __init__(self, parent=None, *args, **kwa...
rollingball-3/Learning-rotation
main.py
main.py
py
2,586
python
en
code
0
github-code
36
32383353461
# -*- coding: utf-8 -*- #performance.py from __future__ import print_function import numpy as np import pandas as pd def create_sharpe_ratio(returns,periods=252): """ 计算策略的Sharpe比率,基于基准为0,也就是假设无风险利率为0 """ return np.sqrt(periods)*(np.mean(returns)/np.std(returns)) def create_drawdowns(pnl): """ ...
szy1900/Event_driven_framework_for_backtesting
performance.py
performance.py
py
882
python
zh
code
38
github-code
36
40243436461
""" Beautify Images Utils """ import random import operator import heapq import math from scipy.interpolate import UnivariateSpline import cv2 import pilgram from PIL import Image, ImageStat import numpy as np from src.utils.image_process import ( do_we_need_to_sharpen, sharpen_my_image, adjust_contrast...
teyang-lau/you-only-edit-once
src/utils/beautify.py
beautify.py
py
6,911
python
en
code
6
github-code
36
27653523771
import time import utilities.custom_logger as cl import logging from base.basepage import BasePage from base.selenium_driver import SeleniumDriver class Register_courses_page(BasePage): log = cl.customLogger(logging.DEBUG) #Locators _search_box_id = "search-courses" _course_xpath = "/html/body/div...
akanksha2306/selenium_python_practice
pages/courses/register_courses_page.py
register_courses_page.py
py
3,129
python
en
code
0
github-code
36
7668440361
import sys def ft_filter(check_function, _list): """filter(function or None, iterable) --> filter object Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true.""" filtered_list = [] for elem in _list: if check_function(elem) == T...
GusFiveO/python_for_data_science
module00/ex06/ft_filter.py
ft_filter.py
py
651
python
en
code
0
github-code
36
75091410342
import tensorflow as tf from transformers import GPT2Tokenizer, TFGPT2LMHeadModel import wikipediaapi # Set up Wikipedia API wiki = wikipediaapi.Wikipedia('en') # Set up tokenizer and model tokenizer = GPT2Tokenizer.from_pretrained('gpt2') model = TFGPT2LMHeadModel.from_pretrained('gpt2', pad_token_id=tokenizer.eos_t...
ethan-haynes/test
train.py
train.py
py
2,291
python
en
code
0
github-code
36
23551852124
#coding: UTF-8 class Dog: name = "" def brak(self): m = self.name + " : Bow-wow!" print(m) pochi = Dog() pochi.name = "Pochi" pochi.brak() hachi = Dog() hachi.name = "Hachi" hachi.brak()
kato-takashi/AI_python
python_training/class.py
class.py
py
212
python
en
code
0
github-code
36
8640307873
"""Extract hourly real-time EIA data from the bulk-download zip file.""" import pandas as pd import json from os.path import join import os import zipfile import requests import logging from electricitylci.globals import data_dir def download_EBA(): """Add docstring.""" url = 'http://api.eia.gov/bulk/EBA.zip...
USEPA/ElectricityLCI
electricitylci/bulk_eia_data.py
bulk_eia_data.py
py
5,340
python
en
code
23
github-code
36
70168571944
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0,10,100) y = [] up_limit = 0.8 for i in x: if i < 6: y.append(0) elif i < 9: y.append((i-6)/3 * up_limit) else: y.append(up_limit) plt.plot(x,y) plt.show()
CryptoGamer8/INFO6205-FINAL
Model/main/draw.py
draw.py
py
264
python
en
code
2
github-code
36
7630680769
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('inicio', '0006_auto_20160820_2050'), ] operations = [ migrations.CreateModel( name='cargo', fields=[...
juanjavierlimachi/sistema-de-Informacion
mipagina/mipagina/apps/inicio/migrations/0007_auto_20160820_2141.py
0007_auto_20160820_2141.py
py
1,065
python
en
code
0
github-code
36
74950126185
#!/usr/bin/env python # coding: utf-8 # In[45]: # Choquet adaptive thresholding: two step algorithm import progressbar from time import sleep import math import cv2 import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg import PIL from skimage import measure from pynverse import inver...
lodeguns/FuzzyAdaptiveBinarization
fuzzy_adaptive_bin.py
fuzzy_adaptive_bin.py
py
36,527
python
en
code
3
github-code
36
13790256283
#!/usr/bin/env python import rbd import rados import json import subprocess from itertools import chain from texttable import Texttable, get_color_string, bcolors def f(x): if x=="quota_max_bytes": return str(pool[x]/1024/1024) else: return str(pool[x]) p = subprocess.check_output('ceph osd du...
angapov/ceph-scripts
ceph.py
ceph.py
py
2,086
python
en
code
0
github-code
36