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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
70521198099 | #run code GPIOZERO_PIN_FACTORY=pigpio PIGPIO_ADDR=192.168.1.130 python3 test.py
# sudo pigpiod
from gpiozero import PWMLED
from time import sleep
from pynput import keyboard
forward = PWMLED(19)
reverse = PWMLED(13)
left = PWMLED(6)
right = PWMLED(5)
led = PWMLED(26)
speed = 1
steer = 1
def on_press(key):
try:
... | Herant/piDrv | as-built/Test_files/manual_control.py | manual_control.py | py | 1,781 | python | en | code | 3 | github-code | 13 |
41831003929 | import numpy as np
import matplotlib.colors as colors
def hsv_distance(color1, color2):
"""
Converts RGB colors to HSV and computes the distance between them in
cartesian coords.
Args:
color1: Unnormalized RGB color 1 (0-255)
color2: Unnormalized RGB color 2 (0-255)
Returns:
... | imwendi/METR4202-Team-14 | src/vision/color_utils.py | color_utils.py | py | 1,157 | python | en | code | 2 | github-code | 13 |
26413470492 | # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json
import sqlalchemy
import win32com.client as win32
from sqlalchemy import create_engine
from sqlalchemy.ext.declarat... | Gaojunsu/coolscrapy | coolscrapy/pipelines.py | pipelines.py | py | 1,893 | python | en | code | 0 | github-code | 13 |
37657154014 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import cv2
import numpy as np
import scipy
from scipy.ndimage import convolve
from scipy import signal
# In[2]:
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
import matplotlib.image as mpig
# In[3]:
blade=mpig.imread("C:/Us... | Enish258/MLand-DL | Canny edge detection without opencv.py | Canny edge detection without opencv.py | py | 3,997 | python | en | code | 1 | github-code | 13 |
31237208189 | def homework_6(nodes): # 請同學記得把檔案名稱改成自己的學號(ex.1104813.py)
# 請使用 Prim Algorithms / Kruskal Algorithms
l = len(nodes)
lst = []
for i in range(l-1): #將座標點之間的距離算出來
for j in range(i+1, l):
path = abs(nodes[i][0]-nodes[j][0])+abs(nodes[i][1]-nodes[j][1]) #abs:絕對值
lst.... | daniel880423/Member_System | file/hw6/1100317/hw6_s1100317_0.py | hw6_s1100317_0.py | py | 1,123 | python | en | code | 0 | github-code | 13 |
31201073418 | import bson
import datetime
import mongoengine as me
import six
from st2common.util import mongoescape
from st2common.models.system.common import ResourceReference
__all__ = [
'StormFoundationDB',
'StormBaseDB',
'EscapedDictField',
'TagsMixin',
'TagField',
'ContentPackResourceMixin'
]
JSON_UN... | gtmanfred/st2 | st2common/st2common/models/db/stormbase.py | stormbase.py | py | 3,727 | python | en | code | null | github-code | 13 |
10053191967 | # -*- encoding: utf-8 -*-
import re
from datetime import date, datetime
from decimal import Decimal
from django import template
from django.conf import settings
from django.template import defaultfilters
from django.utils.encoding import force_text
from django.utils.formats import number_format
from django.utils.saf... | fruitschen/fruits_learning | stocks/templatetags/money.py | money.py | py | 2,823 | python | en | code | 1 | github-code | 13 |
19628992003 | from django.shortcuts import render
from django.http import HttpResponse
from datetime import datetime
from django.template import Template, Context, loader
from appvet.models import *
from appvet.forms import *
# Create your views here.
#vista de la pagina inicio
def vista_inicio(request):
return render(request,... | ClEsteban/Entrega1Esteban | Entrega1Esteban/appvet/views.py | views.py | py | 3,152 | python | es | code | 0 | github-code | 13 |
42138462777 | import numpy as np
class Checkerboard:
def __init__(self):
self.state = np.zeros((3, 3), dtype=int)
self.is_live = True
def update(self, coordinates, player):
(i, j) = coordinates
self.state[i - 1, j - 1] = player
# check if game now over
diagonal_1 = self.state[0, 0] * self.state[1... | DanielBraddock/toe-tac-tic | checkerboards.py | checkerboards.py | py | 1,281 | python | en | code | 0 | github-code | 13 |
31492559127 | from django.contrib.auth import authenticate, login, logout, get_user_model
from django.db import IntegrityError
from rest_framework import status, viewsets, permissions
from rest_framework.views import APIView
from rest_framework.decorators import action
from rest_framework.response import Response
from user.serializ... | xxnpark/snucse | Waffle Studio/Django/Seminar 2/waffle_backend/user/views.py | views.py | py | 5,942 | python | en | code | 0 | github-code | 13 |
12805885013 | day_of_week = input("Enter a day:").lower()
if day_of_week == "monday":
print("Monday")
elif day_of_week == "tuesday":
print("Tuesday")
else:
print("Not Monday")
friends = ["Ross", "Taylor", "Joe"]
#if "Joe" in friends:
if "Joe" in {"Kabir","Aziz","Asma"}:
print("Joe is present")
else:
print("Abse... | hyderdanyal/udemyPython | python basics/loops.py | loops.py | py | 554 | python | en | code | 0 | github-code | 13 |
28765910654 | def gcd(a, b):
while a>0:
if a<b: a, b = b, a
a = int(a%b)
return b
for i in range(int(input())):
s = input()
r = s[::-1]
if gcd(int(s), int(r)) == 1: print("YES")
else: print("NO") | CuongNguyen291201/py | sodaonguyentocungnhau.py | sodaonguyentocungnhau.py | py | 223 | python | en | code | 0 | github-code | 13 |
14680820288 | import numpy as np
from lmfit.lineshapes import gaussian
from lmfit.models import Model
class Stepper:
def __init__(self, start, stop, npts):
self.start = start
self.stop = stop
self.npts = npts
def get_x(self):
return np.linspace(self.start, self.stop, self.npts)
def gauss... | lmfit/lmfit-py | tests/test_custom_independentvar.py | test_custom_independentvar.py | py | 1,235 | python | en | code | 948 | github-code | 13 |
4474465522 | # -*- coding: utf-8 -*-
from odoo import fields, models, api, _
class AccountCashboxLine(models.Model):
""" We add dynamic currency """
_inherit = 'account.cashbox.line'
# def _get_default_currency(self):
# currency_id = self.cashbox_id.currency_id
# if self.payment_method_id:
# ... | LuisMalave2001/GarryTesting | pos_pr/models/account_bank_statement.py | account_bank_statement.py | py | 3,230 | python | en | code | 2 | github-code | 13 |
13176295330 | try:
# import argparse
import json
import requests
except ModuleNotFoundError:
print("Please download dependencies from requirement.txt")
except Exception as ex:
print(ex)
def clean_non_utf8_chars(input_data):
if isinstance(input_data, str):
# If the input is a string, clean it and ret... | muktachanda/Social-Media-Personality-Analysis | app/src/main/python/python/insta_scrape.py | insta_scrape.py | py | 4,298 | python | en | code | 0 | github-code | 13 |
74595784016 | from .base_model import BaseVideoPredictionModel
from .base_model import VideoPredictionModel
from .savp_model import SAVPVideoPredictionModel
from .sv2p_model import SV2PVideoPredictionModel
def get_model_class(model):
model_mappings = {
'savp': 'SAVPVideoPredictionModel',
'savp_vae': 'SAVPVideoP... | m-serra/action-inference-for-video-prediction-benchmarking | video_prediction/savp/models/__init__.py | __init__.py | py | 701 | python | en | code | 13 | github-code | 13 |
4723952074 | from math import log
#计算给定数据集的熵
def calcShannonEnt(dataSet):
#返回数据集的行数
numEntries=len(dataSet)
#保存每个标签(Label)出现次数的字典
labelCounts={}
#对每一组的特征向量进行统计
for featVec in dataSet:
#提取标签的信息
currentLabel=featVec[-1]
#查看是否放入字典中,没有就添加进去
if currentLabel not in labelCounts.keys... | JiweiMma/Decision-Tree | Decisiontree-2.py | Decisiontree-2.py | py | 3,793 | python | zh | code | 0 | github-code | 13 |
21580909805 | from ..GLGraphicsItem import GLGraphicsItem
from ..transform3d import Matrix4x4, Quaternion, Vector3
from .shader import Shader
from .BufferObject import VAO, VBO
import numpy as np
import OpenGL.GL as gl
__all__ = ['GLGridItem']
def make_grid_data(size, spacing):
x, y = size
dx, dy = spacing
xvals = np.... | Liuyvjin/pyqtOpenGL | pyqtOpenGL/items/GLGridItem.py | GLGridItem.py | py | 3,255 | python | en | code | 0 | github-code | 13 |
3945377298 | #!/usr/bin/env python
# encoding: utf-8
# @author: lishaogang
# @file: prog-1.py
# @time: 2020/7/5 0005 10:41
# @desc:
import matplotlib.pyplot as plt
from dDE.DE import DE
from config import test_funcs
MAXSIZE = 100
MAXDIM = 30
MAXGEN = 1500
TIMES = 1
# lbound = -1.28
# rbound = 1.28
func_id = 2
use_CD = False
use_... | ShaquallLee/evolutionary-programming | dDE/prog-1.py | prog-1.py | py | 1,101 | python | en | code | 0 | github-code | 13 |
2973905510 | def heapAdjust(L, i, j):
next = i * 2
tmp = L[i]
while next <= j:
if next + 1 <= j and L[next + 1] > L[next]:
next = next + 1
if L[next] > L[i]:
L[i] = L[next]
i = next
next = next * 2
else: break
L[i] = tmp
def heapSort(L):
L... | sangjianshun/Master-School | heapSort.py | heapSort.py | py | 541 | python | en | code | 34 | github-code | 13 |
4699855055 | '''
[문제]
omr 리스트의 값들은 이번 시험 정답이다.
a는 철수의 답안지이다. 랜덤숫자(1~5) 열 개를 a에 추가 후,
정답과 비교해서 철수의 점수를 출력.
한 문제당 10점이다.
[예시]
omr = [4, 3, 1, 5, 3, 2, 1, 4, 5, 3]
철수 = [5, 2, 5, 5, 2, 1, 4, 4, 4, 1]
성적 = 20
'''
import random
omr = [4,3,1,5,3,2,1,4,5,3]
a =[]
total=0
... | Songmsu/python | H일차배열/일차배열3_문제_누적합_개수/일차배열3_문제03_omr카드_문제.py | 일차배열3_문제03_omr카드_문제.py | py | 598 | python | ko | code | 0 | github-code | 13 |
15283630460 | from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from .models import Product
from .forms import RawProductForm
# Create your views here.
@login_required
def product_create_view(request):
my_form = RawProductForm()
if request.method == "POST":
... | Leopizarro/OrderManager-Django | src/products/views.py | views.py | py | 1,380 | python | en | code | 0 | github-code | 13 |
1025446963 | import argparse
from package import MetaData
from package.log import MockLogger
def get_experiment_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"-f",
"--folder",
help="Folder of tasks to generate latex table for.",
required=True
)
parser.add_argument(
... | Turkish-Word-Embeddings/Word-Embeddings-Repository-for-Turkish | evaluation/dump_similarity_latex_table.py | dump_similarity_latex_table.py | py | 3,067 | python | en | code | 1 | github-code | 13 |
29380812183 | num = int(input('Enter four-digit natural number: '))
search2 = int(input('1) Find the product of the digits of number".\n'
'2) Write the number in reverse order.\n'
'3) In ascending order, sort the numbers included in the given number"\n'
'Enter number of act... | kolyasalubov/Lv-14.03.PythonFundamentals | dmisia/HW3/Practical_Task_2.py | Practical_Task_2.py | py | 836 | python | en | code | 0 | github-code | 13 |
36587499826 | import numpy as np
import math
class Match:
def __init__(self, data1, data2, dist):
self.data1 = data1
self.data2 = data2
self.dist = dist
class KNN:
def __init__(self, datas1, datas2, distf=lambda x, y: math.sqrt(x**2 + y**2)):
self.data1 = datas1
self.data2 = datas2... | ysokmr/sift_image_merger | knn.py | knn.py | py | 702 | python | en | code | 1 | github-code | 13 |
34786229988 | from rct229.rule_engine.rule_base import RuleDefinitionBase
from rct229.rule_engine.rule_list_indexed_base import RuleDefinitionListIndexedBase
from rct229.rule_engine.user_baseline_proposed_vals import UserBaselineProposedVals
from rct229.rulesets.ashrae9012019.ruleset_functions.baseline_system_type_compare import (
... | pnnl/ruleset-checking-tool | rct229/rulesets/ashrae9012019/section23/section23rule8.py | section23rule8.py | py | 6,129 | python | en | code | 6 | github-code | 13 |
3079673625 | # Importing requests library to send HTTP requests
# Parsing data using BeautifulSoup function
import requests
from bs4 import BeautifulSoup
#Parsing the webpage
webpage = "https://en.wikipedia.org/wiki/Deep_learning"
Parsedpage = requests.get(webpage).text
soup = BeautifulSoup(Parsedpage,"html.parser")
# P... | adtmv7/CS5590-490-Python-Deep-Learning | ICP3/Source/webscraping.py | webscraping.py | py | 518 | python | en | code | 2 | github-code | 13 |
74563029458 | import os
import re
import sys
import json
import shutil
import subprocess
import socket
from collections import namedtuple
import classad
from ServerUtilities import executeCommand
from ServerUtilities import MAX_DISK_SPACE, MAX_WALLTIME, MAX_MEMORY
JOB_RETURN_CODES = namedtuple('JobReturnCodes', 'OK RECOVERABLE_ER... | dmwm/CRABServer | src/python/TaskWorker/Actions/RetryJob.py | RetryJob.py | py | 27,933 | python | en | code | 15 | github-code | 13 |
33014996909 | import random
def run():
num_aleatorio = random.randint(1, 100)
num_elegido = int(input('Elige un número al azar: '))
while num_elegido != num_aleatorio:
if num_elegido < num_aleatorio:
print('Busca un número más grande')
else:
print('Busca un número más pequeño')
... | devpcastello/P-DS-Coins_Converter | adivina_el_numero.py | adivina_el_numero.py | py | 446 | python | es | code | 0 | github-code | 13 |
30241116 | from entities.key_data_processing.search_response import SearchResponse
from extractors.value_finding_status import ValueFindingStatus
from entities.key_data_processing.key_data import KeyData
class KeyDataParser:
def __init__(self, search_responses: list[SearchResponse]):
self.__search_responses = searc... | AdrianC2000/InvoiceScannerApp | parsers/key_data_parser.py | key_data_parser.py | py | 692 | python | en | code | 0 | github-code | 13 |
11619097367 | #Nykaa
#User will provide you list of items they want to buy : "Lipstick", "Lip Balm", "Eyeliner", "Deo"
#Build a logic:
## If a item is in male list : assume price as 60, give 10% off
## If a item is in female list : assume price 100 give 20% off
## If a item is in unisex list : assume price as 120 give 5% off
## ... | myselfparag/python-programming | functions/option_argument_hm.py | option_argument_hm.py | py | 1,473 | python | en | code | 0 | github-code | 13 |
1589545432 | import re
input_content = str(input("请输入姓名和手机号,并以空格间隔:"))
# 判断中文正则模板
chinese_pat = re.compile(r"[\u4e00-\u9fa5]+")
# 判断手机号是否合法正则模板
mobile_pat = re.compile("^(13\d|14[5|7]|15\d|166|17\d|18\d)\d{8}$")
phone_name = "".join(re.findall(chinese_pat, input_content))
phone_num = "".join(re.findall(r"\d+", input_content))
i... | Abeautifulsnow/python_learning | scripts/python/re_mobile.py | re_mobile.py | py | 521 | python | zh | code | 0 | github-code | 13 |
70956260178 | from PyQt5.QtWidgets import QWidget, QHBoxLayout
from widgets.Map.Toolbox.Button import Button
from widgets.Map.MapMode import MapMode
class ToolboxWidget(QWidget):
def __init__(self, parent):
super(ToolboxWidget, self).__init__(parent)
self.__parent = parent
self.setGeometry(40, 0, 150,... | GeorgeHulpoi/piu-restaurant-management | widgets/Map/Toolbox/ToolboxWidget.py | ToolboxWidget.py | py | 1,559 | python | en | code | 0 | github-code | 13 |
46804889164 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from os import system
from optparse import OptionParser
queries_liste = {}
quiet = False
databaseConn = None
databaseCursor = None
def process(pkt):
global quiet
global databaseConn
ip46 = IPv6 if IPv6 in pkt else IP
if pkt.haslayer(DNSQR) and UDP in pkt and pkt[UD... | solka-git/git-sample | dns_sniffer.py | dns_sniffer.py | py | 2,217 | python | en | code | 0 | github-code | 13 |
26944164640 | #!/bin/python3
from flask import Flask, request, Response
import requests, urllib.parse
from bs4 import BeautifulSoup
from markupsafe import escape
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from PIL import Image
import io
app = Flask(__... | SusanaCoronaC/CDK | src/webService.py | webService.py | py | 4,270 | python | en | code | 0 | github-code | 13 |
21996192094 | import pandas as pd
import dash
from dash import html, dcc, Input, Output
import plotly.express as px
# Read the data
spacex_df = pd.read_csv("spacex_launch_dash.csv")
max_payload = spacex_df['Payload Mass (kg)'].max()
min_payload = spacex_df['Payload Mass (kg)'].min()
# Create a dash application
app = dash.Dash(__na... | AbdullaOmarA/IBM-Data-Science-Professional | Applied Data Science Capstone/7.SpaceX Interactive Dashboard with Ploty Dash.py | 7.SpaceX Interactive Dashboard with Ploty Dash.py | py | 2,841 | python | en | code | 0 | github-code | 13 |
27659365618 | import sys
from pypdf import PdfReader, PdfWriter
from argparse import ArgumentParser
from pdftool.compress import compress_page
from pdftool.remove_images import remove_images
from pdftool.encryption import encrypt, decrypt
from pdftool.merge import merge
from pdftool.split import range_to_page_indices
from pdftool.... | dwelman-xebia/innoday-python-pdf-tool | pdftool/main.py | main.py | py | 7,387 | python | en | code | 0 | github-code | 13 |
28080517480 | import pruning
import torch
import os
from foundations import paths
from foundations.hparams import ModelHparams
from foundations.step import Step
from models import cifar_vgg, mnist_mlp, imagenet_resnet, cifar_pytorch_resnet, tinyimagenet_resnet
from models import bn_initializers, initializers
registered_models = [mn... | he-zh/sparse-double-descent | models/registry.py | registry.py | py | 3,562 | python | en | code | 13 | github-code | 13 |
4192811681 | import torch
import matplotlib.pyplot as plt
from math import inf
import numpy as np
from utils.conf import args
def load_training_status(file_path:str) -> tuple:
print('loading '+file_path+'...')
checkpoint = torch.load(file_path, map_location=torch.device('cpu'))
records = checkpoint['records']
pri... | Shawn-Guo-CN/EmergentNumerals | analysis/compare_refer_gen_game.py | compare_refer_gen_game.py | py | 1,534 | python | en | code | 4 | github-code | 13 |
22205603026 | #!/usr/bin/env python
# coding: utf-8
# ## CSC420 Assignment 2
# ### Brendan Neal | 1001160236 | nealbre1
# Imports and some helper functions
# In[1]:
import numpy as np
from scipy import spatial
import cv2 as cv
import math
from matplotlib import pyplot as plot
# Make the plot a certain size
plot.rcParams["figu... | br3nd4nn34l/CSC420-Fall-2018 | assignments/a2/a2.py | a2.py | py | 30,486 | python | en | code | 0 | github-code | 13 |
73822458576 | import pandas as pd
import csv
# with pandas
df = pd.read_csv('weather_data.csv')
print(df)
print(df.nunique())
print(df.info())
temp_list = df['temp']
print(temp_list)
# with csv
with open('weather_data.csv') as data_file:
data = csv.reader(data_file)
temperature = []
day_week = []
week_condition ... | Marksman007577/Python-Usecase | Python 100 Days/Day 25/read_csv.py | read_csv.py | py | 678 | python | en | code | 0 | github-code | 13 |
24664088169 | import pygame
import random
import time
from src.load_image import load_image
class Platform(pygame.sprite.Sprite):
v0y = 400
def __init__(self, y, color, game_properties, *groups, **kwargs):
super().__init__(*groups)
self.game_properties = game_properties
self.x, self.y =... | VileHero-Alex/python_project_doodle_jump | src/platforms.py | platforms.py | py | 3,637 | python | en | code | 0 | github-code | 13 |
34510790322 | # Author: Logan deLaar
# Github: Logandelaar1
import glob
import os
# Change 'your_directory_path' to your directory path
directory_path = 'path/to/lables/folder/in/downloaded/roboflow/folder'
# Use glob to get all .txt files in the directory
for filename in glob.glob(os.path.join(directory_path, '*.txt')):
wi... | logandelaar1/Yolo-Data-Parser | yolodataparser_autodelete.py | yolodataparser_autodelete.py | py | 620 | python | en | code | 0 | github-code | 13 |
19374063297 | import zmq
import time
import numpy as np
import multiprocessing as mp
# import signal
# import sys
# def signal_handler(sig, frame):
# print("Keyboard interrupt received. Exiting...")
# sys.exit(0)
# signal.signal(signal.SIGINT, signal_handler)
class GPCRequester(mp.Process):
def __init__(self, queue: m... | localization-as-a-service/liloc-demo | communication_sim.py | communication_sim.py | py | 1,936 | python | en | code | 0 | github-code | 13 |
16069156190 | def Bubble_Sort(a):
b=len(a)-1
for i in range(b):
for y in range(b-i):
if a[y]>a[y+1]:
a[y],a[y+1]=a[y+1],a[y]
return a
a=[]
n=int(input('Enter the size: '))
for j in range(n):
num=input()
a.append(num)
Bubble_Sort(a)
print('\nSorted array: ')
fo... | Shusovan/Basic-Python-Programming | Bubble Sort.py | Bubble Sort.py | py | 355 | python | en | code | 2 | github-code | 13 |
31015659683 | #-*- codeing=utf-8 -*-
#@time: 2020/8/26 9:49
#@Author: Shang-gang Lee
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
class fasttext(nn.Module):
def __init__(self, vocab_size, embedding_dim, class_nums):
super().__init__()
self.embedding=nn.Embedding... | shanggangli/Research-in-NLP | units/FastTextModel.py | FastTextModel.py | py | 1,028 | python | en | code | 0 | github-code | 13 |
74211540817 |
from PyQt5.QtGui import QPagedPaintDevice # !! Not in QtPrintSupport
from qtPrintFramework.pageLayout.model.adaptedModel import AdaptedModel, AdaptedSortedModel
class AdaptedPageNameToEnumModel(AdaptedSortedModel): # !!! Sorted
'''
Dictionary from name to page enum.
From Qt's enum.
Static, a fixed set... | bootchk/qtPrintFramework | qtPrintFramework/pageLayout/model/pageNameToEnum.py | pageNameToEnum.py | py | 1,615 | python | en | code | 2 | github-code | 13 |
219880823 | import sys
# sys.stdin = open("input.txt", "rt")
'''
n = int(input())
arr = []
zeros = [0] * (n + 2)
arr.append(zeros)
for _ in range(n):
tmp = [0] + list(map(int, input().split())) + [0]
arr.append(tmp)
arr.append(zeros)
cnt = 0
for i in range(1, n + 1):
for j in range(1, n + 1):
comp = [arr[i - ... | ignis535/baekjoon | 탐색 & 시뮬레이션/봉우리.py | 봉우리.py | py | 958 | python | en | code | 0 | github-code | 13 |
29018022835 | #함수 이름은 변경 가능합니다.
class NotnumberOfdata(Exception):
def __init__(self):
super().__init__('Num of data is not 3!')
class AlreadyExist(Exception):
def __init__(self):
super().__init__('Already exist name ')
class NotInteger(Exception):
def __init__(self):
super().__init__('Score is n... | kkl4846/KimKyunglin | python_problem/studentprogram.py | studentprogram.py | py | 4,432 | python | en | code | 0 | github-code | 13 |
70136628498 | import datetime
# Define a dictionary to store mood data for each day of the week
moods = {}
# Define a list of mood options
mood_options = ['Happy', 'Sad', 'Excited', 'Angry', 'Calm']
# Get the current day of the week
current_day = datetime.datetime.now().strftime("%A")
# Prompt the user to enter their mood for th... | Ellnutt/Feeling | moodtrk.py | moodtrk.py | py | 790 | python | en | code | 2 | github-code | 13 |
35735181288 | # Exercise 5: Bottle Deposits
def bottle_deposit():
# Reading container count for each size from user
one_ltr_cost = 0.01
one_ltr_more_cst = 0.25
one_ltr_less = int(input("enter number of container which are less than or euqal to 1 liter:"))
one_ltr_more = int(input("enter number of containers wh... | KashyapTushar/kashyaptushar.github.io | Python_Workbook/Ex5_Bottle_Deposit.py | Ex5_Bottle_Deposit.py | py | 551 | python | en | code | 0 | github-code | 13 |
32045617830 | import numpy as np
import pandas as pd
import pytest
from pandas.testing import assert_frame_equal, assert_series_equal
import arkouda as ak
class TestDataFrame:
@staticmethod
def build_pd_df():
username = ["Alice", "Bob", "Alice", "Carol", "Bob", "Alice"]
userid = [111, 222, 111, 333, 222, 1... | Bears-R-Us/arkouda | PROTO_tests/tests/dataframe_test.py | dataframe_test.py | py | 24,649 | python | en | code | 211 | github-code | 13 |
4593446825 | class Solution:
"""
@param source: A string
@param target: A string
@return: A string denote the minimum window
Return "" if there is no such a string
"""
def minWindow(self, source, target):
# write your code here
d, dt = {}, dict.fromkeys(target, 0)
... | ultimate010/codes_and_notes | 32_minimum-window-substring/minimum-window-substring.py | minimum-window-substring.py | py | 1,173 | python | en | code | 0 | github-code | 13 |
18807651704 | # -*- coding: utf-8 -*-
# by Alejandro Rojo Gualix 2022-02 ...
__author__ = 'Alejandro Rojo Gualix'
"""
pip install python-docx freeplane-io
"""
import sys
import argparse
from pathlib import Path
import re
import freeplane
# python-docx
from docx import Document
from docx.enum.text import WD_COLOR_INDEX
"""
SR. No.... | alerojorela/document-outliner | outliner.py | outliner.py | py | 9,271 | python | en | code | 0 | github-code | 13 |
20680351498 | from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import *
... | Derr22/python-selenium-behave-parallel-runner | core/base_class.py | base_class.py | py | 13,097 | python | en | code | 0 | github-code | 13 |
30787526166 | from Cryptodome.Cipher import AES
from Cryptodome.Util.Padding import pad, unpad
import uuid
import hashlib
import os #암호화에 필요한 모듈 가져옴.
import smtplib
from email.mime.text import MIMEText #메일을 보낼 때 메시지의 제목과 본문을 설정
#arr는 잠그기 위한 확장자 list
arr = ['.txt', '.doc', '.docx', '.hwp', '.pptx', '.ppt', '.xls', '.pdf', '.ai',... | smpark0213/P-RansomeWare | encryptdecrypt.py | encryptdecrypt.py | py | 7,726 | python | ko | code | 0 | github-code | 13 |
1050886381 | import json
import joblib
import numpy as np
import os
# called when the deployment is created or updated
def init():
global model
# get the path to the registered model file and load it
# AZUREML_MODEL_DIR is an environment variable created during deployment.
# It is the path to the model folder (./az... | farbodtaymouri/my-azure-ml-projects | model-deployment-online/src/model/score.py | score.py | py | 1,873 | python | en | code | 0 | github-code | 13 |
42081593576 | def solution(number, limit, power):
answer = 0
anslist = []
for i in range(1, number + 1):
n = divnum(i)
if n > limit:
anslist.append(power)
else:
anslist.append(n)
answer = sum(anslist)
return answer
def divnum(num):
cnt = 0
sqr = int(num **(... | HotBody-SingleBungle/HBSB-ALGO | HB/pysrc/프로그래머스/레벨1/Day10(23_01_27)/기사단원의_무기.py | 기사단원의_무기.py | py | 665 | python | en | code | 0 | github-code | 13 |
41639258046 | import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from SYF_ANN import *
normalization=16.0
# STEP 1: Load data, produce one-hot encoding of targets and split into training and testing
dig = load_digits()
onehot_target = [[1 if y==x else 0 for y in ra... | JuanManuelHuerta/Quantitative_Strategy | 01_ANN/v02.py | v02.py | py | 931 | python | en | code | 1 | github-code | 13 |
41908860513 | import torch
import torch.optim as optim
from torch.autograd import Variable
from torchvision.transforms import ToPILImage
from neural_style_net import ContentLoss, StyleLoss
class Solver(object):
def __init__(self, model, content_var, style_var,
content_weight=1, style_weight=1000,
... | dfridman1/neural-style-transfer | solver.py | solver.py | py | 2,455 | python | en | code | 1 | github-code | 13 |
18978410021 | from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ReferenceListProperty,\
ObjectProperty, StringProperty
from kivy.vector import Vector
from kivy.clock import Clock
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label... | DonyTawil/MyKivy | Pong/main.py | main.py | py | 3,653 | python | en | code | 0 | github-code | 13 |
17292129823 | import time
import csv
import numpy
import Adafruit_BMP.BMP085 as BMP180
import Adafruit_ADS1x15.ADS1115 as adc
import smbus
power_mgmt_1 = 0x6b
power_mgmt_2 = 0x6c
bus = smbus.SMBus(0)
address = 0x1e
def read_byte(adr):
return bus.read_byte_data(address, adr)
def read_word(adr):
high = bus.read_byte_data(a... | gcostigan/stab | STAB_1_code/RaspberryPiZero/stab_I.py | stab_I.py | py | 3,916 | python | en | code | 5 | github-code | 13 |
20421011399 | # -*- coding: utf-8 -*-
"""
Created on Thu May 11 20:21:41 2023
@author: alexa
"""
import pygame
from settings import *
from tile import Tile
from player import Player
from debug import *
from support import *
from random import choice
class Level:
def __init__(self):
# get the dis... | alehic173/Python-RPG-Game | level.py | level.py | py | 4,509 | python | en | code | 0 | github-code | 13 |
38188821944 | from Bio import SeqIO
from Bio.Blast import NCBIWWW
from Bio.Blast import NCBIXML
from progress.bar import Bar
import pandas as pd
import geopandas
import matplotlib.pyplot as plt
import os
import re
import geopy.geocoders
from geopy.geocoders import Nominatim
from Bio import Entrez
import folium
def runBlast(sequence... | rebeccalilly/dcs211final | dcsfinal.py | dcsfinal.py | py | 12,175 | python | en | code | 0 | github-code | 13 |
21051835313 | from comdev import *
import json
import sys
# Device with serial interface (fitolamp)
class Fitolamp(Comdevice):
def __init__(self, port_name):
self.status = {"result_code": -1,
"result_text": "NoData",
"current_dtime": "NoData",
"power_s... | MikhailBerezhanov/FLC-01 | gui/flc_com.py | flc_com.py | py | 3,727 | python | en | code | 0 | github-code | 13 |
22006876685 | import keyboardModule as kb
from djitellopy import tello
from time import sleep
import cv2, time
import rospy
import sys,os
from std_msgs.msg import String,Float32MultiArray, Int32MultiArray,Bool
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
"""
if kb.getKey("q"):
mytello.land()
elif... | oscar50513/AI_project | drown_ws/control_node.py | control_node.py | py | 3,123 | python | en | code | 0 | github-code | 13 |
41670160570 | __version__ = 10
import urllib.request
import os
import sys
import zipfile
import time
from optparse import OptionParser
import platform
import shutil
import json
import subprocess
import http.client, mimetypes
import tempfile
print("\nSimple Jobs Distribution Framework\nversion: {}, platform: {}".format(__version__,... | olivierfriard/jobs-distribution | client.py | client.py | py | 13,291 | python | en | code | 1 | github-code | 13 |
22996498097 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 17 16:37:39 2019
"""
import numpy as np
def cal_ICPC(pos):
if pos >= 0.0001:
y = pos*np.log2(pos/0.25)
else:
y = 0
return y
def find_possible(ICPC):
possible_range = []
for ii in range(0,10001):
i = ii/100... | Zhongyihhh/CS412-Gene-Mutation-Detection | Step1_3.py | Step1_3.py | py | 2,262 | python | en | code | 0 | github-code | 13 |
20210567209 | import os
import random
import sys
import source.tokenization.tokenization as tokenization
def save_data(data, label, meta, path, name):
print(path)
foutd = open(path + name + "_remadd.txt", 'w', encoding='utf-8', errors='ignore')
for i, d in enumerate(data):
foutd.write(" ".join(d).replace('\n',... | lin-tan/CoCoNut-Artifact | source/tokenization/generate_data.py | generate_data.py | py | 5,770 | python | en | code | 48 | github-code | 13 |
3848241398 | import json
from dataclasses import dataclass
from datetime import datetime, timezone
import time
from ulanzi import UlanziApp
BAR_COLOR_PAUSED = '#deb764'
BAR_COLOR_RUNNING = '#aadb72'
BAR_COLOR_BG = '#373a40'
class UlanziTimerDisplay(UlanziApp):
"""
App that listens to HASS timer events and dynamically dis... | ict/ulanzi-awtrix-appdaemon | ustopwatch.py | ustopwatch.py | py | 4,535 | python | en | code | 1 | github-code | 13 |
34129706092 | from src.dependencies.imports import *
class Item_issue(LabelFrame):
def __init__(self,master,db):
super(Item_issue,self).__init__(master)
self.grid()
labelfont=('times',16,'bold')
self.config(bd=10,bg="#bdc3c7",font=labelfont)
self.master=master
self.dept... | SohailChamadia/Digital-Assets | src/dependencies/Item_issue.py | Item_issue.py | py | 17,273 | python | en | code | 1 | github-code | 13 |
14917171951 | import plotly.figure_factory as ff
import pandas as pd
import csv
import plotly.graph_objects as go
import statistics
import random
data = pd.read_csv("StudentsPerformance.csv")
finalData = data["reading score"].tolist()
mean = sum(finalData) / len(finalData)
std_dev = statistics.stdev(finalData)
median =... | Asaawari/Properties-of-Normal-Distribution | code.py | code.py | py | 1,660 | python | en | code | 0 | github-code | 13 |
71040828497 | from tkinter import *
from tkinter import filedialog
from nba_api.stats.endpoints import shotchartdetail
import json
import requests
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import customtkinter
# Load teams file
teams = json.loads(requests.get('https://raw.githubusercontent.com/btt... | eramadani3/NBA-Analysis-Tool | Analysis/shotChart.py | shotChart.py | py | 4,624 | python | en | code | 0 | github-code | 13 |
16080882005 | """
Created on Wed Feb 17 11:25:2503 2021
@author: Sule
@name: command_line.py
@description: ->
DOCSTRING:
"""
#!/usr/bin/env python3
# Importing the libraries
from threading import Timer
from sys import exit
from datetime import datetime
import wmi
import pythoncom
import mysql.connector
class Process():
""... | nikola-supic/process_watcher | command_line.py | command_line.py | py | 5,073 | python | en | code | 0 | github-code | 13 |
15805245776 | import argparse
from tools.tools import *
if __name__ == "__main__":
print('''
__
______ ____ ____ | | __
/ ___// __ \_/ __ \| |/ /
\___ \\\\ ___/\ ___/| <
/____ >\___ >\___ >__|_ \\
\/ \/ \/ \/
version 1.0.2
auhtor: iami23... | 5ime/Seek | seek.py | seek.py | py | 815 | python | en | code | 12 | github-code | 13 |
35921111405 | import json
from anytree import Node, RenderTree
from scanner import Scanner
class Parser:
def __init__(self, scanner: Scanner, grammar_json) -> None:
self.scanner = scanner
grammar = json.load(open(grammar_json))
self.terminals = grammar['terminals']
self.non_terminals = grammar[... | hamilamailee/Compiler-Design | lrparser.py | lrparser.py | py | 6,757 | python | en | code | 0 | github-code | 13 |
721675923 | import urllib ,sqlite3
from bs4 import BeautifulSoup
params = urllib.parse.urlencode({'page':1})
url='https://movie.naver.com/movie/point/af/list.nhn?&%s' %params
#print(url)
response = urllib.request.urlopen(url)
#print(response)
navigator = BeautifulSoup(response,'html.parser')
table = navigator.find('table',class_... | sweetfruit77/Test | crawling/BeautifulSoup11.py | BeautifulSoup11.py | py | 1,442 | python | en | code | 0 | github-code | 13 |
1135510907 | import datetime
import itertools
import uuid
from flask import current_app, url_for
from notifications_utils.clients.encryption.encryption_client import EncryptionError
from notifications_utils.recipients import (
InvalidEmailError,
InvalidPhoneError,
try_validate_and_format_phone_number,
validate_emai... | GSA/notifications-api | app/models.py | models.py | py | 78,608 | python | en | code | 7 | github-code | 13 |
37031745149 | import networkx as nx
from fst.classes import State
from fst.utils import findMaxWordSize, findMinimizedState
def create_minimal_transducer(dictionary):
# Initial
fst = nx.MultiDiGraph()
minimal_states = []
max_word_size = findMaxWordSize(dictionary)
# print(max_word_size)
temp_states = []
... | RafaelStudartDiPiero/FST_CTC34 | fst/fst.py | fst.py | py | 5,327 | python | en | code | 0 | github-code | 13 |
22907058374 | from django.test import TestCase
from django.contrib.contenttypes.models import ContentType
from survey.tests.utils import SurveyTestCase
from survey.models import (DesiredFact, FactOption,
Fact, has_required_data, Project)
class DesiredFactTests(TestCase):
def setUp(self):
self.content_type = Co... | gareth-lloyd/flexsurvey | survey/tests/test_models.py | test_models.py | py | 4,220 | python | en | code | 0 | github-code | 13 |
41858059866 | class Node:
def __init__(self, cords, reward):
self.type = 'normal'
self.cords = cords
self.is_wall = False
self.is_door = False
self.door = ''
self.key = ''
self.diamond = ''
self.is_wired = False
self.v = 0
self.r = rewar... | msmsd778/AI_Game_RL | src/python_client/MainClass.py | MainClass.py | py | 377 | python | en | code | 0 | github-code | 13 |
22139695329 | import turtle
a = 10
x = 0
y = 0
turtle.shape('turtle')
for i in range(10):
for j in range(4):
turtle.forward(a)
turtle.left(90)
turtle.penup()
a += 10
x -= 5
y -= 5
turtle.goto(x, y)
turtle.pendown()
| Andrey-phystech/mipt_python_1sem | lab_1/ex5.py | ex5.py | py | 262 | python | en | code | 0 | github-code | 13 |
31728286520 | """
Animation module, including spritesheet
and animation frame classes
Written Dec 29, 2015 by Benjamin Reed
Credit for original spritesheet implementation
goes to Paul Vincent Craven at
programarcadegames.com
"""
import pygame as pyg
import constants as con
class RectWithType(pyg.Rect):
"""
... | benreed/pyg-fg-hello-rect-collision | animation.py | animation.py | py | 4,130 | python | en | code | 0 | github-code | 13 |
6669293011 | import json
from jupyter_server.base.handlers import APIHandler
from jupyter_server.utils import url_path_join
import tornado
import os
class RouteHandler(APIHandler):
# The following decorator should be present on all verb methods (head, get, post,
# patch, put, delete, options) to ensure only authorized use... | csci-env/env-extension | csci_env/handlers.py | handlers.py | py | 888 | python | en | code | 0 | github-code | 13 |
35024601841 | import os
import re
# Set the path to the input file
input_file = "dr-glas.txt"
# Create a directory to store the output files
output_dir = "dr_glas/kapitel"
os.makedirs(output_dir, exist_ok=True)
reg = '([0-9]{1,2}\s(?:juni|juli|augusti|september|oktober).*)\n\n'
# Open the input file and read the contents
with open... | joelfalk1/doktor-glas | scripts/date_separator.py | date_separator.py | py | 817 | python | en | code | 0 | github-code | 13 |
74087812179 | # CRISTIAN ECHEVERRÍA RABÍ
import weakref
import wx
from wx.lib.newevent import NewEvent
#-----------------------------------------------------------------------------------------
__all__ = ['ListCtrl', 'LISTCTRL_DEF_STYLE', 'EVTC_LISTCTRL_DATACHANGE']
#----------------------------------------------------... | cer1969/py-cer-widgets | listctrl/listctrl.py | listctrl.py | py | 5,512 | python | en | code | 1 | github-code | 13 |
24090946202 | from django.urls import path
# Create urls here
from apencil.api.views import (
# Authentication
SignUpEndpoint,
SignInEndpoint,
BookViewSet,
)
urlpatterns = [
# Auth
path("sign-up/", SignUpEndpoint.as_view(), name="sign-up"),
path("sign-in/", SignInEndpoint.as_view(), name="sign-in"),
... | iamshaynez/apencil | apiserver/apencil/api/urls.py | urls.py | py | 703 | python | en | code | 0 | github-code | 13 |
24984459289 | import os
import jieba
from pyltp import NamedEntityRecognizer, Segmentor, \
Postagger, CustomizedSegmentor, \
Parser, SementicRoleLabeller, SentenceSplitter
class HLT(object):
def __init__(self, model_path):
self.model_path = model_path
self.cws_model_file = os.path.join(self.model_path,... | imlifeilong/myner | hitner/utils.py | utils.py | py | 5,038 | python | en | code | 0 | github-code | 13 |
6520124361 | import numpy as np
from datasets import encoder_data
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
class TLP():
"""Two layer perceptron class. d is the dimension of input,
M is the dimension of output and h is the number of hidden nodes."""
def __init__(self, d, M, nodes):
... | AlexHermansson/ANN_lab1 | encoder.py | encoder.py | py | 3,053 | python | en | code | 0 | github-code | 13 |
13514423036 | from ebcli.containers.generic_container import GenericContainer
from ebcli.objects.exceptions import NotFoundError, ValidationError
from mock import patch, Mock
from unittest import TestCase
MOCK_DESTINATION_DOCKERFILE = '/foo'
class TestGenericContainer(TestCase):
def setUp(self):
self.pathconfig = Moc... | aws/aws-elastic-beanstalk-cli | tests/unit/containers/test_generic_container.py | test_generic_container.py | py | 1,392 | python | en | code | 150 | github-code | 13 |
37473394734 | EAST = 0
SOUTHEAST = 1
SOUTHWEST = 2
WEST = 3
NORTHWEST = 4
NORTHEAST = 5
NUM_DIRECTIONS = 6
#Tile X == normal x
#Tile Y = zigzagging vertically
#origin is in the right zigzag column
# \ \
# / /
# \ \ v +y ->+x
# / /
def GetTileInDirection(pos, direction):
if direction == EAST:
return (pos[0]+1,pos[1])... | Chromega/adventofcode | 2020/Day24/day24.py | day24.py | py | 3,786 | python | en | code | 0 | github-code | 13 |
11193176216 | # modified version of binary search that returns the index
# within a sorted sequence indication where the target
# shold be located
def findSortedPosition( theList, target):
low = 0
high = len(theList) - 1
while low <= high:
mid = (low+high)//2
if theList[mid] == target:
return... | Shaunwei/Python4Fun | algorithmAndDataS/SearchingAndSorting/findSortedPosition.py | findSortedPosition.py | py | 522 | python | en | code | 0 | github-code | 13 |
24823123662 | from __future__ import annotations
from plumbum import cli # type: ignore
from pathlib import Path
from quangis_workflows.namespace import CCD, EM, EX
from quangis_workflows.generator import WorkflowGenerator
from quangis_workflows.types import Polytype
sources = [
(CCD.FieldQ, CCD.VectorTessellationA, CCD.Plain... | quangis/quangis-workflows | quangis_workflows/cli/wf_gen.py | wf_gen.py | py | 4,947 | python | en | code | 0 | github-code | 13 |
17531004519 |
from __future__ import print_function
import logging
import sys
_log = logging.getLogger(__name__)
try:
from itertools import izip
except ImportError:
izip = zip
from functools import partial
import json
import threading
try:
from Queue import Queue, Full, Empty
except ImportError:
from queue import... | mdavidsaver/p4p | src/p4p/client/thread.py | thread.py | py | 15,778 | python | en | code | 20 | github-code | 13 |
38889852083 | #! python3
# a program to roll dice
from random import randint
from plotly.graph_objs import Bar,Layout
from plotly import offline
class Dice():
"""A class to roll dice """
def __init__(self,dice_num=6):
self.dice_num=dice_num
"""Rolling the dice"""
def roll(self):
return ra... | DrakeChow3/Stupid-stuff | Script1/rollingDice.py | rollingDice.py | py | 1,051 | python | en | code | 0 | github-code | 13 |
26455187113 | class Solution:
def removeElement(self, nums, val):
# nums = list(filter(lambda x: x!=val, nums))
# return len(nums)
# while val in nums:
# nums.remove(val)
# return len(nums)
# accepted answer
l = 0
for i in range(len(nums)):
if nums[... | Eyakub/Problem-solving | LeetCode/remove_element.py | remove_element.py | py | 500 | python | en | code | 3 | github-code | 13 |
15288499552 | from django.shortcuts import render, redirect
import datetime
import json
from django.core import serializers
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from admin.models import *
def index(re... | kharron/sjdsdirectory | admin/views.py | views.py | py | 3,415 | python | en | code | 0 | github-code | 13 |
73607409936 | from collections import Counter as counter
from typing import Counter, Optional, Sequence, Tuple, Union
import torch
def bleu_score(
input: Union[str, Sequence[str]],
target: Sequence[Union[str, Sequence[str]]],
n_gram: int = 4,
weights: Optional[torch.Tensor] = None,
device: Optional[torch.devic... | pytorch/torcheval | torcheval/metrics/functional/text/bleu.py | bleu.py | py | 5,473 | python | en | code | 155 | github-code | 13 |
33942931130 | import logging
import time
from functools import lru_cache
from typing import List
import numpy as np
import psutil
from recommendations.estimator import discover_models
from recommendations.resolvers import get_resolvers
log = logging.getLogger(__name__)
@lru_cache(maxsize=None)
def load_model(model_name, *args, ... | YUNGC0DE/RecoServiceTeam30 | recommendations/model_utils.py | model_utils.py | py | 2,372 | python | en | code | null | github-code | 13 |
36791156934 | from manimlib import *
class BringTwoRodsTogether(Scene):
CONFIG = {
"step_size": 0.05,
"axes_config": {
"x_min": -1,
"x_max": 11,
"y_min": -10,
"y_max": 100,
"y_axis_config": {
"unit_size": 0.06,
"tick_fre... | nadav7679/phase_field_Ni_batteries | manim_anim.py | manim_anim.py | py | 11,722 | python | en | code | 0 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.