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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
35869726819 | meme_dict = {
"CRINGE": "Algo excepcionalmente raro o embarazoso",
"LOL": "Una respuesta común a algo gracioso",
"SHEESH":"una ligera desaprobacion" ,
"CREEPY":"aterrador,siniestro" ,
"TO AGGRO":"ponerse agresivo" ,
}
whil... | ikerespot/kodland | test.py | test.py | py | 539 | python | es | code | 0 | github-code | 90 |
1966785105 | from brownie import DailyRocket, accounts, network, config
from scripts.helpful_scripts import get_account
fDai = 0x15F0Ca26781C3852f8166eD2ebce5D18265cceb7
def main():
account = get_account()
DailyRocket.deploy(
fDai,
{'from': account}
)
#the constructor has two arguments, addresses ... | Benevolent-MoonG-F/Benevolent | scripts/deploys/deploy_DailyRocket.py | deploy_DailyRocket.py | py | 382 | python | en | code | 1 | github-code | 90 |
31319739765 | THEME_COLOR = "#375362"
FONT=("Arial", 20, 'italic')
from tkinter import *
class QuizUI:
def __init__(self, quiz_brain):
self.quiz = quiz_brain
self.window = Tk()
self.window.title("Quiz")
self.window.config(padx= 20, pady= 20, bg= THEME_COLOR)
self.score_label = Label(text... | Synyster008/Python_Projects | Quiz API/ui.py | ui.py | py | 1,895 | python | en | code | 0 | github-code | 90 |
381713440 | #http://code.activestate.com/recipes/580698-reversi-othello/
import os, copy
class OthelloBoard():
pass_counter = 0
dirx = [-1, 0, 1, -1, 1, -1, 0, 1]
diry = [-1, -1, -1, 0, 0, 1, 1, 1]
def __init__(self, n):
self.n = n
self.board = [[0 for i in range(8)] for j in range(8)]
... | oliverzhang42/reinforcement-learning-othello | OthelloBoard.py | OthelloBoard.py | py | 5,763 | python | en | code | 6 | github-code | 90 |
18669740305 | import abc
import copy
from typing import Optional
import attr
from bech32 import bech32_encode, convertbits
from secret_sdk.core import (
AccAddress,
AccPubKey,
ModeInfo,
ModeInfoSingle,
SignatureV2,
SignDoc,
ValAddress,
ValPubKey,
)
from secret_sdk.core.public_key import (
Public... | secretanalytics/secret-sdk-python | secret_sdk/key/key.py | key.py | py | 7,371 | python | en | code | 37 | github-code | 90 |
29199376862 | #----------------------------Dependencies-----------------------------------
from centroidtracker import CentroidTracker
from matplotlib import pyplot as plt
import matplotlib
import numpy as np
import cv2
from detect import detect
from datetime import datetime
matplotlib.use('TkAgg')
#----------------------... | devanshmesson/Major-Project-1 | Models/Class Counting/main.py | main.py | py | 7,725 | python | en | code | 0 | github-code | 90 |
20264864661 | """
62-unique-paths
leetcode/medium/62. Unique Paths
Difficulty: medium
URL: https://leetcode.com/problems/unique-paths/
"""
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
matrix = [[0 for _ in range(n)] for _ in range(m)]
matrix[0][0] = 0
for i in range(m):
for... | polyglotm/coding-dojo | coding-challange/leetcode/medium/~2022-06-04/62-unique-paths/62-unique-paths.py | 62-unique-paths.py | py | 827 | python | en | code | 2 | github-code | 90 |
35225716529 | from abc import ABC, abstractmethod
import numpy as np
import cv2
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib import _pylab_helpers
from scipy.signal import savgol_filter
from skeleton_tools.skeleton_vi... | TalBarami/SkeletonTools | skeleton_tools/skeleton_visualization/paint_components/dynamic_graphs/dynamic_graphs.py | dynamic_graphs.py | py | 5,485 | python | en | code | 0 | github-code | 90 |
29861539104 | print("Welcome to the Fibonacci Calculator App")
x = int(input("\nHow many digits of the Fibonacci sequence you would like to compute: "))
print("\nThe first " + str(x) + " numbers of the Fibonacci sequence are: ")
fib = [1,1]
for i in range(x-2):
new_fib = (fib[i] + fib[i+1])
fib.append(new_fib)
print("... | tavleenbajwa8/pythoncodes | Fibonacci_Sequence_Calculator_App.py | Fibonacci_Sequence_Calculator_App.py | py | 694 | python | en | code | 0 | github-code | 90 |
5268722440 | #!/usr/bin/python
from turtle import width
from bs4 import BeautifulSoup
import os, glob
import cv2
import urllib.request
import numpy as np
OK_WIDTHS=[210, 315, 370, 1000]
BAD_FILES=[]
# Process all .md files in folder and sub-folders for image blocks
for filename in glob.glob('**/*.md', recursive=True):
print(... | RoninTech/CarryOnRoundTheWorld | content/lpcount.py | lpcount.py | py | 2,033 | python | en | code | 0 | github-code | 90 |
18368931139 | N = int(input())
l = list(map(int, input().split()))
a = [0] * (N+1)
for k in reversed(range(1, N+1)):
num = sum([a[k*i] for i in range(1, N//k+1)])
if num % 2 != l[k-1]:
a[k] = 1
M = sum(a)
ans = [i for i in range(1, N+1) if a[i] > 0]
print(M)
print(' '.join(map(str, ans))) | Aasthaengg/IBMdataset | Python_codes/p02972/s552307878.py | s552307878.py | py | 293 | python | en | code | 0 | github-code | 90 |
23788632764 | import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model, preprocessing
import scipy
from sklearn import datasets, linear_model, preprocessing
from sklearn.datasets import fetch_mldata
import matplotlib.image as mpimg
import skimage.io
from skimage.filters import threshold_otsu
from skimage.s... | sunyi199374/L-BFGS-Based-Adversarial-Input-Against-SVM- | L-BFGS_Based_Adversarial_Attack.py | L-BFGS_Based_Adversarial_Attack.py | py | 7,771 | python | en | code | 4 | github-code | 90 |
18370370289 | from collections import Counter
n = int(input())
a = list(map(int,input().split()))
if sum(a)==0:
print('Yes')
else:
if n%3!=0:
print('No')
else:
s = len(set(a))
if s>3:
print('No')
else:
l = Counter(a)
tf = 1
if s==3:
for v in l.values():
if v!=n//3:
... | Aasthaengg/IBMdataset | Python_codes/p02975/s348975893.py | s348975893.py | py | 636 | python | en | code | 0 | github-code | 90 |
7459894381 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 18 09:40:42 2016
@author: rob
"""
from os import listdir
import readroi
import PIL
import numpy as np
import random as rnd
#filepath = 'C:\\Users\\rob\\Documents\\Thesis\\tp_approved'
def getRois(filepath):
roiFileNames = [f for f in listdir(filepath) if '.zip' in f ... | raguilar1/Thesis | Code/imageHelper.py | imageHelper.py | py | 4,088 | python | en | code | 0 | github-code | 90 |
74499675817 | from tkinter import Tk, BooleanVar
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
class FrameMenu(ttk.Frame):
def __init__(self, parent, controller):
super().__init__(parent)
self.controller = controller
self.fr_option = ttk.Frame(self)
se... | jonasht/python | 04-flashcard_DeTabuada/tabuada-V6/frameMenu.py | frameMenu.py | py | 3,218 | python | en | code | 0 | github-code | 90 |
21146689698 | """making user phone nullable
Revision ID: 15c9834e0b4f
Revises: 3b4890df160d
Create Date: 2015-01-20 00:09:15.533625
"""
# revision identifiers, used by Alembic.
revision = '15c9834e0b4f'
down_revision = '3b4890df160d'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgr... | krishnatejak/renaissance_men | alembic/versions/15c9834e0b4f_making_user_phone_nullable.py | 15c9834e0b4f_making_user_phone_nullable.py | py | 779 | python | en | code | 0 | github-code | 90 |
40395396265 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from peewee import *
from src.db.peewee_mysql import MyRetryDB, MyBaseModel
from src import config
def create_database(key):
db = config[config["base"]["region"]][key]
return MyRetryDB(db["db"], **{
"host": db["host"],
"port": db["port"],
... | yuansx/scheduler | src/db/models.py | models.py | py | 1,814 | python | en | code | 0 | github-code | 90 |
18173389659 | import sys
read = sys.stdin.read
#readlines = sys.stdin.readlines
def main():
n = int(input())
rc = tuple(input())
rc2 = [c == 'W' for c in rc]
r1 = sum(rc2) # 白をすべて赤にした場合
r2 = n - r1 # 赤をすべて白にした場合。
r3 = sum(rc2[:r2]) # 赤を左につめるのに邪魔になる白の数
print(min(r1, r2, r3))
if __name__ == '__main__':
... | Aasthaengg/IBMdataset | Python_codes/p02597/s290414703.py | s290414703.py | py | 409 | python | ja | code | 0 | github-code | 90 |
24509606568 | class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
res = set(t) - set(s)
if(res):
return list(res)[0]
else:
dict1 = {}
for char in t:
dict1[char] ... | taoran12/leetcode | 389-Find the Difference/Solution.py | Solution.py | py | 550 | python | en | code | 1 | github-code | 90 |
16054110821 | from discord.ext import commands
from pymongo import MongoClient
import os
import certifi
import requests
import time
from tabulate import tabulate
from dotenv import load_dotenv
from uuid import UUID
load_dotenv()
class Wynncraft(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.bot.l... | RawPikachu/chest-count-rewrite | Wynncraft.py | Wynncraft.py | py | 3,003 | python | en | code | 1 | github-code | 90 |
23129012410 |
from baseviews import TemplateView, BaseView, BaseResponse
from models import GetPodcastManager, PodcastManager, Podcast
class Index(TemplateView):
""" Index view """
template = "index.tpl"
destFilenameFormatHelp = (
" %filename% - The Original Download Filename<br />" +
" %title% -... | obmarg/pypod | ui/views.py | views.py | py | 1,725 | python | en | code | 1 | github-code | 90 |
44523109805 | '''
Sample predictive model.
You must supply at least 4 methods:
- fit: trains the model.
- predict: uses the model to perform predictions.
- save: saves the model.
- load: reloads the model.
'''
import os
#os.system('pip3 install lightgbm==2.2.2')
#os.system('pip3 install hyperopt')
import pandas as pd
import pickle
... | MetaLearners/Auto-Stream | Auto-Stream/model.py | model.py | py | 13,213 | python | en | code | 0 | github-code | 90 |
20124277111 | import pygame
import math
import os
import time
import random
pygame.font.init() #inicializa las fuentes de texto en pygame
#Se crea la pantalla
ANCHO, ALTO = 1000, 667
VEN = pygame.display.set_mode((ANCHO, ALTO))
pygame.display.set_caption("PT2")
#Se cargan las imágenes
NAVE_JUGADOR = pygame.image.load("Arcadia.png... | Marco-but-stupid/ProyectoTaller | PT2_no_venv/Juego.py | Juego.py | py | 6,366 | python | es | code | 0 | github-code | 90 |
5508568379 | import math
def prime(n):
if n < 2:
return False
else:
for i in range(2,int(math.sqrt(n) + 1)):
if n % i == 0:
return False
return True
def input_List():
sets = []
n = int(input("Enter n: "))
for i in range(n):
sets.inse... | khanhdepdai/learn-python-branium | SubjectPythonBranium/Chương3/3_6/Bai4.py | Bai4.py | py | 695 | python | en | code | 0 | github-code | 90 |
3340387871 | ##################################################################
# FILE : ex7.py
# WRITER : Lior Paz, lioraryepaz, 206240996
# EXERCISE : intro2cs ex7 2017-2018
# DESCRIPTION : a number of various functions that are using recursion,
# with the top among them - hanoi!!!!!! how fun to play with
##################... | lappazos/Intro_Ex_7_Recursion | ex7.py | ex7.py | py | 7,891 | python | en | code | 0 | github-code | 90 |
36913930936 | """
Module supporting arithetic on polynomials with coefficients
drawn from a finite field
(only tested with subclasses of zmodp.ZModBase as the field).
"""
from collections import deque
from itertools import zip_longest
class PolynomialBase:
"""
Base class for Polynomial classes.
"""
field = int
... | benpbenp/fhepy | fhepy/polynomials.py | polynomials.py | py | 4,605 | python | en | code | 1 | github-code | 90 |
37671028824 | import random
from django.db.models import Max
def get_random_object(obj):
max_id = obj.objects.all().aggregate(max_id=Max("id"))["max_id"]
while True:
pk = random.randint(1, max_id)
random_obj = obj.objects.filter(pk=pk).first()
if random_obj:
return random_obj
| mit-teaching-systems-lab/newelk | chat/utils.py | utils.py | py | 310 | python | en | code | 0 | github-code | 90 |
11186389039 | #!/usr/bin/python3
CLIENT='002' #each player needs to have a different CLIENT number. Must be 3 digits and have preceding 0s. e.g. 001, 002, 003
#LTSERVER='192.168.1.102' #insert IP address of server computer
#---------------------
#BUZZER: GPIO5
#TRIGGER: GPIO26
#RELOAD: GPIO12
#IR_TX: GPIO25
#IR_RX... | hycap-academy/Lasertag | player3.py | player3.py | py | 9,077 | python | en | code | 0 | github-code | 90 |
18455237099 | def grand_garden(n, h):
count = 0
j = 100
for i in range(n):
if h[i] != 0:
j = i
break
if j == 100:
return count
while h[j] != 0:
l = j # 左はしきめる
r = l # 動く右はし
for k in range(l, n): # 右端はZeroでないかぎりのばす、ゼロになる最初の位置を取得、すべてゼロでなければ配列の右端
... | Aasthaengg/IBMdataset | Python_codes/p03147/s526147169.py | s526147169.py | py | 1,895 | python | ja | code | 0 | github-code | 90 |
16740577213 | from selenium.webdriver import Remote
from selenium.webdriver import DesiredCapabilities
from tests_environment.set_env_config import SetEnvConfig
class WebDriverSessionCreator:
def create_session(self):
if SetEnvConfig().set_browser() == 'chrome':
return self.__chrome_session()
elif S... | sebajacek001/awesome-launcher | tests_environment/session_creator.py | session_creator.py | py | 1,829 | python | en | code | 0 | github-code | 90 |
41630133083 | import conexao as cnx
cur_dest = cnx.get_cursor(cnx.conexao_destino)
cur_orig = cnx.get_cursor(cnx.conexao_origem)
# cur_aux = cnx.get_cursor(cnx.conexao_aux)
def cadastro():
print("Cadastrando tramites...")
insert = cur_dest.prep("""INSERT INTO se_ptramite (cod_emp_ptr, codigo_ptr, exercicio_ptr, item_ptr, s... | Dhaxx/CONVERSOR_DAAE_SSEWEB | tramites.py | tramites.py | py | 1,576 | python | pt | code | 1 | github-code | 90 |
20002137657 |
import time
def function(x):
out = 1
for i in range(x):
out = out * i
if i%1000 == 0:
end_time = time.time()
time_used = end_time-start_time
print(time_used)
print("time:{:.3}".format(time_used))
m, s = divmod(time_used, 60)
... | joselynzhao/One-shot_ReID | time_test.py | time_test.py | py | 829 | python | en | code | 3 | github-code | 90 |
30541891148 | import sys
class Grafo:
def __init__(self):
self.nodos = set()
self.aristas = {}
self.distancias = {}
def agregar_nodo(self, valor):
self.nodos.add(valor)
def agregar_arista(self, nodo_origen, nodo_destino, distancia):
if nodo_origen not in self.aristas:
... | brokensito/Examen_Ordinaria_EDA2_enero_David_Sanz | ej8_dijkstra.py | ej8_dijkstra.py | py | 3,933 | python | es | code | 0 | github-code | 90 |
26889148218 | def safe_pawns(pawns: set) -> int:
pawns_indexes = set()
safe = 0
for p in pawns:
row = int(p[1]) - 1
col = ord(p[0]) - 97
pawns_indexes.add((row, col))
for pair in pawns_indexes:
first = (pair[0]-1, pair[1]+1)
second = (pair[0]-1, pair[1]-1)
if first in p... | Naethaniel/learn-python | checkIO/home/pawn_brotherhood.py | pawn_brotherhood.py | py | 655 | python | en | code | 0 | github-code | 90 |
44035237876 | import logging
from django.conf import settings
from .clients import get_client
logger = logging.getLogger('events.jabber')
def on_user_created(new_user):
"""
This function should be called for newly registered user.
:type new_user: `django.contrib.auth.models.User`
"""
if not settings.JABBER... | 42cc/p2psafety | p2psafety_django/events/jabber/queries.py | queries.py | py | 974 | python | en | code | 7 | github-code | 90 |
23266409541 | # -*- coding: utf-8 -*-
import os
from datetime import timedelta
class Config(object):
CELERY_BROKER_URL = 'redis://@{host}:7383/0'.format(host=os.getenv('BROKER_HOST')) # celery消息代理, redis3容器
CELERY_RESULT_BACKEND = 'redis://@{host}:7383/0'.format(host=os.getenv('BROKER_HOST')) # celery消息存储, redis3容器
CE... | asynccnu/info_service | service/config.py | config.py | py | 666 | python | en | code | 1 | github-code | 90 |
22706179456 | # 异常Exception
# raise语句引发异常
# raise Exception
# 1/0
# raise Exception("hyperdriver overload")
# 一些内置的异常类
# Exception 几乎所有的异常类都是从它派生而来的!!!
# AttributeError 引用属性或给它赋值失败时引发
# OSError 操作系统不能执行指定的任务(如打开文件)时引发,有多个子类
# IndexError 使用序列中不存在的索引时引发,为LookupError的子类
# KeyError 使用映射中不存在的键时引发,为LookupError的子类
# NameError 找不到名称(变量)时引发
... | wangshu464113010/python | cException.py | cException.py | py | 2,776 | python | zh | code | 0 | github-code | 90 |
16628326287 | from typing import Any, List, Optional, Tuple
from pprint import pprint
from sys import stderr
from math import cos, sin, pi, sqrt
from dihedral_fragments.dihedral_fragment import element_valence_for_atom, NO_VALENCE
try:
from fragment_capping.helpers.molecule import Uncapped_Molecule, Molecule
from fragment_... | bertrand-caron/dihedral_fragments | capping.py | capping.py | py | 5,232 | python | en | code | 0 | github-code | 90 |
36673310433 | import matplotlib.pyplot as plt
import pandas as pd
from sklearn import (datasets, model_selection as skms,
neighbors)
digits = datasets.load_digits()
# Let's compare different values of k
param_grid = {'n_neighbors': [1, 3, 5, 10, 20]}
knn = neighbors.KNeighborsClassifier()
grid_model = skms.Gri... | victordomingos/Learning_DataScience | ML-Python/02-Classification/12_hyperparameters_comparing_k_values.py | 12_hyperparameters_comparing_k_values.py | py | 1,445 | python | en | code | 1 | github-code | 90 |
13676021696 | from semantic_checker_utils import *
from our_ast import *
import visitor
#from parser import *
#from parser import main
#from lexer import main as lex_main
class TypeError(Exception):
#clase para reportar los errores de tipos
def __init__(self,wrongs):
super()
self.wrongs = wrongs... | rayniel95/COOL-Interpreter | semantic_checker.py | semantic_checker.py | py | 35,300 | python | es | code | 1 | github-code | 90 |
3229966216 | class Movie:
def __init__(self, title, href):
self.title = title
self.originalTitle = ""
self.runningTime = ""
self.countryOfOrigin = ""
self.director = ""
self.cast = ""
self.href = href
self.genre = ""
self.tickets = []
class TicketInfo:
... | jovanovicdima/cineskop | scraper/movie.py | movie.py | py | 884 | python | en | code | 0 | github-code | 90 |
13866731787 | import logging
from api_admin.helpers import get_message_from_code_reason
from api_admin.models import (
CodeReason,
TranslateMessage,
)
from api_admin.serializers import (
CreateCodeSER,
CreateMsgSER,
GetMsgSER,
PartnerLanguageSER,
PartnerMessageSER,
)
from api_partner.helpers.routers_db i... | juanpabloglobalsys98/inlaze_repo | api_admin/views/translate_message/translate_message.py | translate_message.py | py | 22,715 | python | en | code | 1 | github-code | 90 |
31393846497 | from django.urls import path
from rest_framework_simplejwt import views as jwt_views
from .views import (
UserRegistrationView,
UserLoginView,
UserListView,
UserDeleteView,
UserEditView,
RestaurantListView,
RestaurantCreate,
ReviewListView,
ReviewCreateView,
ReplyCreateView, ... | Firuz-JuraevML/restaurante | restaurante/restaurant/urls.py | urls.py | py | 1,417 | python | en | code | 0 | github-code | 90 |
5237771456 | class Solution:
def findStartIndexOfSubstring(self, s1: str, s2: str) -> int:
if len(s2) > len(s1):
return -1
for i in range(len(s1) - len(s2)+1):
temp = s1[i:len(s2)+i]
if temp == s2:
return i
return -1
ans = Solution()
... | PrinceSinghhub/Workat-tech-String-and-Tries | Workat@tech String and Tries/Substring Search - I.py | Substring Search - I.py | py | 397 | python | en | code | 1 | github-code | 90 |
70752532456 | import pika
# Establish a connection to RabbitMQ server
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# Declare a queue named 'my_queue'
channel.queue_declare(queue='my_queue',durable=True, exclusive=False, auto_delete=False)
channel.confirm_delivery()
pe... | frauca/samples | python/celery/rabbit_redis/rabbitmq/send.py | send.py | py | 678 | python | en | code | 0 | github-code | 90 |
264219544 | from tensorboardX import SummaryWriter
from sklearn import svm
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import classification_report
from data_process.data_gen_VD import *
from utils import *
from networks import *
import datetime
import os
class ModelBaseline_VD:
def __init__(self, fl... | liyiying/Feature_Critic | model_VD.py | model_VD.py | py | 31,077 | python | en | code | 45 | github-code | 90 |
73950965416 | import requests
import json
def tockenHeader(u, p, y):
loginHeaders = {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
loginRequestBody = {
"userId": u,
"password": p,
"yob": y
}
loginResponse = requests.post(
'http... | sujit369/samcoholdings | samcostocks.py | samcostocks.py | py | 4,125 | python | en | code | 0 | github-code | 90 |
29440169433 | from collections import deque
from random import randrange, randint
import manzana
from conf import *
class Snake:
def __init__(self, x, y):
self.image = pygame.Surface((TILE_SIZE, TILE_SIZE))
self.image.fill("green")
self.rect = self.image.get_rect()
self.posicion = [x, y]
... | AlejandroFeriaGonzalez/snake-pygame | snake.py | snake.py | py | 2,782 | python | es | code | 0 | github-code | 90 |
16390320469 | import pygame
from pygame.sprite import AbstractGroup
from core import settings
from core.base_artefact import BaseArtefact
class AnimatedArtefact(BaseArtefact):
def __init__(self, image, x, y, frames=(1, 4), *groups: AbstractGroup):
super().__init__(image.format(1), x, y, *groups)
self.tick = 0... | marvinbraga/Platform | core/animated_artefacts.py | animated_artefacts.py | py | 849 | python | en | code | 0 | github-code | 90 |
28748850277 | import os
import random
import sys
import pygame
def load_image(name, color_key=-1):
fullname = os.path.join('data', name)
# если файл не существует, то выходим
if not os.path.isfile(fullname):
print(f"Файл с изображением '{fullname}' не найден")
sys.exit()
image = pygame.image.load(fu... | pop-arthur/pygame | buf.py | buf.py | py | 2,311 | python | ru | code | 0 | github-code | 90 |
18502946939 | n,k=map(int,input().split())
x=list(map(int,input().split()))
xmin=(x[n-1]-x[0])*2
for i in range(n-k+1):
x1=abs(x[i])+abs(x[i+k-1]-x[i])
x2=abs(x[i+k-1])+abs(x[i+k-1]-x[i])
xmin=min(xmin,x1,x2)
print(xmin)
| Aasthaengg/IBMdataset | Python_codes/p03274/s690026296.py | s690026296.py | py | 222 | python | en | code | 0 | github-code | 90 |
28814682493 | import var
from PyQt5 import QtWidgets
import conexion, events
class Clients():
def validarDni(dni):
"""
Módulo que valida la letra de un dni segñun sea nacional o extranjero
:param a: dni formato texto
:return: None
:rtype: bool
Pone la letra en mayúsculas, compr... | a19Albertopp/a19albertopp | clients.py | clients.py | py | 10,677 | python | es | code | 0 | github-code | 90 |
20122692625 | import numpy as np
from solcore.solar_cell_solver import solar_cell_solver
from solcore.spice import solve_circuit
def solve_pv_module(solar_cell, options, totalcells=25, bias_start=0, bias_end=75, bias_step=0.1, jscSigma=2e-4,
shading=None):
""" Calculate the IV curve of a PV module made of a... | qpv-research-group/solcore5 | solcore/spice/pv_module_solver.py | pv_module_solver.py | py | 7,514 | python | en | code | 122 | github-code | 90 |
34655517228 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
import numpy as np
import torch
from MOC_utils.model import convert2flow, create_model, load_model
from MOC_utils.data_parallel import DataParallel
from .decode import moc_decode
from MOC_utils.ut... | MCG-NJU/MOC-Detector | src/detector/normal_moc_det.py | normal_moc_det.py | py | 6,989 | python | en | code | 258 | github-code | 90 |
42896612066 | import pandas as pd
import config
import shopify
from exceptions import CantCreateProduct, CantCreateVariant
import download_images_dropbox as dbox
import product_functions
import log
sheet_fields = {
# "Brand & Category":{
# "skiprows": 6,
# "Title": "Default Title",
# "Type": "Product Typ... | VaselLisk123/training_program | upload_product.py | upload_product.py | py | 10,045 | python | en | code | 0 | github-code | 90 |
41413927029 | #module testing
import sys, traceback
def test(expected_result, function, *params):
"""this function supports unit testing of functions. The named function is called
with the specified parameters, and the returned result is compared to the
expected result. The function prints details about the func... | parkerledbetter/415-Python-Project | 415 Project 1/testing.py | testing.py | py | 1,542 | python | en | code | 0 | github-code | 90 |
17616815058 |
from imp import reload
import os
from time import clock_settime
import requests
from yaml import scan
def get_status(success, failed, partial=0):
if partial > 0:
return 'partial'
elif failed == 0:
if success == 0:
return 'failed'
else:
return 'success'
el... | Group-BSE22-8/monitoring | app/helpers/status.py | status.py | py | 1,857 | python | en | code | 0 | github-code | 90 |
27323685434 | """
https://www.hackerrank.com/challenges/30-linked-list-deletion/problem
Output Format
Your removeDuplicates function should return the head of the updated linked list.
The locked stub code in your editor will print the returned list to stdout.
Sample Input
6
1
2
2
3
3
4
Sample Output
1 2 3 4
The data elements ... | mrogove/hackerrank | 30day/Day24_linkedListDeletion.py | Day24_linkedListDeletion.py | py | 2,010 | python | en | code | 0 | github-code | 90 |
7911195521 | import pickle
import numpy as np
from sklearn.feature_extraction.text import TfidfTransformer, TfidfVectorizer
from app.core.exceptions import BadRequestException
from app.ml.classifier_rule import config
from app.ml.classifier_rule.utils.data_preprocessing import clean_text
transformer = TfidfTransformer()
loaded_v... | avinash-chaluvadi-dev/pratilipi-ana | soa-nlp/app/ml/classifier_rule/main.py | main.py | py | 2,483 | python | en | code | 0 | github-code | 90 |
46210901810 | from classes import Graph
import functions
import common
from common import IndexedMatrix
from classes import Node
import sys
def create_data_function(index, value):
return Node(index, value)
lines = common.read_file_as_lines("input.dat")
matrix = IndexedMatrix(lines, create_data_function)
nodes = matrix.data
... | neodem/advent2022 | day12/b.py | b.py | py | 1,058 | python | en | code | 0 | github-code | 90 |
33335289520 | from openpyxl import load_workbook
# The source xlsx file is named as source.xlsx
wb=load_workbook("sample.xlsx")
wb.save('sample1.xlsx')
ws = wb.active
first_column = ws['B']
# Print the contents
for x in range(len(first_column)):
print(first_column[x].value)
| Arokia04/Excel-Automation | copy_column_openpyxl.py | copy_column_openpyxl.py | py | 278 | python | en | code | 0 | github-code | 90 |
17522552147 | import os
from PIL import Image
import glob
UNZIP_DATA_PATH=os.environ['HOME']+"/DATA/NicoTechDice/DiceDataset"
def make_dirs(labels):
for kind in ('train', 'valid', 'test'):
for label in labels:
os.makedirs('%s/%s/%s' % (UNZIP_DATA_PATH, kind, label),
mode=0o775, exist_ok=True)
def co... | llDataSciencell/DiceRecognitionKeras | make_data_directory.py | make_data_directory.py | py | 1,300 | python | en | code | 2 | github-code | 90 |
71045351016 | from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
app = Flask(__name__)
directory = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(directory, 'app.sqlite')
db = SQ... | Firiyuu/CSCProjs | RestAPI/app.py | app.py | py | 1,937 | python | en | code | 0 | github-code | 90 |
677998185 | #循环和列表
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
for number in the_count:
print(f"This is count{number}")
for fruit in fruits:
print(f"A ruit of type: {fruit}")
for i in change:
print(f"I got {i}")
e... | MirandaZhao/Learn_Python_the_Hard_Way | ex32.py | ex32.py | py | 1,506 | python | en | code | 1 | github-code | 90 |
3917842256 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 16 14:38:14 2022
@author: clara
"""
import h5py
import numpy as np
import matplotlib.pyplot as plt
import math
import csv
import pandas as pd
from pathlib import Path
h = 0.6774
def get_filenames(sim_size, sim_res, num_files, dark):
"""
... | clilje/summer_project | Radial Density Functions/Old intermediate Code/rad-density-func-both.py | rad-density-func-both.py | py | 10,391 | python | en | code | 1 | github-code | 90 |
33673080731 | import struct
from collections import namedtuple
from datetime import date
import os
f=open("small.bin","rb")
fmt = '20s 20s 70s 40s 80s 25s 3i12s 25s 50s 50s'
block = '46s'
statinfo = os.stat('small.bin')
size = statinfo.st_size
print(size)
recrd = f.read(struct.calcsize(fmt))
fmtCount = 405
blockCount = 46
sizeCou... | sagar4796/query_processing_with_python | get_data_of nonUnique_SSN.py | get_data_of nonUnique_SSN.py | py | 1,033 | python | en | code | 0 | github-code | 90 |
72351035177 | import torch
from .model import CustomNet
def validate(
validate_dataset,
validate_loader,
model_path,
):
classes = validate_dataset.classes
count_classes = len(classes)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = CustomNet(count_classes).to(device)
... | asa1984/cnn-assignment | src/validate.py | validate.py | py | 1,431 | python | en | code | 0 | github-code | 90 |
40077317135 | print('Escolha uma opção: \n [1] - converter de binário / octal / hexadecimal para decimal \n [2] - converter decimal para binário / octal / hexadecimal \n [3] - Informações do grupo \n [4] - Sair ')
print(" ")
opcao = int(input("Digite uma opção: "))
print(" ")
#OPÇÃO 1 -----------------
if opcao == 1:
base = int(i... | marcoscacojr/CursoMackenie---Python | 20.py | 20.py | py | 1,703 | python | pt | code | 0 | github-code | 90 |
3996513998 | import sys
input = sys.stdin.readline
# BF
# def IOIOI(N,M,S):
# for i in range(1,N+1):
# Pn = 'IO' * i
# Pn += 'I'
# # print(Pn)
# count = 0
# for _ in range(S.find(Pn),M):
# where = S.find(Pn)
# # print(where)
# if where != -1:
# count += 1
# ... | WonyJeong/algorithm-study | wndnjs9878/soma_study/bj-5525.py | bj-5525.py | py | 1,026 | python | en | code | 2 | github-code | 90 |
1563640256 | # ============================================================================ #
# analysis.py
# Signal processing functions and commands.
# James Burgoyne jburgoyne@phas.ubc.ca
# CCAT Prime 2023
# ============================================================================ #
from alcove_commands.alcove_base import... | TheJabur/primecam_readout | src/alcove_commands/analysis.py | analysis.py | py | 8,381 | python | en | code | 7 | github-code | 90 |
6317865557 | # YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
"""
YOLO-specific modules
Usage:
$ python models/yolo.py --cfg yolov5s.yaml
"""
import argparse
import contextlib
import os
import platform
import sys
from copy import deepcopy
from pathlib import Path
FILE = Path(__file__).resolve()
ROOT = FILE.parents[1] # YOLOv5... | ultralytics/yolov5 | models/yolo.py | yolo.py | py | 17,785 | python | en | code | 43,323 | github-code | 90 |
18109467189 | class queue():
def __init__(self):
self.head = 0
self.tail = 0
self.MAX = 100000
self.Q = [[0] for i in range(self.MAX)]
def is_empty(self):
return self.head == self.tail
def is_full(self):
return self.head == (self.tail + 1) % self.MAX
def enqueue(self... | Aasthaengg/IBMdataset | Python_codes/p02264/s041663594.py | s041663594.py | py | 1,484 | python | en | code | 0 | github-code | 90 |
18477238609 | def sieve(n):
prime=[]
limit=n**0.5
data=[i+1 for i in range(1,n)]
while True:
p=data[0]
if limit<=p:
return prime+data
prime.append(p)
data=[e for e in data if e%p!=0]
def main():
n=int(input())
primes=sieve(n+1)
l=len(primes)
factor=[]
... | Aasthaengg/IBMdataset | Python_codes/p03213/s803133484.py | s803133484.py | py | 888 | python | en | code | 0 | github-code | 90 |
42569537576 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 26 09:32:44 2020
@author: user
"""
import numpy as np
import pandas as pd
import os
# import matplotlib
# import matplotlib.pyplot as plt
# import plotly.express as px
# from plotly.offline import plot
from plotly.subplots import make_subplots
import plotl... | goldenberg-lab/GIproject | results_histograms.py | results_histograms.py | py | 2,052 | python | en | code | 0 | github-code | 90 |
24827951852 | import collections
import math
import re
import note_seq
from typing import List
from note_seq import constants
from note_seq.performance_lib import PerformanceEvent, Performance
from note_seq.protobuf import music_pb2
# Example file
TOKEN_SEQUENCE_FILE = "../../data/primers/tokens/primers_token_sequences.json"
MAX... | p-ferreira/generating-music-with-data | src/custom-gpt2/token_sequence_to_midi.py | token_sequence_to_midi.py | py | 5,783 | python | en | code | 5 | github-code | 90 |
3733569104 | import gzip
import numpy as np
from . import parse_pdb as p
from .eventdispatcher import EventDispatcher, Event
atmrec = [
('cid', 'U1'),
('resnum', 'i4'),
('name', '<U4'),
('altloc', 'U1'),
('coord', 'f4',(3)),
('occ', 'f4'),
('b', 'f4'),]
resrec = [
('cid', 'U1'),
('resnum', 'i4... | mok0/structurehandler | structurehandler/structureparser.py | structureparser.py | py | 4,151 | python | en | code | 0 | github-code | 90 |
43959425691 |
from floodsystem.stationdata import build_station_list
from floodsystem.geo import *
def test_rivers_with_stations():
"""This checks that all the rivers are in the set"""
stations = build_station_list()
station_rivers = rivers_with_stations(stations)
count = 0
for station in stations:
... | impulseCoolKid/jm-nat- | test_geo.py | test_geo.py | py | 2,205 | python | en | code | 0 | github-code | 90 |
22300944404 | """
Parse output of nvidia-smi into a python dictionary.
This is very basic!
"""
import os
import subprocess
import pprint
from Animator.utils import eprint
def nvidia_smi(should_print=False):
sp = subprocess.Popen(['nvidia-smi', '-q'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out_str = sp.communicat... | oronnir/CAST | Utils/gpu_profiler.py | gpu_profiler.py | py | 810 | python | en | code | 16 | github-code | 90 |
17939733569 | S=input()
T=input()
lt=len(T)
ls=len(S)
S+='%'*lt
if ls<lt:
flg=0
else:
for i in range(ls-lt+1,-1,-1):
# print('***',S[i:i+lt])
flg=1
for j in range(i,i+lt):
s=S[j]
# print(s,T[j-i])
if s=='?': continue
if s=='%' or s!=T[j-i]:
... | Aasthaengg/IBMdataset | Python_codes/p03565/s830527291.py | s830527291.py | py | 479 | python | en | code | 0 | github-code | 90 |
31950862188 | from mindspore.parallel._utils import (_get_device_num, _get_gradients_mean,
_get_parallel_mode)
from mindspore.context import ParallelMode
from ...common import dtype as mstype
from ...common.parameter import Parameter, ParameterTuple
from ...ops import composite as C
from ...ops... | imyzx2017/mindspore_pcl | mindspore/nn/wrap/cell_wrapper.py | cell_wrapper.py | py | 12,272 | python | en | code | 5 | github-code | 90 |
24384809327 | #!/usr/bin/env python3
import copy
import random
import argparse
import pyfastaq
parser = argparse.ArgumentParser(
description = 'Make simulated genomes for testing pan-genome pipelines',
usage = '%(prog)s [options] <core> <genomes> <infile> <prefix of output files>')
parser.add_argument('--spacing_ns', type... | MagdalenaZZ/Python_ditties | roary_gff_to_test_genomes.py | roary_gff_to_test_genomes.py | py | 5,022 | python | en | code | 0 | github-code | 90 |
19019795465 | class Solution:
def subsets (self, nums: List[int]) -> List[List[int]]:
n = len(nums) ; lim = 2 ** n
i = 0 ; res = []
while (i < lim):
tmp_res = []
mask, j = 1, 1
while (j <= n):
if ((i & mask) != 0):
tmp_res.append(nums... | Tejas07PSK/lb_dsa_cracker | String/Print all Subsequences of a string/solution.py | solution.py | py | 435 | python | en | code | 2 | github-code | 90 |
19254492435 | from sys import stdin
from collections import deque
stdin = open("./input.txt", "r")
num_of_criminal, num_of_relation = map(int, stdin.readline().split())
relations = {}
parents = {}
for i in range(0, num_of_criminal):
relations[chr(ord('A') + i)] = []
parents[chr(ord('A') + i)] = chr(ord('A') + i)
for _ in ... | ag502/algorithm | Problem/BOJ_17220_마약수사대/main.py | main.py | py | 1,231 | python | en | code | 1 | github-code | 90 |
30149579007 | # -*- coding:utf-8 -*-
# @Author: IEeya
import json
import os
import sys
import time
import dgl
import numpy as np
import torch
from OCC.Extend.DataExchange import read_step_file
from UVGraph.EntityMap import EntityMapModel
from UVGraph.Graph import face_adjacency
from UVGraph.uv_grid import get_uvgrid_by_face, get_u... | IEeyaa/MyUVNet | UVGraph/modelToGraph.py | modelToGraph.py | py | 4,898 | python | en | code | 0 | github-code | 90 |
31294050112 | import nsepy
import datetime
import pandas as pd
import os
#data, meta_data = ts.get_daily(symbol=EXCHANGE+':'+symbol,outputsize='full')
def histor(stockname):
today = datetime.date.today()
print(today)
duration = 60
start = today+datetime.timedelta(-duration)
stockData = nsepy.get_... | AtharvSarode/AutomatedTrader | File_Downloading.py | File_Downloading.py | py | 1,060 | python | en | code | 1 | github-code | 90 |
25731789234 | #coding=utf-8
'''
# This file contains django views which used to return json data
# Any issues or improvements please contact jacob-chen@iotwrt.com
'''
from django.shortcuts import render
from django import forms
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect
fr... | wzyy2/PiBox | PiBox/PiHome/PiApp/api.py | api.py | py | 21,405 | python | en | code | 197 | github-code | 90 |
45957732453 | import os
import numpy
import csv
import std_atm
import matplotlib.pyplot as plt
import pandas as pd
# Import pyxfoil from a different folder as a module
#import sys
#sys.path.append('../Utilities')
import pyxfoil
#import mses
'''
Useful Python classes in senior design project
Classes included:
AtmData: recor... | ThomasGreenhill/Sr_Design_Project | Python_Codes/Class130.py | Class130.py | py | 17,522 | python | en | code | 1 | github-code | 90 |
2878652134 | # -*- encoding: utf-8 -*-
'''
@File : 97. 交错字符串.py
@Time : 2020/04/25 09:29:10
@Author : windmzx
@Version : 1.0
@Desc : For leetcode template
'''
# here put the import lib
from typing import List
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
m = len(s1)
... | windmzx/pyleetcode | 97. 交错字符串.py | 97. 交错字符串.py | py | 1,076 | python | en | code | 0 | github-code | 90 |
72849487337 | """
Basic test cases for the `pytools.api` module
"""
from typing import Any, Dict, Union
import pytest
from typing_extensions import TypeAlias
from pytools.api import (
AllTracker,
deprecated,
subsdoc,
to_collection,
to_list,
to_set,
to_tuple,
validate_element_types,
validate_type... | BCG-Gamma/pytools | test/test/pytools/test_api.py | test_api.py | py | 7,924 | python | en | code | 26 | github-code | 90 |
18428797089 | import sys
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
mod = 10**9 + 7
inf = float('inf')
ans = int(0)
N = I()
dp = [{} for i in range(N+4)]
def ok(last4):
for i in range(4):
t = list(last4)
if i >= 1:
t[i - 1], t[i] = t[i], t[... | Aasthaengg/IBMdataset | Python_codes/p03088/s758279273.py | s758279273.py | py | 698 | python | en | code | 0 | github-code | 90 |
22025079612 | """
딕셔너리와 리스트를 이용해 간단하게 풀 수 있는 문제
"""
import sys
n, m = map(int, sys.stdin.readline().rstrip().split())
pokemon_name_dict = dict()
pokemon_list = []
for i in range(n):
pokemon_name = sys.stdin.readline().rstrip() # 포켓몬 이름 입력받음
pokemon_name_dict[pokemon_name] = i + 1 # key : 포켓몬 이름, value : 입력받... | KJH9612/coding_interview | baekjoon/problem_1620.py | problem_1620.py | py | 1,041 | python | ko | code | 0 | github-code | 90 |
10426961609 | import json
import requests
from lxml import etree
"""
糗事百科爬虫
"""
class QiuShi():
def __init__(self):
self.base_url = "https://www.qiushibaike.com/text/page/{}"
# https://www.qiushibaike.com/users/17535149/page_2/
self.start_url = []
self.file = open('./qiushi.json', 'w')
se... | anstones/py-collection | Spider/qiushi.py | qiushi.py | py | 2,470 | python | en | code | 3 | github-code | 90 |
1188923337 | #!/user/bin/env python
# -*- coding:utf-8 -*-
# Code created by gongfuture
# Create Time: 2023/3/22
# Create User: gongf
# This file is kT9bZ4qA9mY6wL1dR5kS part of Homework_test_environment
#
# import os
import random
import time
kT9bZ4qA9mY6wL1dR5kS = random.randrange(0, 10, 1)
print("正在生成随机数,请稍后", end="")
for i ... | gongfuture/Homework_test_environment | Python/作业6/成品/2、编写猜数程序。.py | 2、编写猜数程序。.py | py | 1,158 | python | en | code | 5 | github-code | 90 |
13732460590 | __author__ = 'bocian'
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
import time
baseUrl = "http://newtours.demoaut.com/"
driver = webdriver.Firefox()
underConsTitle = "Under Const... | BBBocian/Python | Selenium_start/TEST_all_links.py | TEST_all_links.py | py | 830 | python | en | code | 0 | github-code | 90 |
39279438854 | import sys #python sürüm bilgisi
import pandas as pd #veri analizi
import numpy as np #hesaplama
import cv2 #image processing
from sklearn.model_selection import train_test_split #veri analitiği
from keras.models import Sequential #model ağırlık
from keras import regularizers #düzenleyici ceza**
from keras.layers impor... | xgaslann/ai-dl-emotion-analysis-with-image-processing | processing.py | processing.py | py | 5,871 | python | en | code | 0 | github-code | 90 |
35458603202 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 21 17:02:08 2019
@author: Arae Zarzosa
"""
import lab4_BST as bst
import lab4_BTree as bt
import lab4_WordEmbedding as we
import numpy as np
if __name__ == "__main__":
done = False
H = None
while done == False:
it = input("Use Binary ... | azarzosa/CS2302-LAB5 | main.py | main.py | py | 1,886 | python | en | code | 0 | github-code | 90 |
37920461616 |
### Preprocess ###
import os, time
import numpy as np
import pandas as pd
import tensorflow as tf
import SimpleITK as sitk
from sklearn.model_selection import train_test_split
from params import modality
from data_augmentation import set_seed
def parse_csv(data_path,type_lst):
if isinstance(type_lst, dict):
... | cgacga/MSc_ProstateCancer | code/preprocess.py | preprocess.py | py | 17,051 | python | en | code | 1 | github-code | 90 |
9034649970 | # -*- coding: utf-8 -*-
#coding=utf-8
import socket
import os
import subprocess
import re
def get_host_ip():
"""
获取本机IP地址
:return: 返回获取的IP
"""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
... | you282507/adb-tools-tk | Library.py | Library.py | py | 1,876 | python | en | code | 0 | github-code | 90 |
70040199337 | """
__version__.py
~~~~~~~~~~~~~~
Information about the current version of the samedialib package.
"""
__title__ = 'samedialib'
__description__ = 'samedialib - Library modules for synesthetic aesthetic media'
__version__ = '0.1'
__author__ = 'Christopher Davis'
__author_email__ = 'agilechris@cdcc.group'
__license__ = ... | cdccgroup/sameida-lib-core | samedialib/__version__.py | __version__.py | py | 390 | python | en | code | 0 | github-code | 90 |
2569183859 | import pygame
from tkinter.filedialog import *
from tkinter import *
import tkinter as tk
from PIL import ImageTk,Image
from tkinter import font
import mutagen
from mutagen.easyid3 import EasyID3
import pigpio
import sys
pygame.init()
class FrameApp(Frame):
def __init__(self,root):
tk.Fr... | LaxmanSingh9/Music_Player | PythonApplication3.py | PythonApplication3.py | py | 6,295 | python | en | code | 0 | github-code | 90 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.