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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
30380144287 | import glob
import os
import pickle
import matplotlib.pyplot as plt
import numpy as np
def normalize_images(image_array):
return image_array.astype('float32') / 255.
def _add_salt_and_pepper(image_array, probability=.5):
image_array = np.squeeze(image_array)
uniform_values = np.random.rand(*image_array... | oarriaga/pathnet.keras | src/utils.py | utils.py | py | 4,771 | python | en | code | 1 | github-code | 90 |
42680204103 | from django.contrib import admin
from course import models
# Register your models here.
class CourseAdminView(admin.ModelAdmin):
list_display = [field.name for field in models.Course._meta.fields]
admin.site.register(models.Course, CourseAdminView)
class DepartmentAdminView(admin.ModelAdmin):
list_display ... | Attendance-System-G14/SATS-Backend | course/admin.py | admin.py | py | 817 | python | en | code | 0 | github-code | 90 |
37846446335 | '''
This file is part of GEAR.
GEAR is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distrib... | miquelcampos/GEAR_mc | gear/xsi/rig/component/eye_01/guide.py | guide.py | py | 4,679 | python | en | code | 24 | github-code | 90 |
19708239101 | from openpyxl import load_workbook
def read_excel_dict(file, sheet_name):
# 读取excel数据
# 得到wb
wb = load_workbook (file)
# 得到sheet,web["Sheet_name"]
sheet = wb[sheet_name]
# 得到所有数据
data = list (sheet.values)
# 获取所有标题
titles = data[0]
# 转化成字典
rows = [dict (zip (title... | guanqinchao/lesson_pytest | common/read_excel.py | read_excel.py | py | 419 | python | en | code | 0 | github-code | 90 |
17375002886 | from prompto.javascript.JavaScriptExpression import JavaScriptExpression
class JavaScriptIdentifierExpression (JavaScriptExpression):
@staticmethod
def parse(ids):
parts = ids.split("\\.")
result = None
for part in parts:
result = JavaScriptIdentifierExpression(result, par... | prompto/prompto-python3 | Python3-Core/src/main/prompto/javascript/JavaScriptIdentifierExpression.py | JavaScriptIdentifierExpression.py | py | 803 | python | en | code | 4 | github-code | 90 |
18181185279 | def query(x):
cnt=0
while(x>0):
x=x%bin(x).count('1')
cnt+=1
return cnt
N=int(input())
X=input()[::-1]
c=X.count('1')
sump,summ=0,0
for i in range(N):
if X[i]=='1':
sump=(sump+pow(2,i,c+1))%(c+1)
if c>1:
summ=(summ+pow(2,i,c-1))%(c-1)
ans=[]
for i in range(N... | Aasthaengg/IBMdataset | Python_codes/p02609/s934936891.py | s934936891.py | py | 580 | python | en | code | 0 | github-code | 90 |
24981946280 | import sys, time
sys.path.append("../..")
from MachineMotion import *
### This Python example showcases how to read encoder positions with MachineMotion v1. ###
mm = MachineMotion()
# Adjust this line to match whichever AUX port the encoder is plugged into
encoderPort = AUX_PORTS.aux_1
checkInput = True
print("Read... | VentionCo/mm-python-api | examples/MachineMotionV1/readEncoder.py | readEncoder.py | py | 1,030 | python | en | code | 6 | github-code | 90 |
816675679 | from flask import g, current_app, abort, url_for
from flask.ext.restful import reqparse
from flask.ext import restful
class ShortUrl(restful.Resource):
def __init__(self):
self.get_parser = reqparse.RequestParser()
self.get_parser.add_argument(
'id', type=str, required=True,
... | Dav1dde/vs | vs/views/rest/v1/short.py | short.py | py | 2,132 | python | en | code | 2 | github-code | 90 |
71913439337 | import tkinter as tk
from tkinter import ttk
from tkinter.font import Font
import ttkthemes
def message(message, width=300, height=150, margin_top=10, margin_bottom=10, margin_left=15, margin_right=15, font_size=12):
root = tk.Tk()
root.title("")
fontstyle = Font(size=font_size)
root.overrideredirect(... | KIY7086/BBDown-Flet-GUI | ttk_message.py | ttk_message.py | py | 1,240 | python | en | code | 0 | github-code | 90 |
12242227485 | def is_prime(x):
if x < 2:
return False
else:
for n in range(2, x-1):
if x % n == 0:
return False
return True
nums = [2, 3, 4, 5, 6, 7, 15, 20, 25]
if __name__ == "__main__":
for n in nums:
print(n, is_prime(n))
| James-T-Harding/git-practice-B | python/debugging/is_prime.py | is_prime.py | py | 287 | python | en | code | 0 | github-code | 90 |
30535002053 | # 두 번째 실행
import json
dict_list=[
{
'name':'james',
'age':20,
'spec':[
175.5,
70.5
]
},
{
'name':'Alice',
'age':21,
'spec':[
168.5,
60.5
]
}
]
# 그니까 제이슨은 모듈이라 이거지 ??
# 제이슨 파일은 언제 사용해요 ? -... | nanminzooda/1_pythonJMJ | 1_Python/section 14/ex14-6(2)-jasonWriter.py | ex14-6(2)-jasonWriter.py | py | 905 | python | ko | code | 1 | github-code | 90 |
13587622768 | import json
import sys
import os
import requests
from tqdm import tqdm
with open('beatmaps.csv') as fd:
beatmaps = fd.read().split(',')
session = requests.Session()
url = "https://osu.ppy.sh/osu/{}"
for beatmap in tqdm(beatmaps):
success = False
while not success:
try:
path = os.path... | Cyanogenoid/osu-patternrating | get-beatmap-files.py | get-beatmap-files.py | py | 961 | python | en | code | 0 | github-code | 90 |
40620543805 | import requests
class Serpapi:
def image_search(self, query):
url = "https://serpapi.com/search"
querystring = {"q":query,"tbm":"isch","engine":"google","api_key":"afdc240a8d4231728dd5276242b371584fd6d2cd6b2ddaab391530fdf36e81f5"}
headers = {
'User-Agent': "PostmanRuntime/7... | benadriaensen83/nanoleaf3 | Serpapi.py | Serpapi.py | py | 1,021 | python | en | code | 0 | github-code | 90 |
14332645237 | from aiogram import Router, F, types
from aiogram.filters import StateFilter
from aiogram.fsm.context import FSMContext
from aiogram.types import Message
from controllers import bug_controller
from keyboards.new_bug import bug_back_status_keyboard, bug_readiness_keyboard, bug_front_status_keyboard
from states.bug_stat... | 2tmirleid/ImpulseItBot | routers/edit_bug_router.py | edit_bug_router.py | py | 3,399 | python | en | code | 0 | github-code | 90 |
10263479546 | from django.test.utils import override_settings
from mock import patch
from nose.tools import assert_false, eq_
from bedrock.mozorg.tests import TestCase
from bedrock.firefox import helpers
@override_settings(FIREFOX_OS_FEED_LOCALES=['xx'])
@patch('bedrock.firefox.helpers.cache')
@patch('bedrock.firefox.helpers.Fir... | m8ttyB/bedrock | bedrock/firefox/tests/test_helpers.py | test_helpers.py | py | 3,075 | python | en | code | null | github-code | 90 |
38108573387 | # -*- coding:utf-8 -*-
# Copyright (C) 2021- BOUFFALO LAB (NANJING) CO., LTD.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the ... | llamaonaskateboard/bflb-mcu-tool | bflb_mcu_tool/libs/bflb_interface_openocd.py | bflb_interface_openocd.py | py | 15,563 | python | en | code | 4 | github-code | 90 |
38876667915 | def do_part_1(s: list):
disk_list = normalize_input(s) # it follows [[x, y, size, used, avail] ....]
viable_pairs = []
for i in range(0, len(disk_list)):
for j in range(0, len(disk_list)):
if disk_list[i][3] != 0:
if i != j:
if disk_list[i][3] <= disk... | dragonxi/advent-of-code-py | aoc2016/2016day22.py | 2016day22.py | py | 1,189 | python | en | code | 0 | github-code | 90 |
39081955193 | ## Setup.
# Imports.
import pyspark
from pyspark.sql import SparkSession
from pyspark.ml import PipelineModel
import pyspark.sql.functions as f
## Spark app.
# Spark context.
sc = pyspark.SparkContext()
# Spark session.
spark = SparkSession(sc)
## Get data.
# Read stream.
df = spark.readStream.format("kafka").option... | SaudIqbal-IITM/big-data-lab-2022 | labs/lab_7/subscriber.py | subscriber.py | py | 1,541 | python | en | code | 0 | github-code | 90 |
18445120009 | import sys
input = sys.stdin.readline
INF = float("inf")
# 解説参照
def main():
n, m = map(int, input().split())
a = list(map(int, input().split()))
a.sort(reverse=True) # 使用可能は数字は大きい順にソートしておく
cost = [-1, 2, 5, 5, 4, 5, 6, 3, 7, 6]
# dp[i]:= マッチi本で作れる最大桁数
dp = [-1] * (n + 1)
dp[0] = 0
for ... | Aasthaengg/IBMdataset | Python_codes/p03128/s975944485.py | s975944485.py | py | 932 | python | ja | code | 0 | github-code | 90 |
24601669129 | from wand.image import Image as WImage
from PIL import Image as PImage
from io import BytesIO
def pillow2wand(pil, image_format = 'PNG'):
"""
Converts the incoming PIL image to a Wand image.
The default image format for data exchange is PNG, which is fine for
most use cases. You might want to override it only if y... | Gutza/MagickPillow | lib/MagickPillow.py | MagickPillow.py | py | 784 | python | en | code | 1 | github-code | 90 |
40348216274 | import torch
import torchvision.models as models
model = models.resnet50(pretrained=True) # download pretrained model
model.eval()
dummy_input = torch.randn(1, 3, 224, 224)
input_names = ["input"]
output_names = ["output"]
torch.onnx.export(model,
dummy_input,
"my_resne... | iamashwinikolhe/ML_pyTorch | export_to_ONNX.py | export_to_ONNX.py | py | 630 | python | en | code | 0 | github-code | 90 |
71495230377 | import re
iFile = open("nist.txt", mode="r", encoding="utf-8")
oFile = open("nist_en.txt", mode="w")
title = ""
desc = ""
srcflag = False
i = 0
for line in iFile:
if " – " in line:
if len(title) > 0:
srcflag = False
desc = desc.encode("cp932","ignore").decode("cp932"... | mtmtEM/platinum_dictionary | scripts/MakeDict_nist.py | MakeDict_nist.py | py | 743 | python | en | code | 0 | github-code | 90 |
14290097505 |
from itertools import count
from turtle import title
from telegram.ext import Filters
from telegram import Update
from telegram.ext import Updater, MessageHandler, CommandHandler, CallbackContext
list = \
[
"Диденко Д.Н., 43 года, Директор по логистике",
"Каруна Т.В., 35 лет, Финансовый директор"... | dmitriydiden/Python-Homework10 | main.py | main.py | py | 2,247 | python | ru | code | 0 | github-code | 90 |
17324261488 | from threading import Event
from typing import Callable
from Xlib import X
from Xlib.ext.xtest import fake_input
from ...errors import AlreadyGrabbedError, UnknownGrabError, GenericGrabError
def _default_on_movement_fn(pos, delta):
print('Cursor moved by {}.'.format((delta)), end=' ')
print('Change this function b... | davis-b/keywatch | keywatch/linux/x11/mouse_movement_capture.py | mouse_movement_capture.py | py | 3,652 | python | en | code | 0 | github-code | 90 |
6933558142 | """
Handlers for dealing with callbacks
"""
import json, pathlib # noqa: E401
import logging
from aiogram import Bot, types
from aiogram.utils.exceptions import MessageNotModified
from process.database import User
from process.function import Function
from process.utility import clean_message, tree_display, escape_d... | karipov/creationDate | src/handlers/callback.py | callback.py | py | 2,444 | python | en | code | 67 | github-code | 90 |
37238565444 | ## 함수 실습 2
## 로또 뽑기, 중복 없이
import random
def get_random_number():
number = random.randint(1,45)
return number
lotto_num = []
lotto_cnt = 0 ## 무한 반복문이기때문에 6개만 생성할수 있도록 count 변수 생성
while True:
if lotto_cnt == 6:break
rand_num = get_random_number() ## 함수 반환값을 따로 변수로 만들어야 한다. 안그럴시 오작동
if rand_nu... | billy0529/python | python basic/chapter6/03.함수실습2.py | 03.함수실습2.py | py | 726 | python | ko | code | 0 | github-code | 90 |
4421151868 | import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence, PackedSequence
class HardMaxOp:
@staticmethod
def max(X):
M, _ = torch.max(X, dim=2, keepdim=True)
A = (M == X).float()
A = A / torch.sum(A, dim=2, keepdim=True)
return M.squeeze(), A.squee... | arthurmensch/didyprog | didyprog/ner/viterbi.py | viterbi.py | py | 9,228 | python | en | code | 69 | github-code | 90 |
17569982305 | # Import necessary libraries
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.ensemble import RandomForestClassifier
from xgboost import XGBClassifier
from sklearn.metrics import accuracy_score
# Load the dataset
train_data = pd.read_c... | joshuaz/kaggle_competitions | titanic2/titanic.py | titanic.py | py | 1,935 | python | en | code | 0 | github-code | 90 |
25046178182 | import networkx as nx
import matplotlib.pyplot as plt
from blank_list import *
f = open('conn_coh', 'r')
'''ввод графа в виде списка ребер'''
coh_list = []
coh_list = [ line.split() for line in f ]
adj_list = transform(coh_list)
tree = []
'''cписок посещенных вершнин'''
visited = {}
for elem in coh_list:
vis... | guskovgithub/Sem2 | graph/graph.py | graph.py | py | 1,718 | python | ru | code | 0 | github-code | 90 |
27258200148 | """Contains the application’s url."""
from django.urls import path
from . import views
app_name = 'administration'
urlpatterns = [
path('', views.index, name='index'),
path('remove_user/<int:id_user>', views.remove_user, name='remove_user'),
path('creating_user', views.creating_user, name='creating_user')... | Cyril45/Raspal | administration/urls.py | urls.py | py | 326 | python | en | code | 0 | github-code | 90 |
2152895599 | """ NAMA = CORRY LUQMA ZUNIRA
KELAS = D
NIM = L200170152 """
A = ["AYASHA", "BONDAN" , "CORRY" , "DIKA" , "EKA"]
B = ["A01" , "B02 " , "C03" , "D04" , "E05"]
C =[]
C.extend(A)
C.extend(B)
def insertionSort(A) :
n = len(A)
for i in range(1,n):
nilai = A[i]
pos = i
... | L200170152/prak_ASD | ModulKe5_D_152/no2.py | no2.py | py | 520 | python | en | code | 0 | github-code | 90 |
13104125005 | import requests
img1_path = '/Users/gtomberlin/Documents/Pictures/google_PNG19633.png'
img2_path = '/Users/gtomberlin/Documents/Pictures/119930_google_512x512.png'
# GET request to hit root endpoint for welcome message
response = requests.get('http://localhost:8000/image_similarity')
print(response.json())
# POST re... | Gabriel0110/Image-Similarity-FastAPI | test_api.py | test_api.py | py | 619 | python | en | code | 0 | github-code | 90 |
6178458998 | from PcapAnalyzer import PcapAnalyzer
from ICMPPairsGenerator import ICMPPairsGenerator
from ChecksumCaculator import ChecksumCaculator
if __name__ == "__main__":
count = 0
checksumCaculator = ChecksumCaculator()
ip_pairs_dict = {}
pcapAnalyzer = PcapAnalyzer(ip_pairs_dict)
pcapAnalyzer.get_filel... | parahaoer/AnalyzeChecksum | main.py | main.py | py | 1,446 | python | en | code | 0 | github-code | 90 |
40674655771 | def func(a):
ret = 0;
while a>0:
ret+=a
a-=1
return ret
n = int(input())
for i in range(0,n):
score = 0
scores = input().split('X')
for x in scores:
if len(x)>0:
score+=func(len(x))
print(score)
| JEHYUNLIM/python_workspace | BaekjoonCode/8958.py | 8958.py | py | 211 | python | en | code | 0 | github-code | 90 |
18004072989 | import copy
n = int(input())
a = list(map(int,(input().split())))
s = [0]*n
s[0] = a[0]
for i in range(n-1):
s[i+1] = s[i] + a[i+1]
s2 = copy.copy(s)
ans = []
# 最初を正とする場合
ans1 = 0
tmp = 0
for i in range(n):
if i%2 == 0: #奇数項
s[i] += tmp
if s[i] <= 0:
tmp += 1 - s[i]
an... | Aasthaengg/IBMdataset | Python_codes/p03739/s573067516.py | s573067516.py | py | 822 | python | en | code | 0 | github-code | 90 |
221623395 | """tests for types"""
import pytest
from meander import types
@pytest.mark.parametrize(
"value, is_valid, result",
(
(1, True, True),
("1", True, True),
(True, True, True),
("true", True, True),
("TrUe", True, True),
(2, False, None),
(0, True, False),
... | robertchase/meander | tests/test_types.py | test_types.py | py | 2,068 | python | en | code | 1 | github-code | 90 |
32743449010 | #!/usr/bin/python
import rospy, math
from control_msgs.msg import GripperCommandActionGoal
from actionlib_msgs.msg import GoalStatusArray
gripper_closing = 0.0
gripper_effort = 10.
gripper_flag = False
############################################
## MoveGripper.py ##
## ... | iandevlaming/Fetch_Scripts | Movement_Tutorials/MoveGripper.py | MoveGripper.py | py | 2,772 | python | en | code | 0 | github-code | 90 |
19220964348 | from abc import ABCMeta
class Warehouse:
def __init__(self):
self._store = []
def add_item(self, item):
if isinstance(item, OfficeEquipment):
self._store.append(item)
def send_item_to_department(self, item_type, items_count, dep, params=None):
if isinstance(item_type,... | twist-tracer/gb-python2 | lesson8/warehouse/warehouse.py | warehouse.py | py | 2,113 | python | en | code | 0 | github-code | 90 |
24556296976 | from pathlib import Path
from bs4 import BeautifulSoup
from gensim.utils import simple_preprocess
from sklearn.feature_extraction.text import TfidfVectorizer
import pandas as pd
import numpy as np
def split_list(seq, num):
"""
Splitting a list into N parts of approximately equal length
Args... | noam972/search-engine-for-israeli-law | pre_processing_functions.py | pre_processing_functions.py | py | 6,324 | python | en | code | 0 | github-code | 90 |
74468503975 | from Classes import Grid, Sprite, Hotbar, Block
from Simulation import SimulateGrid
import pygame
import math
import cProfile
import time
grid_width = 100
grid_height = 50
scaling = 5
unique_number = 0
def CursorLocation(mouse_x, mouse_y):
mouse_x /= scaling
mouse_y /= scaling
mouse_x = math.ceil(mouse_x... | HunterSTL/SandSim | SandSim.py | SandSim.py | py | 5,916 | python | en | code | 0 | github-code | 90 |
39110461199 | from enum import Enum
from time import sleep
from typing import Literal, Union
class LandingStatus(Enum):
LANDING = 1
LANDED = 2
REQUEST_LANDING = 3
LANDING_NOT_CLEAR = 4
LANDING_CLEAR = 5
class Mediator:
def __init__(self, runway, plane):
self.runway = runway
self.runway.med... | Matheus-IT/design-patterns-python | mediator/mediator.py | mediator.py | py | 2,797 | python | en | code | 0 | github-code | 90 |
34670045845 | import pandas as pd
import os
import torchvision
import torchvision.transforms as transform
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from utils_xray import *
# dataset \in ['chest_xray_pneumonia', 'rsna', 'tb', 'gb7', 'chest14', 'all']
dataset = 'chest_xray_pneumonia'
t... | rizvansky/Internship-AI-Lab-IU-2020 | main.py | main.py | py | 3,893 | python | en | code | 0 | github-code | 90 |
31814215571 | """
invlib.vector
=============
The :code:`invlib.vector` module contains the :code:`Vector` class that provides
efficient linear algebra operations for dense vectors.
"""
import numpy as np
import ctypes as c
from invlib.api import resolve_precision, get_stride, get_ctypes_scalar_type, \
buffer_from_memory
###... | simonpf/invlib | src/invlib/interfaces/python/invlib/vector.py | vector.py | py | 5,719 | python | en | code | 6 | github-code | 90 |
13622455578 | #! /usr/bin/python
from astropy.io import fits
from ..dm.timedelays import dm_delay
import PSRpy.fft as ft
import matplotlib.pyplot as plt
import numpy as np
import sys
class ReadFits(object):
"""
Defines a class that stores data and header info from an input PSRFITS file.
"""
def __init__(self, infi... | emmanuelfonseca/PSRpy | PSRpy/fits/readfits.py | readfits.py | py | 10,446 | python | en | code | 2 | github-code | 90 |
36249444447 | #code
"""
Given a string str, find length of the longest repeating subseequence such that the two subsequence don’t have same string character at same position, i.e., any i’th character in the two subsequences shouldn’t have the same index in the original string.
Input:
The first line of input contains an integer T d... | Kapil-Pathak/GeeksForGeeks | DP_Longest Repeating Subsequence.py | DP_Longest Repeating Subsequence.py | py | 971 | python | en | code | 0 | github-code | 90 |
75117419496 | from flask import Flask, request, jsonify
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
# Create a Flask web application
app = Flask(__name__)
# Create and train the chatbot
chatbot = ChatBot('corona bot')
trainer = ChatterBotCorpusTrainer(chatbot)
trainer.train("chatterbot.co... | ronking1808/Projectformyresume1 | back.py | back.py | py | 811 | python | en | code | 0 | github-code | 90 |
25915906371 | print('Gerador de P.A')
print('=-=' * 10)
primeiro = int(input('Primeiro termo:'))
razao = int(input('Razão da P.A:'))
termo = primeiro
cont = 1
total = 0
mais = 10
while mais != 0:
total = total + mais
while cont <= total:
print('{} → '.format(termo), end='')
termo += razao
cont += 1
... | celycodes/curso-python-exercicios | exercicios/ex062.py | ex062.py | py | 493 | python | pt | code | 2 | github-code | 90 |
16989232672 | from time import sleep
import signal
class ProcessTerminator:
kill_now = False
def __init__(self):
signal.signal(signal.SIGINT, self.exit_gracefully)
signal.signal(signal.SIGTERM, self.exit_gracefully)
def exit_gracefully(self, signal_number, frame):
self.kill_now = True
if __nam... | NanoPeter/derprozessleiter | infinite_test.py | infinite_test.py | py | 488 | python | en | code | 0 | github-code | 90 |
6573698010 | import abc
import copy
import datetime
import logging
from chatbot.bot_wrapper import BotQuickReply
from chatbot.consts import ChatPlatform
logger = logging.getLogger(__name__)
class ChatStep(abc.ABC):
MAX_ITEMS_FOR_SUGGESTIONS = 6
MAX_ITEMS_FOR_BUTTONS = 4
STORAGE_DATETIME_FORMAT = '%Y%m%... | hasadna/OpenTrainCommunity | train2/chatbot/steps/chat_step.py | chat_step.py | py | 3,248 | python | en | code | 24 | github-code | 90 |
26469787974 | import tkinter as tk
import tkinter.ttk as ttk
from date_entry import dateEntry
from arithmetic import Arithmetic
from information import information
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title('Age calculator')
self.resizable(False, False)
self.date_entr... | misaghi/age_calculator_tkinter | age_calculator.py | age_calculator.py | py | 2,628 | python | en | code | 0 | github-code | 90 |
17409666297 | import math
################################################################################
# Basic operations
################################################################################
def is_even(n):
return n % 2 == 0
def is_square(n):
root = math.sqrt(n)
return root == int(root)
def is_palindrome(... | gameboy1024/ProjectEuler | src/lib/math_utils.py | math_utils.py | py | 4,424 | python | en | code | 1 | github-code | 90 |
33239366811 | from selenium import webdriver
import time
from selenium.webdriver import ActionChains
b = webdriver.Firefox()
b.get("https://jqueryui.com/droppable")
b.switch_to.frame(0)
ac = ActionChains(b)
src = b.find_element_by_id('draggable')
trgt = b.find_element_by_id('droppable')
ac.drag_and_drop_by_offset(src,... | saba1792/Selenium-Python | actionChain.py | actionChain.py | py | 422 | python | en | code | 0 | github-code | 90 |
73501422697 | '''
기둥과 보 설치
'''
def solution(n, build_frame):
# 1. build_map을 만들고 build_frame을 하나씩 실행
# build_map은 n * n
# 2. 규칙 검사를 실행
# 규칙 검사에 맞지않으면 롤백
build_map = [[2 * [0] for _ in range(n + 1)] for _ in range(n + 1)]
result = []
for x, y, a, b in build_frame:
if b == 0:
result.remove([x, y, a])
else :
result... | Err0rCode7/algorithm | Book_이코테/fourth_try/Implementation/wall.py | wall.py | py | 2,435 | python | ko | code | 0 | github-code | 90 |
8795339419 | # -*- coding:utf8 -*-
'''
dsf core module for working with Debian / Ubuntu 'apt' package manager
@author: Stuart Herbert <stuart@stuartherbert.com>
https://devsetup.systems/dsf-framework/
'''
import os
import dsf
def install(pkg):
"""
Uses 'apt' to install the given package
Params:
* pkg: the name of the pac... | devsetup/devsetup_framework | _pkg/apt.py | apt.py | py | 1,273 | python | en | code | 1 | github-code | 90 |
2233687058 | from collections import Counter
class Solution:
def halvesAreAlike(self, s: str) -> bool:
vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
a_s, b_s = Counter(s[:len(s)//2]), Counter(s[len(s)//2:])
a_c, b_c = 0, 0
for c in a_s:
if c in vowels:
a_... | vyshor/LeetCode | Determine if String Halves Are Alike.py | Determine if String Halves Are Alike.py | py | 690 | python | en | code | 0 | github-code | 90 |
18043890369 | H, W = map(int, input().split())
A = [input() for _ in range(H)]
x = 0
for h in range(H):
if '#' in A[h][:x]:
print('Impossible')
exit()
if A[h][x] != '#':
print('Impossible')
exit()
while x+1 < W and A[h][x+1] == '#':
x += 1
if '#' in A[h][x+1:]:
print('... | Aasthaengg/IBMdataset | Python_codes/p03937/s930238196.py | s930238196.py | py | 367 | python | en | code | 0 | github-code | 90 |
72639166697 | from matplotlib import pyplot as plt
import random
import math
class Person():
def __init__(self,startpos,step_value=1,maxdist=100):
self.x=[startpos[0]]
self.y=[startpos[1]]
self.step_value=step_value
self.maxdist=maxdist
self.current_maxdist=0
self.s... | Chhavi-S/RandomWalk | Main.py | Main.py | py | 1,334 | python | en | code | 0 | github-code | 90 |
23046477911 | '''
1171. Remove Zero Sum Consecutive Nodes from Linked List
Medium
Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences.
After doing so, return the head of the final linked list. You may return any such answer.
(Note that in the exa... | aditya-doshatti/Leetcode | remove_zero_sum_consecutive_nodes_from_linked_list_1171.py | remove_zero_sum_consecutive_nodes_from_linked_list_1171.py | py | 2,025 | python | en | code | 0 | github-code | 90 |
29775841017 | import tensorflow as tf
from tensorflow.keras import datasets, Sequential, layers, optimizers
import datetime
from matplotlib import pyplot as plt
import io
def preprocess(x, y):
x = tf.cast(x, dtype=tf.float32) / 255.
y = tf.cast(y, dtype=tf.int32)
return x, y
def plot_to_image(figure):
buf = io.Byt... | vlluvia/university | cv/hand_writer.py | hand_writer.py | py | 3,275 | python | en | code | 0 | github-code | 90 |
73561589735 | from datetime import datetime
import pytest
from flask import url_for
from devlog.utils.text import slugify
def test_index_no_posts(client):
url = url_for('main.index')
rv = client.get(url)
assert rv.status_code == 200
assert 'żadnych postów' in rv.text
def test_index_one_post(client, post_factory... | zgoda/devlog | tests/test_views.py | test_views.py | py | 4,205 | python | en | code | 0 | github-code | 90 |
31227650308 | __author__ = 'jbowman'
# https://pythonspot.com/conditional-statements/
x = 3
y = 10
if x < y:
print(str(x) + ' is smaller than ' + str(y))
else:
print(str(x) + ' is bigger than ' + str(y))
# game
age = 27
N = 3
halfrange = 5
print('Guess my age, you get ' + str(N) + ' guess(es)!')
for ii in range(N):
g... | Dorga/PythonTutorial | 09Conditionals.py | 09Conditionals.py | py | 721 | python | en | code | 3 | github-code | 90 |
39736531723 | def strToOne(i):
N = list(i)
hap = 1
for i in N:
hap *= int(i)
i = str(hap)
print(i,end=' ')
if len(i) != 1:
return strToOne(i)
else: print()
while True:
s = input()
if s =='0': break
print(s,end=' ')
if len(s) != 1:
strToOne(s)
... | lyong4432/BOJ.practice | #4564.py | #4564.py | py | 335 | python | en | code | 0 | github-code | 90 |
18119342179 | import math
while True:
count = int(input())
if count == 0:
break
data = [int(i) for i in input().split()]
m = sum(data) / len(data)
a = sum([(x - m) ** 2 for x in data]) / count
print('{0:.5f}'.format(math.sqrt(a))) | Aasthaengg/IBMdataset | Python_codes/p02381/s278877712.py | s278877712.py | py | 250 | python | en | code | 0 | github-code | 90 |
38130725618 | import RPi.GPIO as GPIO
import pygame
import time
pygame.mixer.init()
time.sleep(1) # Wait for 1 second
pygame.mixer.music.load("Ready.mp3")
pygame.mixer.music.play(loops=1)
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(5, GPIO.OUT) # Set up pin 5 as an output pin
while True:
key_press = input("Pres... | GlowingGaijin/WiFiDetector | turnoff.py | turnoff.py | py | 638 | python | en | code | 0 | github-code | 90 |
74108357737 | import sys
V = int(sys.stdin.readline())
matrix = [[] for _ in range(V + 1)]
for _ in range(V):
path = list(map(int, sys.stdin.readline().split()))
path_len = len(path)
for i in range(1, path_len // 2):
matrix[path[0]].append([path[2 * i - 1], path[2 * i]])
result1 = [0 for _ in range(V + 1)]
... | dku19jam/algo_study | boj문제풀이/boj_1167.py | boj_1167.py | py | 759 | python | en | code | 0 | github-code | 90 |
18293511609 | import fractions
from functools import reduce
def lcm_base(x, y):
return (x * y) // fractions.gcd(x, y)
def lcm_list(numbers):
return reduce(lcm_base, numbers, 1)
N, M = map(int, input().split())
A = list(map(int, input().split()))
for i in range(N):
A[i] = A[i] // 2
p = 0
de_2 = 0
x = A[0]
while (p ... | Aasthaengg/IBMdataset | Python_codes/p02814/s141648473.py | s141648473.py | py | 679 | python | en | code | 0 | github-code | 90 |
23624252330 | # usage: csv_main.py <input file> <output file> [num entries]
import sys
import time
from src.model.preprocesser import top_N_NEs
"""
This main file runs a program capable of processing a csv input (NERs IDs)
and writes the output (tagged NERs) in another *csv file*
"""
def check_and_return_csv_inputs():
# (3... | mariomastrandrea/WikiNER | src/main/csv_main.py | csv_main.py | py | 2,099 | python | en | code | 0 | github-code | 90 |
18555334689 | def actual(N, S, M, T):
points = [S.count(word) - T.count(word) for word in set(S)]
return max(0, max(points))
N = int(input())
S = [input() for _ in range(N)]
M = int(input())
T = [input() for _ in range(M)]
print(actual(N, S, M, T))
| Aasthaengg/IBMdataset | Python_codes/p03408/s550440706.py | s550440706.py | py | 247 | python | en | code | 0 | github-code | 90 |
9750450815 | import sqlite3
import pandas as pd
import numpy as np
class ArticleArms(object):
"""
Arms of Yahoo! R6 dataset
"""
def __init__(self, path_db, num_cache_lines=10000):
self.conn = sqlite3.connect(path_db)
self.cursor = self.conn.cursor()
self.event_cache = None
self.num_... | hakmink/HCC-MAB | mab/yahoo_r6_arm.py | yahoo_r6_arm.py | py | 7,517 | python | en | code | 1 | github-code | 90 |
17952925329 | def resolve():
N = int(input())
A = [list(map(int, input().split())) for _ in range(N)]
ans = 0
for src in range(N-1):
for dst in range(src+1, N):
mintotal = float("inf")
for trans in range(N):
if trans == src or trans == dst:
continue
... | Aasthaengg/IBMdataset | Python_codes/p03600/s185051839.py | s185051839.py | py | 613 | python | en | code | 0 | github-code | 90 |
13273277433 | #problem 1:
import json
class Movie:
def __init__(self, move_info):
self.cast = []
self.move_info = move_info
#Add method to add cast, method checks for valid data:
def add_cast(self,newcast):
if type(newcast) is dict and newcast['name'] !='' and newcast['age'] !=0 and newcast['sex'] =... | nqlong88/python_programming_v2 | Unit_5/homework/class10_movie_maker.py | class10_movie_maker.py | py | 2,784 | python | en | code | 1 | github-code | 90 |
14031561607 | import os
import time
import numpy as np
import pyro
import torch
from torchmetrics import Accuracy, MeanMetric
import tyxe
from pyro import distributions as dist
from torch.nn.functional import softmax, nll_loss
from tqdm import tqdm
import wandb
import torchmetrics as tm
import torch.nn.functional as F
from src.inf... | silasbrack/approximate-inference-for-bayesian-neural-networks | src/inference/vi.py | vi.py | py | 3,938 | python | en | code | 2 | github-code | 90 |
72888113257 | import os
def compute_bitrate(file_path, duration):
try:
# Get file size in bytes
file_size_bytes = os.path.getsize(file_path)
# Calculate bitrate in kbps
bitrate = (file_size_bytes * 8) / (1000 * duration)
return bitrate
except Exception as e:
print(f"E... | vargasyeriko/_py2ms_git_AUDIO_EDITING_projects | ms_4_Normalization/2_PY_READ_FIELDS/_ms_fields_2_bitrate.py | _ms_fields_2_bitrate.py | py | 510 | python | en | code | 0 | github-code | 90 |
18272309029 | # 2020/07/23
# AtCoder Beginner Contest 154 - A
# Input
s, t = input().split()
a, b = map(int,input().split())
u = input()
aa = a
ab = b
# Calc
if s == u:
aa = aa - 1
elif t == u:
ab = ab - 1
# Output
print(aa, ab)
| Aasthaengg/IBMdataset | Python_codes/p02777/s808300492.py | s808300492.py | py | 227 | python | en | code | 0 | github-code | 90 |
73501451177 | from collections import deque
import sys, copy
input = sys.stdin.readline
n = int(input().rstrip())
_class = [[] for _ in range(n + 1)]
depth = [0 for _ in range(n + 1)]
cost = [0 for _ in range(n + 1)]
for i in range(1, n + 1) :
input_list = list(map(int, input().rstrip().split()))
for a in range(0, len(input_l... | Err0rCode7/algorithm | baekjoon/dijkstra_graph/커리큘럼.py | 커리큘럼.py | py | 842 | python | en | code | 0 | github-code | 90 |
38717357976 | """
A re-implementation of the matplotlib BezierSegment to make it faster.
"""
import math
from typing import Final
import numba
import numpy as np
class FastBezierSegment:
"""
A 2-dimensional Bezier segment with 3 control points.
Parameters
----------
control_points : (N, d) array
Locat... | Sothatsit/CamoWorms | src/bezier.py | bezier.py | py | 2,916 | python | en | code | 0 | github-code | 90 |
4169496984 | from tkinter import Toplevel, StringVar, Entry, END, Button, ttk
import json
class PrepromptEditor(Toplevel):
def __init__(self, parent):
super().__init__(parent)
self.title("PrepromptEditor")
self.parent = parent
self.resizable(False, False)
self.font = parent.font
self.padding = p... | RealityAnchor/ries-gpt-ui | preprompt_editor.py | preprompt_editor.py | py | 2,555 | python | en | code | 11 | github-code | 90 |
21560882290 | # guessing game!
# import random so we can use it
import random
# randomly select a winning number
answer = random.randint(1, 10)
# start the user's guess at 0
guess = 0
#
for x in range(6):
print(x)
guess = int (input ("Guess ? "))
if guess == answer:
print ("You got it!!")
break
elif ... | MaxT2/EWPythonDevelopment | First Session Code/guessing.py | guessing.py | py | 420 | python | en | code | 0 | github-code | 90 |
5435978575 | def countingValleys(n, steps):
valley = seaLevel = 0
for step in steps:
if step == "U":
seaLevel += 1
else:
seaLevel -= 1
if step == "U" and seaLevel == 0:
valley += 1
return valley
if __name__ == '__main__':
steps = int(input().strip())
... | Bluthunder/pythonExercise | hackerrank_interview_prep_kit/warmup_challenges/counting_valleys.py | counting_valleys.py | py | 396 | python | en | code | 0 | github-code | 90 |
18026846529 | def main():
N = int(input())
nums_list = [list(map(int, input().split())) for _ in range(N)]
nums_list.reverse()
cnt = 0
for a, b in nums_list:
cnt += (b - (a + cnt)) % b
print(cnt)
if __name__ == '__main__':
main()
| Aasthaengg/IBMdataset | Python_codes/p03821/s811568774.py | s811568774.py | py | 254 | python | en | code | 0 | github-code | 90 |
39476895766 | f = open("day7/input.txt")
class Directory:
def __init__(self, name : str, parent):
self.name = name
self.parent = parent
self.childern = {}
self.files = {}
self.size = 0
root = Directory("/", None)
cur = None
for line in f:
line = line.strip()
line = line.split(" ... | Chrisk1905/AdventOfCode2022 | day7/part2.py | part2.py | py | 1,866 | python | en | code | 0 | github-code | 90 |
71026292457 | # Apply PEP-328 to Python 2 to unify import directive syntax
# between Python versions
# https://www.python.org/dev/peps/pep-0328
from __future__ import absolute_import
import argparse
import logging
import os
from pprint import pformat
import re
import shutil
import sys
import traceback
from build_migrator.common.al... | KasperskyLab/BuildMigrator | build_migrator/generators/cmake.py | cmake.py | py | 33,886 | python | en | code | 30 | github-code | 90 |
8542312635 | #-*- coding:utf-8 _*-
from torch.utils.data import Dataset
import torch
import numpy as np
from torch.utils.data import DataLoader, Dataset
import torch
import numpy as np
import pandas as pd
import pickle
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
def normaliza... | Meredith-z/ENSO-project | dataset/dataset.py | dataset.py | py | 3,036 | python | en | code | 0 | github-code | 90 |
16524333580 | import pandas as pd
import numpy as np
import random
import toml
agents = 3
items = 100
agent_dist = [0, .25, .25, .5]
users = 40
compatibility1 = [0,0,1]
compatibility2 = [1,0,0]
compatibility3 = [1,0,1]
dist1 = [0.33,.33,.33]
start1 = 1
end = 20
dist2 = [.8,.2,0]
start2 = 21
class item_user_gen:
def __init__(se... | that-recsys-lab/scruf_data_gen | data_gen_outline.py | data_gen_outline.py | py | 2,894 | python | en | code | 0 | github-code | 90 |
5261397648 | def gp(op,cl,ans):
if op == 0 and cl == 0:
print(ans)
elif op < 0 or cl < op:
return
else:
gp(op,cl-1,ans+")")
gp(op-1,cl,ans +"(")
gp(3,3,"")
| ShubhamSinghal12/PythonDSAClassroomApril2022 | Lec16/GeneratingParanthesis.py | GeneratingParanthesis.py | py | 189 | python | nl | code | 1 | github-code | 90 |
34547874184 | import glob
import patch_mem
import parseutil
import argparse
import findTheBits_xx
import pathlib
def pad(ch, wid, data):
tmp = str(data)
return (ch * (wid - len(tmp)) + tmp)
def findAllBitsInDir(dr, verbose, mappings, check):
print("")
print("Finding bits in directory: {}".format(str(dr)), flush=T... | chipsalliance/f4pga-xc7-bram-patch | findTheBits.py | findTheBits.py | py | 2,511 | python | en | code | 15 | github-code | 90 |
23423018805 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
import uuid
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
... | RossLitzenberger/blog | writing/migrations/0001_initial.py | 0001_initial.py | py | 1,519 | python | en | code | 0 | github-code | 90 |
35164007926 | #!pip install nltk
#import nltk
#nltk.download('wordnet') # <-- Uncomment these lines if you haven't downloaded wordnet before
from nltk.corpus import wordnet as wn
# Distractors from Wordnet
def get_distractors_wordnet(syn,word):
distractors=[]
word= word.lower()
orig_word = word
if len(word.split()... | colefoster/jeopardy | play_jeopardy/server/scripts/py_distractors/generate_wordnet.py | generate_wordnet.py | py | 1,156 | python | en | code | 0 | github-code | 90 |
18760388011 | import numpy as np
from synthtiger.components.component import Component
class Switch(Component):
def __init__(self, component, prob=1, args=None):
super().__init__()
self.component = component
self.prob = prob
if args is not None:
self.component._init(**args)
de... | clovaai/synthtiger | synthtiger/components/wrapper/switch.py | switch.py | py | 1,191 | python | en | code | 362 | github-code | 90 |
18353321069 | # coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
#import bisec... | Aasthaengg/IBMdataset | Python_codes/p02936/s227006379.py | s227006379.py | py | 1,172 | python | en | code | 0 | github-code | 90 |
22226471759 | from selenium import webdriver
import time
class WhatsappBot:
def __init__(self):
self.mensagem = "Testando chat bot para whatsapp. Gabriel é lindo"
self.grupos = ["Nath", "PV calaboca", "Heleno", "Mozão 💕"]
options = webdriver.ChromeOptions()
options.add_argument('lang=pt-br'... | GabrielRioo/ChatBot_wpp | zapbot.py | zapbot.py | py | 1,714 | python | en | code | 1 | github-code | 90 |
18152977939 | n= int(input())
cont=0
yes=0
for x in range(n):
a,b= input().split()
a, b= int(a), int(b)
if a==b:
cont+=1
else:
cont=0
if cont>=3:
yes=1
if yes==1:
print("Yes")
else:
print("No") | Aasthaengg/IBMdataset | Python_codes/p02547/s969155046.py | s969155046.py | py | 231 | python | en | code | 0 | github-code | 90 |
19134020783 | fname = input("Please enter the file number ==> ")
parno = int(input("Please enter the paragraph number ==> "))
lineno = int(input("Please enter the line number ==> "))
def get_line(fname, parno, lineno):
parcount = 1
linecount = []
f = open(fname)
lines = f.readlines()
for i in lines:
if i... | Anooj-Pai/Python-Projects | Labs/Lab7/check2.py | check2.py | py | 755 | python | en | code | 0 | github-code | 90 |
41641003373 | import jax.numpy as jnp
import jax
from collections import defaultdict
import itertools
import matplotlib
import os
from tqdm import tqdm
import matplotlib.pyplot as plt
matplotlib.rcParams['mathtext.fontset'] = 'cm'
matplotlib.rcParams['font.family'] = 'STIXGeneral'
plt.style.use('ggplot')
def filter_classes(dataset... | giannisdaras/multilingual_robustness | utils.py | utils.py | py | 3,840 | python | en | code | 10 | github-code | 90 |
42384583865 | from decimal import Decimal, DecimalException
import datetime
from .rosetta_config import RosettaConfig
class Validations(object):
currencies_list = RosettaConfig.CURRENCIES_LIST
instrument_sub_type_list = RosettaConfig.INSTRUMENT_SUB_TYPE
rating_agencies_list = RosettaConfig.RATING_AGENCIES
rating_h... | RoySegall/BismarckValidator | rosetta/rosetta_validations.py | rosetta_validations.py | py | 7,643 | python | en | code | 1 | github-code | 90 |
23638164851 | class Solution(object):
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
length1 = len(word1)+1
length2 = len(word2)+1
dp = [[j for j in range(length2)]]
for i in range(1,length1):
current = [i... | XinScript/Leetcode | 72.Edit_Distance.py | 72.Edit_Distance.py | py | 981 | python | en | code | 0 | github-code | 90 |
18120275609 | import math
n = int(input())
x = list(map(int, input().split()))
y = list(map(int, input().split()))
p_1, p_2, p_3, p_infinit = 0, 0, 0, 0
dis_list = []
for i in range(n):
dis_list.append(abs(x[i] - y[i]))
sum_d = abs(x[i] - y[i])
p_1 += sum_d
p_2 += sum_d ** 2
p_3 += sum_d ** 3
p_2 = math.sqrt(p_2... | Aasthaengg/IBMdataset | Python_codes/p02382/s459975726.py | s459975726.py | py | 398 | python | en | code | 0 | github-code | 90 |
26046018902 |
"""
Variable Length Quantity problem at exercism.com
"""
def encode(numbers):
"""
Encode numbers using Variable length quantity
Args:
numbers ([list]): [list of numbers to encode]
Returns:
[list]: [list of encoded numbers]
"""
values = []
# loop numbers in list
for n... | JCArya/Exercism-in-Python | variable_length_quantity.py | variable_length_quantity.py | py | 2,535 | python | en | code | 1 | github-code | 90 |
74296547177 | import graphviz
import solution2
def render_trie(dot, trie, cur_str=''):
if trie is None:
return
for k in trie:
dot.node(cur_str + k, k)
dot.edge(cur_str, cur_str + k)
render_trie(dot, trie[k], cur_str + k)
dot = graphviz.Digraph()
dot.node('')
render_trie(dot, solution2.trie... | MageJohn/Advent-of-Code-2018 | Day 02 - Inventory Management System/render_solution2_trie.py | render_solution2_trie.py | py | 356 | python | de | code | 0 | github-code | 90 |
37721990881 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 2 16:03:36 2018
@author: 75129
"""
import scipy.io as sio
import numpy as np
import matplotlib as plt
import scipy.interpolate as siInter
import pandas as pd
def resample(img,x_size,y_size,method):
# plt.pyplot.figure()
# plt.pyplot.imshow(img)
(xOldSize,yOl... | zhoukaisheng/Landslide-Susceptibility | SlopeCardResize.py | SlopeCardResize.py | py | 3,411 | python | en | code | 48 | github-code | 90 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.