blob_id
large_string
repo_name
large_string
path
large_string
src_encoding
large_string
length_bytes
int64
score
float64
int_score
int64
detected_licenses
large list
license_type
large_string
text
string
download_success
bool
a616a939277e5a909d98008b4f1f9bfe4db0efa9
Aasthaengg/IBMdataset
/Python_codes/p02630/s170381702.py
UTF-8
341
2.546875
3
[]
no_license
import math , sys N = int( input() ) A = list( map( int, input().split() ) ) Q = int( input() ) count = [0 for _ in range( 10**5 + 1)] for each in A: count[each]+=1 ans = sum(A) for _ in range(Q): B , C = list( map( int , input().split() ) ) D = count[B] ans += (C-B) * D count[B] = 0 count[C]...
true
d21a505f73f698cf2411cf40181421f645de9786
xmlorange/demo
/app/test/information_summary_filter/__init__.py
UTF-8
3,403
3.34375
3
[]
no_license
# -*- coding: utf-8 -*- # 基于信息摘要算法进行数据的去重判断和存储 # 1. 基于内存存储 # 2. 基于Redis的存储 # 3. 基于MySQL的存储 import hashlib import six class BaseFilter(object): """基于信息摘要算法进行数据的去重判断和存储""" def __init__(self, hash_func_name='md5', redis_host='localhost', redis_port=6379, ...
true
b215a3c0e71de73c61ce2ee5fcc0728ea336e4d3
pythonfoo/pythonfoo
/beginnerscorner/tests/threading/functionMultithread.py
UTF-8
596
3.296875
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- #http://docs.python.org/2/library/queue.html from multiprocessing import Process, Queue import time import random def my_function(q, x): doSleep = random.randint(1,11) print doSleep time.sleep(doSleep) q.put( str(x + 100) + ' slept:' + str(doSleep) ) if __name__ == '_...
true
dadbe95f7d522533efef81eb16ed4c89c1288979
jinliangXX/LeetCode
/350. Intersection of Two Arrays II/solution.py
UTF-8
556
3.046875
3
[]
no_license
class Solution(object): def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ result = list() nums1_dict = dict() for num in nums1: if num in nums1_dict: nums1_dict[num] +...
true
9e2e869bb8f48b115224d62532202f80305d64fb
xlyang0211/learngit
/find_duplicate_number.py
UTF-8
760
3.234375
3
[]
no_license
__author__ = 'seany' class Solution(object): def findDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ return self.find_duplicate_number(1, len(nums), nums) def find_duplicate_number(self, start, end, nums): if start == end: return sta...
true
a03656404f195ec58a91e5ef5fc0a27bf67b73e7
seung-lab/KVDbClient
/kvdbclient/base.py
UTF-8
2,199
2.953125
3
[ "MIT" ]
permissive
from abc import ABC from typing import Any from typing import Dict from typing import Tuple from typing import Callable from typing import Iterable from typing import Optional from datetime import datetime from .serializers import Serializer from .serializers import UInt64String class SimpleClient(ABC): from abc...
true
d47c20aa3d9a8a793a99f5c4d177235a3d1b67e9
Aasthaengg/IBMdataset
/Python_codes/p02571/s108289046.py
UTF-8
312
3.09375
3
[]
no_license
S = input() T = input() count = 0 max_count = 0 for i in range(len(S) - len(T) +1): for j in range(len(T)): if S[i+j] == T[j]: count += 1 if max_count <= count: max_count = count if j == (len(T) -1): count = 0 print(len(T) - max_count)
true
994c0b526185269820eac6d2eaa15edeccda1a32
kobeeraveendran/scripting
/youtube-to-mp3/youtube-to-mp3.py
UTF-8
1,320
2.53125
3
[]
no_license
# Kobee Raveendran # YouTube to mp3 download script import pytube from pytube import YouTube import os import subprocess import sys # get video link from user link = input("Enter video URL: ") # create a pytube object out of that link yt = YouTube(link) print("Video title: " + yt.title) # get the sp...
true
e8d3c4fd6bcfe222c29576a49f8ab6f794a59cb5
xylafur/cosc4368-AI-GroupProject
/src/location.py
UTF-8
3,257
3.734375
4
[]
no_license
#!/usr/bin/env python3 """ This module contains the implementation of the various type of squares that can populate our grid world That includes individual squares (locations) of all 3 types (pick up, drop off and normal locations) """ PICKUP = "PICKUP" DROPOFF = "DROPOFF" NORMAL = "NOR...
true
e2bbaf99f4bcb87e64b76a7837b33cce03b7c980
matejgrcic/outlier-exposure
/NLP_classification/utils/display_results.py
UTF-8
6,605
2.96875
3
[ "Apache-2.0" ]
permissive
import numpy as np import sklearn.metrics as sk recall_level = 0.95 def stable_cumsum(arr, rtol=1e-05, atol=1e-08): """Use high precision for cumsum and check that final value matches sum Parameters ---------- arr : array-like To be cumulatively summed as flat rtol : float Relativ...
true
3b719f8d386f849be504144b34a65b7359c754b3
Shanker511/pugbot-satellite
/robot/raspberry-pi-3/examples/voiceToText/SpeechResult.py
UTF-8
890
3.078125
3
[]
no_license
__author__ = 'Pux0r3' class SpeechResult: """ A result from the speech engine """ def __init__(self, results, response_id): """ Creates a new SpeechResult given data from the server :param results: a list of results from the server :param response_id: an identifier for this result :return: """ self...
true
bcda5f2595be9e43947b236e4f9288568a991851
Katherinelove/visualize_data
/Visualized_data/json_formation.py
UTF-8
1,147
3.140625
3
[]
no_license
from urllib.request import urlopen import json import pygal import math #获取数据 json_url="https://raw.githubusercontent.com/muxuezi/btc/master/btc_close_2017.json" responsee=urlopen(json_url) #读取数据 read=responsee.read() #写入数据 with open("btc_close_2017.json","wb") as f: f.write(read) with open("btc...
true
a2f5fb0397ccd11469402da5981dd6e98f7e6311
thientran2020/E-commerce_Web_For_Restaurant
/application/models.py
UTF-8
514
2.8125
3
[]
no_license
import flask from application import db from werkzeug.security import generate_password_hash, check_password_hash class User(db.Document): user_id = db.IntField(unique=True) username = db.StringField(max_length=30) email = db.StringField(max_length=30) password = db.StringField() d...
true
f1fb9fd70d88e3c9098e29f706f6649c542e3c20
GLSmile/pythontest
/数据库驱动/新建表test01.py
UTF-8
470
2.703125
3
[]
no_license
import pymysql import random #创建链接 db =pymysql.connect(host="localhost",port=3306,user="root",password="root",db="test",charset='utf8') #创建游标 cursor =db.cursor() #编写创建表的sql语句 sql1 ="""create table test01( id char(20) not null, t_name char(20))""" try: #执行创建sql语句 cursor.execute(sql1) #提交到数据库 ...
true
1c3c0e15332b62e8a57a1589b9d1960543d9d15e
johnehunt/computationalthinking
/week1/game/starshipgame.py
UTF-8
6,359
3.28125
3
[ "Apache-2.0" ]
permissive
# You need to install pygame for this program to work # However Python 3.8 requires you to install pygame using # pip install pygame==2.0.0.dev12 # Rather than just using pip install pygame import pygame import random import time DISPLAY_WIDTH = 600 DISPLAY_HEIGHT = 400 FRAME_REFRESH_RATE = 30 BLUE = (0, 0, 255) WH...
true
62025e250a175009e8eecaaeb802579c1404b686
thegreatskywalker/my_deep_learning
/untitled4.py
UTF-8
369
2.90625
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri May 25 02:30:41 2018 @author: pt """ from tqdm import tqdm text = "" for char in tqdm(["a", "b", "c", "d"]): text = text + char for i in tqdm(range(100)): pass pbar = tqdm(["a", "b", "c", "d"]) pbar2 = tqdm(total=200, desc...
true
5eb62f120f0c778a1c8ce678f6046ae0a660b0ae
mediastore93/pir_sensor
/pir_timed2.py
UTF-8
1,831
3
3
[]
no_license
#!/usr/bin/env python import time import RPi.GPIO as GPIO import datetime # Use BCM GPIO references GPIO.setmode(GPIO.BCM) GPIO_PIR = 17 print ("PIR Module Holding Time Test (CTRL-C to exit)") # Set pin as input GPIO.setup(GPIO_PIR,GPIO.IN) # Echo def sensor(): Current_State = 0 Previous_State = 0...
true
b08f513735512c578f5453f263d0091f54233066
snehal-QA/BDDTestProject
/Features/Steps/CodeSignalCode/strings.py
UTF-8
2,047
3.921875
4
[]
no_license
# list1=[1,2,3] # #Insert: element to the specific index in list # list1.insert(2,'snehal') # print(list1) # # # Append: Adds element at the end of the list # list1.append('abhijit') # print(list1) # # #Extend: Appends two lists use extend function r + ; extends methods is also use to append iterable collections # # l...
true
c4ea1b46499742c210bee9f380b56837f04162ad
jsxxj/dataProcessing
/addNoiseToBmp.py
UTF-8
1,229
2.765625
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Tue Oct 31 16:39:42 2017 @author: jsx 对指定目录下的图片bmp文件 添加高斯噪声,并另存为一个目录 """ from PIL import Image import os import numpy as np def process_file(filePath): files = os.listdir(filePath) for file in files: fname = os.path.splitext(file) fimage = os.pat...
true
b4356be6d26effa6b2efb8bbdd2d754ad26bf69b
K9L1E/gitlab_job_exporter
/gitlab_job_exporter/__init__.py
UTF-8
5,608
2.625
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 import json import time from dateutil.parser import parse try: from urllib.request import urlopen, Request except ImportError: from urllib2 import urlopen, Request from prometheus_client import Summary from prometheus_client.core import GaugeMetricFamily COLLECTION_TIME = Summary('gitla...
true
37052feb37df65157a86ee87d95d419683ccf4ad
g-rich1234/game-framework
/RPSGame.py
UTF-8
956
3.359375
3
[ "Apache-2.0" ]
permissive
__author__ = 'g_ric_000' class RPSGame(Game): ## this class simulates two players playing rock, paper, scissors def __init__(self): def play_game(self, player1, player2): result = "" move1 = player1.get_move() move2 = player2.get_move() if self.is_vali...
true
84f04aec08479344420158751fac8693b95bf2bc
anudita/Python-
/python_basics.py
UTF-8
861
4.15625
4
[]
no_license
#Immutable data var1 = 2 print "var1 is of",type(var1) var2 = 128.132 print "var2 is of",type(var2) str = "hello" print "str is of",type(str) tup = (1,2,4,5) print "tup is of",type(tup) tup1 = (2,34.2,"hello",24) print "tup1 is of",type(tup1) #operations on tuple print "length of tuple : ",len(tup1) print 2 in tup1 ...
true
d1c1614d45c83eea1c2388b50a241d4c0aced2ba
lyrvid/Moo
/tests/unittests/test_search_db.py
UTF-8
884
2.71875
3
[]
no_license
import api.customer_db as db def test_add_customer_data(setup_db): customer = dict(first_name='Lei', last_name='Ferretti') db.add_customer_to_db(customer) assert len(db.CUSTOMER_DATA) == 1 assert db.CUSTOMER_DATA[0] == customer def test_search_customers_by_field(setup_db): customer = dict(first...
true
07499618cafb5515f8a62d788194419be9568132
gwyrwch/yourbudget
/yourbudget/algorithm/Receipt.py
UTF-8
219
2.625
3
[]
no_license
class Receipt: def __init__(self, lines): self.img_lines = lines @property def average_height(self): res = sorted(map(lambda x: x.size[1], self.img_lines)) return res[len(res) // 2]
true
39a89675a0026c61bcaa3b2d5ebd61c6e81edbf4
lijikai1206/Pycharm_Projects01
/PythonFile/10_MySqlTest/demosql/demo_sql004_InsertData.py
UTF-8
661
2.796875
3
[]
no_license
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="ljk1103", database="runoob" ) mycursor = mydb.cursor() sql = "INSERT INTO Websites (id, name, url, alexa, country) VALUES (%s, %s, %s, %s,%s)" val = [ ('1','Google', 'https://www.google.com','1','USA'), ...
true
7175bcdfa4d8592010b2b1d131dc50dda6e43d92
bosichong/17python.com
/random/randomtest.py
UTF-8
1,358
3.671875
4
[ "Apache-2.0" ]
permissive
#codeing=utf-8 # @Time : 2017-09-20 # @Author : J.sky # @Mail : bosichong@qq.com # @Site : www.17python.com # @Title : Python random 随机数模块操作总结 # @Url : http://www.17python.com/blog/20# # @Details : Python random 随机数模块操作总结 # @Other : OS X 10.11.6 # Python 3.6.1 # VSCode 1.15.1 ##...
true
65ff6051a912c0564ab4138e15c613fa79069810
BasementCat/audio-reactive-led-strip
/server/app/lib/config.py
UTF-8
6,511
2.796875
3
[ "MIT" ]
permissive
import os import json import yaml BASE_CONFIG = { # Configured outputs, see below""" 'OUTPUTS': [], # Whether or not to display a PyQtGraph GUI plot of visualization""" 'USE_GUI': True, # Whether to display the FPS when running (can reduce performance)""" 'DISPLAY_FPS': True, # Locatio...
true
3e70e75707fef3d47b3f8c3320565726c4feb871
sanguix/hello-world
/lib/bearer.py
UTF-8
773
2.96875
3
[]
no_license
#!/usr/bin/python # to make the file executable by python import base64 class CredentialForBearer(object): def __init__(self, key, secret): # constructor self.key = key self.secret = secret def get_credential(self): decoded_credential = self.get_decoded_credential() encoded_c...
true
dee76c880f4ca42387a634c3d3080064c2958ed1
QinJinghui/MVC_Solver
/code_bak_v1/try_num.py
UTF-8
580
2.890625
3
[]
no_license
# -*- encoding: utf-8 -*- # @Author: Jinghui Qin # @Time: 2021/10/15 # @File: try_num.py from transformers import BertTokenizer, AdamW bert_path = "./pretrained_lm/chinese-bert-wwm" bert_tokenizer = BertTokenizer.from_pretrained(bert_path) bert_tokenizer.add_tokens(['[NUM]']) print(bert_tokenizer.vocab) print(bert_...
true
2658ef2b5aca771ed938766ab2772fe881f11b98
jorgermurillo/s3filter
/s3filter/op/project.py
UTF-8
6,228
2.640625
3
[]
no_license
# -*- coding: utf-8 -*- """Projection support """ from s3filter.multiprocessing.message import DataFrameMessage from s3filter.plan.op_metrics import OpMetrics from s3filter.op.operator_base import Operator from s3filter.op.message import TupleMessage from s3filter.op.tuple import Tuple, IndexedTuple # noinspection PyC...
true
069cc97144afe6764188bf5601e559e400d9de37
EmpowerSecurityAcademy/python_datastructures_algorithms
/recursion/recursion.py
UTF-8
88
3.453125
3
[]
no_license
def factorial(n): if n == 1: return 1 else: res = n * factorial(n-1) return res
true
90594fe3b28446a7480ee7f56e6e005813326f8b
onurbabat/Shape-of-Data
/loadiris.py
UTF-8
2,038
3.390625
3
[]
no_license
import numpy, matplotlib.pyplot import sklearn.linear_model import sklearn.svm # labelnames is a dictionary that translates the species names into integers labelnames = {"Iris-setosa\n":0, "Iris-versicolor\n":1, "Iris-virginica\n":2} data, labels = [], [] # Create empty lists for the vectors and labels. f = open...
true
8ad10847c7fe5c70e4dada61c544b9e76ce6a599
DataDog/dd-trace-py
/ddtrace/internal/utils/__init__.py
UTF-8
2,589
2.78125
3
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
from typing import Any from typing import Dict from typing import List from typing import Optional from typing import Tuple import six class ArgumentError(Exception): """ This is raised when an argument lookup, either by position or by keyword, is not found. """ def get_argument_value( args, #...
true
78016a59c8ac5c1d6cc21212ab3b205602fbf7a2
luclarocque/kinodynamic-planning
/fmt/trainsvm.py
UTF-8
3,594
3.09375
3
[]
no_license
import numpy as np import save_obj from sklearn import svm from sklearn.metrics import f1_score # returns a classifier trained using the key-value pairs in # training_dict. def trainsvm(training_dict, c, Jth): X = [] y = [] for k in training_dict: p = k[0] + k[1] # concatenates two states int...
true
babd398bdb3fe5073db1f483b71f4ffc5a8173fd
daigo0927/ProgrammingContest
/AtCoder/ARC103/ProbF.py
UTF-8
662
2.796875
3
[]
no_license
n = int(input()) d = [int(input()) for i in range(n)] if sum(d)%2 > 0: print(-1) exit() d = sorted([(dd, i) for i, dd in enumerate(d)], reverse = True) d_to_i = {dd:i for dd, i in d} n_child = [1]*n d_child = [0]*n ans = [] for dd, i in d: d_i = dd+2*n_child[i]-n if d_i in d_to_i.keys(): i_nex...
true
0a61640bce4a36f4e10775f654a23d160851d0be
Tommyzhou1/WebControl
/test_for_webcontrol.py
UTF-8
551
2.671875
3
[ "MIT" ]
permissive
from aiohttp import web import socketio import time import json ## creates a new Async Socket IO Server sio = socketio.Client() #sio.connect("https://web-control-game.herokuapp.com") sio.connect("http://localhost:3000") #mock data data_set = ['scroll up','scroll down','zoom in','zoom out'] true = True while true: ...
true
db997ae935f39b3f79b6dc1bb45abed87cb0b56b
alexander-svendsen/oldmaid
/communication.py
UTF-8
1,813
2.9375
3
[]
no_license
import socket import sys import time import thread class Server(): def __init__(self, addr, port): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1) print "server listening on addr, port: ", addr, port self.sock.bind((addr, p...
true
86ffd163fc55737de874dd221533d90709d1b45a
zouwx2cs/OpenJudge
/2000-2999/OpenJudge4067.py
UTF-8
144
3.0625
3
[]
no_license
# coding: utf-8 # -*- coding: utf-8 -*- while True: try: str = input() print("YES" if str == str[::-1] else "NO") except: break
true
6c43c283bd75e921733218e92bb9fd2d36f76647
AshwiniR97/OpenCV
/openCVStart.py
UTF-8
287
3.0625
3
[]
no_license
import cv2 # Reading Image - flag (0, 1, -1) img = cv2.imread('lena.jpg', 0) print(img) # Showing Image in Window cv2.imshow('Lena', img) # Wait for 5 seconds cv2.waitKey(5000) # Destroy all open windows cv2.destroyAllWindows() # Writing to file cv2.imwrite('lena_again.png', img)
true
4deb93970b5489f132ad62079c9af551fdc0ff79
GooLiang/Hetu
/examples/runner/parallel/validate_results.py
UTF-8
584
2.671875
3
[ "Apache-2.0" ]
permissive
import numpy as np import os.path as osp import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('number', default=None) parser.add_argument('--rtol', default='1e-6') args = parser.parse_args() directory = 'results' base = np.load(osp.join(directory, '...
true
be13cf72c63bc3106c35c09572ca679656715fa9
go-inoue/nlp100knock
/chapter04/nlp36.py
UTF-8
621
3.46875
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 36. 単語の出現頻度 文章中に出現する単語とその出現頻度を求め,出現頻度の高い順に並べよ. """ from nlp30 import readMecab def wordFreq(sents): freq_dict = dict() for sent in sents: for morph in sent: if morph['surface'] in freq_dict: freq_dict[morph['surface']] += 1 ...
true
caa4355b27c7b4025df90648f0f888cc72f5519a
Gluggers/adventure-game
/tile.py
UTF-8
10,559
3.234375
3
[]
no_license
# -*- coding: utf-8 -*- """Contains functions and constants for Tile objects.""" import logging import sys import pygame import imagepaths import tiledata ### TILE CONSTANTS ### TILE_SIZE = 32 TILE_CLASS = 'Tile' LOGGER = None class Tile(object): """A class used to represent map tiles for the overworld. Ea...
true
030ad71613334325929e689c9cfc4e9802ace9fb
koichipan/Practice
/python sys.argv/test.py
UTF-8
636
3.25
3
[]
no_license
# -*- coding: utf-8 -*- import sys '''read file and print''' def readfile(filename): f = open(filename, 'r') while True: line = f.readline() if len(line) == 0: break print(line) f.close() if len(sys.argv) < 2: print("no argument") sys.exit() if sys.argv[1]...
true
cf2c21ae03e568d21f7f0dd0f3d981966a2e4152
hjzin/PolyphoneDisambiguation
/Code/PolyphoneDisambiguation/DataProcessing/preprocessing.py
UTF-8
2,337
3.03125
3
[]
no_license
#!/usr/bin/env python # -*- coding:utf-8 -*- """ @Time:2019/3/22 @Author: hhzjj @Description:对数据进行预处理,包括tokenize、建立词典等 """ import os from torchtext.data import Field, TabularDataset from torchtext.data import BucketIterator, Iterator import DataProcessing.configure as config def text_tokenize(x): """ 对text进行...
true
0485158a274bbafadf58889631b3abb355f42f43
dgrisham/aqc_research
/programs/algorithms/linear/AQCSatSchedClassic.py
UTF-8
5,956
3
3
[]
no_license
#!/usr/bin/env python2 # author: mberntso last update: 3/28/16 # current input is for sample data as supplied by Prof. Coffey # this algorithm could be improved by implementing a file format # for data input from operator import sub # initialize all tasks as scheduled ## numTasks = 6 x = [1,1,1,1,1,1] ## globa...
true
fb87892c17b5273215494a815e73c61ae427ee68
sungheeyun/PythonLectures
/src/list/basics2.py
UTF-8
670
3.90625
4
[ "Unlicense" ]
permissive
def foo(my_list): return my_list[len(my_list) - 1] def banana(your_list): return your_list[1:] def banana2(your_list): return your_list[-4:-1] def last_three(my_list): return my_list[-3:] if __name__ == "__main__": beth_list = ["a", 2, "c", 4, 5, 6, 7, "beth", "ghayoung"] beth_list = li...
true
080401f64192b5ab2f6da520efed00b3ec3e75fd
LeoRuslan/coursera_python_lessons
/week_8/fifth_pow.py
UTF-8
712
3.40625
3
[]
no_license
# На вход подаётся последовательность натуральных чисел длины n≤1000. # Посчитайте произведение пятых степеней чисел в последовательности. # # Формат ввода # Вводится последовательность чисел # # Формат вывода # Выведите ответ на задачу # # Примечания # Для решения задачи используйте функцию reduce из модуля functools ...
true
d978dae33383361100aa7c5d879506cb0e94fee6
Nomurad/pyec
/pyec/optimizers/nsga.py
UTF-8
5,267
2.546875
3
[ "MIT" ]
permissive
import random import copy from itertools import chain from operator import attrgetter, itemgetter from typing import List, Tuple, Union, Optional from types import FunctionType import numpy as np from ..base.indiv import Individual from ..base.population import Population from ..base.environment import Pool, Norm...
true
ee8bbfba67f37b031746a7b691eb4ab1fb9c51f4
psrc/urbansim
/washtenaw/models/deletion_event_model.py
UTF-8
9,263
2.515625
3
[]
no_license
# Opus/UrbanSim urban simulation software. # Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington # See opus_core/LICENSE from numpy import array, where, resize from opus_core.model import Model from opus_core.sampling_toolbox import sample_noreplace from opus_core.log...
true
9c841f3e1eb535f0d463b1767974cd19f52074aa
greedy0110/algorithm
/baekjoon/2839.py
UTF-8
247
3.390625
3
[]
no_license
N = int(input()) ans = -1 for i in range(5): remaining = N-3*i if remaining == 0: ans = i break elif remaining < 0: break elif remaining % 5 == 0: ans = i + remaining // 5 break print(ans)
true
d7a7a6a909cbcc87e303c16f6933da0c65d85e0d
zrz616/datastructures
/AVLtree.py
UTF-8
1,323
3.5625
4
[]
no_license
class Node(object): """docstring for Node""" def __init__(self, data, parent_node): self.left = None self.right = None self.heigh = 0 self.data = data self.parent_node = parent_node def insert(self, data): if data <= self.data: if not self.left: ...
true
bbac783d26dd531f514bbb7f068d5b1230aaf482
Ayhan-Huang/WebSocket-Test
/tornado_websocket.py
UTF-8
1,620
2.53125
3
[]
no_license
#! user/bin/env python # -*- coding: utf-8 -*- import uuid import json import tornado.web import tornado.ioloop import tornado.websocket class IndexHandler(tornado.web.RequestHandler): """处理客户端的http请求""" def get(self): self.render('index.html') class ChatHandler(tornado.websocket.WebSocketHandler): ...
true
41fd0b4652f714b8f2d1af0be949a54c5257322f
graphql-python/gql
/docs/code_examples/fastapi_async.py
UTF-8
2,033
2.609375
3
[ "MIT" ]
permissive
# First install fastapi and uvicorn: # # pip install fastapi uvicorn # # then run: # # uvicorn fastapi_async:app --reload import logging from fastapi import FastAPI, HTTPException from fastapi.responses import HTMLResponse from gql import Client, gql from gql.transport.aiohttp import AIOHTTPTransport logging.basicC...
true
26a6c5f8a5f8abb6f6fcacd680fe2bd4e6ca39dd
fosskers/alg-a-day
/day08-primes/primes.py
UTF-8
1,111
4.125
4
[]
no_license
# Prime number solver, and a nice iterator! from funchelp import head # Available in my python-libs repo. class primes(): '''An iterator that produces all the prime numbers.''' def __iter__(self): yield 2 prime = 3 while True: yield prime prime = _next_prime(pr...
true
434bb3bc103dad4a5c7b94fb7f440cc31458f8f0
diegocaro/prograudd
/clases/clase15/numpymatrix3.py
UTF-8
373
3.46875
3
[]
no_license
import numpy as np x = np.array([1, 2, 3]) y = np.array([3, 2, 1]) c = np.concatenate([x, y]) print('c:', c) grid = np.array([[1, 2, 3], [4, 5, 6]]) # concatenate along the first axis print('axis=0:',np.concatenate([grid, grid])) # concatenate along the second axis (zero-indexed) pr...
true
def33773ecf7c871a918330f4811224151a119a1
jackmuskopf/sagemaker-aurora
/py-mgr/hcl.py
UTF-8
4,102
2.671875
3
[]
no_license
import logging class NoQuotes(str): ''' A class to indicate no quotes on a terraform value ''' pass class HCLBlock: def __init__(self, **kwargs): self.indent = 4 required_kwargs = ['Class'] for kw in required_kwargs: if kw...
true
1bfc1a5378db93b73dc62a6a6a7e0bcc8fe8f479
Rynhalt/Rynhalt
/codeRunner.py
UTF-8
3,727
2.734375
3
[]
no_license
import builtins from RestrictedPython import compile_restricted from RestrictedPython import utility_builtins import time error = False def limited_range(iFirst, *args): # limited range function from Martijn Pieters RANGELIMIT = 1000 if not len(args): iStart, iEnd, iStep = 0, iFirst, 1 elif le...
true
e921f3f1ffe7daa639ea0fd6553238d23ecb09a3
Sanket1228/pythonBasics
/Practice_Programs/Adding ones/Program2.py
UTF-8
180
3.078125
3
[]
no_license
n,k = map(int,input().split()) x = [0] * n arr = list(map(int,input().split())) for i in arr: for j in range(i-1,n): x[j] += 1 for i in x: print(i,end=" ")
true
2ec03aba21c6f64ced37ec35d4f59250462a321a
haflidijr/All-assignments
/forritun/quizznr2.py
UTF-8
121
2.59375
3
[]
no_license
user = "admin" logged_in = False if user == "admin" and logged_in: print("admin page") else: print("lalala")
true
bfcf2769849961ec531cbbb5417b67334eeddbdc
taozhenting/python_introductory
/10-1从文件中读取数据/10-1-1读取整个文件/file_reader2.py
UTF-8
204
3.40625
3
[]
no_license
#打开文件并访问,删除最后的空行 file_name = 'pi_digits.txt' with open(file_name) as file_object: contents = file_object.read() #rstrip()方法删除空行 print(contents.rstrip())
true
acf20357af1cb7e41d482e702cb160df005fe91d
hannahlindsley/jupyter-mortgage
/bloodloan/mortgage/closing.py
UTF-8
8,108
2.796875
3
[ "Unlicense" ]
permissive
"""Closing costs""" import copy import enum import logging from bloodloan.mortgage import mmath from bloodloan.mortgage import schedule logger = logging.getLogger(__name__) # pylint: disable=C0103 class CCCalcType(enum.Enum): """Determines how the amount of the ClosingCost is calculated DOLLAR_AMOUNT ...
true
489a8c00e395c61cae6df71fc0dd1e7d6ea4f0ef
nicc00/project-2
/visualizations.py
UTF-8
1,463
3.3125
3
[]
no_license
import pandas as pd import matplotlib.pyplot as plt def avgWordPlot(input_file): """ Return a plot comparing average words per comment. Args: input_file: name of input file """ plot_test = pd.read_csv(input_file) subs = plot_test['Subreddit'].values.tolist() top = plot_test['"Top"...
true
6bf805c050a58e48b53a1fab0039028a2739b001
ahmedje123/Programming.ICT
/Practice Exercises/les4/pe4_5.py
UTF-8
180
2.96875
3
[]
no_license
def kwadraten_som(grondgetallen): x = 0 for getal in grondgetallen: if getal >= 0: x += getal ** 2 return x print(kwadraten_som([3, 5, 8, 7, -6]))
true
ffdedf9815da697cc3fa85550197f7f363cedce2
redoctoberbluechristmas/100DaysOfCodePython
/Day26 - NATO Alphabet - List, Dict Comprehensions/main.py
UTF-8
807
4.40625
4
[]
no_license
import pandas # Goals - Take csv of NATO phonetic alphabet and: # 1. Create a dictionary in this format: {"A": "Alpha"} convert CSV into dictionary. Use dictionary comprehension # 2. Create a list of phonetic codewords froma word that user inputs. # {new_key:new_value for (index, row) in data.iterrows()} data = pa...
true
6fc9d8032c359a5d145d139b99cdd20fc1f2f83f
ksato-dev/multiprocessing_exercises
/test_shared_string.py
UTF-8
1,225
3.109375
3
[]
no_license
# -*- coding: utf-8 -*- from multiprocessing import Process, Manager, Lock import time from ctypes import c_char_p def hoge(shared_string, lock): while True: string = shared_string.value if (string != ""): lock.acquire() print(shared_string.value) shared_string....
true
8998b1e56ccf5197a757502b05f23ee32373d386
mandos1995/online_judge
/BOJ/전체문제/11399_ATM.py
UTF-8
214
2.96875
3
[]
no_license
N = int(input()) time = list(map(int, input().split())) time = sorted(time) list_sum = [] min_time = 0 for i in range(len(time)): list_sum.append(time[i]) min_time = min_time + sum(list_sum) print(min_time)
true
9baf6fe905ce33476473e24cd96e770402ecc62d
krisrjohnson/Jeopardy_topic_modeling
/jeopardy_funcs.py
UTF-8
14,643
2.8125
3
[]
no_license
""" Script containing all helper and plotting functions use in report """ import sys import numpy as np import pandas as pd import json import matplotlib.pyplot as plt import nltk import re import time import string import gensim import spacy from collections import Counter, defaultdict from wordcloud import WordCloud...
true
05a38771119a86b06c3abc11c6718558ca910ad9
FelipeAdachi/Fault-Detection-ROV
/0.Generate_Files/preprocess.py
UTF-8
11,874
2.671875
3
[]
no_license
#!/usr/bin/python3 #Este programa desacumula os jsons, isto é: compara um arquivo com o subsequente e deleta qualquer timestamp menor do que o timestamp máximo encontrado no arquivo anterior, tanto para os dados de navegação quanto para o de telemetria. Deve-se especificar o endereço dos dados acumulados de entrada e ...
true
5f55db6bf0dea11a67fa8786d6f0025c3f65914a
Hayleypp/flaskfibonacci
/fibonacci.py
UTF-8
841
3.375
3
[]
no_license
def Solution(target): def calcFibo(target): fib_num = [] i = 2 fib_num.append(2) # assume F1 and F2 are 2 and 3, not 1 and 1 from the original condition fib_num.append(3) while True: next = (fib_num[i - 1] + fib_num[i - 2]) if next > target: ...
true
745fda8f1d86d7949c07253d806b67e5448d2afb
Rayvivek881/python_importent
/DynamicPrograming/palindromicSubstring.py
UTF-8
644
3.125
3
[]
no_license
def palindromeSubStrs(s, n): dp, m = [[0 for i in range(n)] for _ in range(n)], {} for i in range(n): dp[i][i] = 1 m[s[i]] = 1 for i in range(n - 1): if s[i] == s[i + 1]: dp[i][i + 1] = 1 m[s[i: i + 2]] = 1 for length in range(3, n + 1): ...
true
ea54ce73ff8a8d5f8579ab77e00261d670f2b42f
coxdoank/python
/math_func.py
UTF-8
137
3.65625
4
[]
no_license
import math print(math.ceil(2.9)) #pembulatan keatas print(math.floor(2.9)) #pembulatan kebawah x = 2.9 print(round(x)) print(abs(-2.9))
true
601e19b82ad597f779f944f727c4553b37892781
MerliN-47/rpi-object-detection
/src/object-tracking-shape/cv_object_tracking_shape.py
UTF-8
2,268
3.3125
3
[ "MIT" ]
permissive
#!/usr/bin/python3 """ Find geometric shaped objects in the image using houghCircles(). Reference: - https://www.pyimagesearch.com/2014/07/21/detecting-circles-images-using-opencv-hough-circles/ YunFei Robotics Labrotary Twitter: @yfrobotics Website: https://www.yfrl.org """ import cv2 import numpy as np CAMERA_D...
true
0eb2ab000bbb2f64ba8e031dd72a225f9ed8522d
karishma-gangwani/Py4e-codes
/4.6.py
UTF-8
215
3.3125
3
[]
no_license
h = float(input("Enter Hours:")) r = float(input("Enter Rate per hour:")) def computepay(h,r): if h > 40: p = (40*r)+(h-40)*(r*1.5) else: p = (40*r) return p print ("Pay", computepay(h,r))
true
f60e03507d7759d593f15db7a13f10a2f06fd637
mglodziak/python
/08/zadanko.py
UTF-8
1,003
3.21875
3
[]
no_license
import math import turtle as turtuś from random import randrange π=math.pi def okrag (x,y,R,ang): new_x=R*math.cos(ang*π/180) new_y=R*math.sin(ang*π/180) return (x+new_x, y+new_y, ang) def generator(x,y,R,krok): for i in range(0,361,krok): # print(i) yield okrag(x,y,R,i) def r...
true
967fee4b6dbfaaf865a7637403cbe9b3d2878d5a
abujawed11/python_codes
/python codes/test.py
UTF-8
195
3.765625
4
[]
no_license
a = int(input("Enter 1st number: ")) b = int(input("Enter 2nd number: ")) for i in range(a,b+1): for x in range(2,i): if (i%x)==0: break else: print(i)
true
504906527063e51832f03ed5d51ee189972e9f62
jay087/Jason
/Chore_Chart.py
UTF-8
14,597
3.421875
3
[]
no_license
#Group J #Student_Name: Zehua Zheng 17012373 #Student_Name: Jason Wu 17001792 # # This application keeps track of the household chores completed in a shared # house over a number of weeks. # # Author: Rae Harbird # Date: December 2019 from household_module import Household from chores_list_module import ChoresList...
true
015bfdd28da961d303817ea8edf146ac15eb6612
henryhcheung1/VideoPlayer
/src/VideoFileClip.py
UTF-8
960
2.75
3
[]
no_license
from VideoReader import VideoReader from AudioFileClip import AudioFileClip class VideoFileClip: def __init__(self, filename, target_resolution=None, resize_algorithm='bicubic', pixel_format='rgb24', sample_rate=None): self.reader = VideoReader(filename, target_resolution=target_resolut...
true
939c608a4e8ef30e897377b887472d84035c62a2
ourobouros/csc2548-caption-rnn
/evaluation_mode.py
UTF-8
1,502
2.578125
3
[]
no_license
import torch import torchvision from torch.autograd import Variable import pdb from PIL import Image import coco_data_loader import caption_net import json BATCH_SIZE = 150 def evaluation_loop(args): """Generate a set of captions for evaluation""" dataloader = torch.utils.data.DataLoader( coco_data_loader.Co...
true
546d73fee6d07ddf396b065e2c7fb8944172cf8e
ypix/TeTueTwitchBot
/tetuebot/cmds/economy.py
UTF-8
199
2.546875
3
[ "BSD-3-Clause" ]
permissive
from .. import db def coins(bot, user, *args): coins = db.field("SELECT Coins FROM users WHERE UserID = ?", user.get_id()) bot.send_message(f"{user.get_displayname()}, you have {coins:,} coins.")
true
7ca51022df4751b5bf86f9dcbf60c67c58254879
muzudho/kif-parser
/scripts/test_lib.py
UTF-8
547
3.390625
3
[ "MIT" ]
permissive
import hashlib def create_sha256(binary_data): """SHA256のハッシュ値 Parameters ---------- binary_data : binary バイナリー形式 """ return hashlib.sha256(binary_data).hexdigest() def create_sha256_by_file_path(file): """SHA256のハッシュ値 Parameters ---------- file : str ファイル パス ...
true
8e70c13309bfd916c55a2b3b1448cab489d8bf47
NathanKr/numpy-playground
/numpy_try.py
UTF-8
1,141
3.75
4
[ "MIT" ]
permissive
import numpy as np print("np.__version__ : \n",np.__version__) vec1 = np.array([1, 2, 3, 4, 5]) # [1 2 3 4 5] is created print("vec1 : \n",vec1) print("vec1.size : \n",vec1.size) vec2 = np.arange(5) # [0 1 2 3 4] is created print("vec2 : \n",vec2) print("vec2.size : \n",vec2.size) print("np.dot(vec1,vec2) : ",np.do...
true
90af2074e543877e7e33f602beb81da719e915ba
kamkali/Kurs-Python
/week04_day01/files_ex.py
UTF-8
1,756
3.171875
3
[]
no_license
""" 1.Przeczytaj plik 2. Utwórz osobny folder dla każdego wydarzenia (kolumna 'Games') 3. W odpowiednim folderze utwórz osobny plik json dla każdego kraju """ import os import json import pathlib import shutil def read_csv_games(filename='box_since_2000.csv'): with open(filename, 'r') as f: f.read...
true
9910dc5913f0bb8029c8d1b4348c0d08274f4eda
jhauberg/cards.py
/cards/constants.py
UTF-8
6,350
2.84375
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
# coding=utf-8 """ This module provides access to reserved constants; column names, card sizes and such. """ import datetime VERSION_PATTERN = r'^__version__ = [\'"]([^\'"]*)[\'"]' FIXED_TIMESTAMP = datetime.date.today() class Columns: # pylint: disable=too-few-public-methods """ Reserved column names. """ ...
true
4fddd1aea7f54a965832dd8a8c5e98187e652cb4
OCRoArchive/tarproc
/tarproclib/writer.py
UTF-8
4,096
2.515625
3
[ "BSD-3-Clause" ]
permissive
#!/usr/bin/python3 # # Copyright (c) 2017-2019 NVIDIA CORPORATION. All rights reserved. # This file is part of webloader (see TBD). # See the LICENSE file for licensing terms (BSD-style). # import io import sys import tarfile import time from urllib.parse import urlparse __all__ = "TarWriter1 TarWriter".split() cla...
true
bdab70f9bbfad41dad328beab1a161bf9fcdcd9e
Murilloo12/Projeto-N1
/index.py
UTF-8
1,408
3.890625
4
[]
no_license
import random contador = 0 sala = 1 escolha_caminho = 1 semProcesso = False print ('''--- Bem-vindo(a) ---\n \nNesse jogo você é líder de uma guilda de aventureiros e, tem como objetivo chegar ate a sala 9, MAS CUIDADO, no meio do caminho há alguns obstáculos e a aventura deve ser terminado em no máximo de 7 jogadas...
true
1f8260c37ae9a1ed57f69d66763222764e8fdf34
infimath/optimization-taha
/tableau.py
UTF-8
4,860
3.3125
3
[ "MIT" ]
permissive
""" Modified from: http://hubpages.com/technology/Simplex-Algorithm-in-Python """ from __future__ import division from numpy import * # Ref: http://stackoverflow.com/questions/23344185/how-to-convert-a-decimal-number-into-fraction from fractions import Fraction class Tableau: def __init__(self, obj): ...
true
84f8c27e5b608c0de3313a7e42f07f70ebfb4374
Ilia-Abrosimov/Algorithms-and-data-structures
/1. Tasks from interview/I.py
UTF-8
1,645
3.734375
4
[]
no_license
"""Тимофей спросил у студента Саши, умеет ли тот работать с числами в двоичной системе счисления. Он ответил, что проходил это на одной из первых лекций по информатике. Тимофей предложил Саше решить задачку. Два числа записаны в двоичной системе счисления. Нужно вывести их сумму, также в двоичной системе. Встроенную в ...
true
6014e51e42fc4252f01886f63a424ff04e36b0e3
nmcclain/do_route53_backup
/do_route53_backup
UTF-8
1,480
2.640625
3
[]
no_license
#!/usr/bin/python import argparse, re, boto ################################################################ #### quick and dirty nagios/icinga backup of an AWS Route53 zone def main(): #### deal with arguments parser = argparse.ArgumentParser() parser.add_argument('-K', '--aws_key_id', help='AWS key ID', require...
true
e67c05d7872246e1905d70b7e6a2bb92c08175a8
augustogoulart/pdbr
/pdbr/_console_layout.py
UTF-8
1,485
2.765625
3
[ "MIT" ]
permissive
from rich.containers import Lines from rich.errors import NotRenderableError from rich.layout import Layout from rich.panel import Panel class ConsoleLayoutMeta(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: instance = super().__call__(*args, **kw...
true
20a03a528124a72ee0a0cb3615e1b477fba38c5f
Bartleby2718/Windows10-Spotlight-Crawler
/crawler.py
UTF-8
2,920
2.953125
3
[ "MIT" ]
permissive
import getpass import json import os import platform import shutil import sys import PIL.Image # Check if the user is on Windows. is_windows = platform.system() == 'Windows' if not is_windows: print('We detected your operating system is not Windows. ' 'This program is designed to only work ...
true
63043710e6f6c2dcd39608e13ea8009e4915f17a
prstcsnpr/CandidatesGuide
/server/src/candidates_guide.py
UTF-8
4,878
2.578125
3
[]
no_license
# -*- coding: utf-8 -*- import json import string import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") class CandidatesRecommendationHandler(tornado.web.RequestHandler): def post(self): sat = sel...
true
cf464aa06ad28760c65b88e4dbebed15ab17d01b
luandimoura/Problemas_do_URI
/Loja_de_Tintas.py
UTF-8
256
3.40625
3
[ "MIT" ]
permissive
#Programa_Loja_de_Tintas area = int(input("Informe o tamanho em metros quadrados: ")) quantidade_latas = area/54.0 valor = quantidade_latas*80.0 print("Quantidade de latas necessarias: %.1f" %quantidade_latas) print("Valor total: %.2f" %valor)
true
d89f3f6cc0fa3146a3679b269fe840b38e023192
archit12/CodeRead
/Postprocessing.py
UTF-8
272
2.5625
3
[]
no_license
import sys if __name__ == "__main__": argv = sys.argv in_file = argv[1] out_file = argv[2] before = open(in_file) after = open(out_file, 'w+') for line in before.readlines(): line = line.replace('\r', '') line = line.replace('\x1c', '\"') after.write(line)
true
4808ef9fde9dd04abc207356efa4994d04fce4b8
IssamLaradji/MachineLearningOptimization
/presentations/Tekathon_Workshop_2017/utils.py
UTF-8
1,618
2.640625
3
[]
no_license
import numpy as np import json from textblob import TextBlob import re from lxml import html import json import requests import re import argparse from dateutil import parser as dateparser from time import sleep from lxml import html as xmlhtml import numpy as np import pandas as pd headers = {'User-Agent': 'Mozil...
true
8b9c7a5ecf3a62d0d3910e1b275cae8c24af5a66
jayshah52/BookStore
/db.py
UTF-8
1,710
3.078125
3
[]
no_license
import sqlite3 def connect(): con = sqlite3.connect("books.db") cur = con.cursor() cur.execute("CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY, title TEXT ,author TEXT, year INTEGER, isbn integer )") con.commit() con.close() connect() def insert(title, author, year,isbn): con = sqli...
true
2d2463782a8b19f65defb4e72affc4ae26b7892d
YJL33/LeetCode
/old_session/session_1/_64/_64_minimum_path_sum.py
UTF-8
735
3.71875
4
[]
no_license
""" 64. Minimum Path Sum Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. """ class Solution(object): def minPathSum(self, grid): """ ...
true
a3dc76416eb3b75be108c387990b2a7fdba885e4
niucheng1991/Machine-Learning
/linear_regression/regresion.py
UTF-8
3,509
3.359375
3
[]
no_license
#-*- coding: utf-8 -*- import math import numpy as np # 回归基类 class Regression(object): def __init__(self, n_iter, learning_rate): self.n_iter = n_iter self.learning_rate = learning_rate def initialize_weights(self, n_features): """ 随机初始化权重参数[-1 / N, 1 / N] """ ...
true
cf4df5cf15a2e819134cf13f11eabc53e0bd9079
manon2012/python
/work/leetcode/intersect.py
UTF-8
596
2.953125
3
[]
no_license
def intersect(a,b): # d = {} # res = [] # # for i in a: # if i not in d: # d[i] = 1 # else: # d[i] += 1 # print (d) # for i in b: # if i in d and d[i] > 0: # condition here to avoid appending i to the list when d[i] <= 0 # res.append(i...
true
3cb2327d04779ef2086c0c3b53743894945fdad2
bachelorbois/HumorHeadlines
/src/lib/features/phoneticfeature.py
UTF-8
1,231
3.0625
3
[]
no_license
import numpy as np from Levenshtein import StringMatcher from g2p_en import G2p from lib.features import Feature from lib.parsing import Headline class PhoneticFeature(Feature): # initialize grapheme to phoneme g2p = G2p() # error counter #counter = 0 @classmethod def compute_feature(cls, HL: ...
true
60ee0d1a9899f99c2e3a3ed2c4c47b350bc36c06
Taechit/sentiment
/Sentiment.py
UTF-8
6,203
2.6875
3
[]
no_license
#!/usr/local/bin/python # -*- coding: utf-8 -*- import os, sys from pythainlp.tokenize import word_tokenize import codecs import re #สำหรับแยกคำ def stringSplit(txt): pos = txt.rfind(',') return txt[:pos-1],txt[pos+1:] def naiveBayes (word,training): countPos = 0 countNeg = 0 d =0 da = 0 ...
true