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
23511005935
class Node: def __init__(self, data): self.data = data self.next_node = None def __str__(self): return self.data.__str__() if self.data is not None else 'None' class LinkedList: def __init__(self): self.head = None def add(self, data): if self.head is None: ...
YunTaoYoung/AlgorithmPractise
Python/LinkedList/linked_list.py
linked_list.py
py
6,323
python
en
code
0
github-code
90
73792445095
from django.db import models from django.dispatch import receiver from django.db.models.signals import post_save from home.models import User class ReaderTicket(models.Model): """Модель читательского билета.""" user = models.OneToOneField(User, on_delete=models.CASCADE) @receiver(post_save, sender=User)...
alexmon1989/libraries_portal
reader_cabinet/models.py
models.py
py
855
python
en
code
0
github-code
90
24397256030
import tensorflow as tf from networks.backbone.ConvNeXt.convnext import create_model (x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data() x_train = x_train.astype('float32') / 255 x_test = x_test.astype('float32') / 255 model = create_model(model_name='convnext_tiny_224', input_shape=(32, 32)...
Yuri-Su/Baseline
models/backbone/ConvNeXt/test.py
test.py
py
653
python
en
code
1
github-code
90
14705347428
import jax from jax import numpy as jnp, random import flax.linen as nn import gymnasium as gym from typing import Any from typing_extensions import TypedDict from .types import Metrics Params = TypedDict("Params", { 'discount': float, 'actor_learning_rate': float, 'critic_learning_rate': float, 'actor...
gabe00122/custom-rl-practice
custom_rl_jax/policy_gradient/actor_critic.py
actor_critic.py
py
3,966
python
en
code
0
github-code
90
25754081192
import argparse import os import pickle from collections import namedtuple import numpy as np import scipy.io as sio import torch import torchvision.transforms.functional as F from PIL import Image from torch.utils.data import DataLoader from torchvision import transforms from tqdm import tqdm from dataset import get...
IGLICT/TM-NET
python/extract_latents_geo_only_all_parts.py
extract_latents_geo_only_all_parts.py
py
4,156
python
en
code
33
github-code
90
18452740779
N = int(input()) l = [] for i in range(N): A, B = [int(_c) for _c in input().split(" ")] l.append({"A": A, "B": B, "sum": A + B}) l = sorted(l, key=lambda x: x["sum"], reverse=True) a_total = 0 b_total = 0 for i, _l in enumerate(l): if i % 2 == 0: a_total += _l["A"] else: b_total += _l...
Aasthaengg/IBMdataset
Python_codes/p03141/s392520330.py
s392520330.py
py
351
python
en
code
0
github-code
90
40326666770
from selenium import webdriver from selenium.webdriver.common.by import By import time import math try: link = 'http://suninjuly.github.io/execute_script.html' browser = webdriver.Chrome() browser.get(link) def calc(x): return str(math.log(abs(12*math.sin(int(x))))) x_element = browser.f...
Lastti/stepik-auto-tests-course
lesson 2/lesson2_2step_6.py
lesson2_2step_6.py
py
981
python
en
code
0
github-code
90
73120664296
# -*-coding:gbk-*- import urlparse import re from bs4 import BeautifulSoup __author__ = 'yzh' class parse1(object): def __init__(self): pass def _get_new_urls(self,page_url,soup): new_urls=set() links=soup.find_all('a',href=re.compile(r'/view/\d+\.htm')) for link in links: ...
yzhihao/python_spier
parser_.py
parser_.py
py
1,294
python
en
code
0
github-code
90
74690463016
# -*- coding:utf-8 -*- """ 在pyctp2的父目录中, 执行 python red.py pyctp2.sbin.md2 md_exec """ import logging import threading import asyncio import json from pydispatch import dispatcher from autobahn.asyncio.websocket import WebSocketServerProtocol, WebSocketServerFactory from pyctp2.common.base import INFO_PATH,D...
danielscai/pyctp2
run.py
run.py
py
3,815
python
en
code
2
github-code
90
28857894731
from flask import Flask, request, abort from linebot import ( LineBotApi, WebhookHandler ) from linebot.exceptions import ( InvalidSignatureError ) from linebot.models import * import src.TextCommands.joke as joke import src.TextCommands.ping as ping import src.TextCommands.greeting as greeting impor...
William0506/Hual_Bot
app.py
app.py
py
4,467
python
en
code
1
github-code
90
18576039619
import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines in_n = lambda: int(readline()) in_nn = lambda: map(int, readline().split()) in_s = lambda: readline().rstrip().decode('utf-8') in_nl = lambda: list(map(int, readline().split())) in_nl2 = lambda H: [in_n...
Aasthaengg/IBMdataset
Python_codes/p03464/s231541662.py
s231541662.py
py
941
python
en
code
0
github-code
90
15597564016
import numpy as np import os import pandas as pd import math import itertools import shutil class SpecCense_Construction: def __init__(self,ordered_dicton_parameters,list_sensor_name, \ width,margin,saving_location_dict,option_remove): self.__ordered_dicton...
Ranim-94/Stage_Cense_2020
Code/Classes_and_Functions/Class_Data_Building.py
Class_Data_Building.py
py
13,394
python
en
code
1
github-code
90
17999922319
A, B, C = map(int, input().split()) N = A % B M, i = 0, 2 while M != N: M = i * N % B if M == C: print("YES") break i += 1 else: print("NO")
Aasthaengg/IBMdataset
Python_codes/p03730/s424999004.py
s424999004.py
py
172
python
en
code
0
github-code
90
31746551226
import os, sys import numpy as np import torch from torchvision import datasets, transforms from sklearn.utils import shuffle def get(seed=0, fixed_order=False, pc_valid=0, tasknum = 5): if tasknum>5: tasknum = 5 data = {} taskcla = [] size = [1, 28, 28] # Pre-load # MNIST mea...
csm9493/UCL
dataloaders/split_mnist.py
split_mnist.py
py
2,893
python
en
code
32
github-code
90
21156941205
# # @lc app=leetcode.cn id=82 lang=python # # [82] 删除排序链表中的重复元素 II # # @lc code=start # Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def deleteDuplicates(self, head): """ ...
paterlisia/leetcode-solution
src/Python/Linked-List/82.删除排序链表中的重复元素-ii.py
82.删除排序链表中的重复元素-ii.py
py
774
python
en
code
9
github-code
90
44112736859
import cProfile import io from multiprocessing import Process import pstats import time from aiokafka import AIOKafkaProducer import asyncio async def send_many(): text = b"1234567891" * 1000 producer = AIOKafkaProducer( bootstrap_servers="localhost:29092", max_batch_size=65535, ling...
dream2333/fastspider
bench/confluent.py
confluent.py
py
805
python
en
code
0
github-code
90
14159796599
# Importing Modules # -All Python programs can call a basic set of functions, called built-in functions # -incl. print(), input(), len(), etc. # -Python also comes with a set of modules called the 'standard library' # -Each module is a Python program that contains a related group of functions that can be embedded ...
SkyCHarris/automate_python
flow_control2/importing_modules_ending_programs4.py
importing_modules_ending_programs4.py
py
1,369
python
en
code
0
github-code
90
31607510585
import datetime from celery import shared_task from django.conf import settings from django.utils import timezone from core.utils import send_html_email from transcriber.exceptions import TranscriptionFailureException from transcriber.models import AudioFile from transcriber.services import AudioFileS3TranscriptionSe...
planeks/files-transcription-api
src/transcriber/tasks.py
tasks.py
py
1,558
python
en
code
0
github-code
90
39407318759
# coding: utf-8 # # Version info # >>conda -V # conda 4.3.21 # >>python --version # Python 3.5.2 :: Anaconda custom (x86_64) ########################### # imports ########################### import matplotlib.pyplot as plt import numpy as np import sys import pylab # Make sure you link to these in your working direc...
wsdhrqqc/classcode
fall_2018/poleward_transport_fall2017_skeleton.py
poleward_transport_fall2017_skeleton.py
py
3,473
python
en
code
null
github-code
90
28151301591
import numpy, os from typing import Tuple, List from .c_core import CppVoxelGrid, CppMapper, AABB3, CppMeshDynTri2D from .c_core import cppSVG_Polyline from .c_core import TRI, QUAD, HEX, TET, LINE from .c_core import \ meshquad3d_voxelgrid, \ meshquad3d_subdiv, \ meshhex3d_voxelgrid, \ meshhex3d_subdiv,\ m...
nobuyuki83/pydelfem2
PyDelFEM2/msh.py
msh.py
py
9,735
python
en
code
10
github-code
90
1180318027
from .extensions import Options from .helpers import * from .layouts import sg, ButtonsAndStatus def scale_frames_layout(): return [ [sg.Text('Scale an image by percent. Scale step is additive and\n'+ 'is increment which each frame. If duplicate is checked,\n'+ 'then...
gorenje/pclxtool
gui/func_scale_frames.py
func_scale_frames.py
py
3,787
python
en
code
0
github-code
90
23815893307
from __future__ import annotations import sys import typing as t import uuid import click from globus_cli.parsing import ParsedIdentity if t.TYPE_CHECKING: import globus_sdk from globus_cli.services.auth import CustomAuthClient if sys.version_info >= (3, 8): from typing import Literal else: from t...
globus/globus-cli
src/globus_cli/commands/group/invite/_common.py
_common.py
py
1,847
python
en
code
67
github-code
90
10746452985
import torch from utils.iou import * import torch.multiprocessing as mp device = torch.device("cuda" if torch.cuda.is_available() else "cpu") from itertools import product import time def eval_single_image_recall(this_true_labels,this_det_labels,true_box,true_difficultie,det_box,det_score): #print(true_boxes[num]....
eric612/Mobilenet-YOLO-Pytorch
utils/eval_mAP.py
eval_mAP.py
py
11,002
python
en
code
30
github-code
90
40953264609
def solution(input_string): loners = [] # 외톨이 알파벳들을 저장할 리스트 # 각 알파벳별로 등장한 부분을 기록할 딕셔너리를 초기화합니다. positions = {} for char in input_string: positions[char] = [] # 문자열을 순서대로 탐색하면서, 각 알파벳이 등장한 위치를 기록합니다. for i in range(len(input_string)): char = input_string[i] posit...
jino1023/Algorithm-Test
programmers/외톨이알파벳.py
외톨이알파벳.py
py
1,855
python
ko
code
0
github-code
90
41662848867
from flask import Flask, render_template, request, jsonify import pandas as pd app = Flask(__name__) # Load your recipes data recipes_data = pd.read_csv("dataset_recipe.csv") # Load unique ingredients from unique_incredients.csv unique_ingredients = pd.read_csv("unique_ingredients.csv")["ingredient"].tolist() # Rep...
G-Robocraze/cooking
app.py
app.py
py
1,325
python
en
code
0
github-code
90
24369102488
from datetime import datetime from ncg.preprocess import build_and_save_sentence_vectors import torch import os if __name__ == "__main__": dir_in = os.path.join('data', 'flickr30k', 'captions', 'en') fnames = [ 'test_2016.1.en', 'test_2016.2.en', 'test_2016.3.en', 'test_2016.4.en', 'test_2016.5.en' ...
maartje/ImageCaptionGeneration
preprocess_test.py
preprocess_test.py
py
704
python
en
code
0
github-code
90
32282894117
import os from typing import Dict from typing import List from typing import Tuple import torch import yaml from torch import Tensor import utils.constants as constants def process_label_file(input_yaml_path: str, data_folder, train_data: bool, riib: bool = False, clip: bool = True) -> \ List[Dict]: """ ...
Marcelo00/traffic_light_detection
utils/utils.py
utils.py
py
7,388
python
en
code
0
github-code
90
71873603178
#!/usr/bin/env python3 # Python 3.9.5 # 02_read_with_multiple_worksheets.py # Dependencies import os import pandas path = 'C:\\Users\\user\\spreadsheets' # Spreadsheets are stored within this directory os.chdir(path) # ============================================================================================ # A...
fenceMeshwire/python_excel
02_read_with_multiple_worksheets.py
02_read_with_multiple_worksheets.py
py
1,058
python
en
code
1
github-code
90
71026282857
import argparse import logging import os import shlex import subprocess from build_migrator.builders._log_providers.console import ConsoleLogProvider from build_migrator.builders._log_providers.strace import StraceLogProvider from build_migrator.modules import Builder, EntryPoint logger = logging.getLogger(__name__)...
KasperskyLab/BuildMigrator
build_migrator/builders/generic_builder.py
generic_builder.py
py
6,441
python
en
code
30
github-code
90
17358693414
from bs4 import BeautifulSoup from common import * res = [HEADER] # ["bridge","srcchain","srctoken","dstchain","dsttoken","srctoken_contract","dsttoken_contract","srcholder","dstholder","isopen","fee_fixed","fee_percent","fee_minfee","fee_maxfee","minamount", "liquidity", "extra"] FOLDER = os.path.dirname(os.path.rea...
DeFiEye/BridgeEye
crosschain/layerswap.py
layerswap.py
py
2,540
python
en
code
45
github-code
90
6171661372
from typing import Optional from pydantic import BaseModel, Field from fastapi import FastAPI, HTTPException import numpy as np import re import os import mlflow import pandas as pd from mlflow.tracking import MlflowClient from sqlalchemy import create_engine import psycopg2 from psycopg2 import sql app = FastAPI() o...
yemoncada/mlops_diabetes
inference/inference.py
inference.py
py
10,290
python
en
code
0
github-code
90
18315365169
from collections import Counter,defaultdict,deque from heapq import heappop,heappush,heapify import sys,bisect,math,itertools,fractions,pprint sys.setrecursionlimit(10**8) mod = 10**9+7 INF = float('inf') def inp(): return int(sys.stdin.readline()) def inpl(): return list(map(int, sys.stdin.readline().split())) n,m = ...
Aasthaengg/IBMdataset
Python_codes/p02852/s188093940.py
s188093940.py
py
570
python
en
code
0
github-code
90
5781062610
class QuizBrain: def __init__(self,q_list): self.question_number = 0 self.question_list = q_list self.correct_answers = 0 self.wrong_answers = 0 def next_question(self): current_question = self.question_list[self.question_number] self.question_number...
jcamilovallejos/bootcamp_python
intermidate_quiz_game_start/quiz_brain.py
quiz_brain.py
py
1,027
python
en
code
0
github-code
90
33547828952
from typing import cast from pathlib import Path from constructs import Construct from aws_cdk import ( Stack, CfnOutput, Duration, aws_lambda as _lambda, aws_lambda_python_alpha as pylambda, aws_apigatewayv2_alpha as apigw2, aws_apigatewayv2_integrations_alpha as integrations, aws_apiga...
m3sh32/pillow
service/lib/api_stack.py
api_stack.py
py
2,154
python
en
code
1
github-code
90
32304118209
#This code is taking from a specific range of columns their values, delete all n/a and null values #and then add it to a user specify columns in excel #But as con, the code doesnt save the formulaes in a new file #so this should be used as a endway editing import openpyxl from openpyxl import Workbook from open...
Aleksandrengineer/python_practice
xlsmodif.py
xlsmodif.py
py
1,319
python
en
code
0
github-code
90
20382775351
import pyaudio import wave from scipy.io import wavfile p = pyaudio.PyAudio() info = p.get_host_api_info_by_index(0) numdevices = info.get('deviceCount') for i in range(0, numdevices): if (p.get_device_info_by_host_api_device_index(0, i).get('maxInputChannels')) > 0: if "Umik" in p.get_device_inf...
DanielQu1108/forJaime
Scripts/record.py
record.py
py
1,329
python
en
code
0
github-code
90
43125611767
from cmath import isnan import numpy as np import inc.Helpers.tools as tls import inc.coloring as clr import inc.Helpers.display as dsp def render_smooth(verts2d, vcolors, img): """Renders the image, using interpolate colors to achieve smooth color transitioning Parameters ---------- vert...
kpetridis24/image-rendering
inc/triangle_filling.py
triangle_filling.py
py
6,816
python
en
code
0
github-code
90
34356101480
# invoer v_stijn = int(input("snelheid van stijn: ")) v_kaat = int(input("snelheid van kaat: ")) afstand = int(input("afstand: ")) tot_afstand = 0 tijd = 0 #berekenen while tot_afstand < afstand: tijd += 1 tot_afstand = tot_afstand + v_kaat + v_stijn #uitvoer uitvoer = "Na {} s hebben Stijn en Kaat elkaar ont...
ArthurCallewaert/5WWIPython
07b_iteraties/Fietsen.py
Fietsen.py
py
355
python
nl
code
0
github-code
90
18480200299
n, m = map(int,input().split()) numbers = [{} for _ in range(n)] for i in range(m): p, y = map(int,input().split()) numbers[p-1][i] = y #pで県を指定して、iで順番の情報を保つ answers = {} for i in range(n): number = numbers[i] if len(number) == 0: continue new_number = sorted(number.items(), key = lambda x...
Aasthaengg/IBMdataset
Python_codes/p03221/s463530649.py
s463530649.py
py
636
python
en
code
0
github-code
90
70667384616
def knapnapSacknap(W, wt, val, n): knap = [[0 for x in range(W + 1)] for x in range(n + 1)] for i in range(n + 1): for w in range(W + 1): if i == 0 or w == 0: knap[i][w] = 0 elif wt[i-1] <= w: knap[i][w] = max(val[i-1] + knap[i-1][w-wt[i-1...
projeto-de-algoritmos/PD_Dupla10A
list5.py
list5.py
py
887
python
pt
code
0
github-code
90
1769339104
import matplotlib.pyplot as plt, numpy as np x = range(1, 11) y = range(1, 11) plt.scatter(x, y) x1 = np.arange(-1000, 1000, 1) plt.plot(x1, x1**2) plt.show()
rodrigoargondizo/SEII-RodrigoFariaArgondizo
Semana04/Exercicio03/plot0x.py
plot0x.py
py
163
python
en
code
0
github-code
90
22890619304
import os from _operator import and_ from datetime import datetime from fdfs_client.client import Fdfs_client from flask import Blueprint, render_template, request, session, jsonify # from sqlalchemy import all_ from App.models import Area, Facility, House, HouseImage from utils import status_code from utils.settings i...
htengteng/Ihome
ihome/App/house_views.py
house_views.py
py
6,540
python
en
code
0
github-code
90
13225317498
#!/usr/bin/env python3 # # Bank Server application # Jimmy da Geek import socket import threading import signal import sys HOST = "127.0.0.1" # Standard loopback interface address (localhost) PORT = 65432 # Port to listen on (non-privileged ports are > 1023) ALL_ACCOUNTS = dict() # initialize an emp...
maggiehollis/ATM-Banking-Server
bank_server.py
bank_server.py
py
10,521
python
en
code
0
github-code
90
38090717167
import streamlit as st import pandas as pd import numpy as np import gensim st.title('映画レコメンド') # 映画情報の読み込み movies = pd.read_csv("data/movies.tsv", sep="\t") # 学習済みのitem2vecモデルの読み込み model = gensim.models.word2vec.Word2Vec.load("data/item2vec.model") # 映画IDとタイトルを辞書型に変換 movie_titles = movies["title"].tolist() movie_i...
yamazakihironori/movie_recommender_hy
app.py
app.py
py
3,832
python
en
code
0
github-code
90
18399059139
import sys import math from collections import defaultdict sys.setrecursionlimit(10**7) def input(): return sys.stdin.readline()[:-1] mod = 10**9 + 7 def I(): return int(input()) def II(): return map(int, input().split()) def III(): return list(map(int, input().split())) def Line(N,num): if N<=0: for...
Aasthaengg/IBMdataset
Python_codes/p03033/s882967802.py
s882967802.py
py
1,083
python
en
code
0
github-code
90
11961762706
#!/usr/bin/python import time import RPi.GPIO as io io.setmode(io.BCM) led = 19 lane1 = 24 lane2 = 25 lane3 = 26 io.setup(led, io.OUT) io.setup(lane1, io.IN, pull_up_down=io.PUD_UP) io.setup(lane2, io.IN, pull_up_down=io.PUD_UP) io.setup(lane3, io.IN, pull_up_down=io.PUD_UP) io.output(led, io.LOW) while True: ...
wcameronbowen/pinewood-derby
sensor-test.py
sensor-test.py
py
561
python
en
code
0
github-code
90
24039564042
# caesar cipher program # enter messag and step and receive encoded or decoded message uppercases = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] lowercases = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', '...
floor3d/software-projects
caesar-cipher/caesar.py
caesar.py
py
1,091
python
en
code
0
github-code
90
17650268045
from cgitb import reset import sys import tkinter as tk from tkinter import * from tkinter.font import Font from traceback import print_tb from board import Board, read_board_from_file, popupmsg from boat import Boat import numpy as np import graphics from setuptools import Command def rules(): text = """Battle...
IviIvanova18/Battleship
Graphics/graphics.py
graphics.py
py
7,014
python
en
code
2
github-code
90
73551176615
print('---Welcom to Babs Calculator---') while True: print(''' ~press 1 for addition ~press 2 for substraction ~press 3 for multiplication ~press 4 for division ~press 0 for quit''') choice=int(input('Choose your option: ')) if choice==1: num1=input('Enter first number: ') num2=input('Enter sec...
bhavanatheruvath/Babs-Calculator
mycalcu.py
mycalcu.py
py
1,369
python
en
code
0
github-code
90
3485725884
g = lambda x : 2 * x + 1 print (g(5)) h = lambda x , y : x + y print (h(5,6)) list(filter(None, [1, 0, False, True])) #过滤False的数 def odd(x): return x % 2 temp = range(10) show=filter(odd, temp) print (list(show)) show=list(filter(lambda x: x % 2 ,range(10))) #将range里的值带入前边的函数,并筛选出结果为True的range print (show) show=li...
MuYi0420/newstudy
python/lambda.py
lambda.py
py
457
python
zh
code
0
github-code
90
23467691482
from tltk import nlp import tltk import codecs def run(sen): test=sen#ประโยคที่ใช้ทดสอบ test=tltk.nlp.word_segment(test)#ตัดคำ test=test.replace("<s/>","")#เอา</s>ออกจากประโยค result = sentolist(test) return result #ทำให้ประโยคจากการตัดคำกลายเป็นlist def sentolist(test): stat=0 end=...
darthice/thainer
ngram.py
ngram.py
py
2,950
python
th
code
0
github-code
90
18261204709
import numpy as np a = [list(map(int, input().split())) for _ in range(3)] n = int(input()) b = [int(input()) for i in range(n)] for i in range(3): for j in range(3): for k in range(n): if a[i][j] == b[k]: a[i][j] = 0 c = [] c.append(np.sum(a,axis = 0)) c.append(np.sum(a,axis = ...
Aasthaengg/IBMdataset
Python_codes/p02760/s062510441.py
s062510441.py
py
519
python
en
code
0
github-code
90
73276530855
""" AWS DeepRacer reward function """ import math # Constants DEBUG_LOG_ENABLED = True # Action space constants MAX_SPEED = 8.0 MAX_STEERING_ANGLE = 30.0 # TUNING: Adjust these to find tune factors affect on reward # # Reward weights, always 0..1. These are relative to one another SPEED_FACTOR_WEIGHT = 1.0 WHEEL_FA...
cdthompson/deepracer-training-2019
models/sep/iota/reward.py
reward.py
py
9,929
python
en
code
42
github-code
90
4346485533
import numpy as np from keras import optimizers import vggmodel from tensorflow.keras.preprocessing import image as image_utils from tensorflow.keras.models import load_model import h5py from keras.models import load_model import cv2 # 15 is Next # 16 is Previous # 17 is start # 18 is stop # class_names=["Stop navigat...
bismabatool/Visual-Speaker
lipreading/predict.py
predict.py
py
2,228
python
en
code
0
github-code
90
13590358498
import torch from torch_geometric.transforms import Distance from torch_geometric.data import Data def test_distance(): assert Distance().__repr__() == 'Distance(norm=True, max_value=None)' pos = torch.tensor([[-1, 0], [0, 0], [2, 0]], dtype=torch.float) edge_index = torch.tensor([[0, 1, 1, 2], [1, 0, 2,...
Cyanogenoid/fspool
graphs/test/transforms/test_distance.py
test_distance.py
py
867
python
en
code
44
github-code
90
8417668797
from threading import Thread, Lock from simplespider.utils import singleton from time import ctime, sleep def lock(lock_obj): def decorator(f): def inner(*args, **kwargs): try: lock_obj.acquire() return f(*args, **kwargs) finally: loc...
lingweimin/SimpleSpider
simplespider/threadpool.py
threadpool.py
py
3,900
python
en
code
0
github-code
90
70458448938
import json import os import requests import unittest import core import extensions.mangadex.account as account import extensions.mangadex.ext as mangadexExt from models import Chapter, Manga, Tag, SearchResult, ParseResult # testing methods defined in Mangadex class class TestExtension(unittest.TestCase): # va...
Benjababe/GenericMangoDownloader
tests/test_mangadex.py
test_mangadex.py
py
7,265
python
en
code
2
github-code
90
4175385469
class Solution(object): def maxProfit(self, k, prices): """ :type k: int :type prices: List[int] :rtype: int """ if k == 0 or len(prices) < 2: return 0 if k >= len(prices) // 2: result = 0 for i in range(1, len(pric...
HopeCheung/Programing-materials
leetcode/leetcode188(sell stock).py
leetcode188(sell stock).py
py
1,022
python
en
code
0
github-code
90
35960767100
from Service import Service from CommonStrings import ApacheProjectsData, ClusterSise from Log.Logger import LoggerInstance def handle_page_repositories(repositories_list, s, log): r"""This function get a list of repositories data, save it, and extract and save the topics and contributors of each :param repos...
shaharkr/DevelopersBugsMatching
main.py
main.py
py
2,280
python
en
code
0
github-code
90
18254466259
from collections import deque D1 = {i:chr(i+96) for i in range(1,27)} D2 = {val:key for key,val in D1.items()} N = int(input()) que = deque([("a",1)]) A = [] while que: x,n = que.popleft() if n<N: imax = 0 for i in range(len(x)): imax = max(imax,D2[x[i]]) for j in range(1,min...
Aasthaengg/IBMdataset
Python_codes/p02744/s764691633.py
s764691633.py
py
468
python
en
code
0
github-code
90
27007893037
# -*- coding: utf-8 -*- from plone.app.robotframework.testing import REMOTE_LIBRARY_BUNDLE_FIXTURE from plone.app.testing import applyProfile from plone.app.testing import FunctionalTesting from plone.app.testing import IntegrationTesting from plone.app.testing import PLONE_FIXTURE from plone.app.testing import PloneSa...
IMIO/urban.vocabulary
src/urban/vocabulary/testing.py
testing.py
py
1,940
python
en
code
0
github-code
90
9001724211
from aws_cdk import ( core, aws_codecommit as codecommit, aws_codebuild as codebuild, aws_events_targets as targets, aws_events as events, aws_lambda as _lambda ) from aws_cdk.aws_events import EventField class PRConstruct(core.Construct): def __init__(self, scope: core.Const...
quixoticmonk/PRworkflow-CDK
lib/pr_construct.py
pr_construct.py
py
5,120
python
en
code
0
github-code
90
23055271595
import os import time import threading from PIL import ImageTk, Image import tkinter as tk from tkinter import Label, Entry, Frame from pyPS4Controller.controller import Controller import mount #Global variables USER_DIR = "/home/" + os.popen("whoami").readlines()[0].split("\n")[0] + "/" #dinamic user ROMS_DIR = USE...
RogelioHK/equipo2-proyecto-consolaRetro-Pi
filesystem/emu.py
emu.py
py
14,974
python
en
code
0
github-code
90
74213760937
from django import forms from .models import Testimonial class testimonialForm(forms.ModelForm): """ Form to add testimonial. """ class Meta: """ Form has all required fields from Testimonial model """ model = Testimonial fields = ('client_name', 'client_testimo...
Louibens/PP5-Avenue_Louise
testimonials/forms.py
forms.py
py
354
python
en
code
0
github-code
90
36518062549
def prime(x): count=0 for i in range(1,x+1): if x%i==0: count+= 1 return count t=int(input()) for i in range(t): n=int(input()) x=m=n while prime(n)!=2: n += 1 y=n-m while prime(x)!=2: x -= 1 z=m-x if y>z: print(x) elif y<z: ...
20A91A0210/codemind-python
Nearest_Prime.py
Nearest_Prime.py
py
416
python
en
code
0
github-code
90
10390595582
from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument("--source", type=str, required=True, help="where is the data scraped from, to decide which core to insert it in") args = parser.parse_args() if args.source == "Twitter": import tweepy import pandas as pd import time con...
rbose99/CZ4034-Information-Retrieval
data/scrape_gui.py
scrape_gui.py
py
2,841
python
en
code
1
github-code
90
10402436956
import pandas as pd import numpy as np import sys cluster_file, cdc_file, hivtrace_file, patient_file, seq_file, sierra_file, recency_file, pvl_file, out_file = sys.argv[1:] clusters = pd.read_csv(cluster_file, sep="\t", index_col="StudyID") cdc = pd.read_csv(cdc_file, index_col="StudyID") hivtrace = pd.read_csv...
kantorlab/hiv-real-time-phylogeny
template-phylo/reports/individual/individuals.py
individuals.py
py
1,778
python
en
code
0
github-code
90
17728033101
#! /usr/bin/python3 __author__ = "Xinyue Tan <xt2215" __date__ = "$Sep 17, 2018" def classify_infrequent_word_rare(word, word_set): if word in word_set: return word; else: return "_RARE_"; def classify_infrequent_word_customized(word, word_set): if word in word_set: return word;...
Christine-Tan/4705NLP
hw1/classify_infrequent_word.py
classify_infrequent_word.py
py
1,997
python
en
code
1
github-code
90
17263723120
from .ContentWarningTable import ContentWarningTable from ..movies.MovieStub import MovieStub from ..cw.ContentWarning import ContentWarning import boto3 import os from typing import List, Dict, Union class MovieTable: DYNAMO_DB_CLIENT = boto3.client("dynamodb") MOVIES_TABLE = os.environ["MOVIES_TABLE"] ...
ContentWarnings/Backend
src/databases/MovieTable.py
MovieTable.py
py
3,570
python
en
code
1
github-code
90
33466843885
# import the finance screener import ScreenMachine as sm from ScreenerPath import * # import database and parsing library import mysql.connector import json # loading json MySQL configurations and database with open("/home/richpaulyim/Documents/configs/configyf.json") as json_data: data = json.load(json_data) sq...
richpaulyim/Web-Briareus
Stock-Hits/ExtractInsertFinance.py
ExtractInsertFinance.py
py
2,051
python
en
code
1
github-code
90
38134303240
import pygame from View.GameStateENUM import GameState as gs, ButtonType as bt class AbstractUIDropdownButton(): def __init__(self, gameWindow, buttonColor, buttonText, buttonWidth, buttonHeight, displayX, displayY, viewManager): #button properties self.gameWindow = gameWindow self.buttonColor = button...
Miko3o/maze_solver
part_3_b/View/UIDropdownButtons/AbstractUIDropdownButton.py
AbstractUIDropdownButton.py
py
3,643
python
en
code
0
github-code
90
15653096378
from app import app from flask import Flask, session, redirect, render_template, flash, url_for, request from app.forms import LoginForm from app.models import Users from tools import login_require @login_require.login_message_req @app.route("/login/", methods=['GET', 'POST']) def login(): form = LoginForm() ...
liwg1995/NiceCatMonitor
app/views.py
views.py
py
1,120
python
en
code
0
github-code
90
1869259227
import cashPayment import cardPayment class OrderCtrl: def __init__(self): self.card = cardPayment.CardPayment() self.cash = cashPayment.CashPayment() self.amount = 0 def order(self, price): print(price, "원의 결제를 진행하겠습니다") self.amount = price ch = int(inp...
yong4980/KMU_Shopping_Mall
orderCtrl.py
orderCtrl.py
py
621
python
en
code
0
github-code
90
18461120129
from sys import stdin def main(): n = int(input()) h = list(map(int, input().split())) #print(n, h) L = [0 for _ in range(n)] L[0] = 0 L[1] = abs(h[1] - h[0]) for ind in range(2, n): L[ind] = min(L[ind - 1] + abs(h[ind] - h[ind - 1]), L[ind - 2] + abs(h[ind] - h[ind - 2])) print(L[-1]) if __...
Aasthaengg/IBMdataset
Python_codes/p03160/s843039729.py
s843039729.py
py
369
python
en
code
0
github-code
90
30779057834
from django.core.cache import cache import urllib.request import urllib.error import xml.dom.minidom import hashlib import requests import json from urllib.parse import quote def smsseng(mobile,msg,code): url = "http://cf.51welink.com/submitdata/Service.asmx/g_Submit" ontent = "'尊敬的用户您好,您的{}验证码为{},三分钟内有效!'"...
lxb0323/township_bsckstage
utils/yanzheng/duanxin.py
duanxin.py
py
3,312
python
en
code
0
github-code
90
74397364456
from selenium import webdriver from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from time import sleep import random # 要搜索的网址,如百度、谷歌...shiyixia url = 'https://www.baidu.com/' # 要搜索的关键字,以数组的形式填入 keyword_...
Jarthong/seo
atuo_search_random.py
atuo_search_random.py
py
1,379
python
en
code
0
github-code
90
1166157718
import sys import hellopython def testFunc(): name = "LiuXing" gender = 'male' arr = [1, 2, 3, 4] dic = {'x': 1, 'y': 2, 'z': 3} arr.pop() print(name, gender, arr, dic) testFunc() filename = "test.txt" filepath = "C:/Users/Administrator/Desktop/" with open(filepath + filename) as testFile: print(testFile.read()...
MiataXing/Freestyle
src/py/180424.py
180424.py
py
421
python
en
code
1
github-code
90
73070401896
from marshmallow import Schema, fields, post_load from folker.module.file.action import ( FileMethod, FileStageAction, FileStageReadAction, FileStageWriteAction, FileStageDeleteAction, ) class FileActionSchema(Schema): type = fields.String() method = fields.String() file = fields.Str...
felipehernandez/folker-test
folker/module/file/schema.py
schema.py
py
658
python
en
code
2
github-code
90
13456237855
import os ventMap = {} # x: [y's] with open(os.path.join(os.path.dirname(__file__), "input2.txt")) as f: for line in f: processedLine = line.replace(' -> ', ',') numbers = [(int)(val) for val in processedLine.split(',')] if numbers[0] != numbers[2] and numbers[1] != numbers[3]: ...
JDaniel41/advent-of-code-2021
day05/main.py
main.py
py
2,369
python
en
code
0
github-code
90
26272473934
k = int(input()) inputStr = str(input()) maxLen = 0 prevStateLen = 0 state = "N" stateLen = 0 for i in range(0, k): part = inputStr[i] if not state == part: prevStateLen = stateLen state = part stateLen = 0 stateLen += 1 maxLen = max(maxLen, min(prevStateLen, stateLen) * 2) print(maxLen)
spotky1004/Coding-Problem-Solving
Baek/contest/end/4th UNIST Algorithm Programming Contest Uni-CODE 2022 Open Contest/A.py
A.py
py
311
python
en
code
2
github-code
90
70099952938
import boto3 s3 = boto3.client('s3') Bucket = '<your bucket>' Key = '<s3 bucket prefix>/pagecounts-20100212-050000.gz' SQLstr = "select s._1,s._4 from s3object s where CAST(s._4 as INTEGER)>50000 limit 20" """ S3 SELECT command SQL refer to: https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-glacier-select-sql-referen...
hawkey999/BigData-ImmersionDay
Lab1-S3Select/S3SelectDemo-csv.py
S3SelectDemo-csv.py
py
1,859
python
en
code
4
github-code
90
70611673258
""" @Author: Rossi Created At: 2021-02-21 """ import json import time from mako.template import Template from Broca.faq_engine.index import ESIndex, VectorIndex from Broca.message import BotMessage class FAQAgent: def __init__(self, agent_name, es_index, vector_index, threshold, topk, prompt_threshold, ...
lawRossi/Broca
Broca/faq_engine/agent.py
agent.py
py
2,897
python
en
code
4
github-code
90
8711155948
''' Created on Oct 18, 2010 @author: guillaume.aubert@gmail.com ''' import sys import os import binascii from bitstring import BitString def dirwalk(dir): """ Walk a directory tree, using a generator. This implementation returns only the files in all the subdirectories. Beware, this is a generator...
gaubert/rodd
src/eumetsat/tools/lrit_grib_extractor.py
lrit_grib_extractor.py
py
4,355
python
en
code
3
github-code
90
9164856725
import time start_time = time.time() # 2 # / \ # 1---3 # | X | # 0---4 neighbours = [{1, 3, 4}, {0, 2, 3, 4}, {1, 3}, {0, 1, 2, 4}, {0, 1, 3}] def run(before, current): if len(before) == 8: print("Done all: " + str(before)) return [before] if len({tuple(sorted([i, current])) for i in neigh...
rrickfox/AdventOfCode
haus_nikolaus.py
haus_nikolaus.py
py
1,043
python
en
code
0
github-code
90
33485103606
'''Computing ASSIGNMENT-3''' # Question 1 - Python program to count the number of occurrences of each word or character in the string entered by the user as follows: from subprocess import list2cmdline print("\nQuestion-1\n") str = input("Type Your String: ") str_set1 = set(str) str_list = str.split() s...
vipinbansal179/Pec-Computing
Assignment3.py
Assignment3.py
py
6,016
python
en
code
0
github-code
90
34872756170
import pytest from pandas import ( Interval, Timedelta, Timestamp, ) class TestContains: def test_contains(self): interval = Interval(0, 1) assert 0.5 in interval assert 1 in interval assert 0 not in interval interval_both = Interval(0, 1, "both") asse...
pandas-dev/pandas
pandas/tests/scalar/interval/test_contains.py
test_contains.py
py
2,354
python
en
code
40,398
github-code
90
1789142955
# https://leetcode.com/problems/binary-tree-right-side-view/ # Recursive Approach: TC - O(N), SC - Auxillary O(N) # 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 Solut...
danish-faisal/Striver-s-SDE-Sheet
Binary Tree - Day 17/left-view-of-binary-tree.py
left-view-of-binary-tree.py
py
968
python
en
code
0
github-code
90
424982169
''' May 2017 @author: Burkhard ''' import tkinter as tk from tkinter import ttk from tkinter import scrolledtext from tkinter import Menu from tkinter import Spinbox from tkinter.messagebox import showinfo #----------------------------------------------------------- # Callback functions #-----------------------------...
PacktPublishing/Python-GUI-Programming-Cookbook-Second-Edition
Chapter11/Ch11_Code/GUI_Complexity_end_tab3_multiple_notebooks.py
GUI_Complexity_end_tab3_multiple_notebooks.py
py
8,126
python
en
code
311
github-code
90
39736052903
import sys input = sys.stdin.readline for i in range(int(input())): n = int(input()) N = [] d = 2 while n != 1: if n % d != 0: d += 1 else: n //= d N.append(d) set_N = list(set(N)) set_N.sort() for i in set_N: print(i, N.count(...
lyong4432/BOJ.practice
#2312.py
#2312.py
py
324
python
en
code
0
github-code
90
5859161460
from revChatGPT.V1 import Chatbot from os import getenv from threading import Thread from uuid import uuid4 from func import okreturn, jsonerror chatbot = Chatbot(config={ 'session_token': getenv('CHATGPT_TOKEN') }) dic = {} def get(uu): try: a = dic[uu] if (a['finish']): dic.pop...
simsum929/webchatgpt
chat.py
chat.py
py
787
python
en
code
null
github-code
90
70971501097
""" Windows Defender """ import os import re import subprocess from common.interface_scanner import IScanner from common.response import Response from common.enum_returncode import Returncodes class WindowsDefender(IScanner): """ Scanner as Windows Denfer """ def __init__(self) -> None: self....
JSXRED/rvp
common/scanner/windowsdefender.py
windowsdefender.py
py
1,848
python
en
code
3
github-code
90
70213367656
import matplotlib.pyplot as plt import numpy as np import scipy.signal as spsig from cebl import util from . import bandpass from . import windows def downsample(s, factor): """Downsample a discrete signal by a given factor. Args: s: Numpy array containing the discrete signal to downsample. ...
idfah/cebl
cebl/sig/resamp.py
resamp.py
py
10,883
python
en
code
10
github-code
90
27706203505
from codeinterpreterapi import CodeInterpreterSession from codeinterpreterapi import File class CodeInterpreter: def __init__(self, db_manager): self.db_manager = db_manager async def process(self, prompt, uploaded_files): files = [] for uploaded_file in uploaded_files: fi...
mahm/codeinterpreter-streamlit
code_interpreter.py
code_interpreter.py
py
718
python
en
code
33
github-code
90
40509118705
from qparser import * import json import requests class TestRequestParser: """The class test each method from class RequestParser from qparser.py""" REQUESTPARSER = RequestParser() REQUESTPARSERTWO = RequestParser() REQUESTPARSERTHREE = RequestParser() REQUESTPARSERFOUR = RequestParser() ...
elmasta/GPBot
test_qparser.py
test_qparser.py
py
9,307
python
en
code
0
github-code
90
29394966755
operators=[] #operatörlerin olduğu stack final=[] #son stack includes=False #gelen operatörün kendisinden önce parantez içerip içermediğini belirler, içeriyorsa true içermiyorsa false index=0 #her karakter atlanıldığında index değerinin artışı burada tutulur, özellikle birden fazla basamaklı sayılar olduğunda kullanış...
lullabytuls/calculator-design-with-python-using-stack-
main.py
main.py
py
6,225
python
tr
code
0
github-code
90
72779923818
from rest_framework import serializers from invitesys.models import InviteContractSign class ContractInfoSerializer(serializers.ModelSerializer): class Meta: model = InviteContractSign fields = ('id', 'ctid', 'generate_date', 'sign_status_A', 'sign_status_B', 'content') extra_kwargs = { ...
fhydralisk/walibackend
invitesys/serializers/contract.py
contract.py
py
406
python
en
code
1
github-code
90
3460975198
import json from copy import deepcopy from enum import Enum from os import environ import httpx from lib.durak.exceptions import ActionNotDefined, IllegalAction from lib.durak.game import AI, Game def noop(*, from_state): return Game.deserialize(from_state).serialize() def attack(*, from_state, user, payload):...
maximpertsov/durak-sockets
lib/durak/__init__.py
__init__.py
py
4,104
python
en
code
0
github-code
90
29542456617
# -*- coding: utf-8 -*- # @Time : 2021/9/30 15:40 # @Github : https://github.com/monijuan # @CSDN : https://blog.csdn.net/qq_34451909 # @File : 700. 二叉搜索树中的搜索.py # @Software: PyCharm # =================================== """给定二叉搜索树(BST)的根节点和一个值。 你需要在BST中找到节点值等于给定值的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 NULL。 例如, 给定二叉...
monijuan/leetcode_python
code/AC1_easy/700. 二叉搜索树中的搜索.py
700. 二叉搜索树中的搜索.py
py
1,901
python
zh
code
0
github-code
90
5544452822
# 안전 영역 import sys si = sys.stdin.readline N = int(si()) # 상하좌우 dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)] # 1. 2차원 그래프 생성하기 graph = [[] for i in range(N)] answer = -1 maxi = -1 for i in range(N): tmp = list(map(int, si().split())) graph[i] = tmp # 2차원 그래프의 최댓값 체크하기 for i in graph: a = max(i) maxi = m...
SteadyKim/Algorism
language_PYTHON/백준/BJ2468.py
BJ2468.py
py
1,547
python
ko
code
0
github-code
90
2234268098
class Node: def __init__(self, found=False, nodes={}): self.found = found self.nodes = nodes def addWord(self, word): if word == "": self.found = True else: c = word[0] if c not in self.nodes: self.nodes[c] = Node(nodes={}) ...
vyshor/LeetCode
Word Break II.py
Word Break II.py
py
1,451
python
en
code
0
github-code
90