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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
5818447084 | from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.clock import Clock
from kivy.properties import NumericProperty, ListProperty, ObjectProperty
from kivy.lang import Builder
from kivy.graphics import Color, Ellipse, Line , Rectangle, Point, GraphicException
from kivy.uix.boxlayout import Box... | aaaler/k9 | kpilot/uix/consolelog/ConsoleLog.py | ConsoleLog.py | py | 2,434 | python | en | code | 1 | github-code | 50 |
72049113436 | #!/usr/bin/python
# -*- coding: utf-8 -*-
class Business(object):
def get_business(self):
return {
'address': '1835 E Guadalupe Rd, Ste 106',
'city': 'Tempe',
'id': '--9QQLMTbFzLJ_oT-ON3Xw',
'is_open': 1,
'latitude': 33.3617,
'longitud... | Cedric-Chen/ShopMe | datamodel_test/business.py | business.py | py | 549 | python | en | code | 0 | github-code | 50 |
8213765542 | # import os
# from win32com.client import Dispatch
# import shutil
# import winreg
# from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
# from selenium import webdriver
# from selenium.webdriver.common.by import By
# from selenium.webdriver.chrome.service import Service
# from selenium.webdr... | jaykakadiya18/linkedin-auto | main.py | main.py | py | 8,442 | python | en | code | 0 | github-code | 50 |
22933510217 | from flask import Flask
from test import db
import json
# from gevent import pywsgi
server=Flask(__name__)
sql='SELECT * from user_message '
@server.route('/login',methods=['get'])
def login():
res= db.my_db(sql)
if res:
tinydict={'Name': '', 'Age': '', 'sex': ''}
tinydict['Name']=res[0][1]
... | 17621445641/duitang_back_end | test/user_message_get接口.py | user_message_get接口.py | py | 520 | python | en | code | 0 | github-code | 50 |
18552393261 | import cv2
import numpy as np
import xml.etree.ElementTree as ET
class Pedestrian:
def __init__(self, gt_file, extrinsics_file, intrinsics_file):
self.cont = 0
self.labels = self.read_txt(gt_file)
self.cameraMatrix, self.distCoeffs = self.read_intrinsics(intrinsics_file)
self.rvec, ... | gabrielppierre/SAFEMAC_ui_integration | modules/detect_pedestrian.py | detect_pedestrian.py | py | 2,385 | python | en | code | 0 | github-code | 50 |
7320575331 | def check_is_looped(BR):
graph = {}
for k, it in groupby(sorted(BR), key=lambda x: x[0]):
graph[k] = {e for _, e in it}
sub_graph = {}
while True:
vertex_set = set(graph).intersection(chain.from_iterable(graph.values()))
sub_graph = {k: vertex_set & vs for k, vs in graph.items()
... | ArturSavchuk/decision_support | Lab1/is looped checking.py | is looped checking.py | py | 528 | python | en | code | 0 | github-code | 50 |
11172453620 | import os
import torch
import PIL.Image as Image
import matplotlib.pyplot as plt
import sys
sys.path.append("/home/ubuntu/Desktop/Domain_Adaptation_Project/repos/biastuning/")
from utils import *
results_folder_name = 'endovis18_10label_textaffine_decdertuning_4e-4_adamw_focal_alpha75e-2_gamma_2_256_bs64_rsz_manyaug... | JayParanjape/biastuning | eval/endovis18/calculate_ious.py | calculate_ious.py | py | 1,089 | python | en | code | 26 | github-code | 50 |
29210778507 | from flask import Flask, render_template, request, flash, g
from flask_bootstrap import Bootstrap
from sqlite3 import connect, Connection
from datetime import datetime
app = Flask(__name__)
Bootstrap(app)
app.secret_key = 'development key'
from forms import ServiceRequestForm, ClientRegistrationForm
DATABASE = '../db/... | mfitton/easydoesitBB | src/app.py | app.py | py | 2,455 | python | en | code | 0 | github-code | 50 |
25770588657 | import numpy as np
import utilities as util
class TimeStepping():
def __init__(self, param):
# Initialize objects using param
self.param = param
self.mesh, self.uw, self.flux, self.boundary, self.sources = \
param.initialize_objects()
# Aliasing functions for convenien... | chuckjia/weather | timesteps.py | timesteps.py | py | 9,077 | python | en | code | 0 | github-code | 50 |
75057405594 | #-*-coding: utf-8-*-
class CaesarCipher:
def __init__(self, key):
self.key = int(key);
self.abc ="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
def encode(self, txt):
return self.translate(txt, "e");
def decode(self, txt):
return self.translate(txt, "d");
def translate(self, txt, m):
translated = "";
txt = txt.upper();... | binarioGH/codewars | cesarclass.py | cesarclass.py | py | 667 | python | en | code | 0 | github-code | 50 |
37091507423 | from functools import reduce
def bucket_sort(items):
bucket = [[] for i in range(len(items))]
for item in items:
index = int(item * 10)
bucket[index].append(item)
for i in range(len(items)):
bucket[i] = sorted(bucket[i])
items = reduce(lambda x, y: x + y, bucket)
return... | MYTE21/DSA.Train | (3) Python - Data Structures and Algorithms/Sorting Algorithms/Bucket Sort/Bucket Sort.py | Bucket Sort.py | py | 530 | python | en | code | 2 | github-code | 50 |
36994718564 | import torch
import pkg_resources as pkg
def check_version(current: str = '0.0.0',
minimum: str = '0.0.0',
name: str = 'version ',
pinned: bool = False,
hard: bool = False,
verbose: bool = False) -> bool:
"""
Check curre... | madara-tribe/custom-yolov8 | custom/nn/commons.py | commons.py | py | 2,883 | python | en | code | 0 | github-code | 50 |
24000692357 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# 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
# of the License, or (at your option) any later version.
#
# This program is distrib... | JT-a/blenderpython279 | scripts/addons_extern/ctools-master/piemenu/piemenu_meshmerge.py | piemenu_meshmerge.py | py | 3,776 | python | en | code | 5 | github-code | 50 |
20194608595 | from __future__ import print_function
from ExpressionValidator import ExpressionValidator
from DatasetRepository import DatasetRepository
import re
import json
class ConfigValidator:
selectRowOps = ['lt', 'gt', 'le', 'ge', 'eq', 'neq']
def __init__(self, configStr = "", configObj = None):
if configOb... | bryantrobbins/baseball | shared/btr3baseball/ConfigValidator.py | ConfigValidator.py | py | 7,537 | python | en | code | 22 | github-code | 50 |
29106172402 | # This problem could be solved with DFS and tracking nop/jmp with a stack
with open ('input.txt') as f:
lines = f.readlines()
attempted_fix_idx = set()
finish_dx = len(lines)
while True:
tried_fix = False
acc = 0
idx = 0
visited_idx = set()
while True:
... | cdabella/advent_of_code | 2020/day08/day8pt2_bruteforce.py | day8pt2_bruteforce.py | py | 1,220 | python | en | code | 0 | github-code | 50 |
38656605907 | # https://leetcode.com/problems/product-of-array-except-self/?envType=study-plan-v2&envId=top-interview-150
from functools import reduce
from typing import List
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
out = []
total_mult = reduce(lambda a, b: a * b, nums)
... | Litovkaa/algorithms | prod_except_self.py | prod_except_self.py | py | 592 | python | en | code | 0 | github-code | 50 |
27342003268 | import math
from urllib.request import urlretrieve
import torch
from PIL import Image
from tqdm import tqdm
import numpy as np
import random
import torch.nn.functional as F
def download_url(url, destination=None, progress_bar=True):
"""Download a URL to a local file.
Parameters
----------
url : str
... | Robbie-Xu/CPSD | utils/util.py | util.py | py | 7,689 | python | en | code | 20 | github-code | 50 |
10418024287 | from typing import List, Union
from ebooklib.epub import Link, Section
from bs4 import BeautifulSoup, Tag, NavigableString, Comment
from typography import Title, Paragraph, TypographyList
disallowed_tags = ['[document]', 'noscript', 'header', 'html',
'meta', 'head', 'input', 'script', 'style'
... | c4rls/projeto-integrador | projeto_integrador/utils.py | utils.py | py | 2,933 | python | en | code | 1 | github-code | 50 |
73407137754 | '''
args - argumentos nao nomeados
serve pra colocar a quantidade de argumentos que vc quiser,
msm q ainda não estejam definidos
* - *args (empacotamento e desempacotamento)
'''
def soma(*args):
total = 0
for numero in args:
print('Total', total, numero)
total += numero
print('Total', t... | Enzslv4/Pythoncurso1 | aula71.py | aula71.py | py | 591 | python | pt | code | 0 | github-code | 50 |
7857087798 | import os
import discord
import asyncio
from replit import db
from datetime import date
# from dotenv import load_dotenv
# from ds import *
# load_dotenv()
TOKEN = os.environ["DISCORD_TOKEN"]
prefix = ":V"
bot = discord.Client()
print("running")
#db functions
def addDB(cat, item):
pass
# ---------------------... | p-r-o-m-e/-DISCONTINUED-Python_discordBot2 | main.py | main.py | py | 4,630 | python | en | code | 0 | github-code | 50 |
42880387454 | class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
s, i = 0, 0
n = len(nums)
res = inf
for j in range(n):
s += nums[j]
while s >= target:
res = min(res, j - i + 1)
s -= nums[i]
i += 1
... | MengSunS/daily-leetcode | two_pointers/209.py | 209.py | py | 976 | python | en | code | 0 | github-code | 50 |
25156563766 | import torch
import numpy as np
from time import sleep
from ai.model import Model, fc
from ai.infer import Inferencer
def test_inferencer():
model = Model(fc(8, 8)).init().eval()
inferencer = Inferencer(model, batch_size=1)
assert_parity(model, inferencer)
def test_param_update():
model = Model(fc(... | calvinpelletier/ai | tests/infer/test_inferencer.py | test_inferencer.py | py | 1,283 | python | en | code | 0 | github-code | 50 |
17678326104 | from automation.risk_management import *
def run( # chạy hàng ngày
run_time = dt.datetime.now()
):
start = time.time()
info = get_info('daily',run_time)
period = info['period']
dataDate = info['end_date']
folder_name = info['folder_name']
# create folder
if not os.path.isdir(join(dep... | TranHuyNam177/DataAnalytics-New | automation/risk_management/MarketPressureReport.py | MarketPressureReport.py | py | 20,420 | python | en | code | 0 | github-code | 50 |
7000527118 | #5와 6의 차이 2864
#https://www.acmicpc.net/problem/2864
hello = list(input().split())
min_result=[]
max_result=[]
for k in hello :
temp1 = ''
temp2 = ''
for i in k :
if i == '5' or i == '6':
temp1 += '5'
temp2 += '6'
else :
temp1 += i
temp2 += ... | PangPangGod/Programmers_PY | BaekJoon_2864.py | BaekJoon_2864.py | py | 437 | python | en | code | 0 | github-code | 50 |
72665457116 |
import pandas as pd
import numpy as np
from ...librarys import env
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS as esw
from . import base
class Reviews():
def load(self):
dataPath = env.getDataPath()
try:
rev... | tonystevenj/prosperity-adviser-fall2019 | DataVisualization/Server/models/data/reviews.py | reviews.py | py | 5,674 | python | en | code | 5 | github-code | 50 |
72262649754 | '''applib.model.entity -- generic model objects
'''
import re
import applib
import pyglet
from applib.engine import sprite
def _normalise(string):
'''Normalise the given string.
'''
string = string.strip().lower()
string = re.sub(r'\s+', '_', string)
string = re.sub(r'[^a-z_]', '', string)
... | chardbury/paper-dragon-31 | applib/model/entity.py | entity.py | py | 1,937 | python | en | code | 1 | github-code | 50 |
553648911 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isCousins(self, root, x, y):
"""
In a binary tree, the root node is at depth 0, and children of each depth k no... | ljia2/leetcode.py | solutions/tree/993.Cousins.in.Binary.Tree.py | 993.Cousins.in.Binary.Tree.py | py | 1,863 | python | en | code | 0 | github-code | 50 |
9653741486 | import pandas as pd
import numpy as np
import joblib
from pydantic import BaseModel
from sklearn.svm import SVC
from sklearn.feature_extraction.text import CountVectorizer
import re
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
#class Tw... | alok449/twitter-sentiment-analysis | nlpmodel.py | nlpmodel.py | py | 2,867 | python | en | code | 0 | github-code | 50 |
15673482668 | #%% About
'''
We will prefer to get data from the Informatics team API.
For documentation see http://gbadske.org:9000/dataportal/
'''
#%% Packages and functions
import requests as req # For sending HTTP requests
import inspect
import io
import pandas as pd
# To clean up column names in a dataframe
def cleanc... | GBADsInformatics/GBADsLiverpool | Global Aggregate workspace/Code and Control Files/1a_extract_from_gbadske_api.py | 1a_extract_from_gbadske_api.py | py | 17,861 | python | en | code | 0 | github-code | 50 |
17552563298 | # shows acoustic features for tracks for the given artist
from __future__ import print_function # (at top of module)
from spotipy.oauth2 import SpotifyClientCredentials
import json
import spotipy
import time
import sys
import spotipy.util as util
import spotipy.oauth2 as oauth2
CLIENT_ID = "894a0b2883b6401781... | kilshaw/Spotify-Remixer | spotipyaudiofetures.py | spotipyaudiofetures.py | py | 1,300 | python | en | code | 0 | github-code | 50 |
34755933789 | from flask_restful import Resource, reqparse
from models.usuario import UsuarioModel
class Usuario(Resource):
def get(self, id):
usuario = UsuarioModel.find_user(id)
if usuario:
return usuario.json(), 200
return {"message": "user not found"}
def delete(self, id):
u... | MagnoDutra/flask-restful-api | resources/usuario.py | usuario.py | py | 1,394 | python | en | code | 0 | github-code | 50 |
74269958875 | import re
from libs.base_client import BaseClient
from libs.common import md5
class SeHuaTang(BaseClient):
def __init__(self):
super().__init__()
self.rule = {
'start_url': 'forum.php?mod=forumdisplay&fid=103&page=%page',
'base_url': 'https://www.sehuatang.net',
... | atzouhua/crawle | clients/av/sehuatang.py | sehuatang.py | py | 1,118 | python | en | code | 1 | github-code | 50 |
18098633302 | from sklearn import datasets
import numpy as np
from matplotlib import pyplot as plt
# 1.load sample data.
boston = datasets.load_boston()
X, y = boston.data, boston.target
m, n = np.shape(X)
y = y.reshape(m, 1)
# 2. normalize.
np.set_printoptions(precision=4)
u = np.mean(X, axis=0)
X = X - u
sigma = np.mean(X**2, ... | buptstehc/ml | lr/ne.py | ne.py | py | 526 | python | en | code | 0 | github-code | 50 |
73702222234 | import time
import datetime
from scrapy.selector import Selector
from scrapy.http import Request
from vtvspider import VTVSpider, get_nodes, extract_list_data, extract_data
import MySQLdb
INSERT_AWARD_RESULTS = 'INSERT INTO sports_awards_results (award_id, category_id, genre, location, season, result_type, participant... | headrun/SWIFT | SPORTS/sports_spiders/scripts/dev_scripts5/heisman_spider.py | heisman_spider.py | py | 4,648 | python | en | code | 1 | github-code | 50 |
2070367749 | from omni.isaac.gym.vec_env import VecEnvBase
env = VecEnvBase(headless=True)
from franka_move_task import FrankaMoveTask
task = FrankaMoveTask(name="Franka")
env.set_task(task, backend="torch")
from stable_baselines3 import PPO
from stable_baselines3.common.callbacks import BaseCallback
from os.path import exists
i... | Battlemech/Autonomous-Agents | franka_move/franka_train.py | franka_train.py | py | 2,264 | python | en | code | 0 | github-code | 50 |
26951848240 | import dis
def main():
a=int(input())
if a%2==0:
for i in range(0,a,2):
print(i)
else:
i=1
while i<=a:
print(i)
i+=2
#main()
dis.dis(main)
| jero98772/toma_nota | clases/lenguajes_programacion/jcoco/b.py | b.py | py | 158 | python | en | code | 0 | github-code | 50 |
32871865820 | import torch.nn as nn
class Convolution(nn.Module):
def __init__(self,c_in, c_out, k, s, p, bias=False):
super(Convolution, self).__init__()
self.conv = nn.Sequential(
nn.Conv2d(c_in,c_out,k,s,p,bias),
nn.BatchNorm2d(c_out),
nn.LeakyReLU(0.1)
)
def f... | wuxianjun666/darknet | model.py | model.py | py | 2,474 | python | en | code | 0 | github-code | 50 |
32619444210 | import cv2
import numpy
import uuid
from PIL import Image, ImageDraw, ImageFont, ImageColor
from src.utils import timer_func, convert_to_gray, IMAGE_EXTENSIONS, get_full_filename, get_rendered_filename, \
RENDERED_IMAGE_EXTENSION
pyxelart_defaults = {
'width': 128,
'height': 72,
'method': 'pyxelate',... | PittCaleb/pyxelArt | src/pyxelart.py | pyxelart.py | py | 8,903 | python | en | code | 0 | github-code | 50 |
71786615194 | n = int(input())
p = list(map(int, input().split()))
p.sort()
weigh = p[0]
if weigh > 1:
print(1)
else:
for i in range(1, n):
# p에서 i번째 수를 뽑았을 때 이 수가 지금까지 뽑은 수 보다 크되, 적어도 차이가 2 이상이어야 한다.
# 만약 weigh가 20이고 뽑은게 21이면 weigh에 더할 수 있기 떄문이다.
if weigh + 1 < p[i]:
print(weigh + 1)
... | JH-TT/Coding_Practice | BaekJoon/Greedy/2437.py | 2437.py | py | 492 | python | ko | code | 0 | github-code | 50 |
28826721749 | # 开发作者:crowder Zhuo
# 开发时间:2019/10/10 20:44
# 文件名称: try022
# 开发工具:Python
tour = []
height = []
hei = 100.0 # 起始高度
tim = 10 # 次数
for i in range(1, tim + 1):
# 从第二次开始,落地时的距离应该是反弹高度乘以2(弹到最高点再落下)
if i == 1:
tour.append(hei)
else:
tour.append(2 * hei)
hei /= 2
height.... | shuai2931806756/test001 | try022.py | try022.py | py | 527 | python | zh | code | 0 | github-code | 50 |
23903709790 | #Treasures island game
print("Welcome to Treasure Island.")
print("Your mission is to find the treasure.")
#Different paths to choose
choice = input("You're at a lake house in the forest, do you go right or left?\n")
if choice == "left":
choice2 = input("You've made it to the docks, do you want to 'wait' or 'swim' ... | XavierTackett/Self_python_projects | simple_games.py | simple_games.py | py | 1,953 | python | en | code | 0 | github-code | 50 |
74381971036 | """
Quicksort: Time Complexity
Best: O(log(n))
Worst: O(n^2)
Space Complexity:
Worst: O(log(n))
4, 2, 7, 3, 1, 6
pivot = 4
"""
def quickSort(arr):
elements = len(arr) # get number of elements
# Base case
if ... | lauras5/python_algs | sorting/quicksort.py | quicksort.py | py | 1,394 | python | en | code | 0 | github-code | 50 |
22117380357 | import math
STEPSIZE = 0.1 # mm/step
MAX_RPM = 500 # max motor speed
TRAVEL_SPEED = 40 # mm/sec
STEPS_PER_REV = 200
x_steps = []
y_steps = []
x_rpms = []
y_rpms = []
x = 0
y = 0
def distance_between_coords(x1, y1, x2, y2):
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
# returns number of motor steps needed to go ... | 3chospirits/Zen-Sand-Table--ES50-Final-Project | archive/coord_to_motor.py | coord_to_motor.py | py | 1,470 | python | en | code | 0 | github-code | 50 |
34656680824 | _author_ = 'jake'
_project_ = 'leetcode'
# https://leetcode.com/problems/maximum-depth-of-n-ary-tree/
# Given a n-ary tree, find its maximum depth.
# The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
# Recursive function. Base cases of no node or leaf n... | jakehoare/leetcode | python_1_to_1000/559_Maximum_Depth_of_N-ary_Tree.py | 559_Maximum_Depth_of_N-ary_Tree.py | py | 736 | python | en | code | 49 | github-code | 50 |
19528465138 | import unittest
from lxml import objectify
from color_gamma_analyzer.brightness_processing import brightness_processing
class TestBrightnessProcessingMethod(unittest.TestCase):
def test_brightness_processing(self):
brightness_processing(2, "./resources/data_files/input_bp_test.xml",
... | yzghurovskyi/ColorGammaAnalyzer | color_gamma_analyzer/tests/test_brightness_processing.py | test_brightness_processing.py | py | 1,724 | python | en | code | 2 | github-code | 50 |
32797968749 | import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from LP_util import get_normalized_data
from sklearn.utils import shuffle
'''
Notes added by myself as learning exercise and practice. Code by the
Lazy Programmer for Deep Learning Part 2 (Modern Deep Learning in Python).
'''
class HiddenLay... | geoffder/learning | LP_deep_learning_2/LP_dropout_tensorflow.py | LP_dropout_tensorflow.py | py | 7,126 | python | en | code | 0 | github-code | 50 |
23445476397 | #!/usr/bin/env python3
import torch
from torch.nn.functional import softplus
from .. import settings
from ..functions import add_diag
from ..lazy import (
BlockDiagLazyTensor,
DiagLazyTensor,
KroneckerProductLazyTensor,
MatmulLazyTensor,
NonLazyTensor,
RootLazyTensor,
)
from ..likelihoods impo... | KhurramPirov/Log-Determinants-Estimator | demo/FLOVE/likelihoods/multitask_gaussian_likelihood.py | multitask_gaussian_likelihood.py | py | 15,064 | python | en | code | 0 | github-code | 50 |
28887970366 | ############################################################
# CMPSC442: Homework 5
############################################################
student_name = "John_Hofbauer"
############################################################
# Imports
# What modules can I import? -- collections, itertools, math, random, ... | JohnHofbauer/Artificial-Intelligence | Assignment 5/homework5_jch5769.py | homework5_jch5769.py | py | 6,509 | python | en | code | 0 | github-code | 50 |
10759963601 | import generic
import streamlit as st
import spacy_streamlit
from itertools import combinations
import json
import sys
def show_layout(type='page',data=None,layout=[.1,.6]):
cols = st.columns(layout)
returns = []
if type == 'page':
data = ['Prev Page','Next Page']
for col_idx, col in enumerat... | staedi/rel_annotate | frontend.py | frontend.py | py | 15,136 | python | en | code | 0 | github-code | 50 |
40212789780 | import FWCore.ParameterSet.Config as cms
vertexRecoBlock = cms.PSet(
vertexReco = cms.PSet(
seccut = cms.double(6.0),
primcut = cms.double(1.8),
smoothing = cms.bool(False),
finder = cms.string('avr'),
minweight = cms.double(0.5),
weightthreshold = cms.double(0.001)
)
)
| cms-sw/cmssw | RecoBTag/SecondaryVertex/python/vertexReco_cff.py | vertexReco_cff.py | py | 286 | python | en | code | 985 | github-code | 50 |
20935076901 | # 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 mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if len(lists) == 0... | Jason-Woo/leetcode_problemset | Merge k Sorted Lists/code.py | code.py | py | 1,200 | python | en | code | 0 | github-code | 50 |
71027155036 | # -*- coding: utf-8 -*-
"""
Module : B8IT105 - Programming for Big Data
Assignment : CA3 - 10 function sequence calculator
using map, reduce, filter and generator.
Description : Unit tests for the sequence calculator application.
Student Code : 10541255
Student Name : Alyosha Pulle
"""
import... | alyoshapulledbs/B8IT105 | CA3/TestSequenceCalculatorApp.py | TestSequenceCalculatorApp.py | py | 3,763 | python | en | code | 0 | github-code | 50 |
2665724051 | import webbrowser as wb
import speech_recognition as sr
from time import ctime
import time
import os
from gtts import gTTS
import search_google.api
# the user is asking for their covfefe social media sources here
# we will say clara tell me news about refugees
def facebook(topic):
speak("Hold on "+name+" , I will r... | tinahaibodi/claraAI | data science/visionex.py | visionex.py | py | 3,141 | python | en | code | 0 | github-code | 50 |
7986839948 | import os
import shutil
from aiogram import Dispatcher, types
from aiogram.dispatcher import FSMContext
from aiogram.types import InputFile
from aiogram.utils import markdown
from utils.bot_init import bot
from utils.checks.curators_check import *
from utils.log import logging
from utils.states import CuratorsChecks
... | Theones777/TTS_bot | handlers/curators.py | curators.py | py | 11,806 | python | en | code | 0 | github-code | 50 |
19990773923 | # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
from scrapy.pipelines.images import ImagesPipeline
import scrapy
import hashlib
# class WeiboPipeline(object):
# def proc... | wangj98/weibo | weibo/pipelines.py | pipelines.py | py | 1,137 | python | en | code | 0 | github-code | 50 |
27989542722 | #DAY 19 0F 100
#TO FIND IF NUMBER IS PALLINDRONE OR NOT IN PYTHON
#taking input
num =int(input("Enter a number to check if its pallindrone or not: "))
#initialise the value
temp =num
rev = 0
#using while loop
while temp !=0:
digit = rev*10
rev = temp %10 +digit
temp = temp// 10
if num ==rev:
print("Th... | ayushigeorge/python_projects | day19of100.py | day19of100.py | py | 407 | python | en | code | 3 | github-code | 50 |
73696114074 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
import subprocess
import time
"""Takes a textfile with ip-adresses and their frequency as input, performs
whois-request using the Linux-Bash and produces a csv-output showing the
ip-address and the correspondign frequency, the countrycode and the owner
of the ip-ad... | alex-gehrig/whois-helper | whois-helper.py | whois-helper.py | py | 2,836 | python | en | code | 0 | github-code | 50 |
13719821630 | # -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib.sites.models import Site
from django.contrib.syndication.views import Feed
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.views.generic.base import TemplateView
from django.views.generic.detail... | lzjun567/django_blog | apps/blog/views.py | views.py | py | 6,195 | python | en | code | 206 | github-code | 50 |
23924691708 | # extract useful information from the dat file
import re
import sys
def readMETA(str) :
# return the seq id, gene seq length, allele type,
# and description
ret = {}
regex = re.compile(r'ID\s{3}(.*); SV \d+; standard; DNA; HUM; (\d+) BP.')
ret1 = regex.search(str)
if ret1 :
ret['ID'] ... | YingZhou001/Immuannot | scripts/scripts/easyipd/IPDtools.py | IPDtools.py | py | 11,239 | python | en | code | 3 | github-code | 50 |
33742333601 | """Base model object, which defines the power spectrum model.
Private Attributes
==================
Private attributes of the model object are documented here.
Data Attributes
---------------
_spectrum_flat : 1d array
Flattened power spectrum, with the aperiodic component removed.
_spectrum_peak_rm : 1d array
... | fooof-tools/fooof | specparam/objs/fit.py | fit.py | py | 60,820 | python | en | code | 312 | github-code | 50 |
9565218848 | import os
import base64
from cryptography.fernet import Fernet
import sent_mes
import wp
class Ramsomware:
def __init__(self, key=None):
self.key = key
self.typ_crypt = None
self.file_target = ['txt']
def generator_key(self):
self.key = Fernet.generate_key()
... | Galateos/edu_ramsomware | main.py | main.py | py | 2,593 | python | en | code | 1 | github-code | 50 |
19398309415 | import kopf
import kubernetes
@kopf.on.create('muge.net', 'v1', 'databases')
def create_fn(body,spec, meta, status, **kwargs):
# Get info from Database object
name = body['metadata']['name']
namespace = body['metadata']['namespace']
db_type = spec['type']
tag = spec['tag'] if spec['tag'] else 'lat... | ianmuge/kopf-test | operator/main.py | main.py | py | 1,939 | python | en | code | 0 | github-code | 50 |
39675483796 | # Just listing some resources with AWS's pagination
# while logging the API Calls from AWS
import boto3
import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
def list_lambdas():
client = boto3.client('lambda')
paginator = client.get_paginator('list_functions')
response_iterator = pa... | gelouko/useful-scripts | aws/list_frenzy.py | list_frenzy.py | py | 1,700 | python | en | code | 1 | github-code | 50 |
1165190937 | import pygame
# A class that handles the unit object.
class Unit:
# Initializes a unit object.
# x,y = the unit's coordinates within the game window
# color = the unit's color
#
def __init__(self, x, y, color):
self.x = x
self.x_target = x
self.y = y
self.y_targ... | abmarney/rts-pub | unit.py | unit.py | py | 1,747 | python | en | code | 0 | github-code | 50 |
74269272475 | import cv2
import numpy as np
import configparser
from configparser import SafeConfigParser
def frame_change(pos):
global posicao, new
posicao = pos
new = True
def sliders_update(val):
global new
new = True
def main():
config = configparser.ConfigParser()
config.read('config.ini')
ar... | Atzingen/rastreador-pendulo | cmd_code/set_filters.py | set_filters.py | py | 5,550 | python | en | code | 0 | github-code | 50 |
72751883675 | import sys
##fonctions
def validation_arg(qte = 3, msg_usage = "script.py input output"):
if len(sys.argv) != qte:
print("Option illégale")
print("Usage: ", msg_usage)
sys.exit(-1)
def extraire_metaDonnees(fichier):
fh = open(fichier, "r")
valeur1, valeur2 = fh.readline().split()
... | AnneMay/DESS-bioinfo | INF8212/cp_dict.py | cp_dict.py | py | 1,230 | python | fr | code | 0 | github-code | 50 |
1376070763 | import math
TickSize = .01 # change it to .1 for illiquid stocks
LotSize = 100
OptionSize = 100
M = 10 # max round lots for holding
K = 5 # max round lots for each trading action
H = 5 # mean reversion half life
S0 = 50
Lambda = math.log(2) / H
theta = .5
sigma = .1
sigma_dh = .01
kappa = 1e-4
kappa_dh = .1
alpha = .... | sophiagu/RLF | gym-rlf/gym_rlf/envs/Parameters.py | Parameters.py | py | 395 | python | en | code | 7 | github-code | 50 |
25971216929 | #!/usr/bin/env python3
import paho.mqtt.client as mqtt
import uuid
import sys
LOCAL_MQTT_HOST="169.62.47.162"
LOCAL_MQTT_PORT=1883
LOCAL_MQTT_TOPIC="persist_faces"
def on_connect_local(client, userdata, flags, rc):
print("connected to local broker with rc: " + str(rc))
def on_message(client,userdata, msg):
tr... | sthiruvallur/face_detection_edge_to_cloud | cloud_src/cloud_persist_msg/persist_image.py | persist_image.py | py | 1,040 | python | en | code | 1 | github-code | 50 |
33002225914 | from django.urls import path
from . import views
urlpatterns = [
path('', views.myAccount),
path('registerUser/', views.registerUser, name='registerUser'),
path('login/', views.login, name='login'),
path('logout/', views.logout, name='logout'),
path('helloWorld/', views.helloWorld, name='helloWorl... | moxex/yetti-tech | users/urls.py | urls.py | py | 326 | python | en | code | 0 | github-code | 50 |
40886710059 | n = f = 0
while True:
#numero inteiro
try:
n = int(input('Digite um número inteiro: '))
except Exception as ValueError:
print ('Número inteiro inválido. ', end='')
except Exeception as KeyboardInterrupt:
print ('O usuário preferiu não informar')
else:
break
while True:
#numero float
try:
f = float... | lucasclemerson/course-python | exercicios/exe113.py | exe113.py | py | 675 | python | pt | code | 0 | github-code | 50 |
25730093355 | from django.urls import path
from . import views
app_name = 'posts'
urlpatterns = [
path('', views.index, name='index'),
path('create/', views.create, name='create'),
path('<int:pk>', views.detail, name='detail'),
path('<int:pk>/update/', views.update, name='update'),
path('<int:pk>/delete/', view... | myeonghwan57/Pair_project_01 | matdori/posts/urls.py | urls.py | py | 692 | python | en | code | 0 | github-code | 50 |
22351628247 | import urllib, io
from Tkinter import *
from PIL import Image, ImageTk
root = Tk()
fd = urllib.urlopen("http://www.google.com/images/srpr/logo11w.png")
imgFile = io.BytesIO(fd.read())
im = ImageTk.PhotoImage(Image.open(imgFile)) # <-- here
image = Label(root, image = im)
image.grid(row = 7, column = 1)
root.mainlo... | MBAustin/happy-birthday-dad | test_files/imageTest.py | imageTest.py | py | 324 | python | en | code | 0 | github-code | 50 |
35685315220 | import numpy as np
import matplotlib.pyplot as plt
fig, ax_lst = plt.subplots(1, 1)
x = np.linspace(0, 2, 100)
y = np.square(np.sin(x-2))*np.exp(-1*np.square(x))
plt.plot(x, y, label='f(x)')
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title('Exercise 10')
plt.legend()
plt.show() | wyfapril/CS6112017 | PythonExercises/exercise10.py | exercise10.py | py | 283 | python | en | code | 0 | github-code | 50 |
7466642366 | from config import timevert
from aiogram.types import ReplyKeyboardRemove, \
ReplyKeyboardMarkup, KeyboardButton, \
InlineKeyboardMarkup, InlineKeyboardButton
i = {
"бургерок": {"type": "food", "price": 95, "value": 50, "emoji": "🍔"},
"сочок": {"type": "food", "price": 40, "value": 30, "emoji": "🧃... | marcoflacko/holy | shop.py | shop.py | py | 3,052 | python | en | code | 0 | github-code | 50 |
13114569053 | from dotenv import load_dotenv
from os import getenv, makedirs
from os.path import isdir
from shutil import rmtree
from datetime import datetime, timedelta, date
from collections import Counter
from multiprocessing import cpu_count
def get_uf_file(path_file):
"""
Retorna a UF a qual um arquivo é referente
... | marcoswb/brazilian-climatology | utils/functions.py | functions.py | py | 7,367 | python | en | code | 0 | github-code | 50 |
31634699775 | try:from .internetBytesIO import *
except ImportError: from internetBytesIO import *
from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES, PKCS1_OAEP
import os, subprocess
def getBackupAccount():
f=open(os.path.join(BASE_DIR_PATH, "data", "backupAccount"), "r")
j... | HeronErin/hermesfs | src/backupUtils.py | backupUtils.py | py | 1,645 | python | en | code | 0 | github-code | 50 |
23646206849 | import numpy as np
import pandas as pd
import plotly.graph_objects as go
import dash_core_components as dcc
import dash_html_components as html
from jupyter_dash import JupyterDash
from plotly.subplots import make_subplots
from dash.dependencies import Input, Output
from visualizers import BaseVisualizer
class Asset... | yuhsuanyang/stock_market_analysis | code/visualizers/asset_debt_visualizer.py | asset_debt_visualizer.py | py | 5,608 | python | en | code | 1 | github-code | 50 |
28076365082 | # -*- coding: utf-8 -*-
"""
@Author 坦克手贝塔
@Date 2022/2/24 16:36
"""
"""
给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
给定的有序链表: [-10, -3, 0, 5, 9]
一个可能的答案是:[0, -3, 9, -10, null, 5]
"""
"""
思路:快慢指针每次找中间一个即可
"""
# Definition for singly-linked list.
class ListNode(object):
... | TankManBeta/LeetCode-Python | problem109_medium.py | problem109_medium.py | py | 1,560 | python | en | code | 0 | github-code | 50 |
33363570959 | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
#
# Michael Beck
#
# Core
import json
import logging
import datetime
import os
import sys
# Third party
import wx
import wx.adv
# Own
from client.commands import bind_command, check_cmd, sample_cmd, download_cmd, \
login_cmd, logout_cmd, update_archives_cmd
if geta... | UWDigitalAg/TerraByte_Client | client_app.py | client_app.py | py | 27,873 | python | en | code | 2 | github-code | 50 |
20935625661 | # -*- coding:utf-8 -*-
class Solution:
# 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
# 函数返回True/False
def duplicate(self, numbers, duplication):
# write code here
flag = [0 for _ in range(len(numbers))]
for i in range(len(numbers)):
if flag[numbers[i]] != 0:
dupl... | Jason-Woo/leetcode_problemset | jz_problemset/jz50/code.py | code.py | py | 499 | python | en | code | 0 | github-code | 50 |
72611241114 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from astlib.tensor_utils.analyze import level
class PositionalEncoder(nn.Module):
def __init__(self, d_model, max_len=5000):
super(PositionalEncoder, self).__init__()
pe = torch.zeros(max_len, d_model)
position ... | haseebs/semantic-code-search | encoders/positional_encoder.py | positional_encoder.py | py | 1,635 | python | en | code | 4 | github-code | 50 |
11226024856 | from bitarray import bitarray
def compute_if_absent(some_dict, key, default_value_func):
key_value = some_dict.get(key)
if key_value is None:
key_value = default_value_func()
some_dict[key] = key_value
return key_value
def get_from_multi_level_dict(some_dict, keys):
current_dict = some_dict
for key ... | yestinchen/star_retrieval | vsimsearch/utils.py | utils.py | py | 781 | python | en | code | 0 | github-code | 50 |
45828721608 | from os import environ
import boto3
from flask import Blueprint, jsonify
from flask_api import status
BUCKET_NAME = environ.get("BUCKET_NAME")
AWS_ENDPOINT = environ.get("AWS_ENDPOINT")
service = Blueprint("service", __name__)
@service.route("/")
def healthcheck():
return "Healthy", status.HTTP_200_OK
@serv... | jim-sheldon/Flask-localstack | service/handlers.py | handlers.py | py | 663 | python | en | code | 0 | github-code | 50 |
38460413370 | import numpy as np
from PIL import Image, ImageDraw
def create_go_board_image(board, file_path):
# Define the colors for the stones and empty positions
black_stone = (0, 0, 0)
white_stone = (255, 255, 255)
empty_pos = (222, 184, 135)
# Create a blank image for the board
img_size = board.sh... | Jiankun-Huang/JBX-Go | modules/visualize.py | visualize.py | py | 1,225 | python | en | code | 1 | github-code | 50 |
25900615154 | #!/usr/bin/env python
import argparse
import atexit
import signal
import sys
import threading
import utils
import mapsolvers
import CNFsolvers
from MarcoPolo import MarcoPolo
def parse_args():
parser = argparse.ArgumentParser()
# Standard arguments
parser.add_argument('infile', nargs='?', type=argparse... | batchenRothenberg/AllRepair | python/marco.py | marco.py | py | 11,275 | python | en | code | 8 | github-code | 50 |
26901819625 | import abc
from typing import List, Tuple
class ClassificationCorpusPreprocessor(abc.ABC):
'''
input: path to input file
return: list of tuples (class_no, class_name, text)
'''
@abc.abstractmethod
def preprocess(self, file_path:str)->List[Tuple[str, str, str]]:
pass
class TouTiaoNewsPr... | shazi7804/aws-cdk-sagemaker-model-endpoints | app/nlp_processing/preprocess.py | preprocess.py | py | 2,563 | python | en | code | 1 | github-code | 50 |
27213230237 | #Returns a dictionary of types and their advantages.
#Also returns a dictionary of types and the file location to the label.
#These type_numbers are arbitrarily given to the types
#Its only for consistency
types = ["Normal","Fighting","Flying","Poison","Ground","Rock","Bug","Ghost","Steel","Fire","Water","Grass... | prenio/Type-Master | Type Master/TypeEffectiveness.py | TypeEffectiveness.py | py | 1,499 | python | en | code | 0 | github-code | 50 |
18661870882 | '''
Main utility functions
'''
import numpy as np
import tensorflow as tf
def preprocess_targets(targets, words2int, batch_size):
left_side = tf.fill([batch_size, 1], words2int['<SOS>'])
right_side = tf.strided_slice(targets, [0, 0], [batch_size, -1], [1, 1])
preprocessed_targets = tf.concat([left_side, r... | manikanthr5/OpenDomainChatbot | nlp_utils.py | nlp_utils.py | py | 1,730 | python | en | code | 11 | github-code | 50 |
14604091999 | #!/usr/bin/python
import os
import subprocess
import re
import shlex
files = [f for f in os.listdir('.') if os.path.isfile(f)]
cwd = os.getcwd()
replaced = re.sub(' ', '\ ', cwd)
homeworkfiles = []
homeworkdirectories = []
for f in files:
if f[0] == 'e':
homeworkfiles.append(f)
ho... | elhanarinc/ceng495 | 495-hw3/untar.py | untar.py | py | 641 | python | en | code | 0 | github-code | 50 |
1500206109 | import sys
import pygame
from settings import Settings
from ship import Ship
def run_game():
# 初始化并创建屏幕对象
pygame.init()
screen = pygame.display.set_mode((1200,800))
pygame.display.set_caption("Alien Invasion")
# 创建一艘飞船
#背景色
# bg_color=(129,216,207)
# 开始游戏的主循环
while True:
... | swq90/python | exercise/alien_invasion/alien.py | alien.py | py | 656 | python | en | code | 0 | github-code | 50 |
34468730555 | """Read class metadata."""
import json
from typing import Iterable
import polars as pl
from polars.type_aliases import FrameType as FrameType
from mo.core import dtypes
from mo.core.interfaces import IReader
from mo.core.typing import PathStr
class ManifestReader(IReader):
"""Read page view data from a CSV."""... | coursekata/mo | mo/core/read/classes.py | classes.py | py | 2,663 | python | en | code | 0 | github-code | 50 |
32880893456 | # LEGB rules
# Local, enclosed, global and built_in
# Built-in Scope
from math import pi
pi = 15
def outer():
pi = 26
def inner():
# pi = 7
nonlocal pi
pi+=1
print(pi)
inner()
outer()
| SumathKetharaju/Sumanth_Uploads | sumanth_Initial_Programs/local_global.py | local_global.py | py | 237 | python | en | code | 1 | github-code | 50 |
32006979748 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 31 17:03:58 2018
@author: bangyc
"""
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(618)
# number of arm
K = 5
# probability distribution
true_prob = [1/6, 1/2, 2/3, 3/4, 5/6]
beta_prior_alpha1 = [1, 1, 1, 1, 1]
beta_prior_al... | yangjh39/CSE-547-ML-for-Big-Data | Tompson Sampling/Tompson Sampling.py | Tompson Sampling.py | py | 2,570 | python | en | code | 0 | github-code | 50 |
11026558740 | # -*- coding: utf-8 -*-
from odoo.addons.l10n_eu_oss.models.eu_tag_map import EU_TAG_MAP
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tests import tagged
@tagged('post_install', 'post_install_l10n', '-at_install')
class TestOSSBelgium(AccountTestInvoicingCommon):
@classmetho... | anhjean/beanbakery_v15 | addons/l10n_eu_oss/tests/test_oss.py | test_oss.py | py | 3,836 | python | en | code | 5 | github-code | 50 |
33490538960 | f = open('A-small-attempt0.in')
out = open('a.txt', 'w')
T = int(f.readline().strip())
for case in range(T):
row1 = int(f.readline().strip())
for i in range(row1-1):
f.readline()
set1 = set(int(i) for i in f.readline().strip().split())
for i in range(4-row1):
f.readline()
row2 = int(... | wind1900/exercise | codejam2014/A.py | A.py | py | 754 | python | en | code | 2 | github-code | 50 |
36587083995 | def isprime(n):
n = abs(int(n))
if n < 2:return (False)
if n == 2:return (True)
if not n & 1: return (False)
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0:return (False)
return (True)
def z(contfrac, a=1, b=0, c=0, d=1):
for x in contfrac:
while a > 0 and b > 0 and c... | cmrfrd/Random-Python | googlechallenge.py | googlechallenge.py | py | 1,466 | python | en | code | 0 | github-code | 50 |
25795503433 | try:
4/0
except ZeroDivisionError as e:
print(e)
# 4/0만 하면 ZeroDivisionError라는 애러가 뜬다
# 그렇기 때문에 try로 애러를 쓰고 except에 ZeroDivisionError를 미리 잡아주면 print했을때 애러의 종류가 출력된다.
try:
f = open('none', 'r')
except FileExistsError as e:
print(str(e))
else:
data = f.read()
print(data)
f.close()
# 파일이 없다... | SIRIJEONG/python | test39.py | test39.py | py | 1,430 | python | ko | code | 0 | github-code | 50 |
30877593895 | # -*- coding: utf-8 -*-
"""
Exercise 3: Area of a Room
Write a program that asks the user to enter the width and length of a room.
Once the value has been read, your proram should compute and display the area
of the room.
The length and the width will be entered as floating point numbers.
(include units in... | grypy/Introduction_Exercises | Room_Area.py | Room_Area.py | py | 653 | python | en | code | 0 | github-code | 50 |
2269258358 | #%%
import time
import asyncio
import pandas as pd
import gradio as gr
from utils import google
from utils.credentials import *
variables = {
"project_id": "vtxdemos",
"region": "us-central1",
"instance_name": "pg15-pgvector-demo",
"database_user": "emb-admin",
"database_password": DATABASE_PASSWOR... | jchavezar/vertex-ai-samples | gen_ai/rag/rag_upload_while_query_vertex.py | rag_upload_while_query_vertex.py | py | 1,518 | python | en | code | 10 | github-code | 50 |
13127491780 | import socket
import struct
import time
from PIL import Image
def recvall(receiver, buffer_size=65536):
data_buffer = b''
data_chunk=receiver.recv(buffer_size)
while len(data_chunk) >= buffer_size:
data_buffer+=data_chunk
data_chunk=receiver.recv(buffer_size)
data_buffer+=data_chunk
... | Trevahok/Python-VNC | trev_receiver.py | trev_receiver.py | py | 999 | python | en | code | 1 | github-code | 50 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.