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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
15441316510 | """
Entity class for iDiamant.
"""
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN, NAME, VERSION, MANUFACTURER
class IdiamantEntity(CoordinatorEntity):
"""
The main iDiamant entity class.
"""
def __init__(self, coordinator, config_entry):
su... | clementprevot/home-assistant-idiamant | custom_components/idiamant/entity.py | entity.py | py | 1,067 | python | en | code | 4 | github-code | 36 |
17256388628 | execfile('simple_map.py')
def viterbi(states, piarr, trans_p, emit_p, obs):
# Initialize T1, which keep track of everything done so far
# T1 - probability of most likely path so far
T1 = [{}]
T2 = [{}]
# length of sequence
T = len(obs)
# init T1 for each state
for s in range(0, len(states)):
st = s... | abarciauskas-bgse/stochastic | project/viterbi.py | viterbi.py | py | 1,593 | python | en | code | 0 | github-code | 36 |
20693896588 | #!/usr/bin/python
# -- coding: utf8 --
"""
Django settings for Russian Learner Corpus project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
import os
import jso... | elmiram/russian_learner_corpus | heritage_corpus/settings.py | settings.py | py | 4,402 | python | en | code | 3 | github-code | 36 |
17895997999 | import argparse
import time
from modulos.AOJApp import AOJ
from modulos.Acciones import Acciones
from modulos.BarraMenu import irA
from modulos.Cartas import EmitirCarta, BlanquearCarta
from modulos.ConsultaRespuesta import CR
from modulos.Reporte import Reporte
newInstance = AOJ()
app = newInstance.retornarAOJApp()
... | gameztoy/AOJ | scripts/Cartas/CPMB09_37_EditarCarta.py | CPMB09_37_EditarCarta.py | py | 1,569 | python | es | code | 0 | github-code | 36 |
29719252617 | """
Day 9 part 2
"""
from utils import read_input
def find_window(opts, total):
window = []
for o in opts:
window.append(o)
while sum(window) > total:
window.pop(0)
if sum(window) == total:
return window
def find_missing(vals, pre):
idx = pre
while... | yknot/adventOfCode | 2020/09_02.py | 09_02.py | py | 975 | python | en | code | 0 | github-code | 36 |
29788651993 | from os.path import join, isdir
from os import listdir, mkdir
from importlib import import_module
NOTCODE_DIR = 'notcode'
if not isdir(NOTCODE_DIR):
mkdir(NOTCODE_DIR)
# read profile:
profiles = [x.rstrip('.py') for x in listdir('profiles') if x.endswith('.py')]
profile = None
if not profiles:
raise Exception... | ofek-b/vomBuch-insAnki | constants.py | constants.py | py | 774 | python | en | code | 1 | github-code | 36 |
9955744674 | #!/usr/bin/env python3
from PIL import ImageEnhance
from PIL import Image
def get_average_color(img):
img = Image.open('/home/pi/Desktop/img5.jpg')
img = img.resize((50,50))
#print(img.size)
img = img.crop((15, 15, 35, 35))
converter = ImageEnhance.Color(img)
img = converter.enhance(2.5)
#... | aparajitaghimire/Clueless-Recreated | Python Scripts/color_detect.py | color_detect.py | py | 787 | python | en | code | 1 | github-code | 36 |
2114104151 | import aiohttp
import uvicorn
from fastapi import FastAPI
from fastapi import Request
from starlette.responses import Response
app = FastAPI(title="Yhop Proxy",
version="0.0.1",
openapi_url="/openapi.json", )
@app.route("/", methods=['HEAD', 'OPTION', 'GET', 'POST'])
async def proxy(reque... | sdliang1013/caul-proxy | src/caul_proxy/server_uvicorn.py | server_uvicorn.py | py | 1,038 | python | en | code | 0 | github-code | 36 |
43143608911 | from rest_framework import serializers
from apps.categories.serializers import CategorySerializer
from apps.media.models import Image
from apps.media.serializers import ImageSerializer
from apps.products.models import Product, Variant
from apps.reviews.serializers import ReviewSerializer
class ProductSerializer(seria... | mushfiq1998/bkpe-multivendor-ecommerce | apps/products/serializers.py | serializers.py | py | 2,117 | python | en | code | 0 | github-code | 36 |
74367228902 | import json
from flask import Flask, render_template, request, jsonify
import requests
app = Flask(__name__)
API_KEY = '0c20320445392a19d9b2a02ae290502c'
BASE_URL = 'http://api.weatherstack.com/current'
def get_weather(city):
params = {
'access_key': API_KEY,
'query': city,
}
try:
... | ruisu666/WeatherApp-Flask | app.py | app.py | py | 2,886 | python | en | code | 0 | github-code | 36 |
13100916881 | from numpy import matrix, array, linalg, random, amax, asscalar
from time import time
def linpack(N):
eps=2.22e-16
ops=(2.0*N)*N*N/3.0+(2.0*N)*N
# Create AxA array of random numbers -0.5 to 0.5
A=random.random_sample((N,N))-0.5
B=A.sum(axis=1)
# Convert to matrices
A=matrix(A)
B=mat... | ddps-lab/serverless-faas-workbench | google/cpu-memory/linpack/main.py | main.py | py | 801 | python | en | code | 96 | github-code | 36 |
41928732216 | from __future__ import absolute_import
import xadmin
from .models import UserSettings, Log
from xadmin import views
from xadmin.layout import *
from django.utils.translation import ugettext_lazy as _, ugettext
class BaseSetting(object):
enable_themes = True
use_bootswatch = True
xadmin.site.register(views... | SweetShance/rewardSystem | rewardSystem/extra_apps/xadmin/adminx.py | adminx.py | py | 3,368 | python | en | code | 0 | github-code | 36 |
2954449489 | import argparse
import logging
def main(pretrained_graph_path, dataset_path):
from model import FacialRecognition
from dataloader import load_inception_graph
load_inception_graph(pretrained_graph_path)
model = FacialRecognition(dataset_path, 'test_set.csv')
model.train()
if __name__ == ... | josepdecid/IU-AdvancedMachineLearning | Labs/Lab3/main.py | main.py | py | 886 | python | en | code | 0 | github-code | 36 |
13860968318 | import pygame
import assets
clock = pygame.time.Clock()
win = pygame.display.set_mode((1365, 768))
#=================ROW 1====================
button1 = assets.Button(0, 0, 452, 253, (12, 12, 12), "", (255, 255, 255))
button2 = assets.Button(455, 0, 452, 253, (12, 12, 12), "", (255, 255, 255))
button3 = assets.Butto... | tanmay440/Game-Hub-Mega | Tic Tack Toe/main.pyw | main.pyw | pyw | 3,872 | python | en | code | 0 | github-code | 36 |
21548587442 | import pytest
from mixer.backend.django import mixer
from apps.edemocracia.models import EdemocraciaGA
from apps.edemocracia.tasks import (get_ga_edemocracia_daily,
get_ga_edemocracia_monthly,
get_ga_edemocracia_yearly,)
from django.db import Integ... | labhackercd/cpp-participacao-backend | src/apps/edemocracia/tests/test_analytics_edemocracia.py | test_analytics_edemocracia.py | py | 3,150 | python | en | code | 2 | github-code | 36 |
37639995341 | from block import Block
from hashlib import sha256
from collections import deque
class Blockchain():
# Set the parameters for the blockchain
def __init__(self, block_size, genesis_block_secret):
self.block_size = block_size
self.genesis_block_hash = sha256(genesis_block_secret.encode('u... | ketanv3/blockchain-evm | blockchain.py | blockchain.py | py | 2,050 | python | en | code | 0 | github-code | 36 |
42491423724 | import pytest
from demo_app import create_app
from demo_app import db as _db
from demo_app.blog.models import Author, Category, Entry
@pytest.fixture(scope='session')
def app():
app = create_app('testing')
app_context = app.app_context()
app_context.push()
yield app
app_context.pop()
@pytest.f... | AlexPG/flask-demo-app | tests/conftest.py | conftest.py | py | 1,640 | python | en | code | 0 | github-code | 36 |
72240231143 | from datetime import datetime
from typing import Any, Dict, List
import jsonlines
from tinydb import TinyDB, where
from higgins import const
class DateTimeSerializer():
OBJ_CLASS = datetime # The class this serializer handles
def encode(self, obj):
return obj.strftime('%Y-%m-%dT%H:%M:%S')
def... | bfortuner/higgins | higgins/database/tiny.py | tiny.py | py | 2,550 | python | en | code | 7 | github-code | 36 |
7748613059 | from tensorflow.keras.preprocessing import image as imageprep
import os
import numpy as np
from PIL import Image
import json
import requests
from io import BytesIO
def image_to_np_array(img_path, image_size):
img = imageprep.load_img(img_path, target_size=(image_size, image_size))
img = imageprep.img_to_array... | cloudera/CML_AMP_Image_Analysis | lib/utils.py | utils.py | py | 1,813 | python | en | code | 10 | github-code | 36 |
17109457983 | from .code_ast import ASTFile
from .goto import Goto
from .util import bf_move
class CodeLinker:
def __init__(self, code: ASTFile):
self.code: ASTFile = code
def process(self) -> str:
code, declarations = self.code.process()
pos = 0
data = ""
for i in code:
... | PashkovD/braincompiler | braincompiler/linker.py | linker.py | py | 629 | python | en | code | 0 | github-code | 36 |
30064471237 | from aljoadmin.models import Comment
from django import forms
class CommentForm(forms.ModelForm):
content = forms.CharField(
widget=forms.Textarea(attrs={'style':'width:100%; height:80px;'}),
label=''
)
class Meta:
model = Comment
fields = ('content',) | 97kim/aljo | aljoadmin/forms.py | forms.py | py | 264 | python | en | code | 1 | github-code | 36 |
73923124264 | #!/usr/bin/env python3
import requests
import json
import sys
from collections import OrderedDict
def get_versions():
url = 'https://api.github.com/repos/jenkinsci/swamp-plugin/releases'
versions = set()
response = requests.get(url)
if response.status_code == 200:
response = response.json()
... | vamshikr/swamp-plugin-stats | src/jenkins.py | jenkins.py | py | 1,306 | python | en | code | 0 | github-code | 36 |
36002000545 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 27 15:26:23 2022
@author: lidon
"""
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 13 14:57:16 2021
@author: a
"""
import numpy as np
import scipy.stats
import math
# Markov chain class
class Markov:
# state: states of a Markov Chain
# tra... | lidongrong/miss_hmm | code/HMM.py | HMM.py | py | 4,510 | python | en | code | 0 | github-code | 36 |
35909639327 | import pygame
import pytest
from scoreboard import Scoreboard
from settings import Settings
from game_stats import GameStats
@pytest.fixture
def scoreboard():
""" 创建一个新的 Scoreboard 实例 """
pygame.init()
ai_settings = Settings()
screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.sc... | shixiaoxiya/py_course_zly_ | Projects/project_code/third2_left _test/test_scoreboard.py | test_scoreboard.py | py | 1,852 | python | en | code | 0 | github-code | 36 |
310628557 | import logging
import collections
import html
import gw2buildutil
from . import util as gw2util
logger = logging.getLogger(__name__)
PAGE_ID = 'build'
PAGE_ID_PREFIX = 'builds/'
PAGE_TITLE_PREFIX = 'Guild Wars 2 build: '
def build (gw2site):
textbody_renderer = gw2buildutil.textbody.Renderer(
gw2buildu... | ikn/ikn.org.uk | lib/iknsite/gw2/build.py | build.py | py | 1,379 | python | en | code | 0 | github-code | 36 |
34398257612 | import qrcode
data = "Winson is the goat no cappa"
img = qrcode.make(data)
qr = qrcode.QRCode(version = 1, box_size = 10, border = 5)
qr.add_data(data)
qr.make(fit=True)
img = qr.make_image(fill_color = 'red', back_color = 'white')
img.save('C:/Users/wilko/Desktop/python12projects/qrcode/qrcode.png') | Riamuwilko/python_beginner_projects | qrcode/main.py | main.py | py | 303 | python | en | code | 0 | github-code | 36 |
937990517 | import logging
from django.core.exceptions import ValidationError
from django import forms
from django.utils.translation import gettext as _
from custody.models import MultiSigAddress
from coldstoragetransfers.helpers.btc import BTCHelper
class MultiSigAddressForm(forms.ModelForm):
class Meta:
model = Mu... | chriscslaughter/nodestack | custody/forms.py | forms.py | py | 1,960 | python | en | code | 0 | github-code | 36 |
33953035551 | import messageUtils as mu
import threading
class Listener(threading.Thread):
def __init__(self, socketO, caller, connection=None):
threading.Thread.__init__(self)
self.caller = caller # Client or Server object
self.connection = connection # Connection object or None if Client is calling this
if self.connectio... | rehnarehu/netproj | chat/mythreads.py | mythreads.py | py | 997 | python | en | code | 0 | github-code | 36 |
19450895845 | # -*- coding: utf-8 -*-
import os
import sys
import datetime
import struct
import wave
def argumentsparser():
usage = "Usage: python {} inputfile.kamata_programs".format(__file__)
arguments = sys.argv
if len(arguments) == 1 or len(arguments) > 2:
return usage
arguments.pop(0)
if not argumen... | amariichi/kamata2wav | kamata2wav.py | kamata2wav.py | py | 2,462 | python | en | code | 0 | github-code | 36 |
5913567690 | import torch
from torch import optim, nn
import os
from tqdm.auto import tqdm
from model import *
from data import *
from torch.cuda.amp import autocast, GradScaler
from validate_and_test import *
def load_checkpointed_model_params(model, optimizer, resume_checkpoint):
checkpoint = torch.load(resume_checkpoint)
... | ParasharaRamesh/NUS-CS5242-Neural-Networks-and-Deep-Learning | Assignment 2 (Autoencoders & CNNs)/Question-5_CIFAR10/train.py | train.py | py | 8,557 | python | en | code | 0 | github-code | 36 |
35493639057 | from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.views import View
from main.models import *
from main.forms import *
from cart.forms import CartAddProductForm
def base_context(request):
context = dict()
context['user... | SwAsKk/Online_Shop_Django | main/views.py | views.py | py | 1,497 | python | en | code | 0 | github-code | 36 |
43228825355 | # %%
from datasets import load_dataset
from transformers import AutoTokenizer, BertForSequenceClassification, TrainingArguments, Trainer
from transformers import pipeline
# %%
tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
model = BertForSequenceClassification.from_pretrained("distilbert-base-unc... | NgThVinh/dsc_uit | main.py | main.py | py | 2,653 | python | en | code | 0 | github-code | 36 |
31826733278 | import argparse
import pprint
import sys
from designspaceProblems import DesignSpaceChecker
def main(args=None):
parser = argparse.ArgumentParser(
description='Check designspace data.')
parser.add_argument(
'input_ds',
metavar='PATH',
help='path to designspace file',
t... | LettError/DesignspaceProblems | Lib/designspaceProblems/__main__.py | __main__.py | py | 542 | python | en | code | 18 | github-code | 36 |
30898137207 | """
Graph implementation
class GraphMatrix - adjacency matrix
"""
from collections import deque
class GraphMatrix:
"""
Graph implementation using an adjacency matrix
[
[ ]
[ ]
[ ]
]
"""
def __init__(self, size: int):
""" Inits Graph class with optional graph_matrix "... | g-areth/algos | src/algorithms/datastructures/graphs/graph_adj_matrix.py | graph_adj_matrix.py | py | 3,053 | python | en | code | 0 | github-code | 36 |
37936099877 | import apache_beam as beam
with beam.Pipeline() as pipeline:
batches_with_keys = (
pipeline
| 'Create produce' >> beam.Create([
('spring', '🍓'),
('spring', '🥕'),
('spring', '🍆'),
('spring', '🍅'),
('summer', '🥕'),
('summer', '🍅'),
... | ezeparziale/apache-beam-start | examples/groupby_batches.py | groupby_batches.py | py | 529 | python | en | code | 0 | github-code | 36 |
28891383601 | """Initializes and checks the environment needed to run pytype."""
import logging
import sys
from typing import List
from pytype.imports import typeshed
from pytype.platform_utils import path_utils
from pytype.tools import runner
def check_pytype_or_die():
if not runner.can_run("pytype", "-h"):
logging.critic... | google/pytype | pytype/tools/environment.py | environment.py | py | 3,242 | python | en | code | 4,405 | github-code | 36 |
37129616360 | import numpy as np
import cv2
import NeuralNetwork
import json
import os
import matplotlib.pyplot as plt
#defining the initial parameters and the learning rate
batch_size = 10
nn_hdim = 2048
learning_rate = 0.1
f1 = "relu"
f2 = "sigmoid"
threshold = 0.0001
sd_init = 0.01
sd_init_w2 = sd_init
def make_json(W1, W2, b1... | leosegre/medic_ip_project | main.py | main.py | py | 6,594 | python | en | code | 0 | github-code | 36 |
74667010345 | from math import sqrt, cos, sin, pi
import numpy as np
import pyvista as pv
# Affine rotation ####
#' Matrix of the affine rotation around an axis
#' @param theta angle of rotation in radians
#' @param P1,P2 the two points defining the axis of rotation
def AffineRotationMatrix(theta, P1, P2):
T = np.vstack(
... | stla/PyVistaMiscellanous | InvertedSolidMobiusStrip.py | InvertedSolidMobiusStrip.py | py | 3,809 | python | en | code | 4 | github-code | 36 |
33779283072 | #!/usr/local/bin/python3.7
#############
# Imports #
#############
import globalvars
import modules.conf as conf
import modules.misc as misc
import modules.platform as platform
import modules.special as special
import modules.subst as subst
import configparser
import os
import shutil
import subprocess
#############... | kraileth/miniraven | miniraven.py | miniraven.py | py | 10,771 | python | en | code | 1 | github-code | 36 |
5808173653 | from datetime import datetime
class DateBuilder:
def __init__(self, raw_date: str):
self.raw_date = raw_date
def get_month(self):
months = {}
for i, m in enumerate(["january", "febuary", "march", "april", "may", "june", "july", "august", "september", "october", "november", "dec... | Vel4ta/Event_Manager | events/lib/DateBuilder.py | DateBuilder.py | py | 2,102 | python | en | code | 0 | github-code | 36 |
15478699282 | import os
import copy
import sys
import glog
import tifffile
try: from .tools import uity
except: from tools import uity
import numpy as np
from absl import flags, app
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import controller.processing
class TissueCut(object):
def __init__(self, gpu="-1", num... | BGIResearch/StereoCell | stereocell/segmentation/tissue.py | tissue.py | py | 2,701 | python | en | code | 18 | github-code | 36 |
28068881292 | from itertools import combinations
import sys
input = sys.stdin.readline
def solution(orders, course):
answer = {}
for n in course:
food = {}
for i in orders:
combi = list(combinations(sorted(i), n))
for i2 in combi:
try:
food[''.join(... | hwanginbeom/algorithm_study | 2.algorithm_test/21.08.22/21.08.22_gyeonghyeon.py | 21.08.22_gyeonghyeon.py | py | 726 | python | en | code | 3 | github-code | 36 |
40164893998 | from django.shortcuts import render
# Create your views here.
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from django.http.response import JsonResponse
from djangoapi.models import Department,Employee
from djangoapi.serializers import DepartmentSerializer,Employe... | 00karina/FullStackApp | djangoapi/views.py | views.py | py | 1,633 | python | en | code | 0 | github-code | 36 |
10503132777 | import re
stroke_dic = dict()
with open('data/stoke.dat', encoding='utf-8') as f:
data = f.readlines()
for string in data:
temp = string.split("|")
temp[2] = temp[2].replace("\n", "")
stroke_dic[temp[1]] = int(temp[2])
split_dic = dict()
with open('data/chaizi-ft.dat', encoding='utf-8'... | NanBox/PiPiName | stroke_number.py | stroke_number.py | py | 2,480 | python | en | code | 503 | github-code | 36 |
35936751903 | import covasim as cv
import pandas as pd
import sciris as sc
import pylab as pl
import numpy as np
from matplotlib import ticker
import datetime as dt
import matplotlib.patches as patches
import seaborn as sns
import matplotlib as mpl
from matplotlib.colors import LogNorm
# Filepaths
resultsfolder = 'sweeps'
sensfolde... | optimamodel/covid_nsw | 1_submission/plot_nsw_sweeps.py | plot_nsw_sweeps.py | py | 13,309 | python | en | code | 2 | github-code | 36 |
3703533790 | from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from myapp.forms import MyModelForm
from myapp.models import MyModel
def form_request(request, url, template):
if request.method == 'POST':
form = MyModelForm(request.POST)
if form.is_valid():
... | msampaio/estudo_django | myapp/views.py | views.py | py | 1,153 | python | en | code | 0 | github-code | 36 |
29588126043 | import re
NAME=r'(?P<NAME>[a-zA-Z_][a-zA-Z_0-9])'
NUM=r'(?P<NUM>\d+)'
PLUS=r'(?P<PLUS>\+)'
TIMES=r'(?P<TIMES>\*)'
EQ=r'(?P<EQ>=)'
WS=r'(?P<WS>\s+)'
master_pat=re.compile('|'.join([NAME,NUM,PLUS,TIMES,EQ,WS]))
if __name__=="__main__":
scanner=master_pat.scanner('foo=42')
scanner.matcher()
| chen19901225/SimplePyCode | SimpleCode/PY_CookBook/chapter2/chapter2.py | chapter2.py | py | 301 | python | en | code | 0 | github-code | 36 |
29126825853 | #Grupo PHP
#Kevin Cevallos
#María Camila Navarro
#Joffre Ramírez
import ply.lex as lex
reserved = {
'if': 'IF',
'else': 'ELSE',
'elseif': 'ELSEIF',
#'boolean': 'BOOLEAN',
#'float': 'FLOAT',
#'string': 'STRING',
'null': 'NULL',
'array': 'ARRAY',
#'object': 'OBJECT',
'break': 'BRE... | keanceva/ProyectoLP | lexicoLP.py | lexicoLP.py | py | 6,448 | python | en | code | 0 | github-code | 36 |
40109668297 | import tkinter as tk
import tkFont
from tkinter import font
def list_fonts():
font.families()
for f in list(font.families()):
print("Font: ", f)
root = tk.Tk()
btn = tk.Button(root, text="List families", command=list_fonts)
btn.grid(row=0, column=0)
root.mainloop()
| ekim197711/python-tkinter | print_fonts.py | print_fonts.py | py | 299 | python | en | code | 0 | github-code | 36 |
34547409945 | def new_filter(lines, index, inverted):
c = 0
c_1 = 0
for i in lines:
c += 1
if i[index] == "1":
c_1 += 1
if c_1 + c_1 >= c:
print("get 1")
if inverted:
f_v = "0"
else:
f_v = "1"
else:
if inverted:
f_v ... | marin-jovanovic/advent-of-code | 2021/03/part_two.py | part_two.py | py | 1,005 | python | en | code | 0 | github-code | 36 |
29073464319 | import csv
import datetime
import pathlib
from typing import Generator
import click
from case_rate._types import Cases, CaseTesting, PathLike
from case_rate.sources._utilities import download_file
from case_rate.storage import InputSource
def _to_date(date: str) -> datetime.date:
'''Converts a date string into ... | richengguy/case-rate | src/case_rate/sources/public_health_agency_canada.py | public_health_agency_canada.py | py | 4,097 | python | en | code | 0 | github-code | 36 |
38066575543 | # import the argmax function from numpy to get the index of the maximum value in an array
from numpy import argmax
# import the mnist dataset from keras, which contains 60,000 images of handwritten digits for training and 10,000 images for testing
from keras.datasets import mnist
# import the to_categorical function fr... | mohammadnr2817/digit_classifier | digit_classifier.py | digit_classifier.py | py | 11,367 | python | en | code | 0 | github-code | 36 |
72092398505 | day1 = ("monday", "tuesday", "wednesday") # 변수 day1에 문자열이 요소인 튜플 만들어 대입
day2 = ("thursday", "friday", "saturday") # 변수 day2에 문자열이 요소인 튜플 만들어 대입
day3 = ("sunday", ) # 변수 day3에 문자열이 요소인 튜플 만들어 대입, 요소가 1개인 튜플은 만들때 만드시 요소 뒤에 ,콤마를 써야한다.
day = day1 + day2 + day3 # 변수 day에 튜플 day1, day2, day3를 튜플 연결 연산자 +를 이용하여 새로 만들어진 튜플 대입... | jectgenius/python | ch05/05-13daytuple.py | 05-13daytuple.py | py | 966 | python | ko | code | 0 | github-code | 36 |
42153809968 | # 1012 유기농배추
import sys
sys.setrecursionlimit(10**6)
case = int(input())
moves = [[0, 1], [0, -1], [-1, 0], [1, 0]]
def dfs(graph, x, y):
graph[y][x] = 2
for move in moves:
nx = x+move[0]
ny = y+move[1]
if 0 <= nx < len(graph[0]) and 0 <= ny < len(graph):
if graph[ny][nx]... | FeelingXD/algorithm | beakjoon/1012.py | 1012.py | py | 763 | python | en | code | 2 | github-code | 36 |
27142738401 | from django.shortcuts import render, get_object_or_404
from .models import Animal
def index(request):
animais = Animal.objects.all()
return render(request, 'clientes/index.html', {
'animais': animais
})
def ver_animal(request, animal_id):
animal = get_object_or_404(Animal, id=animal_id)
... | LorenzoBorges/Projeto-Veterinario | clientes/views.py | views.py | py | 406 | python | en | code | 0 | github-code | 36 |
74117892903 | # Números primos: Escreva um programa que determine se um número é primo ou não.
num = int(input("Digite um número para verificar se é primo ou não: "))
if num < 2:
print(f"{num} não é primo")
for i in range(2, num):
if num % i == 0:
print(f"{num} não é primo")
break
else:
print(f"{num} é... | kingprobr/Python-Exercises | PrimeNumber.py | PrimeNumber.py | py | 341 | python | pt | code | 0 | github-code | 36 |
11539702751 | import os
import pygame
import pygame.color
from views.panelview import PanelView
class MenuView(PanelView):
def __init__(self, config, bus):
PanelView.__init__(self, config, bus)
self.fntRegText = pygame.font.Font(os.path.join(self.config.script_directory, "assets/Roboto-Regular.ttf"), 16)
... | mcecchi/OctoPiControlPanel | views/menuview.py | menuview.py | py | 2,401 | python | en | code | 1 | github-code | 36 |
27182055536 | # Viết chương trình in bảng cửu chương từ 2 đến n (Xuất ra theo cột)
while True:
n=int(input("Nhập số nguyên n: "))
if n <= 2:
print("Nhập số nguyên n > 2 nha, please")
continue
break
for i in range(1,10):
for j in range(2, n+1):
print("{}x{}={}".format(i, j, i *j), end='\t')
... | hanhkim/py_fundamental | Tuan3_300923/bai5.py | bai5.py | py | 363 | python | vi | code | 0 | github-code | 36 |
17210427292 | #!/usr/bin/env python3
import rospy
import numpy as np
from nav_msgs.msg import Odometry
from rosflight_msgs.msg import Command
from diff_flatness import diff_flatness
from traj_planner import trajectory_planner
from controller import controller
import yaml
# import matplotlib.pyplot as plt
class simTester:
def ... | malioni/demo | scripts/sim_tester.py | sim_tester.py | py | 5,990 | python | en | code | 0 | github-code | 36 |
70887541865 | #!/usr/bin/env python
# coding: utf-8
# Leet Code problem: 206
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# Iteratively
# class Solution:
# def reverseList(self, head: Optional[ListNode]) -> Optional[List... | jwilliamn/trenirovka-code | leetc_206.py | leetc_206.py | py | 1,138 | python | en | code | 0 | github-code | 36 |
2050897159 | from openpyxl import load_workbook, Workbook
from django.core.management import BaseCommand
from django.db.utils import IntegrityError
from nomenclature.models import *
SERVICE_TYPES = [
'Not defined',
'ПРОФ',
'Лабораторное исследование',
'Коммерческий профиль',
'Услуга'
]
class Command(BaseComma... | Sin93/lab | nomenclature/management/commands/import.py | import.py | py | 9,200 | python | en | code | 0 | github-code | 36 |
14299284987 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/1/9 17:59
# @Author : lingxiangxiang
# @File : demonpyexcele.py
import pyExcelerator
#创建workbook和sheet对象
wb = pyExcelerator.Workbook()
ws = wb.add_sheet(u'第一页')
#设置样式
myfont = pyExcelerator.Font()
myfont.name = u'Times New Roman'
myfont.bold = True
my... | ajing2/python3 | tmptestdemon/dataprocess/demonpyexcele.py | demonpyexcele.py | py | 930 | python | zh | code | 2 | github-code | 36 |
34408041143 | class Solution:
def maxProfit(self, prices: list[int]) -> int:
left, right = 0, 1
max_profit = 0
while right < len(prices):
if prices[left] < prices[right]:
# Calculate profit
profit = prices[right] - prices[left]
max_profit = max(m... | anuragMaravi/LeetCode-Solutions | python3/121. Best Time to Buy and Sell Stock.py | 121. Best Time to Buy and Sell Stock.py | py | 494 | python | en | code | 0 | github-code | 36 |
25874083390 | #! python3
# scraper for dark souls armor
import requests
import re
import sqlite3
from bs4 import BeautifulSoup
import time
# connecting to actual database
conn = sqlite3.connect("./databases/armor.db")
# testing connection
# conn = sqlite3.connect(":memory:")
c = conn.cursor()
with conn:
c.execute("""CREAT... | Bipolarprobe/armorcalc | armorscrape.py | armorscrape.py | py | 3,289 | python | en | code | 0 | github-code | 36 |
41774888432 | import time
import sys
sys.path.append("../")
from Utils_1 import Util
import pymysql
from lxml import etree
import requests
import http
from Utils_1.UA import User_Agent
import random
"""
数据来源:中华人民共和国商务部
来源地址:http://femhzs.mofcom.gov.cn/fecpmvc/pages/fem/CorpJWList_nav.pageNoLink.html?session=T&sp=1&sp=S+_t1... | 921016124/Spiders | module/对外投资/femhzs_mofcom_gov.py | femhzs_mofcom_gov.py | py | 5,506 | python | en | code | 0 | github-code | 36 |
74339876262 | #!/usr/bin/env python3
# pip install unittest-xml-reporting
# pip install coverage
# sudo pip install flake8
# pip install --upgrade --pre pybuilder
# sudo pyb install_dependencies publish
# See also as example : https://github.com/yadt/shtub/blob/master/build.py
# sudo apt-get install python-setuptools python-all debh... | kvogelgesang/py-rest-sys-collect | build.py | build.py | py | 7,931 | python | en | code | 0 | github-code | 36 |
18798753930 |
class Song:
"""class to represent a song
attributes:
title (str): the title of the song
artist(str): name of the songs creator.
duration(int): the duration of the song in seconds. may be zerp
"""
def __init__(self, title, artist, duration = 0):
self.title =... | DhanKumari/python_2 | oops_song(new).py | oops_song(new).py | py | 4,515 | python | en | code | 0 | github-code | 36 |
1544319051 | import json
import pandas as pd
# import file
print("reading actors.tsv")
actors_df = pd.read_csv('actors.tsv', sep='\t')
# drop unused columns
print("processing data")
actors_df = actors_df.drop(columns=['nconst', 'birthYear', 'primaryProfession', 'knownForTitles'])
actors_df['primaryName'] = actors_df['primaryName'... | stephanieyaur/gg-project | actors_modifier.py | actors_modifier.py | py | 742 | python | en | code | null | github-code | 36 |
36772978754 | """
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
"""
# Definition for a binary tre... | narendra-solanki/python-coding | BinaryTreeLevelOrder.py | BinaryTreeLevelOrder.py | py | 1,730 | python | en | code | 0 | github-code | 36 |
16968865127 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
from django.utils.translation import ugettext_lazy as _
USERNAME_FIELD_HELP_TEXT = _(
'Required field. Leng... | infolabs/django-edw | backend/edw/admin/customer/forms.py | forms.py | py | 2,967 | python | en | code | 6 | github-code | 36 |
35396451951 | #!/usr/bin/env python3
# coding=utf-8
'''MDMForm 系统配置主窗口'''
import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QPalette, QPixmap, QIcon
from PyQt5.QtWidgets import QMainWindow,QMessageBox,QTableWidgetItem,QFileDialog
from PyQt5 import QtSql
from PyQt5.QtSql import QSqlQuery
f... | LeeZhang1979/UniTools | src/MDMForm.py | MDMForm.py | py | 19,446 | python | en | code | 0 | github-code | 36 |
16816398616 | '''import random
countries = ['gt', 'nic', 'cr']
population = {country: random.randint(1, 100)
for country in countries}
print(population)
result2 = {country: population for (country, population) in population.items() if population > 50}
print(result2)
text = 'Hola, si soy una mierda'
unique = {c: text.count(c) for ... | Fergg9/Python_one | dictComp_Condi.py | dictComp_Condi.py | py | 871 | python | es | code | 0 | github-code | 36 |
18187575174 | from casinos_manager import CasinosManager
from player import EmptyPlayer, HumanPlayer, MLPlayer, RuleBasePlayer, RandomPlayer
class PlayersManager:
def __init__(self, print_game: bool = True):
self._player_slots = [EmptyPlayer(index=i + 1) for i in range(5)]
self._print_game = print_game
def... | KeunhoByeon/LasVegas_Python | players_manager.py | players_manager.py | py | 4,667 | python | en | code | 0 | github-code | 36 |
27702917459 | from re import L
from flask import Flask
from flask import jsonify
from flask import request
from flask_restful import Api, Resource, reqparse
import json
import sys
from get_details import get_name
from process_swipe import process_swipe
import requests
import random
from eventlet import wsgi
import eventlet
from redi... | mbruty/COMP2003-2020-O | recommender/main.py | main.py | py | 5,688 | python | en | code | 3 | github-code | 36 |
8857084207 | from tkinter import *
import core
class GUI:
"""
py2048 GUI
"""
windowtitle = "py2048"
tilesize = 50
tilepadding = 5
topheight = 50
bottomheight = 50
def __init__(self, core):
self.core = core
self.window = Tk()
self.window.title(GUI.windowtitle)
... | StuartSul/py2048 | py2048/gui.py | gui.py | py | 1,051 | python | en | code | 1 | github-code | 36 |
34086497372 | from subprocess import call
import os,sys
def create_udb(repo_):
repo_name = os.path.basename((repo_))
udb_name = repo_name + '.udb'
print(repo_name,udb_name)
call('und create -languages python c++ java ' + udb_name ,shell = True)
call('und add -db '+ udb_name + ' ' + repo_ ,shell = True)
call(... | akhilsinghal1234/mdd-intern-work | Extraction/batch.py | batch.py | py | 404 | python | en | code | 0 | github-code | 36 |
33677703357 | from app.models import TraceLog
import os
import sys
class Logger:
METHOD = {
"GET": "\033[94mGET\033[m",
"POST": "\033[92mPOST\033[m",
"PUT": "\033[93mPUT\033[m",
"PATCH": "\033[96mPATCH\033[m",
"DELETE": "\033[91mDELETE\033[m"
}
@classmethod
def log(cls, type... | Mauricio-Silva/backend-user | app/utils/logger.py | logger.py | py | 2,230 | python | en | code | 0 | github-code | 36 |
876066722 | from invertpy.brain.mushroombody import PerfectMemory, WillshawNetwork
from invertpy.sense import CompoundEye
from invertsy.agent import VisualNavigationAgent
from invertsy.env.world import Seville2009, SimpleWorld
from invertsy.sim.simulation import VisualNavigationSimulation
from invertsy.sim.animation import Visual... | InsectRobotics/InvertSy | examples/test_vis_nav_simple_world.py | test_vis_nav_simple_world.py | py | 2,060 | python | en | code | 1 | github-code | 36 |
73547213863 | #!/usr/local/bin/python3
# coding=utf-8
import random
import copy
from Chord import Chord
from BaseEvent import BaseEvent
import Midi
from Utils import *
class Event (BaseEvent):
def __init__(self, name = None, index = None, time = None, duration = 4, octave = 0, volume = 100, pitches = [], mode = None, channel = ... | psenzee/MuGen | src/Event.py | Event.py | py | 9,557 | python | en | code | 0 | github-code | 36 |
36031367368 | def elimduplicados():
lista = []
n = int(input("Ingrese la cantidad de numeros en la lista: "))
if n.isdigit():
for i in range(0, n):
ele = int(input())
lista.append(ele)
print (list(set(lista)))
else:
print("El valor insertado no es un numero.") | Vitio11/StartPython | Ejercicio19.py | Ejercicio19.py | py | 310 | python | es | code | 0 | github-code | 36 |
69822409383 | # -*- coding: utf-8 -*-
"""Subclass of ``BasisSet`` designed to represent an OpenMX configuration."""
import collections
import json
import pathlib
from typing import Sequence
from importlib_resources import files
from aiida_basis.data.basis import PaoData
from ...metadata import openmx as openmx_metadata
from ..mixin... | azadoks/aiida-basis | aiida_basis/groups/set/openmx.py | openmx.py | py | 8,289 | python | en | code | 0 | github-code | 36 |
74436895785 | # Author Chaudhary Hamdan
from functools import reduce
def factors(n):
return set(reduce(list.__add__,
([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))
t = int(input())
for _ in range(t):
n,k = [int(x) for x in input().split()]
if k == 0:
print(0)
... | hamdan-codes/codechef-unrated-contests | Codingo21_CODINGO01.py | Codingo21_CODINGO01.py | py | 536 | python | en | code | 2 | github-code | 36 |
43511996346 | import os
from django.test import TestCase
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse
from django.core.exceptions import ImproperlyConfigured
from hitparade.models import *
from hitparade.utils import *
from hitparade.tests.helpers imp... | HitParade/hitparade | web/hitparade/hitparade/tests/integration/test_endpoints.py | test_endpoints.py | py | 1,924 | python | en | code | 1 | github-code | 36 |
72721111143 | from utilities import util
import binascii
# Challenge 52
STATE_LEN = 2 # 16 bits
AES_BLOCK_SIZE = 16
# merkle damgard construction using AES-128 as a compression function
def md_hash(message, state_len = STATE_LEN, H = None):
# initial state
h = b''.join([util.int_to_bytes((37*i + 42) % 256) for i in range(stat... | fortenforge/cryptopals | challenges/iterated_hash_multicollisions.py | iterated_hash_multicollisions.py | py | 2,422 | python | en | code | 13 | github-code | 36 |
36315576627 | from __future__ import print_function
import sys
import json
import collections
import getopt
g_debug = False
g_indent = 4
def debug(s):
if g_debug:
print("DEBUG> " + s)
def usage(s):
sys.stderr.write("Usage: %s [-t <indent>] [-d] <[-f <json file>] | txt>\n"
% s)
sys.stderr... | idorax/vCodeHub | sharpsword/python/jsonfmt.py | jsonfmt.py | py | 1,840 | python | en | code | 1 | github-code | 36 |
75071109224 | import requests
import pandas as pd
import numpy as np
import seaborn as sns
from bs4 import BeautifulSoup
import warnings
import nltk
#import surprise
import scipy as sp
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import CountVectorizer
from nltk.corpus import stopword... | Liixxn/MovieMender | generos.py | generos.py | py | 7,990 | python | es | code | 1 | github-code | 36 |
17793223864 | from dgl.nn.pytorch.conv import SAGEConv
import torch
import torch.nn as nn
import torch.nn.functional as F
import time
import numpy as np
from dgl import DGLGraph
from dgl.data import citation_graph as citegrh
import networkx as nx
class GraphSAGE(nn.Module):
def __init__(self,
in_feats,
... | Gabtakt/GNN-lab | GraphSAGE.py | GraphSAGE.py | py | 2,428 | python | en | code | 1 | github-code | 36 |
22564966347 | class Solution:
def maximumDetonation(self, bombs: List[List[int]]) -> int:
graph = defaultdict(list)
for i in range(len(bombs)):
for j in range(len(bombs)):
if i != j:
if( bombs[i][0] - bombs[j][0]) ** 2 + (bombs[i][1] - bombs[j][1]) ** 2 <= (bombs[i][... | miedan/competetive-programming | detonate-the-maximum-bombs.py | detonate-the-maximum-bombs.py | py | 756 | python | en | code | 0 | github-code | 36 |
42222604118 | """ new visualizations 2020
Revision ID: 437ffc36a821
Revises: d73f1a3bccf3
Create Date: 2020-07-16 19:48:01.228630
"""
from alembic import op
from sqlalchemy import String, Integer
from sqlalchemy.sql import table, column, text
from caipirinha.migration_utils import get_enable_disable_fk_command
# revision identi... | eubr-bigsea/caipirinha | migrations/versions/437ffc36a821_new_visualizations_2020.py | 437ffc36a821_new_visualizations_2020.py | py | 2,171 | python | en | code | 1 | github-code | 36 |
17792225774 | from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import os
import re
from builtins import open
from pants.backend.codegen.antlr.java.java_antlr_library import JavaAntlrLibrary
from pants.backend.jvm.targets.java_library import JavaLibrary
from pants.backend.jvm.tasks.n... | fakeNetflix/twitter-repo-pants | src/python/pants/backend/codegen/antlr/java/antlr_java_gen.py | antlr_java_gen.py | py | 6,475 | python | en | code | 0 | github-code | 36 |
22346293555 | class Game:
def __init__(self, id):
self.p_one_moved = False
self.p_two_moved = False
self.ready = False
self.id = id
self.moves = [None, None]
self.wins = [0,0]
self.ties = 0
def get_player_move(self, p):
return self.moves[p]
def play(self,... | guiltylogik/BasicPythonGames | multi_player/game.py | game.py | py | 1,259 | python | en | code | 0 | github-code | 36 |
74779852584 | from unittest import TestCase
from collections import namedtuple
from P2_Sorting.HeapSort.heap_sort import heap_sort
class Task(object):
def __init__(self, deadline, penalty):
assert isinstance(deadline, int) and deadline > 0
assert penalty > 0
self._penalty = penalty
self._deadli... | GarfieldJiang/CLRS | P4_AdvancedTech/Greedy/task_scheduling_with_matroid.py | task_scheduling_with_matroid.py | py | 4,191 | python | en | code | 0 | github-code | 36 |
71967566185 | import subprocess
import pytest
from pipfile2req.requirements import requirement_from_pipfile
def compare_requirements(left, right):
return len(set(left.splitlines()) - set(right.splitlines())) == 0
@pytest.mark.parametrize(
"command,golden_file",
[
("pipfile2req -p tests", "tests/requirements.... | frostming/pipfile-requirements | test_pipfile_requirements.py | test_pipfile_requirements.py | py | 2,499 | python | en | code | 49 | github-code | 36 |
29498462869 | from main import validate_amount_payment, define_amount_hour, get_amount_hour, read_data_file
from constant.days_info import list_days
import pytest
def test_validate_valid_line():
assert validate_amount_payment(
"THOMAS=MO08:00-12:00,TU10:00-13:00,TH01:00-04:00,SA14:00-18:00,SU20:00-23:00",
defin... | jefvasquezg/acme | test/test_main.py | test_main.py | py | 2,193 | python | en | code | 0 | github-code | 36 |
42469623972 | import os
import morfeusz2
import pandas as pd
from sklearn.metrics import classification_report
def lemmatize_text(text):
if isinstance(text, str):
text = text.split()
morf = morfeusz2.Morfeusz(expand_dag=True, expand_tags=True)
text_new = []
for word in text:
w = morf.analyse(word)[0... | kingagla/reviews_classification | scripts/utils.py | utils.py | py | 1,049 | python | en | code | 3 | github-code | 36 |
70942499944 | from pyspark.sql import SparkSession
from pyspark.sql.functions import col
import boto3
session = boto3.Session(profile_name="***_AdministratorAccess",region_name="us-east-1")
s3 = boto3.resource('s3')
# Inicialize a sessão do Spark
spark = SparkSession.builder.getOrCreate()
# Leia os arquivos Parquet e crie os dataf... | nataliasguimaraes/compassuol | sprint_09/desafio_etl/processed_trusted/proc_trusted.py | proc_trusted.py | py | 2,573 | python | pt | code | 0 | github-code | 36 |
3060572520 | #!/usr/bin/python
import xlswriter
workbook = xlswriter.Workbook('merge1.xlsx')
worksheet = workbook.add_worksheet()
worksheet.set_column('B:D, 12')
worksheet.set_row(3, 30)
worksheet.set_row(6, 30)
worksheet.set_row(7, 30)
merge_format = workbook.add_format({
'bold': 1,
'border': 1,
'align': 'center',
'valign':... | psmano/pythonworks | pyworks/testxlswriter.py | testxlswriter.py | py | 497 | python | en | code | 0 | github-code | 36 |
9993947987 | import paho.mqtt.client as mqtt
import os, time
import random
from threading import Thread
import sys
USERNAME = "ttdqymlc"
PASSWORD = "x8cN-GqZBJPK"
SERVER = "m16.cloudmqtt.com"
PORT = 14023
QOS = 0
topic_sub = "edgex2device"
topic_pub = "device2edgex"
# -------------------ham cho xu ly du lieu--------------------... | phanvanhai/DeviceService-Zigbee | demo/master_device.py | master_device.py | py | 6,353 | python | en | code | 0 | github-code | 36 |
71277311783 | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# 21-Merge-Two-Sorted-Lists
""" Logic: Use a loop to go through the linked
lists, store the smaller value in the
new result linkedlist."""
def mergeTwoLists(self, list1: Optional[Li... | aryanv175/leetcode | 21-Merge-Two-Sorted-Lists/solution.py | solution.py | py | 721 | python | en | code | 2 | github-code | 36 |
75084616422 | """
firebase.py
This module caches video information in Firebase using the user's id as the key.
Cached video entries include duration, title, channel name, category, and timestamp.
The timestamp acts as a TTL of 24 hours, and entries older than the TTL are updated by requesting
the video information from the YouTube ... | ractodev/youtube-wrapped-v1 | utils/firebase.py | firebase.py | py | 4,392 | python | en | code | 1 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.