blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 133 | path stringlengths 2 333 | src_encoding stringclasses 30
values | length_bytes int64 18 5.47M | score float64 2.52 5.81 | int_score int64 3 5 | detected_licenses listlengths 0 67 | license_type stringclasses 2
values | text stringlengths 12 5.47M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
35823a1601154542d734445efd4708066d34a8bc | Python | tczhaodachuan/LeetCode | /src/main/bloomberg/Merge.py | UTF-8 | 501 | 3.359375 | 3 | [] | no_license | def merge(nums1, nums2):
m = len(nums1)
n = len(nums2)
nums = []
i = 0
j = 0
while i < m and j < n:
if nums1[i] <= nums2[j]:
nums.append(nums1[i])
i += 1
else:
nums.append(nums2[j])
j += 1
while i < m:
nums.append(nums1... | true |
4e644e90fc953c0a8de3321c5bcaa3616e8ec2a4 | Python | Hardthof/AdventOfCode2020 | /AdventDay8.py | UTF-8 | 1,427 | 2.859375 | 3 | [] | no_license | from datetime import datetime
def bt(data):
#print('depth: ', len(data['hist']), '\n', data)
if data['stp'] in data['hist']:
#print('last vlaue is: ', data['accumulator'])
return False
nd = data.copy()
nd['hist'] = data['hist'].copy()
nd['hist'].append(nd['stp'])
if data['cmd'... | true |
a42a9a6bc064b47593904efa55866febf9f61fb6 | Python | yangxiangtao/biji | /1-pbase/day10/practice/caic_call_name.py | UTF-8 | 148 | 3.203125 | 3 | [] | no_license | count=0
def fx(name):
print('你好',name)
global count
count += 1
fx('小航')
fx('小李')
print('fx函数共被调用',count,'次') | true |
b7c4499061c440616c29be517634b73ee94d5f8d | Python | StephanBischoff-Digle/adventofcode | /2021/01/01.1/proto.py | UTF-8 | 220 | 2.78125 | 3 | [] | no_license | #!/usr/bin/env python3
import fileinput
measures = [int(line.strip()) for line in fileinput.input("input.txt")]
solution = [measures[i] < measures[i + 1] for i in range(len(measures) - 1)].count(True)
print(solution)
| true |
6f0b00bb79ffa2c52c3e237e88e4ab7a584f6714 | Python | LittleSheepy/MyMLStudy | /ml06pyPackeg/pk02opencv/cv02官网教程470/cv3ImageProcessing/cv1Basic/cv9BasicThresholdingOperations.py | UTF-8 | 1,504 | 3.09375 | 3 | [] | no_license | """
阈值基本操作
"""
import numpy as np
import sys
import cv2
import cv2 as cv
max_value = 255
max_type = 4
max_binary_value = 255
trackbar_type = 'Type: \n 0: Binary \n 1: Binary Inverted \n 2: Truncate \n 3: To Zero \n 4: To Zero Inverted'
trackbar_value = 'Value'
window_name = 'Threshold Demo'
## [Threshold_Demo]
de... | true |
2cad1244bac774b712bf0eaf4a25efc6fc35c9ad | Python | LopesAbigail/UFABC-PI-2021 | /inverted-numbers.py | UTF-8 | 188 | 3.53125 | 4 | [] | no_license | number = int(input())
inverted_number = ''
while (number > 0):
current_digit = number % 10
number = number // 10
inverted_number += str(current_digit)
print(inverted_number)
| true |
1c923b5b4a6cb0b073464618933739ec6dc80af6 | Python | hkrsmk/beepboop-shopee-code-league-2020 | /3_ShortAlgoContest/hawjia/ItemStock.py | UTF-8 | 2,789 | 3.296875 | 3 | [
"Unlicense"
] | permissive | from enum import Enum
import math
import sys
class Type(Enum):
DYANAMIC = 1
STATIC = 2
class Node:
def __init__(self, id, type, parent, ratio, stock):
self.id = id
self.parent = parent
self.type = Type(type)
self.ratio = ratio
self.stock = stock
self.childre... | true |
54bddf7c5d5855bd4ca7bca5f312cb91bc72d423 | Python | arthur422tp/arthur422 | /Math.py | UTF-8 | 614 | 3.359375 | 3 | [] | no_license | import random
n = 1
Exam = []
Answer = []
Answer2 = []
T = 0
file = open("Math.txt","r",encoding='utf-8')
for i in file.readlines():
a = i.split("=")
Exam.append(a[0])
Answer.append(a[1])
file.close
for i in Answer:
j = i.replace("\n","")
j = j.replace(" ","")
Answer2.append(j)
while n <= 10:
... | true |
16b7e382f02b83aec44d8ec952fd6919e336fe59 | Python | owenbrown/python_stack | /doubly_linked_list.py | UTF-8 | 6,432 | 3.8125 | 4 | [] | no_license | import unittest
class Node(object):
def __init__(self, value, previous_node: 'Node' = None, next_node: 'Node' = None):
self.value = value
self.previous_node = previous_node
self.next_node = next_node
class DoublyLinkedList(object):
def __init__(self):
self.head = None # typ... | true |
0badccb8a26fadebc9401c02dd78773236edece0 | Python | w-mg-moorhouse/WakeAndShake | /src/RemoteNodeServices.py | UTF-8 | 1,809 | 2.671875 | 3 | [
"MIT"
] | permissive | '''
Created on 10 May 2015
@author: will
'''
import threading
import time
from wakeonlan import wol
import subprocess
class RemoteNodeServices(object):
'''
classdocs
'''
@staticmethod
def __wakeNode(remoteNode):
try:
wol.send_magic_packet(remoteNode.getMAC())
ex... | true |
6845b825ea2f2b0098e714d60f7df335a066f994 | Python | nausheenfatma/DS-and-Algorithms-Practice | /4.1IsTreeBalanced.py | UTF-8 | 2,167 | 4.1875 | 4 | [] | no_license | """
Implement a function to check if a tree is balanced. For the purposes of this question,
a balanced tree is defined to be a tree such that no two leaf nodes differ in distance
from the root by more than one
answer: difference of min depth and max depth should not be greater than 1
order:o(n)
"""
class Node:
def ... | true |
23dc7d8130b378161fdf4f5a8acb522d0f0e2099 | Python | Enphonn/Python | /Lab2/task3.py | UTF-8 | 433 | 2.734375 | 3 | [] | no_license | import collections
import xml.etree.ElementTree as et
def find_equal(file):
words = list((open(file).read().lower()).split())
return collections.Counter(words)
voc = find_equal("file.txt")
root = et.Element("root")
doc = et.SubElement(root, "doc")
p =0
for key in voc:
et.SubElement(doc,"... | true |
6ce09823e3dd61bc3a8c196338762f037ab51131 | Python | hexin-pku/MapMD | /srcpy/mapr.py | UTF-8 | 14,811 | 2.609375 | 3 | [] | no_license | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
class vecc:
def __init__(self, **args):
# initial size
if 'vsize' in args:
self.vsize = args['vsize']
else:
print('warning, loss of matrix size')
exit()
# initial di... | true |
75b656b9680cdc6095fcee6c0c91a99744f25a7b | Python | InnoFang/algorithm-visualization | /sorts/Python/merge_sort.py | UTF-8 | 1,000 | 3.6875 | 4 | [
"Apache-2.0"
] | permissive | def merge_sort(data):
yield from __merge_sort(data, 0, len(data) - 1)
def __merge_sort(data, start, end):
"""Merge sort: O(nlogn)"""
if end <= start:
return
mid = start + ((end - start + 1) // 2) - 1
yield from __merge_sort(data, start, mid)
yield from __merge_sort(data, mid + 1, end)
... | true |
eaca69a0c614390f2516d112004379902fc3484d | Python | DanielSalamon/A05-MAS-virus-spreading | /model/simulationInitialiser.py | UTF-8 | 1,837 | 2.609375 | 3 | [] | no_license | from model.areas import Home, Other, School, Work, All
from model.agents.baseAgent import *
class SimulationInitialiser():
def __init__(self, virusModel):
self.model = virusModel
self.workplaces = list() # list of each area in the simulation
self.homes = list()
self.schools = l... | true |
ec519a9ac4ed897cdbf44cafba8558da1494bc3d | Python | Eemann33/Python-Data-Structures | /Queue.py | UTF-8 | 978 | 4.6875 | 5 | [] | no_license |
'''Creating a Queue class in Python using a list '''
class Queue:
def __init__(self):
self.items = []
def enqueue(self,item):
'''Adds an item to the back of the queue'''
self.items.insert(0,item)
def dequeue(self):
'''Returns and removes the item in the front of the que... | true |
63258ef0405daca2bfd27e1958126b7dfb85a599 | Python | olinrobotics/cut_mission | /scripts/Pathing.py | UTF-8 | 4,793 | 2.828125 | 3 | [] | no_license | #!/usr/bin/env python
import rospy
import math
from cut_mission.msg import Waypoint, WaypointPairLabeled
from geometry_msgs.msg import Twist, Point
from std_msgs.msg import Bool
import tf
from cut_mission.srv import *
class Pathing():
def __init__(self):
rospy.init_node("pathing")
self.s = rospy.Service('getCurr... | true |
901e18d0fe1eabe386f0b7bce84c6cc8c2b47ca7 | Python | AndrewLester/2020-robot | /src/components/trajectory_follower.py | UTF-8 | 3,781 | 2.765625 | 3 | [
"MIT"
] | permissive | from wpilib.controller import RamseteController, SimpleMotorFeedforwardMeters, PIDController
from wpilib.kinematics import DifferentialDriveKinematics, ChassisSpeeds, DifferentialDriveWheelSpeeds
from wpilib.geometry import Pose2d, Rotation2d, Translation2d
from wpilib.trajectory import Trajectory
from magicbot import ... | true |
9d96b372fae937b3d239ba1f678a12a655afbf35 | Python | grantjenks/python-runstats | /runstats/core.py | UTF-8 | 16,213 | 3.828125 | 4 | [
"Apache-2.0"
] | permissive | """Python RunStats
Compute Statistics, Exponential Statistics and Regression in a single pass.
"""
from __future__ import division
NAN = float('nan')
class Statistics:
"""Compute statistics in a single pass.
Computes the minimum, maximum, mean, variance, standard deviation,
skewness, and kurtosis.
... | true |
5263a60e26e8e57c7c8bfc7af3f4988f525c6ebc | Python | KIMBIBLE/telepot | /introductionExample/inlineQuery.py | UTF-8 | 1,545 | 2.71875 | 3 | [
"MIT"
] | permissive | import sys
import telepot
from telepot.namedtuple import InlineQueryResultArticle, InputTextMessageContent
import configparser
# read bot's token from configfile
def getBotToken(configFilePath):
config = configparser.ConfigParser()
config.read(configFilePath)
TOKEN = config.get('bbkim_test_bot_INFO', 'TOKEN')
ret... | true |
b7b7a9ed82ff6320241eb9cb138f4bd82faf9a67 | Python | lvoursl-zz/gotohack | /test_for_posts_text_length.py | UTF-8 | 1,718 | 2.90625 | 3 | [] | no_license | import re
def killshit(text):
temp = text.split(' ')
ans = ""
for i in range (len(temp)):
if len(temp[i]) > 4 and len(temp[i]) < 21:
ans += temp[i]
ans += ' '
return ans
delete = re.compile(u'\W+?', re.UNICODE)
groups_file = tuple(open('groups_list.txt', 'r+'))
groups_... | true |
9127ba353eb6e994d079553c8946bd5cfd017784 | Python | chalobest/bestbits | /best/tag.py | UTF-8 | 1,467 | 2.546875 | 3 | [] | no_license | from fuzzywuzzy import fuzz,process
import re
def find_tag(s,list,thrd):
inp=s.lower()
for i in list:
if fuzz.ratio(i,s) >= thrd:
return 1
return 0
def get_tag_list(s):
catg =[ ['station',80,0],
['bus',80,0],
['east',80,0],
['west',80,0],
#['nagar',80,0],
['park',80,0],
['marg',80,0],
... | true |
24c5e208dcec68e9a1ba5256b316806d87446cf8 | Python | Scott-S-Lin/OpenCV | /0521/p06_邊緣檢測/02_prewitt.py | UTF-8 | 2,120 | 2.84375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import sys
import numpy as np
from scipy import signal
import cv2
#prewtt卷積
def prewitt(I,_boundary='symm',):
#因為prewitt_X是可分離卷積核,根據卷積運算的結合律,可以分兩次小卷積核運算
#1:垂直方向的 " 平均值平滑 "
ones_y = np.array([[1],[1],[1]],np.float32)
i_conv_pre_x = signal.convolve2d(I,ones_y,mode='same',boundary =... | true |
7b7cf96567679c59beed9483a4974655e77dff46 | Python | Chewystein/Inventory | /Learning.py | UTF-8 | 2,515 | 3.625 | 4 | [] | no_license | import os
class Node():
def __init__(self):
self.tag = ""
self.location = ""
def __init__(self, tag, location):
self.tag = tag
self.location = location
def main():
# Initialize the two arrays
badTagList = []
missingTagList = []
# Check throug... | true |
7760d301ad70c68dfefc43fe4604d508ec6c861b | Python | SpirentOrion/osv | /scripts/manifest_common.py | UTF-8 | 2,801 | 2.640625 | 3 | [
"BSD-3-Clause"
] | permissive | #!/usr/bin/python
import os, io, re, subprocess
defines = {}
def add_var(option, opt, value, parser):
var, val = value.split('=')
defines[var] = val
def expand(items):
for name, hostname in items:
if name.endswith('/**') and hostname.endswith('/**'):
name = name[:-2]
host... | true |
62a6c087ee8e28fd782b8aeec21f347501c3ed8c | Python | cyrustabatab/SpaceInvadersClassic | /heart.py | UTF-8 | 446 | 2.921875 | 3 | [] | no_license | import pygame,os
from item import Item
vec = pygame.math.Vector2
class Heart(Item):
name = 'heart'
time_last = 0
@property
def image_path(self):
return os.path.join('assets','heart.png')
@property
def text(self):
text = "Adds 10 HP"
WHITE = (255,255,255)
... | true |
0876215635d418a1f8d4e8e790e844d1282fe510 | Python | Kawser-nerd/CLCDSA | /Source Codes/CodeJamData/15/42/13.py | UTF-8 | 1,557 | 3.171875 | 3 | [] | no_license | # Python 3.2
import sys
infile = None
outfile = None
def readline():
x = infile.readline()
if len(x) > 0:
return x[:-1] # remove trailing endline
else:
return x
def readint():
return int(readline())
def readfloat():
return float(readline())
def readints():
xs = readline().s... | true |
1bfb5619c56dac7a48a406930bfe6aa19bd4915e | Python | vhrehfdl/Algorithm | /Baekjoon/Binary_Search/2470.py | UTF-8 | 986 | 3.078125 | 3 | [] | no_license | import sys
num = int(sys.stdin.readline())
solutes = sorted(list(map(int, sys.stdin.readline().split()))[:num])
min_diff = (abs(solutes[0] + solutes[1]), solutes[0], solutes[1])
print(solutes)
def binary_search(idx, val):
start = idx + 1
end = len(solutes) - 1
while start < end:
mid = (start + e... | true |
cde18543e5ee2a472978c4f697866a9260ac16bd | Python | mba-tradelab/programmation_python_mathematiques | /sources/corrigés/ch04/van_der_pol_4.py | UTF-8 | 1,982 | 2.71875 | 3 | [] | no_license | #!/usr/bin/python3
#-*- coding: Utf-8 -*-
########################################################################
# (C) Alexandre Casamayou-Boucau, Pascal Chauvin, Guillaume Connan #
# #
# Complément de l'ouvrage : ... | true |
49c4cded78274c29d154345d6633b0cdaa3b7497 | Python | Rockyzsu/StudyRepo | /python/my_py_notes_万物皆对象/modules_python常用模块/二维码处理/qrcode包/demo.py | UTF-8 | 582 | 2.53125 | 3 | [] | no_license | # coding:utf-8
'''
@author = super_fazai
@File : demo.py
@Time : 2018/7/3 17:36
@connect : superonesfazai@gmail.com
'''
"""
open-code: https://github.com/lincolnloop/python-qrcode
"""
# 常规用法
import qrcode
img = qrcode.make('https://www.baidu.com')
img.save('out.png')
# 高级用法
# import qrcode
#
# qr = qrcode.QR... | true |
bcc4f8d7a4b30969e6b0ff2a442c7767a6a00c46 | Python | ryandivas798/_ITP2017_FinalProject | /Final Project.py | UTF-8 | 8,313 | 3.140625 | 3 | [] | no_license | #I got most of the codes from youtube but i also modified most of the codes.
import os
import random
import pygame
from pygame.sprite import *
from pygame import *
pygame.init()
hitboxes = []
blocks =[]
class textsprite (Sprite): #This code is reusable, just fill in the parameters to reuse
def __init__(self, font... | true |
f1eb02c4fb01de0d5bc54e23c5e7f6bd563c35aa | Python | elenaisnanocat/Algorithm | /SWEA/swea_2805_농작물 수확하기.py | UTF-8 | 410 | 3.203125 | 3 | [] | no_license | T = int(input())
for tc in range(1, T+1):
N = int(input())
arr = [list(input()) for _ in range(N)]
mid = N//2
start = end = mid
ans = 0
for i in range(N):
for j in range(start, end+1):
ans += int(arr[i][j])
if i < mid:
start, end = start - 1, end + 1
... | true |
1e8ed999e36bfe33030a0423504050ca85ea307d | Python | maeji9811/AtCoder | /Easy/tax_rate.py | UTF-8 | 198 | 3.59375 | 4 | [] | no_license | import math
n = int(input())
x_int = int(n / 1.08)
x_ceil = math.ceil(n / 1.08)
if n == int(x_int * 1.08):
print(x_int)
elif n == int(x_ceil * 1.08):
print(x_ceil)
else:
print(':(')
| true |
56ae9af447a3c2e6778be5e3fdbb70f9ff74ce8b | Python | cookieswolf/coin_quant | /program/trade/script_detect.py | UTF-8 | 3,536 | 2.59375 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2018-10-17 21:55:41
# @Author : Michael (mishchael@gmail.com)
#!/usr/bin/python
# -*- coding:utf-8 -*-
import subprocess,time,sys
from datetime import datetime
TIME = 180 #程序状态检测间隔(单位:分钟)
CMD = script_path = 'python ../trade/bfx_main.py' ... | true |
b10eaae3b55dd10370110d354ae484defc6f0b60 | Python | hoangbinhc11996/python_tutorial | /numpy-module.py | UTF-8 | 751 | 2.796875 | 3 | [] | no_license | import numpy as np
m1 = np.ones((3, 4))
print(m1)
m2 = np.zeros((2, 3, 4), dtype=np.int16)
print m2
m3 = np.random.random((2, 2))
print m3
m4 = np.empty((3, 2))
print m4
m5 = np.arange(10, 25, 5)
print m5
m6 = np.linspace(0, 100, 101)
print m6
# x, y, z = np.loadtxt('data.txt',
# skiprows=1,... | true |
b4a03aafd733519947fb7063083675e78dc7a36c | Python | ssggrr55/CVL757_2021 | /2021CES2346_A2/2021CES2346_A2_Q3/2021CES2346_A2_Q3.py | UTF-8 | 5,183 | 2.890625 | 3 | [] | no_license | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import math
import numpy as np
te=2
tn=te+1
lem=[3000,3000]
xco=[0,lem[0],(lem[0]+lem[1])]
yco=[0,0,0]
I =40e6
E =70e3
snofel= [1,2] #start node of elements
enofel= [2,3] ... | true |
9d9cec892c3f186f036b6a7fd30a803415c41623 | Python | pjy970108/studying-algorithm | /baekjoon_problem/0914/백준_9093.py | UTF-8 | 149 | 2.96875 | 3 | [] | no_license | N = int(input())
for _ in range(N):
sen = list(input().split())
k=[]
for i in sen:
k.append(i[::-1])
print(' '.join(k)) | true |
c5a109658340c323388bb9792bbbb840d880aae5 | Python | Abekabe/verdict-crawler | /processorlib/defend_content_litigation.py | UTF-8 | 1,402 | 2.53125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
# coding: utf-8
import os
import csv
def get_defend_content_litigation(verdict, date, file_num):
try:
content = ''
if verdict.find('\n壹、') != -1 and verdict.find('壹、程序部分') == -1:
content_line = verdict.replace('\n貳、', '@').replace('\n參、', '@').replace('\... | true |
b093f7c22157f3a5e3c38d0c95b57ccc2d04a542 | Python | nl356/cs4300sp2020-jcb468_jf638_jmf373_nl356_dms539 | /tfidf.py | UTF-8 | 3,839 | 3.46875 | 3 | [] | no_license | #This script will read in movies and songs from database and return a matrix of tfidf values
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
import re
import json
from movies.movies import read_movies_json
from songs.songs import read_songs_json
from time import time
def build_vectorize... | true |
3a6155dc5e47c8570b94f4488971bcc2e8625b9d | Python | mansaluke/pixel2style2pixel-mobilenetv3 | /criteria/vggface2/utils.py | UTF-8 | 1,542 | 2.8125 | 3 | [
"MIT"
] | permissive | import pickle
import torch
from torch.autograd import Variable
def vgg_preprocess(batch):
tensortype = type(batch.data)
(r, g, b) = torch.chunk(batch, 3, dim=1)
batch = torch.cat((b, g, r), dim=1) # convert RGB to BGR
batch = (batch + 1) * 255 * 0.5 # [-1, 1] -> [0, 255]
mean = tensortype(batch.... | true |
d93e980ecc121ee9ca4b1a1f876040befb3f42f5 | Python | schiebermc/CP_Lib | /HackerRank/Practice/InterviewPrep/StacksandQueues/Queues_ATaleofTwoStacks/pycode.py | UTF-8 | 933 | 3.59375 | 4 | [] | no_license | # use this as the main template for python problems
class queue(object):
def __init__(self):
self.s1 = []
self.s2 = []
def push(self, val):
self.s1.append(val)
def pop(self):
if(len(self.s2) == 0): # form dequeue stack
while(len(self.s1) != 0):
... | true |
ba40ab9e935e03c7abedb29c8b4f53dc67f5d150 | Python | tawrahim/CSC7050 | /Compiler_Project/natasha.py | UTF-8 | 411 | 3.046875 | 3 | [] | no_license | import sys
from natasha_lexer import *
if __name__ == '__main__':
# file_name = sys.argv[1]
file_name = "hello.natasha"
if not file_name.endswith(".natasha"):
sys.stderr.write('Invalid natasha file')
sys.exit(1)
pass
file = open(file_name)
characters = file.read()
file... | true |
1b83747a59e238ac48514435cadae25aadd2e7c2 | Python | Baymax94/Games | /Game15/Game15.py | UTF-8 | 2,066 | 2.859375 | 3 | [
"MIT"
] | permissive | '''
Function:
连连看小游戏
Author:
Charles
微信公众号:
Charles的皮卡丘
'''
import os
import pygame
from utils import *
from config import *
'''游戏主程序'''
def main():
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Gemgem-微信公众号: Charles的皮卡丘')
# 加载背景音乐
pygame.mixer.init()
pygame.mixe... | true |
463fafc94d038caf74adb66affc297dd7a92e01e | Python | aldajo92/CodeChallengesPython | /basic_algorithms/02_sorting/02_merge_sort.py | UTF-8 | 1,173 | 4.09375 | 4 | [] | no_license | def mergesort(items):
# Base case, a list of 0 or 1 items is already sorted
if len(items) <= 1:
return items
# Otherwise, find the midpoint and split the list
midpoint = len(items) // 2
# TODO
left = items[:midpoint]
right = items[midpoint:]
# Call mergesort recursively with th... | true |
42127fba02f6fe21fa36943ac56cfa9d38a3164f | Python | stscirij/jwst | /jwst/straylight/straylight_step.py | UTF-8 | 5,209 | 2.515625 | 3 | [
"BSD-2-Clause"
] | permissive | #! /usr/bin/env python
from ..stpipe import Step
from .. import datamodels
from . import straylight
__all__ = ["StraylightStep"]
class StraylightStep (Step):
"""
StraylightStep: Performs straylight correction image using a Mask file.
"""
class_alias = "straylight"
spec = """
method = ... | true |
4f53300f76a9b918d7e667d39eaecae140a7f30e | Python | Schneeple/pythonCodes | /monteCarlo.py | UTF-8 | 630 | 3.078125 | 3 | [] | no_license | import random
import numpy as np
import matplotlib.pyplot as plt
import chart_studio.plotly as py
# Odds for Craps and Histogram graph
def roll():
roll_one= random.randint(1,6)
roll_two=random.randint(1,6)
sum=roll_one+roll_two
if sum > 12:
print("Error, sum can not be above 12")
return sum
x=0 # Starting num... | true |
24df8c9e2dc79607530826a9ce1104a877211f1b | Python | KimGyunYeop/hkd2020_SentimentAnalysis_Korean_GC | /data/sampling.py | UTF-8 | 1,132 | 2.71875 | 3 | [] | no_license | import pandas as pd
df = pd.read_csv('./data/naverMovie_Reviews_2017.txt', sep='\t')
df = df.drop_duplicates(subset = ['reviews'])
all_df = df
pos = df[df['label']==1]
print(len(pos))
neg = df[df['label']==0]
print(len(neg))
df = pd.read_csv('./data/naverMovie_Reviews_2018.txt', sep='\t')
df = df.drop_duplicates(subs... | true |
91c2f81c4ab6028328a17e0c252771798d862968 | Python | kirbisity/carNoiseFinder | /src/graph.py | UTF-8 | 1,597 | 3.078125 | 3 | [] | no_license | import socket
import sys
from matplotlib import pyplot as plt
#python3 graph.py
"""
recv message and sends ok
@returns: message: the message received from peer
"""
def recv_message():
data = connection.recv(1024).decode()
message = "OK!\n"
connection.send(message.encode())
return data
"""
@returns: ans: the grap... | true |
6b3f2945170cd443c884e1e8c285649511954499 | Python | dgamayunov/my_python | /get_parity.py | UTF-8 | 153 | 3.203125 | 3 | [] | no_license | def fun(x):
if x%2==0:
print('Чётное число')
else:
print('Не чётное число')
| true |
fd2ef3969cb4f0bff81f826caf99a6006e1c79fb | Python | breezekiller789/LeetCode | /217_Contains_Duplicate.py | UTF-8 | 749 | 3.421875 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# https://leetcode.com/problems/contains-duplicate/
# Joma class有講過這個,用一個演算法來做,線性時間,常數空間。
# https://www.youtube.com/watch?v=pKO9UjSeLew&ab_channel=JomaTech
# https://www.youtube.com/watch?v=9YTjXqqJEFE
# nums = [1, 2, 3, 1]
# nums = [1, 2, 3, 4]
nums = [1, 1, 1, 3, 3, 4, ... | true |
7fed14fa7746e7f9b87dafc4bfd5a1ddebbadb7f | Python | wkgreat/pylearning | /practice/tensorflow_prac/free_practice/kmeans.py | UTF-8 | 4,555 | 3.359375 | 3 | [] | no_license | """
KE WANG | wkgreat@outlook.com
20190731
KMeans Algorithm
"""
import random
import numpy as np
from copy import deepcopy
import matplotlib.pyplot as plt
class LabelPoint:
"""
the labeled point or (feature vector)
point is multi-dimensional vector
label is a unique identity of which cluster this poin... | true |
d76a0ab0c4954a01dbb43c6c0027fbbe7630db22 | Python | Zardosh/Algorithms | /HackerRank/Algorithms/Implementation/Easy/ModifiedKaprekarNumbers/Python/ModifiedKaprekarNumbers.py | UTF-8 | 743 | 3.265625 | 3 | [
"Unlicense"
] | permissive | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the kaprekarNumbers function below.
def kaprekarNumbers(p, q):
output_string = ""
for number in range(p, q + 1):
number_length = len(str(number))
last_part = int(str(number ** 2)[-number_length:])
first... | true |
ff431448d53bf6826ad6e5ceeda581bb08be4bc9 | Python | AnthonyDiTomo/hw-4 | /problem4.py | UTF-8 | 505 | 4 | 4 | [] | no_license | num1 = int(input("Please enter number 1 "))
num2 = int(input("Please enter number 2 "))
operator = input("What calculation would you like to do? (add, sub, mult, div) ")
if operator == "add":
print(num1 + num2)
elif operator == "sub":
print(num1 - num2)
elif operator == "mult":
print(num1 * num2)
elif ope... | true |
da5638b2925b3db65969bb9593a2059cd64d1756 | Python | couderbe/ResolutionConflits | /constantes.py | UTF-8 | 3,638 | 2.828125 | 3 | [] | no_license | import numpy as np
import argparse
### ---------- CONSTANTES ---------- ###
# Création des commandes pour modifier les paramètres du problème dans un terminal
parser = argparse.ArgumentParser()
parser.add_argument("-na", type=int, default=10, help="Nombre d'avions, initialisé à 10")
parser.add_argument("-rc", type=in... | true |
a1d1cc86c0609d193578c5a6a1b3f2af5e7d4d72 | Python | induane/harrenrpg | /old_engine_code/states/shop.py | UTF-8 | 10,631 | 3.03125 | 3 | [
"MIT"
] | permissive | """
This class is the parent class of all shop states.
This includes weapon, armour, magic and potion shops.
It also includes the inn. These states are scaled
twice as big as a level state. The self.gui controls
all the textboxes.
"""
import copy
import pygame as pg
from .. import tools, setup, shopgui
from .. import... | true |
8380c66beca72b78dd09ac5dc54b92dd92c688fd | Python | zappaz00/glasses_classifier | /sunglasses_bot.py | UTF-8 | 3,043 | 2.75 | 3 | [] | no_license | import telebot
import os
import cv2
import numpy as np
import sunglasses
from googletrans import Translator
token = os.getenv("GLASSES_TOKEN")
bot = telebot.TeleBot(token)
user_states = {}
def exception_catcher(base_function):
def new_function(*args,
**kwargs): # This allows you to decorate... | true |
67b6222a77ceee21a5e1f0e7525a84e2f965ef3b | Python | wangzelin007/first_project | /Users/suidx/Desktop/python/excercise_20171115/0004_20171116.py | UTF-8 | 1,262 | 3.40625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
'''
Created on Thu Nov 16 21:23:04 2017
任一个英文的纯文本文件,统计其中的单词出现的个数
@author: suidx
list=[]
f=open('globaltimes.txt')
paper=f.readlines()
for readline in paper:
line=readline.replace(',',' ')
line=readline.replace('.',' ')
line=readline.replace('\n',' ')
str=line.split(' ')
... | true |
4c66b84b5e7bc9ae17284852a1c22f1e6f845e81 | Python | c-goldschmidt/pyfl-utils | /pyfl_utils/imgconvert.py | UTF-8 | 1,871 | 2.796875 | 3 | [
"WTFPL"
] | permissive | import logging
import math
import os
from PIL import Image
from tempfile import NamedTemporaryFile
_logger = logging.getLogger(__name__)
def to_tga(filename):
im = Image.open(filename)
im_name = '.'.join(filename.split('.')[:-1])
im.save(im_name + '.tga')
def tga_from_string(string):
out_size = (256, 256)
max... | true |
0a542b7ae3ed4949ab593d247f12c42a6a9f46aa | Python | NashLea/elliott_wave | /q-learning/q.py | UTF-8 | 6,485 | 2.65625 | 3 | [] | no_license | import sys
import csv
import datetime
import numpy as np
import collections
import random
import itertools
import matplotlib.pyplot as plt
import fapprox
Gamma = 1.0
LookBack = [87, 54, 33, 21, 13, 8, 5, 3, 2, 1]
Epsilon = 0.9
Data = [
# ('dj', None, None),
# ('gdx', None, None),
# ('qcom', None, None),
... | true |
17a224b4e6107bb7eee982542a867fb2763fcd77 | Python | AakashOfficial/ChallengeTests | /challenge_1/python/returnlove/src/reverse_a_string.py | UTF-8 | 473 | 4.34375 | 4 | [
"MIT"
] | permissive | # read input string from user
input_string = raw_input("enter any string")
# solution 1
# create a variable to store the reversed string
reversed_string = ""
# loop through the input in reverse order and append each letter
for l in xrange(len(input_string)-1, -1, -1):
reversed_string += str(input_string[l])
print('... | true |
20ef0d6c3b0607998c6224bdbe80f75eee2cbba8 | Python | arasharchor/JackRabbot-Navigation | /sibot/manual_pc_setup_files/sibot_remote_ws/src/sibot/sibot_comm/scripts/utils.py | UTF-8 | 4,752 | 2.71875 | 3 | [] | no_license | """--------------------------------------------------------------------
COPYRIGHT 2014 Stanley Innovation Inc.
Software License Agreement:
The software supplied herewith by Stanley Innovation Inc. (the "Company")
for its licensed Segway RMP Robotic Platforms is intended and supplied to you,
the Company's customer, ... | true |
adb033c2305c2f0c3299a08a45d08f44354936d4 | Python | Aasthaengg/IBMdataset | /Python_codes/p02851/s648777084.py | UTF-8 | 1,565 | 2.78125 | 3 | [] | no_license | def read():
N, K = list(map(int, input().strip().split()))
A = list(map(int, input().strip().split()))
return N, K, A
def solve(N, K, A):
if K == 1:
return 0
S = [0 for _ in range(N+1)]
for i in range(N):
S[i+1] = S[i] + A[i]
count_sum = 0
count = dict()
fo... | true |
9277978a0301958c83fe2947a86a956d21c49c3b | Python | joluoch/USGS_3DEP_LIDAR_Challenge | /scripts/plots.py | UTF-8 | 2,664 | 2.59375 | 3 | [
"MIT"
] | permissive | import warnings
warnings.filterwarnings('ignore')
# import geoplot as gplt
import numpy as np
import plotly.offline as go_offline
import plotly.graph_objects as go
import geopandas as gpd
# import geoplot.crs as gcrs
import imageio
import pandas as pd
import pathlib
import matplotlib.pyplot as plt
from shapely.geometr... | true |
60fbe74f388118f29b430f407476af9ecc798c7c | Python | CrysthelAparicio/wdym-regex | /test.py | UTF-8 | 5,032 | 3.390625 | 3 | [
"MIT"
] | permissive | import re # Para las Regex
import os # Para el archivo
import subprocess as sp # Entradas y salidas
# ===============================================
# Ruteo
def getPath():
actualPath = os.getcwd()[1:].split("/")
retValue = ""
newPath = []
for path in actualPath:
if(path != "home"):
... | true |
c5fa49489e277b206998d6c0fd38158919d68be6 | Python | kshitijsudan01/vatopa | /pagewatch_demo/pagemapwatch | UTF-8 | 4,207 | 2.546875 | 3 | [] | no_license | #!/usr/bin/env python
import pygtk
pygtk.require('2.0')
import gtk, gobject, os, array, sys
import pagemap
pid = int(sys.argv[1])
def pixel2page(x, y):
block = ((y >> 5) << 5) + (x >> 5)
return (block << 10) + ((y & 31) << 5) + (x & 31)
def page2pixel(page):
block = page >> 10
x = (block & 31) * 32
... | true |
2c12e7594ad11fa34f485da3a58470ffc3a52437 | Python | HugoKlepsch/grade12python | /Grade12Python/review/looping.py | UTF-8 | 2,875 | 3.046875 | 3 | [] | no_license | from Tkinter import *
import time
w = 1366
h = 700
multix = input("enter zoom x: ")
multiy = input("enter zoom y: ")
size = input("enter size of dot: ")
numIter = input("number of iterations to calculate: ")
# multix = numIter * 0.06
# multiy = numIter * 0.01
# size = 1
def sortnumbers(w, x, y, z):
while((w <=... | true |
509d956c12c7903ba6fd8bcf4d0ae3e5aa21c4db | Python | limchyo/coding-for-future | /01_python/For_statement_practice.py | UTF-8 | 803 | 3.828125 | 4 | [] | no_license |
# 00100
# 01110
# 11111
# 01110
# 00100
# for num in range(1, 6):
# print("1" * num)
# for a in range(1, 101):
# print(a)
# A = [70, 60, 55, 75, 95, 90, 80, 80, 85, 100] #평균점수(for문)
# b = 0 # 0으로 시작해서 A의 값을 하나씩 받을 준비.
# for a in A: # 70부터 하나씩 값이 출력
# b += a # b는 a의 값이 순차적으로 더해진다.
# average = b / len(A... | true |
2e9c714919066ddfec0f1b39d73a3b96cfe7f81d | Python | hombit/mercury | /python/freddi/__init__.py | UTF-8 | 4,267 | 2.515625 | 3 | [] | no_license | from functools import partial
import numpy as np
from ._freddi import _Freddi, _FreddiNeutronStar
from .evolution_result import EvolutionResult
class _MetaFreddi(type(_Freddi)):
def __new__(mcs, name, bases, attrs, boost_cls=object):
attrs['_boost_class'] = boost_cls
test_obj = boost_cls(**boost... | true |
5ce7985b3513b1b52f15099c13766559a9c4d938 | Python | NY2308/Student-Repository | /HW11_Yash_Navdiwala/HW11_Test_Yash_Navdiwala.py | UTF-8 | 3,429 | 2.890625 | 3 | [] | no_license |
"""" Test for Repository """
import unittest
import os
import sqlite3
from HW11_Yash_Navdiwala import Repository, Student, Instructor, Major
class TestRepository(unittest.TestCase):
""" Test for repository """
def setUp(self) -> None:
"""This methods allow you to define instructions that will be ex... | true |
ff730382a922bb179953d2a38068ad2e3f28fba5 | Python | takushi-m/atcoder-work | /contests/diverta2019/c.py | UTF-8 | 658 | 2.765625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
n = int(input())
sl = [input() for _ in range(n)]
xa = []
bx = []
ba = []
x = []
for s in sl:
if s[0]=="B" and s[-1]=="A":
ba.append(s)
elif s[-1]=="A":
xa.append(s)
elif s[0]=="B":
bx.append(s)
else:
x.append(s)
if len(xa)>0:
xa = xa[:-1]+[x... | true |
fbc6890d4197fea5b3d89761d64aaa112d9c9694 | Python | NEWE69/projetnsi | /projetnsi-main - Copie/python/brouillon2.py | UTF-8 | 1,545 | 2.875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 17 11:55:48 2021
@author: dhem.romain
"""
import random
import sqlite3
def piece():
t = ["Face","Pile"]
r=random.choice(t)
return r
def detectionpile():
re = piece()
print("La pièce est tombé sur",re)
... | true |
7daadf221f7314a4e8fd91d7496e29f7ad742ade | Python | nlake44/sample-apps | /python/composite-test/composite.py | UTF-8 | 3,556 | 2.515625 | 3 | [] | no_license | #!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | true |
5f8ef9fa5fe811b674fdb1ac465993750e75c85a | Python | Prakti/striptease | /striptease/util.py | UTF-8 | 1,435 | 2.96875 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # -*- coding: utf-8 -*-
"""
striptease.util
~~~~~~~~~~~~~~~
Utility module for striptease.
"""
try:
import logbook as logging
Logger = logging.Logger
except ImportError:
import logging
def Logger(name, level=None):
"""
This is a function that emulates the logbook Logger con... | true |
f362b5359715182a2456621524d169ff53250c77 | Python | MovsisyanM/Data-Structures-And-Algos-Revisit | /Content/Data Structures/BinaryTreeCodebase.py | UTF-8 | 1,356 | 3.875 | 4 | [
"MIT"
] | permissive | "a valueless binary search tree"
class BinaryTree:
def __init__(self): self.tree = EmptyNode()
def __repr__(self): return repr(self.tree)
def lookup(self, value): return self.tree.lookup(value)
def insert(self, value): self.tree = self.tree.insert(value)
class EmptyNode:
def __repr__(self... | true |
c28f607cc395b618a40dee4c4d2d05e537c9b712 | Python | MemoryForSky/Data-Structures-and-Algorithms | /my_target_offer/37_serialize_binary_trees.py | UTF-8 | 2,795 | 4.375 | 4 | [] | no_license | """
面试题37:序列化二叉树
题目:请实现两个函数,分别用来序列化和反序列化二叉树。
思路:
本题的思路主要是二叉树的遍历和重构; --> 思路是一样的,都是考虑终止条件和迭代公式
"""
class Node:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.string = ""
def serialize(self, p_root):
... | true |
c6f1459cae66e4af63456e283260c8377d31f0c0 | Python | mdevilliers/python-bestiary | /pymotw/functools/wraps_examples.py | UTF-8 | 618 | 3.53125 | 4 | [] | no_license | # https://pymotw.com/2/functools/
import functools
def show_details(name, f):
"""Show details of a callable object."""
print '%s:' % name
print '\tobject:', f
print '\t__name__:',
try:
print f.__name__
except AttributeError:
print '(no __name__)'
print '\t__doc__', repr(f._... | true |
8e1940028a1cae119091ee5ad66ff625ce4975e8 | Python | agniecha95/Project | /main.py | UTF-8 | 2,307 | 2.96875 | 3 | [] | no_license | import os
import time
import db_handler
from db_executer import Db_executer
from CustomLogger import logger
path_to_watch = '.'
before = dict([(f, None) for f in os.listdir(path_to_watch)])
while 1:
db_name =r'E:\Moje\Python szkolenie\Python zaawansowany\Project\clinic.db'
db = Db_executer(db_name)
afte... | true |
d5121a57e5300b619edef249404b79a52f64ec0b | Python | m-star18/atcoder | /submissions/abc004/b.py | UTF-8 | 186 | 2.609375 | 3 | [
"Unlicense"
] | permissive | import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
print(read().rstrip().decode()[::-1])
| true |
c3b13c2536b62626f06e78215b6c347db50e684b | Python | sergun-36/homeworks | /hw_1_formatString_SA.py | UTF-8 | 193 | 3.125 | 3 | [] | no_license | username="Sergei"
city="Minsk"
date="05.11.2020"
weather="rainy"
weather_message="Hello {0} today {2} in the city {1} it is {3} ".format(username,city, date, weather)
print(weather_message)
| true |
e39f54b7882f0a2288e2e403df8c028897280102 | Python | Merricx/chaos-image-encryption | /encryption.py | UTF-8 | 3,123 | 2.8125 | 3 | [] | no_license | import random, os
import hashlib
import numpy as np
import time
from sympy import Matrix
from PIL import Image
def ACM(img, p, q, m):
counter = 0
if img.mode == "P":
img = img.convert("RGB")
assert img.size[0] == img.size[1]
while counter < m:
dim = width, heigh... | true |
5f4a88763de7d42793d3f64ce75b3d1b650ddb50 | Python | Samarth2028/PoseSim | /PoseSim.py | UTF-8 | 17,881 | 3 | 3 | [] | no_license | import matplotlib.pyplot as plt
import numpy as np
import math
#Dictionalry of Body parts with their corresponding id's according to mpi openpose model
BODY_PARTS = { "Head": 0, "Neck": 1, "RShoulder": 2, "RElbow": 3, "RWrist": 4,
"LShoulder": 5, "LElbow": 6, "LWrist": 7, "RHip": 8, "RKnee": 9,
... | true |
6bb92224b6fea36ad321cc798ddcd539dba70126 | Python | bemova/Deep_reinforcement_learning | /gym_mountain_car/tile_coding/demo.py | UTF-8 | 1,646 | 2.625 | 3 | [
"MIT"
] | permissive | import gym
import numpy as np
from gym_mountain_car.tile_coding.tilecoder import tilecoder
env = gym.make("MountainCar-v0")
tile = tilecoder(env, 4, 18)
theta = np.random.uniform(-0.001, 0, size=(tile.n))
# Custom alpha learned to generalize based upon number of tilings
alpha = (.1/ tile.numTilings)*3.2
# Discounting... | true |
9f005b01920d8923f2bb0bcd0cf2ab21d212a662 | Python | shiki7/Atcoder | /NYC2015/B.py | UTF-8 | 182 | 3.078125 | 3 | [] | no_license | N = int(input())
a = [int(input()) for _ in range(N)]
a = sorted(a)
total = a[0]
ans = 1
for i in range(1, N):
if a[i] > total:
total += a[i]
ans += 1
print(ans)
| true |
d406564fa26778d0f6326c077eed4c63f86e1973 | Python | Roshan98b/DSA | /Algorithms/GridTravel-DP1.py | UTF-8 | 552 | 3.671875 | 4 | [] | no_license | # No of ways to travel from top left to bottom right with blockages
def travel_count(m, n, blockage, memo = {}):
key = str(m) + ',' + str(n)
if (key in memo):
return memo[key]
elif (m == 0 or n == 0 or (m, n) in blockage):
return 0
elif (m == n == 1):
return 1
else:
m... | true |
8e996e8716311e501dfad4575c8cb460a7160ee3 | Python | loveAlakazam/leetcode | /303/Range_Sum_Query_Immutable.py | UTF-8 | 639 | 3.5625 | 4 | [] | no_license | class NumArray(object):
def __init__(self, nums):
self.origin=nums
len_origin = len(nums)
for idx in range(1,len_origin):
self.origin[idx]=self.origin[idx]+self.origin[idx-1]
"""
:type nums: List[int]
"""
def sumRange(self, i, j):
if ... | true |
f0c58b860359458882e2e2de4e4e0e3681950404 | Python | riya-the-coder/C-129 | /C-129b.py | UTF-8 | 670 | 2.84375 | 3 | [] | no_license | import csv
dataset1=[]
dataset2=[]
with open("dataset_1.csv","r")as f:
csvReader=csv.reader(f)
for row in csvReader:
dataset1.append(row)
Headers1=dataset1[0]
PlanetData1=dataset1[1:]
with open("dataset2sorted.csv","r")as f:
csvReader=csv.reader(f)
for row in csvReader:
datas... | true |
7afb1abb6ae05b58e7d0390bbfd6e4716fb45bf5 | Python | danielcb29/ComputerGraphics | /Taller2/op3dFigura.py | UTF-8 | 4,487 | 2.765625 | 3 | [] | no_license | #Practica 2 Daniel Correa 1225622
from OpenGL.GL import *
import OpenGL.GL as gl
from OpenGL.GLUT import *
from OpenGL.GLU import *
import random
from math import *
c11=0.094
c12= 0.392
c13=0.047
c21=0.047
c22=0.141
c23=0.392
c31=0.482
c32=0.035
c33=0.035
c41=0.698
c42=0.670
c43=0.003
c51=1.0
c52=1.0
c53=1.0
c61=... | true |
77b86a0f211e1585d2a918105f57bbd6108c3170 | Python | renatomak/coursera-python | /semana_05/test_functions/test_factorial.py | UTF-8 | 267 | 3.109375 | 3 | [] | no_license | from functions import factorial
def test_factorial_number_negative():
assert factorial(-1) == 1
def test_factorial_zero():
assert factorial(0) == 1
def test_factorial_one():
assert factorial(1) == 1
def test_factorial_five():
assert factorial(5) == 120 | true |
c600ecb031992b3c19915b7e68f7169d14a32f15 | Python | marcus-deans/duke-computationalmethods | /Lab6-Linear-Algebra/creative_chapra_08_16.py | UTF-8 | 752 | 3.21875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
[Chapra 8.16]
[Marcus Deans]
[20 October 2019]
I understand and have adhered to all the tenets of the Duke Community Standard
in creating this code.
Signed: [md374]
"""
import numpy as np
import matplotlib.pyplot as plt
from chapra_08_16 import rotate_2d
x = np.array([1, 3, 5, 7, 10, 13, ... | true |
a3d976d6c17fb72a85c9d0e8bf42b18880f78a48 | Python | baejinsoo/algorithm_study | /algorithm_study/BOJ/2512.py | UTF-8 | 523 | 3.03125 | 3 | [] | no_license | import sys
input = sys.stdin.readline
n = int(input())
bugets = list(map(int, input().split()))
m = int(input())
bugets.sort()
start = 0
end = bugets[-1]
answer = 0
while start <= end:
mid = (start + end) // 2
res = 0
for buget in bugets:
if buget <= mid:
res += buget
else:
... | true |
b48098e13d148558bd61fdaeac39d32b0545b1fe | Python | ksvulchev/Programing101 | /lecture2/task30.py | UTF-8 | 415 | 3.9375 | 4 | [] | no_license | #!/usr/bin/python
def prepare_meal(number):
meal = ""
while (number % 3 == 0 ):
number /= 3
meal = meal + "spam "
if number % 3 != 0 and number % 5 == 0:
meal = meal + "and "
while (number % 5 == 0 ):
number /= 5
meal = meal + "eggs "
return meal
print (prepare_meal(5))
print (prepare_meal(3))
pri... | true |
aa18ed0975c09046a4392ecaa648b641bfa95de8 | Python | jaekookang/useful_bits | /Machine_Learning/RNN_LSTM/predict_character/seq2seq_char.py | UTF-8 | 2,820 | 3.109375 | 3 | [] | no_license | # Simple character-level prediction using RNN
# 2017-03-30 jkang
#
# 'hello_world_good_morning_see_you_hello_great'
#
# input: 'ello_world_good_morning_see_you_hello_great'
# output: 'hello_world_good_morning_see_you_hello_grea'
#
# Python3.5
# Tensorflow1.0.1
# ref: https://hunkim.github.io/ml/
import tensorflow a... | true |
54d33a62e389170b235026a366be1c13376fe632 | Python | jbd0101/mission-python-uclouvain-bac1 | /mission10/TestXYRobot.py | UTF-8 | 1,270 | 2.9375 | 3 | [] | no_license | #Developpe par jean-christophe bauduin,groupe 11.13
from XYRobot import *
import unittest
import graphics
class TestXYRobot(unittest.TestCase):
def test_position_ini (self):
r2d2 = XYRobot("R2-D2")
self.assertEqual(r2d2.position(), (0,0)), "your robot is not at the required place"
de... | true |
ef3e728c4bbf8c68c90a0baca1f11a413fb7cb63 | Python | omarXzain/data-structures-and-algorithms-401 | /data_structures_and_algorithms/challenges/multi_bracket_validation/multi_bracket_validation.py | UTF-8 | 796 | 4 | 4 | [] | no_license |
def multi_bracket_validation(strings):
arr = []
obj = { '(':')', '[':']', '{':'}' }
for x in strings:
if (x == '(' or x == '{' or x == '['):
arr.append(x)
elif x in obj.values():
if len(arr) == 0:
return False
item = arr.pop()
... | true |
6753afd59a0c3a35bfa2bd837f2b67bbb7c20d77 | Python | shogo82148/JO_RI_bot | /TwitterBot/modules/DateTimeHooks/__init__.py | UTF-8 | 18,077 | 2.78125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
時刻や日付に関するもろもろ
"""
import re
import datetime
import unicodedata
import random
import math
# 漢数字・数字変換
_kanjidigit = u'〇一二三四五六七八九'
_re_kanji = re.compile(u"([" + _kanjidigit + u"])")
_re_kanjijiu1 = re.compile("([" + _kanjidigit + u"])十([" + _kanjidigit + u"])")
_re_kanj... | true |
a6bbd9398cf3e4587c746e2561eae787b4192e50 | Python | jonashaag/voice-gender-classifier | /infer.py | UTF-8 | 1,367 | 2.703125 | 3 | [] | no_license | import numpy as np
import onnxruntime
from lib import CLIP_LENGTH, load_audio, stft
ONNX_FILE = "gender.onnx"
def infer(wav: "(time,)") -> float:
clip_starts = range(0, len(wav), CLIP_LENGTH)
clip_lengths = np.asarray(
[min(CLIP_LENGTH, len(wav) - start) for start in clip_starts]
)
weights =... | true |
2bcba16f6181e9be4900ba1196409b7d2bcbbd0e | Python | AV272/Python | /Tasks/9__Set_functions.py | UTF-8 | 2,120 | 4.3125 | 4 | [] | no_license | '''
Ввод:
3
123
3
pop # удаляет первый элемент множества. Так как множество не упорядочено, неизвестно какой элемент будет удален.
remove 2 # удаляет указанный элемент. Если элемента нет выводит ошибку.
discard 3 # Удаляет указанный элемент. Если элемента нет не выводит ошибку.
Задача:
Записать заданные значения в мно... | true |
5785fb68f48ab6ec44995eb9c64377efde908eeb | Python | ccruz182/Python | /collections/deque.py | UTF-8 | 204 | 3.046875 | 3 | [] | no_license | from collections import deque
def main():
d = deque("cesar")
d.append("1")
print(d)
d.popleft()
print(d)
d.rotate(2)
print(d)
if __name__ == "__main__":
main()
| true |
72c8b2eb305e63bc572709cd8212bfa147fcef05 | Python | abhiskk/pythia | /pythia/tests/utils/preprocessing.py | UTF-8 | 419 | 2.921875 | 3 | [
"BSD-3-Clause"
] | permissive | # Copyright (c) Facebook, Inc. and its affiliates.
import unittest
from pythia.utils.preprocessing import text_tokenize
class TestUtilsPreprocessing(unittest.TestCase):
TOKENS = ["this", "will", "be", "a", "test", "of", "tokens"]
SENTENCE = "This will be a test of tokens?"
def test_text_tokenize(self):
... | true |
9685f5881363ca148bd585872c02a58474a4aedf | Python | dominicle8/cryptopals | /3_22.py | UTF-8 | 588 | 2.78125 | 3 | [] | no_license | import random
import time
cryptopals_3_21 = __import__('3_21')
def main():
time.sleep(random.randint(4, 10))
rand_seed = int(time.time())
print(rand_seed)
target_mt = cryptopals_3_21.MT19937(rand_seed)
time.sleep(random.randint(4, 10))
curr_time = int(time.time())
start_time = curr_time -... | true |