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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
11593483082 | #
# 따라하며 배우는 파이썬과 데이터과학(생능출판사 2020)
# 14.20 분류기의 정확성을 알아보자, 390쪽
#
from sklearn.datasets import load_iris
from sklearn.metrics import confusion_matrix
iris = load_iris()
y_pred_all = knn.predict(iris.data)
conf_mat = confusion_matrix(iris.target, y_pred_all)
print(conf_mat)
plt.matshow(conf_mat)
plt.show() | dongupak/DataSciPy | src/파이썬코드(py)/Ch14/code_14_20_3.py | code_14_20_3.py | py | 380 | python | ko | code | 12 | github-code | 13 |
7827768324 | import numpy as np
import astropy
from astropy.io import fits
from astropy.io import ascii
from astropy import wcs
from PIL import Image
#resized_img = Image.fromarray(orj_img).resize(size=(new_h, new_w))
#import scipy
#from scipy.misc import imresize
import tng_api_utils as tau
import initialize_mock_fits as imf
impor... | gsnyder206/mock-surveys | mocks_from_publicdata/create_mock_hydro_image.py | create_mock_hydro_image.py | py | 13,780 | python | en | code | 7 | github-code | 13 |
19112969310 | import json
from typing import List
import math
import datetime
# This script is used to convert raw Amazon Transcribe json format to a nice text format with timestamps
# The Amazon Transcript raw doesnt have the identifying of individuals
# General overview: This parses the raw format from Amazon, splits up into each... | AdamCorbinFAUPhD/Parse-Amazon-Transcriptions | parse_amazon_transcripts.py | parse_amazon_transcripts.py | py | 4,044 | python | en | code | 1 | github-code | 13 |
28568364931 | from __future__ import annotations
import sys
import os
import tempfile
import shutil
import copy
from typing import (
Optional,
Type,
Callable,
Any,
Iterator,
Iterable,
Union,
List,
Dict,
cast,
)
from types import ModuleType
from google.protobuf import symbol_database as SDB
... | painebenjamin/pibble | api/helpers/googlerpc.py | googlerpc.py | py | 24,691 | python | en | code | 1 | github-code | 13 |
24989774649 | import numpy as np
import matplotlib.pyplot as plt
from library.information_continuos import diff_E
from library.pdf_estimators import *
from scipy.stats import norm
import seaborn as sns
from library.plot import plot_settings, plot_kernels
xReal = np.linspace(-5, 5, 10000)
dxReal = xReal[1] - xReal[0]
pdfReal = norm... | Wronsmin/Information-Theory | assignement_2.py | assignement_2.py | py | 1,414 | python | en | code | 0 | github-code | 13 |
3277759843 | import sys
import os
sys.path.append(os.getcwd())
sys.path.append('../Library/Web3/')
sys.path.append('../Library/Crypto/')
import time
import base64
import uuid
import sqlite3
import asyncio
from datetime import datetime
from flask import Flask, request
import json
import connector
import argparse
from web3 import We... | NeoGeek88/Distributed-Storage-on-Ethereum | Server/server.py | server.py | py | 10,027 | python | en | code | 4 | github-code | 13 |
28620185094 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ========================================================
# Module : read_config
# Author : Null
# Create Date : 2018/3/25
# Amended by : Null
# Amend History : 2018/6/5
# ========================================================
import configp... | xiaoxiaolulu/AndroidAuto | config/read_config.py | read_config.py | py | 1,922 | python | en | code | 6 | github-code | 13 |
28375201409 | #!/usr/bin/python3.6
#-*- coding: utf-8 -*-
import os
import datetime
def decrypted(tekst,klucz):
klucz = klucz*(-1)
alphabet = "abcdefghijkmnolpqrstuvwxyzabcdefghijkmnolpqrstuvwxyz"
ALPHABET = "ABCDEFGHIJKMNOLPQRSTUVWXYZABCDEFGHIJKMNOLPQRSTUVWXYZ"
lista =[]
for i in range(0,len(tekst)):
lis... | aszpatowski/JSP2019 | lista8/zadanie2.py | zadanie2.py | py | 1,965 | python | pl | code | 0 | github-code | 13 |
11957017853 | #!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
install_requires = [
'django-taggit',
'django-markdown',
]
setup(
name='yaba2',
version='0.1',
... | rogersmark/yaba2 | setup.py | setup.py | py | 804 | python | en | code | 2 | github-code | 13 |
73911050579 | from django.db import models
from accounts.models.account import Account
class Payment(models.Model):
payments = models.Manager()
class Meta:
app_label = 'billing'
base_manager_name = 'payments'
default_manager_name = 'payments'
owner = models.ForeignKey(Account, on_delete=mode... | datahaven-net/zenaida | src/billing/models/payment.py | payment.py | py | 1,927 | python | en | code | 17 | github-code | 13 |
35517259114 | from SLL import *
class ModRLE_SLL(SLL) :
'''
This class is inherited from SLL class.
It will be used for Modified Run-Length Encoding the linked list.
'''
def ModRLE(self) :
'''
Used to print the Modified Run-Length Encoded version of Linked List.
The modified Run-Length... | paramSonawane/99Problems | Python/P11.py | P11.py | py | 1,281 | python | en | code | 0 | github-code | 13 |
27149298573 | import math
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption("Drawing Arcs")
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: # 接收到退出事件后退出程序
pygame.quit()
exit()
screen.fi... | linzch3/How-TO-Use-XXX | How-To-Use-pygame/0.基础入门/1.4_绘制弧形.py | 1.4_绘制弧形.py | py | 744 | python | en | code | 0 | github-code | 13 |
41517158945 | from django import forms
from .views import Author, Book
# python manage.py shell에서 테스트법.
# >>> from django import forms
# >>> from testmodelform.views import Author, Book
# >>> from testmodelform.forms import DefaultTextInput
# >>> w = DefaultTextInput()
# >>> print(w)
# >>> print(w.media)
# >>> print(w.media['css'])... | 3dartmax/test | testmodelform/forms.py | forms.py | py | 3,158 | python | en | code | 0 | github-code | 13 |
12363858840 | import serial
import time
serialPort = "COM9"
baudRate = 115200
arduino = serial.Serial(serialPort,baudRate,timeout=0.5)
time.sleep(1)
while 1:
command = input('输入指令:')
command = bytes(command, encoding = "utf8")
arduino.write(command)
time.sleep(3) # 等待电机转动完毕才能读取返回的信息。可以通过速度计算得到精准地等待时间
msg = ar... | CarlSome/Minitaur | MainControl/MinitaurController.py | MinitaurController.py | py | 430 | python | en | code | 0 | github-code | 13 |
9087869320 | #https://www.acmicpc.net/problem/4446
#백준 4446번 ROT13 (문자열)
import sys
def check(alpha):
if alpha in vowelBig:
return 2
if alpha in vowelSmall:
return 1
return 0
small = "bkxznhdcwgpvjqtsrlmf"
big = "BKXZNHDCWGPVJQTSRLMF"
vowelBig = 'AIYEOU'
vowelSmall = 'aiyeou'
while True:
try:
... | MinsangKong/DailyProblem | 07-16/1-1.py | 1-1.py | py | 1,241 | python | ko | code | 0 | github-code | 13 |
74861060817 | import arcpy
import os
import sys
import traceback
import platform
import logging
import Configuration
import datetime
def getLoggerName():
''' get unique log file name '''
if Configuration.DEBUG == True:
print("UnitTestUtilities - getLoggerName")
seq = 0
name = nameFromDate(seq)
#add +=1 t... | Esri/solutions-geoprocessing-toolbox | utils/test/UnitTestUtilities.py | UnitTestUtilities.py | py | 7,774 | python | en | code | 129 | github-code | 13 |
73123057616 | import asyncio
import websockets
from websockets.exceptions import ConnectionClosedError, ConnectionClosedOK
import json
import random
import settings
async def send_messages(uri):
id_seq = 0 # Initialize outside the loop to keep it persistent
while True: # Outer loop to reconnect
try:
as... | rozdol/ws_assignment | feeder.py | feeder.py | py | 1,605 | python | en | code | 0 | github-code | 13 |
10494002264 | from collections import Counter
import pandas as pd
df = pd.read_csv('busca.csv')
X_df = df[['home', 'busca', 'logado']]
Y_df = df['comprou']
X_dummies = pd.get_dummies(X_df)
X = X_dummies.values
Y = Y_df.values
porcentagem_treino = 0.9
total_dados = len(Y)
quantidade_treino = int(porcentagem_treino * total_dado... | caiquetgr/alura_courses | machine_learning/python_machine_learning/classifica_buscas.py | classifica_buscas.py | py | 1,159 | python | pt | code | 0 | github-code | 13 |
41643349535 | # Method: Traverse from bottom-right to top-left adding the min(grid[r+1][c], grid[r][c+1]) to the current location in grid
# TC: O(m*n), since we traverse the whole grid once
# SC: O(1), since values are updated in-place
from typing import List
class Solution:
def minPathSum(self, grid: List[List[int]]) -... | ibatulanandjp/Leetcode | #64_MinimumPathSum/solution.py | solution.py | py | 828 | python | en | code | 1 | github-code | 13 |
21271417237 | from typing import (
Callable,
Dict,
)
from datetime import datetime
from web3 import Web3
from web3.gas_strategies.time_based import (
fast_gas_price_strategy,
medium_gas_price_strategy,
slow_gas_price_strategy,
glacial_gas_price_strategy,
)
from web3.middleware import geth_poa_middleware
impo... | xiaoxiaoleo/NFT-Bot | core/chain_network.py | chain_network.py | py | 5,387 | python | en | code | 7 | github-code | 13 |
69875471378 | import img2pdf
from tkinter import *
from tkinter import messagebox, filedialog
root = Tk()
root.resizable(False, False)
root.config(bg='black')
root.iconbitmap("D:/Applications/Image To PDF/Image To PDF.ico")
root.geometry("320x190")
root.title("Image To PDF Converter")
def file():
global img
... | CHARANKUMAR2002/Image-To-PDF-Converter | Image To PDF Converter.py | Image To PDF Converter.py | py | 2,154 | python | en | code | 1 | github-code | 13 |
5772382455 | import pandas as pd
class Logger():
def __init__(self, log_dir, experiment_name, columns = ['episodes', 'total_rewards', 'state_val', 'reward_val']):
self.log_dir = log_dir
self.experiment_name = experiment_name
self.fname = '{}/{}.csv'.format(log_dir, experiment_name)
self.dat... | henrykenlay/RLProject | Logger.py | Logger.py | py | 635 | python | en | code | 1 | github-code | 13 |
9933373984 | # Chapter 5: Iterations
# Exercise 2: Write another program that prompts for a list of numbers as above
# and at the end prints out both the maximum and minimum of the numbers instead
# of the average
num = 0
max = None
min = None
while True :
svar = input('Enter a number: ')
if svar == 'done' :
bre... | scucatti/py4e | assignment5_2.py | assignment5_2.py | py | 616 | python | en | code | 0 | github-code | 13 |
12640673284 | from datetime import time, timedelta, datetime
import json
from pathlib import Path
import random
from typing import Optional, Tuple
class SolutionJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime) or isinstance(obj, (time, timedelta)):
return '%s' % obj
... | magic7s/ProcessScheduler | processscheduler/solution.py | solution.py | py | 14,288 | python | en | code | null | github-code | 13 |
24944531625 | #!/usr/local/bin/python
"""自定义列表!
Usage:
list add <list_file> <item> [before (index <item_index> | key <keyword>)]
list batchadd <list_file> <batch_item>...
list del <list_file> (index <item_index> | key <keyword>)
list view <list_file> [<keyword>]
list all [<keyword>]
list dedup <list_file>
list remove-... | nightingu/damebot | scripts/mylist.py | mylist.py | py | 15,716 | python | en | code | 1 | github-code | 13 |
37684777622 | #!/usr/bin/env python
import logging
import sys
import redis
from benchmark import benchmark
logger = logging.getLogger(__name__)
BUCKET_SIZE = 50000
KEYS = 1000000
def main():
# configure logging
logging.basicConfig(format="%(asctime)s [%(funcName)s][%(levelname)s] %(message)s")
logger.setLevel(loggin... | hurdad/redis-bucketing | bucketing-test.py | bucketing-test.py | py | 2,449 | python | en | code | 0 | github-code | 13 |
24577701705 | import sys
from ting_file_management.file_management import txt_importer
def process(path_file, instance):
"""Aqui irá sua implementação"""
extract = txt_importer(path_file)
file_in_queue = None
for index in list(range(instance.__len__())):
file_in_queue = (
instance.search(index)
... | livio-lopes/ting | ting_file_management/file_process.py | file_process.py | py | 1,283 | python | en | code | 0 | github-code | 13 |
9340196514 | "Code for sorting contact names etc"
def alphanumeric_sort(items):
"Sort given items with alphabets first and then numbers and symbols etc"
alpha_list = []
other_list = []
for item in items:
if item[0].isalpha():
alpha_list.append(item)
else:
other_lis... | kashifpk/sms_vault | sms_vault/lib/sort.py | sort.py | py | 391 | python | en | code | 0 | github-code | 13 |
9269108071 | import sys
word = sys.stdin.readline().rstrip()
# 숫자만 추출
re = ""
for i in word:
if(ord(i) >= ord('0') and ord(i) <= ord('9')):
re += i
num = int(re)
print(num)
# 숫자만 추출2
# num = 0
# for x in word:
# # isdecimal() -> 0~9까지 참으로 반환
# if x.isdecimal():
# num = num*10+int(x)... | cracking-interview/be-interview | 알고리즘/강의/jiyeong/탐색,시뮬레이션/숫자만추출.py | 숫자만추출.py | py | 473 | python | en | code | 2 | github-code | 13 |
679660816 | from abc import ABC, abstractmethod
from footballdashboardsdata.utils.subclassing import get_all_subclasses
class DataSource(ABC):
@classmethod
@abstractmethod
def get_name(cls) -> str:
"""
Get the name of the data source.
Returns:
str: _description_
"""
@... | dmoggles/footballdashboardsdata | footballdashboardsdata/datasource.py | datasource.py | py | 1,208 | python | en | code | 0 | github-code | 13 |
501192956 | from django.contrib import admin
from django.db.models import Count
from django.utils.html import format_html
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.contrib import admin, messages
from django.contrib.admin.options import IS_POPUP_VAR
from django.contrib.a... | BalkisAbbassi/project-mangement-python | pm/admin.py | admin.py | py | 9,140 | python | en | code | 0 | github-code | 13 |
71421315857 | #!/usr/bin/env python
#Complementing a Strand of DNA
dna_dict = {'A':'T', 'T':'A', 'G':'C', 'C':'G'}
def rev_comp(s):
sc = ''
for nu in s:
sc += dna_dict[nu]
return sc[::-1]
if __name__ == '__main__':
with open('data/rosalind_revc.txt', 'r') as f:
s = f.read().strip()
with open('o... | dogaukinder/dogalind | revc.py | revc.py | py | 372 | python | en | code | 0 | github-code | 13 |
38815083345 | s = 'Python'
def test_answer1():
assert s[4] == 'o'
assert s[:4] == 'Pyth'
assert s[1:4] == 'yth'
assert s[::-1] == 'nohtyP'
def test_answer2():
l = [3,7,[1,4,'hello']]
l[2][2] = "goodbye"
assert l[2][2] == "goodbye"
def test_answer3():
d1 = {'simple_key':'hello'}
assert d1[... | arifcalik/lexicon | Oct31_pyton_intro/intro.py | intro.py | py | 851 | python | en | code | 0 | github-code | 13 |
16386460519 | words=input("please enter the words which are to be sorted seperated by space").split()
print(words)
sortedWords=sorted(words, key=None, reverse=False)
duplicatesRemoved=set({})
for w in sortedWords:
duplicatesRemoved.add(w)
output=""
for i in sorted(list(duplicatesRemoved)):
output+=(i+" ")
print(out... | deepakdm2016/SCBPractice | PythonSection3/10.py | 10.py | py | 324 | python | en | code | 0 | github-code | 13 |
69966344659 | from flask_restplus import fields, Namespace, Resource
from gtfs_api.models import StopTime, Stop
stop_time_namespace = Namespace('stop_time', description='通過時間に関するエンドポイント')
stop_time = stop_time_namespace.model('StopTime', {
'trip_id': fields.String(require=True, description='', example=''),
'arrival_time':... | aruneko/DonanbusGTFSAPI | gtfs_api/apis/stop_times.py | stop_times.py | py | 1,843 | python | en | code | 0 | github-code | 13 |
4973769686 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
answer = []
stack = []
... | yeos60490/algorithm | leetcode/easy/binary-tree-inorder-traversal.py | binary-tree-inorder-traversal.py | py | 646 | python | en | code | 0 | github-code | 13 |
15734862013 | import torch
import torch.nn as nn
class LinearClassifier(nn.Module):
def __init__(self, d_features, seq_length, d_hid, d_out):
super(LinearClassifier, self).__init__()
self.d_features = d_features
self.maxpool = torch.nn.MaxPool1d(seq_length, stride=1, padding=0)
self.fc1 = nn.Lin... | Jincheng-Sun/Kylearn-pytorch | Modules/linear.py | linear.py | py | 767 | python | en | code | 0 | github-code | 13 |
22827003783 | from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from autosklearn.classification import AutoSklearnClassifier
import pickle
# dataset:
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_... | NickKletnoi/pythonProject | IRIS_predict.py | IRIS_predict.py | py | 2,244 | python | en | code | 0 | github-code | 13 |
776848012 | import argparse
import cv2
import dlib
# drag and select the roi
def drag_and_select(event, x, y, flags, param):
global dragging, roi_selected, startX, startY, endX, endY
if event == cv2.EVENT_LBUTTONDOWN:
(startX, startY) = (x, y)
roi_selected = False
dragging = True
elif event ==... | ashar-7/correlation_object_tracker | object_tracking.py | object_tracking.py | py | 3,124 | python | en | code | 22 | github-code | 13 |
29859559657 | import gzip
import io
import re
import sys
from datetime import datetime, timedelta, timezone
from dateutil import parser
from intelmq.lib.bot import CollectorBot
from intelmq.lib.mixins import HttpMixin, CacheMixin
from intelmq.lib.utils import parse_relative
from intelmq.lib.exceptions import MissingDependencyError... | certtools/intelmq | intelmq/bots/collectors/microsoft/collector_interflow.py | collector_interflow.py | py | 4,900 | python | en | code | 856 | github-code | 13 |
26205068120 | from database import Database
from user import User
class UserService:
def __init__(self):
self.db = Database('mongodb://localhost:27017')
def create_user(self, user_dict):
user = User.from_dict(user_dict)
user_id = str(self.db.insert_user(user.to_dict()).inserted_id)
return {'... | gamaweliton/web_api-dscontinuado | user_service.py | user_service.py | py | 1,161 | python | en | code | 0 | github-code | 13 |
30421764278 | import pytest
from main import process_earley, Grammar, Rule
def get_result(rules, word):
grammar = Grammar()
for rule in rules:
grammar.add_rule(Rule(rule))
return process_earley(grammar, word)
@pytest.mark.parametrize('rules, word, result', [
(['S S C', 'S C', 'C c D', 'D a D b', 'D 1'], ... | molodec3/practise2 | test.py | test.py | py | 1,832 | python | en | code | 0 | github-code | 13 |
38770192626 | from collections import deque
n, m = map(int, input().split())
l = []
for _ in range(n):
l.append(list(map(int, input())))
visited = [[False] * m for _ in range(n)]
directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
queue = deque([(0, 0)])
while queue:
v = queue.popleft()
if v[0] == n - 1 and v[1] == m - 1:... | leeseulee/algorithm-practice | this-is-coding-test/5-4.py | 5-4.py | py | 610 | python | en | code | 0 | github-code | 13 |
71471431057 | import numpy as np
import onnx
from onnx.backend.test.case.base import Base
from onnx.backend.test.case.node import expect
# The below ScatterElements' numpy implementation is from https://stackoverflow.com/a/46204790/11767360
def scatter_elements(data, indices, updates, axis=0, reduction="none"): # type: ignore
... | onnx/onnx | onnx/backend/test/case/node/scatterelements.py | scatterelements.py | py | 7,318 | python | en | code | 15,924 | github-code | 13 |
31547766085 | import os
import os.path as osp
from collections import Counter, defaultdict
import numpy as np
import pandas as pd
from tqdm import tqdm
from utils.dataset import ImageItemsDataset
class HappyDataset(ImageItemsDataset):
def __init__(self, *args, load_all_images=False, load_random_image=True, p_fin=0.5, second=... | asnorkin/happy_whale | pipeline/dataset.py | dataset.py | py | 7,820 | python | en | code | 2 | github-code | 13 |
38917827889 | """
Python script for data processing
"""
import numpy as np
import pandas as pd
import torch
from torch.utils.data import Dataset, DataLoader
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
class DigitDataset(Dataset):
def __init__(self, images, labels):
self.images ... | MenciusChin/Kaggle | digit/preprocessing.py | preprocessing.py | py | 1,702 | python | en | code | 1 | github-code | 13 |
35418484899 | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver = webdriver.Chrome(executable_path=r'C:\Users\Akumar4\Downloads\chromedriver_win32\chromedriver.exe')
driver.get("https://psfmember.org/civicrm/contribute/transact?reset=1&id=13")
time.sleep(5)
driver.maximize_wi... | AnilKumar568/Selenium | Conditional_Commands.py | Conditional_Commands.py | py | 531 | python | en | code | 0 | github-code | 13 |
2609007012 | # re-format markdown chat to book
def flatten(lst):
flattened_list = []
for item in lst:
if isinstance(item, list):
flattened_list.extend(flatten(item))
else:
flattened_list.append(item)
return flattened_list
def formatChat(chat):
chunks = chat.split("ChatGPT: \... | Navezjt/AI-Song-Of-Ice-And-Fire | materials/non-writing/chatToBook.py | chatToBook.py | py | 1,545 | python | en | code | 0 | github-code | 13 |
15096363522 | import psutil
from aoe2stats.Game import Game
from aoe2stats.memutils import *
proc_names = ['age2_x1.exe', "wk.exe"]
def connectGame(pid):
return Game(openProc(pid))
def findPid():
for proc in psutil.process_iter():
if proc.name().lower() in proc_names:
return proc.pid
return 0
def... | serg-bloim/allods-cheat | aoe2stats/cheats.py | cheats.py | py | 516 | python | en | code | 1 | github-code | 13 |
14522008179 | import torch
import numpy as np
import os, argparse, json
import wandb
from sklearn.metrics import precision_recall_fscore_support
from models import TheModel
from datasets import data_loader
def train(config, model, data, results, outputs):
model.train()
# Initialize the optimizer
optimizer = to... | kasraprime/Machine-Learning-Booster | ML.py | ML.py | py | 8,509 | python | en | code | 0 | github-code | 13 |
13766451738 | # method : transfer_id_to_decimal
# this method is used to transfer the node's id (binary)
#into ordinary decimal number
from hashlib import sha1
from random import randint
from node_id import get_node_id
def transfer_id_to_dec(nid):
assert len(nid) == 20 # node id must be equaled to 20 bytes
#just for... | aimer1027/Python_tests | test_field/DHT/clawer_DHT/trans_id.py | trans_id.py | py | 629 | python | en | code | 0 | github-code | 13 |
26295000395 | from typing import List
import cli
from enum import Enum
class OptionTypes(Enum):
ENCRYPTOR = 1
FOLDER_ADMIN = 2
GO_BACK = 0
EXIT = -1
# Options displayed in the main menu of help subprogram
HELP_OPTIONS = [
cli.SelectOption("Encryptor", OptionTypes.ENCRYPTOR),
cli.SelectOption("Folder Admi... | marekprochazka/python-windows-utils | src/help/help.py | help.py | py | 4,753 | python | en | code | 0 | github-code | 13 |
43231407174 | import math
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.pyplot import cm
import vars
from modules.neuron_chain import NeuronChain
from modules.neuron_chain_v2 import NeuronChainV2
def main():
model1 = NeuronChain(vars.N, vars.STIMULI_EVAPORATION_COEFF,
vars.T... | VY354/my_repository | Python/projects/machine_learning/liquid_memory_neruon_chain/src/main.py | main.py | py | 1,385 | python | en | code | 0 | github-code | 13 |
71717244179 | #!/usr/bin/python
# coding: utf-8
class Person(object):
role = 'Person'
def __init__(self, name, aggressivity, life_value):
self.name = name
self.aggressivity = aggressivity
self.life_value = life_value
def attack(self, dog):
dog.life_value -= self.aggressivity
class Do... | auspbro/code-snippets | Python/LPTHW/dogVShuman.py | dogVShuman.py | py | 768 | python | en | code | 2 | github-code | 13 |
10364185463 | from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.models import User
from django.contrib.auth import logout
from posts.models import Post
from index.models import SendMail
# Create your views here.
def home(request):
posts = Post.objects.all()[0:3]
conte... | melliflu0u5/myPlace | index/views.py | views.py | py | 2,095 | python | en | code | 0 | github-code | 13 |
4554805067 | from tkinter import *
from tkinter.font import Font
root = Tk()
root.title("Avi's - TODO List")
# Define our Font
my_font = Font(
family="Brush Script MT",
size=30,
weight="bold")
# Creat frame
my_frame = Frame(root)
my_frame.pack(pady=10)
# Create listbox
my_list = Listbox(my_frame,
font=my_font,
width=25,
h... | avisingh23598/todoList | todo.py | todo.py | py | 2,167 | python | en | code | 0 | github-code | 13 |
40113683721 | from flask import Flask, request, render_template, redirect, url_for
import sqlite3
app = Flask(__name)
# Function to initialize the database
def init_db():
conn = sqlite3.connect("myapp/database.db")
cursor = conn.cursor()
cursor.execute(
"""CREATE TABLE IF NOT EXISTS user_messages (id INTEGER PR... | fdac23/ChatGPT_Insecure_Code_Analysis | All Generated Codes/CWE-89/CWE-89_SQI-3c.py | CWE-89_SQI-3c.py | py | 1,268 | python | en | code | 0 | github-code | 13 |
72605798739 | from Bio.SeqRecord import SeqRecord
from Bio import SeqIO
def make_fragment(file, format, fraglength):
for seq_record in SeqIO.parse(file, format):
i = 0
while True:
yield seq_record.seq[i:i+fraglength]
i += 30
chroms = [str(i) for i in range(1, 23)]
chroms.extend(["X", "... | hamazaki1990/mkreads | mkfragment.py | mkfragment.py | py | 827 | python | en | code | 0 | github-code | 13 |
8314168640 | import logging
from odoo import models, fields, api, _
from odoo.exceptions import ValidationError
from dateutil.relativedelta import relativedelta
import re
import logging
# logging.info("afasffas")
class Agreement(models.Model):
_name = "library.agreement"
_description = "Agreement"
_inherit = 'mail.... | markoancev1/Library-Odoo | library/models/agreement.py | agreement.py | py | 3,633 | python | en | code | 0 | github-code | 13 |
73467174096 | ##### Programa que saca el H/V promedio para las estaciones
import os
import math
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import statistics as stats
import sys
import os.path as path
from os import remove
print("************************************")
print("*H/V PROMEDIO POR ESTACIÓN***"... | Cat2nadi/Efecto_deSitio_2021 | DATOS_CORREGIDOS/txt/HV_Promedio.py | HV_Promedio.py | py | 4,869 | python | es | code | 0 | github-code | 13 |
8054755806 | from itertools import product
import os
os.chdir(r'/home/rawleyperetz/Desktop')
num='0123456789'
brute_list=[]
last=int(input('Enter a number <=6: '))
for length in range(1,(last+1)):
to_attempt = product(num, repeat=length)
for attempt in to_attempt:
brute_list.append(''.join(attempt))
file = open('brute_... | rawleyperetz/android_bruteForce | bruteforce_number.py | bruteforce_number.py | py | 402 | python | en | code | 0 | github-code | 13 |
19904808367 | class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
#埃拉托斯特尼筛法
#给出要筛数值的范围n,找出sqrt(n)以内的素数p1,p2,p3,p4...
#先用2去筛,即把2留下,把2的倍数剔除掉;
#再用下一个素数,也就是3筛,把3留下,把3的倍数剔除掉;
#接下去用下一个素数5筛,把5留下,把5的倍数剔除掉;不断重复下去......
if n < 3:... | littleliona/leetcode | easy/204.count_primes.py | 204.count_primes.py | py | 840 | python | zh | code | 0 | github-code | 13 |
218218321 | import numpy as np
import urllib.request
import re
def htmlPrinter(numberList):
def tagSub(htmlKey, text):
return re.sub(r"\\n", " ", re.sub(r"\n ", "", re.sub("</"+htmlKey+">", "", re.sub("<"+htmlKey+">", "", re.search("<"+htmlKey+">((?s).*)</"+htmlKey+">", text).group(0))))).strip()
def authorSub... | ischigal/revealArXiV | arXivToReveal.py | arXivToReveal.py | py | 1,599 | python | en | code | 0 | github-code | 13 |
70010090577 | #monster_battle_functions.py
import random
from colorama import init, Fore, Style
init(autoreset=True)
import textwrap
import shutil
columns, _ = shutil.get_terminal_size()
class Monster:
d20 = [x + 1 for x in range(20)]
def __init__(self, name, armor_class, hit_points, to_hit, initiative, damage):
... | hikite1/Adventure-Story | adventure_pkg/monster_battle_functions.py | monster_battle_functions.py | py | 1,664 | python | en | code | 0 | github-code | 13 |
21247938816 | import tkinter as tk
def on_button_click(event):
text = event.widget.cget("text")
if text == "=":
try:
result = str(eval(entry.get()))
entry.delete(0, tk.END)
entry.insert(tk.END, result)
except Exception as e:
entry.delete(0, tk.END)
... | kobdash/Calculators | Python Calculator/PythonCalculator.py | PythonCalculator.py | py | 2,014 | python | en | code | 0 | github-code | 13 |
28665385158 | from django.shortcuts import render
from article.models import Article
from django.contrib.auth.decorators import login_required
# Create your views here.
@login_required
def article_details(request, id=None):
if id is not None:
get_article = Article.objects.get(id = id)
context = {
'article_... | samiulislamponik/Try-django-3.10 | article/views.py | views.py | py | 1,273 | python | en | code | 0 | github-code | 13 |
17386376756 | #!/usr/bin/env python3
from tkinter import *
import tkinter.font as tkFont
import time
import math
import random
import boolean
algebra = boolean.BooleanAlgebra()
FALSE = boolean.boolean._FALSE
TRUE = boolean.boolean._TRUE
# Variables
window = Tk()
modeChange = StringVar()
modeInt = IntVar()
inputExpr1 = StringVar()
... | jvisbal0312/DS_Preternship | tkinter_separatelines.py | tkinter_separatelines.py | py | 13,880 | python | en | code | 1 | github-code | 13 |
31528747590 | # Joan Quintana Compte-joanillo. Assignatura CNED (UPC-EEBE)
'''
IN-15
https://www.math.ubc.ca/~pwalls/math-python/integration/simpsons-rule/
Integral amb el mètode de Simpson simple (N=2) o compost (N>2, parell)
cd /home/joan/UPC_2021/CNED/apunts/python/T1/
PS1="$ "
python3 simpson2.py
'''
import numpy as np
import m... | joanillo/CNED | T1/simpson2.py | simpson2.py | py | 2,004 | python | en | code | 0 | github-code | 13 |
74417636497 | import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix
from sklearn.metrics import f1_score
from sklearn.metrics import accuracy_sc... | AarohSinha100/MACHINE_LEARNING-OLD- | Diabetes_Prediction_KNN/main.py | main.py | py | 1,676 | python | en | code | 0 | github-code | 13 |
14551151633 | #!/usr/bin/env python3
import sys
PRICE_COLUMN_NUM = -7
chunk_sum = 0
square_sum = 0
chunk_size = 0
for line in sys.stdin:
values = line.split(',')
try:
price = int(values[PRICE_COLUMN_NUM])
chunk_sum += price
square_sum += price ** 2
chunk_size += 1
except Exception:
... | StepDan23/MADE_big_data_course | hw_1/mapper_var.py | mapper_var.py | py | 466 | python | en | code | 0 | github-code | 13 |
37170492854 | import unittest
import numpy as np
import numpy.testing as npt
import jose
class test_create_profile(unittest.TestCase):
def test_positivity(self):
data = np.ones((200,200))
data[0,0] = -1
variance = np.ones(data.shape) / 100
profile = jose.create_profile(data, varianc... | exosports/JOSE | jose/test/test_create_profile.py | test_create_profile.py | py | 664 | python | en | code | 0 | github-code | 13 |
41567513051 | from collections import Counter
def solution(str1, str2):
answer = 0
ans1 = [str1[i:i+2].lower() for i in range(len(str1)-1) if str1[i:i+2].isalpha()]
ans2 = [str2[i:i+2].lower() for i in range(len(str2)-1) if str2[i:i+2].isalpha()]
ans1 = Counter(ans1)
ans2 = Counter(ans2)
a = ans1 & ... | bnbbbb/Algotithm | 프로그래머스/lv2/17677. [1차] 뉴스 클러스터링/[1차] 뉴스 클러스터링.py | [1차] 뉴스 클러스터링.py | py | 564 | python | en | code | 0 | github-code | 13 |
30035025565 | #!usr/bin/env python3
__version__ = "0.1.6"
import os
import requests
from xml.etree import ElementTree
try:
API_KEY = os.environ['EIA_KEY']
except KeyError:
raise RuntimeError("eiapy requires an api key to function, read "
"https://github.com/systemcatch/eiapy#setting-up-your-api-key ... | systemcatch/eiapy | eiapy.py | eiapy.py | py | 13,523 | python | en | code | 22 | github-code | 13 |
13614636290 | def type_tag(x):
return type_tag.tags[type(x)]
class HN_record(object):
"""A student record formatted via Hamilton's standard"""
def __init__(self, name, grade):
"""name is a string containing the student's name, and grade is a grade object"""
self.student_info = [name, grade]
class JO_rec... | clovery410/mycode | python/chapter-2/discuss8-3.py | discuss8-3.py | py | 2,546 | python | en | code | 1 | github-code | 13 |
17922410362 | from RPi import GPIO
from classes.shiftregister import Shiftregister
import time
class LCD:
def __init__(self, is_vier_bits=0, e=20, rs=21):
super().__init__()
self.sr = Shiftregister()
self.is_vier_bits = is_vier_bits
self.e = e
self.rs = rs
self.__show_cursor = Tr... | DebieThomas/project-backend | classes/lcd.py | lcd.py | py | 2,161 | python | en | code | 0 | github-code | 13 |
5975786712 | from utils import *
if __name__ == '__main__':
with open('../data/small_data_97.txt') as file:
data_file = file.read()
split_data = data_file.split('\n')
data = []
for item in split_data:
data.append(item.split())
data.pop() # Removes the random empty list at the end
choice =... | nathangurnee/feature-selection | src/main.py | main.py | py | 561 | python | en | code | 0 | github-code | 13 |
440530677 | import argparse
import math
import gmpy2
from gmpy2 import mpfr, mpq
from tqdm import tqdm, trange
from utils.funcs import zeta, zeta_prime
from utils.prec import set_dec_prec
from utils.time import timing
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--precision", type=int, default... | YuyangLee/Riemann-Zeta-Function | 1_root_newton.py | 1_root_newton.py | py | 1,340 | python | en | code | 2 | github-code | 13 |
34536899461 | #!/usr/bin/python
import numpy as np
from pprint import pprint
ITERATIONS = 10
def most_common(lst):
return max(set(lst), key=lst.count)
class Clustering():
def classify(self, point):
index = self.find_closest_centroid_index(point)
return self.labels[index]
def find_closest_centroid_index(self, poi... | ohnorobo/machine-learning | clustering.py | clustering.py | py | 7,030 | python | en | code | 1 | github-code | 13 |
43664521385 | import argparse
import os
import sys
import glob
import math
import pandas as pd
import numpy as np
import multiprocessing
from sklearn.metrics import confusion_matrix
import time
import pickle
import multiprocessing as mp
from ops.sequence_funcs import *
from ops.anet_db import ANetDB
from ops.thumos_db import THUMOSD... | happygds/two_level | submit_test.py | submit_test.py | py | 7,936 | python | en | code | 1 | github-code | 13 |
5478021134 | from Adafruit_GPIO.MCP230xx import MCP23017
import Adafruit_GPIO as GPIO
from .button import Button
from .button_array import ButtonArray
from .led_array import LedArray
from .led import Led
from . import config
from . import event_loop
import signal
class HardwareUserInterface:
def __init__(self, jukebox):
... | fqxp/jukebox | jukebox/hardware/ui.py | ui.py | py | 1,792 | python | en | code | 1 | github-code | 13 |
73605336338 | # !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author:梨花菜
# @File: LinkList.py
# @Time : 2020/9/3 22:10
# @Email: lihuacai168@gmail.com
# @Software: PyCharm
import time
def bubble(arr):
"""
>>> arr = [3,1,2,4]
>>> bubble(arr)
>>> arr == [1, 2, 3, 4]
True
"""
if len(arr) <= 1:
retu... | lihuacai168/LeetCode | simple/冒泡排序.py | 冒泡排序.py | py | 916 | python | en | code | 4 | github-code | 13 |
42123888441 | """
Touch the Dot Game: A game where players use hand tracking to touch dots that appear on the screen.
"""
import sys
import random # Standard library imports first
import threading
import time
from typing import List, Tuple, Optional, Any
from enum import Enum
from dataclasses import dataclass
import cv2
import num... | wisamalsamak/touch_the_dot | touch_the_dot.py | touch_the_dot.py | py | 7,868 | python | en | code | 1 | github-code | 13 |
22154197125 | import os
import zipfile
import MySQLdb
import logging
import sys
import os.path
from os import path
from MySQLdb.cursors import Cursor
from . import settings
import csv
from . import database
# Unzip exported file and delete file afterwards
def getData(export_path, export_file):
try:
data_zip = zipfile.Z... | CazCapone/NA-Parser | core/data.py | data.py | py | 4,113 | python | en | code | 1 | github-code | 13 |
43288822346 | from django.core.management.base import BaseCommand
from oscar.core.loading import get_model
from thumb_prerender.utils import create_thumb
ProductImage = get_model('catalogue', 'ProductImage')
class Command(BaseCommand):
help = "For creating product image thumbnails"
def handle(self, *args, **options):
... | wm3ndez/django-thumb-prerender | thumb_prerender/management/commands/create_product_thumbs.py | create_product_thumbs.py | py | 585 | python | en | code | 0 | github-code | 13 |
71684711059 | # -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations
from gluon import utils as gluon_utils
import datetime
import json
import time
@auth.requires_login()
def index():
return dict()
def about():
return dict()
def addSchedule():
form = SQLFORM.factory(
... | joepreyer/next-bus | controllers/default.py | default.py | py | 7,468 | python | en | code | 0 | github-code | 13 |
73476858259 | # -*- coding: utf-8 -*-
import os
import cv2
import copy
import math
import numpy as np
import keras
# import torch
# from torch.autograd import Variable
# from torchvision import transforms
# from torch.utils.data import Dataset, DataLoader
from data_loader.data_processor import DataProcessor
class KerasDataset(ker... | frotms/image_classification_keras | data_loader/dataset.py | dataset.py | py | 4,274 | python | en | code | 1 | github-code | 13 |
31200973888 | import os
import pipes
from oslo.config import cfg
from st2common.constants.action import LIBS_DIR as ACTION_LIBS_DIR
from st2common.util.types import OrderedSet
__all__ = [
'get_system_packs_base_path',
'get_packs_base_paths',
'get_pack_base_path',
'check_pack_directory_exists',
'check_pack_cont... | gtmanfred/st2 | st2common/st2common/content/utils.py | utils.py | py | 4,456 | python | en | code | null | github-code | 13 |
74779371216 | # -*- coding: utf-8 -*-
# encoding: utf-8print
import pyrealsense2 as rs
import numpy as np
import cv2
'''
开启点云
'''
# Declare pointcloud object, for calculating pointclouds and texture mappings
pc = rs.pointcloud()
# We want the points object to be persistent so we can display the last cloud when a frame drops
point... | Computer-Vision-and-Robotic-Perception/asabe-robot-2023 | ComputerVision/xyz_get_from_2d.py | xyz_get_from_2d.py | py | 7,637 | python | en | code | 1 | github-code | 13 |
9657137694 | class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
a = list(set(nums))
b = len(nums) // 3
c = []
for i in a:
if nums.count(i) > b:
c.append(i)
return c | SaranDharshanSP/LeetCode-Solutions | 0229-majority-element-ii/0229-majority-element-ii.py | 0229-majority-element-ii.py | py | 254 | python | en | code | 0 | github-code | 13 |
24742856852 | # 3. Promedio de números aleatorios
# Realice un programa que permita calcular el promedio de 1000 números aleatorios generados en el rango de [0, 100000]
import random
acumulador = 0
i = 0
while i < 1000:
n = random.randint(0, 10000)
acumulador = n
i += 1
print(acumulador)
promedio = acumulador / i
p... | mateoadann/Ej-por-semana | Ficha 6/ejercicio 3 ficha 6.py | ejercicio 3 ficha 6.py | py | 362 | python | es | code | 0 | github-code | 13 |
786811772 | import socket
HOST = "localhost"
PORT = 8000
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:
client_socket.connect((HOST, PORT))
client_id = str(client_socket.getsockname())
print(f"Welcome to the library, client {client_id}. Type 'exit' to quit.")
while True:
... | ashar933/OnlineLibrary | nashclient.py | nashclient.py | py | 532 | python | en | code | 0 | github-code | 13 |
15016287608 | a = 0
b = 1
n = int(input("How many fibonacci terms you need?(other than 0 and 1) : "))
i = 0
print(a)
print(b)
while i < n:
sum = a + b
print(sum)
a = b
b = sum
i = i + 1
| harshshahashah/MyCaptain-Python | fibonacci.py | fibonacci.py | py | 206 | python | en | code | 0 | github-code | 13 |
285390395 | class Solution(object):
def solveSudoku(self, board):
self.board = board
self.solve()
print(self.board)
def unAssigned(self):
for i in range(9):
for j in range(9):
if self.board[i][j] == ".":
return i, j
return -1, -... | soniaarora/Algorithms-Practice | Solved in Python/LeetCode/arrays/solveSudoku.py | solveSudoku.py | py | 1,954 | python | en | code | 0 | github-code | 13 |
42279771249 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 4 14:45:49 2022
@author: aquaf
"""
#(1)嘉宾名单
##创建
lists = ["张三","李四","王五"]
##打印消息,邀请嘉宾
for i in range(3):
print("邀请函".center(20)) #居中打印标题
print("尊敬的{}:".format(lists[i]))
print(" 值此佳节,诚邀您参会!" '\n') #输出后换行
##打印无法赴约的嘉宾名单,添加嘉宾后再次打... | aquafina2332/Getting-Started-for-Python | python通识4.4-列表与字典.py | python通识4.4-列表与字典.py | py | 1,944 | python | zh | code | 0 | github-code | 13 |
19734399551 | # coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from swagger_server.models.base_model_ import Model
from swagger_server.models.business_category import BusinessCategory # noqa: F401,E501
from swagger_server.models.m... | HebbaleLabs/Python-Assessment-Template | swagger_server/models/business_category_results_object.py | business_category_results_object.py | py | 3,179 | python | en | code | 0 | github-code | 13 |
7861589588 | """ 4(2(3)(1))(6(5)) first character in string is root.
Substring inside the first adjacent pair of parenthesis is for left subtree and substring inside second pair of parenthesis is for right subtree """
class Node:
def __init__(self, value):
self.key = value
self.left = self.right = None
def preorder(root):
... | bettercallavi/workbook | DataStructure/BinaryTree/tree_from_backeted_subtree.py | tree_from_backeted_subtree.py | py | 1,139 | python | en | code | 0 | github-code | 13 |
17332194771 | # DateValidation
from datetime import date
import Error
monthsStr = {'JAN': 1, 'FEB': 2, 'MAR': 3, 'APR': 4, 'MAY': 5, 'JUN': 6,
'JUL': 7, 'AUG': 8, 'SEP': 9, 'OCT': 10, 'NOV': 11, 'DEC': 12}
def validateDate(date):
'''
US01: Dates (birth, marriage, divorce, death)
should not be... | EricLin24/SSW555-DriverlessCar | DateValidation.py | DateValidation.py | py | 3,168 | python | en | code | 0 | github-code | 13 |
29116358382 | # https://www.youtube.com/watch?v=4-P0gptDT40&t=131s
import numpy
from numpy.random import randint
from matplotlib import pyplot
pyplot.rc('font', family='serif', size=5)
import sys
sys.path.append('../scripts/')
# Our helper
from plot_helper import *
#-----------------
beispiel_flag = 13
#----------------
de... | RKnOT/Lineare_Algebra | Vetor_Lineare_Algebra_01.py | Vetor_Lineare_Algebra_01.py | py | 3,876 | python | en | code | 0 | github-code | 13 |
72315294737 | # AUTHOR: Lucas Nelson
import os
def return_sorted_filenames(chrom):
chrom_filepath = f"/home/mcb/users/lnelso12/evoGReg/outputs/chr{chrom}"
existing_genes = set() # Ensures only files that are already in the directory are checked from the TSS file
for existing_gene in os.listdir(chrom_filepath):... | LucasNelson60/G4-EvoLSTM | remove_redundant_files.py | remove_redundant_files.py | py | 2,092 | python | en | code | 0 | github-code | 13 |
30313349100 | from wazo_ui.helpers.service import BaseConfdService
class CallPermissionService(BaseConfdService):
resource_confd = 'call_permissions'
def __init__(self, confd_client):
self._confd = confd_client
def list(self, *args, **kwargs):
return super().list(*args, **kwargs)
def get(self, re... | wazo-platform/wazo-ui | wazo_ui/plugins/call_permission/service.py | service.py | py | 3,397 | python | en | code | 4 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.