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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
71129782185 | from urllib.request import urlopen
import random
import datetime
from Initialize import sqlitewrite, sqliteread, settings, sqliteFetchAll, getmoderators
commands_BotCommands = {
"!ping": ('bot.ping', 'cmdarguments', 'user'),
"!uptime": ('bot.uptime', 'cmdarguments', 'user'),
"!roll": ('bot.roll', 'cmdargum... | gcfrxbots/rxbot | RxBot/Bot.py | Bot.py | py | 6,155 | python | en | code | 6 | github-code | 36 |
24591814026 | s = "hgfygtfytfuybvj iughiuhfinbk jbnio"
target = "u"
indexes = []
for i, symbol in enumerate(s):
if symbol == target:
indexes.append(i)
# print(i)
# break
# else:
# print("symbol was not found")
if indexes:
print(indexes)
else:
print("symbol was not found")
count = {}
for i... | MikitaTsiarentsyeu/Md-PT1-69-23 | Lessons/lesson 16.07/practice.py | practice.py | py | 511 | python | en | code | 0 | github-code | 36 |
12244843214 | # BINARY SEARCH
def search(lst,p):
l = 0
u = len(lst)-1
while l<=u:
m = (l+u)//2
if lst[m]==p:
return True,m+1
else:
if lst[m]<p: l = m+1
if lst[m]>p: u = m-1
return False,'none'
lst = [int(x) for x in input('enter list\n').... | NighatRaza/Data-Structures-Using-Python | binarysearch.py | binarysearch.py | py | 572 | python | en | code | 0 | github-code | 36 |
43319728592 | #Number 1
def fizzbuzz(n):
number = 1
while number <= n:
if number % 3 == 0:
print ('fizz')
elif number % 5 == 0:
print ('buzz')
elif number % 3 == 0 and number % 5 == 0:
print ('fizzbuzz')
else:
print (number)
number = number + 1
#Number 2
def pal(n):
m = n
whil... | aannhvo/CS61A | study.py | study.py | py | 24,997 | python | en | code | 0 | github-code | 36 |
24569667329 | import tensorflow as tf
import cv2
import time
import argparse
import posenet
from joblib import dump, load
import pandas as pd
column_names = ['Eye_L_x', 'Eye_L_y', 'Eye_R_x', 'Eye_R_y', 'Hip_L_x', 'Hip_L_y',
'Knee_L_x', 'Knee_L_y', 'Ankle_L_x', 'Ankle_L_y', 'Toes_L_x',
'Toes_L_y', 'ToesEnd_L_x', 'Toes... | rahul-islam/posenet-python | webcam_demo.py | webcam_demo.py | py | 5,792 | python | en | code | null | github-code | 36 |
12486442970 | """
Objects and Classes
Check your solution: https://judge.softuni.bg/Contests/Practice/Index/950#4
SUPyF Objects and Classes - 05. Optimized Banking System
Problem:
Create a class BankAccount which has a Name (string), Bank (string) and Balance (decimal).
You will receive several input lines, containing info... | SimeonTsvetanov/Coding-Lessons | SoftUni Lessons/Python Development/Python Fundamentals June 2019/Problems and Files/07. OBJECT AND CLASSES/05. Optimized Banking System.py | 05. Optimized Banking System.py | py | 2,123 | python | en | code | 9 | github-code | 36 |
22807184796 | # Makes some radial plots of gas density and temperature.
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
x_field = 'Radiuspc'
y_fields = ['Density', 'Temperature']
weight_field = 'CellMass'
x_min = 1.0e-1
x_max = 2.0e2
fns = sys.argv[1:]
plot_folde... | enzo-project/enzo-dev | run/Hydro/Hydro-3D/RotatingSphere/profile_script.py | profile_script.py | py | 936 | python | en | code | 72 | github-code | 36 |
74253274663 | """ Module containing implementation of evolutionary computation algorithms, such as:
- basic Evolutionary Algorithm
- Genetic Programming
- Evolutionary Strategies
for solving the cases (see 'cases' module).
"""
import random
import copy
from typing import Tuple, Union, Dict, Any, List
from dea... | JiriPavela/perun-optimization-evolution | src/evolution/ec.py | ec.py | py | 19,236 | python | en | code | 0 | github-code | 36 |
16722490719 | import sys
if __name__ == "__main__":
fname = sys.argv[1]
with open(fname, 'r') as file:
number = 0
for l in file:
num_str = l.strip().split(' ')
number += int(num_str[0])
print("Total point number: %d", number + 20) | Enigmatisms/LiDARSim2D | py/point_num.py | point_num.py | py | 273 | python | en | code | 23 | github-code | 36 |
74476200743 |
def encontrar_chave(dicionario, valor_procurado):
for chave, valor in dicionario.items():
if valor == valor_procurado:
return chave
month = int(input())
months_dict = {
'January': 1,
'February': 2,
'March': 3,
'April': 4,
'May': 5,
'June': 6,
'July': 7,... | luis-sardinha/desafio-python-DIO | desafio-twitter/desafio_mes.py | desafio_mes.py | py | 513 | python | es | code | 0 | github-code | 36 |
35436780435 | import urllib.request
from bs4 import BeautifulSoup
url = 'http://127.0.0.1:8000/'
res = urllib.request.urlopen(url)
data = res.read()
html = data.decode("utf-8")
soup = BeautifulSoup(html, 'html.parser')
print(soup)
h1 = soup.html.body.h1
print('h1:', h1.string) | SeungYeopB/bigdata | crawling1/sample01.py | sample01.py | py | 266 | python | en | code | 0 | github-code | 36 |
24623808952 | import matplotlib.pyplot as plt
from generator import Generator
import torch
from discriminator import Discriminator
import torch.nn as nn
import utils
import torch.utils.data as data
G = Generator()
input_z = torch.randn(1, 20)
input_z = input_z.view(input_z.size(0), input_z.size(1), 1, 1)
fake_image = G(input_z)
D ... | TOnodera/pytorch-advanced | gan/main.py | main.py | py | 1,442 | python | en | code | 0 | github-code | 36 |
20665600389 | from ast import arg
from brownie import (
accounts,
config,
network
)
import eth_utils
LOCAL_BLOCKCHAIN_ENVIRONMENTS=["development", "ganache-local"]
FORKED_LOCAL_ENVIRONMENTS=["mainnet-fork-dev"]
OPENSEA_URL = "https://testnets.opensea.io/assets/{}/{}"
def get_account_v2(index=None, id=None):
if (in... | ckt22/upgradeable-contract-template | scripts/helpful_scripts.py | helpful_scripts.py | py | 2,352 | python | en | code | 0 | github-code | 36 |
33403799483 | import os.path
import bitarray
# Класс создан для хранения предыдущего блока и ксора переданного с предудущим для последующего сохранения
class CBCEncrypter:
def __init__(self, init_key: bitarray.bitarray) -> None:
super().__init__()
# Ключ инициализации
self.key = init_key
self.p... | remoppou/CTF | crypto/Feistel-song/solution/solve.py | solve.py | py | 8,778 | python | ru | code | 0 | github-code | 36 |
4130598030 | #By Alexandros Panagiotakopoulos - alexandrospanag.github.io
class Lifecycle:
x = 0
name = ''
def __init__(self, nam): #constructor example
self.name = nam
print(self.name,'constructed')
def party(self): #objects constructed counter example
self.x = self.x + 1
... | AlexandrosPanag/My_Python_Projects | Object-Oriented Programming (OOP)/Object Lifecycle/Object Lifecycle.py | Object Lifecycle.py | py | 554 | python | en | code | 1 | github-code | 36 |
30478421727 | import pprint
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
import tensorflow_ranking as tfr
import tensorflow_recommenders as tfrs
import collections
def _create_feature_dict():
"""Helper function for creating an empty feature dict for defaultdict."""
return {"embeddings": [], "r... | colinfritz-ai/GAP_Recommender_System_MVP | GAP_Recommender_System_Utilities.py | GAP_Recommender_System_Utilities.py | py | 3,307 | python | en | code | 0 | github-code | 36 |
26444005522 | #定义地瓜类
class SweetPotato:
#定义初始化方法
def __init__(self):
self.cookedLevel=0
self.cookedString="生的"
self.condiments=[]
def __str__(self):
msg = "您的地瓜已经处于 " + self.cookedString + "的状态"
# if len(self.condiments)>0:
# msg = msg + " ,添加的佐料为:"
# for te... | sjr125697/PythonBasicDemo | 烤地瓜.py | 烤地瓜.py | py | 2,262 | python | en | code | 1 | github-code | 36 |
14300436310 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 20 20:16:15 2021
@author: RISHBANS
"""
import pandas as pd
mnist_data = pd.read_csv("mnist-train.csv")
features = mnist_data.columns[1:]
X = mnist_data[features]
y = mnist_data['label']
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y... | edyoda/ML-with-Rishi | mnist_nn.py | mnist_nn.py | py | 1,205 | python | en | code | 4 | github-code | 36 |
30160636048 | import pytest
from django.urls import reverse
from mixer.backend.django import mixer
pytestmark = [pytest.mark.django_db]
def test_get_user_list(api_client):
"""Получение списка пользователей."""
url = reverse('users')
response = api_client.get(url)
assert response.status_code == 200
def test_new_... | X-Viktor/FLStudy | users/tests/api/test_users.py | test_users.py | py | 627 | python | en | code | 1 | github-code | 36 |
35685627050 | """ Classes for basic manipulation of GraphNet """
import numpy as np
import tensorflow as tf
def _copy_any_ds(val):
"""
Copy semantics for different datatypes accepted.
This affects what happens when copying nodes, edges and graphs.
In order to trace gradients,
and defines a consistent interfa... | mylonasc/tf_gnns | tf_gnns/datastructures.py | datastructures.py | py | 18,665 | python | en | code | 9 | github-code | 36 |
3592662594 | from fastapi import APIRouter, Depends, HTTPException, UploadFile
from sqlalchemy.orm import Session
from typing import List
from db.database import get_db
from security.auth import oauth2_scheme, get_current_user
from . import schemas, crud
router = APIRouter()
@router.post("/events/add")
async def add_event(tex... | ostrekodowanie/Synapsis | backend/api/events/routes.py | routes.py | py | 1,070 | python | en | code | 0 | github-code | 36 |
27158727859 | """
CartoonPhoto
Yotam Levit
Date: 13/11/2020
"""
import cv2
def read_image(image_name):
return cv2.imread(image_name)
def get_edged(image):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
grey = cv2.medianBlur(gray, 5)
edges = cv2.adaptiveThreshold(gray, 255,
cv2.AD... | yotamlevit/CartoonPhoto | Convertor.py | Convertor.py | py | 961 | python | en | code | 0 | github-code | 36 |
9019137787 | from chessboard import *
import pygame
import sys
def redraw(screen, board, pieces, square_size, WHITE, GREY):
# Draw the chess board
for row in range(8):
for col in range(8):
if (row + col) % 2 == 0:
color = WHITE
else:
color = GREY
p... | Miesjell/chess | main.py | main.py | py | 6,010 | python | en | code | 0 | github-code | 36 |
8403047178 | from typing import Any, List, Dict
class Config:
"""
Contains parsed yaml config
"""
def __init__(self, config_yaml: Any) -> None:
# self.query: Dict[str, TableConfig] = {}
self._parse_conf(config_yaml)
def _parse_conf(self, conf_yaml: Any) -> None:
"""
Parses ... | parkroyal/Data_Loader | configlayer/models.py | models.py | py | 2,975 | python | en | code | 0 | github-code | 36 |
8135943468 | from accounts.serializers import UserSerializer
from django.shortcuts import redirect
from django.conf import settings
from django.contrib.auth import get_user_model
from rest_framework.generics import CreateAPIView
from rest_framework.views import APIView
from rest_framework import serializers, status
from rest_frame... | QuocHung52/course-pool-react | backend/accounts/views.py | views.py | py | 3,658 | python | en | code | 0 | github-code | 36 |
24401520806 | from tkinter import *
import Mediator
from Model.BoardModel import BoardModel
from View.BoardView import BoardView
from Controller.GemController import GemController
from random import randint
from Handler import Handler
class BoardController:
"""
The main class that is responsible for the board.... | vladbochok/university-tasks | c1s2/labwork-4/Controller/BoardController.py | BoardController.py | py | 2,928 | python | en | code | 3 | github-code | 36 |
20270208049 | """
Module containing the constants needed for the numerical solution of the laplace equation.
"""
# DIMENSIONS OF THE PLATES [CM]
l_y = 5 # Side 1
l_z = 10 # Side 2
d = 1 # Separation in between plates
# DIMENSIONS OF THE BOX [CM]
L_X = 10
L_Y = 15
L_Z = 30
# POTENTIALS [V]
V_1 = 1... | nmonrio/laplace-eq-sim | params.py | params.py | py | 500 | python | en | code | 0 | github-code | 36 |
28704089727 | #!/usr/bin/env python3
import os
import sys
from pathlib import Path
import logging
from pdf_tool import PDF_Tool
from form import *
from PySide2.QtWidgets import QApplication, QMainWindow
from PySide2.QtCore import Qt, QObject, QEvent
from PySide2.QtGui import QIcon, QMouseEvent
os.environ["QT_AUTO_SCREEN_SCALE_FAC... | GschoesserPhilipp/Pdf-Tool-GUI | mainwindow.py | mainwindow.py | py | 10,229 | python | en | code | 0 | github-code | 36 |
33236543359 | from il_utils import *
def make_cfg(insFile,varsFile,printIns=False):
cfg={}
#load all instructions
instructions,varmap=load_il(insFile,varsFile)
gen_ins=('Plus','Minus','Times','Greater','And','Or','GreaterEq','Equal','Not','Move')
check_gen=lambda i,f: True if (f(i)!='null' and op(i) in... | jorgeypcb/ImpCodeGenerator | riscv/cfg.py | cfg.py | py | 1,858 | python | en | code | 0 | github-code | 36 |
490651592 | # import tcod
from random import randint
from game_messages import Message
class BasicMonster:
def take_turn(self, target, game_map, entities):
results = []
monster = self.owner
if monster.distance_to(target) >= 2:
# monster.move_astar(target, entities, game_map)
m... | Denrur/map_as_dict | ai.py | ai.py | py | 1,543 | python | en | code | 0 | github-code | 36 |
41310446545 | from nltk import CFG
from nltk import ChartParser # parse_cfg, ChartParser
from random import choice
import re
from enum import Enum, auto
from argparse import ArgumentParser
from os import listdir
from os.path import isfile, join
import os
this_dir = os.path.dirname(os.path.abspath(__file__))
name_segment_... | Mimic-Tools/name-generation | src/name_generation/generate.py | generate.py | py | 12,855 | python | en | code | 12 | github-code | 36 |
24389835444 | import re as _re
from argparse import *
from .. import path as _path
_ArgumentParser = ArgumentParser
_Action = Action
# Add some simple wrappers to make it easier to specify shell-completion
# behaviors.
def _add_complete(argument, complete):
if complete is not None:
argument.complete = complete
e... | jimporter/bfg9000 | bfg9000/arguments/parser.py | parser.py | py | 4,385 | python | en | code | 73 | github-code | 36 |
34181491873 | import json
import logging
import traceback
import warnings
from datetime import datetime
from collections import OrderedDict
from typing import Dict, Callable, Optional, Union, List, Any, Type, Sequence
from qiskit.providers.backend import BackendV1 as Backend
from qiskit.providers.provider import ProviderV1 as Provi... | Qiskit/qiskit-ibm-runtime | qiskit_ibm_runtime/qiskit_runtime_service.py | qiskit_runtime_service.py | py | 47,557 | python | en | code | 106 | github-code | 36 |
5603106879 | import discord
from utils.auth import AuthManager
class Account(discord.Cog):
@discord.slash_command(name="register", description="Register using your discord username")
async def register(self, ctx):
AuthManager.registerGuild(ctx.author)
AuthManager.registerUser(ctx.author)
await ctx.... | liang799/rivenDealer | cogs/account.py | account.py | py | 517 | python | en | code | 1 | github-code | 36 |
10739040334 | from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
from QLed import QLed
class Box(QGroupBox):
instances = []
def __init__(self, name, opcID='opcID', horizontal_spacing=10, width=100):
#self.setTitle(name)
super().__init__(name)
self.instances.append(self)
self.opcName=name
mainLayou... | ValdsteiN/metabolon-gui | components/widgets/box.py | box.py | py | 3,168 | python | en | code | null | github-code | 36 |
30569661147 | """
Привет! ID успешной посылки: 54853357
_____________________________________
Задача:
Гоша реализовал структуру данных Дек, максимальный размер которого определяется заданным числом. Методы push_back(x),
push_front(x), pop_back(), pop_front() работали корректно. Но, если в деке было много элементов, программа работал... | fenixguard/yandex_algorithms | sprint_2/final_tasks/deque.py | deque.py | py | 9,249 | python | ru | code | 2 | github-code | 36 |
1942587161 | # 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 generateTrees(self, n: int) -> List[TreeNode]:
def dfs(start: int,end: int) -> List[TreeNode]:
... | hellojukay/leetcode-cn | src/unique-binary-search-trees-ii.py | unique-binary-search-trees-ii.py | py | 879 | python | en | code | 3 | github-code | 36 |
20422534772 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="webull",
version="0.6.1",
author="ted chou",
description="The unofficial python interface for the WeBull API",
license='MIT',
author_email="ted.chou12@gmail.com",
long_description=... | tedchou12/webull | setup.py | setup.py | py | 1,036 | python | en | code | 576 | github-code | 36 |
14231634112 | #!/usr/bin/env python3
import fire
import logging
import os, sys, traceback
from IsoNet.util.dict2attr import Arg,check_parse,idx2list
from fire import core
from IsoNet.util.metadata import MetaData,Label,Item
class ISONET:
"""
ISONET: Train on tomograms and restore missing-wedge\n
for detail description, ... | IsoNet-cryoET/IsoNet | bin/isonet.py | isonet.py | py | 26,881 | python | en | code | 49 | github-code | 36 |
9627005158 | import numpy as np
import pandas as pd
from nltk.tokenize import RegexpTokenizer
from nltk.corpus import stopwords
from PyQt5 import QtGui
from PyQt5.QtWidgets import *
import sys
from PIL import Image
from wordCloud.WC import Ui_MainWindow
from wordcloud import WordCloud
from wordcloud import ImageColorGenerator... | LeeDong-Min/WordCloud | text_mining(moon_and_trump).py | text_mining(moon_and_trump).py | py | 5,583 | python | en | code | 0 | github-code | 36 |
1080065395 | from django.contrib import admin
from django.urls import path
from form1 import views
urlpatterns = [
path('form1', views.index,name='index'),
path('form2', views.form2, name='Supervisor'),
path('', views.login_view, name='home'),
path('signup', views.signup_view, name='signup'),
path('menu', views... | prajwalgh/QuantumGIS-SIH-PH | mainbody/form1/urls.py | urls.py | py | 1,079 | python | en | code | 0 | github-code | 36 |
22136785531 | import os
import time
import json
import torch
import random
import warnings
import torchvision
import numpy as np
import pandas as pd
import pathlib
from utils import *
from data import HumanDataset
from data import process_df
from data import process_submission_leakdata_full
from data import process_loss_weight
from... | felixchen9099/kaggle_human_protein | my_utils/wrong_classification.py | wrong_classification.py | py | 6,274 | python | en | code | 31 | github-code | 36 |
4999987358 | import asyncio
import json
import random
import re
import requests
from discord import Intents
from discord import Colour
from discord import Embed
from discord.ext import commands
from discord.utils import get
from environment_variables import (
DISCORD,
REDDIT,
OPTION_FLAGS
)
from links import (
hu... | Haskili/Thanatos | main.py | main.py | py | 17,397 | python | en | code | 1 | github-code | 36 |
18561686919 | from typing import ForwardRef
import random
def get_reversed_array(arr):
start = 0
end = len(arr) - 1
while start < end:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
numbers = random.sample(range(10), 10)
print(numbers)
get_reversed_array(numbers)
print(numbe... | prithivirajmurugan/Notes | Algorithm_DataStructures/reverse_array.py | reverse_array.py | py | 324 | python | en | code | 0 | github-code | 36 |
32805054000 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import svm
import time
data = pd.read_csv('wdbc.data')
# data.info()
# data.columns
# replace 'M' and 'B' with 1 and 0
data['diagnosis'] = data['diagnosis'].map({'M':1,'B':0})
print (data['diagnosis'])
# dataset[1] = dataset[1].map({'M... | Siyuan-gwu/Machine-Learning-SVM-Diagnostic | venv/SVM.py | SVM.py | py | 2,386 | python | en | code | 1 | github-code | 36 |
38990098370 | from coleccion_vehiculos import ColeccionVehiculos
from interfaz_lista import ILista
from clase_nuevo import Nuevo
from clase_usado import Usado
import unittest
class TestLista(unittest.TestCase):
__lista= object
def setUp(self):
self.__lista= ILista(ColeccionVehiculos())
v= Us... | Nicolino-c137/Ejercicios-Unidad-3-POO | Ejercicio 9/clase_test.py | clase_test.py | py | 2,201 | python | pt | code | 0 | github-code | 36 |
22355060265 | import re
from collections import ChainMap
from os import environ
from pathlib import Path
from subprocess import run
import pytest
import yaml
here = Path(__file__).absolute().parent
tests_dir = here.parent
root = tests_dir.parent
# Need to be in root for docker context
tmp_dockerfile = Path(root / "Dockerfile.mlrun... | mlrun/mlrun | tests/integration/test_notebooks.py | test_notebooks.py | py | 3,076 | python | en | code | 1,129 | github-code | 36 |
31521305202 | class Solution(object):
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
i2,i3,i5=0,0,0
nums=[1]
for _ in xrange(n-1):
u2,u3,u5=nums[i2]*2,nums[i3]*3,nums[i5]*5
nums.append(min(u2,u3,u5))
if u2==nums[-1]:
... | szhu3210/LeetCode_Solutions | LC/264.py | 264.py | py | 473 | python | en | code | 3 | github-code | 36 |
20638178622 | from tkinter import *
from tkinter.messagebox import *
root=Tk()
h,w=root.winfo_screenheight(),root.winfo_screenwidth()
root.geometry('%dx%d+0+0'%(w,h))
def ope():
root.destroy()
import operator
def newb():
root.destroy()
import busdetails
def newr():
root.destroy()
import newroute
... | aviraljain19/Python-Bus-Booking-Project | addbus.py | addbus.py | py | 1,153 | python | en | code | 0 | github-code | 36 |
30467454597 | # Given the running logs of n functions that are executed in a nonpreemptive single threaded CPU, find the exclusive time of these functions.
#
# Each function has a unique id, start from 0 to n-1. A function may be called recursively or by another function.
#
# A log is a string has this format : function_id:start_or_... | dundunmao/LeetCode2019 | 636. Exclusive Time of Functions.py | 636. Exclusive Time of Functions.py | py | 6,078 | python | en | code | 0 | github-code | 36 |
74470689064 | import os
import datetime
import glob
import urllib.request
import tqdm
import gzip
import pandas as pd
import re
import utils
import random
from time import gmtime, strftime
from multiprocessing import Process
config = __import__('0_config')
def clean_row(row):
return row.decode('utf-8', 'ignore').strip()
def ... | Diego999/Risk-Analysis-using-Topic-Models-on-Annual-Reports | 1_download_data.py | 1_download_data.py | py | 8,603 | python | en | code | 6 | github-code | 36 |
16758722392 | class Spreader(object):
def __init__(self, blockpool, spread):
blockpool_iter = iter(blockpool)
self.feeders = [Feeder(blockpool_iter) for _ in range(spread)]
self.current = 0
def __iter__(self):
return self
def next(self):
next = None
while next is None:
... | taavi/job_spreader | spreader1.py | spreader1.py | py | 1,027 | python | en | code | 5 | github-code | 36 |
2722536523 | class Solution:
def totalFruit(self, f: List[int]) -> int:
# sliding window
n = len(f)
res, l = float('-inf'), 0
basket = collections.defaultdict(int)
for r in range(n):
f_tpy = f[r]
basket[f_tpy] += 1
if len(basket) <= 2:
... | ZhengLiangliang1996/Leetcode_ML_Daily | contest/weekcontest102/fruitintoBaskets.py | fruitintoBaskets.py | py | 587 | python | en | code | 1 | github-code | 36 |
7737901543 | from django.contrib import admin
from django.urls import include, path
from drf_yasg import openapi
from drf_yasg.views import get_schema_view
from rest_framework import permissions
schema_view = get_schema_view(
openapi.Info(
title="Wallet API",
default_version='v1',
description="Applicati... | sheirand/Wallet | core/urls.py | urls.py | py | 743 | python | en | code | 0 | github-code | 36 |
42576586601 | """" Detecção de Relógio """
import cv2
classificador = cv2.CascadeClassifier('cascades\\relogios.xml')
imagem = cv2.imread('outros\\relogio2.jpg')
imagemcinsa = cv2.cvtColor(imagem, cv2.COLOR_BGR2GRAY)
detectado = classificador.detectMultiScale(imagemcinsa, scaleFactor= 1.01, minSize=(10,10), minNeighbors=10)
fo... | alans96/PythonProject | Computer Vision/1 Detecção de Faces com Python e OpenCV/6 exe.py | 6 exe.py | py | 459 | python | pt | code | 0 | github-code | 36 |
35652531980 | cache = []
answer = []
match = ""
dic = ""
lenMatch = 0
lenDic = 0
def wildCard(x, y):
global match, dic, lenMatch, lenDic
if cache[x][y] != -1:
return cache[x][y]
elif x == lenMatch-1 and y == lenDic-1:
if match[x] == '*' or match[x] == '?' or match[x] == dic[y]:
return True
... | 0nandon/Algorithms_Practice | algospot/Dynamic programming/WILDCARD.py | WILDCARD.py | py | 1,365 | python | en | code | 0 | github-code | 36 |
40536503890 | import requests
import json
import os
import _G
from datetime import datetime
import utils
PREV_NEWS_FILE = '.mtd_prevnews.json'
NEWS_URL = os.getenv('MTD_NEWS_URL')
WEBHOOK_URL = os.getenv('MTD_WEBHOOK_URL')
MTD_NEWS_TAG = {
1: 'MAINTENANCE',
2: 'UPDATE',
3: 'GACHA',
4: 'EVENT',
5: 'CAMPAIGN',
6: 'BU... | ken1882/RD_Terminator_3k | module/mtd_news.py | mtd_news.py | py | 3,622 | python | en | code | 0 | github-code | 36 |
11580789914 | import re
import chatterbot
from chatterbot.trainers import ListTrainer
from chatterbot import ChatBot
import logging
logger = logging.getLogger()
logger.setLevel(logging.ERROR)
f = open('E:\\ProjectWork\\ImranV.1.0\\dataset.txt','r')
train_data = []
for line in f:
m = re.search('(Q:|A:)?(.+)', line)
... | AakashMaheedar1998/ChatBot | Chatbot2.py | Chatbot2.py | py | 1,320 | python | en | code | 0 | github-code | 36 |
2946357970 | import heapq,copy,collections
from typing import List,Optional
from collections import deque
class ListNode:
def __init__(self, val = 0, next = None):
self.val = val
self.next = next
class Solution:
#排序链表:给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
def sortList(self, head: Optional[ListNode]) -... | gpj10054211/guoDeveloper | listnode.py | listnode.py | py | 3,590 | python | en | code | 0 | github-code | 36 |
12476621690 | #example 21 generating specific pattern"
'''
*
**
***
****
*****
'''
i=1
j=1
while i<=5:
j=1
# if (i==3):
# continue
# pass
while j<=i:
print("*",end="")
j+=1
print("")
i+=1
i=2
j=2
while i<=5:
j=5
while j>=i:
print("*",end="")
j-=... | Mahnoorahmed928/exercixes_practice_python | specific_pattern2.py | specific_pattern2.py | py | 354 | python | en | code | 0 | github-code | 36 |
16154335818 |
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.core.validators import EmailValidator
from django.conf import settings
from django.core.mail import EmailMessage
from django.template.loader import get_template
from crispy_forms.helper import FormHelper
from crispy_forms.la... | langcog/web-cdi | webcdi/cdi_forms/forms/contact_form.py | contact_form.py | py | 2,511 | python | en | code | 7 | github-code | 36 |
43284653684 | import setuptools
from pathlib import Path
with open("README.md", "r") as file:
long_description = file.read()
with open("requirements.txt") as file:
REQUIREMENTS = file.read().split("\n")
setuptools.setup(
name="port_env",
version="0.0.3",
author="Moist-Cat",
author_email="moistanonpy@gm... | Moist-Cat/port_env | setup.py | setup.py | py | 898 | python | en | code | 0 | github-code | 36 |
20832781197 | from pocket_coffea.utils.configurator import Configurator
from pocket_coffea.lib.cut_definition import Cut
from pocket_coffea.lib.cut_functions import get_nObj_min, get_HLTsel, get_nBtagEq
from pocket_coffea.parameters.cuts import passthrough
from pocket_coffea.parameters.histograms import *
from pocket_coffea.paramete... | ryanm124/AnalysisConfigs | configs/ttHbb/example_config.py | example_config.py | py | 6,758 | python | en | code | null | github-code | 36 |
30148633270 | import logging
import time
from datetime import datetime
import pytz
from flask import Flask
from flask import json
from github import Github
import commands
import envvariables
from sendToRegression import bucket, administrative_issue, close
logging.basicConfig(level=logging.INFO)
logger = logging.get... | peterkungl/bucketservice | FlaskRest.py | FlaskRest.py | py | 1,635 | python | en | code | 0 | github-code | 36 |
70992284585 | import json, hashlib, hmac, requests
def json_encode(data):
return json.dumps(data, separators=(',', ':'), sort_keys=True)
def sign(data, secret):
j = json_encode(data)
print('Signing payload: ' + j)
h = hmac.new(secret, msg=j.encode(), digestmod=hashlib.sha256)
return h.hexdigest()
cl... | YamatoWestern/investment-bot | bitkub_helpers/bitkub_caller.py | bitkub_caller.py | py | 2,601 | python | en | code | 0 | github-code | 36 |
5310951357 |
def gen_ol():
for o in range(16):
mask = 8
line = []
for bit in range(4, 8):
inv = '' if mask & o else '~'
line.append(f'{inv}o[{bit}]')
mask >>= 1
print(f' wire ol{o:x} = ' + ' & '.join(line) + ';')
def gen_ou():
for o in range(8):
... | msiddalingaiah/Sigma | Verilog/statemachine/gen.py | gen.py | py | 1,240 | python | en | code | 0 | github-code | 36 |
41386874756 | arr = []
flash_counter = 0
step_counter = 0
with open('input.txt') as f:
for i in f:
arr.append([[int(e), False] for e in i.strip()])
def stage2(array, pos=(0, 0)):
global flash_counter
x, y = pos
if array[y][x][1]:
array[y][x][0] += 1
return
elif array[y][x][0] > 9:
... | Oskar-V/advent-of-code-2021 | 11/solution.py | solution.py | py | 1,249 | python | en | code | 0 | github-code | 36 |
6752387766 | # -*- coding: utf-8 -*-
from PyQt5.QtWidgets import QDialog
from PyQt5.QtGui import QDoubleValidator
from PyQt5.QtCore import pyqtSlot, QDate
from warehouse.views.editregtuff import Ui_Dialog
from supplyer.controllers.supplyercontroller import SupplyerController
from stuff.controllers.stuffcontroller import StuffCon... | zxcvbnmz0x/gmpsystem | warehouse/modules/editregstuffmodule.py | editregstuffmodule.py | py | 10,777 | python | en | code | 0 | github-code | 36 |
40795182425 | import asyncio
from concurrent.futures import ThreadPoolExecutor
import nest_asyncio
from discord import Message, File
from ImageGenerator import ImageGenerator
from wiezenlibrary.Game import Game
_executor = ThreadPoolExecutor(10)
nest_asyncio.apply()
class DiscordWiezen(Game):
def __init__(self, bot, parent):... | FreekDS/De-Grote-Wiezen-Bot | bot/DiscordWiezen.py | DiscordWiezen.py | py | 1,751 | python | en | code | 1 | github-code | 36 |
41484161294 | from random import *
from Boat import Boat
from State import States
boatlist = []
for i in range(2):
boat = Boat(randint(1, 6), randint(1, 6))
print(boat.x, boat.y)
if i > 0:
for ent in boatlist:
if boat == ent:
boat = Boat(randint(1, 6), randint(1, 6))
b... | xStagg/bataille_navale | bataille-navale.py | bataille-navale.py | py | 1,004 | python | en | code | 0 | github-code | 36 |
18306677513 | import asyncio
from loguru import logger
from mipa.ext.commands import Bot
from mipac import (
Note,
NotificationFollowRequest,
LiteUser,
ClientManager,
NotificationFollow,
)
from catline.adapters import QueueStorageJSONAdapter, QueueStorageRedisAdapter
from catline.queue import IFQueueStorageAdapte... | TeamBlackCrystal/akari | main.py | main.py | py | 2,637 | python | en | code | 2 | github-code | 36 |
24778042796 | """
From https://brian2.readthedocs.io/en/stable/resources/tutorials/3-intro-to-brian-simulations.html
An experiment to inject current into a neuron and change the amplitude randomly every 10 ms. Model that using a Hodgkin-Huxley type neuron.
"""
from brian2 import *
import matplotlib.pyplot as plt
start_scope()
# Pa... | seankmartin/NeuroModelling | hodgkin_huxley.py | hodgkin_huxley.py | py | 1,776 | python | en | code | 0 | github-code | 36 |
13492120891 | def read_msh(file, flag_plot):
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
#custom functions
from read_gmsh_V1 import read_gmsh
from elarea import elarea
#%% Create a structure for the output and assign
class structtype():
... | aydinu1/UA-fem | fem_util/read_msh.py | read_msh.py | py | 3,122 | python | en | code | 0 | github-code | 36 |
37749838738 | # coding=utf-8
from nuntium.models import OutboundMessage
from mailit.management.commands.handleemail import AnswerForManageCommand
from global_test_case import GlobalTestCase as TestCase
from mailit.bin.handleemail import EmailHandler
class ParsingMailsWithAttachments(TestCase):
def setUp(self):
super(Pa... | ciudadanointeligente/write-it | mailit/tests/email_parser/email_with_attachments_parser_tests.py | email_with_attachments_parser_tests.py | py | 1,576 | python | en | code | 38 | github-code | 36 |
70177547624 | import re
if __name__ == '__main__':
string = input('Please enter string')
regexQuery = input('Please enter regex query')
try:
p = re.compile(regexQuery)
if p.match(string) is not None:
print(p.match(string))
else:
print('Returns nothing')
except Excep... | krishna-kumar456/Code-Every-Single-Day | solutions/regexquery.py | regexquery.py | py | 353 | python | en | code | 0 | github-code | 36 |
16147236974 | from typing import List
from app.movements.base import Special
from app.movements.constants import Attacks
from app.movements.utils import replace_values_string
from app.settings import BASSIC_ATTACK_ENERGY, PLAYER_ENERGY
class Fighter:
def __init__(self, name, specials:List[Special]) -> None:
self.name = ... | FranciscoAczayacatl/GameRPG | app/fighters/fighter.py | fighter.py | py | 1,201 | python | en | code | 0 | github-code | 36 |
19262571802 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from datetime import datetime, timedelta
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.worker_result import WorkerResult
from pokemongo_bot import inventory
from pokemongo_bot.item_list import Item
... | PokemonGoF/PokemonGo-Bot | pokemongo_bot/cell_workers/heal_pokemon.py | heal_pokemon.py | py | 11,496 | python | en | code | 3,815 | github-code | 36 |
1889249844 | '''
Created on 08.02.2016.
@author: Lazar
'''
def static_link_procesor(object):
classesString = "";
if not object.classes is None:
for x in object.classes.htmlClasses:
if hasattr(x, 'value'):
classesString += " " + x.key + "=\"" + x.value + "\"";
else:
... | lazer-nikolic/GenAn | src/concepts/static_link.py | static_link.py | py | 798 | python | en | code | 2 | github-code | 36 |
17883182675 | from PySide2.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QSpacerItem, QSizePolicy, QPushButton
from PySide2.QtCore import QSize, QCoreApplication
class PMReportWidget(QWidget):
def __init__(self):
super().__init__()
_translate = QCoreApplication.translate
self.setObjectName("tab_re... | pyminer/pyminer | pyminer/lib/ui/widgets/reportwidget.py | reportwidget.py | py | 1,899 | python | en | code | 77 | github-code | 36 |
3101135100 | class Node(object):
def __init__(self, data):
self.data = data
self.next = None
def length(node):
length = 0
if node is None:
return length
while node is not None:
length += 1
node = node.next
return length
def count(node,data):
count = 0
if node is None:
... | lennystudy/LeetCode | python/LinkedLists.py | LinkedLists.py | py | 499 | python | en | code | 0 | github-code | 36 |
29431099884 | def search_visitor(check_name):
with open("방명록.txt","r",encoding="UTF-8") as file:
visitor = file.read()
if visitor.find(name) == -1:
# if name in visitor:
return False
return True
name = input('이름을 입력하세요 ( 예 : 홍길동 ) : ')
is_visit = search_visitor(name)
print(is_v... | hyunjaebong/NewDataScience | PythonBasic/chapter08/추가문제/6 search_visito.py | 6 search_visito.py | py | 770 | python | ko | code | 1 | github-code | 36 |
39780727033 | import os
import sys
import numpy as np
import pickle
from matplotlib import pyplot as plt
from tqdm import tqdm
ZOOMIN_BUFFER = 1.0
def compute_epoch(result):
return result['epoch'] + result['step_within_epoch'] / result['epoch_length']
def compute_avg_acc(result, standard_or_own_domain):
d = result['zerosh... | kjmillerCURIS/vislang-domain-exploration | clip_finetuning_plot_utils.py | clip_finetuning_plot_utils.py | py | 3,093 | python | en | code | 0 | github-code | 36 |
36324286850 | import json
import smtplib, ssl
import os
from email.message import EmailMessage
import db_functions
from datetime import datetime
## Helper functions Start
def elicit_slot(session_attributes, intent_name, slots, slot_to_elicit, message):
return {
'sessionAttributes': session_attributes,
'dialog... | anilreddy864/BBot | Lex_Code/lambda_function.py | lambda_function.py | py | 4,994 | python | en | code | 0 | github-code | 36 |
75076600744 | import os
import time
import json
"""
This Script is used to gather all the data from running all the combinations of inputs to ./main
It will then write the output to a file called "data.txt" which can be processed and changed
into json format using processData.py in the reports file.
"""
data_json = {}
testAmount = ... | DaveR27/Game-of-Life | DataGathering/GatherData.py | GatherData.py | py | 1,945 | python | en | code | 0 | github-code | 36 |
12633123289 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
# load libraries
import numpy as np
import scipy.sparse as sp
import cplex as cp
# In[4]:
def mixed_integer_linear_programming(direction, A, senses, b, c, l, u, types):
# create an empty optimization problem
prob = cp.Cplex()
# add decision variables to... | berdogan20/Operations-Research-Problems | TheCoinDistributionProblem/Solution.py | Solution.py | py | 2,514 | python | en | code | 0 | github-code | 36 |
17702834387 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 1 19:59:15 2023
@author: rockerzega
"""
from clases import SimpleRNN, STData, RNN
from torch.utils.data import DataLoader
from funciones import fit, generador, RSME, predict, plot_series
# preparacion de la data simulada
n_steps = 50
series = gen... | rockerzega/rnn-ejemplo | src/rnn-lib.py | rnn-lib.py | py | 1,606 | python | en | code | 0 | github-code | 36 |
20948647501 | import numpy as np
from sklearn.metrics import confusion_matrix
import settings
def evaluate_conf_mat(conf_mat):
ignore_label = settings.IGNORE_LABEL
# omit ignore label row and column from confusion matrix
if ignore_label >= 0 and ignore_label < settings.NUM_CLASSES:
row_omitted = np.delete(... | ElhamGhelichkhan/semiseggan | metric.py | metric.py | py | 950 | python | en | code | 0 | github-code | 36 |
16146047995 | # report 1 (my way)
# report headings
print(f"ACCOUNT NO CUSTOMER NAME PHONE NO")
# intitialize counters and accumulators
cust_counter = 0
# open file
f = open("Customers.dat", "r")
# process each line in file
for line in f:
line_split = line.split(", ")
cust_num = line_split[0].strip()
cust_... | sweetboymusik/Python | Lesson 33/reports.py | reports.py | py | 761 | python | en | code | 0 | github-code | 36 |
42425916848 | import os
from dotenv import load_dotenv
DEFAULT_GUNICORN_WORKERS = 4
DEFAULT_CONFIG_PATH = ".env"
ACCESS_TOKEN_EXPIRE_MINUTES = 30 # 30 minutes
REFRESH_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7 # 7 days
ALGORITHM = "HS256"
load_dotenv(DEFAULT_CONFIG_PATH)
JWT_SECRET_KEY = os.environ["JWT_SECRET_KEY"]
JWT_REFRESH_SECRET... | IslomK/family_budget | family_budget/core/const.py | const.py | py | 364 | python | en | code | 3 | github-code | 36 |
20427901161 | # Written by P. Xydi, Feb 2022
######################################
# Import libraries
######################################
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.cm as cm
color_1 = cm.get_cmap("Set2")(2) # set blue
color_2 = cm.get_cmap("S... | pxydi/Named-Entity-Recognition | src/tools.py | tools.py | py | 6,287 | python | en | code | 0 | github-code | 36 |
27177310215 | #region libraries
import cv2
import numpy as np
#endregion
#region process
def process(img_path,template_path): # This Function takes the path and name of basic image and template image
img_bgr = cv2.imread(img_path) # read the image by opencv(cv2)
img_gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY) # convert... | RealTourani/Match-Point | Match_Point.py | Match_Point.py | py | 1,547 | python | en | code | 3 | github-code | 36 |
18909907329 | from prettytable import PrettyTable
class Database:
def __init__(self, database_name):
import mysql.connector as m1
self.var = "w"
self.conn = m1.connect(host="localhost", user="root", password="utkarsh")
self.cursor = self.conn.cursor()
self.cursor.execute("CREA... | Codineer/shop-management-sytem | database.py | database.py | py | 5,264 | python | en | code | 0 | github-code | 36 |
39479422820 | from django.contrib.auth.models import Group, User
from datetime import datetime
from django.utils import timezone
from schedule.periods import Day
from datetime import timedelta
from apps.policies.models import SchedulePolicyRule
from apps.services.models import Service
"""def get_current_events_users(calendar):
... | openduty/openduty | apps/incidents/escalation_helper.py | escalation_helper.py | py | 4,082 | python | en | code | 121 | github-code | 36 |
28281049495 | import argparse
import pathlib
import itertools
import sys
import urllib
import docker
import tqdm
from compose import config
version = "0.8.0"
def _resolve_name(args, service):
if args.use_service_image_name_as_filename:
return urllib.parse.quote(service["image"], safe="")
return service["name"]
... | pohmelie/docker-compose-transfer | docker_compose_transfer/__init__.py | __init__.py | py | 3,985 | python | en | code | 1 | github-code | 36 |
20220878757 | import pathlib
prj_path = str(pathlib.Path(__file__).parent.parent.parent.resolve())
from advent_of_code.lib import parse as aoc_parse
from advent_of_code.lib import aoc
@aoc.pretty_solution(1)
def part1(data):
horizontal = sum(x[1] for x in data if x[0] == 'forward')
depth = sum(
-x[1] if x[0] == 'u... | Perruccio/advent-of-code | advent_of_code/year2021/solutions/day02.py | day02.py | py | 1,006 | python | en | code | 0 | github-code | 36 |
8228541339 | from models.pointnet import PointNetDenseCls
import torch
import torch.nn as nn
import torch.nn.functional as F
import hydra
import os
from datasets import kpnet
import logging
from itertools import combinations
import numpy as np
from tqdm import tqdm
def pdist(vectors):
distance_matrix = -2 * vectors.mm(torch.t... | qq456cvb/SemanticTransfer | train_emb.py | train_emb.py | py | 6,581 | python | en | code | 11 | github-code | 36 |
2251372103 | from typing import List
import mlflow
import pandas as pd
import tensorflow as tf
from keras_preprocessing.image import ImageDataGenerator
from zenml.steps import BaseParameters, Output, step
class EvaluateClassifierConfig(BaseParameters):
"""Trainer params"""
input_shape: List[int] = (224, 224, 3)
batc... | thbinder/mlops_sea_animal_classification | src/domain/steps/mlflow_evaluator.py | mlflow_evaluator.py | py | 1,170 | python | en | code | 4 | github-code | 36 |
24680231703 | # Bank account examples (with data) using decimal instead of floating
# point numbers
from decimal import *
class Account(object):
""" This class represents a bank account
Constants:
qb: Decimal formatting for bankers rounding
Attributes:
name (str): The name of the bank account
b... | scottherold/python_refresher_8 | RollingBack/rollback2.py | rollback2.py | py | 2,587 | python | en | code | 0 | github-code | 36 |
15371935865 | from RsSmw import *
import json
try:
with open ("config.json") as config_f:
RsSmw.assert_minimum_version('5.0.44')
config = json.load(config_f)
IP_ADDRESS_GENERATOR = config["IP_ADDRESS_GENERATOR"]
PORT = config["PORT"]
CONNECTION_TYPE = config["CONNECTION_TYPE"]
TRA... | mgarczyk/channel-sounder-5g | generator.py | generator.py | py | 1,625 | python | en | code | 0 | github-code | 36 |
8196850520 | from django.contrib import admin
from .models import User
class UserAdmin(admin.ModelAdmin):
list_display = (
'pk', 'role', 'username', 'email',
'first_name', 'last_name',
)
search_fields = ('username', 'email',)
list_filter = ('email', 'username')
admin.site.register(User, UserAdmi... | lojiver/foodgram-project | backend/foodgram/users/admin.py | admin.py | py | 323 | 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.