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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
17795520961 | import math
from typing import List
class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
def can_eat(k: int) -> bool:
ans = 0
for pile in piles:
ans += math.ceil(pile / k)
return ans <= h
left = 1
right = 10 ** 9
... | fastso/learning-python | leetcode_cn/solved/pg_875.py | pg_875.py | py | 517 | python | en | code | 0 | github-code | 36 |
14128566758 | #!/usr/local/bin/ python3
# -*- coding:utf-8 -*-
# __author__ = "zenmeder"
class Solution(object):
def findTargetSumWays(self, nums, S):
if not nums:
return 0
for i in range(len(nums)):
if i == 0:
dp = {nums[0]: 1, -nums[0]: 1} if nums[0] else {0:2}
continue
now = {}
for pre in dp.keys():
... | zenmeder/leetcode | 494.py | 494.py | py | 610 | python | en | code | 0 | github-code | 36 |
28514953067 | from PyQt4.QtCore import SIGNAL, QObject
from PyQt4 import QtGui
from opus_gui.util.icon_library import IconLibrary
def create_qt_action(icon_name, text, callback, parent_qt_object):
'''
Convenience method to create actions.
@param icon_name (str) name of icon to use (no Icon is used of the value is None)
... | psrc/urbansim | opus_gui/util/convenience.py | convenience.py | py | 3,823 | python | en | code | 4 | github-code | 36 |
2440750792 | #!/bin/env python3
from typing import Optional, TypeVar
from sqlmodel import SQLModel, Field
class MedicationLinkBase(SQLModel):
medication_id : Optional[int] = Field(
default=None,
foreign_key="medication.id"
)
class MedicationLinkBaseWithRequiredID(SQLModel):
medication_id : int = Fiel... | shlomo-Kallner/poppy_backend_assessment | src/poppy_s/lib/models/base/medications.py | medications.py | py | 924 | python | en | code | 0 | github-code | 36 |
23214835305 | # -*- coding: utf-8 -*-
import json
import re
from datetime import date
import dryscrape
from bs4 import BeautifulSoup
# Заголовки столбцов таблицы
titles = [
'Биржевой инструмент', # 0
'Предл.', # 1
'Спрос', # 2
'Ср.вз. цена', # 3
'Объем договоров', # 4
'Кол - во дог.', # 5
'НПЗ' # 6
]
... | rbikbov/test_python_bot | bot.py | bot.py | py | 9,250 | python | ru | code | 0 | github-code | 36 |
74768116583 | from collections import namedtuple
from datetime import date
import json
from django.shortcuts import reverse
from django.template import loader
from djaveAPI.find_models import publishable_model_from_name
from djaveAPI.paged_results import construct_paged_results
from djaveAPI.to_json import TYPE
from djaveAPI.widget... | dasmith2/djaveAPI | djaveAPI/docs.py | docs.py | py | 6,615 | python | en | code | 0 | github-code | 36 |
1076138061 | import unittest
from AntiSpam import AntiSpam
class TestAntiSpam(unittest.TestCase):
def setUp(self) -> None:
self.antiSpam = AntiSpam()
self.emailList = [
'nombre1@hotmail.com',
'nombre2@outlook.com',
'nombre3@yahoo.es',
'nombre4@hotmail.com',
... | malandrinersdev/desafio-miniaoc | soluciones/guillermoig/reto-1/test_AntiSpam.py | test_AntiSpam.py | py | 1,212 | python | en | code | 2 | github-code | 36 |
12020470252 | import container
import procs.procLoader
import terrainLoader
import things.thing
import things.stats
import util.boostedDie
import util.serializer
## Order in which we serialize records.
FIELD_ORDER = ['name', None,
'templates', None,
'display', None,
'interactions', None,
'flags', Non... | Valoren/Angpy | things/terrain/terrain.py | terrain.py | py | 7,247 | python | en | code | 1 | github-code | 36 |
30164407430 | #!/usr/bin/python3
"""
File: test_file_storage.py
"""
import unittest
import json
class TestFileStorage(unittest.TestCase):
"""File Storage Test"""
def test_json_load(self):
with open("file.json") as fd:
d = json.load(fd)
self.assertEqual(isinstance(d, dict), True)
de... | peterkthomas/AirBnB_clone | tests/test_models/test_engine/test_file_storage.py | test_file_storage.py | py | 474 | python | en | code | 0 | github-code | 36 |
6926982149 | import json
import os
import boto3
import time
def lambda_handler(event, context):
#Parse event
if type(event['body']) == str:
body = json.loads(event['body'])
data = body['data']
command = body['command']
else:
body = event['body']
data = body['data']
co... | metalstormbass/Terraform-Cloud-Goof | lambda_code/main.py | main.py | py | 1,102 | python | en | code | 0 | github-code | 36 |
72184818663 | """
Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome
that can be built with those letters.
Letters are case sensitive, for example, "Aa" is not considered a palindrome here.
"""
class Solution(object):
def longestPalindrome(self, s):
"""
... | Delacrua/LearningPython | LeetCode/409.longest_palindrome.py | 409.longest_palindrome.py | py | 662 | python | en | code | 0 | github-code | 36 |
25166244861 | import re
from django import forms
from crispy_forms.helper import FormHelper
from content.src.reg_expressions import RegExpressions
from content.models import Content, Video
from product.models import Product
class StyleMixin:
"""Класс добавляющий форматирование форм crispy-forms"""
def __init__(self, *ar... | NewterraV/content_selling_platform | content/forms.py | forms.py | py | 13,160 | python | ru | code | 0 | github-code | 36 |
24438494857 | # Some functions for the Mojang API
# import requests
import requests
import datetime
import json
class MinecraftUUIDError(ValueError):
pass
class MinecraftUsernameError(ValueError):
pass
class Player:
# Essential variables
username = None
uuid = None
alias = None
# Vars to be used i... | joshuaSmith2021/chamosbot-gassistant | mojang.py | mojang.py | py | 2,392 | python | en | code | 0 | github-code | 36 |
22076774319 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 4 18:18:30 2023
@author: Pervin
"""
#mini uygulama
#if, for ve fonksiyonlari birlikte kullanmak
maaslar = [1000,2000,3000,4000,5000]
def maas_ust(x):
print(x*10/100 + x)
def maas_alt(x):
print(x*20/100 + x)
for i in maaslar:
if i >= 3000:
... | pervincaliskan/Python | function_loops_example.py | function_loops_example.py | py | 366 | python | en | code | 1 | github-code | 36 |
74173801063 | from ctypes import CDLL, c_char_p, c_void_p, c_int, Structure, byref, c_byte
class SDL_Event(Structure):
_fields_ = [
('type', c_byte),
('padding', c_int * 1024),
]
class SDL(object):
SDL_INIT_AUDIO = 0x00000010
SDL_INIT_VIDEO = 0x00000020
SDL_OPENGL = 0x00000002
def... | supersmo/parley-who-vertigo | python/external/sdl.py | sdl.py | py | 1,644 | python | en | code | 1 | github-code | 36 |
20093789712 | # 序列:字符串 元祖 列表
# 成员操作符 🔗操作符 重复操作符 切片操作符
zodiac_name = ('猴鸡狗猪属牛虎兔龙蛇马羊')
constellation_name = (u'摩羯座', u'水瓶座', u'双鱼座', u'白羊座', u'金牛座', u'双子座',
u'巨蟹座', u'狮子座', u'处女座', u'天秤座', u'天蝎座', u'射手座')
# 元祖 不可变更
constellation_days = ((1, 20), (2, 19), (3, 21), (4, 21), (5, 21), (6, 22),
... | mario2100/Spring_All | try/py_try/1_zodiac_constellation.py | 1_zodiac_constellation.py | py | 1,963 | python | en | code | 0 | github-code | 36 |
30079500269 | import QRTicketing
import cv2
def Decode(str):
a='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
cipherstr=''
for i in str:
k=a.index(i)
cipherstr+=a[((k - 5)%26)]
return str
cap = cv2.VideoCapture(0)
detector = cv2.QRCodeDetector()
while True:
_, img = cap.read()
data, bbox, _ = detector.detectA... | PreethiPreetz-30/Ticketless-Entry---QR | ScanTicket.py | ScanTicket.py | py | 593 | python | en | code | 0 | github-code | 36 |
7753689154 | total_notas = int(input("Ingrese la cantidad total de notas: "))
suma_notas = 0.0
# Solicitar las notas individuales y sumarlas
for i in range(total_notas):
nota = float(input("Ingrese la nota {}: ".format(i+1)))
suma_notas += nota
# Calcular el promedio
promedio = suma_notas / total_notas
# Mos... | rubenalvarez98/Recuperalo | condicionales/condicionales5.py | condicionales5.py | py | 414 | python | es | code | 0 | github-code | 36 |
33008617060 | """ Python Class and Object """
class Parrot:
# class attribute
name = ""
age = 0
# create parrot1 object
parrot1 = Parrot()
parrot1.name = "Blu"
parrot1.age = 10
# create another object parrot2
parrot2 = Parrot()
parrot2.name = "Woo"
parrot2.age = 15
# access attributes
print(f"{parrot1.name} is {par... | Saiteja151/PYTHON_REPOS | Python/OOPS/OOPS/oops.py | oops.py | py | 1,971 | python | en | code | 0 | github-code | 36 |
15870462971 | import os
import sys
import time
import torch
import torch.nn.functional as F
from sklearn.metrics import mean_squared_error
from graphrepr.evaluate import test_model
from graphrepr.savingutils import save_configs, save_history, LoggerWrapper
from graphrepr.config import parse_model_config, parse_representation_config,... | gmum/graph-representations | scripts/main_dmpnn.py | main_dmpnn.py | py | 8,394 | python | en | code | 18 | github-code | 36 |
74837131945 | import unittest
from unittest.mock import Mock
from BookService import BookService
class TestBookService(unittest.TestCase):
def setUp(self) -> None:
self.book_repository = Mock()
self.author = "Лев Толстой"
self.list_books = [Mock(title="Анна Каренина"), Mock(title="Детство")]
def t... | vit21513/unit_test | homework/hw_4/test_bookService.py | test_bookService.py | py | 1,002 | python | en | code | 0 | github-code | 36 |
8838127682 | """Models for Blogly."""
from flask_sqlalchemy import SQLAlchemy
import datetime
db = SQLAlchemy()
DEFAULT_IMAGE_URL = "https://cdn2.iconfinder.com/data/icons/avatars-99/62/avatar-370-456322-512.png"
def connect_db(app):
"""Connect to database."""
db.app = app
db.init_app(app)
class User(db.Model):
... | kabdrau/Blogly-application | models.py | models.py | py | 2,622 | python | en | code | 0 | github-code | 36 |
31065164595 |
from ..utils import Object
class UpdateMessageEdited(Object):
"""
A message was edited. Changes in the message content will come in a separate updateMessageContent
Attributes:
ID (:obj:`str`): ``UpdateMessageEdited``
Args:
chat_id (:obj:`int`):
Chat identifier
... | iTeam-co/pytglib | pytglib/api/types/update_message_edited.py | update_message_edited.py | py | 1,307 | python | en | code | 20 | github-code | 36 |
11576039211 | from socket import *
from datetime import datetime
serverPort = 8080
serverSocket = socket(AF_INET, SOCK_DGRAM)
#atribui a porta ao socket criado
serverSocket.bind(('', serverPort))
print("The server is ready to receive")
while True:
#recebe a mensagem do cliente em bytes
message, clientAddress = serverSocket.r... | srpantoja/Redes_trabalhos | python/UDPServer.py | UDPServer.py | py | 593 | python | pt | code | 0 | github-code | 36 |
10638103617 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 14 23:01:14 2016
@author: Neo
parameter fitting, using Oort-Lindblad equation:
k*u_l^* = (S1*sin(l) - S2*cos(l)/r + B*cos(b) + A*cos(2l)*cos(b)
"""
import numpy as np
sin = np.sin
cos = np.cos
k = 4.7407
def ParFit(pmlon, err, l, b, r):
'''
pmls = pml*cos(b),... | Niu-Liu/thesis-materials | gaia-crf1/OLeqnFit.py | OLeqnFit.py | py | 3,982 | python | en | code | 0 | github-code | 36 |
22108118261 | #!/usr/bin/env python
# coding: utf-8
# Loading the libraries
import requests
from bs4 import BeautifulSoup
import time
import random
from tqdm.notebook import tqdm as tqdm
# Part a
page_url = "https://www.barnesandnoble.com/b/books/_/N-1fZ29Z8q8?Nrpp=40&page=1"
headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0... | jeetp465/Web-Scraping | Barnes and Noble Scraping.py | Barnes and Noble Scraping.py | py | 1,841 | python | en | code | 0 | github-code | 36 |
1252647732 | class MiddleoftheLinkedList(object):
def middleNode(self, head):
A = [head]
while A[-1].next:
A.append(A[-1].next)
return A[len(A) // 2]
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
if __name__ == '__main__':
a = MiddleoftheLink... | lyk4411/untitled | beginPython/leetcode/MiddleoftheLinkedList.py | MiddleoftheLinkedList.py | py | 669 | python | en | code | 0 | github-code | 36 |
40935361016 | list = []
dataIn = None
def printLowHigh(list):
high = list[0]
low = list[0]
for i in range(len(list)):
if i < low:
low = list[i]
if i > high:
high = list[i]
print (low, high)
def Promedio(list):
suma = 0
for i in range(len(list)):
suma = suma + ... | carlitomm/python_prog_course | 1ejercicios_clases/eje8.py | eje8.py | py | 544 | python | en | code | 0 | github-code | 36 |
2457622473 |
# This Python code reproduces the upper and low panel of Fig. 6 in Clay et. al. (2008).
#Save the voltage nd time series csv files as v1.csv for the standard HH model (top panel of fig.6 and v2.csv for the revised model (bottom panel for of fig. 6)
from neuron import h
import numpy as np
import matplotlib.pyplot ... | ModelDBRepository/189922 | clay_mohit.py | clay_mohit.py | py | 3,447 | python | en | code | 0 | github-code | 36 |
34357549837 | import argparse
import modelsim_utils
import time
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--do_file_name' , default = 'run_cmd.do')
parser.add_argument('-r', '--run_to_pane_shift_sleep_sec', default = 4) # 7
parser.add_argument('-t','--true_or_false_flag_example', action='store_tr... | Brandon-Valley/examples | python/script_arg_parse.py | script_arg_parse.py | py | 496 | python | zh | code | 0 | github-code | 36 |
39755602271 | # @Author : tony
# @Date : 2021/5/2
# @Title : epjb2009 paper practice
# @Dec : deal with the dataset
import networkx as nx
# deal with the INT dataset
def readINT(dataUrl):
G = nx.read_gml(dataUrl)
list = dict()
edge_list = []
for id, label in enumerate(G.nodes()):
list[int(label)] = in... | DDMXIE/LinkPrediction | practice/dataTransform.py | dataTransform.py | py | 2,178 | python | en | code | 0 | github-code | 36 |
8446001098 | import unittest
import pytest
from cupy_backends.cuda import stream as stream_module
import cupy
from cupy import _core
from cupy import testing
# TODO(leofang): test PTDS in this file
class DummyObjectWithCudaArrayInterface(object):
def __init__(self, a, ver=3):
self.a = a
self.ver = ver
... | cupy/cupy | tests/cupy_tests/core_tests/test_ndarray_cuda_array_interface.py | test_ndarray_cuda_array_interface.py | py | 10,691 | python | en | code | 7,341 | github-code | 36 |
2285653529 | #Item 1 #############################################################################################################
import hashlib
from random import randint
def cadastrar(nome,senha):
senhaReal = senha
senhaHash = (hashlib.md5(senhaReal.encode('utf-8')).hexdigest())
with open("UsuariosCadastrados.t... | Williamsbsa/Quebra-de-Hash-MD5-Python | QuebradeHashMd5.py | QuebradeHashMd5.py | py | 5,406 | python | pt | code | 0 | github-code | 36 |
32336318719 | from flask_app.config.mysqlconnection import connectToMySQL
class User:
def __init__(self, data):
self.id = data['id']
self.first_name = data['first_name']
self.last_name = data['last_name']
self.email = data['email']
self.created_at = data['created_at']
self.updated... | JBShort/post-Bootcamp-Python | flask_mysql/Users_CRUD_Modularized/flask_app/models/user.py | user.py | py | 1,593 | python | en | code | 0 | github-code | 36 |
18605057627 | import tensorflow as tf
from QingDaoCoRec.CoRec import input_data
import os
import csv
import time
import numpy as np
dir = 'MODEL'
mod_name = 'model'
mod_cnt = 0
mod_end = '.ckpt'
batch_size = 100
def wei_mat(shape):
ini = tf.random.truncated_normal(shape, stddev=0.1)
return tf.Variable(ini)... | B1ACK917/QingDaoCoRec | CoRec/mod.py | mod.py | py | 6,068 | python | en | code | 1 | github-code | 36 |
11193542891 | """ клиентская часть """
import sys
import json
import time
import re
import logging
import logs.config_client_log
from lib.variables import ACTION, PRESENCE, TIME, USER, ACCOUNT_NAME, RESPONSE, AUTH, ALERT, MSG, ERR200, ERR400, \
CLIENT_LISTEN, LISTEN, SENDER, MSG, MSG_TEXT, ERROR
from lib.utils import create_soc... | ESarmanov/client_server_app_Python_GeekBrains | Lesson_7_Sarmanov_EF/client.py | client.py | py | 8,345 | python | ru | code | 0 | github-code | 36 |
25577847045 | class Solution:
def maxProfit(self, prices: List[int]) -> int:
# add up the difference between all local valleys and peaks
profit = 0
for i in range(1, len(prices)):
prev = prices[i-1]
current = prices[i]
if current > prev:
profit += curre... | korynewton/code-challenges | leetcode/BestTimeToBuySell2/solution.py | solution.py | py | 353 | python | en | code | 0 | github-code | 36 |
11306283317 | import sys
import numpy as np
from tensorflow.keras.applications import VGG16
from tensorflow.keras.applications.vgg16 import preprocess_input
from FaultInjector.StuckAtFaultInjector import StuckAtFaultInjector
from RunManager.NetworkManager import NetworkManager
from FaultDetector.FaultDetectorMetrics import FaultD... | GabrieleGavarini/FaultInjector | main.py | main.py | py | 6,630 | python | en | code | 1 | github-code | 36 |
24739226033 | from fastapi import APIRouter
from app.api.segmentation import doc_parser, paddle
from app.core.config import settings
from app.schemas.doc_parser import ImageInput, ImageOutput
router = APIRouter(prefix="/segment", tags=["segment"])
@router.post("/detect-image")
async def doc_parser_api(*, img_in: ImageInput):
... | rednam-ntn/dosa | server/app/api/__init__.py | __init__.py | py | 933 | python | en | code | 1 | github-code | 36 |
35918965719 | import contextlib
import hashlib
import httplib
import socket
import tempfile
import urllib2
try:
from PIL import Image as PILImage
except ImportError:
import Image as PILImage # noqa
from django.conf import settings
from django.core.files import File
from django.db import transaction
from comics.aggregator... | macanhhuy/comics | comics/aggregator/downloader.py | downloader.py | py | 5,379 | python | en | code | null | github-code | 36 |
74050008424 | import json
import uuid
import websocket
import time
import threading
from parlai.core.params import ParlaiParser
# the socket callback functions operate asynchronously.
# upon exit of a chat, we do not want the user to view any additional messages from the server.
# alas, it is necessary to send two messages ([DONE],... | facebookresearch/ParlAI | parlai/chat_service/services/terminal_chat/client.py | client.py | py | 3,446 | python | en | code | 10,365 | github-code | 36 |
30330065701 | import numpy as np
import os
import argparse
import h5py
import sys
from spad_tools.listFiles import listFiles
from spad_tools.array2tiff import array2tiff, array2RGBtiff
from spad_tools.getFCSinfo import getFileInfo
from libttp import ttp
"""
This set of functions allows to read a binary file containing SPAD measurem... | VicidominiLab/libspadffs | spad_fcs/meas_to_count.py | meas_to_count.py | py | 12,651 | python | en | code | 0 | github-code | 36 |
7392241864 |
import argparse
from . import board
from . import constants
from . import solver
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("board", nargs="?")
parser.add_argument("-m", "--manual", default=False, action="store_true")
return parser.parse_args()
def main():
args = ... | MattCCS/SudokuSolver | sudoku.py | sudoku.py | py | 698 | python | en | code | 0 | github-code | 36 |
11984682489 | class Subscriber:
def __init__(self):
self.clients = []
def add(self, name, email):
for client in self.clients:
if client["name"] == name and client["email"] == email:
raise Exception("This client exists")
if type(name) == str and type(email) == str:
... | TestowanieAutomatyczneUG/laboratorium-12-wolnikowa | .github/src/zad2.py | zad2.py | py | 4,782 | python | en | code | 0 | github-code | 36 |
42300807705 | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
url = ''
driver = webdriver.Chrome()
driver.get(url)
element_founder = driver.find_element_by_name('q')
element_founder.send_keys('selenium')
element_founder.send_keys(Keys.RETURN)
results = driver.find_elements_by_css_selector... | seriybeliy11/parsers | sel_parser.py | sel_parser.py | py | 380 | python | en | code | 0 | github-code | 36 |
26284873290 | # To sort an array considering it as a nearly complete binary tree and then sorting it using max heapify
def max_heapify(mh, idx):
left = (idx << 1) + 1
right = (idx + 1) << 1
largest = idx
if left < len(mh) and mh[left] > mh[largest]:
largest = left
if right < len(mh) and mh[righ... | deveshaggrawal19/projects | Algorithms/Searching and Sorting/Heap_Sort.py | Heap_Sort.py | py | 822 | python | en | code | 0 | github-code | 36 |
20928709222 | #!/usr/bin/env python
# coding: utf-8
# In[6]:
import time
import json
import pandas as pd
import re
import logging
from datetime import date, datetime, timedelta
from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.common.by import By
from webdriver_manager.c... | shivanianand/NaukriDataAnalysis | Scraping_final.py | Scraping_final.py | py | 4,365 | python | en | code | 0 | github-code | 36 |
40858491511 | #!/usr/bin/env python
import sys
import fitsio
import healpy
import numpy as np
import scipy as sp
import argparse
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
from picca.data import forest
from picca.data import delta
from picca import io
if __name__ == '__main__':
parser = argparse... | vserret/picca | tutorials/picca_plotSpec.py | picca_plotSpec.py | py | 8,731 | python | en | code | 0 | github-code | 36 |
19173841991 | #max duty_ns is 20ms and min is 5ms. We want 180 degrees (divisions)#Some variables
# This values may change depending on your servos
MIN_DUTY_NS = 500000
MAX_DUTY_NS = 2000000
PWM_FRECUENCY = 50 #hz
DEGREE_TO_NS = (MAX_DUTY_NS-MIN_DUTY_NS)/180
PWM_PATH = "/sys/class/pwm/"
# -------------- from bonescript's bone.js -... | maxpowel/BeagleBone-Tools | servo/servo.py | servo.py | py | 2,482 | python | en | code | 20 | github-code | 36 |
6394496653 | # Copyright (c) 2023 Graphcore Ltd. All rights reserved.
# The functional definition in this file was ported to Python
# from XCFun, which is Copyright Ulf Ekström and contributors 2009-2020
# and provided under the Mozilla Public License (v2.0)
# see also:
# - https://github.com/dftlibs/xcfun
# - https://git... | graphcore-research/pyscf-ipu | pyscf_ipu/exchange_correlation/b88.py | b88.py | py | 999 | python | en | code | 31 | github-code | 36 |
39099180403 | def palindrome(string):
try:
if len(string) == 0:
raise ValueError("We cannot catch a void string")
return string == string[::-1]
except ValueError as ex:
print(ex)
return False
def main():
try:
# print(palindrome(121))
print(palindrome(""))
e... | ArturoCBTyur/Prueba_Nueva | exceptions.py | exceptions.py | py | 452 | python | en | code | 0 | github-code | 36 |
35001315098 | from ipywidgets import Box, HBox, VBox, FloatSlider, FloatProgress, Label, Layout
s1 = FloatSlider(description='Apple', min=-5, max=5, step=0.01, value=0, layout=Layout(width='90%'))
s2 = FloatSlider(description='Horse', min=-5, max=5, step=0.01, value=0, layout=Layout(width='90%'))
s3 = FloatSlider(description='Flower... | CaptainProton42/MNISTFromScratch | media/softmax_widget.py | softmax_widget.py | py | 1,890 | python | en | code | 1 | github-code | 36 |
9195714863 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from math import sqrt
def wn_conv1d(*args, **kwargs):
return nn.utils.weight_norm(nn.Conv1d(*args, **kwargs))
def wn_conv_transpose1d(*args, **kwargs):
return nn.utils.weight_norm(nn.ConvTranspose1d(*args, **kwargs))
de... | kklemon/text-gan-experiments | legacy/vq_vae_text/vq_vae_text/modules.py | modules.py | py | 10,464 | python | en | code | 0 | github-code | 36 |
958022852 | #!/usr/bin/env python3
"""An Implement of an autoencoder with pytorch.
This is the template code for 2020 NIAC https://naic.pcl.ac.cn/.
The code is based on the sample code with tensorflow for 2020 NIAC and it can only run with GPUS.
Note:
1.This file is used for designing the structure of encoder and decoder.
... | China-ChallengeHub/oppo_0.71 | trainer2.py | trainer2.py | py | 7,400 | python | en | code | 1 | github-code | 36 |
71599661864 | import io
import unittest
from glop.host import Host
import glop.tool
from .host_fake import FakeHost
SIMPLE_GRAMMAR = "grammar = anything*:as end -> join('', as) ,"
class ToolTests(unittest.TestCase):
maxDiff = None
def check_call_and_return_files(self, host, args, files):
orig_wd = None
... | dpranke/glop | tests/tool_test.py | tool_test.py | py | 8,564 | python | en | code | 4 | github-code | 36 |
3156449566 | #!/usr/bin/python3
# Script responsible for removing extra tags of nightly images
# QUAY_ACCESS_TOKEN is needed to set as environment variable before executing script
# The access token is used for authentication against the quay api.
import os
import json
import requests
from dateutil.relativedelta import *
from date... | kiegroup/kogito-pipelines | tools/clean-nightly-tags.py | clean-nightly-tags.py | py | 3,786 | python | en | code | 2 | github-code | 36 |
22836675271 | n = int(input())
n_list = input()
m = int(input())
m_list = input()
n_list = list(map(int, n_list.split(" ")))
m_list = list(map(int, m_list.split(" ")))
dic = {}
for i in n_list:
if i not in dic:
dic[i] = 1
else:
dic[i] = dic[i]+1
for i in m_list:
if i in dic:
print(dic[i], end=... | KuBonWhi/Algorithm | Backjoon/BOJ_10816.py | BOJ_10816.py | py | 360 | python | en | code | 0 | github-code | 36 |
25489916263 | import pytest
import pytest_spec.basic as basic
class TestErrors:
def test_zero(parameter_list):
with pytest.raises(ZeroDivisionError) as e:
basic.division_by_zero(1)
assert e.type == ZeroDivisionError
assert e.typename == "ZeroDivisionError"
assert str(e.value) == "div... | atu4403/pytest_spec | tests/basic/test_basic.py | test_basic.py | py | 865 | python | en | code | 0 | github-code | 36 |
42735837127 | # -------------------------------------------------
# [programmers] 큰수 만들기 (그리디)
# 1. 가장 큰 수를 찾음
# 2. 가장 큰수의 왼쪽 중 가장 작은 수 날림
# 3. k의 개수가 남으면 가장 큰수 오른쪽 가장 작은수 날림
# -------------------------------------------------
# def solution(number, k):
# max_value = max(number) # 아스키 코드로 가장 큰 문자열 반환
# # for i in number[... | jungbin97/pythonworkspace | 그리디/[programmers]큰수만들기.py | [programmers]큰수만들기.py | py | 2,003 | python | ko | code | 0 | github-code | 36 |
20405571634 | from tespy.networks import Network
from tespy.components import (Turbine, Pump, Condenser, HeatExchangerSimple, CycleCloser, Source, Sink)
from tespy.connections import Connection, Bus
import matplotlib.pyplot as plt
import numpy as np
def easy_process():
# network
fluid_list = ['Water']
rankine_nw = Netw... | JubranKhattab/testing_tespy_projects | rankine_cycle.py | rankine_cycle.py | py | 6,236 | python | en | code | 0 | github-code | 36 |
74207679783 | import random
from ltl.spot2ba import Automaton
import ltl.worlds.craft_world as craft
from collections import defaultdict
# TODO: add `grass` and `toolshed` back
GRAMMAR = """
BinOp -> 'and' | 'or'
UOp -> 'do not' | 'you should not'
Not -> 'not'
Item -> 'apple' | 'orange' | 'pear'
Landmark -> 'f... | czlwang/ltl-environment-dev | ltl/language/generator.py | generator.py | py | 8,694 | python | en | code | 0 | github-code | 36 |
34455554450 | # -*- coding: utf8 -*-
from django.db import models
class Timer(models.Model):
""" Модель таймера """
start_time = models.DateTimeField(
verbose_name="Время начала",
null=True,
blank=True
)
end_time = models.DateTimeField(
verbose_name="Время конца",
null=True,... | Aplles/project_tracker | models_app/models/timer/models.py | models.py | py | 1,025 | python | ru | code | 0 | github-code | 36 |
36728079897 | #!/usr/bin/env python2
from pwn import *
IP, PORT = 'pwn01.chal.ctf.westerns.tokyo', 12463
DEBUG = False
context.arch = 'x86_64'
context.aslr = False
context.log_level = 'debug'
context.terminal = ['gnome-terminal', '-x', 'sh', '-c']
def hn(prev, targ):
val = targ - prev
return (val & 0xffff) if (val & 0xf... | Aleks-dotcom/ctf_lib_2021 | Zh3ro_ctf/pwn/More_printf/public/vuln/randomsol.py | randomsol.py | py | 2,746 | python | en | code | 1 | github-code | 36 |
70593996584 | import math
import os
from itertools import count, cycle
import json
#MUST BE INSTALLED VIA PIP
import tkinter
from tkinter import *
from tkinter import messagebox
from PIL import Image, ImageTk
#-------------------------------------------------------------------------------
#!--- VARS FOR QUESTY STUFF
# goat gifs
... | introvertices/Task-list | main.py | main.py | py | 8,432 | python | en | code | 0 | github-code | 36 |
6395338624 | from intersection import Movement, Phase
import numpy as np
import random
class Agent:
"""
The base clase of an Agent, Learning and Analytical agents derive from it, basically defines methods used by both types of agents
"""
def __init__(self, eng, ID):
"""
initialises the Agent
... | mbkorecki/rl_traffic | src/agent.py | agent.py | py | 11,440 | python | en | code | 1 | github-code | 36 |
12139898242 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Color-coded progress bars
"""
__author__ = "Argentina Ortega Sainz"
__copyright__ = "Copyright (C) 2015 Argentina Ortega Sainz"
__license__ = "MIT"
__version__ = "2.0"
import sys
from PyQt4 import QtGui
from PyQt4.QtGui import QProgressBar
DEFAULT_STYLE = """
QProg... | argenos/AUI | aui/utilities/ColorProgressBar.py | ColorProgressBar.py | py | 1,563 | python | en | code | 0 | github-code | 36 |
25482260523 | import cv2
import time
import mediapipe as mp
cap = cv2.VideoCapture(1)
mp_hands = mp.solutions.hands
hands = mp_hands.Hands() #hands.py ctrl+left mouse
mp_draw = mp.solutions.drawing_utils
new_frame_time = 0
prev_frame_time = 0
while True:
ret, frame = cap.read()
new_frame_time = time.time()
fps = 1... | atuad7535/Volume_Control_Using_Hand_Gesture | Hand_Tracking.py | Hand_Tracking.py | py | 1,333 | python | en | code | 7 | github-code | 36 |
13643223508 | from time import *
timer = int(input("1 - start, 2 - end: "))
while timer != 2:
if timer == 1:
start_timer = time()
timer = int(input("1 - start, 2 - end: "))
end_timer = time()
total = end_timer-start_timer
print("Time that has passed:",total,"seconds")
points = 0
if total < 10:
points += 3
elif t... | Joshwen7947/Zero-to-Knowing | Udemy_code/lesson 12 code/main.py | main.py | py | 1,178 | python | en | code | 0 | github-code | 36 |
25947162458 | class Solution:
def maxVowels(self, s: str, k: int) -> int:
max_count = 0
count = 0
vowels = ("a", "e", "i", "o", "u")
left = 0
right = 0
while right <= len(s)-1:
if left-1 >=0 and s[left-1] in vowels:
count -= 1
if s[right] in... | dzaytsev91/leetcode-algorithms | medium/1456_maximum_number_of_vowels_in_a_substring_of_given_length.py | 1456_maximum_number_of_vowels_in_a_substring_of_given_length.py | py | 567 | python | en | code | 2 | github-code | 36 |
74353872105 | import re
import phonenumbers
from django import forms
from django.utils.translation import ugettext_lazy as _
from kavenegar import *
from sentry import http
from sentry.plugins.bases.notify import NotificationPlugin
import sentry_kavenegar
DEFAULT_REGION = 'IR'
MAX_SMS_LENGTH = 160
def validate_phone(phone):
... | amirasaran/sentry-kavenegar | sentry_kavenegar/models.py | models.py | py | 4,522 | python | en | code | 3 | github-code | 36 |
6673487305 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Test config.py module."""
# STDLIB
import os
# THIRD-PARTY
import numpy as np
import pytest
# SYNPHOT
from synphot.config import conf as synconf
from synphot.utils import generate_wavelengths
# LOCAL
from stsynphot import config
from stsynphot.stio ... | spacetelescope/stsynphot_refactor | stsynphot/tests/test_config.py | test_config.py | py | 2,785 | python | en | code | 11 | github-code | 36 |
36771601568 | ## dammit-turnip
## Version: 0.1
## Author: Adam Lenart
## Main file that interacts with the user
## standard imports
import argparse
## 3rd parth imports
from PIL import Image
## own modules
from src import dialog_action
from src import processor
###################################################################... | adamlenart/dammit-turnip | make_circle.py | make_circle.py | py | 5,417 | python | en | code | 0 | github-code | 36 |
448222125 | from __future__ import print_function
from pyspark.sql import functions as F
from pyspark.sql.functions import mean, min, max, variance, lag, count, col
from pyspark import sql
from pyspark import SparkContext, SparkConf
from pyspark.sql.types import ArrayType, StringType, IntegerType, DoubleType, LongType, FloatType
f... | avilin66/Pyspark_codes | EUW_CUSTOMER_LOCATION_WEATHER_DATA.py | EUW_CUSTOMER_LOCATION_WEATHER_DATA.py | py | 5,260 | python | en | code | 1 | github-code | 36 |
18248471298 | """
This file contains methods to visualize EKG data, clean EKG data and run EKG analyses.
Classes
-------
EKG
Notes
-----
All R peak detections should be manually inspected with EKG.plotpeaks method and
false detections manually removed with rm_peak method. After rpeak examination,
NaN data can be accounted for by ... | CardioPy/CardioPy | cardiopy/ekg.py | ekg.py | py | 87,636 | python | en | code | 7 | github-code | 36 |
41907884718 | import time
import cv2
import mediapipe as mp
mp_face_detection = mp.solutions.face_detection
import os
os.environ['OPENCV_FFMPEG_CAPTURE_OPTIONS'] = 'rtsp_transport;udp'
class face_detection:
def __init__(self):
self.URL = "rtsp://192.168.0.22:8554/"
self.cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
self.image = ... | CSID-DGU/2022-2-SCS4031-EZ_SW | FaceDetection.py | FaceDetection.py | py | 1,175 | python | en | code | 0 | github-code | 36 |
34118610496 | import os
from flask import Flask
import ghhops_server as hs
import rhino3dm
import pymaxwell5 as pym
app = Flask(__name__) #flask
hops = hs.Hops(app) #flask
#hops = hs.Hops() #http
@hops.component(
"/maxwell",
name="Maxwell",
description="render",
icon="C://Users//archi//Dropbox//course//maxwell.p... | seghier/maxwell | venv/maxwell.py | maxwell.py | py | 1,679 | python | en | code | 0 | github-code | 36 |
21334762187 | import unittest
import numpy as np
import pandas as pd
from os.path import join, dirname
from pandas import DataFrame, read_csv
from sostrades_core.execution_engine.execution_engine import ExecutionEngine
from sostrades_core.tests.core.abstract_jacobian_unit_test import AbstractJacobianUnittest
class GHGEmissionsJac... | os-climate/witness-core | climateeconomics/tests/l1_test_gradient_agriculture_ghgemissions_discipline.py | l1_test_gradient_agriculture_ghgemissions_discipline.py | py | 3,649 | python | en | code | 7 | github-code | 36 |
2876716401 | from argparse import ArgumentParser
from config_parser import get_config
import os
import yaml
import matplotlib.pyplot as plt
import time
import torch
from torch import nn, optim
import wandb
from typing import Callable, Tuple
from utils.loss import LabelSmoothingLoss
from utils.opt import get_optimizer, get_adversa... | GregTheHunInDk/Robust_KWT | adv_pretrain.py | adv_pretrain.py | py | 16,336 | python | en | code | 0 | github-code | 36 |
10724474044 | import xmltodict
import json
# Loading and parsing the xml file.
with open (r'q1.xml', "r") as xml_file:
xml_data = xml_file.read()
print(xml_data)
# Convert xml to json
json_data = json.dumps(xmltodict.parse(xml_data), indent=4)
print(json_data)
with open("output.json", "w") as json_file:
json_fil... | JonathanDabre/ip_ut2 | UT-2/xml/q4.py | q4.py | py | 338 | python | en | code | 1 | github-code | 36 |
23680100556 | #grid = [[0 for j in range(9)] for i in range(9)]
import time
def not_complete(board):
for i in board:
if 0 in i:
return True
return False
#will return True if the inputted number is not in the row
def check_row(board, row_num, num):
if num in board[row_num]:
return... | jfitz02/Sudoku-Solver | sudoku solver/sudokusolver.py | sudokusolver.py | py | 2,719 | python | en | code | 0 | github-code | 36 |
43914267111 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def flatten(self, root: Optional[TreeNode]) -> None:
"""
Do not return anything, modify root... | robinsdeepak/leetcode | 114-flatten-binary-tree-to-linked-list/114-flatten-binary-tree-to-linked-list.py | 114-flatten-binary-tree-to-linked-list.py | py | 712 | python | en | code | 0 | github-code | 36 |
2182128872 | import logging
import threading
import numpy as np
import pandas as pd
from timeit import default_timer as timer
from datetime import datetime, timedelta, timezone
from time import sleep
import time
import matplotlib.pyplot as mpl
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection i... | 5ymph0en1x/SyDOM | utils/predictor.py | predictor.py | py | 21,887 | python | en | code | 82 | github-code | 36 |
21131384578 | """Django Models for tracking the configuration compliance per feature and device."""
import json
import logging
from deepdiff import DeepDiff
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.module_loading import import_string
from hier_config import Host as HierConfi... | nautobot/nautobot-plugin-golden-config | nautobot_golden_config/models.py | models.py | py | 27,885 | python | en | code | 91 | github-code | 36 |
41613286837 | import socket
if __name__ == '__main__':
# 创建TCP套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置套接字选项
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 绑定 监听
server_socket.bind(('',8080))
server_socket.listen(128)
while True:
cl... | ABDM357/python_summary_knowledge_001 | Day01-15 Python基础课程/Day01-15课程与项目/07 [项目]web服务器:自己动手实现web服务器/03-代码/00-模拟web服务器接收浏览器的HTTP请求.py | 00-模拟web服务器接收浏览器的HTTP请求.py | py | 661 | python | en | code | 0 | github-code | 36 |
33831041355 | def nextSmaller(arr):
# result array
res = [-1] * len(arr)
# stak
stack = []
# traversing from end
for i in range(len(arr)-1, -1, -1):
# current element
curr = arr[i]
# keep popping element from stack untill you're getting a bigger element
while len(stack) and a... | Rohit-2412/DSA | Array/maxAreaRectangle.py | maxAreaRectangle.py | py | 1,577 | python | en | code | 2 | github-code | 36 |
74436410985 | # -*- coding: utf-8 -*-
# Data preparation at one-second level for Ph.D thesis
# @author: Andres L. Suarez-Cetrulo
import glob
import time
import logging
import yaml
import subprocess
import os
import pandas as pd
import numpy as np
import datetime
# Global attributes
SLASH = os.path.sep
EQUIVALENCE = {
's': 1,
... | cetrulin/Quant-Quote-Data-Preprocessing | src/2_testing.py | 2_testing.py | py | 16,897 | python | en | code | 0 | github-code | 36 |
24850285371 | from character import Enemy
from battle import Battle
from system import display_message
class LastCastle:
def __init__(self, player):
self.player = player
self.enemy = Enemy()
self.enemy.define_enemy("last_boss", self.player.stats["level"])
self.battle = Battle(self.player, self.en... | shimeji3207/projects | textrpg/last_castle.py | last_castle.py | py | 941 | python | ja | code | 0 | github-code | 36 |
36992033529 | import os
import sys
from PIL import Image
from scene.cameras import Camera
from typing import NamedTuple
from scene.colmap_loader import read_extrinsics_text, read_intrinsics_text, qvec2rotmat, \
read_extrinsics_binary, read_intrinsics_binary, read_points3D_binary, read_points3D_text
from scene.hyper_loader impor... | hustvl/4DGaussians | scene/dataset_readers.py | dataset_readers.py | py | 23,816 | python | en | code | 995 | github-code | 36 |
3131749916 | #https://open.kattis.com/problems/bela
def dom(x):
values = {"A":11, "K":4, "Q":3, "J":20, "T":10, "9":14}
return(values[x] if x in values else 0)
def rec(x):
values = {"A":11, "K":4, "Q":3, "J":2, "T":10}
return(values[x] if x in values else 0)
info = input().split(" ")
cards = []
score = 0
for i in ra... | MrLuigiBean/Some-Open-Kattis-Problems | Python3/Bela.py | Bela.py | py | 504 | python | en | code | 0 | github-code | 36 |
3540344939 | import requests
from requests.auth import HTTPBasicAuth
import json
from decouple import config
url = "https://climate.jira.com/rest/api/2/issue"
auth = HTTPBasicAuth(
"brandon.hoffman@climate.com",
f"{config('JIRA_API_KEY')}"
)
headers = {
"Accept": "application/json",
"Content-Type": "application... | branhoff/jira-gpt-enhancer | backend/create_issue.py | create_issue.py | py | 811 | python | en | code | 0 | github-code | 36 |
22124651099 | import json
from channels.generic.websocket import AsyncWebsocketConsumer
from channels.db import database_sync_to_async
from .models import Message
from userauth.models import User
from .models import Conversation
class ChatConsumer(AsyncWebsocketConsumer):
def __init__(self, *args, **kwargs):
super().__i... | codynego/ChaCha | chat/consumers.py | consumers.py | py | 3,576 | python | en | code | 1 | github-code | 36 |
74352476903 | # -*- coding: utf-8 -*-
"""
-------------------------------------------------------------------------------
GUFY - Copyright (c) 2019, Fabian Balzer
Distributed under the terms of the GNU General Public License v3.0.
The full license is in the file LICENSE.txt, distributed with this software.
----------------... | Fabian-Balzer/GUFY | GUFY/simgui_modules/checkBoxes.py | checkBoxes.py | py | 8,443 | python | en | code | 0 | github-code | 36 |
73563359464 | import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '/fslhome/lc453/mlip-2/lib')))
from mpi4py import MPI
from ase.db import connect
from ase.optimize import BFGS
from ase.db import connect # api for connecting to the atoms database
import numpy as np
in_dir=".."
prefix=""... | msg-byu/HfNiTi-genetic | get_energy_data.py | get_energy_data.py | py | 678 | python | en | code | 0 | github-code | 36 |
13367936976 | from dotenv import load_dotenv
from os import getenv
from model import load_embeddings_model
from csv import DictReader
from ast import literal_eval
from langchain.schema.document import Document
from langchain.vectorstores import FAISS
def _load_books() -> list:
"""
Load the books from a csv file and organize... | AethersHaven/Bookie | embed.py | embed.py | py | 2,661 | python | en | code | 0 | github-code | 36 |
11543344946 | from flask import Flask, render_template, request,jsonify
from flask_cors import CORS,cross_origin
import requests
from bs4 import BeautifulSoup as bs
from urllib.request import urlopen
import logging
import pymongo
logging.basicConfig(filename="scrapper.log" , level=logging.INFO)
app = Flask(__name__)
@app.route("/"... | nnamanagarwal/data_science_project | new_pw_eng_scrap/app.py | app.py | py | 4,203 | python | en | code | 0 | github-code | 36 |
71186846185 | """
1. Ingresa a https://developer.twitter.com/
2. Accede con tu cuenta de Twitter ó crea una cuenta
3. Busca en la página la forma de solicitar una cuenta para desarrollador
4. Completa la información que se te solicita
5. Crea tu proyecto
6. Copia los tokens de tu proyecto
7. Pega las cr... | xtecuan/CursoCienciaDeDatos | CursoCienciaDeDatos_ejemplos/sesion4/credentials.py | credentials.py | py | 498 | python | es | code | 0 | github-code | 36 |
42578020211 | ''' This module contains functions and classes responsible for
writing solutions into different outputs (files, screen, GUI, etc).
Warning:
if new methods for writing output are added, they MUST
follow the rule: data must be added
sequentially, row after row, column after column.
'''
i... | araith/pyDEA | pyDEA/core/data_processing/write_data.py | write_data.py | py | 30,938 | python | en | code | 38 | github-code | 36 |
73243569705 | #!/usr/bin/python3
"""Unittest module for the Review Class."""
import unittest
from datetime import datetime
import time
from models.review import Review
import re
import json
from models.engine.file_storage import FileStorage
import os
from models import storage
from models.base_model import BaseModel
from tests.test... | olanipekundenis/AirBnB_clone | tests/test_models/test_review.py | test_review.py | py | 1,721 | python | en | code | 0 | github-code | 36 |
1792979964 | import unicurses
import numpy as np
import math
import wave
import struct
import time
stdscr = unicurses.initscr()
unicurses.cbreak()
unicurses.noecho()
unicurses.curs_set(0)
unicurses.keypad(stdscr, True)
LINES, COLS = unicurses.getmaxyx(stdscr)
height = 16
def drawData(data, x, y):
for i in range(len(data)):
... | AaronLieberman/ArduinoTinkering | FFTTest/FFTTest2-win.py | FFTTest2-win.py | py | 2,207 | python | en | code | 0 | github-code | 36 |
24974566125 | #!/usr/bin/python3
"""Defines a class Square that is a sub class of rectangle"""
Rectangle = __import__('9-rectangle').Rectangle
class Square(Rectangle):
"""A square, sub class of rectangle."""
def __init__(self, size):
"""Inintializes a new instance of Square.
Args:
size (int): ... | Ikechukwu-Miracle/alx-higher_level_programming | 0x0A-python-inheritance/11-square.py | 11-square.py | py | 480 | python | en | code | 0 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.