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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
14854443648 | from __future__ import absolute_import, unicode_literals
from stravalib.attributes import EntityAttribute, SUMMARY, DETAILED
from stravalib.model import Athlete
from stravalib.tests import TestBase
class EntityAttributeTest(TestBase):
def setUp(self):
super(EntityAttributeTest, self).setUp()
def te... | swuerth/StravaDevChallenge | strava-club-highlights-gcloud/env/lib/python2.7/site-packages/stravalib/tests/test_attributes.py | test_attributes.py | py | 1,187 | python | en | code | 0 | github-code | 13 |
2839469983 | #-*- coding: utf-8 -*-
from .constant import *
from .function import formatDateTime, formatSize
from .tag import Tag
class Area:
InvalidPosition = 0xFFFFFFFFFFFFFFFF
def __init__(self):
self.start = Area.InvalidPosition
self.end = Area.InvalidPosition
class Record:
ModifTime = 1
Fi... | gefranks/amuletools | record.py | record.py | py | 8,932 | python | en | code | 0 | github-code | 13 |
72366449617 |
class Group:
def __init__(self,name):
self.name = name
def addMembers(self,m1, m2,m3):
self.member1 = m1
self.member2 = m2
self.member3 = m3
def getInfo(self):
print("Group name: ", self.name)
print("Members : ")
print(self.member1.getInfo())
... | karimsuzon/Developing-Python-Application | week8_UML_CODE_GROUP_MEMBER.py | week8_UML_CODE_GROUP_MEMBER.py | py | 796 | python | en | code | 0 | github-code | 13 |
32402704385 | import subprocess
import json
import os
import sys
import cv2
from scipy.io import wavfile
import time
import numpy as np
from scipy.signal import fftconvolve
from lib import ImageProcessingFunctions as ip
import shutil
import pickle
import datetime
class SyncVideoSet:
def __init__(self, path_in, mode=1):
... | lkoopmans/3D_reconstruction_stationary_array | lib/SyncVideoSet.py | SyncVideoSet.py | py | 26,269 | python | en | code | 0 | github-code | 13 |
4320583991 | ##############################################################################
# Copyright (C) 2018, 2019, 2020 Dominic O'Kane
##############################################################################
from math import sqrt, exp, log
from enum import Enum
from numba import njit, float64, int64
import nump... | domokane/FinancePy | financepy/models/process_simulator.py | process_simulator.py | py | 14,570 | python | en | code | 1,701 | github-code | 13 |
26972998662 | # lets say we have 2 variables arrange in following way
name = "Anurag" # <- global name
def foo(): # <- global name
# global name
name = "Sayan" # <- local variable
def bar():
foo()
if something:
name = "lksdjfks"
foo()
print(name)
if something:
name = "lksdjfks"
# when you initailize any name without any... | annup76779/python5tutor | sayan/old_files/scopes.py | scopes.py | py | 899 | python | en | code | 0 | github-code | 13 |
21935309326 | import numpy as np
import pickle
from utils import get_immediate_subdirectories
root_dir = './data_dir'
data_file = 'data.txt'
targets_file = 'index_target.txt'
features_file = 'index_features.txt'
split_test = 0.15
split_valid = 0.15
dirs = get_immediate_subdirectories('./data_dir')
for dir in dirs:
data_path ... | MJHutchinson/BayesMLP | utils/convert_dataset.py | convert_dataset.py | py | 1,426 | python | en | code | 1 | github-code | 13 |
26717381504 | from sqlalchemy.orm import declarative_base
from sqlalchemy import Integer, Column, VARCHAR, DECIMAL
Base = declarative_base()
class Product(Base):
__tablename__ = 'product'
id: int = Column(Integer, primary_key=True)
name = Column(VARCHAR(20))
price = Column(DECIMAL)
def __str__(self):
... | ashcherbyna1/hw_anastasiia_shcherbyna | models/product.py | product.py | py | 386 | python | en | code | 0 | github-code | 13 |
70095219537 | import setuptools
with open('README.md', 'r') as fh:
long_description = fh.read()
setuptools.setup(
name='dsplib',
version='1.0.0',
author='Zach Beever',
author_email='zbeever@bu.edu',
description='Small DSP library.',
long_description=long_description,
long_description_content_type='t... | zbeever/dsplib | setup.py | setup.py | py | 920 | python | en | code | 0 | github-code | 13 |
22334472955 | #Leetcode 925. Long Pressed Name
class Solution:
def isLongPressedName(self, name: str, typed: str) -> bool:
i = 0
j = 0
n = len(name)
m = len(typed)
while j<m:
if i<n and name[i] == typed[j]:
i+=1
elif j == 0 or type... | komalupatil/Leetcode_Solutions | Easy/Long Pressed Name.py | Long Pressed Name.py | py | 405 | python | en | code | 1 | github-code | 13 |
2495577781 |
import tkinter as tk
from tkinter import *
import socket
import webbrowser
def helloWorld():
print('helloWorld')
def findIP():
print(socket.gethostbyname(socket.gethostname()))
def getIp():
print('##')
## Create Buttons
def createBtnQuit(name1):
root = tk.Tk()
root.geometry('500x700')
btn = tk... | nzevgolisda/tkinter.py | main.py | main.py | py | 1,930 | python | en | code | 0 | github-code | 13 |
73260107856 | #from _2factor_wrapper import _2Factor
from _2factor_wrapper.Configure2Factor import Configure2Factor
import unittest
def verify_api():
"""Test the api by verifying the API"""
instance = _2Factor(api_key='293832-67745-11e5-88de-5600000c6b13')
response = instance.verify()
assert isinstance(response, dict)
assert... | chiseledCoder-zz/2factor-py | tests/tests.py | tests.py | py | 837 | python | en | code | 0 | github-code | 13 |
71984698257 | # SWEA 1486번 장훈이의 높은 선반
'''
높이가 B인 선반
점원의 키는 Hi, 탑을 쌓아서 선반 위의 물건을 사용할 것
탑의 높이는 점원이 1명일 경우 그 점원의 카와 같고
2명 이상일 경우 탑을 만든 모든 점원의 키의 합과 같음
가장 낮은 탑의 높이
'''
def backtrack(n,sum_):
global min_sum
# 가지치기
if sum_ >= min_sum: # 합이 최소값을 넘어가면 리턴
return
if B == min_sum: # B와 완전 일치하면 리턴
... | euneuneunseok/TIL | SWEA/D4/1486. 장훈이의 높은 선반/장훈이의 높은 선반.py | 장훈이의 높은 선반.py | py | 1,140 | python | ko | code | 0 | github-code | 13 |
13885045762 | import json
import os
import copy
#format start,end to :00 or :30 format
def processHour(start,end):
#set start time to kill in schedule
if (start % 100) >= 0 and (start % 100) < 30 :
start = ((start/100)) *100
else :
start = ((start/100)) *100 + 30
#set end time to kill in schedule
... | ikendoit/Langara-Scraper | roomLangara/getDays.py | getDays.py | py | 3,720 | python | en | code | 0 | github-code | 13 |
43026577034 | from aiogram import Bot, Dispatcher, types
from aiogram.utils import executor
bot = Bot(token='1650077573:AAHfZMCUxCyMdBE42gpK9JPRcRVD0O2k_gQ')
dp = Dispatcher(bot)
@dp.message_handler()
async def get_message(message: types.Message):
chat_id = message.chat.id
text = 'Какой-то другой текст'
sent_message ... | pol1969/aiogram | app.py | app.py | py | 443 | python | en | code | 0 | github-code | 13 |
28568289611 | import os
from typing import Any, Union, List
from pibble.api.configuration import APIConfiguration
from pibble.api.helpers.store import APISessionStore, UnconfiguredAPISessionStore
from pibble.api.exceptions import ConfigurationError
from pibble.util.log import logger, ConfigurationLoggingContext
from pibble.util.str... | painebenjamin/pibble | api/base.py | base.py | py | 3,374 | python | en | code | 1 | github-code | 13 |
72102798739 | from ast import Break
from asyncio.windows_events import INFINITE
while True:
while True:
try:
problema = int(input("Dame un numero de problema entre 1-10: "))
except ValueError:
print("Debes escribir un número -_-")
continue
if problema == 22:
... | XTEP63/Practicas-y-Tareas-ITESO | OS22b/Tareas/tarea6.py | tarea6.py | py | 6,836 | python | es | code | 3 | github-code | 13 |
34421121778 | # coding=utf-8
"""Tools used for solving the Day 24: Blizzard Basin puzzle."""
# Standard library imports:
from typing import Iterable
# Third party imports:
from aoc_tools.algorithms.graphs.a_star_search import ASNode, a_star_search
# Set constants:
DELTA_MAP = {"^": (0, 1), ">": (1, 0), "v": (0, -1), "<": (-1, 0)}... | JaviLunes/AdventCode2022 | src/aoc2022/day_24/tools.py | tools.py | py | 8,908 | python | en | code | 0 | github-code | 13 |
10045945107 | from random import randint
answers = ['Outlook good', 'Yes Signs point to yes', 'Reply hazy', 'try again', 'Ask again later', 'Better not tell you now','It is certain', 'It is decidedly so', 'Without a doubt', 'Yes – definitely', 'You may rely on it', 'As I see it, yes', 'Most likely', 'Cannot predict now', 'Concentra... | arnavpshah/arnavpshah-Python | magic_8_ball.py | magic_8_ball.py | py | 1,023 | python | en | code | 0 | github-code | 13 |
13613062640 | class Solution(object):
# traversal the list once, running time is O(n)
def searchInsert(self, nums, target):
length, index = len(nums), 0
while index < length:
if nums[index] >= target:
return index
else:
index += 1
return index
... | clovery410/mycode | leetcode/35search_insert_position.py | 35search_insert_position.py | py | 1,513 | python | en | code | 1 | github-code | 13 |
14646907565 | from sqlalchemy import Column, Identity, Integer, String, Table
from . import metadata
SubscriptionPendingInvoiceItemIntervalJson = Table(
"subscription_pending_invoice_item_intervaljson",
metadata,
Column(
"interval",
String,
comment="Specifies invoicing frequency. Either `day`, `... | offscale/stripe-sql | stripe_openapi/subscription_pending_invoice_item_interval.py | subscription_pending_invoice_item_interval.py | py | 758 | python | en | code | 1 | github-code | 13 |
37943988708 | # Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
from HepMCAnalysis_i.HepMCAnalysis_iConf import HepMCAnalysis
class HepMCAnalysis_i(HepMCAnalysis):
def __init__(self, name = "HepMCAnalysis_i", file = None):
super( HepMCAnalysis_i, self ).__init__( name )
... | rushioda/PIXELVALID_athena | athena/Generators/HepMCAnalysis_i/python/HepMCAnalysis_iConfig.py | HepMCAnalysis_iConfig.py | py | 1,957 | python | en | code | 1 | github-code | 13 |
14979063472 | from datetime import date
from rest_framework import serializers
from django.db import models
from basemodels import UserData, Stock, StockData, Product, Nature, ProductSupplier, \
ProductPacking, StockMovement, PurchaseDocuments, Company, Installation, Lagerausgang, InstallationLinks, \
InstallationConsumption... | MatthiasLenz/Lagerverwaltung | lagerapp/masterdata/serializers.py | serializers.py | py | 15,412 | python | en | code | 1 | github-code | 13 |
5726235309 | class Vacancy:
"""Class to represent vacancy information"""
def __init__(self, name: str, url: str, salary: int,
employer: str, requirement: str) -> None:
"""
Instance initialisation
:name: Vacancy name
:url: URL link to vacancy
:salary: Minimum salary
... | MarkPcv/vacancy_parser_oop | services/vacancy.py | vacancy.py | py | 3,162 | python | en | code | 1 | github-code | 13 |
20511403367 | from flask import *
from flag import getflag
app = Flask(__name__)
app.secret_key = 'oh you got it, one more step to get flag'
@app.route('/', methods=['GET', 'POST'])
def index():
if request.is_json:
action = request.json.get('action', '').strip()
flag = getflag(request.json.get('token', '').stri... | PKU-GeekGame/geekgame-0th | src/session/game/app.py | app.py | py | 1,293 | python | en | code | 46 | github-code | 13 |
40808750050 | import platform
import subprocess
class NixSys(object):
def __init__(self):
uname = platform.uname()
arch = platform.architecture()
self.name = uname.node
self.release = uname.release
self.version = uname.version
self.machine = uname.machine
self... | alierkanimrek/rpct | src/axones/nixsys/main.py | main.py | py | 3,450 | python | en | code | 0 | github-code | 13 |
73788712338 | import shapes
import rendering
import matrix
import math
# Variáveis globais
window_width = 640
window_height = 480
cubo = None
x_axis, y_axis, z_axis = None, None, None
controls = False
controls_string_off = "Pressione [TAB] para exibir os controles"
controls_string_on = """Translacao:
Q = X+ | W = X-
E = Y+ | R = Y-... | felipedeoliveirarios/trabalho_cg | Old/polyhedron/polyhedron.pyde | polyhedron.pyde | pyde | 11,006 | python | en | code | 1 | github-code | 13 |
7830089880 | from django.contrib import admin
from cl.donate.models import Donation, MonthlyDonation
@admin.register(Donation)
class DonationAdmin(admin.ModelAdmin):
readonly_fields = (
"date_modified",
"date_created",
)
list_display = (
"__str__",
"amount",
"payment_provider",... | freelawproject/courtlistener | cl/donate/admin.py | admin.py | py | 1,156 | python | en | code | 435 | github-code | 13 |
12188156003 | class ListNode:
# 节点超级工厂,用来生产二叉树中的节点
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Tree:
def __init__(self):
# 初始化一棵空树:树根为None
self.root = None
def add(self, item):
# 在二叉树增加一个节点
node = ListNode(item)
# ... | 15149295552/Code | Month09/day04_DATASTRUCT/code/04_binary_tree.py | 04_binary_tree.py | py | 1,599 | python | ja | code | 1 | github-code | 13 |
26000757342 | from __future__ import unicode_literals, print_function
import pickle
import plac
import random
from pathlib import Path
import spacy
from spacy.util import minibatch, compounding
import os
from os import listdir
import plac
import logging
import argparse
import sys
import json
import pickle
from PIL import Image ... | Teknowmics-Internship/Invoice-extraction | NER Train model (1).py | NER Train model (1).py | py | 7,353 | python | en | code | 0 | github-code | 13 |
2526262426 | import random
from sys import maxsize
from copy import deepcopy
import json
import numpy as np
import torch
from torch.optim import Adam
from . import gamelib
from . import constants
from . import utils
from .arch.model import FeatureEncoder, PolicyNet
"""
Most of the algo code you write will be in this file unless ... | wllmzhu/alpha-terminal | python-algo/src/algo_strategy.py | algo_strategy.py | py | 12,225 | python | en | code | 1 | github-code | 13 |
24337818175 | import binascii
print("ENTER THE STRING")
input_string = raw_input()
str1 = binascii.unhexlify(input_string)
length = len(str1)
for i in range(0,255):
str2=""
for j in range(length):
str2 += chr(ord(str1[j])^i)
print(str2)
| nsg1999/cryptopals | Single_byte_XOR.py | Single_byte_XOR.py | py | 231 | python | en | code | 0 | github-code | 13 |
14288739346 | # -*- coding: utf-8 -*-
"""
Truncates string or JSON data so that it fits a specific number of characters.
"""
__author__ = "Jakrin Juangbhanich"
__email__ = "juangbhanich.k@gmail.com"
def truncate(message: str, max_length: int=128, split_ratio: float=0.8) -> str:
""" Truncates the message if it is longer than ... | krinj/logkit | logkit/utils/truncate.py | truncate.py | py | 737 | python | en | code | 4 | github-code | 13 |
797264922 | #!/usr/bin/env python
import itertools
'''
https://code.google.com/codejam/contest/8384486/dashboard#s=p2&a=2
Brute force solution
'''
def solve(l, names):
alphabet = set(''.join(names))
A = len(alphabet)
bools = [False] * 3
# Try all N! (for small dataset, 3!) alphabetical orderings
for ordering ... | christabella/code-busters | centrists_naive.py | centrists_naive.py | py | 1,002 | python | en | code | 2 | github-code | 13 |
74468148817 | '''
Main file to run, this will produce a video
using MatplotLib and display the results
within a GUI
'''
import matplotlib.pyplot as plt
import matplotlib.image as mimg
import os
import cv2
from models import GestureAngleClassifier
#Matplotlib jargon to setup GUI for one frame
def display_image(path, pred):
... | AnshKetchum/gesture-classifier | gesture-by-angle-classifier/output.py | output.py | py | 1,048 | python | en | code | 0 | github-code | 13 |
7531728449 | from cStringIO import StringIO
import django
from django.utils import translation
import jingo
from jingo.tests.test_helpers import render
from mock import patch
from nose import with_setup
from nose.tools import eq_, ok_
import tower
from tower.tests.helpers import fake_extract_from_dir
from tower import ugettext ... | clouserw/tower | tower/tests/test_l10n.py | test_l10n.py | py | 11,819 | python | en | code | 34 | github-code | 13 |
44889001224 | import cv2 as cv
import csv
import math
import numpy as np
import scipy.signal
from matplotlib import pyplot as plt
import argparse
from Tracker import Tracker
agentLength = 10.5 # cm (cube)
def readTrack(opt):
# read CSV file
N = opt.nCars # number of cars
positions = [] # for perspective transform
with ope... | Zimrahin/zTracking | readTrack.py | readTrack.py | py | 8,656 | python | en | code | 3 | github-code | 13 |
35784868388 | from PIL import Image
import numpy as np
import os
import imageio
import cv2
import sys
sys.path.insert(0, r"add/sensors/folder/to/path")
from config import *
def tiff_to_avi(input_filepath):
path = os.path.dirname(input_filepath)
filename_ext = os.path.basename(input_filepath)
filename = os.path.splitext... | UCLA-VMG/EquiPleth | data_acquisition/postproc/tiff_to_avi.py | tiff_to_avi.py | py | 1,516 | python | en | code | 6 | github-code | 13 |
9543178637 | import gym
from stable_baselines3 import PPO
# Model path
model_dir = ""
model_path = ""
# Load in model
model = PPO.load(model_path)
# Forms environment
env = None
env.reset()
# Run model for show
done = False
while done:
obs = env.reset()
done = False
while not done:
env.render()
acti... | akingsley319/AI_Plays_DarkSouls | src/EldenRing/ai_plays/engine.py | engine.py | py | 403 | python | en | code | 1 | github-code | 13 |
72753723538 | from mock import patch
from unittest import TestCase
from robotarena.robot import RobotRandom
class TestRobotRandom(TestCase):
def __randint_side_effect(self, lower_bound, upper_bound):
if lower_bound == 0 and upper_bound == 2:
return 1 # always return "push"
elif lower_bound == 0 and ... | LIQRGV/robot-arena | test/robot/test_robot_random.py | test_robot_random.py | py | 958 | python | en | code | 0 | github-code | 13 |
30816467974 | """
Slightly modified version of WidgetGallery to remove
any dynamic changes of the style. All the style elements
are defined by qtmodern in the main.py file.
"""
from PyQt5.QtWidgets import QApplication, QCheckBox, QComboBox , QDateTimeEdit, QDial, QGridLayout, \
QGroupBox, QDialog, QLabel, QLineEdit, QProgress... | me701/norwegianwood | demo_qtmodern/widgetgallery.py | widgetgallery.py | py | 8,059 | python | en | code | 0 | github-code | 13 |
23607494022 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import os.path
import struct
import sys
import numpy as np
import cv2
# from easydict import EasyDict as edict
import torch
import sklearn
from sklearn import preprocessing
from sklear... | CN1Ember/feathernet_mine | quan_table/insightface_v2/megaface/fast_gen_megaface_pytorch_flip.py | fast_gen_megaface_pytorch_flip.py | py | 22,020 | python | en | code | 1 | github-code | 13 |
31767138079 | # cut the embed head in current pth file
import os
import torch
path = "ArT_mid/MixNet_FSNet_M_160.pth"
cpt = torch.load(path)
model_cpt = cpt["model"]
print(model_cpt.keys())
keys_list = list(model_cpt.keys())
for key in keys_list:
if "embed_" in key:
model_cpt.pop(key)
print(model_cpt.keys())
cpt["m... | D641593/MixNet | model/cut_pth.py | cut_pth.py | py | 380 | python | en | code | 26 | github-code | 13 |
72396604499 | import numpy as np
import pickle, os
from scipy import stats
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import scipy.stats as st
if __name__ == "__main__":
base_to_PGP = -999
base_from_PGP = -999
"""
def plot_cost(CurrentCase, ylist_type, default_case_name):
ax = plt.... | LDuan3008/MEM_CostUncertainty | Postprocess_codes/Postprocess_uncertainty.py | Postprocess_uncertainty.py | py | 32,979 | python | en | code | 0 | github-code | 13 |
9940171419 | # import math, heapq, bisect, itertools, functools
# from collections import deque, Counter, defaultdict, OrderedDict
# python sample.py < input.txt
if __name__ == '__main__':
n = int(input())
A = [[] for _ in range(n)]
for _ in range(n-1):
u, v = [int(i)-1 for i in input().split()]
A[u].a... | yang-su2000/CP-Practice | 2023-05/B303e.py | B303e.py | py | 1,244 | python | en | code | 0 | github-code | 13 |
4912316824 | from youtube_transcript_api import YouTubeTranscriptApi, NoTranscriptFound
video_url = 'https://www.youtube.com/watch?v=Bb0J_2imRQc'
video_id = video_url.split("watch?v=")[-1]
try:
# Fetching the transcript
transcript = YouTubeTranscriptApi.get_transcript(video_id)
# Printing the transcript
for text ... | marciob/youtube-text-transcript | get_text_transcript1.py | get_text_transcript1.py | py | 439 | python | en | code | 0 | github-code | 13 |
15190298330 | #!/usr/bin/env python3.4
# coding: latin-1
# (c) Massachusetts Institute of Technology 2015-2018
# (c) Brian Teague 2018-2019
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 ... | kkiwimagi/cytoflow-microscopy-kiwi | cytoflowgui/cytoflow_application.py | cytoflow_application.py | py | 7,568 | python | en | code | 0 | github-code | 13 |
17304824026 | data = [int(i) for i in input().split()]
class Node:
def __init__(self, data, i):
self.children = []
self.metadata = []
self.children_count = data[i]
i += 1
self.metadata_count = data[i]
i += 1
for _ in range(self.children_count):
self.children.ap... | kameranis/advent_of_code_2018 | day_8/sol_2.py | sol_2.py | py | 959 | python | en | code | 1 | github-code | 13 |
1078216782 | #!/usr/bin/env python
# coding: utf-8
# # Renaming photos
# ## Author(s): Brian Nhan Thien Chung (UCI NATURE research technician)
# ### Created on: Friday August 28, 2020 by Brian Nhan Thien Chung
# ### Last edited on: Wednesday September 9, 2020 by Brian Nhan Thien Chung
#
# The purpose of this Jupyter Notebook is t... | briannhan/machine-learning-code | Renaming photos/Renaming photos.py | Renaming photos.py | py | 14,700 | python | en | code | 0 | github-code | 13 |
14383128855 | from flask import Flask, render_template, request
from flask_mysqldb import MySQL
app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'xxxxxxxxxxxxxxx'
app.config['MYSQL_DB'] = 'bank'
mysql = MySQL(app)
@app.route('/', methods=['GET', 'POST'])
de... | julienmiquelilab/ilab | app-IN-cloud-TP1.py | app-IN-cloud-TP1.py | py | 1,222 | python | en | code | 0 | github-code | 13 |
19905007427 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x, left=None, right=None):
self.val = x
self.left = left
self.right = right
class Solution(object):
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rty... | littleliona/leetcode | easy/572.subtree_of_another_tree.py | 572.subtree_of_another_tree.py | py | 1,527 | python | en | code | 0 | github-code | 13 |
41379836944 | # import libraries
from urllib.request import urlopen
import csv
from bs4 import BeautifulSoup
quote_page = "https://arxiv.org/search/advanced?advanced=&terms-0-operator=AND&terms-0-term=Machine+Learning&terms-0-field=title&classification-computer_science=y&classification-economics=y&classification-eess=y&classificati... | amysen/BR_Algothon | cornell_scraper.py | cornell_scraper.py | py | 1,918 | python | en | code | 1 | github-code | 13 |
6768252735 | import pandas as pd
import matplotlib.pyplot as plt
def show_overview(data):
#DataFrame shape.
print('Shape of DataFrame is: {}\n'.format(str(data.shape)))
#First 10 rows.
print('First 10 rows look like this:')
print(data.head(10))
#Stats.
print('\nDataframe stats are:')
print(data.des... | asicoderOfficial/mas_stock_prediction | src/eda.py | eda.py | py | 767 | python | en | code | 2 | github-code | 13 |
3481263724 | import RPi.GPIO as GPIO
import time as time
import sys
timestamp = 0
count = 0
r = []
#time.sleep(90) # REMOVE AFTER GOING BACK INSIDE
print(sys.argv)
if len(sys.argv) > 1:
interval = int(sys.argv[1]) # Seconds between each measurement
if len(sys.argv) > 2:
num_intervals = int(sys.argv[2]) # number of inter... | srajadnya1/E11-Labwork | rad_sensor.py | rad_sensor.py | py | 996 | python | en | code | 0 | github-code | 13 |
12871052855 | """
Problem statement:
Design a system that manages the reseration state of n seats that are numbered from 1 to n.
Implement the SeatManager class:
* SeatManager(int n) Initialize a SeatManager object that will manage n seats numbered from 1 to n. All seats are initially avail... | Nacriema/Leet-Code | daily_challenges/seat-reservation-manager.py | seat-reservation-manager.py | py | 4,632 | python | en | code | 0 | github-code | 13 |
35997219576 |
import utils
import backoff
from azure.mgmt.authorization import AuthorizationManagementClient
from azure.core.exceptions import ResourceNotFoundError
@backoff.on_exception(backoff.expo, HttpResponseError, max_time=300)
@utils.Decorator()
def assign_role_to_rg(cli_args, resource_group, msi_principal_id):
resou... | crodriguezde/reimage | msi.py | msi.py | py | 1,797 | python | en | code | 0 | github-code | 13 |
3720816290 | '''
풀다가 엇나감
긴 코드를 함수로 자르는 연습 더 해야함
'''
from collections import deque
import sys
global INT_MAX
INT_MAX = sys.maxsize
n,m = map(int,input().split()) # m = 병원
grid =[
list(map(int,input().split()))
for _ in range(n)
]
# 빈칸인 경우 0, 사람인 경우 1, 병원인 경우 2
visited = [
[0 for _ in range(n)]
for _ in range(n)
]... | JaeEon-Ryu/Coding_test | LeeBrosCode/코테2.py | 코테2.py | py | 3,495 | python | en | code | 1 | github-code | 13 |
18719739725 | import io
import os
import socket
import struct
import cv2
import time
import numpy as np
import pygame
from PIL import Image
from pygameControl import CV2PYGAME, RCControl
server_socket = socket.socket()
#data collected from stream and pygame controls will be save to:
train_data = []
file_name = 'training_ether_fina... | herobaby71/Self-driving-RC-Car | LaptopServerDataCollection.py | LaptopServerDataCollection.py | py | 3,422 | python | en | code | 0 | github-code | 13 |
3464690631 | from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404, JsonResponse
from .models import Question, Test, Filters
from django.template import loader
from django.shortcuts import render
import json
def index(request):
latest_question_list = Question.objects.order_by('-... | nanfang-wuyu/Django | mysite/polls/views.py | views.py | py | 3,859 | python | en | code | 0 | github-code | 13 |
15892288690 | # -*- coding: utf-8 -*-
import asyncio
import re
from abc import ABC, abstractmethod
from base64 import (b16decode, b16encode, b32decode, b32encode, b64decode,
b64encode, b85decode, b85encode)
from copy import deepcopy
from hashlib import md5 as _md5
from itertools import chain
from logging import ... | ClericPy/uniparser | uniparser/parsers.py | parsers.py | py | 64,715 | python | en | code | 8 | github-code | 13 |
12377795623 | import requests
def make_requests(url):
protocols = ['ldap', 'rmi', 'ldaps']
for protocol in protocols:
headers = {
'User-Agent': '${jndi:' + protocol + '://10.10.0.1:443/a}',
}
request = url + "/${jndi:" + protocol + "://20.20.0.1:443/a}/?pwn=$\{jndi:" + protocol + "://30.... | Sekuloski/Log4j-python | main.py | main.py | py | 466 | python | en | code | 0 | github-code | 13 |
40710010990 | ### IMPORTS
import sys
import matplotlib.pyplot as plt
### MAIN
for q in range(len(sys.argv)-1) :
filename = sys.argv[q+1]
file = open(filename, "r")
lines = file.readlines()
times = []
mFlowRates = [0]
i = 0
time = 0
for line in lines :
if "Time ="... | zdhughes91/GeN-Foam-Restructure | Tutorials/toBeUpdated/testingMod/plotMassFlowRate.py | plotMassFlowRate.py | py | 846 | python | en | code | 0 | github-code | 13 |
27789230829 | from socket import socket, AF_INET, SOCK_STREAM
from uuid import getnode
from ast import literal_eval
import time
import sys
#Registers device onto the server using device's id and MAC address
def REGISTER( deviceID, MAC, IP, port ):
print ("Device attempting to register to server, input values:")
print ("Devi... | MatthewCookUNR/CPE-401-IoT-Proxy-Network-2017 | IoT Proxy/Server-Side Program.py | Server-Side Program.py | py | 12,597 | python | en | code | 0 | github-code | 13 |
28989810024 | '''
https://leetcode.com/problems/kth-largest-element-in-an-array/
'''
def quickSelect(nums,beg,end):
if beg < end:
p = partition(nums,beg,end)
if p == k:
return nums[k]
elif p < k:
return quickSelect(nums,p+1,end)
return quickSelect(nums,beg,p-1)
return n... | riddheshSajwan/data_structures_algorithm | sorting/quickSelect.py | quickSelect.py | py | 758 | python | en | code | 1 | github-code | 13 |
8488144393 | import datetime
from allauth.account import app_settings as allauth_settings
from allauth.account.adapter import get_adapter
from allauth.utils import email_address_exists
from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Count, Q
from pho... | OmegaBox/OmegaBox_Server | app/members/serializers.py | serializers.py | py | 15,939 | python | en | code | 1 | github-code | 13 |
74175598738 | #!/usr/bin/env python3
from common.util import load, test, change_dir, parse_nums
def solve(part, file, lo=0, hi=0):
ranges = sorted(parse_nums(line) for line in load(file))
res = 0
for x, y in ranges:
if lo + 1 <= x - 1:
if part == 1:
return lo+1
res += x - lo - 1
lo = max(lo, y)
... | andrewmacheret/aoc | 2016/python/day20/main.py | main.py | py | 654 | python | en | code | 0 | github-code | 13 |
21308439710 | # my first base fashion-MNIST
import keras
import tensorflow as tf
import numpy as np
from keras.datasets import fashion_mnist
np.random.seed(1)
tf.set_random_seed(1)
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
type(train_images)
train_images = train_images / 255.0
test_imag... | guchchcug/fashion-mnisit-base | fashion-MNIST.py | fashion-MNIST.py | py | 937 | python | en | code | 0 | github-code | 13 |
17945600663 | import requests
from datetime import datetime, timedelta, date
from openmrs.models import Paciente, Location, ConsultaClinica
# location_url = 'http://197.218.241.174:8080/openmrs/ws/rest/v1/reportingrest/dataSet/5cd2ea5b-b11f-454b-9b45-7a78ac33eab9'
# inscritos_url = 'http://197.218.241.174:8080/openmrs/ws/rest/v1/re... | fxavier/echosys | app/openmrs/services/data_service.py | data_service.py | py | 5,540 | python | en | code | 0 | github-code | 13 |
4593694305 | class Solution:
"""
@param nums: A list of integers
@return: An integer indicate the value of maximum difference between two
Subarrays
"""
def maxDiffSubArrays(self, nums):
# write your code here
if len(nums) == 0:
return 0
maxL = [nums[0]] ... | ultimate010/codes_and_notes | 45_maximum-subarray-difference/maximum-subarray-difference.py | maximum-subarray-difference.py | py | 1,256 | python | en | code | 0 | github-code | 13 |
4904155281 | ##~~~~~~~~~~~~~~~~-~~~~~~~~~~~~~~~~~##
# DevConsole for cheats and testing
##~~~~~~~~~~~~~~~~-~~~~~~~~~~~~~~~~~##
# Possible commands TODO :
# ### Dev
# # - dev_gamelog #-// {Bool} #-// Enable/Disable game event log print
# ### Cheats
# # - game_ball_add #-// No param ... | Pitchumi/PongPython | TKinter/devconsole.py | devconsole.py | py | 4,294 | python | en | code | 0 | github-code | 13 |
70337602579 | #!/usr/bin/env python
"""
Minimal example for running an async web server using aiohttp.
Code taken from here:
http://aiohttp.readthedocs.io/en/stable/web.html
"""
from aiohttp import web
async def hello(request):
return web.Response(body=b"Hello, world")
app = web.Application()
app.router.add_route('GET', '/'... | deeplook/backend-code-challenge | serve_aiohttp.py | serve_aiohttp.py | py | 347 | python | en | code | 0 | github-code | 13 |
22335271885 | #Solution1 - for fractional numbers only
class Sort:
def insertionSort(Self, arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j>=0 and key<arr[j]:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
return arr
def ... | komalupatil/Leetcode_Solutions | Sorting Algorithms/Bucket Sort.py | Bucket Sort.py | py | 1,987 | python | en | code | 1 | github-code | 13 |
21472626439 | import numpy as np
import tensorflow as tf
from pathlib import Path
from django.views.generic import TemplateView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from .forms import CommentTextForm
from .utils import clear_text
from .models import Results, UserStudiesCount
... | pavlovich-ivan/text-toxicity-analyzer | app/classifier/views.py | views.py | py | 2,315 | python | en | code | 0 | github-code | 13 |
2105030042 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: ran
@file: triangle_120.py
@time: 2021/6/20 16:25
@desc:
三角形最小路径和
给定一个三角形 triangle ,找出自顶向下的最小路径和。
每一步只能移动到下一行中相邻的结点上。相邻的结点 在这里指的是 下标 与 上一层
结点下标 相同或者等于 上一层结点下标 + 1 的两个结点。也就是说,如果正位于当前行
的下标 i ,那么下一步可以移动到下一行的下... | reflectc/leetcode_program | src/triangle_120.py | triangle_120.py | py | 1,296 | python | zh | code | 0 | github-code | 13 |
1310102853 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
class MultivariateLinearRegressionModel(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(3, 1)
def forward(self, x):
return self.linear(x)
def train(model, optimi... | tnqkr98/SpeechRecognition | py_remind11(DataProcessing).py | py_remind11(DataProcessing).py | py | 1,415 | python | en | code | 0 | github-code | 13 |
38362611888 | class Solution1(object):
"""
Sorting
- Time: O(N log N)
- Space: O(N)
"""
def kClosest(self, points, K):
"""
:type points: List[List[int]]
:type K: int
:rtype: List[List[int]]
"""
dist = [(i,x[0]*x[0]+x[1]*x[1]) for i,x in enumerate(points)]
... | rctzeng/AlgorithmDataStructuresPractice | Leetcode/KClosestPointsToOrigin_973.py | KClosestPointsToOrigin_973.py | py | 1,727 | python | en | code | 0 | github-code | 13 |
22335021715 | #Leetcode 17. Letter Combinations of a Phone Number
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
mapping = { "2": "abc", "3": "def", "4":"ghi", "5":"jkl", "6":"mno", "7":"pqrs", "8":"tuv", "9":"wxyz"}
if len(digits) == 0:
return []
if len(digi... | komalupatil/Leetcode_Solutions | Medium/Letter Combinations of a Phone Number.py | Letter Combinations of a Phone Number.py | py | 769 | python | en | code | 1 | github-code | 13 |
16732682352 | import sounddevice as sd
import numpy as np
import os
import sys
import math
import time
import datetime
import argparse
import csv
from timeit import default_timer as timer
parser = argparse.ArgumentParser(description="Beeps at you when you\'re too loud",
formatter_class=argparse.Ra... | OliveiraRyan/YellDetector | audio_reader.py | audio_reader.py | py | 3,715 | python | en | code | 0 | github-code | 13 |
71545554259 | import tensorflow as tf
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
num_classes = 10
img_rows, img_cols, img_ch = 28, 28, 1
input_shape = (img_rows, img_cols, img_ch)
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 25... | bashendixie/ml_toolset | 案例67 tensorflow2.8 比较不同优化器/test_optimizers.py | test_optimizers.py | py | 3,641 | python | en | code | 9 | github-code | 13 |
8151426436 | import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
import toascii
max_len = 250
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class Net(nn.Module):
def __init__(self, device, batch_size, input_size=max_len, hidden_size=max_len, num_... | HaloKim/kor-sentence | predict.py | predict.py | py | 2,830 | python | en | code | 0 | github-code | 13 |
70221744018 | from django.shortcuts import render, redirect
from django.http import HttpResponse
from qtech_search_engine.models import KeywordDescriptionModel, AllUsers
# Create your views here.
def HomeView(request):
keywords = KeywordDescriptionModel.objects.all()
context = {
'keywords': keywords,
}
r... | thedrowsywinger/qtech_interview_problem | qtech_search_engine/views.py | views.py | py | 2,197 | python | en | code | 0 | github-code | 13 |
2369303713 | from twitter import Twitter, OAuth
import random
import os, ssl
#catches verification errors
if (not os.environ.get('P... | Andeyn/TartanHacks | POOPOO.py | POOPOO.py | py | 1,162 | python | en | code | 0 | github-code | 13 |
74403148817 | import sys
from sets import Set
def get_problem(infile):
NM = [int(val) for val in infile.next().strip().split(' ')]
N = NM[0]
M = NM[1]
exist_dir = None
new_dir = None
exist_dir = [infile.next().strip() for i in range(N)]
new_dir = [infile.next().strip() for j in range(M)]
return (exis... | litao91/googlecodejam | filefixit/filefixit.py | filefixit.py | py | 1,375 | python | en | code | 1 | github-code | 13 |
36933256183 | '''
Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.
'''
n=int(input("Enter the number of eleme... | imhariprakash/Courses | python/hackerrank programs/abc-cab-bca-pattern-py/main.py | main.py | py | 593 | python | en | code | 4 | github-code | 13 |
29201566825 | import numpy as np
import datetime
print('start loading data:', datetime.datetime.now())
file = "clustering1.txt"
print('start loading data:', datetime.datetime.now())
with open('F:\\Google Drive\\coursera\\Algorithms - Tim Roughgarden\\3. Greedy Algorithms, Minimum Spanning Trees, and Dynamic Programming\\' + file) as... | sunanqi/learning | Greedy Algorithms- Minimum Spanning Trees- and Dynamic Programming by Tim Roughgarden/clustering.py | clustering.py | py | 1,479 | python | en | code | 0 | github-code | 13 |
32903262375 | import tkinter as tk
from tkinter import ttk, filedialog, simpledialog
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import pandas as pd
import libSimpleNnet
class Application(tk.Frame):
"""
GUI class, inherits from Tkinter's Frame class.
"""
def _... | asparks1987/libsimplennet | simpleNnetGUI.py | simpleNnetGUI.py | py | 5,154 | python | en | code | 0 | github-code | 13 |
4210417730 | import math
from typing import List
class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
def calc_time(mid, piles):
sum = 0
for i in range(len(piles)):
sum += math.ceil(piles[i]/mid)
return sum
low = 1
high = max(pi... | mhasan09/leetCode_M | koko_eating_banananas.py | koko_eating_banananas.py | py | 650 | python | en | code | 0 | github-code | 13 |
26624124389 | from _collections import deque
n, l ,r = map(int, input().split())
data = []
for i in range(n):
temp = list(map(int, input().split()))
data.append(temp)
def bfs( x, y, index):
q = deque()
# 초기 세팅, 방문처리
q.append([x,y])
union[x][y] = index
dx = [0,0,1,-1]
dy = [1,-1,0,0]
union... | isakchoe/TIL | algorithm /dfs_bfs/ex_21.py | ex_21.py | py | 1,521 | python | en | code | 0 | github-code | 13 |
26161460535 | # encoding: utf-8
import sys
from workflow import Workflow, ICON_WEB, web
#API_KEY = 'AIzaSyAWrIPT4uIsUkymkPdvK3RJ-S6PNr-LMI0'
list_of_apis = [
#this is to avoid quota
#make sure the api keys are from different projects. So i had to make 8 projects. each project's api key goes here.
'<your youtube api keys go h... | namanrjpt/youtube-white-alfred | youtube.py | youtube.py | py | 2,389 | python | en | code | 0 | github-code | 13 |
25930015725 | # Copyright (c) 2012-2017, Andreas Heumaier<andreas.heumaier@microsoft.com>
# All rights reserved.
#
# See LICENSE file for full license.
#
# Packer build runnner
#
import subprocess
TEMPLATE = 'gitlab-ubuntu-docker.json'
VARFILE = 'varfile'
def validate(template=TEMPLATE):
print("execute validate"... | aheumaier/GitlabDemo | setup.py | setup.py | py | 831 | python | en | code | 2 | github-code | 13 |
10152525504 | import json
import os
import string
from collections import defaultdict
from importlib.resources import files
from fontTools import unicodedata
STRUCTURE = "IDEOGRAPHIC DESCRIPTION CHARACTER"
DATA_DIR = files("ids_py.data")
CHARACTERS_COMPOSITION_PATH = DATA_DIR.joinpath("IDS_characters_composition.json")
COMPONEN... | BlackFoundryCom/ids-py | src/ids_py/__init__.py | __init__.py | py | 3,995 | python | en | code | 1 | github-code | 13 |
14655281434 | # -*- coding:utf-8 -*-
import sys
from importlib import reload
reload(sys)
sys.setdefaultencoding('utf-8')
import numpy as np
#from numpy import *
#计算欧式距离
def distEcloud(vecA,vecB):
return np.sqrt(np.sum(np.power(vecA-vecB,2)))
#随机设置K个中心点
def randCenter(dataSet,k):
raw_number=np.shape(dataSet)[1]
zeroM... | bgmlxxlmgb/PythonApp | src/core/main/algorithmic/classify/CLuster-KMeans.py | CLuster-KMeans.py | py | 3,789 | python | en | code | 0 | github-code | 13 |
5236063616 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
cur_node = self.head
while cur_node:
print(cur_node.data)
cur_node = cur_node.next
def ... | rvirjn/data-science | ds/singly_linked_list.py | singly_linked_list.py | py | 1,302 | python | en | code | 2 | github-code | 13 |
549158344 | import os
if 'APP_CONFIG' not in os.environ:
os.environ['APP_CONFIG'] = '/brum/dev/PowerMeter/scripts/config/bat_inverter.yaml'
"""
Based on MODBUS-HTML_SI44M-80H-13_32009R_V10
"""
import time
import datetime
from lib import log, config
from lib.quicklock import lock
from lib.telemetry import send_data_lines
fr... | funnybrum/PowerMeter | scripts/bat_inverter.py | bat_inverter.py | py | 2,431 | python | en | code | 0 | github-code | 13 |
37862285443 | from __future__ import print_function
from PyAstronomy.pyaC import pyaErrors as PE
import numpy as np
class SMW_RHK:
def __init__(self, ccfs="rutten", afc="middelkoop", rphot="noyes"):
"""
Converting Mount-Wilson S-index into RHK index.
The Mount-Wilson S-index is a measure of the emission-l... | sczesla/PyAstronomy | src/pyasl/asl/sindex.py | sindex.py | py | 11,836 | python | en | code | 134 | github-code | 13 |
21230531925 | """empty message
Revision ID: 96db82cc5f09
Revises:
Create Date: 2023-09-15 11:46:08.150893
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '96db82cc5f09'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... | itsnotanant8288/simple-python-backend | migrations/versions/96db82cc5f09_.py | 96db82cc5f09_.py | py | 1,684 | python | en | code | 0 | github-code | 13 |
4970463773 | import sys
sys.setrecursionlimit(1000000000)
INF = 1000000009
MAX = 100001
dist = []
graph = []
class Triad:
def __init__(self, source, target, weight):
self.source = source
self.target = target
self.weight = weight
def __lt__(self, other):
if self.weight < other.weight:
return True... | truclycs/code_for_fun | algorithms/python/python_blue/L21/_11710___Expensive_subway.py | _11710___Expensive_subway.py | py | 2,129 | python | en | code | 7 | github-code | 13 |
39424037573 | import re
from enum import Enum
from PreLexer import PreLexer, Token, RecognitionException
from CompilerException import CompilerException
# TODO: move to utils?
def iterUntil(func, cond):
res = func()
while not cond(res):
yield res
res = func()
# Gives numbers to tokens, and generates a tok... | demin-dmitriy/almost-haskell | src/AHLexer.py | AHLexer.py | py | 10,926 | python | en | code | 1 | github-code | 13 |
21043641485 | from profiles.models import Profile
from customers.models import Customer
from io import BytesIO
import base64
import matplotlib.pyplot as plt
def get_salesman(val):
return Profile.objects.get(id=val).user.username
def get_customer(val):
return Customer.objects.get(id=val).name
def get_graph():
buffer=B... | sandeep-045/python-training | django/reports_proj/sales/utils.py | utils.py | py | 1,355 | python | en | code | 0 | github-code | 13 |
42818968215 | import datetime as dt
class Car:
"""Representation of a car.
:param str make:
The make of the car.
:param str model:
The model of the car.
:param int year:
The car's year of manufacture.
"""
def __init__(self, make, model, year):
self.make = make
self.m... | smallpythoncode/csci161 | assignments/final/jahnke_kenneth_final_part4.py | jahnke_kenneth_final_part4.py | py | 3,609 | python | en | code | 0 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.