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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
25031594128 | print('-=' * 30)
print('Lojas JOÃO')
print('-=' * 30)
preço = float(input('Preço das compras: '))
print('''FORMAS DE PAGAMENTO
[1] à vista dinheiro/cheque 10% de desconto
[2] à visto no cartão 5% de desconto
[3] em até 2x no cartão é o preço normal
[4] 3x ou mais no cartão: 20% de juros''')
print('-=' * 30)
opção = int... | joaovictoraraujodev/python_estudos | mundo2/desafio44.py | desafio44.py | py | 961 | python | pt | code | 0 | github-code | 36 |
32699799681 | import io
import json
import sys
INDENT = 4 * " "
DEFAULT_NEWRESPARAM = "res"
def toCppType(t):
if isinstance(t, list):
if len(t) == 2:
return "{}<{}>".format(t[0], t[1])
elif len(t) == 3:
return "{}<{}<{}>>".format(t[0], t[1], t[2])
else:
raise Runtime... | daphne-eu/daphne | src/runtime/local/kernels/genKernelInst.py | genKernelInst.py | py | 10,745 | python | en | code | 51 | github-code | 36 |
38966606507 | n = int(input())
for i in range(1, n + 1):
#각 자릿수 합 구하기
a = sum(map(int, str(i)))
num = i + a
if num == n:
print(i)
break
if n == i:
print(0) | leehyeji319/PS-Python | 백준/브루트포스/2231.py | 2231.py | py | 202 | python | ko | code | 0 | github-code | 36 |
23912659039 | from math import pi, cos, sin
import numpy
# Return a list of points representing a circle with radius R, centered at origin and on xz plane.
# With DIVISION points.
# The first point is at (0, 0, R) and go counter-clockwise.
def getCircle(r, division=1800):
p = []
step = 2 * pi / division
for i in xrange(... | leohtkam/invkin-simuator | path.py | path.py | py | 1,500 | python | en | code | 0 | github-code | 36 |
19021910953 | from collections import Iterable
l = isinstance('abc',Iterable)
print(l)
L=list(range(1,11))
print(L)
L2 = [x * x for x in range(1,20)]
print(L2)
L3 = [m + n for m in 'abc' for n in 'hkl']
print(L3)
import os
L4 = [d for d in os.listdir('.')]
print('all dir',L4)
L5 = ['Hello','World',18,'Apple',None]
L6 = [s.lower... | jacena/python3 | iterable.py | iterable.py | py | 484 | python | en | code | 0 | github-code | 36 |
34988790617 | instructions = []
with open('input.txt', 'r') as f:
for line in f.readlines():
instruction, value = line.strip().split(' ')
value = int(value[1:]) if value.startswith('+') else int(value)
instructions.append((instruction, value))
acc = 0
i = 0
mem = set()
while True:
instruction, value... | JeroenMandersloot/aoc2020 | day8/puzzle1.py | puzzle1.py | py | 659 | python | en | code | 0 | github-code | 36 |
506390690 | """
Snapping
"""
def snap_points_to_near_line(lineShp, pointShp, epsg, workGrass,
outPoints, location='overlap_pnts', api='grass',
movesShp=None):
"""
Move points to overlap near line
API's Available:
* grass;
* saga.
"""
... | jasp382/glass | glass/gp/snp.py | snp.py | py | 4,241 | python | en | code | 2 | github-code | 36 |
25412177948 | from ..shared.list_arithmatic import add
from ..shared.digits import to_digits
from itertools import permutations
from ..shared.solver import Solver
def digit_sum(n:int)->int:
return add(to_digits(n))
def digit_sums(biggest: int):
pool = list(range(0,biggest))
for a, b in permutations(pool,2):
po... | bathcat/pyOiler | src/pyoiler/problems/euler056.py | euler056.py | py | 1,033 | python | en | code | 1 | github-code | 36 |
719879844 | from collective.honeypot import _
from collective.honeypot.config import ACCEPTED_LOG_LEVEL
from collective.honeypot.config import DISALLOW_ALL_POSTS
from collective.honeypot.config import EXTRA_PROTECTED_ACTIONS
from collective.honeypot.config import HONEYPOT_FIELD
from collective.honeypot.config import IGNORED_FORM_F... | collective/collective.honeypot | collective/honeypot/utils.py | utils.py | py | 5,278 | python | en | code | 3 | github-code | 36 |
10712753654 | # coding=utf-8
def isNum(n:str)-> int:
sum = 0
for i in n:
sum += int(i)**3
return sum == int(n)
def main():
n = input()
if(isNum(n)):
print("YES")
else:
print("NO")
main() | Dearyyyyy/TCG | data/3920/AC_py/518295.py | 518295.py | py | 228 | python | en | code | 0 | github-code | 36 |
16731276324 | import numpy as np
def update_varSum(idx_new, series, win_size, prevVal=None):
"""
Returns the power sum average based on the blog post from
Subliminal Messages. Use the power sum average to help derive the running
variance.
sources: http://subluminal.wordpress.com/2008/07/31/running-standard-devia... | RichieHakim/basic_neural_processing_modules | bnpm/welford_moving.py | welford_moving.py | py | 3,338 | python | en | code | 3 | github-code | 36 |
10744207821 | import numpy
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.pyplot import figure
img_path = '/home/moby/PycharmProjects/datasets_processing/figures/'
plt.rcParams.update({
'font.family': 'serif',
'font.sans-serif': ['Times'],
'text.latex.preamble':
r'\usepackage[T2A]{fonte... | SergWh/datasets_processing | thesis_plots/gpt_classes.py | gpt_classes.py | py | 1,188 | python | en | code | 0 | github-code | 36 |
21618269201 | from __future__ import absolute_import
import logging
import tempfile
import unittest
from apache_beam.examples.cookbook import group_with_coder
from apache_beam.testing.util import open_shards
# Patch group_with_coder.PlayerCoder.decode(). To test that the PlayerCoder was
# used, we do not strip the prepended 'x:' ... | a0x8o/kafka | sdks/python/apache_beam/examples/cookbook/group_with_coder_test.py | group_with_coder_test.py | py | 2,877 | python | en | code | 59 | github-code | 36 |
72721103783 | from utilities import util
import binascii
import RSA as rsa
# Challenge 40
def broadcast_attack(c1, c2, c3, p1, p2, p3):
_, n1 = p1
_, n2 = p2
_, n3 = p3
c1 = int(binascii.hexlify(c1), 16)
c2 = int(binascii.hexlify(c2), 16)
c3 = int(binascii.hexlify(c3), 16)
x1 = c1 * n2 * n3 * util.modinv(n2 * n3, ... | fortenforge/cryptopals | challenges/RSA_broadcast_attack.py | RSA_broadcast_attack.py | py | 867 | python | en | code | 13 | github-code | 36 |
40294323346 | import time
import random
import lxc
import code
import string
from multiprocessing.pool import ThreadPool
import os
from os.path import join, isfile, exists
import json
LXC_BASE = "tmpl_apach"
MOUNTPOINT = "files"
LXC_IP = "10.10.13.7"
##### GRADER FUNCTIONS
import http.client
ip1 = '127.0.0.1'
ip2 = LXC_IP
... | mabdi/ctf-pylxc | challs/Apache_Man_2/grader.py | grader.py | py | 8,833 | python | en | code | 0 | github-code | 36 |
45923290828 | from SortAlgs import *
import matplotlib.pyplot as plt
import plotly.express as px
import timeit
import random
import numpy as np
N = 10000
X = [random.randint(0, N) for _ in range(N)]
naive_time = timeit.timeit("naive_sort(X, X)", globals=globals(), number=1)
merge_time = timeit.timeit("merge_sort(X, X)", globals=gl... | SchardtS/Coding-Club | 2023_12_18_SortingAlgorithms/Simon/ComplexityVisualization.py | ComplexityVisualization.py | py | 1,087 | python | en | code | 2 | github-code | 36 |
42307368708 | # 3
# 5 1 5
N = int(input())
nums = input().strip().split(' ')
for i in range(len(nums)):
nums[i] = int(nums[i])
def cal(nums):
nums.sort()
mid = len(nums)//2
less, great = nums[:mid],nums[mid:]
return 2*(sum(great)-sum(less))-great[0]-(great[1] if len(nums) & 1 else -less[-1])
print(cal(nums)) | jing-ge/Jing-leetcode | offer/jd/1.py | 1.py | py | 315 | python | en | code | 0 | github-code | 36 |
1636559220 | import sys
import os
import subprocess
import graphviz_gen
from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QLineEdit, QPlainTextEdit, QVBoxLayout
from PySide6.QtCore import QFile, QThread, Slot, Qt
from PySide6.QtUiTools import QUiLoader
from PySide6.QtSvgWidgets import QSvgWidget
class Base(QWidge... | 0x000922/Network-Troubleshooter | main.py | main.py | py | 2,487 | python | en | code | 0 | github-code | 36 |
34373633188 | from django.urls import path
from . import views
from django.urls import include, path, re_path
# /playlist
# /user/<id>
urlpatterns = [
path('index/', views.index, name='index'), # page
re_path('^index/registration/', views.registration),
path('login/', views.login), # page
path('logout/', views.log... | Maxgioman/Python | playlist/urls.py | urls.py | py | 900 | python | en | code | 0 | github-code | 36 |
670179501 | import pandas as pd
import pickle
# leemos el archivo con las respuestas a la encuesta Origen Destino
# este archivo es muy grande para github. No lo subí
encuesta = pd.read_csv("C:/Users/Edgar Trejo/Desktop/tviaje.csv")
# obtenemos las respuestas para viajes que son de la cdmx, del edomex y hgo
# la pregunta 'p5_7_7'... | edtrelo/BioMatematica | Modeling COVID-19 Spreading in the ZMVM/data/src/datos_geo/distritos_a_mun.py | distritos_a_mun.py | py | 1,705 | python | es | code | 0 | github-code | 36 |
38864421405 | # gunicorn/django 服务监听地址、端口
bind = '0.0.0.0:8210'
# gunicorn worker 进程个数,建议为: CPU核心个数 * 2 + 1
workers = 3
# gunicorn worker 类型, 使用异步的event类型IO效率比较高
worker_class = "gevent"
# 日志文件路径
errorlog = "./log/error.log"
accesslog = './log/access.log' #正常时的log路径
loglevel = "info"
import os
import sys
cwd = os.getcwd()
sys.p... | JNan-QQ/CMS | studyFree/gunicorn_conf.py | gunicorn_conf.py | py | 434 | python | en | code | 0 | github-code | 36 |
21822870669 | import os, sys
ruta = __file__
for i in range(2):
ruta = os.path.dirname(ruta) #subir dos niveles en carpetas, es decir sube hasta imp
print("Ruta:", ruta)
sys.path.append(ruta)
#import a.x as x
def y1():
print("y1")
def y2():
print("y2")
x.x1()
if __name__ == "__main__": #con esta condici... | manuelgm92/Learning-Data-Science | otros/imp/b/y.py | y.py | py | 439 | python | es | code | 0 | github-code | 36 |
15639017903 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: anzhang28@163.com
# FileName: qsbk.py
# function: search story from qiushibaike
# date: 2017/01/09
import re
import basictest
class Qsbk(basictest.StaticPage):
def getBriefContent(self):
pginfo = self.getOnelineContent(self.getPageInfo().read())
... | zhangan2040/study | spiders/qsbk.py | qsbk.py | py | 1,863 | python | en | code | 0 | github-code | 36 |
28511585187 | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington
# See opus_core/LICENSE
import os, webbrowser
from time import strftime,localtime
from opus_core.indicator_framework.core.source_data import SourceData
from opus_co... | psrc/urbansim | opus_core/indicator_framework/core/indicator_factory.py | indicator_factory.py | py | 4,651 | python | en | code | 4 | github-code | 36 |
3678250480 | from typing import Any, List, Text
from rasa.nlu.config import RasaNLUModelConfig
from rasa.nlu.tokenizers.tokenizer import Token, Tokenizer
from rasa.nlu.training_data import Message, TrainingData
from rasa.nlu.constants import TEXT_ATTRIBUTE, TOKENS_NAMES, MESSAGE_ATTRIBUTES
from rasa.utils.io import DEFAULT_ENCODI... | msamogh/rasa-frames | rasa/nlu/tokenizers/mitie_tokenizer.py | mitie_tokenizer.py | py | 2,085 | python | en | code | 4 | github-code | 36 |
37803606526 | """
Wrapper Class for the Github Secrets Filler
"""
import os
import sys
import dotenv
import github
from ..GithubEnvironmentSecret import GithubEnvironmentSecret
class Filler:
dotenv_values = None
github_repository = None
environment = None
gh_env_secret = None
def __init__(self, args):
... | ArteGEIE/github-secrets-filler | bin/libraries/filler/Filler.py | Filler.py | py | 2,996 | python | en | code | 0 | github-code | 36 |
34980535013 | '''
Created on 2018年8月30日
@author: huowolf
'''
#===============================================================================
# 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
# 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
#===============================================================================
class Solution:
def twoSum(self, nums, ... | huowolf/leetcode | src/array/twoSum.py | twoSum.py | py | 1,013 | python | zh | code | 0 | github-code | 36 |
70472354663 | '''
Created on Aug 1, 2019
@author: jsaavedr
Reading an image
'''
import pai_io
import matplotlib.pyplot as plt
if __name__ == '__main__':
filename = '../images/gray/lion_gray.jpg'
image = pai_io.imread(filename, as_gray = True)
print('shape: {}'.format(image.shape))
##showing image
plt.imshow (... | Cotorrra/CC5508-Imagenes | Basic Tools/pai_basis/example_1.py | example_1.py | py | 399 | python | en | code | 0 | github-code | 36 |
18215403219 | palavras = ('arroz', 'cachorro', 'bolo', 'amor', 'baixinho', 'cor',
'beleza', 'olhar', 'suavidadee', 'caneta', 'perfeitos',
'vaidade', 'existe', 'bateria', 'porco', 'vaca', 'gatinhos')
for palavra in palavras:
print(f'Na palavra {palavra.upper()} temos: ',end='')
for letra in palavra:
... | jonathanbisp/115-Exercicios-Python | aulas/desafio077.py | desafio077.py | py | 392 | python | pt | code | 1 | github-code | 36 |
10478855527 | from PIL import Image as im
o = im.open('cave.jpg')
# Open two new images of the same size.
n1 = im.new(o.mode,o.size)
n2 = im.new(o.mode,o.size)
# Grab the x and y maximum coords of the original
xmax, ymax = o.size[0], o.size[1]
# Iterate over ever pixel in the image, and decide if the product of the
# coordinates... | nancejk/PythonChallenge | 11.py | 11.py | py | 653 | python | en | code | 1 | github-code | 36 |
13996961200 | from numpy import zeros
from dividexp import db
from dividexp.models import Users, Teams, Trips, Expenses
from math import fabs
from datetime import datetime
class TripManager:
def __init__(self):
self.id = 0
self.users_ids = {}
self.size = 1
self.expenses = []
self.team = ... | veronika-suprunovich/dividexp | dividexp/manager.py | manager.py | py | 8,591 | python | en | code | 2 | github-code | 36 |
25323402636 | import json
import pandas as pd
from django.conf import settings
from django.http.response import JsonResponse
from django_celery_results.models import TaskResult
from rest_framework import mixins, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import NotFound, PermissionDenied
fr... | mateusz28011/ml-api | ml/views.py | views.py | py | 4,070 | python | en | code | 1 | github-code | 36 |
74536701223 | from django.shortcuts import render
from .forms import DataFrameForm
from main.utils import ContractAlternatives
import pandas as pd
from .utils import convert_date_format
# Create your views here.
def homepage(request):
return render(request, 'main/homepage.html')
def calculo_rapido(request):
if request.m... | cmichellbs/sistema | main/views.py | views.py | py | 1,430 | python | en | code | 0 | github-code | 36 |
21141929383 | import socket
import time
from threading import Thread
from cryptography.fernet import Fernet
socket = socket.socket()
socket.bind(('', 9885))
socket.listen(50)
clients = []
try:
key = open("key.txt", "r", encoding="utf-8")
except FileNotFoundError:
key = Fernet.generate_key()
open("key.txt", "w", encodin... | miniusercoder/irc | server.py | server.py | py | 2,119 | python | en | code | 1 | github-code | 36 |
34106559298 | __author__ = 'Shuo Yu'
import pymysql
import glob
import h5py
import numpy as np
def db_connect():
return pymysql.connect(host="127.0.0.1",
user="shuoyu",
passwd="qoowpyep",
db="silverlink",
charset='utf8',... | Platinays/SilverLinkResearch | parse.py | parse.py | py | 4,222 | python | en | code | 0 | github-code | 36 |
74133895143 | from django.urls import path
from . import views
app_name = 'mainapp'
urlpatterns = [
path('',views.mainpage,name='main-page'),
path('book_detail/<int:pk>',views.bookdetailpage,name='book-detail'),
path('author_detail/<int:pk>',views.authordetailpage,name='author-detail'),
path('book_list/',views.book... | Chouaib-Djerdi/Fennec-Bookstore | backend/bookstore/mainapp/urls.py | urls.py | py | 962 | python | en | code | 2 | github-code | 36 |
15891318383 | import json
import asyncio
from aioredis import Channel
from websockets import WebSocketCommonProtocol
from app.queue.pubsub import ConsumerHandler, ProducerHandler
from app.queue.redis import queue_conn_sub, queue_conn_pub
CONNECTED = set()
async def web_socket_chat(_, websocket: WebSocketCommonProtocol):
CON... | Arthur264/music-new.chat | app/websockets.py | websockets.py | py | 1,155 | python | en | code | 0 | github-code | 36 |
38040183892 | import numpy as np
import argparse
import cv2
import colorsys # 提取图片中主要颜色
from PIL import Image # python imaging library,已经是python平台事实上的图像处理标准库
import numpy as np
from skimage import draw
image = cv2.imread('F:\\maomi\\0.png')
def color_Handle():
color = [
# 黄色范围~这个是我自己试验的范围,可根据实际情况自行调整~注意... | MrLeedom/colorRecognition | test1/test4.py | test4.py | py | 4,153 | python | en | code | 0 | github-code | 36 |
17096777387 | #aula 4 Programa para verificar se uma string digitada corresponde ao contrário (palíndromo)
#sopapos, radar, revivier, osso, ovo, anilina, arara
texto = input("Digite uma frase: ")
dif = False
for pos in range(len(texto)//2):
if texto[pos] != texto[-1-pos]:
dif = True
break
if dif:
print("A fr... | pedroivoadv/Pucrs | logicaprogramacao01/aula05/exercicioal20.py | exercicioal20.py | py | 400 | python | pt | code | 0 | github-code | 36 |
3512694431 | import discord
import responses
import pymongo
import datetime
client = pymongo.MongoClient("mongodb+srv://discordroll:check@discordroll.ej9jzg7.mongodb.net/?retryWrites=true&w=majority")
db = client.users
print(db)
async def send_message(message, user_message, is_private):
try:
time = datetime.datetime... | Tadjikistan/Proekt_2023_VG | Discord_bot/bot.py | bot.py | py | 2,257 | python | en | code | 0 | github-code | 36 |
1219461364 | m = -1
x = 0
y=0
for i in range(9):
n = list(map(int, input().split()))
if max(n) > m:
m = max(n)
x= i+1
y = n.index(m)+1
print(m)
print(x, y) | arittung/Coding_Test | Baekjoon/2566.py | 2566.py | py | 188 | python | en | code | 0 | github-code | 36 |
28068849012 | # 거리두기 확인하기
# https://programmers.co.kr/learn/courses/30/lessons/81302
from collections import deque
def bfs(place, x, y):
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
queue = deque()
queue.append((x, y))
# 큐가 빌 때까지 반복
while queue:
x, y = queue.popleft()
# 현재 위치에서 4가지 방향으로의 위치 확인
... | hwanginbeom/algorithm_study | 2.algorithm_test/21.07.25/21.07.25_wooseok.py | 21.07.25_wooseok.py | py | 2,440 | python | ko | code | 3 | github-code | 36 |
43061119996 | import socket
import sys
import functions
import time
# Create a TCP/IP socket
loop = True
while(loop):
sock = socket.create_connection(('localhost', 10000))
try:
# Send data
print("Ingrese sus valores 'p','g' y 'a'... ")
print("--------------------------... | RyuketsuKun/Laboratorio_5_Evaluado | cliente.py | cliente.py | py | 4,543 | python | es | code | 0 | github-code | 36 |
8786955819 | from .fund import Fund
import glob
import re
import csv
import datetime
class FundLog:
@classmethod
def list_ids(self):
result = []
for i in glob.glob("fundlog-*.csv"):
m = re.match('fundlog-(\S+)\.csv', i)
result.append(m.groups()[0])
return result
def __i... | t-bucchi/accagg | accagg/fundlog.py | fundlog.py | py | 1,641 | python | en | code | 0 | github-code | 36 |
11751989424 | import logging
import jwt
from django.conf import settings
from django.contrib.auth import login
from django.views.generic import TemplateView
from expirybot.apps.blacklist.models import EmailAddress
from ..forms import MonitorEmailAddressForm
from ..models import EmailAddressOwnershipProof, UserProfile
from ..uti... | fawkesley/expirybot-web | expirybot/apps/users/views/add_email_address_view.py | add_email_address_view.py | py | 4,351 | python | en | code | 1 | github-code | 36 |
1155657087 | from django.http import HttpResponseNotFound, JsonResponse
from django.shortcuts import get_object_or_404, render, redirect
from django.contrib.auth.decorators import login_required
from django.views.generic import CreateView, UpdateView, DeleteView, ListView, DetailView
from datetime import datetime,timedelta
from dja... | AndoniWadgymar/greenbin | greenbin/trash/views.py | views.py | py | 6,306 | python | en | code | 0 | github-code | 36 |
35387155314 | #!/usr/bin/env python3
from sys import stderr, exit
import random
import math
from time import monotonic
from TALinputs import TALinput
from multilanguage import Env, Lang, TALcolors
import vertex_cover_lib as vcl
# METADATA OF THIS TAL_SERVICE:
args_list = [
('goal',str),
('code_lang',str),
('lang',str... | romeorizzi/TALight | example_problems/tutorial/vertex_cover/services/eval_approx_weighted_vc_driver.py | eval_approx_weighted_vc_driver.py | py | 3,249 | python | en | code | 11 | github-code | 36 |
854328737 | #!/usr/bin/env python
"""Groot Object Protection Report for python"""
from pyhesity import *
from fnmatch import fnmatch
import psycopg2
from datetime import datetime
import codecs
import smtplib
from email.mime.multipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import Encoders
# command lin... | bseltz-cohesity/scripts | groot/python/grootSoxReport/grootSoxReport.py | grootSoxReport.py | py | 5,406 | python | en | code | 85 | github-code | 36 |
26358980006 | #!/usr/bin/env python
import base64
import logging
import os
import sys
import toml
from prometheus_client import CollectorRegistry, Gauge, push_to_gateway
from prometheus_client.exposition import basic_auth_handler
from git_metrics import SaasGitMetrics, SaasConfigReadError, GitCommandError
from gql import GqlApi
i... | app-sre/push-saas-metrics | push-saas-metrics.py | push-saas-metrics.py | py | 4,496 | python | en | code | 0 | github-code | 36 |
13909904792 | """Module with lagrangian decomposition methods."""
# Python packages
import gurobipy
import logging as log
import pandas as pd
import copy
# Package modules
from firedecomp.classes import solution
from firedecomp import config
from firedecomp.AL import ARPP
# Subproblem ---------------------------------------------... | jorgerodriguezveiga/firedecomp | firedecomp/AL/ADPP.py | ADPP.py | py | 13,091 | python | en | code | 0 | github-code | 36 |
993280779 | #! /usr/bin/python3
import logging
from binascii import hexlify
from struct import unpack
from time import strftime
from collections import OrderedDict
from . import commands_helpers, attributes_helpers
from .parameters import *
from .conversions import zgt_encode, zgt_decode, zgt_checksum, zgt_decode_struct
from .resp... | elric91/ZiGate | pyzigate/interface.py | interface.py | py | 28,853 | python | en | code | 18 | github-code | 36 |
75022097384 | """
Переделать скрипт из задания 5.1b таким образом, чтобы, при запросе параметра, которого
нет в словаре устройства, отображалось сообщение „Такого параметра нет“.
Если выбран существующий параметр, вывести информацию о соответствующем параметре,
указанного устройства.
"""
london_co = {
'r1': {
'location': '21 New ... | kevgenius/MyPython | pyneng_3.0/Task5.1c_request of information.py | Task5.1c_request of information.py | py | 1,225 | python | ru | code | 0 | github-code | 36 |
71700208104 |
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('fitness', views.fitness, name='fitness'),
path('barbells', views.barbells, name='barbells'),
path('dumbbells', views.dumbbells, name='dumbbells'),
path('cart', views.cart, name='cart'),
pa... | fravila08/fitness_store | ecom_app/urls.py | urls.py | py | 366 | python | en | code | 0 | github-code | 36 |
26383114619 | from typing import Protocol
import numpy as np
from sklearn.metrics import f1_score, accuracy_score, balanced_accuracy_score
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.svm import LinearSVC
from sklearn.dummy import DummyC... | jarsba/gradu | scripts/base_clf.py | base_clf.py | py | 2,198 | python | en | code | 0 | github-code | 36 |
10189099421 | import pytest
from auroraapi.interpret import Interpret
class TestInterpret(object):
def test_create_no_arguments(self):
with pytest.raises(TypeError):
Interpret()
def test_create_wrong_type(self):
with pytest.raises(TypeError):
Interpret("test")
def test_create(self):
d = { "intent": "test", "entit... | auroraapi/aurora-python | tests/test_interpret.py | test_interpret.py | py | 646 | python | en | code | 4 | github-code | 36 |
16789541655 | #Online Gradient Descent
import numpy as np
from random import *
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#Formatting content.......
print("Reading data.............")
def read_file(filename):
with open(filename) as f:
f.readline()
f.readline()
f.readline()
... | ManishaNatarajan/Online-Learning | log_reg.py | log_reg.py | py | 9,140 | python | en | code | 0 | github-code | 36 |
74752000104 | import unittest
from unittest.mock import patch, MagicMock, call, DEFAULT
from requests.exceptions import ConnectionError
from lib.marcParse import (
parseMARC,
transformMARC,
extractAgentValue,
extractHoldingsLinks,
extractSubjects,
extractSubfieldValue,
parseHoldingURI
)
from lib.dataMode... | NYPL/sfr-ingest-pipeline | lambda/sfr-doab-reader/tests/test_marc.py | test_marc.py | py | 10,255 | python | en | code | 1 | github-code | 36 |
8606037106 | from bson.objectid import ObjectId
from bson.json_util import dumps
from json import loads
from mongoengine import Document
from serializers.common_serializer import default
from common.common_module import parse_pages
from common.mongodb_module import build_lookup_filter
def get_all_generic(model: any, mongo_filter... | carlos-herrera-cervantes/todo-api-python-sanic | source/repositories/base_repository.py | base_repository.py | py | 2,688 | python | en | code | 1 | github-code | 36 |
74962642022 | import tensorflow as tf
import numpy as np
import keras
import librosa
import os
# Indexes for the model:
# 0: Benjamin
# 1: Stromberg
# 2: Julia
# 3: Margaret
# 4: Nelson
model_path = "E:\\Python_Projects\\StrombergAI\\src\\speaker_recognition\\model\\stromberg-recognizer-model.keras"
def audio_to_fft(audio):
# ... | TheItCrOw/Ask-Stromberg | src/speaker_recognition/test.py | test.py | py | 3,461 | python | en | code | 0 | github-code | 36 |
73326550503 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Python爬虫初探
from urllib import request
import chardet #检测html编码方式的模块
if __name__ == '__main__':
response = request.urlopen("http://www.baidu.com")
html = response.read()
htmlCharset = chardet.detect(html) #会得到一个字典 类似{'encoding': 'utf-8', 'confidence': 0.9... | BobXGY/PythonStudy | python_weather_spider/pc0.py | pc0.py | py | 482 | python | en | code | 0 | github-code | 36 |
16217747254 | from jinja2 import Environment, FileSystemLoader
from os import walk
from shutil import copytree, rmtree, ignore_patterns
try: rmtree("./build")
except Exception as e: print("Creating build folder", e, "Occured")
copytree("./", "./build", ignore=ignore_patterns('*.py', "templates", "*.git"))
ENV = Environment(loade... | Just-Moh-it/assignment-nerd | compiler.py | compiler.py | py | 773 | python | en | code | 4 | github-code | 36 |
11277772009 | n=float(input("enter the number of new louves ordered"))
o=float(input("enter the number of old louves ordered"))
r=185
re="{:.2f}".format(r)
print("the regular price for the new loaf is ",re)
he=185*n
hm="{:.2f}".format(he)
print("the total price for the new loaf is ", hm)
h=185*0.6
oh=h*o
ohh="{:.2f}".forma... | DundeShini/CSA0838-PYTHON-PROGRAMMING- | bakery cells.py | bakery cells.py | py | 450 | python | en | code | 1 | github-code | 36 |
24912437981 | # -*- coding: utf-8 -*-
__author__ = 'neo'
import json
import tornado.web
from common.mongo_utils import *
from common.api_tagdef import *
from common.iot_msg import *
from OpenAPI_server.http_utils import http_client_pool, http_client_post
from common.eventno import *
from common.iot_procdef import *
from OpenAPI_se... | ennismar/python | OpenAPI/OpenAPI_server/camera_proc.py | camera_proc.py | py | 15,655 | python | en | code | 0 | github-code | 36 |
35515269259 | import argparse
import matplotlib.pyplot as plt
import numpy as np
from textwrap import wrap
def moving_avg_filter(data_arr, w):
data_arr_cumsum = np.cumsum(data_arr)
data_arr_cumsum[w:] = (data_arr_cumsum[w:] - data_arr_cumsum[:-w])
data_arr_filtered = data_arr_cumsum[w-1:]/w
return data_arr_filt... | onermustafaumit/MLNM | gland_segmentation/mask_rcnn/plot_valid_metrics.py | plot_valid_metrics.py | py | 2,635 | python | en | code | 4 | github-code | 36 |
33635193286 | import sys
import pypyodbc
from PyQt5.QtWidgets import *#QApplication, QMainWindow,QDialog,QMessageBox
from PyQt5 import uic
from PyQt5.QtGui import QIcon
import time
import random
from tkinter import *
from PyQt5.QtCore import pyqtSlot
class Elim(QDialog):
def __init__(self):
# lista=[["Dt1234","Jose","... | whitoutpieces/Unknow | Creatabla.py | Creatabla.py | py | 2,633 | python | en | code | 0 | github-code | 36 |
69875187303 | M = int(input())
d = {
1: True,
2: False,
3: False
}
for i in range(M):
x, y = map(int, input().split())
d[x], d[y] = d[y], d[x]
for k, v in d.items():
if v: print(k)
| dntlakfn/boj | 1547.py | 1547.py | py | 195 | python | en | code | 0 | github-code | 36 |
16226121324 | #!/usr/bin/env python
# encoding: utf-8
#import datetime
import tweet_easy.tweet_easy as te
# Input variables
start_date = "2018-08-01"
#Twitter API credentials
tweet_api = te.tweet_easy(filename_credentials = '/Users/ana/Documents/Twitter/twitter-credentials.json')
controlIdFolder = "controlFolder/"
outputFolder ... | abatanero/twitter-btc | 00_download_tweets.py | 00_download_tweets.py | py | 661 | python | en | code | 0 | github-code | 36 |
8452080503 |
def count_palindromic_substrings(s):
n = len(s)
def is_palindrome(t):
return t == t[::-1]
count = 0
for i in range(n):
for j in range(i+1):
substr = s[j:i+1]
if is_palindrome(substr):
count += 1
return count | kashyapa/coding-problems | google/educative/dp/8_count_palindromic_substrings.py | 8_count_palindromic_substrings.py | py | 287 | python | en | code | 0 | github-code | 36 |
15131197168 | # Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution:
def findRightInterval(self, intervals: List[Interval]) -> List[int]:
start = {}
end = {}
for i in range(len(intervals)): #딕셔너리로 받아놓기(key: 값, vl... | EnteLee/practice_algorithm | leetcode/436_find_right_interval/Find_Right_Interval_khy.py | Find_Right_Interval_khy.py | py | 2,043 | python | ko | code | 0 | github-code | 36 |
14605662471 | import unittest
import pandas as pd
from arcs.summarize_results import per_query_ndcg, stats
class SummarizeResultsTest(unittest.TestCase):
def setUp(self):
test_queries = ["2006", "2015", "291 erskine", "311", "330153"]
test_domains = ["data.kcmo.org", "data.detroitmi.gov", "datacatalog.cookcoun... | socrata/arcs | tests/test_summarize_results.py | test_summarize_results.py | py | 1,569 | python | en | code | 1 | github-code | 36 |
29875713843 | # Copyright (c) 2023 Dawn
# Operations Research Calculator is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
# http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" B... | Dawn-of-Time/Operations-Research-Calculator | UI/Animation/indexAnimation.py | indexAnimation.py | py | 3,489 | python | en | code | 0 | github-code | 36 |
27102810736 | # -*- coding: utf-8 -*-
from django import forms
from django.utils.translation import ugettext_lazy as _
from .models import Pedido
class PedidoForm(forms.ModelForm):
class Meta:
model = Pedido
fields = ('descripcion', 'fecha', 'proveedor', 'usuario','total',)
labels = {
'descri... | IvanVilla1585/RefrescosChupiFlum | ChupiFlum/pedido/forms.py | forms.py | py | 1,012 | python | es | code | 1 | github-code | 36 |
14812101209 | import numpy as np
import matplotlib.pyplot as plt
import os
n = 100
A = 10
x = np.linspace(0, np.pi, 100) # задаём отрезок
fx = (-np.sin(x)*((np.sin((x**2)/np.pi))**(2*A)))
# создание папки для текстовика
try:
os.mkdir('results')
except OSError:
pass
complete_file = os.path.join('results', 'task_01_307B_... | AlexPogudin/wor1 | Pogudin_16_PY.py | Pogudin_16_PY.py | py | 784 | python | ru | code | 0 | github-code | 36 |
36687194652 | from osgeo import gdal, gdal_array
import numpy as np
# "Before" image
im1 = "D:\\Python36\\testdata\\before.tif"
# "After" image
im2 = "D:\\Python36\\testdata\\after.tif"
#Output image name
output = "D:\\Python36\\testdata\\change.tif"
# Load before and after into arrays
ar1 = gdal_array.LoadFile(im1).astyp... | Jinunmeng/Python-ImageProcess | change_detection.py | change_detection.py | py | 1,207 | python | en | code | 0 | github-code | 36 |
42830439112 | import requests
from requests import utils
session = requests.session()
number_list = []
for i in range(1,6):
headers = {
'Host':'match.yuanrenxue.com',
'Connection':'keep-alive',
'Content-Length':'0',
'Pragma':'no-cache',
'Cache-Control':'no-cache',
'sec-ch-ua':'" ... | zqtz/yuanrenxue | exam03/exam03.py | exam03.py | py | 1,631 | python | en | code | 0 | github-code | 36 |
12381823391 | from captcha.image import ImageCaptcha
import os
import random
import string
import asyncio
import re
import datetime
import discord
from discord.ext import commands
def randomStr(n=5):
randlst = [random.choice(string.digits + string.ascii_lowercase + string.ascii_uppercase) for i in range(n)]
return ''.join... | PriestessSakuraka/discord.py-captcha-bot | bot.py | bot.py | py | 3,460 | python | en | code | 0 | github-code | 36 |
45138682316 | from flask import Flask, send_from_directory
from flask_sqlalchemy import SQLAlchemy
import os
app = Flask(__name__, static_folder='./build/static')
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
'''
db = SQLAlchemy(app)
class User(db.Model):
__tablename__ = 'user'
token_id = db.Column(db.String(255), prim... | hb275/DPP_Agency | app.py | app.py | py | 2,006 | python | en | code | 0 | github-code | 36 |
16265787967 | class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
W = 9
SW = 3
row = lambda r: [board[r][c] for c in range(W)]
col = lambda c: [board[r][c] for r in range(W)]
sqr = lambda r,c: [board[r*SW+sr][c*SW+sc] for sr,sc in product(range(SW),range(SW))]
... | alexbowe/LeetCode | 0036-valid-sudoku/0036-valid-sudoku.py | 0036-valid-sudoku.py | py | 701 | python | en | code | 5 | github-code | 36 |
26304669003 | import sys
import pandas as pd
from sqlalchemy import create_engine
import copy
def split_categories_columns(df):
row = df['categories'][0]
categories_column_names = row.split(';')
categories_column_names= [category.split('-')[0] for category in categories_column_names]
rename_dict = {}
for inde... | chrapkus/disaster_repository_project | scripts/process_data.py | process_data.py | py | 3,803 | python | en | code | 0 | github-code | 36 |
30395088282 | import journal
def print_header():
print('-'*20)
print('Journal App'.center(20))
print('-'*20)
def run_event_loop():
print('What would you like to do with your journal?')
cmd = 'EMPTY'
journal_name = input("Enter the name of the journal you'd like to edit > ")
journal_data = journal.load... | ianauger/journal | program.py | program.py | py | 1,114 | python | en | code | 0 | github-code | 36 |
13651328548 | # Для этого упражнения вам необходимо будет написать программу, которая будет запрашивать у пользователя
# расстояние в футах. После этого она должна будет пересчитать это число в дюймы, ярды и мили и вывести на экран.
# Коэффициенты для пересчета единиц вы без труда найдете в интернете.
FOOT_TO_INCH = 12
FOOT_TO_YARD... | Wladislavich/Wlad_study | Python excercises/chapter 1 - variables/ex015 Distance.py | ex015 Distance.py | py | 971 | python | ru | code | 0 | github-code | 36 |
42925904616 | import logging
import os
import shutil
from typing import List
import numpy as np
import pandas as pd
import pysam
from hmnfusion import bed as ibed
from hmnfusion import graph, region
# Helper functions
def cigar2position(cigars: List[List[int]], start: int) -> dict:
"""Construct from a cigar and a position, a ... | guillaume-gricourt/HmnFusion | src/hmnfusion/quantification.py | quantification.py | py | 8,947 | python | en | code | 0 | github-code | 36 |
38628061872 | #!/usr/bin/env python
import os
from posixpath import split
import pygame
import numpy as np
from eden.core import Eden
import platform
if platform.system() == 'Windows':
import ctypes
ctypes.windll.user32.SetProcessDPIAware()
from pygame.transform import scale as surf_scale
from typing import List, Tuple
asse... | DouPiChen/Eden-v0 | python/eden/interactive.py | interactive.py | py | 23,947 | python | en | code | 0 | github-code | 36 |
20402768654 | #!/usr/bin/python3
"""
Adds two integers.
Args:
a (int or float): The first number to add.
b (int or float): The second number to add. Defaults to 98.
Returns:
int: The sum of a and b.
Raises:
TypeError: If a or b are not integers or floats.
"""
def add_integer(a, b=... | Jubrilabdulazeez/alu-higher_level_programming | python-test_driven_development/0-add_integer.py | 0-add_integer.py | py | 642 | python | en | code | 0 | github-code | 36 |
27770016752 | import numpy as np
from sklearn.impute import SimpleImputer
X=[[np.nan,2,3],[4,np.nan,6],[10,np.nan,9]]
imputer = SimpleImputer(missing_values=np.nan,strategy='mean')
# allowed_strategies = ["mean", "median", "most_frequent", "constant"]
xx= imputer.fit_transform(X)
print(xx)
from sklearn.impute import KNNImputer
X =... | kshsky/PycharmProjects | ml-case/01-集装箱危险品瞒报预测/fillna_from_knn.py | fillna_from_knn.py | py | 459 | python | en | code | 0 | github-code | 36 |
3640824514 | import math
from typing import List
import flair
import torch
import torch.nn as nn
import torch.nn.functional as F
from .data import tokenize, tokenize_batch
from .two_hot_encoding import NGramsEmbedding
class RNNModel(nn.Module):
"""Container module with an encoder, a recurrent module, and a decoder."""
... | HallerPatrick/two_hot_encoding | multihot/model.py | model.py | py | 17,797 | python | en | code | 6 | github-code | 36 |
19800848708 | def wavefront(n):
sq = [[1,1,1,2,2,3]]
if n <= 6:
return sq[0][n - 1]
else:
q = n // 6
r = n % 6
for i in range(q):
sq.append([sq[i][1]+sq[i][5]])
for j in range(4):
sq[i + 1].append(sq[i + 1][j] + sq[i][j + 2])
sq[i... | chelsh/baekjoon | Solved/9461_wavefrontSequence.py | 9461_wavefrontSequence.py | py | 532 | python | en | code | 1 | github-code | 36 |
17795545171 | # Definition for a binary tree node.
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
ans = []
stack = []
current = root
... | fastso/learning-python | leetcode_cn/solved/pg_94.py | pg_94.py | py | 578 | python | en | code | 0 | github-code | 36 |
495364467 | import contextlib
import datetime
import errno
import inspect
import multiprocessing
import os
import re
import signal
import subprocess
import sys
import tempfile
import threading
from collections import namedtuple
from enum import Enum
import yaml
from six.moves import configparser
from dagster import check
from da... | helloworld/continuous-dagster | deploy/dagster_modules/dagster/dagster/utils/__init__.py | __init__.py | py | 9,956 | python | en | code | 2 | github-code | 36 |
71304383463 | #Desafio 20
#Débora Janini
salario= float(input())
if salario >=0 and salario <=400:
percent= 0.15
elif salario <=800:
percent= 0.12
elif salario <=1200:
percent= 0.10
elif salario <=2000:
percent= 0.07
else:
percent= (0.04)
nsalario = salario + (percent*sala... | deborajanini/desafios-python | desafio20.py | desafio20.py | py | 485 | python | en | code | 0 | github-code | 36 |
42324347897 | """
使用模型性能评价指标
"""
from deepepochs import Trainer, rename, metrics as dm
import torch
from torch import nn
from torch.nn import functional as F
from torchvision.datasets import MNIST
from torchvision import transforms
from torch.utils.data import DataLoader, random_split
# datasets
data_dir = './datasets'
transform =... | hitlic/deepepochs | examples/3-metrics.py | 3-metrics.py | py | 2,620 | python | en | code | 0 | github-code | 36 |
29889532379 | # coding: utf-8
import requests
import json
def fetch_weather(location):
result = requests.get(
'https://api.seniverse.com/v3/weather/now.json',
params={
'key': 'glgqeom9bcm7swqq',
'location': location,
'language': 'zh-Hans',
'unit': 'c'
},
... | AIHackerTest/Leon-Huang_Py101-004 | Chap2/project/weather-api-mvp.py | weather-api-mvp.py | py | 803 | python | en | code | 0 | github-code | 36 |
12427518361 | from setuptools import setup, find_packages
pkg_vars = {}
setup(
name='croneval',
description='cron schedule expression evaluator',
author='Selçuk Karakayalı',
author_email='skarakayali@gmail.com',
maintainer='Selçuk Karakayalı',
url='http://github.com/karakays/croneval/',
packages=find_... | karakays/croneval | setup.py | setup.py | py | 575 | python | en | code | 0 | github-code | 36 |
37979061712 | import csv
import random
import sqlite3
import sys
from PyQt5 import QtWidgets, QtGui
from PyQt5.QtWidgets import QWidget, QApplication, QTextEdit, QScrollArea, QPushButton
from StatistikWidjet_form import Ui_Statistic
import datetime as dt
from CONST import NOTES_DB, STATISTIC_DB, ARITHMETIC_DB, FUNNY_TEXTS
class... | samsadlonka/yandex_lyceum_qt_project | Statistic.py | Statistic.py | py | 5,184 | python | en | code | 0 | github-code | 36 |
16776613582 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Note: To use the 'upload' functionality of this file, you must:
# $ pip install twine
import io
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with io.open(os.path.join(here, 'README.md'), encoding='utf-8') a... | Inokinoki/django-multiplefilefield | setup.py | setup.py | py | 1,482 | python | en | code | 1 | github-code | 36 |
10094338951 | import sys
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
from middleware.connection import GatherSocket, DispatcherSocket
from middleware.connection import ReplicationSocket, ProducerSocket
import middleware.constants as const
#
# format(msg) -> home_team home_points away_p... | PatricioIribarneCatella/nba-statistics | src/joiners/summary.py | summary.py | py | 1,919 | python | en | code | 0 | github-code | 36 |
17794549871 | n, k = map(int, input().split())
s = list(input())
s_c = []
left = 0
right = 0
for i in range(n - 1):
if s[i] == s[i + 1]:
right = i + 1
else:
s_c.append(''.join(s[left:right + 1]))
i += 1
left = i
right = i
s_c.append(''.join(s[left:right + 1]))
s_c_len = len(s_c)
cc ... | fastso/learning-python | atcoder/contest/solved/abc140_d.py | abc140_d.py | py | 708 | python | en | code | 0 | github-code | 36 |
26739483197 | from youtube_dl import YoutubeDL
import re
yt_regex = re.compile(r"^((?:https?:)?\/\/)?((?:www|m)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w\-]+\?v=|embed\/|v\/)?)([\w\-]+)(\S+)?$")
ytdlopts = {
'outtmpl': './downloads/%(id)s-%(title)s.%(ext)s',
'restrictfilenames': True,
'noplaylist': False,
'nocheckcer... | ArpitKhandelwal-developer/Yt-Download | main.py | main.py | py | 1,649 | python | en | code | 1 | github-code | 36 |
74260921062 | import numpy as np
from nuscenes import NuScenes
from typing import Dict, List, Set
from pathlib import Path
import pickle
from tqdm import tqdm
import json
import copy
import argparse
from easydict import EasyDict
import yaml
from nuscenes.eval.detection.config import config_factory
from ..dataset import DatasetTemp... | quan-dao/practical-collab-perception | pcdet/datasets/v2x_sim/v2x_sim_dataset_rsu.py | v2x_sim_dataset_rsu.py | py | 13,285 | python | en | code | 5 | github-code | 36 |
4589972020 | from constants import contract_name
from src.dao.skill_dao import skill_name
from src.handlers.base_handler import BaseHandler
from src.exceptions.skill_exceptions import CannotDeleteSkill
from src.models.skill import Skill
class SkillHandler(BaseHandler):
def __init__(self, mongo):
super().__init__(mongo... | markbekhet/PI4-main-project-migration-test | frontfacingserver/src/handlers/skill_handler.py | skill_handler.py | py | 1,229 | 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.