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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
22316226689 | from keras import applications
from keras.preprocessing.image import ImageDataGenerator
from keras import optimizers
from keras.models import Sequential, Model
from keras.layers import Dropout, Flatten, Dense
from keras.layers import Input, BatchNormalization
from keras import metrics
import time
import cv2
img_width,... | kirklandnuts/image_classification | src/train_var_sizes.py | train_var_sizes.py | py | 4,501 | python | en | code | 0 | github-code | 13 |
38240297696 | #! /usr/bin/python3
import sys
import math
def readIn():
for line in sys.stdin:
uv = line.split()
return int(uv[0]), int(uv[1])
h, v = readIn()
angle_rad = math.radians(v)
sinus = math.sin(angle_rad)
ans = math.ceil(h/sinus)
#print(ans)
sys.stdout.write(str(ans))
| AnimalMother83/Kattis-solutions | ladder.py | ladder.py | py | 283 | python | en | code | 0 | github-code | 13 |
10453549953 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
# ======================================================
# @File: : main
# @Author : forward_huan
# @Date : 2023/2/15 20:23
# @Desc :
# ======================================================
import argparse
import os
import re
import threading
from pip._vendor.distli... | forwardhuan/PreQtUI | main.py | main.py | py | 3,624 | python | en | code | 0 | github-code | 13 |
10366143787 | # Программирование на языке высокого уровня (Python).
# https://www.yuripetrov.ru/edu/python
# Задание task_07_02_02.
#
# Выполнил: Буц И.Д.
# Группа: АДЭУ-211
# E-mail: !!!
"""
Ошибки (номера строк через пробел, данная строка - №2): !!!
"""
def primes(a, b):
"""Вернуть список простых чисел на отрезк... | Igor69-web/OOAP-211 | лаб7/2.py | 2.py | py | 1,317 | python | ru | code | 0 | github-code | 13 |
16011525630 | # -*- coding: utf-8 -*-
"""
Created on Sun May 5 16:08:11 2019
@author: 12718
"""
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
import time
time0 = time.time()
mnist = input_data.read_data_sets('MNIST_data', one_hot = True)
x = tf.placeholder('float', [None, 7... | MingyangChen1994/machinelearning | testcnn.py | testcnn.py | py | 2,899 | python | en | code | 0 | github-code | 13 |
71603041618 | from flask import Flask
from flask_restful import Resource, Api, reqparse
from flask import request
from flask import jsonify
from flask_cors import CORS
import json
import configparser
import networkx as nx
import graphWork as gw
app = Flask(__name__)
#api = Api(app)
CORS(app)
def get_steam_api_key():
config = c... | brandonsness/NetSciProj | src/python/app.py | app.py | py | 1,574 | python | en | code | 0 | github-code | 13 |
14212507430 | from __future__ import print_function
from __future__ import division
import pandas as pd
import torch
from torch.utils.data import Dataset, DataLoader, random_split
import torch.nn as nn
import torch.optim as optim
import numpy as np
import torchvision
from torchvision import datasets, models, transforms
import skima... | weimegan/brain-mris-race | train.py | train.py | py | 6,689 | python | en | code | 0 | github-code | 13 |
27583986519 | n=int(input())
list1=input().split()
flag=0
for i in range(n-1):
if n==1:
break
if int(list1[i])>int(list1[i+1]):
flag=1
break
if flag==0:
print("yes")
else:
print("no")
| devikamadasamy/beginner | sorted_or_not.py | sorted_or_not.py | py | 183 | python | en | code | 0 | github-code | 13 |
17504577849 | import random
from datetime import datetime, timedelta, timezone
from django.contrib import messages
from django.db.models import Q
from django.shortcuts import render, redirect
from card.forms import CardGenerateForm
from card.models import Card
def cards_list(request):
"""Render home page. Show card list"""
... | slychagin/cards-app | card/views.py | views.py | py | 5,250 | python | en | code | 1 | github-code | 13 |
26376674088 | # it needs pillow python library
import os
from PIL import Image, ImageEnhance, ImageFilter
path = "./imgs"
pathout = "/pyimgs"
for filename in os.listdir(path):
if filename == ".DS_Store":
continue
img = Image.open(f"{path}/{filename}")
edit = img.filter(ImageFilter.SHARPEN).convert('L')
cle... | Clearviss/A-D-inc. | Python_Projects/pajton/pyphotoeditor.py | pyphotoeditor.py | py | 412 | python | en | code | 1 | github-code | 13 |
29267560679 | from django.shortcuts import render
from django.shortcuts import HttpResponse
from .forms import *
from django.http import HttpResponseRedirect
import time
# Create your views here.
def index(request):
if request.method=='GET':
start = time.clock()
form1=inputform(request.GET)
if form1.is... | jatinjade007/fibonacciSeries | fibonacciSeries/views.py | views.py | py | 1,512 | python | en | code | 0 | github-code | 13 |
32256798783 | from mycroft import MycroftSkill, intent_file_handler
# from mycroft.util import play_wav
from mycroft.skills.audioservice import AudioService
import os
import wave
import struct
import math
import time
#
class SoundTuner(MycroftSkill):
def __init__(self):
MycroftSkill.__init__(self)
def initialize(se... | andlo/sound-tuner-skill | __init__.py | __init__.py | py | 4,174 | python | en | code | 2 | github-code | 13 |
29880592767 | """Exporter module."""
import asyncio
import sys
from logging import getLogger
from typing import Any, Dict, List
from prometheus_client import CollectorRegistry, Gauge, start_http_server
from prometheus_juju_exporter.collector import Collector
from prometheus_juju_exporter.config import Config
class ExporterDaemon... | canonical/prometheus-juju-exporter | prometheus_juju_exporter/exporter.py | exporter.py | py | 3,842 | python | en | code | 1 | github-code | 13 |
10907049075 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = '0.1a1'
CHUNKSIZE = 67108864 # 64 MiB size, for hashing in chunks
import sys
import os
import os.path
import argparse
from pathlib import Path
import hashlib
from datetime import datetime
import csv
from tqdm import tqdm
cli = argparse.ArgumentParser()
c... | mhvwerts/MANBAMM-data-management | superhash.py | superhash.py | py | 3,685 | python | en | code | 0 | github-code | 13 |
12895278993 | """
:mod:`Abstract data source <src.system.data_sources.data_source>` for a rider.
"""
from typing import Dict
from src.system.data_sources.data_source.python_dict import DataSourcePythonDict
from src.system.constants import DEFAULT_COL
class BaseRider(
DataSourcePythonDict
):
"""
:mod:`Abstract data s... | chingdaotze/actuarial-model | src/data_sources/annuity/model_points/model_point/riders/base.py | base.py | py | 1,164 | python | en | code | 1 | github-code | 13 |
2856051038 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl import flags
import numpy as np
import tensorflow.compat.v2 as tf
from valan.framework import common
from valan.framework import hparam
from valan.r2r import constants
from valan.r2r impor... | google-research/valan | r2r/env_ndh_test.py | env_ndh_test.py | py | 6,708 | python | en | code | 69 | github-code | 13 |
74324842577 | # %%
import re
import sys
# %%
def replace_latex_math_mode(text):
"""
Replaces LaTeX math mode expressions ($...$) with [tex: ...] in a given text.
"""
# Regular expression to match LaTeX math mode expressions
latex_math_mode_pattern = r'\$(.*?)\$'
# Replace LaTeX math mode expressions with [te... | Krypf/useful_program_20230616 | markdown_to_hatena.py | markdown_to_hatena.py | py | 2,478 | python | en | code | 0 | github-code | 13 |
40640156881 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Format insar names and images
#
# By Rob Zinke 2019
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Import modules
from datetime import datetime, time
import numpy as np
import matplotlib.pyplot as plt
from osgeo import gdal
####################################
### --- Geographic tra... | EJFielding/InsarToolkit | MetaFormatting/InsarFormatting.py | InsarFormatting.py | py | 3,125 | python | en | code | 4 | github-code | 13 |
25683926542 | #!/usr/bin/env python3
#from statistics import NormalDist
# sigma = standarddev/sqrt(n)
# Store 1 array of mu
# Store 1 array of sigma
# search with mu to limit
# In limited space, do below
#NormalDist(mu=2.5, sigma=1).overlap(NormalDist(mu=5.0, sigma=1))
# take average of all overlaps
#[0.1, 0.9, 0.3, 0.3] -> 0... | clairemcwhite/transformer_infrastructure | hf_seqsim.py | hf_seqsim.py | py | 27,653 | python | en | code | 2 | github-code | 13 |
74564285458 | """
_InsertComponent_
MySQL implementation of UpdateWorker
"""
__all__ = []
import time
from WMCore.Database.DBFormatter import DBFormatter
class UpdateWorker(DBFormatter):
sqlpart1 = """UPDATE wm_workers
SET last_updated = :last_updated
"""
sqlpart3 = """ WHERE name =... | dmwm/WMCore | src/python/WMCore/Agent/Database/MySQL/UpdateWorker.py | UpdateWorker.py | py | 1,071 | python | en | code | 44 | github-code | 13 |
74909554896 | import math
def f(x):
funcao = math.exp(-x**2) - math.cos(x)
return funcao
a = float(input())
a_salvo = a
b = float(input())
b_salvo = b
L = float(input())
while True:
x = (a * f(b) - b * f(a)) / (f(b) - f(a))
if f(a)*f(b) < 0:
if abs(f(x)) > L:
if f(a)*f(x) > 0:
a... | Teuszin/Calculo-Numerico | Listas_do_Lop/Lista_02/Raiz_M_Cordas.py | Raiz_M_Cordas.py | py | 674 | python | pt | code | 0 | github-code | 13 |
19623047190 | # -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
class firstInFirstOut:
def processData(self, numberFrames, pages):
countPages = 0
controlFrameExit = 0
pagesInMem = list()
for i in range(len(pages)):
if np.isin(pages[i],pagesInMem):
pass
... | streeg/pseudo-os | memory/firstInFirstOut.py | firstInFirstOut.py | py | 803 | python | en | code | 0 | github-code | 13 |
20061336875 | """
Computer choice = rock/papers/scissors
User choice = input
Compare
"""
import random
options = ['rock', 'papers', 'scissors']
computer_choice = random.choice(options)
user_choice = input("Enter rock/papers/scissors : ")
if user_choice!="paper" and user_choice!="rock" and user_choice!="sci... | tejasps/Python_Basic_Projects | rock_papers_scissors.py | rock_papers_scissors.py | py | 772 | python | en | code | 0 | github-code | 13 |
8479410064 | from django.shortcuts import render, redirect
from .forms import ArticleForm, CommentForm
from .models import Article
# Create your views here.
def index(request):
articles = Article.objects.all()
context = {
"articles": articles,
}
return render(request, "articles/index.html", context)
def... | kimheekimhee/TIL | django/1018/articles/views.py | views.py | py | 974 | python | en | code | 1 | github-code | 13 |
10255541746 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 9 20:05:54 2020
@author: sarroutim2
"""
from torch.nn.utils.rnn import pack_padded_sequence
from torch.optim.lr_scheduler import ReduceLROnPlateau
import argparse
import csv
import h5py
import progressbar
import time
from utils import Vocabulary
f... | sarrouti/multi-class-text-classification-pytorch | train.py | train.py | py | 11,236 | python | en | code | 3 | github-code | 13 |
10273502877 | ################################################################################
## IMPORTS #####################################################################
################################################################################
#import data
import numpy as np
import random
from numpy import asarray as... | austinsherron/Python-Machine-Learning | utils/test.py | test.py | py | 4,484 | python | de | code | 0 | github-code | 13 |
16313989232 | """
This script will take multiple fasta files and it will delete samples within them
based on a list of names from a second file. It will return a "cleaned" fasta file
for each of the original files in a new directory.
Simon Uribe-Convers - December 1st, 2017 - http://simonuribe.com
"""
import sys
import os
from Bi... | uribe-convers/Genomic_Scripts | Delete_Sequences_in_Multiple_Files_Based_on_Names.py | Delete_Sequences_in_Multiple_Files_Based_on_Names.py | py | 2,376 | python | en | code | 0 | github-code | 13 |
24252937918 | import os
import json
import pandas as pd
import numpy as np
from tqdm import tqdm
import cv2
from .utils_dataset import NpEncoder
df = pd.read_csv("/data/datasets/KITTI/kitti_scene_infos.csv")
TARGET_SIZE = (256, 256)
class KittiBuilder:
def __init__(self, in_dir, seq_nb):
self.in_dir = in_dir
... | gaetan-landreau/epipolar_NVS | dataset/kitti_builder.py | kitti_builder.py | py | 8,203 | python | en | code | 0 | github-code | 13 |
72049840657 | #Pillai Lab
#Daniel Castaneda Mogollon
#This code reports the number of snps, indels, and divergence from a reference sequence against query sequences.
#It takes a reference sequence from a .fasta file and gets the difference from every other sequence. The reference
#sequence must have 'reference' in its header. It co... | dcm9123/pillai_lab | snp_finder.py | snp_finder.py | py | 3,372 | python | en | code | 0 | github-code | 13 |
40526187068 | from math import *
from stepper import *
STEP_PER_MM=0.0125
MM_PER_STEP=80
STEP_TMC2225_32_PER_MM=0.00125
MM_TMC2225_32_PER_STEP=800
#2GT 2mm per gear, 20 gear , 20*2=40mm a cycle
#1.8 per step, so 200 steps a cycle. then 0.2mm/step
trace_flg=0
def plat_plot_show():
pass
def plat_plot(x,y,para... | chuanjinpang/esp8266_upy_plotter_controller_fireware | corexy.py | corexy.py | py | 4,382 | python | en | code | 6 | github-code | 13 |
34862561619 | import time
def test_time(func, test_times=100):
def wrapper(*args, **kwargs):
# 计时
start = time.process_time()
for i in range(test_times):
result = func(*args, **kwargs)
elapsed = (time.process_time() - start)
print(func.__name__, ":")
print("Time used:... | GMwang550146647/leetcode | fundamentals/test_time.py | test_time.py | py | 411 | python | en | code | 0 | github-code | 13 |
48489364474 | #Vanshika Shah
#UCID: vns25
#Section 003
#! /usr/bin/env python3
# Echo Server
import sys
import socket
import codecs
import datetime, time
from datetime import timezone
import os
# Read server IP address and port from command-line arguments
serverIP = sys.argv[1]
serverPort = int( sys.argv[2] )
dataLen = 1000000
... | vns25/Computer-Networks | HW4/httpserver.py | httpserver.py | py | 3,265 | python | en | code | 0 | github-code | 13 |
6086116959 | import json
import os
import time
import uuid
from os.path import join, exists
import cclib
from rdkit.Chem.rdDistGeom import EmbedMolecule
from rdkit.Chem.rdForceFieldHelpers import MMFFOptimizeMolecule, UFFOptimizeMolecule
from rdkit.Chem.rdmolfiles import MolFromSmiles, MolToXYZBlock, MolToSmiles
from rdkit.Chem.rd... | jules-leguy/EvoMol | evomol/evaluation_dft.py | evaluation_dft.py | py | 26,818 | python | en | code | 48 | github-code | 13 |
25038372271 | import speech_recognition as sr
r = sr.Recognizer()
speech = sr.Microphone()
word = "hello this is a test"
with speech as source:
print("say hello this is a test")
audio = r.adjust_for_ambient_noise(source)
audio = r.listen(source)
try:
recog = r.recognize_wit(audio, key = "6Y4KLO4YTWDQSYQX... | msalem-twoway/TwoWayVoice | FunctionalityTests/matchMicToPhrase.py | matchMicToPhrase.py | py | 611 | python | en | code | 0 | github-code | 13 |
32837236415 | def lyrics_to_frequencies(lyrics):
myDict = {}
for word in lyrics:
if word in myDict:
myDict[word] += 1
else:
myDict[word] = 1
return myDict
rains = ['And', 'who', 'are', 'you', 'the', 'proud', 'lord', 'said',
'that', 'I', 'must', 'bow', 'so', 'low',
'Only', 'a', 'ca... | MysticSaiyan/MITx-6.00.1x | Python Modules/dictionary.py | dictionary.py | py | 1,148 | python | en | code | 0 | github-code | 13 |
70828874579 | # !/usr/bin/python
# -*- coding:utf-8 -*-
import sys
import time
import logging
from PyQt6.QtWidgets import (QWidget, QDialog, QHBoxLayout, QVBoxLayout, QTabWidget, QGridLayout, QLabel, QLineEdit, QTextEdit, QFileDialog, QToolTip, QPushButton, QApplication)
from PyQt6.QtGui import QFont
from PyQt6.QtCore import (QSize... | Glooow1024/paper_collector | main.py | main.py | py | 9,685 | python | en | code | 0 | github-code | 13 |
41267518876 | '''
@author Piero Orderique
@date 12 Jan 2021
This file is for testing linalg module
'''
from linalg import Matrix
mat1 = Matrix([
[1, 1, 2],
[3, 5, 8],
[3, 0, 4],
])
mat2 = Matrix([
[7, 0, 6],
[9, 8, 7],
[3, 9, 5],
])
print(mat1 + mat2) | pforderique/Python-Scripts | RandomScripts/Math/Linear_Algebra_Library/test_runner.py | test_runner.py | py | 266 | python | en | code | 1 | github-code | 13 |
30999315241 | from random import Random
from time import time
from math import cos
from math import pi
from inspyred import ec
import inspyred
from inspyred.ec import terminators
import math
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib.delaunay as triang
import matplotlib.patches as pat... | roosnic1/twotsp | traveling_santa_evo.py | traveling_santa_evo.py | py | 2,776 | python | en | code | 4 | github-code | 13 |
34950411455 | import configparser
from datetime import datetime
import os
from pyspark.sql import SparkSession
from pyspark.sql.functions import udf, col, monotonically_increasing_id
from pyspark.sql.functions import year, month, dayofmonth, hour, weekofyear, date_format,to_timestamp,dayofweek,from_unixtime
import pyspark.sql.functi... | MaryamAlMansour/Wrangling-with-Spark | home/etl.py | etl.py | py | 5,323 | python | en | code | 0 | github-code | 13 |
72320848657 | from django.http import HttpResponse
from rest_framework.renderers import JSONRenderer
from django.urls import reverse_lazy
from django.views.generic import ListView, DetailView, CreateView
from django.views.generic.base import TemplateView
from ToDo.serializer import TaskSerrializer
from ToDo.models import Task, Cate... | AshtiNematian/To_Do_List | Reminder/Reminder/ToDo/views.py | views.py | py | 1,621 | python | en | code | 0 | github-code | 13 |
6910666626 | import sys
import os
import time
from pathlib import Path
from abstract_component import NotificationMessage
# add parent directory to import space, so we can keep directory structure
current = os.path.dirname(os.path.realpath(__file__))
parent = os.path.dirname(current)
sys.path.append(parent)
from sirene.player imp... | lwilfert/05FeuerRoboter | katy_mainControl/global_controller.py | global_controller.py | py | 4,880 | python | en | code | 0 | github-code | 13 |
34799486412 | import os
def grab_images_from_video(video_path="", save_dir="", filename=""):
# -r 一秒截取多少张
# -vf fps=1/20 每隔20秒截取一张
os.system(
'ffmpeg -i ' + video_path + ' -f image2 -q:v 2 -vf fps=fps=1/2 ' + save_dir + '/' + filename + '_image-%4d.jpg')
video_path = '/home/xiehuaiqi/Videos/vlc_video_recordi... | Xiehuaiqi/python_script | cut_video/ffmpeg_cut.py | ffmpeg_cut.py | py | 555 | python | en | code | 0 | github-code | 13 |
27718378832 | import math
import numpy as np
def dot_product(input):
# print(sum([item[0]*item[1] + bias for item in input]))
return sigm(sum([item[0] * item[1] for item in input]))
def sigm(x):
return 1 / (1 + math.e ** (-x))
def count_error(expected, predicted):
return predicted - expected
def predict(point... | MarekUlip/CollegePythonScripts | Nonconventional-algs/navy_backpropag2.py | navy_backpropag2.py | py | 1,874 | python | en | code | 0 | github-code | 13 |
73389482577 | from prototype import Search, State, Action
from typing import Callable, Optional, Any, List, Union
import time
import random
import math
import pickle
from multiprocessing import Manager, Process
'''
A Prototype of a Node
'''
class Node:
def __init__(self, state:State, parent=None):
self.state = state
self... | TheanLim/MinimaxMCTS | mcts.py | mcts.py | py | 10,721 | python | en | code | 0 | github-code | 13 |
22334437985 | #Leetcode 226. Invert Binary Tree
#BFS
# 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 Solution1:
def invertTree(self, root: TreeNode) -> TreeNode:
if root =... | komalupatil/Leetcode_Solutions | Easy/Invert Binary Tree.py | Invert Binary Tree.py | py | 1,182 | python | en | code | 1 | github-code | 13 |
42014911165 | p=print
f=list(map(int,open('input')))
p(sum(f))
s=0
w=set()
for n in f:
s+=n
if s in w:break
w.add(s);f.append(n)
p(s)
| halvarsu/advent-of-code | python/day1/day1golf.py | day1golf.py | py | 123 | python | en | code | 0 | github-code | 13 |
34652749503 |
#import sqlite3
import sqlite3 as sql
#use conn instead of typing all of that
conn = sql.connect('db_strings.db')
#create the database if it doesn't exist already
with conn:
#use cur instead of conn.cursor()
cur = conn.cursor()
#create table if it doesnt exist
cur.execute("CREATE TABLE IF NOT EXISTS ... | markedin/Python-Projects | DatabaseSubmissionAssignment/dbSubAssignment.py | dbSubAssignment.py | py | 1,049 | python | en | code | 0 | github-code | 13 |
42642146444 | from mwpyeditor.core import mwglobals
from mwpyeditor.core.mwrecord import MwRecord
class MwLIGH(MwRecord):
def __init__(self):
MwRecord.__init__(self)
self.id_ = ''
self.model = ''
self.name = None
self.icon = None
self.weight = 0.0
self.value = 0
s... | Dillonn241/MwPyEditor | mwpyeditor/record/mwligh.py | mwligh.py | py | 3,744 | python | en | code | 4 | github-code | 13 |
33524122338 | #backup.py
#-*- coding:utf-8 -*-
import subprocess
from dumpXml import dumpXml
# 1. get xml & parsing
def getXml():
cmd = "adb shell uiautomator dump"
proc = subprocess.Popen(
cmd,
shell = True,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE
)
out, err = proc.communi... | sjoon2455/smartMonkey_login | backup.py | backup.py | py | 2,324 | python | en | code | 0 | github-code | 13 |
28250288576 | # https://www.udemy.com/course/100-days-of-code/learn/lecture/19658862#overview
# Day 11 - Blackjack game
############### Blackjack Project #####################
#Difficulty Normal 😎: Use all Hints below to complete the project.
#Difficulty Hard 🤔: Use only Hints 1, 2, 3 to complete the project.
#Difficulty Ex... | avk-ho/100-days-of-Python | day11_blackjack-project.py | day11_blackjack-project.py | py | 6,258 | python | en | code | 0 | github-code | 13 |
16791698368 | """ Network formation model with preference parameter
@Author: Daniel Roncel Díaz
Script with functions to run load data and create plots.
"""
import numpy as np
import statistics
import math
from collections import Counter
import pickle
import matplotlib.pyplot as plt
## Utils
base_colors = ['orange', 'blue']
de... | danielroncel/tfg | network_formation_model_preference/graphics.py | graphics.py | py | 18,169 | python | en | code | 0 | github-code | 13 |
70165357779 | #!/usr/bin/env python
from __future__ import print_function
import sys
# WRONG
# Sum of 24632 numbers that cannot be expressed as the sum of two abundant numbers: 346398923
def is_perfect(num):
return sum(divisors(num)) == num
def is_abundant(num):
return sum(divisors(num)) > num
def is_deficient(num):
return ... | jarretraim/euler_py | 21-30/23.py | 23.py | py | 1,627 | python | en | code | 0 | github-code | 13 |
38711940671 | from tkinter import *
from tkinter import colorchooser
import random
tk=Tk()
canvas=Canvas(tk, width=500, height=500)
canvas.pack()
def func1():
canvas.create_arc(10,10, 200, 80, extent=45, style=ARC)
canvas.create_arc(10,80, 200, 160, extent=90, style=ARC)
canvas.create_arc(10,10, 200, 240, extent=135, st... | VigularIgnat/python | project ph/ark kolo duga.py | ark kolo duga.py | py | 1,445 | python | en | code | 0 | github-code | 13 |
16402762030 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy@gmail.com
"""
命令补全
"""
from prompt_toolkit.completion import Completer
from prompt_toolkit.completion import Completion
from wapi.common import constants
from wapi.common.loggers import create_logger
from wapi.common.args import ArgumentParser
from .base ... | wxnacy/wpy | wpy/completion/command.py | command.py | py | 3,161 | python | en | code | 0 | github-code | 13 |
21586109661 | """
Hash Function
-------------
In data structure Hash, hash function is used to convert a string(or any other
type) into an integer smaller than hash size and bigger or equal to zero.
The objective of designing a hash function is to "hash" the key as
unreasonable as possible. A good hash function can avoid collision ... | corenel/lintcode | algorithms/128_hash_code.py | 128_hash_code.py | py | 2,291 | python | en | code | 1 | github-code | 13 |
6786162662 | #!/usr/bin/env python
# coding: utf-8
# In[7]:
import numpy as np
a=np.arange(40,50)
b=np.arange(50,60)
x_values = [a[0], b[0]]
y_values = [a[1], b[1]]
plt.plot(x_values, y_values)
# In[20]:
import matplotlib.pyplot as plt
sales_1 = [160,150,140,145,175,165,180]
sales_2 = [70,90,160,150,140,145,175]
line_char... | RAJASOORYA/Data-Visualization-using-python | Day 1 Assignment.py | Day 1 Assignment.py | py | 871 | python | en | code | 0 | github-code | 13 |
23549556614 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 4 13:02:53 2020
@author: tmuza
"""
# Importing Libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import Imputer, LabelEncoder, OneHotEncoder, StandardScaler
from sklearn.model_selection import train_test_split
... | tmuzanenhamo/Machine-Learning-Algorithms | Data Preprocessing/Data Preprocessing.py | Data Preprocessing.py | py | 1,374 | python | en | code | 0 | github-code | 13 |
27188481113 | import sys
from collections import deque
input = sys.stdin.readline
N, M = map(int, input().split())
def bfsW(s):
queue = deque()
queue.append(s)
visited[s[0]][s[1]] = 1
cnt_w = 1
di, dj = [0, 1, 0, -1], [1, 0, -1, 0]
while queue:
n = queue.popleft()
for k i... | Nam4o/Algorithm | 백준/Silver/1303. 전쟁 - 전투/전쟁 - 전투.py | 전쟁 - 전투.py | py | 1,462 | python | en | code | 1 | github-code | 13 |
3023952966 | import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from pymongo import MongoClient # pymongo를 임포트 하기(패키지 인스톨 먼저 해야겠죠?)
client = MongoClient('mongodb://test:test@localhost', 27017) # mongoDB는 27017 포트로 돌아갑니다.
db = clien... | baek0001/my_project | school.py | school.py | py | 7,317 | python | ko | code | 0 | github-code | 13 |
24956679472 | #!/usr/bin/env python
import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
class Geek(db.Model):
message = db.StringProperty(required=True)
when = db.DateTimeProperty(auto_now_add=True)
who = db.StringProperty()
class ... | bjthinks/grapher | geekouttest/main.py | main.py | py | 972 | python | en | code | 1 | github-code | 13 |
25288846241 | class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
direct = [[0, 1], [0, -1], [1, 0], [-1, 0]]
n = len(board)
m = len(board[0])
global flag
flag = False
visit ... | kyx2333/Analysis_Algorithm | leetcode/79.py | 79.py | py | 1,610 | python | en | code | 0 | github-code | 13 |
33760013924 | import json
from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer
from asgiref.sync import async_to_sync
class ChatConsumer(WebsocketConsumer):
def connect(self):
self.room_name = "chat"
self.room_group_name = "chat_room"
async_to_sync(self.channel_layer.group_ad... | tarunnar/chatproject | chatapp/consumers.py | consumers.py | py | 1,379 | python | en | code | 0 | github-code | 13 |
38821176188 | import threading
import time
def thread1():
for i in range(10):
print('thread 1- running')
time.sleep(3)
def thread2():
for i in range(10):
print('thread 2- running')
time.sleep(3)
t1 = threading.Thread(target=thread1)
t2 = threading.Thread(target=thread2)
tt = threading.cur... | Bhaskar100/DBTest | thread-test.py | thread-test.py | py | 385 | python | en | code | 0 | github-code | 13 |
1139683286 | textoTotal1 = 0
textoTotal2 = 0
textoTotal3 = []
with open('C:\\Curso01\\seccao13\\arquivos_de_texto\\ex07.txt') as arquivo1:
textoTotal1 = arquivo1.readlines()
with open('C:\\Curso01\\seccao13\\arquivos_de_texto\\ex08.txt') as arquivo2:
textoTotal2 = arquivo2.readlines()
textoTotal3.append(textoTotal1)
texto... | Sancheslipe/atividades_python_basico_ao_avancado_geral | seccao13/ex09.py | ex09.py | py | 611 | python | en | code | 0 | github-code | 13 |
4457946145 | # -*- coding: utf-8 -*-
from odoo import models, fields, api
class Book(models.Model):
_name = 'book_store.book'
name = fields.Char("名称", help='书名')
author = fields.Char('作者', help='作者')
date = fields.Datetime("出版日期", help="日期")
price = fields.Float("定价", help='定价')
_sql_constraints = [
... | 2232408653/model_test | book_store/models/book.py | book.py | py | 1,724 | python | en | code | 0 | github-code | 13 |
31931306095 | from Dataset import *
from tqdm import tqdm
import os
import torch
import torchvision
import matplotlib.pyplot as plt
import torch.backends.cudnn as cudnn
from Model import Model
def plot_graph(train_loss_curve):
# Training Loss vs Epochs
# plt.plot(range(10), [0.30456, 0.056742, -0.10345, -0.2049603, -0.2553... | Ruchi-Gupte/3D-Bounding-Box-with-Tracking | Train_3D_Features/Train.py | Train.py | py | 3,724 | python | en | code | 1 | github-code | 13 |
16451340634 |
# billentyűt lenyomom
# ha stunlock, akkor nem csinál semmit
# ha fut casttimer már, azt reseteli, kivéve ha 2es
# ha '2' volt a billentyű, akkor elindítja a casttimert
# ha casttimer végigér, akkor stunlock indul el
# ez csak beállít egy window title nevet -> ez alapján zárja be majd .ahk, ha bezártam obliviont!
... | chrishor29/OblivionCastTimer | fast.py | fast.py | py | 4,662 | python | en | code | 0 | github-code | 13 |
37284841870 | import matplotlib.pyplot as plt
from language_analysis.FILE_PATHS import LANGUAGE_TEXT_PATH
from ASCII_art import LOGO
from language_analysis.fonctions import parse_file, get_most_used_char
# pip install matplotlib OR pip3 install matplotlib
TEXT_PATH = 'text.txt'
NUM_MOST_FREQ_CHAR = 5
SHOW_HIST = True
if __name__ =... | romainflcht/APP3 | main.py | main.py | py | 3,515 | python | fr | code | 0 | github-code | 13 |
72943547218 | # def variant_one(team, side, user):
# if side not in team:
# team[side] = []
# team[side].append(user)
# return team
#
#
# def variant_two(team, side, user):
# if side not in team:
# team[side] = []
# team[side].append(user)
# else:
# for key, value in teams.item... | Andon-ov/Python-Fundamentals | 20_dictionaries_exercise/force_book.py | force_book.py | py | 1,619 | python | en | code | 0 | github-code | 13 |
23721773295 | # Suppoting code to download git repo.
import os
import subprocess
import configparser
config = configparser.ConfigParser()
config.read('pyconfig.ini')
GIT_REPO = config['DEFAULT']['GIT_REPO']
args = ['git', 'clone', '--depth=1', 'git@github.com:pramitmitra/ReadingNotes.git']
#args = ['git', 'clone', '--depth=1', GIT... | pramitmitra/ReverseEngg_PLSQL | DownloadGitCode.py | DownloadGitCode.py | py | 691 | python | en | code | 0 | github-code | 13 |
10725724153 | codigo = 0
alc = 0
gas = 0
dies = 0
while codigo != 4:
if 1 <= codigo < 4:
if codigo == 1:
alc += 1
if codigo == 2:
gas += 1
if codigo == 3:
dies += 1
codigo = int(input())
print("MUITO OBRIGADO")
print(f"Alcool: {alc}")
print(f"G... | PacMan111/ProblemasBeecrowd | Python/1134.py | 1134.py | py | 362 | python | en | code | 0 | github-code | 13 |
8597501156 | class Solution:
def maxNumber(self, nums1, nums2, k):
m, n = len(nums1), len(nums2)
start, end = max(0, k - n), min(k, m)
return max(self.merge(self.getMaxSubsequence(nums1, i), self.getMaxSubsequence(nums2, k - i)) for i in range(start, end+1))
def getMaxSubsequence(self, nums, k):
... | HourunLi/Leetcode | SourceCode/MonotonousStack/0321_Create_Maximum_Number.py | 0321_Create_Maximum_Number.py | py | 818 | python | en | code | 1 | github-code | 13 |
20418558112 | import os
import matplotlib.pyplot as plt
import datetime
import requests
import json
import urllib.request
from deep_translator import GoogleTranslator
class Engine:
def __init__(self, town):
self.town = town
self.info = None
self.no_connection = False
self.download_data()
... | przemek-dul/Weatherapp | engine.py | engine.py | py | 5,667 | python | en | code | 0 | github-code | 13 |
13617659853 | # -*- coding:utf-8 -*-
# 多线程 下载 豆瓣 刘诗诗 图片
import requests
import json
import os
import random
from selenium import webdriver
from queue import Queue
from lxml import etree
from fake_useragent import UserAgent
from threading import Thread
from time import time, sleep
PIC_PATH = "shishi"
ua = UserAgent()
# 请求头
headers ... | pyl-10/web_crawler | cecilia_liu_pictures.py | cecilia_liu_pictures.py | py | 3,315 | python | en | code | 0 | github-code | 13 |
24915075936 | #
# Turn the data scraped (by copy paste) from
# https://www.gbmaps.com/4-digit-postcode-maps/free-uk-postcode-district-maps.htm
# into a CSV.
#
# Manually fixed typos / inconsistencies in input:
# - SSwansea -> Swansea
# - London N -> N-London
# - added E-London to London
# - added HS-Outer Hebrides to Scotland
# - ad... | TechForUK/my_eu | prototype/data/postcode-regions/postcode-regions.py | postcode-regions.py | py | 1,309 | python | en | code | 18 | github-code | 13 |
43989860556 | def draw_star(k):
for i in range(k):
for j in range(k):
if i % 3 == 1 and j % 3 == 1:
print(' ', end='')
else:
print('*', end='')
print()
num = int(input(''))
draw_star(num) | ryanjung94/Algorithm_study | 2020_01_19/draw_star/draw_star.py | draw_star.py | py | 251 | python | en | code | 0 | github-code | 13 |
72101940817 | import torch
import torch.nn.functional as F
from torch.nn.modules.loss import _Loss
from torch import nn
class OrderedLoss(_Loss):
def __init__(self, alpha=1, beta=0.5):
super(OrderedLoss, self).__init__()
self.criterion = nn.CrossEntropyLoss()
self.alpha = alpha
self.beta = beta
... | yongpi-scu/BRNet | nets/loss/orderedloss.py | orderedloss.py | py | 646 | python | en | code | 2 | github-code | 13 |
7834568730 | from io import BytesIO
from typing import IO, Optional
from flask import wrappers
from secure_tempfile import SecureTemporaryFile
from werkzeug.formparser import FormDataParser
class RequestThatSecuresFileUploads(wrappers.Request):
def _secure_file_stream(
self,
total_content_length: Optional[int... | freedomofpress/securedrop | securedrop/request_that_secures_file_uploads.py | request_that_secures_file_uploads.py | py | 1,655 | python | en | code | 3,509 | github-code | 13 |
36196613321 | import re
file = open('html_songs_list.txt')
content = file.read()
file.close()
songs_matches = re.findall('\/tracks">(?:.*)(?=<\/a>)', content)
songs = list()
for song_match in songs_matches:
song_name = song_match.split('>')[1] + ' - Lil Wayne'
if '\'' in song_name:
song_name = song_name.replace('\'', '')... | Shoop123/audio-f-word-detection | song_downloader/extract_music.py | extract_music.py | py | 464 | python | en | code | 1 | github-code | 13 |
21359678914 | # coding: utf-8
import json
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options
def get_json_list( url ):
chrome.get(url)
elem = []
object_dict = {}
elem = chrome.find_elements_by_class_name("rc") # Находим элементы с название класа
obj = 1
for i in ele... | MaxiZhorin/google_parser_bot | sol.py | sol.py | py | 1,887 | python | ru | code | 0 | github-code | 13 |
35552355632 | """
Implémantation du module Tag.
"""
import discord
from discord.ext import commands
import random
import pymysql
import asyncio
from pymysql import cursors
from Classes import MarianneException, GestionnaireResources
from Classes.GestionnaireResources import GestionnaireResources
from Fonctions import Message, Erreu... | aleclev/marianne-bot | Commandes/Tag.py | Tag.py | py | 6,528 | python | fr | code | 1 | github-code | 13 |
23200031466 | from setuptools import setup, find_packages
from spso.version import __version__, __author__, __email__, __license__
import os
desc = "Simple particle swarm optimizer in python"
setup( name = 'spso',
version = __version__,
description = desc,
long_descriptio... | nicochidt/pythonspo | setup.py | setup.py | py | 935 | python | en | code | 1 | github-code | 13 |
73917840657 | """
- poll a website (based on 'onlinetermine.zollsoft.de') that references available doses of vaccination
- if one slot is available, fill the registration form very quickly (faster that humans) and let the user validate
"""
import datetime
import time
from selenium.webdriver.chrome.options import Options
from seleni... | chauvinSimon/appointment_bot | main.py | main.py | py | 3,499 | python | en | code | 1 | github-code | 13 |
72829503379 | import bpy
from bpy.props import *
from mathutils import Vector
from ... base_types import AnimationNode
from ... events import propertyChanged
class rollerNode(bpy.types.Node, AnimationNode):
bl_idname = "an_rollerNode"
bl_label = "Roller Node"
bl_width_default = 200
val_x = FloatProperty(name = "Dat... | Clockmender/My-AN-Nodes | nodes/general/roller.py | roller.py | py | 1,981 | python | en | code | 16 | github-code | 13 |
27190856278 | from zad3testy import runtests
# gorsza złożoność, po prostu odczytuje wartości z drzewa
# i wstawiam do tablicy
def maxim( T, C ):
def GetHeight(T):
h = 0
curr = T
while curr:
curr = curr.right
h += 1
return h
def GetTab(node,idx):
nodes[idx... | JakubWorek/algorithms_and_data_structures_course | TREES/maxin/zad3.py | zad3.py | py | 557 | python | pl | code | 0 | github-code | 13 |
36704816195 | """Decoder builds the decoder network on a given latent variable."""
import tensorflow as tf
from tensorflow import distributions as ds
def decoder(latent, img_size, units):
"""Decoder builds a decoder network on the given latent variable tensor.
Args:
lv (tf.Tensor): sample_size x batch_size x laten... | cshenton/auto-encoding-variational-bayes | vae/decoder.py | decoder.py | py | 682 | python | en | code | 19 | github-code | 13 |
35677389432 | # ADXL-345 program for the client device
# Will act as an anti-tampering sensor
import time
import board
import busio
import adafruit_adxl34x
from api_call import DeliveryDetectorBox
def run_adxl(box_num, names):
box = DeliveryDetectorBox(box_num)
i2c = busio.I2C(board.SCL, board.SDA)
adxl = adafruit_adxl3... | Capstone-Projects-2022-Spring/project-delivery-detector | ClientDevice/adxl.py | adxl.py | py | 720 | python | en | code | 2 | github-code | 13 |
26573240350 | import socket
import threading
from queue import Queue
print_lock = threading.Lock()
target = "www.google.com"
def port_scan(port):
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
connection = soc.connect((target, port))
with print_lock:
print(f'Port {port} is open!')
connection.close()
ex... | Mathanraj-Sharma/python_socket_programming | 03_threaded_port_scanner.py | 03_threaded_port_scanner.py | py | 679 | python | en | code | 0 | github-code | 13 |
13402451589 | #!/usr/bin/python
"""
--- Day 4: Security Through Obscurity ---
Finally, you come across an information kiosk with a list of rooms. Of
course, the list is encrypted and full of decoy data, but the
instructions to decode the list are barely hidden nearby. Better remove
the decoy data first.
Each room consists of an e... | jtyr/advent-of-code-2016 | 04.py | 04.py | py | 3,363 | python | en | code | 0 | github-code | 13 |
24814262995 | import sys
import os
class SystemInfo:
def __init__(self):
self.isRunning = False
self.isRaspberryPi = "linux" in sys.platform
if(self.isRaspberryPi):
self.arduinoPort = "/dev/ttyACM0"
self.bluetoothPort = "/dev/rfcomm0"
self.enableWindow = "DISP... | MinervaBots/Trekking | firmware/pi/SystemInfo.py | SystemInfo.py | py | 592 | python | en | code | 1 | github-code | 13 |
15639294293 | """Дополнительные классы для настройки основных классов приложения."""
from django.db.models import Model, Q
from django.shortcuts import get_object_or_404
from rest_framework import status
from rest_framework.response import Response
from rest_framework.serializers import ModelSerializer
from core.constants import M... | Yohimbe227/The-Social-Recipe-Network | backend/core/classes.py | classes.py | py | 2,297 | python | ru | code | 0 | github-code | 13 |
9023398094 | from itertools import permutations
x = input()
y = []
k = []
for a in x:
y.append(a)
print(*y)
for n in range(len(y)):
j=0
for j in range(len(y)):
c = y[n] + y[j]
k.append(c)
j += 1
n += 1
print(*k)
a = sorted(list(permutations(y,2)))
for k in a:
print ("".join(k))
| animeshmod/python-practice | stirng_break.py | stirng_break.py | py | 314 | python | en | code | 0 | github-code | 13 |
47917483924 | """migration
Revision ID: d1f28027789c
Revises:
Create Date: 2021-02-01 22:04:46.812707
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'd1f28027789c'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generate... | Shahid313/social-media-website | migrations/versions/d1f28027789c_migration.py | d1f28027789c_migration.py | py | 3,839 | python | en | code | 0 | github-code | 13 |
1232765265 | import argparse
import shutil
import os
import subprocess
import sys
import re
import csv
from bench_utils import *
import accel_conf
APIS = {"HighLevel" : ["HighLevel", "high", "hl"],
"MiddleLayer" : ["MiddleLayer", "middle", "ml"],
"JobApi" : ["JobApi", "job"]}
FIELDS_BASE = {CONFIG ... | intel/DML | tools/benchmarks/scripts/run_dml_benchmarks.py | run_dml_benchmarks.py | py | 11,921 | python | en | code | 62 | github-code | 13 |
44025457321 | import random
import numpy as np
from pysc2.lib import actions, units
from collections import defaultdict
from Models.BuildOrders.ActionSingleton import ActionSingleton
from Models.HelperClass.HelperClass import HelperClass
class State:
def __init__(self, bot_obj):
# Game state
self.units_amount... | DukeA/DAT02X-19-03-MachineLearning-Starcraft2 | Src/Models/BotFile/State.py | State.py | py | 11,603 | python | en | code | 0 | github-code | 13 |
43254290911 | N = int(input())
arr = list(map(int, input().split()))
dp = [[0 for _ in range(21)] for _ in range(N + 1)]
dp[1][arr[0]] = 1
for j in range(1, N):
for i in range(21):
if dp[j][i] > 0:
if 0 <= i - arr[j] <= 20:
dp[j + 1][i - arr[j]] += (dp[j][i])
if 0 <= i + arr[j] ... | KimSoomae/Algoshipda | week12/G5/고재현_5557_1학년.py | 고재현_5557_1학년.py | py | 408 | python | en | code | 0 | github-code | 13 |
30605394521 | from django.db import models
#from RegisterUsers.models import Patient
#from RegisterUsers.models import Doctor
# Create your models here.
class ScheduleAppointment(models.Model):
#patient = models.ForeignKey(Patient,on_delete=models.CASCADE)
#doctor = models.ForeignKey(Doctor,on_delete=models.CASCADE)
#u... | atheeswaran/Scalable-Services | appointmentScheduling/AppointmentScheduling/models.py | models.py | py | 509 | python | en | code | 0 | github-code | 13 |
72722421458 | from typing import List, Tuple
class Config:
correct_config = "012345678"
def __init__(self, config, zero_x: int, zero_y: int, parent=None, depth=-1):
self.config = config
self.zero_x = zero_x
self.zero_y = zero_y
self.depth = depth
self.parent = parent
self.c... | danielspeixoto/8PuzzleSolver | Config.py | Config.py | py | 1,298 | python | en | code | 0 | github-code | 13 |
43230325606 | #!/usr/bin/env python
import os
from os import path
import sys
# Directory containing this program.
PROGDIR = path.dirname(path.realpath(__file__))
# For python_config.
sys.path.insert(0, path.join(PROGDIR, "..", "..", "..", "etc"))
# Use non-interactive backend.
import matplotlib
matplotlib.use("Agg")
import python... | mukerjee/etalon | experiments/buffers/sequence_graphs/sg_cc.py | sg_cc.py | py | 1,474 | python | en | code | 12 | github-code | 13 |
17037610184 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayCommerceEducateTuitioncodePlanruleSendModel(object):
def __init__(self):
self._allot_type = None
self._execute_type = None
self._out_biz_no = None
self._peri... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/AlipayCommerceEducateTuitioncodePlanruleSendModel.py | AlipayCommerceEducateTuitioncodePlanruleSendModel.py | py | 3,360 | python | en | code | 241 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.