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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
41867662857 | from django.core.urlresolvers import reverse
from oscar_testsupport import testcases
from oscar.apps.offer import models
class TestAnAdmin(testcases.WebTestCase):
# New version of offer tests buy using WebTest
is_staff = True
def setUp(self):
super(TestAnAdmin, self).setUp()
self.range =... | bobofzhang/django-oscar | tests/functional/dashboard/offer_tests2.py | offer_tests2.py | py | 1,899 | python | en | code | null | github-code | 90 |
32589559567 | # -*- coding:utf-8 -*-
# ----------------------------------------------------------------------------------------------------------------------
# Author: Tuozhen
# Date: 2021/11/1
# Description: Leetcode 104. Maximum Depth of Binary Tree
# Given the root of a binary tree, return its maximum depth.
# A binary tree's ma... | TuozhenLiu/Data-Structure-Algorithm | Binary_Tree/DFS/Depth/Maximum_Depth_of_Binary_Tree.py | Maximum_Depth_of_Binary_Tree.py | py | 1,934 | python | en | code | 2 | github-code | 90 |
18287811499 | import numpy as np
def solve():
dp = np.zeros((2, N+1))
# print(dp)
ac = 0
wa = 0
for i in range(M):
if (dp[0][S[i][0]] == 0):
if(S[i][1] == "WA"):
dp[1][S[i][0]] += 1
elif(S[i][1] == "AC"):
ac += 1
dp[0][S[i][0]] = 1
... | Aasthaengg/IBMdataset | Python_codes/p02802/s030107388.py | s030107388.py | py | 576 | python | en | code | 0 | github-code | 90 |
18760256201 | import numpy as np
from synthtiger.components.component import Component
class Opacity(Component):
def __init__(self, opacity=(0, 1)):
super().__init__()
self.opacity = opacity
def sample(self, meta=None):
if meta is None:
meta = {}
opacity = meta.get(
... | clovaai/synthtiger | synthtiger/components/color/opacity.py | opacity.py | py | 678 | python | en | code | 362 | github-code | 90 |
3151660162 | import logging
_LOGGER = logging.getLogger(__name__)
async def zhiChat(hass, query):
#query = question.strip()
_LOGGER.debug("QUERY: %s", query)
if not query:
return "空谈误国,实干兴邦!"
if query == '全部动作' or query == '?' or query == '?':
return '打开/关闭(设备或群组名);查询(设备或群组名,可省略“查询”);... | clouduserd/Yonsmm | custom_components/zhibot/zhichat/__init__.py | __init__.py | py | 3,041 | python | en | code | 0 | github-code | 90 |
14992055702 | import os
def run(inputs):
total = 0
data = set() # Use a set to store the answers from each group
for line in inputs.split(os.linesep):
if not len(line.strip()):
# Reaching an empty line means a new group so add the current total and reset
total += len(data)
d... | jimhendy/AoC | 2020/06/a.py | a.py | py | 750 | python | en | code | 0 | github-code | 90 |
13386669160 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
n = int(input())
li = []
for _ in range(n):
k = int(input())
h = math.sqrt(k)
if k>3:
for i in range(2,int(h)+1):
g= True
if k%i == 0:
g = False
break
if... | iftekherhossain/30-Days-of-Code | day 25.py | day 25.py | py | 519 | python | en | code | 0 | github-code | 90 |
23165978549 | from datetime import datetime
from app.db import Base
from sqlalchemy import Column, Integer, String, ForeignKey, DateTime, select, func
from sqlalchemy.orm import relationship, column_property
from .User import User
from .Like import Like
# db = get_db()
class Post(Base):
__tablename__ = 'posts'
id = Column(... | ian-sieg/sfsg-python-redux | backend/app/models/Post.py | Post.py | py | 2,349 | python | en | code | 0 | github-code | 90 |
23736441387 | income = float(input())
months = int(input())
personal_spendings = float(input())
income_per_month = income - personal_spendings
total_per_month = income_per_month - (0.3 * income)
saved = total_per_month * months
saved_percent = saved / (income * months) * 100
print(f'She can save {saved_percent:.2f}%')
print(f'{sa... | krstoilo/SoftUni-Basics | Python-Basics/exam_preparation/savings.py | savings.py | py | 331 | python | en | code | 0 | github-code | 90 |
18815328417 | from spatula import HtmlPage, PdfPage, XPath, URL
from openstates.models import ScrapeCommittee
import re
class UnexpectedMemberListFormat(Exception):
def __init__(self):
super().__init__(
"Unexpected member list format, number of headings didn't match number of member groups"
)
clas... | openstates/openstates-scrapers | scrapers_next/sc/committees.py | committees.py | py | 14,323 | python | en | code | 820 | github-code | 90 |
24394751566 | import Adafruit_DHT
from luma.led_matrix.device import max7219
from luma.core.interface.serial import spi, noop
from luma.core.render import canvas
from luma.core.virtual import viewport
from luma.core.legacy import text, show_message
from luma.core.legacy.font import proportional, CP437_FONT, TINY_FONT, SINCLAIR_FONT,... | EnzoPujol/TrabajoFinalPython | RegistroAmbiental.py | RegistroAmbiental.py | py | 3,002 | python | es | code | 0 | github-code | 90 |
38304787370 |
# given a string that contains a single pair of parenthesis, compute recursively a new string made of only of the parenthesis and their contents, so "xyz(abc)123" yields "(abc)"
def paren_bit(str):
if str[0] == ')':
return ''
if str[0] == '(':
index = str.index(')')
return str[0:index+1] + paren_bit(str[index... | jemtca/CodingBat | Python/Recursion-1/paren_bit.py | paren_bit.py | py | 447 | python | en | code | 0 | github-code | 90 |
4104824160 | import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('espiral.csv', names=['x', 'y', 'z'])
def graph():
x = df['x']
y = df['y']
z = df['z']
ax = plt.figure().add_subplot(projection='3d')
ax.plot(x, y, z)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
... | KaboomPhysicist/CursoFCII | lectures/Parcial2/CC1010052517/Punto1/graph.py | graph.py | py | 436 | python | en | code | 0 | github-code | 90 |
15756440721 | c = 600851475143
def funcy(num):
prime = True
for x in range(1,num+1):
#print("num=",num,"x=",x)
if num % x == 0 and x!=num and x!=1:
#print(num," Not prime")
prime = False
break
return prime
#funcy(c)
#print("Prime? ",funcy(600851475143))... | dzinrai/my_euler_proj | e3.py | e3.py | py | 556 | python | en | code | 0 | github-code | 90 |
17543999517 | import torch
import numpy as np
import math
import time
torch.backends.cudnn.benchmark = True
def CIM_CAC_GPU(T_time, J, batch_size=1, time_step=0.05, r=None, alpha=3.0, beta=0.25, gamma=0.00011, delta=10, mu=1, rho=3, tau=1000, noise=0, H0=None, stop_when_solved=False, num_sol=10, custom_fb_schedule=None, custom_pump... | mcmahon-lab/cim-optimizer | cim_optimizer/CAC.py | CAC.py | py | 6,710 | python | en | code | 21 | github-code | 90 |
22002128448 | import numpy as np
import os
import json
import pandas as pd
import tensorflow as tf
from keras.preprocessing import image
from keras.callbacks import ModelCheckpoint, LearningRateScheduler
from keras.applications.inception_v3 import InceptionV3
from keras.models import Model
from keras.layers import Dense, Gl... | kagiak/thesisProject | INCEPTIONV3-recipe1m.py | INCEPTIONV3-recipe1m.py | py | 4,525 | python | en | code | 0 | github-code | 90 |
27073577373 | # 3.1 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay the hourly rate for the hours up to 40 and 1.5 times the hourly rate for all hours worked above 40 hours. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use in... | NallaLokeshReddy/Programming_for_Everybody | Week 5/Asign1.py | Asign1.py | py | 622 | python | en | code | 0 | github-code | 90 |
36678063593 | from project.settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'unicore_mc.db',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.Du... | universalcore/unicore-mc | test_settings.py | test_settings.py | py | 1,887 | python | en | code | 0 | github-code | 90 |
35712404775 | import os
import sys
import colorama
current_filename = os.path.abspath(__file__)
parent_dir = os.path.dirname(current_filename)
great_parent_dir = os.path.dirname(parent_dir)
sys.path.append(great_parent_dir)
from flaml import AutoML
from ray import tune
from sklearn.model_selection import train_test_split
from skle... | Microsoft-tele/NewUserPredict | train/train_automl.py | train_automl.py | py | 2,655 | python | en | code | 2 | github-code | 90 |
31831141051 | from compiler.scopes import NestedScopeable
from compiler.symbol_table import SymbolTable
from system.builtin_functions.main import *
from utils.constants import *
from utils.data_classes import *
from utils.errors import InterpreterError, ErrorCode
class Interpreter(BeforeNodeVisitor, NestedScopeable):
def __ini... | ll-bat/custom-language | compiler/interpreter.py | interpreter.py | py | 10,652 | python | en | code | 0 | github-code | 90 |
37388438947 | class animal:
alive = True
def sleep(self):
print("It is sleeping")
def eat(self):
print("It is eating")
class fish(animal):
def myfish(self):
print("This is a fish")
fsh = fish()
fsh.sleep()
fsh.eat()
fact = fsh.alive
print(fact)
fsh.myfish() | zahraisiaho/Python | inheritance.py | inheritance.py | py | 286 | python | en | code | 0 | github-code | 90 |
2129441411 | import sqlite3
db = sqlite3.connect('vedomosti14.db')
sql = db.cursor()
sql.execute("""CREATE TABLE IF NOT EXISTS students (
ФИО TEXT,
оценка TEXT
)""")
db.commit()
student_ФИО = input('ФИО: ')
sql.execute(f"SELECT ФИО FROM students WHERE ФИО = (?)", (student_ФИО))
if sql.fetchone() is None:
... | Maxim-niko/osnovyprogi | database_0.py | database_0.py | py | 744 | python | ru | code | 1 | github-code | 90 |
70762207018 | from tkinter import *
import os.path
ventana = Tk()
ventana.title("Texto en ventana")
ruta_icono = os.path.abspath('./imagenes/logo.ico')
ruta_icono_alt = os.path.abspath('./21-tkinter/imagenes/logo.ico')
#Para cargar la ventana y el icono desde cmd o visual studio
if not os.path.isfile(ruta_icono): #Comprobando si n... | AlexSR2590/curso-python | 21-tkinter/02-textos.py | 02-textos.py | py | 1,247 | python | es | code | 0 | github-code | 90 |
38360586118 | import threading
import time
import unittest
import mock
import openhtf
from openhtf import plugs
from openhtf import util
from openhtf.core import phase_descriptor
from openhtf.core import phase_executor
from openhtf.core import phase_group
from openhtf.core import test_descriptor
from openhtf.core import test_execu... | oxiwear-inc/spintop-openhtf | test/openhtf_test/core/exe_test.py | exe_test.py | py | 25,933 | python | en | code | 0 | github-code | 90 |
40580976676 | """
1166. Design File System
You are asked to design a file system that allows you to create new paths and associate them with different values.
The format of a path is one or more concatenated strings of the form: / followed by one or more lowercase English letters. For example, "/leetcode" and "/leetcode/problems" ... | venkatsvpr/Problems_Solved | LC_Design_File_system.py | LC_Design_File_system.py | py | 3,210 | python | en | code | 3 | github-code | 90 |
9804336976 | # 解法一,通过了牛客,利用快排的partition函数,复杂度O(n)
import random
def partition(lst, s, e):
pivot = random.randint(s,e)
p = lst[pivot]
lst[e], lst[pivot] = lst[pivot], lst[e]
small = s-1
for i in range(s,e):
if lst[i]<p:
small += 1
lst[i], lst[small] = lst[small], lst[i]
... | liured/Target_offer | 40.最小的k个数.py | 40.最小的k个数.py | py | 1,665 | python | en | code | 0 | github-code | 90 |
20851201192 | """
"Max Depth of Binary Tree
Given a binary tree, find its maximum depth.
The maximum depth of a binary tree is the number of nodes along the longest path from the root node down to the farthest leaf node."
"""
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
... | Harishkumar18/data_structures | interviewbit_problems/trees/max_depth_binary_tree.py | max_depth_binary_tree.py | py | 649 | python | en | code | 1 | github-code | 90 |
70157072618 | import random
MIN_VALUE = 1
MAX_VALUE = 100
MIN_LEN = 5
MAX_LEN = 10
MIN_STEP = 1
MAX_STEP = 10
RULES = 'What number is missing in the progression?'
def get_task_with_right_answer():
progression_len = random.randint(MIN_LEN, MAX_LEN)
first_elem = random.randint(MIN_VALUE, MAX_VALUE)
step = random.randint... | KMCH80/python-project-lvl1 | brain_games/games/progression.py | progression.py | py | 1,066 | python | en | code | 0 | github-code | 90 |
42134588867 | from __future__ import print_function
from __future__ import division
import torch
import torch.nn as nn
from torchvision import datasets, models, transforms
import os
import json
VERSION = 2
def test_model(model, dataloaders, criterion, device=None):
predicted_labels = []
actual_labels = []
test_acc_his... | ryanmccann1024/classify_mediums | src/models/predict_model.py | predict_model.py | py | 4,737 | python | en | code | 0 | github-code | 90 |
12861266343 | import re
sel_m = raw_input("Enter 1 or 2 as method number")
if int(sel_m)==1:
email_m1 = raw_input("Enter email id for method 1:")
'''
retreives email that starts with string priya
'''
match_1 = re.match('^priya[.*A-Za-z0-9]+@[A-Za-z0-9]+(\.[A-Za-z0-9]+)$',email_m1)
if match_1 == None:
print("Invalid email for... | harinipradeep/hub-repo | python/code005_checkemailid/checkem.py | checkem.py | py | 727 | python | en | code | 0 | github-code | 90 |
20989878758 | from tkinter import *
from PySide6 import QtCore, QtWidgets, QtGui
from PIL import Image, ImageTk
import geopandas as gpd
import pandas as pd
import rasterio
class Event:
def __init__(self, transform):
self.transform = transform
self.coordinate = []
def capture_coordinate(self,event):
... | nilraj9800/SatelliteImageProcessing | src/event_handling.py | event_handling.py | py | 1,493 | python | en | code | 0 | github-code | 90 |
69881646376 | """Test the ``dtool verify`` command."""
import os
from click.testing import CliRunner
import dtoolcore
from . import SAMPLE_DATASETS_DIR
from . import tmp_dir_fixture # NOQA
lion_dataset_uri = "file://" + os.path.join(SAMPLE_DATASETS_DIR, "lion")
def test_dataset_verify_functional(tmp_dir_fixture): # NOQA
... | jic-dtool/dtool-info | tests/test_verify_command.py | test_verify_command.py | py | 1,630 | python | en | code | 0 | github-code | 90 |
26495622737 | import turtle as tr
class Lives(tr.Turtle):
def __init__(self):
super().__init__()
self.life = 5
self.color('pink')
self.penup()
self.goto(665, 310)
self.write(f'♥\n{self.life}', align="center", font=("Courier", 25, "bold"))
self.hideturtle() | nirg122/Breakout-Game | lives.py | lives.py | py | 305 | python | en | code | 0 | github-code | 90 |
18062567039 | w = input()
d = {}
for i in w:
if i in d:
d[i] += 1
else:
d[i] = 1
ans = "Yes"
for i in d.values():
if i%2!=0:
ans = "No"
break
print(ans) | Aasthaengg/IBMdataset | Python_codes/p04012/s072554683.py | s072554683.py | py | 182 | python | en | code | 0 | github-code | 90 |
18522731889 | import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007
def main():
N, *A = map(int, read().split())
ans = 0
for a in A:
while a % 2 == 0:
ans += 1
a //= 2
print(ans)... | Aasthaengg/IBMdataset | Python_codes/p03325/s143241009.py | s143241009.py | py | 372 | python | en | code | 0 | github-code | 90 |
18208149839 | def main():
input()
A = list(map(int, input().split()))
cusum = [0] * len(A)
cusum[-1] = A[-1]
if A[0] > 1:
print(-1)
return
for i in range(len(A)-2, -1, -1):
cusum[i] = cusum[i+1] + A[i]
pre_node = 1
ans = 1
for i in range(1, len(A)):
node = (pre_node - A[i-1]) * 2
if node < A... | Aasthaengg/IBMdataset | Python_codes/p02665/s320519782.py | s320519782.py | py | 470 | python | en | code | 0 | github-code | 90 |
26359987550 | # coding: utf-8
from PyQt5.QtWidgets import QDialog, QMessageBox
from PyQt5.Qt import pyqtSignal
from ui.TaskOutputDialog import Ui_TaskOutputDialog
from core.plot import PlotTask, PlotSubTask, PlotWorker
class TaskOutputDialog(QDialog, Ui_TaskOutputDialog):
signalClose = pyqtSignal(QDialog)
def __init__(sel... | penglecn/ChiaTools | TaskOutputDialog.py | TaskOutputDialog.py | py | 1,246 | python | en | code | 8 | github-code | 90 |
24722737962 | import tkinter as tk
from typing import Any, Callable, Tuple
from PIL import Image, ImageTk
import webbrowser
from tkinter import filedialog, ttk
from tkinter.filedialog import asksaveasfilename
import threading
import roop.globals
from roop.utils import is_img
max_preview_size = 800
def create_preview(parent):
... | forb1dden/Roop-2 | roop/ui.py | ui.py | py | 11,032 | python | en | code | 3 | github-code | 90 |
30041379137 | '''
Owner: Venkatasubramanian
Topic: Files
'''
'''
Basic operations:
1) Open a file
2) Read or write (perform operation)
3) Close the file
File modes
'r' Open a file for reading. (default)
'w' Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
'x' Open a f... | rvsp/Python3-reference | Files/_files.py | _files.py | py | 940 | python | en | code | 1 | github-code | 90 |
5645110086 | # coding: utf-8
'''
Component Manager. Manages life cycle of components, which should generally
follow the life cycle of their entity.
Do not hold onto Entities, Components, etc. They /can/ be destroyed at any
time, leaving you holding a dead object. Only keep the EntityId or ComponentId,
then ask its manager. If the... | cole-brown/veredi-code | game/ecs/component.py | component.py | py | 18,524 | python | en | code | 1 | github-code | 90 |
11584699873 | from filtrark.sql_parser import SqlParser
from modelark import SqlRepository
from ....application.domain.common import (
TenantProvider, AuthProvider)
from ....application.domain.models import (
Channel, Device, Message, Subscription)
from ....application.domain.repositories import (
ChannelRepository, Devi... | knowark/instark | instark/core/data/sql/sql_model_repositories.py | sql_model_repositories.py | py | 2,347 | python | en | code | 2 | github-code | 90 |
18323768570 | # -*- encoding: utf-8 -*-
# django
from django import forms
# project
from guest.models import *
class AddPictureForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(AddPictureForm, self).__init__(*args, **kwargs)
self.fields['picture_data'] = forms.ImageField()
class Meta:
model = Picture
... | Corea/album | guest/forms.py | forms.py | py | 419 | python | en | code | 0 | github-code | 90 |
16282908616 | import os
from operator import itemgetter
files_all=0
size_all=0
path_list=[]
path_dict={}
files_list=[]
files_dict={}
extentions_list=[]
extentions_dict={}
superpath_list=[]
superpath_dict={}
SUFFIXES = {1000:['KB','MB','GB','TB','PB','ZB','YB'],
1024:['KiB','MiB','GiB','TiB','PiB','ZiB','YiB']}
class E... | funkacer/Files_directories | old/Files_directories01.py | Files_directories01.py | py | 9,312 | python | en | code | 0 | github-code | 90 |
38991687017 | import numpy as np
import time
import cv2
import dlib
from gpiozero import LED
# Author: Harrison McIntyre
# Last Updated: 8.3.2020
# Contact: hamac2003@gmail.com
### References / Credits
#Below are links to some of the example code and/or libraries that I integrated into my project.
"""
[Facial Detection (Dlib)... | hamac2003/WatchedPotThatNeverBoils | Python/RaspberryPi.py | RaspberryPi.py | py | 2,015 | python | en | code | 1 | github-code | 90 |
42707300469 | import tweepy
import sys
import csv
def show_usage():
print("python hashtag_search.py <hashtag> <output_file_name> [<limit>]")
print("\thashtag: the hashtag you're searching for")
print("\toutput_file_name: the name of the file this will be saved to (will be extended with .csv)")
print("\tlimit: the ma... | PatHealy/TweepyHashtagSearch | hashtag_search.py | hashtag_search.py | py | 4,468 | python | en | code | 0 | github-code | 90 |
18284214969 | import collections as col
def prime(n):
ans = []
for i in range(2, int(n**0.5)+1):
while not n%i: n //= i ; ans.append(i)
if n != 1: ans.append(n)
return col.Counter(ans)
n = int(input())
a = list(map(int,input().split()))
cnt = col.Counter()
for num in a:
new = prime(num)
for key... | Aasthaengg/IBMdataset | Python_codes/p02793/s541735136.py | s541735136.py | py | 593 | python | en | code | 0 | github-code | 90 |
13118182869 | """This module contains helper functions to be used across the project."""
from flask import request, url_for, current_app
def paginate(tablename, query, schema):
"""Return a paginated collection of resources."""
page = request.args.get("page", default=1, type=int)
per_page = request.args.get(
"... | EricMontague/MailChimp-Newsletter-Project | server/app/project_helpers.py | project_helpers.py | py | 839 | python | en | code | 0 | github-code | 90 |
17963427089 | n=int(input())
a=list(map(int,input().split()))
a.sort(reverse=True)
i1=-1
lena1=0
for i in range(len(a)-1):
if a[i]==a[i+1]:
lena1=a[i+1]
i1=i
break
if i1==-1:
print(0)
elif i1+2<len(a)-1:
lena2=0
for i in range(i1+2,len(a)-1):
# if a[i]==a[i+1] and a[i]... | Aasthaengg/IBMdataset | Python_codes/p03625/s257284805.py | s257284805.py | py | 441 | python | en | code | 0 | github-code | 90 |
20400903262 | import logging
from django.db import models
from menu import models as menu_models
class CartPosition(models.Model):
dish = models.OneToOneField(
to=menu_models.Dish,
to_field='id',
on_delete=models.CASCADE,
primary_key=True
)
quantity = models.IntegerField(null=False)
... | KostyaLukyanchikov/food_delivery | src/shopping_cart/models.py | models.py | py | 1,431 | python | en | code | 0 | github-code | 90 |
6961918735 | import requests
from django.db.models import Q
from django.shortcuts import render, redirect, get_object_or_404
from config import settings
from post.models import Video, Post, Comment
from utils import youtube
__all__ = [
# 'youtube_search',
'youtube_search_save',
'youtube_post',
]
# def youtube_se... | recordingbetter/Instagram-practice | django_app/post/views/youtube.py | youtube.py | py | 3,892 | python | en | code | 1 | github-code | 90 |
22315217472 | """
문제 설명
길이가 n인 배열에 1부터 n까지 숫자가 중복 없이 한 번씩 들어 있는지를 확인하려고 합니다.
1부터 n까지 숫자가 중복 없이 한 번씩 들어 있는 경우 true를, 아닌 경우 false를 반환하도록 함수 solution을 완성해주세요.
"""
def solution(arr):
answer = True
# [실행] 버튼을 누르면 출력 값을 볼 수 있습니다.
# print('Hello Python')
arr.sort()
if len(arr) != arr[-1]:
answer = False
... | polkmn222/programmers | python/프로그래밍강의/알고리즘 문제 해설/part2/순열검사.py | 순열검사.py | py | 536 | python | ko | code | 1 | github-code | 90 |
36440773311 | import pytest
def flipAndInvertImage(A):
for i in A:
# Reverse the image
i.reverse()
# Flip the image
for index, num in enumerate(i):
if num == 1:
i[index] = 0
else:
i[index] = 1
return A
assert flipAndInvertImage([[1,1,0... | sepulworld/leet | flipping_an_image.py | flipping_an_image.py | py | 402 | python | en | code | 1 | github-code | 90 |
73089826217 | from flask import Flask, render_template
import geopandas as panda
import folium
app = Flask(__name__)
@app.route('/')
def index():
# Cargar mapa con GeoPandas desde archivos Shape
gdf = panda.read_file('data/peru.shp')
# Crear un mapa de Folium
m = folium.Map(location=[-9.1900, -75.0152], zoom_start... | WilliamsPS/Datos | app.py | app.py | py | 873 | python | es | code | 0 | github-code | 90 |
20088069707 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 2 16:34:29 2017
@author: Administrator
"""
import tensorflow as tf
node1 = tf.constant(3.0, dtype=tf.float32)
node2 = tf.constant(4.0)
print(node1, node2)
sess = tf.Session()
print(sess.run([node1, node2]))
node3 = tf.add(node1, node2)
print("node:", node3)
print("se... | MosterAndMonk/temporary | kaggle/digit_recognizer/code/tensorflow/get_started_tf.py | get_started_tf.py | py | 3,983 | python | en | code | 0 | github-code | 90 |
40434799238 | # 친구리스트에서 자신의 모든 친구를 찾고 친구들의 친밀도를 계산하는 알고리즘
# 입력 : 친구 관계 그래프 g, 모든 친구를 찾을 name
# 출력 : 모든 친구의 이름과 자신과의 친밀도
def findFre(g, name):
usedName = []
already = set()
usedName.append((name, 0)) # 친밀도와 이름을 함께 묶어서 튜플로 처리
already.add(name)
while usedName:
(fre, d) = usedName.pop(0)
print(fre... | namekun/pythonStudy | ch15_Graph/친밀도알고리즘.py | 친밀도알고리즘.py | py | 920 | python | ko | code | 0 | github-code | 90 |
320082774 | import numpy as np
from typing import Tuple, List
from matplotlib import pyplot as plt
from net.metrics.utility.best_metrics import best_metrics
from net.utility.msg.msg_plot_complete import msg_plot_complete
def AUFROC_plot(figsize: Tuple[int, int],
title: str,
experiment_ID: str,
... | cirorusso2910/GravityNet | net/plot/AUFROC_plot.py | AUFROC_plot.py | py | 2,762 | python | en | code | 7 | github-code | 90 |
18477214399 | n = int(input())
from math import factorial
def comb(n, r):
if n < r:
return 0
return factorial(n) // factorial(r) // factorial(n - r)
def factorization(n):
arr = []
temp = n
for i in range(2, int(-(-n**0.5//1))+1):
if temp%i==0:
cnt=0
while temp%i==0:
... | Aasthaengg/IBMdataset | Python_codes/p03213/s780908134.py | s780908134.py | py | 1,051 | python | en | code | 0 | github-code | 90 |
21617224498 | from itertools import combinations
class Solution:
def mostVisitedPattern(self, username: List[str], timestamp: List[int], website: List[str]) -> List[str]:
def prepare_timestamps(username, timestamp, website):
track = {}
for i in range(len(username)):
if username[... | sgowdaks/CP_Problems | LeetCode/AnalyzeUserWebsiteVisitPattern.py | AnalyzeUserWebsiteVisitPattern.py | py | 2,029 | python | en | code | 0 | github-code | 90 |
27929290587 | from collections import defaultdict
from math import ceil
def init():
with open('input2.txt','r') as f:
eqs = f.readlines()
reactions = {}
for eq in eqs:
cs,p = eq.strip().split(' => ')
i_p,n_p = p.split(' ')
p = (int(i_p),n_p)
cs = cs.split(', ')
l_c = []
... | arty-hlr/CTF-writeups | 2019/adventofcode/14/solve1.py | solve1.py | py | 2,129 | python | en | code | 1 | github-code | 90 |
33108713426 | from turtle import Turtle
ALIGNMENT = "center"
FONT = ("Arial", 24, "normal")
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.score = 0
self.penup()
self.color("white")
self.goto(x=0, y=260)
self.update_scoreboard()
self.hideturtle()
... | rorManish09/Python-Projects | 20_SnakeGame/scoreboard.py | scoreboard.py | py | 651 | python | en | code | 2 | github-code | 90 |
18431234229 | import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_nl = lambda: list(map(int, readline().split()))
in_na = lambda: map(int, read().split())
in_s = lambda: readline().rstrip().decode('utf-8')
def main():
N = ... | Aasthaengg/IBMdataset | Python_codes/p03095/s755907500.py | s755907500.py | py | 567 | python | en | code | 0 | github-code | 90 |
41578519982 | import pickle
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib.cm as cm
import matplotlib.gridspec as gridspec
from math import pi
from math import sin
from math import cos
from PlotMaker import PlotMaker
from Network import OverlapNetwork
from LearningNetwork imp... | chingf/mixed-attractor-network | run.py | run.py | py | 4,596 | python | en | code | 0 | github-code | 90 |
42267504374 | import sys
input = sys.stdin.readline
delta = [(0,1),(1,0),(0,-1),(-1,0)]
def cctview(grid, idx=0):
if idx == len(cctv): # 모든 cctv의 시야 방향을 정했을 경우
tot = 0 # 사각지대 수
for line in grid: # 0(=사각지대)의 개수를 모두 더함
for cert in line:
if not cert:
... | junhong625/TIL | Algorithm/Baekjoon/Gold/[15683번] 감시.py | [15683번] 감시.py | py | 2,314 | python | ko | code | 2 | github-code | 90 |
26295849885 | import csv
import GPFMaker
results = []
with open("baby_protein_ids.txt") as csvfile:
reader = csv.reader(csvfile) # change contents to floats
for row in reader: # each row is a list
for element in row:
results.append(element)
print(format(results))
for protein_id in results:
GPFMaker... | georgesquinn/geometric-protein | BabyProteinGPFMaker.py | BabyProteinGPFMaker.py | py | 338 | python | en | code | 0 | github-code | 90 |
20926069265 | from rest_framework import serializers
from rest_framework.reverse import reverse
from users.models import User
from .models import Task
class TaskSerializer(serializers.ModelSerializer):
links = serializers.SerializerMethodField()
status_display = serializers.SerializerMethodField()
assigned = serialize... | Katsiarynka/task_manager | tasks/serializers.py | serializers.py | py | 1,378 | python | en | code | 0 | github-code | 90 |
22565365957 | import os
import sqlite3
import typing
import numpy as np
import Helpers
import Models
# how much to spend when buying a stock
BUY_BUDGET: int = 1000
# how high a stock can rise before we sell it to take profits
# RISE_LIMITS: typing.List[int] = np.logspace(0.1, 2, 10, dtype=int)
RISE_LIMITS: np.ndarray = np.logspa... | cwcowell/haircuts-and-oatmeal | src/HaircutsAndOatmeal.py | HaircutsAndOatmeal.py | py | 2,263 | python | en | code | 0 | github-code | 90 |
72111370538 | import os
from FileManaging import DFManaging
import RawDataFetching as RawDF
def source_dir() -> str:
return "src"
__source_dir__ = source_dir()
class DataFile:
"""
Description:
A simple data managing class.
"""
def __init__(self, exists_or_not: bool = False, **kwargs) -> None:
... | SqrWent/EVE_Industry_Helper | EIH.py | EIH.py | py | 2,084 | python | en | code | 0 | github-code | 90 |
14064056891 | from collections import OrderedDict
from pathlib import Path
from typing import List, Tuple
import cf_units as unit
import numpy as np
from iris.analysis import MEAN
from iris.coords import DimCoord
from iris.cube import Cube, CubeList
from numpy import ndarray
from improver import PostProcessingPlugin
from improver.... | metoppv/improver | improver/calibration/rainforest_calibration.py | rainforest_calibration.py | py | 30,148 | python | en | code | 95 | github-code | 90 |
13005124855 | # -*- coding: utf-8 -*-
from typing import Tuple
from torch import nn
import torch
from ray.rllib.models.torch.misc import normc_initializer
from torch.distributions import MultivariateNormal
from torch_geometric.data import HeteroData
from torch_geometric.nn import GATConv
import torch.nn.functional as F
class Graph... | benedikt-schesch/l2rpn-baselines | src/python/agent.py | agent.py | py | 6,894 | python | en | code | 1 | github-code | 90 |
26965791847 | #!/usr/bin/env python
import os
import importlib.util
def get_version():
spec = importlib.util.spec_from_file_location(
"version",
os.path.abspath(os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'..',
'biweeklybudget',
'version.py'
)... | jantman/biweeklybudget | dev/get_version.py | get_version.py | py | 583 | python | en | code | 87 | github-code | 90 |
38035203562 | import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import csv
############################USER INPUTS############################
CommInt = 0.05
StopTime = 60.0
#adding 1 since it is otherwise between 0 and 49.95
bodi = ["BOD1"]
codi = ["COD1"]
bod = ["BOD31"]
cod = ["COD31"]
bod_c = ["BO... | annalaino/GPS-X-coding | Robustness.PY | Robustness.PY | py | 3,190 | python | en | code | 0 | github-code | 90 |
20600533616 | import logging
import os
from pathlib import Path
from typing import TYPE_CHECKING, Any, Optional
from flask import Flask
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
from . import default_settings
if TYPE_CHECKING:
from vault.models.user import User
def create_app() -> Flask:
... | jizhang/vault-server | vault/__init__.py | __init__.py | py | 1,841 | python | en | code | 0 | github-code | 90 |
23362991304 | import random
def main_game(score):
while True:
move = input('> ')
if move == "!exit":
print("Bye!")
break
if move == "!rating":
print(score)
else:
choices = ['rock', 'paper', 'scissors']
computer_move = random.choice(["sci... | Stellupo/JetBrainsAcademyPython | RockPaperScissors.py | RockPaperScissors.py | py | 3,106 | python | en | code | 0 | github-code | 90 |
11528207188 | from __future__ import annotations
import asyncio
import sys
from typing import Union, Optional
import redis
if sys.version_info >= (3, 8):
from typing import Type, TypedDict
else:
from typing_extensions import Type, TypedDict
if sys.version_info >= (3, 11):
from asyncio import timeout as async_timeout
... | Arun-chaitanya/posthog-vite | env/lib/python3.10/site-packages/fakeredis/aioredis.py | aioredis.py | py | 9,077 | python | en | code | 0 | github-code | 90 |
18103791289 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
input:
11
7
8
9
10
11
12
13
14
15
16
17
output:
4
"""
import sys
def is_prime(x):
if x == 2:
return True
elif x < 2 or not x % 2:
return False
return pow(2, x - 1, x) == 1
def solve(_c_list):
cnt = 0
for ele in _c_list:
... | Aasthaengg/IBMdataset | Python_codes/p02257/s011262731.py | s011262731.py | py | 546 | python | en | code | 0 | github-code | 90 |
27675680003 | """ Simple Linked List. """
class Node:
""" Element of a linked list.
Contains a key and points to the next element. """
def __init__(self, key, next_element=None):
self.key = key
self.next_element = next_element
class SimpleLinkedList:
""" Implementation of a Linked List. """
d... | brunobcestari/CS_studies | data_structures/Python/linkedlists.py | linkedlists.py | py | 3,346 | python | en | code | 0 | github-code | 90 |
15414011717 | from django.urls import reverse
from rest_framework import status
from rest_framework.exceptions import ErrorDetail
from rest_framework.test import APITestCase, APIClient
from habits.models import Habit
from users.models import User
class HabitsTestCase(APITestCase):
def setUp(self):
self.user = User.ob... | AnastasiaLykova/drf_habits_7_course | habits/tests.py | tests.py | py | 3,913 | python | en | code | 0 | github-code | 90 |
21372786886 | class Book:
def __init__(self, name, author, pages):
self.name = name
self.author = author
self.pages = pages
# book = Book("My Book", "Me", 200)
# print(book.name)
# print(book.author)
# print(book.pages)
# "self" се самоизвиква - в нашия пример е "book".
# Функция, която е ... | BogomilaKatsarska/Python-Advanced-SoftUni-OOP | First Steps in OOP - L1Q3.py | First Steps in OOP - L1Q3.py | py | 486 | python | bg | code | 0 | github-code | 90 |
18385146459 | # -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1
def main():
N,M=map(int,input().split())
... | Aasthaengg/IBMdataset | Python_codes/p03003/s629987976.py | s629987976.py | py | 884 | python | en | code | 0 | github-code | 90 |
38510276392 | """ wordprocessing.py """
import string
from collections import OrderedDict, Counter
import sys
import re
import spacy
import numpy as np
def keyword_extractor(data: list) -> list:
"""
Function to extract keywords from the headers and paragraphs of slides
:param data: The list of dictionaries of the form... | mtkumar123/CSC510_Project_LectureAid | code/wordprocessing.py | wordprocessing.py | py | 9,663 | python | en | code | 0 | github-code | 90 |
27855183703 | from typing import TextIO
# importing the required module
import matplotlib.pyplot as plt
from my_functions import * #make_random_matrix, write_to_file, read_whole_file, simple_plot, read_input
def exp1_1_main(input_file_path, input_file_name, recalc_flag, redraw_flag, first_scenario, last_scenario):
input_struct ... | guysmathphd/Exp1 | exp1_1.py | exp1_1.py | py | 1,439 | python | en | code | 0 | github-code | 90 |
44019931702 | """
Find the least common ancestor of two nodes in a binary tree. Handle the case when one or both
the nodes may be absent from the tree.
"""
class Node:
def __init__(self, key, left=None, right=None):
self.key = key
self.left = left
self.right = right
def lca(root, p, q):
if root is... | prathamtandon/g4gproblems | Graphs/LCA.py | LCA.py | py | 1,098 | python | en | code | 3 | github-code | 90 |
10419448365 | import torch.nn as nn
import torch.nn.functional as F
import torch
from torchsummary import summary
import torchvision.models as models
from torchvision.models import vgg19
from modelDefinitions.basicBlocks import *
import torch.nn.init as init
class attentiomDiscriminator(nn.Module):
def __init__(self):
... | sharif-apu/BJDD_CVPR21 | modelDefinitions/attentionDis.py | attentionDis.py | py | 3,190 | python | en | code | 59 | github-code | 90 |
71732163496 | from public_api import models
from decimal import Decimal
from public_api import api as public_api
from public_api import user_collection_view
from public_api import user_resume_view
import json
import datetime
import os
def sign_up(request):
try:
user_id = json.loads(bytes.decode(request.body)).get('user... | HoganRich/test_linux | hou/user_manage/api.py | api.py | py | 8,615 | python | en | code | 0 | github-code | 90 |
27093773898 | from spack import *
class PyFasteners(PythonPackage):
"""A python package that provides useful locks."""
homepage = "https://github.com/harlowja/fasteners"
url = "https://pypi.io/packages/source/f/fasteners/fasteners-0.14.1.tar.gz"
version('0.14.1', 'fcb13261c9b0039d9b1c4feb9bc75e04')
depe... | matzke1/spack | var/spack/repos/builtin/packages/py-fasteners/package.py | package.py | py | 480 | python | en | code | 2 | github-code | 90 |
18553720689 | import sys
input = sys.stdin.readline
ri = lambda: int(input())
rs = lambda: input().rstrip()
ril = lambda: list(map(int, input().split()))
rsl = lambda: input().rstrip().split()
ris = lambda n: [ri() for _ in range(n)]
rss = lambda n: [rs() for _ in range(n)]
rils = lambda n: [ril() for _ in range(n)]
rsls = lambda ... | Aasthaengg/IBMdataset | Python_codes/p03402/s564934402.py | s564934402.py | py | 1,010 | python | en | code | 0 | github-code | 90 |
38626414527 | numbers = [int(x) for x in input().split()]
def positive_sum(some_array):
global total_positive_sum
for num in some_array:
if num > 0:
total_positive_sum += num
return total_positive_sum
def negative_sum(some_array):
global total_negative_sum
for num in some_ar... | slambeca/SoftUni-Python-Advanced-May-2023 | 5.2. Functions Advanced - Exercise/negative_vs_positive.py | negative_vs_positive.py | py | 2,773 | python | en | code | 0 | github-code | 90 |
24600316141 | from django.test import Client, TestCase
from django.urls import reverse
from lcc.models import Question
class QuestionTests(TestCase):
fixtures = [
"Countries.json",
"Gaps.json",
"Questions.json",
"TaxonomyClassification.json",
"TaxonomyTag.json",
"TaxonomyTagGrou... | eaudeweb/lcc-toolkit | lcc/tests/api.py | api.py | py | 588 | python | en | code | 2 | github-code | 90 |
18456017199 | import heapq
from sys import stdin
N,K = map(int,input().split())
sushi = {}
for i in range(N):
t,d = map(int, stdin.readline().split())
if t in sushi.keys():
sushi[t].append(d)
else:
sushi[t] = [d]
P = []
Q = []
for x in sushi.keys():
sushi[x].sort(reverse = True)
P.append(sush... | Aasthaengg/IBMdataset | Python_codes/p03148/s485880886.py | s485880886.py | py | 926 | python | en | code | 0 | github-code | 90 |
18298114199 | import numpy as np
N ,M= map(int,input().split())
l=list(map(int,input().split()))
n0 = 2**int(np.ceil(np.log2(2*(max(l))-1)))
A = np.zeros(n0)
for i in range(N):
A[l[i]-1]+=1
C = np.fft.ifft( np.fft.fft(A)*np.fft.fft(A) )
ans=0
j=2
q=[]
for ci in np.real(C[:2*(max(l))-1] + 0.5):
q.append([int(ci),j])
j... | Aasthaengg/IBMdataset | Python_codes/p02821/s825044843.py | s825044843.py | py | 499 | python | zh | code | 0 | github-code | 90 |
38844750996 | # coding:utf-8
import json
import pytest
from apis.device_management.device_account.apis_device_account import Apis
@pytest.mark.bvt
@pytest.mark.device
@pytest.mark.flaky(reruns=3, reruns_delay=3)
def test_by_asset_types():
"""
获取设备模型
"""
try:
res = Apis().api_by_asset_types()
assert... | zj1995-09-09/supercare_api | testcase/device_management/device_account/test_device_by_asset_types.py | test_device_by_asset_types.py | py | 514 | python | en | code | 0 | github-code | 90 |
18539552459 | def check():
H, W = map(int, input().split())
S = [0]*(H+2)
S[0] = '.'*(W+2)
S[H+1] = '.'*(W+2)
for h in range(1,H+1):
S[h] = '.' + input() + '.'
dh = [0,1,0,-1]
dw = [1,0,-1,0]
for h in range(1,H+1):
for w in range(1,W+1):
if S[h][w]=='.':
... | Aasthaengg/IBMdataset | Python_codes/p03361/s997484610.py | s997484610.py | py | 568 | python | en | code | 0 | github-code | 90 |
14671101038 | from tkinter import *
import random
from tkinter.simpledialog import askstring
from tkinter.messagebox import showerror,showinfo,askyesno
root=Tk()
values={"A":8,"B":6,"C":4,"D":2}
letters=list(values.keys())
def deposit():
global deposited_money
try:
deposited_money=int(askstring("Deposit",... | Pokemon-2812/GUI-Projects | slot_machinegui.py | slot_machinegui.py | py | 3,281 | python | en | code | 0 | github-code | 90 |
73340167657 | from __future__ import annotations
__all__ = [
"to_min",
"direction_shorthand",
]
from typing import TYPE_CHECKING
if TYPE_CHECKING:
import pandas as pd
def to_min(series: pd.Series) -> pd.Series:
"""
Convert a series of timedeltas to a series of minutes
"""
return series.apply(lambda x:... | ianhi/mbta-analysis | mbta_analysis/_util.py | _util.py | py | 607 | python | en | code | 0 | github-code | 90 |
18226525229 | a, b, c, d = map(int, input().split())
flg = False
while True:
if c - b <= 0:
flg = True
break
if a - d <= 0:
flg = False
break
a -= d
c -= b
print('Yes' if flg else 'No') | Aasthaengg/IBMdataset | Python_codes/p02700/s102669495.py | s102669495.py | py | 205 | python | en | code | 0 | github-code | 90 |
73170951016 | from data import data
from art import logo, vs
import random
import os
def compare(A, B):
guess = input("Who has more followers? Type 'A' or 'B': ").lower()
if A["follower_count"] > B["follower_count"] and guess == 'a':
return True
elif A["follower_count"] > B["follower_count"] and guess == '... | Baldazzar/codebootcamp | higher-or-lower/main.py | main.py | py | 1,576 | python | en | code | 0 | github-code | 90 |
11616051979 | def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
try:
num = int(input("Введите число "))
if 0 <= num <= 1000:
print(is_prime(num))
else:
print("Введите число из диапозона (... | Hackir0/lab2 | lab2.1.py | lab2.1.py | py | 431 | python | ru | code | 0 | github-code | 90 |
5026364275 | import json
import warnings
import requests
warnings.filterwarnings('ignore')
from io import BytesIO
import seaborn as sns
from PIL import Image
sns.set_theme(style="darkgrid", font_scale=1.5, font="SimHei", rc={"axes.unicode_minus":False})
import torch
import torchmetrics
from torch import nn, optim
from torch.nn ... | Sunests/ml_system_design_2023 | ModelServer/model.py | model.py | py | 3,115 | python | en | code | 0 | github-code | 90 |
12213197009 | ar = []
with open('dataset_313198_2_4.txt', 'r') as f:
for l in f:
ar += [int(j) for j in l.split()]
sr = set(ar)
dr = {k:0 for k in ar}
for k in ar:
dr[k] += 1
print(max(dr.values()))
| Skylight666/for_csc_i_love_gitlab | AllForPython/foot/kek.py | kek.py | py | 205 | python | en | code | 0 | github-code | 90 |
5941895016 | import os
from tinydb import TinyDB
DB_FILE = "database.json"
DIRECTORY = "./database"
class Database:
"""
The database Model.
Creates and saves a new database director and
file if they don't exist already.
"""
def __init__(self):
"""Database constructor"""
if not os.path.exi... | Salomondiei08/ChessPy | chess_tournament_app/models/database.py | database.py | py | 557 | python | en | code | 3 | github-code | 90 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.