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
16044432406
import os from core.module import Plugin class SuyambuPlugin(Plugin): def __init__(self): Plugin.__init__(self) self.name = "Ngrok" self.description = "Use ngrok service to forward local port (Only supports HTTP traffic)" self.author = ["Jeeva"] self.options.add("lport", "...
whoisjeeva/suyambu-tool
plugins/ngrok.py
ngrok.py
py
1,019
python
en
code
0
github-code
13
24635520479
import sqlite3 from sqlite3 import Error def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d def get_db_connection(db): """ create a database connection to a SQLite database """ try: conn = sqlite3.connect(db) ...
alex-peresunko/svitlo
database.py
database.py
py
3,928
python
en
code
0
github-code
13
11098084805
player_name = input() max_points = 0 name = '' while player_name != "Stop": current_points = 0 for letters in player_name: number = int(input()) if letters == chr(number): current_points += 10 else: current_points += 2 if current_points >= max_points: ...
tanchevtony/SoftUni_Python_basic
More exercises/exam_6_7_july_2019/06. name game.py
06. name game.py
py
471
python
en
code
0
github-code
13
3463595801
from level1 import db from datetime import timedelta import re class IdiomImporter(object): def __init__(self, fp, date, name) -> None: super().__init__() self.name = name self.date = date or date.today() self.fp = fp # example: S9E10, S3 self.title_patten_re = re....
nanfang/level1
level1/importer.py
importer.py
py
1,554
python
en
code
0
github-code
13
22072754684
from src.crawl import DailyStock from src.data import StockData from src.config import read_config config = read_config() def run(request): stocks_latest = DailyStock() stock_data = StockData() if stock_data.is_date_dup(stocks_latest.closing_date): return "%s stock prices exist" % stock_data.la...
Chendada-8474/stock-homework
main.py
main.py
py
529
python
en
code
0
github-code
13
25942577925
import numpy as np class Material: def __init__(self, name, E, nu, alpha, f): self.name = name self.E = E # Youngs modulus [Pa] self.nu = nu # Poissons ratio [-] self.alpha = alpha # Thermal expansion coefficient self.f = f # Materia...
cladah/CoupledPhaseFramework
IntegratedSimulation/HelpFile.py
HelpFile.py
py
6,933
python
en
code
0
github-code
13
19056629946
import math def find_seat_id(commands): xrange = (0, 127) yrange = (0, 7) for command in commands: if command == "F": new_max = math.floor((xrange[0] + xrange[1]) / 2) xrange = (xrange[0], new_max) elif command == "B": new_min = math.ceil((xra...
jakewilliami/scripts
julia/Other/advent_of_code/2020/doov/05/v1.py
v1.py
py
876
python
en
code
3
github-code
13
17048286794
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AnttechBlockchainFinanceFsupvFundTransferModel(object): def __init__(self): self._fund_supv_task_id = None self._request_no = None self._transfer_amount = None sel...
alipay/alipay-sdk-python-all
alipay/aop/api/domain/AnttechBlockchainFinanceFsupvFundTransferModel.py
AnttechBlockchainFinanceFsupvFundTransferModel.py
py
2,791
python
en
code
241
github-code
13
30313362550
from unittest import TestCase from hamcrest import assert_that, contains_inanyorder, empty from unittest.mock import Mock from ..service import CallPermissionService class TestUpdate(TestCase): def setUp(self): self.confd = Mock() self.service = CallPermissionService(self.confd) def test_fi...
wazo-platform/wazo-ui
wazo_ui/plugins/call_permission/tests/test_service.py
test_service.py
py
1,190
python
en
code
4
github-code
13
23407772194
import os import google.protobuf as pb import google.protobuf.text_format from proto import efficient_pytorch_pb2 as eppb def main(): gene_base_template() def gene_base_template(): root_dir = os.getenv("CURRENT_DIR") # default values hyper = eppb.HyperParam() hyper.main_file = hyper.main_file ...
hustzxd/EagleEyeEFF
proto/gene_hyperparam_template.py
gene_hyperparam_template.py
py
4,027
python
en
code
6
github-code
13
14790098957
# © 2022 Gakuto Seyama # SPDX-License-Identifier: BSD-3-Clause import rclpy #ROS2のクライアントのためのライブラリ from rclpy.node import Node from std_msgs.msg import Int16 #通信の型(16ビットの符号付き整数) rclpy.init() node = Node("talker") pub = node.create_publisher(Int16, "countup", 10) n = 0 def cb(): #17行目で定期...
gaku-3319/mypkg
mypkg/talker.py
talker.py
py
560
python
ja
code
0
github-code
13
17495717097
# 1.py与2.py都用的是书上的例子作为测试 #利用字典来存储图 #用优先队列太麻烦了,其实就是选择与当前结点距离最小的点 # Dijkstra算法——通过边实现松弛 # 指定一个点到其他各顶点的路径——单源最短路径 # 初始化图参数 # 源节点为s G = {'s':{'t':10,'y':5}, 't':{'y':2,'x':1}, 'y':{'t':3,'x':9,'z':2}, 'x':{'z':4}, 'z':{'s':7,'x':6} } #在python中INITIALIZE-SINGLE-SOURCE函数可以省略,利用字典直接赋值,用65535表示正无穷 d = {'s':0, 't':65535,...
Miamiamiamyt/algorithms
算法/单源最短路径/1.py
1.py
py
1,287
python
zh
code
0
github-code
13
321508836
""" Pour obtenir les nombres premiers compris entre 2 et un certain entier N on va construire une liste chaînéee d’objets appelés des MangeNombres, chacun comportant deux variables d’instance : - un nombre premier - et une référence sur le MangeNombres suivant de la liste. Le comportement d’un MangeNombres se réduit à ...
aurao22/simplon
2021-11/2011-11-29/1_concepts_fondamentaux/4_mange_nombre.py
4_mange_nombre.py
py
1,400
python
fr
code
0
github-code
13
35345225444
import sys import os import re from PySide.QtGui import * from PySide.QtCore import * sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from UI.Raw.Artist_UI import Ui_ArtTools from Main.Core import worker from Main import Core from ExternalCalls import SlotsNewConversion class QTUIProject(QDialog,Ui_Ar...
underminerstudios/ScriptBackup
FlashArtPipeline/art_pipeline/UI/ArtistsUI.py
ArtistsUI.py
py
8,008
python
en
code
2
github-code
13
28383465195
##!/appl/easybuild/opt/Python/3.8.2-GCCcore-9.3.0/bin/python import pytools as pt import numpy as np from myutils import spherical_to_cartesian, cartesian_to_spherical, get_vlsvfile_fullpath, timer, save, mkdir_path, restore from carrington import get_all_cell_coordinates import matplotlib.pyplot as plt from numba imp...
kostahoraites/carrington
utils/biot_savart.py
biot_savart.py
py
29,150
python
en
code
0
github-code
13
12035789025
#!/usr/bin/env python # coding: utf-8 # In[1]: import os import re import zipfile import numpy as np import matplotlib.pyplot as plt import pandas as pd import json from glob import glob import xml.etree.ElementTree as ET # In[2]: def get_filename_dict(list_jpg): dict_dashlap_img = dict() for path_jpg ...
sogangori/data_loading
DashLap_lie.py
DashLap_lie.py
py
2,527
python
en
code
0
github-code
13
33987945784
#!/usr/bin/env python # -*- coding: utf-8 -*- import os.path import PyPDF2 import tabula import numpy import csv from decimal import Decimal from datetime import date from django.utils import timezone from docx import Document from .models import Plazo BASE = os.path.join(os.path.dirname(os.path.dirname(__file__)), 's...
OrlandoRodriguez93/reportes
apps/cartas/utils.py
utils.py
py
11,285
python
es
code
0
github-code
13
16179879285
import numpy as np import mdtraj as md from mdtraj.testing import eq random = np.random.RandomState(0) def compute_neighbors_reference(traj, cutoff, query_indices, haystack_indices=None): if haystack_indices is None: haystack_indices = range(traj.n_atoms) # explicitly enumerate the pairs of query-hay...
mdtraj/mdtraj
tests/test_neighbors.py
test_neighbors.py
py
1,848
python
en
code
505
github-code
13
8619704326
#CORNER DETECTION import cv2 import numpy as np from matplotlib import pyplot as plt #cv2.namedWindow("res") vc = cv2.VideoCapture(0) if vc.isOpened(): rval, frame = vc.read() else: rval = False while rval: gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) cv2.imshow('gray1',gray) #gray = np.f...
n-s405/Detect-Defects-in-Train-Tracks
29_06_shiTomassi-corner-testing-01.py
29_06_shiTomassi-corner-testing-01.py
py
762
python
en
code
3
github-code
13
12124228259
import cv2 import imgkit as imgkit class VideoCamera(object): def __init__(self): self.subtitle = "Some text" self.col = (100, 200, 100) # Using OpenCV to capture from device 0. If you have trouble capturing # from a webcam, comment the line below out and use a video file ...
qrzeller/RealTimeStatisticsOnLiveStream
app/video_streaming_with_flask_example/camera.py
camera.py
py
1,463
python
en
code
2
github-code
13
73282859539
import io import os import sys import json import time import pickle import logging import hashlib import threading import importlib import urllib.request # The multiprocessing module does not work correctly on Windows if sys.platform.startswith('win'): from multiprocessing.dummy import Pool, Manager thread_co...
BasioMeusPuga/Lector
lector/sorter.py
sorter.py
py
14,594
python
en
code
1,479
github-code
13
71297739538
from polygon import RESTClient import pandas as pd from datetime import datetime, timedelta pd.options.mode.chained_assignment = None def get_ticker_data(ticker, date): client = RESTClient("VxaBiHSENdZfJj1Ljm9dpoH5x7LYX1JF") minute_data = client.get_aggs(ticker, 1, "minute", date, date) minute_data = pd...
chuk1123/stock_bot
stock_data.py
stock_data.py
py
5,519
python
en
code
1
github-code
13
71687148818
from time import sleep from fastapi import FastAPI, Depends, Request, Query from fastapi.responses import HTMLResponse from fastapi.templating import Jinja2Templates from fastapi.staticfiles import StaticFiles from sqlmodel import select, Session from fastapi_htmx_template.db import get_session, create_db_and_tables...
jweckman/python_tutorials
templates/fastapi_htmx_template/main.py
main.py
py
1,561
python
en
code
0
github-code
13
165114924
from django.views.generic import ListView from mainapp.models import Product from .models import Order, Cart from django.shortcuts import render, get_object_or_404, redirect from django.contrib import messages # добавить в корзину товар def add_to_cart(request, slug): item = get_object_or_404(Product, slug=slug)...
ShadowLore/indigo
cart/views.py
views.py
py
4,375
python
en
code
0
github-code
13
21793040413
# -*- coding: utf-8 -*- """ Created on Sat May 23 16:55:43 2020 @author: lokopobit """ # Load external libreries import os, json from elasticsearch.helpers import parallel_bulk from collections import deque from tqdm import tqdm import time # import auxiliar_functions as auxFuns # def cle...
lokopobit/newspapers_analytics
clean_and_store.py
clean_and_store.py
py
8,819
python
en
code
1
github-code
13
39447238724
from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect from django.urls import reverse from .models import Aluno from .forms import AlunoForm # Create your views here. def Cadastrar_aluno(request): if request.method == 'POST': form = AlunoForm(request.POST) ...
heduardoPro/Atividade-Avaliativa-DSW
core/views.py
views.py
py
1,488
python
en
code
0
github-code
13
71800857937
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Example use of simpleDASreader8. The objective of this file is to illustrate basic processing of data using scipy.signal and saving to file """ import simpleDASreader import numpy as np import matplotlib.pyplot as plt import scipy.signal as sps import datetime,os ...
ASN-Norway/simpleDAS
examples/decimate_and_save.py
decimate_and_save.py
py
2,749
python
en
code
5
github-code
13
10173109285
#! /usr/bin/env python """ A partir de dos listas de enteros, 'numeros1' y 'numeros2', almacenar en una lista el resultado de multiplicar cada uno de los elementos de 'numeros1' por, a su vez, cada uno de los elementos de 'numeros2'. Es decir, la lista resultante tendra len(numeros1) * len(numeros2) elemen...
jmchema/CursoPython
Dia2/Ejercicio7.py
Ejercicio7.py
py
486
python
es
code
0
github-code
13
32059737451
import branca import folium import pandas as pd from flask import Flask app = Flask(__name__) @app.route('/') def index(): start_coords = (45.5236, -122.6750) folium_map = folium.Map(location=start_coords, zoom_start=3) data = pd.read_csv("data-edited.csv") data_frame = pd.DataFrame(data, columns=['...
1000monkeys/CoronaDashboard
main.py
main.py
py
1,416
python
en
code
0
github-code
13
35214332834
import pygame class TwoWayDict(dict): def __setitem__(self, key, value): # Remove any previous connections with these values if key in self: del self[key] if value in self: del self[value] dict.__setitem__(self, key, value) dict.__setitem__(self, valu...
vinaykudari/LiftSimulator
app.py
app.py
py
3,426
python
en
code
1
github-code
13
30907718154
from datetime import date from odoo.exceptions import ValidationError from odoo.tests import common class HousingCooperativeCase(common.TransactionCase): def setUp(self): super(HousingCooperativeCase, self).setUp() self.lease1 = self.env.ref("housing_cooperative_base.demo_lease_1") self.l...
coopiteasy/vertical-housing-cooperative
housing_cooperative_base/tests/test_housing_cooperative.py
test_housing_cooperative.py
py
5,289
python
en
code
1
github-code
13
20499935897
import time, random, timeit # list generator def createList(): random.seed(a=None, version=2) list1 = list(i for i in range(10000)) random.shuffle(list1) return list1 # selection sorting def selectionSort(li:list): for i in range(len(li)): minIdx = i for j in range(i...
PKTOSE/2022_1PG
HW16/source4.py
source4.py
py
2,048
python
en
code
0
github-code
13
36734766654
from django.test import TestCase from django.utils import timezone from django.urls import reverse from .models import Post from django.contrib.auth.models import User class PostTestCaseBase(TestCase): def setUp(self): self.user = User.objects.create_user(username='tanja') class PostModelTest(PostTestC...
ZandTree/diary
post/tests.py
tests.py
py
2,373
python
en
code
0
github-code
13
3014855380
""" File Name: pair.py Author: Ameya Shringi as6520@g.rit.edu Vishal Garg """ class Pair: """ Data Structure that represents the pair of matches """ __slots__ = 'frame1', 'frame2', 'matches',\ 'fundamental_matrix', 'essential_matrix',\ 'projection_matrix_1', 'proj...
as6520/three-dimension-reconstruction
pair.py
pair.py
py
1,092
python
en
code
3
github-code
13
43114658292
# 정확한 순위 import sys import heapq input = sys.stdin.readline INF = int(1e9) n, m = map(int, input().split()) # n : 학생수(노드 수), m : 성적비교횟수(간선의 수) # 다익스트라? 플로이드워셜? => 플로이드 워셜 v # 플로이드 워셜 graph = [[INF] * (n + 1) for _ in range(n + 1)] for a in range(1, n+1): for b in range(1, n+1): if a == b: graph[a][b] =...
jinhyungrhee/Problem-Solving
NDB/NDB_1738_정확한순위.py
NDB_1738_정확한순위.py
py
2,543
python
ko
code
0
github-code
13
31384318800
# Histogram Computation import cv2 as cv import matplotlib.pyplot as plt import numpy as np img = cv.imread("Photos/mei.jpg") img = cv.resize(img, (500,700), interpolation=cv.INTER_AREA) #INTER_AREA/LINER/CUBIC cv.imshow("Resize",img) gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) #Grayscale Histogram gray_hist= cv.calc...
Justinfungi/AI_Computer_Vision
Myopencv/Opencv4_Hist_Color.py
Opencv4_Hist_Color.py
py
2,452
python
en
code
2
github-code
13
25532019467
from bs4 import BeautifulSoup as soup from urllib.request import urlopen as uReq my_url = 'https://www.met.ie/forecasts/dublin' #open connection and download html uClient = uReq(my_url) page_html = uClient.read() page_soup = soup(page_html, "html.parser") for_info = page_soup.find(class_="forecast") #...
lukehebb1/weather.py
weather.py
weather.py
py
695
python
en
code
0
github-code
13
21358401079
import os import signal import threading from tkinter import * from tkinter.scrolledtext import ScrolledText from PIL import Image, ImageTk from tkinter.filedialog import askdirectory import base64 from pictures.cat_logo import img as logo from platforms import * class GUIOperate(object): # 运行GUI @staticmethod def...
sugarfz/Video_Crack
gui.py
gui.py
py
8,758
python
en
code
0
github-code
13
44162233255
#Crie um programa que leia uma frase qualquer e diga #Se ela é um palindromo, desconsiderando os espaços. #Crie um programa que leia uma frase qualquer e diga #Se ela é um palindromo, desconsiderando os espaços. frase = str(input('Digite uma frase: ')).upper().strip() palavras = frase.split() junto =''.join(palavras) ...
jamissi/expython
Desafio053-Palindromo.py
Desafio053-Palindromo.py
py
585
python
pt
code
1
github-code
13
13036861867
import discord from discord.ext import commands from dotenv import load_dotenv import diceroller load_dotenv() TOKEN = os.getenv("DISCORD_TOKEN") client = discord.Client() @client.event async def on_ready(): print(f"{client.user} has connected to Discord!") bot = commands.Bot(command_prefix='/') @bot.command(...
SwampFalc/FriendComputer
bot.py
bot.py
py
466
python
en
code
0
github-code
13
41885777525
import requests class Robot: def __init__(self, ip): self.host = "http://" + ip + "/api/v2.0.0/" file = open('address.txt', 'r+') ignore, auth = file.readlines() file.close() auth = auth.rstrip('\n') self.headers = {"Content-Type": "application/json", "Authorization...
haydenisaac/PythonToPLC
robot.py
robot.py
py
2,512
python
en
code
0
github-code
13
36162345415
# ================================================== [ setting ] ================================================== import re word = "grail" sent = "a scratch" # print(word[0:3]) # print(sent[2:-1]) # print(sent[2:len(sent)]) # print(sent[2 :]) # print(sent[ ::2]) # print("black Knight".capitalize()) # ...
KimJiSeong1994/Changwon_DataAnalysis_Study_Group
Book/Do it Pandas/지성/9. string preprocessing.py
9. string preprocessing.py
py
3,114
python
en
code
1
github-code
13
15954075305
# -*- coding: UTF-8 -*- ''' get the query field name(字段名) ''' def field_name_list(filename,name_list): from module.staff_list import staff_list_get staff_list = staff_list_get(filename) if name_list[0] == '*': field_get_name=staff_list[0].split(",") else: field_get_name=name_list[1].s...
Bigberg/python
day4--员工信息管理/Staff/module/get_field_name.py
get_field_name.py
py
550
python
en
code
0
github-code
13
20781955685
from extract import Payload from transform import Mapper from load import Store from threading import Thread if __name__=="__main__": Yep = Payload() t1=Thread(target=Yep.get()) t2=Thread(target=Yep.unzip()) t3=Thread(target=Mapper) t4=Thread(target=Store) t1.start() t2.start() t3.start...
Data-Visualization-Analytics/image_processing
pipeline/project_image_processing/main.py
main.py
py
394
python
en
code
1
github-code
13
72943549458
# digits = '' # letters = '' # other = '' # # text = input() # for char in text: # if char.isdigit(): # digits += char # elif char.isalpha(): # letters += char # else: # other += char # print(digits) # print(letters) # print(other) import sys from io import StringIO input1 = """Ag...
Andon-ov/Python-Fundamentals
22_text_processing_lab/digits_letters_and_other.py
digits_letters_and_other.py
py
597
python
en
code
0
github-code
13
455199242
import requests from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry from .utils import log def deploy_ping(api_key: str, site_id: str, note: str, detail: str): """Based on https://api.speedcurve.com/#add-a-deploy""" data = { "site_id": site_id, } i...
piotrtomiak/yari
deployer/src/deployer/speedcurve.py
speedcurve.py
py
855
python
en
code
null
github-code
13
71616361619
example = { 'iceberg': ['cold', 15, {'a', 'b'}, 33.98, 15 / 2, False], 'fire': ['hot', 46, ['cha', 'ching'], 81.13], 'earth': ['solid', 100, (13, 31, 1), 90.01, {'b': 'c'}] } elements = ['fire', 'storm', 'cloud', 'iceberg', 'volcano', 'earth'] def func(dct, lst): for i in lst: try: ...
ulukbek-bolot-uulu/HW_2.5
HW_2_5_1.py
HW_2_5_1.py
py
623
python
en
code
0
github-code
13
9856577084
import smartpy as sp @sp.module def main(): class SpekunContract(sp.Contract): def __init__(self): self.data.sepeda = {} self.data.peminjam = sp.set() @sp.entrypoint def add_sepeda(self, params): assert not self.data.sepeda.contains(params.id_sepeda)...
fadhilrasendriya/spekun-tezos
contract/spekun_contract.py
spekun_contract.py
py
1,745
python
id
code
0
github-code
13
70761876819
values = [] def addValues(arrayLen): for i in range (arrayLen): values.append(int(input("Insira o " + str(i+1) + "º valor da lista: "))) def sortInAscendingOrderAndPrint(array): for i in range(len(array)-1): for j in range(i+1, len(array)): if array[i] > array[j]: ...
LiajuX/Python-Exercises-2020
Arquivo16-Ex.3.py
Arquivo16-Ex.3.py
py
1,332
python
pt
code
0
github-code
13
36983887553
import datetime import random from dateutil.relativedelta import relativedelta from django.db.models import F from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from django.utils.text import slugify from .models import * @receiver(post_save, sender=Order) def update_order(...
Suboms/data_analysis
dataset/signals.py
signals.py
py
1,696
python
en
code
1
github-code
13
25933036595
from socket import * def headerClient(connfd): request = connfd.recv(4096).decode() #print('connection from %s' % connfd.getpeername()) print(request) response = 'HTTP/1.1 200 ok' response += '' response += '\r\n' f = open('baidu.html',encoding='utf-8') data = f.read() ...
Ahead180-103/ubuntu
python/shell.py/pynet/http1.1_proto/http_base.py
http_base.py
py
793
python
en
code
0
github-code
13
38002318668
from BTagging.BTaggingFlags import BTaggingFlags def buildDL1(basename): metaInstance = { 'IsATagger' : False, 'xAODBaseName' : basename, 'DependsOn' : ['AtlasExtrapolator', 'BTagCalibrationBrokerTool', ...
rushioda/PIXELVALID_athena
athena/PhysicsAnalysis/JetTagging/JetTagAlgs/BTagging/python/BTaggingConfiguration_DL1Tag.py
BTaggingConfiguration_DL1Tag.py
py
2,444
python
en
code
1
github-code
13
32467385429
# Today we have: Convert Roman Numerals to Decimal # # Given a Roman numeral, find the corresponding decimal value. Inputs will be between 1 and 3999. # # Example: # Input: IX # Output: 9 # # Input: VII # Output: 7 # # Input: MCMIV # Output: 1904 # # I : 1 # V : 5 # X : 10 # L : 50 # C : 100 # D : 500 # M : 1000 # So ...
DBasoco/Daily-Interview-Pro
2020-09-25.py
2020-09-25.py
py
2,650
python
en
code
1
github-code
13
26695433704
import json import os from pydantic import constr, root_validator from model_dataclass.constants import VALID_ACTIONS from pydantic.dataclasses import dataclass, Optional from pydantic.json import pydantic_encoder StageName = os.environ.get('StageName') @dataclass class PushNotificationTemplateModel: id: Optio...
masudur-rahman-niloy/social-signin
lambda_layers/global_utils/python/model_dataclass/push_notification_template_model.py
push_notification_template_model.py
py
1,270
python
en
code
0
github-code
13
7425535402
from django.db import models from django.contrib.auth.models import User from contract.models import Contract class EventStatus(models.Model): label = models.CharField(max_length=128, blank=False) class Meta: verbose_name_plural = "Event status" def __str__(self): return self.label class Event(models.Mode...
XavierCoulon/OC-P12-Epic-Events-V2
src/event/models.py
models.py
py
869
python
en
code
0
github-code
13
1300445662
import json from subprocess import check_output, STDOUT from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def index(): cards = json.loads(open('data/former.txt', 'r').read()) return render_template('index.html', cards=cards, card_len = len(cards)) @app.route('/contact', methods...
NLQuy/CTFWU
2023/KMACTFIII/WelcomeToKCSC/run.py
run.py
py
724
python
en
code
1
github-code
13
7158074000
import unittest from src.pub import Pub from src.drink import Drink from src.customer import Customer class TestPub(unittest.TestCase): def setUp(self): self.pub = Pub("Ox", 100.00) self.customer_1 = Customer("David", 50.00) self.drink_beer = Drink("Beer", 5.00) self.drink_wine = D...
CatAnderson/python_pub_lab
pub_lab/tests/pub_test.py
pub_test.py
py
1,996
python
en
code
0
github-code
13
29624190032
# ---------------------------------------------------------------------------- # # TITLE - tasks.py # AUTHOR - James Lane edited from Steve Mairs # PROJECT - archipelago # CONTENTS: # 1. KillNoisyEdges # 2. GetInOrion # 3. GetDistance # 4. GetAnalysisFiles # 5. ZipAnalysisFiles # 6. StackCatalogs # 7. NanTo...
jamesmlane/Archipelago
tasks.py
tasks.py
py
13,825
python
en
code
0
github-code
13
3721087980
''' Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order. ''' ''' 트리의 왼쪽 하위 노드는 루트보다 작다 트리의 오른쪽 하위 노드는 루트보다 크다 ''' class Solution: # reference : jose14520 def generateTrees(self, n: int) -> L...
JaeEon-Ryu/Coding_test
LeetCode/0095_ Unique Binary Search Trees II.py
0095_ Unique Binary Search Trees II.py
py
1,570
python
en
code
1
github-code
13
28680158745
import sys from typing import List from collections import deque input = sys.stdin.readline #dfs 풀이는 간단할거같고.. #bfs 위상정렬 풀이로 풀어보면... #일단 1에서 시작 --> indegree가 0인 애들은 갱신 종료 --> #쭉 진행하면서 final DP값만 취하기 ansRoute = [1] def backTracking(node : int) -> List: # 거슬러 올라가기 #하나만 취하면 되므로 그냥 쭉쭉 따라가면 됨 global ansRoute ...
hodomaroo/BOJ-Solve
백준/Gold/2611. 자동차경주/자동차경주.py
자동차경주.py
py
1,528
python
ko
code
2
github-code
13
71881778259
import pandas as pd import numpy as np #Conta a quantidade de vitórias e pole position por piloto #Abertura dos arquivos de dados CSV f1_results = pd.read_csv("analise_f1\\f1_data\\results.csv") drivers = pd.read_csv("analise_f1\\f1_data\drivers.csv") drivers_reduced = drivers.drop(columns=['dob', 'url']) #Retira dad...
lucasbraide/analise_dados
analise_f1/win_pole_count.py
win_pole_count.py
py
2,145
python
pt
code
0
github-code
13
72947641619
import torch import torch.nn as nn import torch.optim as optim import torch.multiprocessing as mp import torch.nn.functional as F # Define Actor-Critic Network # class ActorCritic(nn.Module): # def __init__(self, input_size, output_size): # 8 * n | 3 * n # super(ActorCritic, self).__init__() # sel...
RuihanRZhao/Efficiency_RL
src/NeuralNet/a3c_torch/v_1_0_0/neural_network.py
neural_network.py
py
2,246
python
en
code
2
github-code
13
2870601251
from rknnlite.api import RKNNLite import cv2 import numpy as np def show_outputs(output): output_sorted = sorted(output, reverse=True) top5_str = "\n-----TOP 5-----\n" for i in range(5): value = output_sorted[i] index = np.where(output == value) for j in range(len(index)): ...
xuesongzh/learn-ai
npu/RKNN Tooklit2/06_rknntoolkitlite2/rknntoolkitlite2.py
rknntoolkitlite2.py
py
1,297
python
en
code
0
github-code
13
29008236530
import numpy as np import argparse from common.functionutil import makedir, join_path_names, list_files_dir, basename, get_substring_filename, \ get_regex_pattern_filename, find_file_inlist_with_pattern from dataloaders.imagefilereader import ImageFileReader from imageoperators.imageoperator import NormaliseImage...
antonioguj/bronchinet
src/scripts_util/create_movie_slicesCT_with_masks.py
create_movie_slicesCT_with_masks.py
py
5,422
python
en
code
42
github-code
13
4043820646
# Определить индексы элементов массива (списка), значения которых принадлежат заданному диапазону # (т.е. не меньше заданного минимума и не больше заданного максимума) def fill_the_list(a, list): list = [] for i in range(a): list.insert(i, int(input("Введите элемент массива: "))) return list def ...
DonGaetano/HW-Python
SEM6/Task32.py
Task32.py
py
1,118
python
ru
code
0
github-code
13
24899436377
import sys import re if len(sys.argv) == 3: if not sys.argv[2].isnumeric(): sys.exit('Error') minLen = int(sys.argv[2]) new_list = re.sub(r'[^a-zA-Z\d\s]', '', sys.argv[1]).split() test = ['done', 'test'] print([c for c in new_list if len(c) > minLen]) else: sys.exit('Error')
alizaynoune/python_modules
Module00/ex07/filterwords.py
filterwords.py
py
311
python
en
code
0
github-code
13
28403529801
# 1. Using Selenium WebDriver, open the web browser. # 2. Maximize the browser window. # 3. Navigate to https://en.wikipedia.org/ (Links to an external site.) web URL # 4. Check URL and title are as expected. # 5. In a search field, find searchInput and click on it. # 6. Check that the title Python (programming languag...
wenlingdou/Wikipedia
wikipedia.py
wikipedia.py
py
2,904
python
en
code
0
github-code
13
14505432487
import unittest from egat.test_runner_helpers import WorkProvider class MockWorkNode(): resources = [] i = None class TestGetNextNode(unittest.TestCase): def test_empty_work_pool(self): wp = WorkProvider() self.assertIsNone(wp.get_next_node()) def test_empty_work(self): wp = W...
egineering-llc/egat
tests/egat/test_work_provider.py
test_work_provider.py
py
972
python
en
code
4
github-code
13
9070177197
lost_fights = int(input()) helmet_price = float(input()) sword_price = float(input()) shield_price = float(input()) armor_price = float(input()) helmet_repairs = (lost_fights // 2) * helmet_price sword_repairs = (lost_fights // 3) * sword_price shield_repairs = (lost_fights // 6) * shield_price armor_repairs = (lost_f...
vbukovska/SoftUni
Python_fundamentals/Data_Types_and_Variables/GladiatorExpenses.py
GladiatorExpenses.py
py
486
python
en
code
0
github-code
13
35184339337
import os from strategy import * from player import Player from base_options import * def main(): root = os.path.dirname(os.path.abspath(__file__))[:-5] # removes /code opt = BaseOptions().parse(BaseOptions.IPD2P) NUM_ITER = opt.niter NUM_PLAYERS = opt.nplay NUM_REPETITIONS = opt.nrep FIXED = ...
eliabntt/iterative_prisoner_dilemma
code/ipd2p.py
ipd2p.py
py
5,642
python
en
code
3
github-code
13
29516695032
import numpy as np import cv2 import os dirname = 'detectedCodes' os.mkdir(dirname) img = cv2.imread("pcf0000.png") imgContours = img.copy() cv2.imshow('',img) #PREPROCESSING! imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) imgBlur = cv2.GaussianBlur(imgGray,(5,5),1) imgCanny = cv2.Canny(imgBlur,10,50) #############...
raghavddps2/Technical-Interview-Prep-1
OpenCV/ImageCombination/detect.py
detect.py
py
1,749
python
en
code
0
github-code
13
12926509992
#!/usr/bin/python import os,sys; from acommon import *; context = Context(os.getcwd()); if (context.processArgv(sys.argv) or context.hasNoPlatform()): sys.exit(-1); # Check if this is not really a sync to another path (target and source are same)) if (context.TARGET_DEBUG_32 == context.DEBUG_32): if (context.ver...
achacha/AOS
_devtools/bin/gather_binaries_AObjectServer.py
gather_binaries_AObjectServer.py
py
1,283
python
en
code
1
github-code
13
16276286194
from utils import * # 三维平面, 要求X,Y都是二维的 x = np.linspace(0, 10, 20) y = np.linspace(2, 8, 20) X, Y = np.meshgrid(x, y) Z = 2 * X + 5 * Y + 3 print(x, y) print(X, Y) print(Z) fig = plt.figure(figsize=(14, 10)) axes = fig.add_subplot(int(f'111'), projection='3d') axes.plot_surface(X, X + 1, Y, cmap="cool") # axes.plot(x...
MosRat/BnuMcLab
MCExp1/Lesson2/code/plot_3d.py
plot_3d.py
py
376
python
en
code
1
github-code
13
22102455162
import torch import torch.nn as nn from typing import Tuple, Union from configs import Config class SimpleAC(nn.Module): def __init__(self, states: int, actions: Union[Tuple[int], int], hidden_n=64, obs_capacity=1): super().__init__() num_decisions, num_actions = actions if isinstance...
Jlevan25/rl
models/simple_nn.py
simple_nn.py
py
1,354
python
en
code
0
github-code
13
9875097637
import pyodbc import os import XmlGenerator as xml_creator import subprocess import datetime import time import base64 from rauth import OAuth2Service import json import requests import getpass import xmltodict conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\PUNTOVENTA\...
ambonilla/hermes
DocsVerifier.py
DocsVerifier.py
py
9,766
python
en
code
0
github-code
13
12084755093
# -*- coding: utf-8 -*- from http.server import HTTPServer from http.server import BaseHTTPRequestHandler from http import HTTPStatus from urllib import parse code = '' domain = '127.0.0.1' port = 5050 url = 'http://' + domain + ':' + str(port) + '/' class MyHandler(BaseHTTPRequestHandler): def do_GET(self): ...
ryotosaito/box-sync-for-python
redirect_server.py
redirect_server.py
py
1,187
python
en
code
0
github-code
13
28409246153
from books.models import Request class WriteRequestMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): data = request.__dict__ Request.objects.create(method=data.get("method"), path=data.get("path")...
Taniadz/shop
books/middleware.py
middleware.py
py
592
python
en
code
1
github-code
13
5185510446
import stochsticLibrary as lib import numpy as np from state import State import fisherSolver as solver # Assigned probbaility of transition between states num_states = 5 assigned_prob = np.random.rand(num_states, num_states) def evaluate_policies(discount, states, initial_distribution, max_iters, prices_policy, de...
Sadie-Zhao/Stochastic-Min-Max-Stackelberg-ICRL
stochasticAlg.py
stochasticAlg.py
py
17,460
python
en
code
4
github-code
13
18750147485
from docproduct.predictor import RetreiveQADoc pretrained_path = 'model_artifacts/BioBertFolder/biobert_v1.0_pubmed_pmc/' bert_ffn_weight_file = 'model_artifacts/newFolder/models/bertffn_crossentropy/bertffn' embedding_file = 'model_artifacts/Float16EmbeddingsExpanded5-27-19.pkl' doc = RetreiveQADoc(pretrained_path=p...
MohamedAbdultawab/remedy_api
model.py
model.py
py
530
python
en
code
1
github-code
13
23024202492
from flask import request, url_for, redirect, flash, abort, current_app, Flask from werkzeug import DispatcherMiddleware from flask_login import current_user from functools import wraps #See: #https://stackoverflow.com/questions/36269485/how-do-i-pass-through-the-next-url-with-flask-and-flask-login def handle_needs_lo...
Gastron/captaina-web
captaina/utils.py
utils.py
py
2,651
python
en
code
3
github-code
13
74633347538
import discord import logging import os from utils.bot import MusicBot logging.basicConfig(level=logging.INFO) logger = logging.getLogger("discord") handler = logging.FileHandler(filename="discord.log", encoding="utf-8", mode="w") handler.setFormatter(logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(message...
XoutDragon/Discord-Music-Bot
main.py
main.py
py
629
python
en
code
0
github-code
13
37985603008
from Digitization.DigitizationFlags import jobproperties from AthenaCommon import CfgMgr # The earliest bunch crossing time for which interactions will be sent # to the TgcDigitizationTool. def TGC_FirstXing(): return -50 # The latest bunch crossing time for which interactions will be sent # to the TgcDigitizatio...
rushioda/PIXELVALID_athena
athena/MuonSpectrometer/MuonDigitization/TGC_Digitization/python/TGC_DigitizationConfig.py
TGC_DigitizationConfig.py
py
1,779
python
en
code
1
github-code
13
18684713232
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np def keypoints_to_heatmap_labels(keypoints, rois, num_kps=17, heatmap_size=56): """Encode keypoint location in the target heatmap for use in S...
whjzsy/SiamRCNN
utils/keypoint_rcnn.py
keypoint_rcnn.py
py
5,178
python
en
code
null
github-code
13
73288792659
@virtual_numbers_app.route('/export-subscribers', methods=['GET']) def export_subscribers(): beacon_columns = [ 'beacon_id', 'uuid', 'major', 'minor', 'beacon_type_id', 'latest_battery_level', 'merchant_id', 'beacon_id' ] search_filter = {} if rec_search_val is not None: search_filter['$or'] = [] ...
edward01/my-snippets
python/export_csv.py
export_csv.py
py
1,075
python
en
code
0
github-code
13
17040122644
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.UniversalKeyword import UniversalKeyword class AlipayEcoCityserviceMessageUniversalSendModel(object): def __init__(self): self._keyword_list = None self._mess...
alipay/alipay-sdk-python-all
alipay/aop/api/domain/AlipayEcoCityserviceMessageUniversalSendModel.py
AlipayEcoCityserviceMessageUniversalSendModel.py
py
3,670
python
en
code
241
github-code
13
42994522889
#!/usr/bin/env python # # Create a Configuration from marlin_config.json # import json import sys import shutil opt_output = '--opt' in sys.argv output_suffix = '.sh' if opt_output else '' if '--bare-output' in sys.argv else '.gen' try: with open('marlin_config.json', 'r') as infile: conf = json.load(infi...
MarlinFirmware/Marlin
buildroot/share/PlatformIO/scripts/mc-apply.py
mc-apply.py
py
2,929
python
en
code
15,422
github-code
13
12551384207
import aws_cdk.aws_ec2 as ec2 import aws_cdk.aws_s3 as s3 import aws_cdk.aws_ecr as ecr from aws_cdk import Stack, Tags from constructs import Construct class BilenivarInfraStack(Stack): def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwar...
yamansener199/bilenivar-infra
bilenivar_infra/bilenivar_infra_stack.py
bilenivar_infra_stack.py
py
1,939
python
en
code
0
github-code
13
43111196450
import sys from argparse import ArgumentParser import nltk from nltk.corpus import stopwords from nltk.tokenize import word_tokenize import math import string import collections as co """ Class for calculating term and document frequency """ class Words: """ Displaying term and document frequency fo...
mruiz99/TFDFer
tfdfer.py
tfdfer.py
py
10,057
python
en
code
0
github-code
13
45195069516
from zad2testy import runtests class Node: def __init__(self): self.left = None self.right = None self.parent = None self.c = 0 self.w = '' def create_tree(L): x = Node() for i in L: p = x for j in range(len(i)): if i[j] == '0' and p.l...
kkorta/ASD
egzaminy/2020\2021/3/2.py
2.py
py
1,592
python
en
code
0
github-code
13
8801620856
import argparse from collections import Counter parser = argparse.ArgumentParser() parser.add_argument('text_file') parser.add_argument('out_file') args = parser.parse_args() flatten = lambda l: [item for sublist in l for item in sublist] with open(args.text_file) as fp: lines = fp.read().splitlines() sents = [...
Chung-I/s5-taibun-aug
local/gen_vocab_from_text.py
gen_vocab_from_text.py
py
549
python
en
code
1
github-code
13
330735726
import pandas as pd import pytest from phillydb.tables import ( PhillyCartoQuery, RealEstateTaxRevenue, ) from phillydb.testing_utils import maybe_monkeypatch_response def test_real_estate_tax_revenue(opa_account_numbers, monkeypatch, pytestconfig): tx_rv = RealEstateTaxRevenue() if not pytestconfig....
ssuffian/phillydb
tests/test_tables.py
test_tables.py
py
939
python
en
code
1
github-code
13
27642286894
import cv2 as cv import time video = cv.VideoCapture('videos/carPark.mp4') if not video.isOpened(): print('Erro ao carregar o vídeo.') exit() image_count = 1 while True: ret, image = video.read() #Rotina para verificar se o vídeo chegou ao fim e então terminar o loop ou reiniciar o vídeo if not r...
CarlosAlfredoOliveiraDeLima/carpark-monitoring-computer-vision
utils/crop_ROIs_video.py
crop_ROIs_video.py
py
3,775
python
en
code
0
github-code
13
42809937781
import re from flask import Response, jsonify, make_response from marshmallow.exceptions import ValidationError from sqlalchemy.exc import IntegrityError from common.constants.exceptions import SqlalchemyExceptionConstants from common.constants.http import HttpStatusCodeConstants from common.schemas.response import ...
BorodaUA/practice_api_server
utils/exceptions.py
exceptions.py
py
2,726
python
en
code
0
github-code
13
25474332412
from flask import Flask, request, jsonify from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow import os app= Flask(__name__) # Tester code to see if app is working. make sure you are in a pipenv shell and run your script # @app.route('/') # def hello(): # return "Got Here" # if _...
genesisschaerrer/journal-api
app.py
app.py
py
3,514
python
en
code
0
github-code
13
43911947395
# -*- coding: utf-8 -*- #USING USER INPUT TO CALCULATE AGE - SOME EXAMPLES OF STRING METHODS, TRY/EXCEPT import datetime now = datetime.datetime.now() currentyear = now.year def hello_world(): name = input("Please type your name: ").title() if (name.isdigit()): print("Oops, please only type letters"...
mabely/module2
ch03_functions_importing/ch3file3_mabel_age_calc.py
ch3file3_mabel_age_calc.py
py
743
python
en
code
0
github-code
13
24703943314
""" @Author: odedkushnir """ import pandas as pd import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import seaborn as sns import pathlib def main(): # For Local Run suffix = "CVB3-p2.freqs" dir_path = "/Volumes/STERNADILABTEMP$/volume1/okushnir/Cirseq/CV/20170802_...
SternLabTAU/SternLab
scripts/Median_mutation_rates_human_rrna.py
Median_mutation_rates_human_rrna.py
py
3,342
python
en
code
1
github-code
13
37269070510
import os f = open(os.path.dirname(__file__) + "/input.txt", "r") links = [] for line in f.readlines(): links.append([int(x) for x in line[line.index("<->") + 4:].split(",")]) visited = set() def visit(node, queue): if node in visited: return visited.add(node) queue.extend(links[node]) group...
vakrilov/advent-of-code
2017/12/solve2.py
solve2.py
py
502
python
en
code
0
github-code
13
3299850039
import torch import numpy as np import pickle from torch.utils.data import Dataset, DataLoader # from pytorch_FFNN_example import Net, retrieveHandWritingData from CNN_PyTorch_Homebrew import Net import CNN_PyTorch_Homebrew def loadModel(model_no): if model_no == 1: filepath = './FFNN_Model.dat' elif m...
RutvikPansare/Handwriting-Recognition-Using-Pytorch
NN_Confusion_Matrix.py
NN_Confusion_Matrix.py
py
2,223
python
en
code
0
github-code
13
1791707001
import requests import re import random import wikipedia import unicodedata as ud PLUGINS = [] def plugin(regexp): def decorator(fn): PLUGINS.append((regexp, fn)) return fn return decorator http = requests.Session() def yahoo_url(pairs): return "https://query.yahooapis.com/v1/public/yql?q=" \ "s...
szastupov/her
plugins.py
plugins.py
py
3,473
python
en
code
2
github-code
13
70858408018
import numpy as np def uniquant(X, delta, thr, y_max=None): """ uniquant Uniform scalar quantizer (or inverse quantizer) with threshold Note: Use three arguments for inverse quantizing and four arguments for quantizing. Y = uniquant(X, del, thr, ymax); quantizer X = uniquant(Y, de...
DomChennnn/Dict_Coding
uniquant.py
uniquant.py
py
1,372
python
en
code
2
github-code
13