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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
908e51ee6d0de395e4c85e596fb438dff63950c6 | Python | boseutsav/pythonrepo | /tryitertools.py | UTF-8 | 1,385 | 3.625 | 4 | [] | no_license | import itertools
# counter = itertools.cycle([1,2,3])
#
# print(next(counter))
# print(next(counter))
# print(next(counter))
# print(next(counter))
# print(next(counter))
# print(next(counter))
# print(next(counter))
# print(next(counter))
# print(next(counter))
# counter = itertools.count()
# data =[100,200,300,400]... | true |
1ea2a7fb7e062b754603b3f81df017c6f482b159 | Python | darshit-rudani/Pthone-OOP | /51.singal inheritance2.py | UTF-8 | 312 | 3.625 | 4 | [] | no_license | class Student( object ):
def __init__(self , name ,age):
self.name = name
self.age = age
def display(self):
print(self.name)
print(self.age)
class Marks(Student):
def __init__(self,name,age,mark):
self.mark = mark
Student.__init__(self,name,age)
a = Marks("dd",22,100)
a.display()
print(a.mark) | true |
806ec2b5e800aa3b4807aed673d1d2a42486cde4 | Python | bogonets/answer-lambda-cv2-helper | /cv2_helper_cvt_to_rect.app.py | UTF-8 | 570 | 2.53125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import numpy as np
import cv2
import sys
def on_init():
return True
def on_valid():
return True
def on_run(xy: np.ndarray, wh: np.ndarray):
assert len(xy) == 2
assert len(wh) == 2
#sys.stdout.write(f"[cvt to rect] xy {xy}\n")
#sys.stdout.write(f"[cvt to rect] wh {... | true |
05f0a8cbeced6a1ba6c797685813e49fd99a58c0 | Python | arjun-sarath/luminarpythonprograms | /functions/prime_or_not.py | UTF-8 | 294 | 3.765625 | 4 | [] | no_license | def prime(num1):
count = 0
for i in range(1, num1 + 1):
if num1 % i == 0:
count += 1
if count == 2:
return 1
else:
return 0
num = int(input("enter a number: "))
ans = prime(num)
if ans == 1:
print("prime")
else:
print("not prime")
| true |
eb5a61be9ee5c6838301177725afec8b7ae4cfeb | Python | oliverwehrens/openhab-geofency | /generate_passwords.py | UTF-8 | 164 | 2.796875 | 3 | [
"Apache-2.0"
] | permissive | import hashlib
user = "john"
pw = "supersecurepassword"
print("Add the following line to the users.txt\n")
print(f"{user} {hashlib.sha1(pw.encode('utf-8')).hexdigest()}")
| true |
a970e720b4739b39f9209329f8e2ac054ce8b1d4 | Python | oatovar/Cryptopals-Solutions | /c03.py | UTF-8 | 2,129 | 3.46875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | #!/usr/bin/env python3
# Cryptopals Set 1 Challenge 3
import string
# Distribution Statistics: http://www.data-compression.com/english.html
CHARACTER_FREQ = {
'a': 0.0651738, 'b': 0.0124248, 'c': 0.0217339, 'd': 0.0349835, 'e': 0.1041442, 'f': 0.0197881, 'g': 0.0158610,
'h': 0.0492888, 'i': 0.0558094, 'j': ... | true |
d3de051395ab672e2c467ec519febae24722dc3f | Python | Harsimran710/Population-Data-Scrapper-Voice-Assistant- | /Main.py | UTF-8 | 6,207 | 3.171875 | 3 | [] | no_license | import json
import pyttsx3
import re
import requests
import speech_recognition as SR
import threading
import time
API_Key = "Enter Your API Key Here"
Project_Token = "Enter Your Project Tocken Here"
Run_Token = "Enter Your Run Tocken Here"
class Data:
def __init__(self,API_Key,Project_Token):
self.API_Key... | true |
4067dfaaaf9588e8126ff19ff74e7508af172fda | Python | ForgedExistence/FYP_Iteration_1 | /test.py | UTF-8 | 3,088 | 3.0625 | 3 | [] | no_license | import matplotlib.pyplot as plt
from matplotlib import animation
import numpy as np
fig = plt.figure()
ax = plt.axes(xlim=(-300e9, 300e9), ylim=(-300e9, 300e9))
class Body:
solar_sys = []
s_day = 24*60**2
i = 0
def __init__(self, mass, name, velocity, radius):
self.mass = mass
self.n... | true |
b1b08ca13b8f2875d692088e009198c100ec4a7c | Python | seedbook/nlp100 | /1_8.py | UTF-8 | 311 | 3.296875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
#お題の文章
sentence = "I am an NLPer"
#暗号化文章格納用
code = ""
#小文字をasciiコードに変換
for i in sentence:
if 97 <= ord(i) & ord(i) <= 122:
code += str(ord(i))
else:
code += i
#プリント
print code
| true |
de89adae920a848feaa3561a83b902e430157065 | Python | Ragav-Subramanian/My-LeetCode-Submissions | /827. Making A Large Island Python Solution.py | UTF-8 | 1,299 | 2.875 | 3 | [] | no_license | class Solution:
def largestIsland(self, grid: List[List[int]]) -> int:
DIR = [0, 1, 0, -1, 0]
m, n, nextColor = len(grid), len(grid[0]), 2
componentSize = defaultdict(int)
def paint(r,c,color):
if (r<0) or (r>=m) or (c<0) or (c==n) or (grid[r][c]!=1):
retu... | true |
6b87bfe955a0813ea854741ad673632a1cfde68a | Python | p1198528948/python-study | /day01_从键盘读取输入/temperature.py | UTF-8 | 707 | 4.4375 | 4 | [] | no_license | #!/usr/bin/env python3
#
print("将华氏温度转为摄氏温度")
print("公式 C = (F - 32) / 1.8")
# 这里必须是 int
temperature_value = int(input("请输入温度值: "))
fahrenheit = temperature_value
celsius = (fahrenheit - 32) / 1.8 # 转换为摄氏度
# {:5d} 的意思是替换为 5 个字符宽度的整数,宽度不足则使用空格填充。
# {:7.2f}的意思是替换为为7个字符宽度的保留两位的小数,小数点也算一个宽度,宽度不足则使用空格填充。
# 其中7指宽度为7,.2f指... | true |
2f4b9f4db84f5d0e4468099deb9dc9cc8125ba59 | Python | jmy315/time2code | /strong_password/main.py | UTF-8 | 1,071 | 3.40625 | 3 | [] | no_license | """
idea:
1) create four varialbes to track each requirement
2) go through the passowrd char by char
3) check all four variables and return how many more chars are needed
complexity: O(N) where N is the number of chars in password
"""
from absl import app
def main(argv):
print(strong_password(argv[1]))
def stro... | true |
60f3aa3af2bc49ad4af8a375329353a97cf9d989 | Python | Will-So/blackbox_interpretations | /blackbox_interpretations/best_tree.py | UTF-8 | 1,758 | 3.640625 | 4 | [] | no_license | """
Takes an already fitted model with an ensemble of trees and finds the tree
that most closely resembles the results of the overall model.
"""
from sklearn import tree
import graphviz
def get_best_tree(model, X, keep_scores=False):
"""
Given a model of ensembled trees with an `estimators_` attribute,
fi... | true |
226b6f4e74b8ba06f7f844a86bfedacabcc7e47f | Python | elemoine/adventofcode | /2020/day22/part1.py | UTF-8 | 1,191 | 3.546875 | 4 | [] | no_license | import collections
def parse_cards(inputfile):
with open(inputfile) as f:
data = f.read()
player1, player2 = data.split("\n\n")
player1_deck = collections.deque()
for line in player1.splitlines():
try:
v = int(line.strip())
except Exception:
v = None
... | true |
a3ac37f0c97bc72c0be99683c5aeba19ec2f8d40 | Python | lopati/FRED-FrUIT | /FredFrUIT.py | UTF-8 | 8,777 | 3.28125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 27 20:36:53 2016
@author: kliu
"""
# https://github.com/mortada/fredapi (works for Tesla now!)
from fredapi import Fred
# https://research.stlouisfed.org/docs/api/api_key.html (free to use!)
fred = Fred(api_key='d94ebccb76f6251246594b7e1b5ee6cf')
# Matplotli... | true |
3d1be698be9232d1cb0339a1e6dc45a380118a47 | Python | mbencherif/ECE420-Embedded-DSP-LAB | /LAB3/lab3_python/lab3.py | UTF-8 | 1,054 | 2.8125 | 3 | [] | no_license | import numpy as np
import matplotlib.pyplot as plt
from scipy.io.wavfile import read, write
from numpy.fft import fft, ifft
def sig2sq(mag_spec):
return np.log10(np.square(abs(mag_spec)))/20
FRAME_SIZE = 1024
ZP_FACTOR = 2
FFT_SIZE = FRAME_SIZE * ZP_FACTOR
################## YOUR CODE HERE ####################... | true |
e04d1c3eba653082c9ece4466867024b9aa96712 | Python | ThanosAd/CodeWars | /DuplicateEncoder.py | UTF-8 | 595 | 3.4375 | 3 | [] | no_license | # Code for 'Duplicate Encoder' Kata - 6 Kyu
# https://www.codewars.com/kata/54b42f9314d9229fd6000d9c
def duplicate_encode(word):
word1 = word.lower()
Word = list(word1)
counter = 0
current = ""
k = 0
out = ""
for x in range(0, len(Word)):
current = Word[x]
#counter = counte... | true |
4480c4f2f0e9d71fdff204e186b7012c0a306171 | Python | siawyoung/practice | /problems/diameter.py | UTF-8 | 1,063 | 4.125 | 4 | [] | no_license |
# Design an efficient algorithm to compute the diameter of a tree.
# A tree must have a root. The diameter of a tree is the combined length of its 2 longest branches.
# Modified class with any number of children
class TreeNode:
def __init__(self):
self.parent = None
self.children = []
def ad... | true |
89d0ab81643233539fde3239ce897796946f1b98 | Python | aunaik/Machine_Learning | /Decision_Tree_Classifier/Decision_Tree_Classifier.py | UTF-8 | 10,088 | 3.625 | 4 | [] | no_license | #!/usr/bin/env python
#B565: Data Mining
#Author: Akshay Naik
#Description: Implemented the greedy algorithm that learns a classification tree given a data set. The code
#assumes that all features are numerical and properly finds the best threshold for each split. Uses Gini and
#information gain, as specified b... | true |
9f9cb0afff938849f5ad997f434552479c87d44c | Python | dr-neptune/pyoop | /photo_sharer/wiki_images_app.py | UTF-8 | 1,269 | 2.8125 | 3 | [] | no_license | from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
import wikipedia
import requests
# communicate with frontend.kv
Builder.load_file("wiki_frontend.kv")
class FirstScreen(Screen):
def get_image_link(self):
# get user query from text input
... | true |
c55844d8174783c409a56496057df0b980c76f6d | Python | UncommonAvenue/mm-x-ctf | /ocempgui/access/Accessible.py | UTF-8 | 2,778 | 2.5625 | 3 | [] | no_license | # $Id: Accessible.py,v 1.2 2005/08/31 08:17:29 marcusva Exp $
#
# Copyright (c) 2004-2005, Marcus von Appen
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must... | true |
35997602042956b7f9ed837fef6bce53eefc6a1a | Python | abhaysinh/Data-Camp | /Data Analyst with Python Track/01-Introduction to Data Science in Python/02- Loading Data in pandas/05-More column selection mistakes.py | UTF-8 | 1,259 | 4 | 4 | [] | no_license | '''
More column selection mistakes
Another junior detective is examining a DataFrame of Missing Puppy Reports.
He's made some mistakes that cause the code to fail.
The pandas module has been loaded under the alias pd, and the DataFrame is called mpr.
Instructions
100 XP
1 Inspect the DataFrame mpr using info... | true |
b5c7470519e82a727215a9b4e422511f25d7bc7d | Python | Xintong-Brian-Liu/LeetCode | /Array/Easy/53-Maximum-Subarray.py | UTF-8 | 2,439 | 4.09375 | 4 | [] | no_license | '''
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
'''
# Approach 1 Brute Force:
# Since we only need to find the max_sum, not t... | true |
6c343309a08a2fc9a5dd840ae9006a2a97d273b6 | Python | pribanacek/cicadas | /src/plan/RandomAssembler.py | UTF-8 | 2,974 | 3.046875 | 3 | [] | no_license | import networkx as nx
from src.layout.PlannedGraph import PlannedGraph
from src.parser.PathFact import PathFact
from .GraphAssembler import GraphAssembler
def trimPaths(pathA, pathB):
i = 0
j = 0
while pathA[i] == pathB[i]:
i += 1
while pathA[-j - 1] == pathB[-j - 1]:
j += 1
newPat... | true |
e5087e3d0c83c1ebeb7604aaac102e8ff02336f4 | Python | tonnydourado/micromodels | /tests.py | UTF-8 | 22,254 | 2.859375 | 3 | [
"Unlicense"
] | permissive | import datetime
from aniso8601.timezone import parse_timezone
from datetime import date
import decimal
import unittest
import uuid
import micromodels
from micromodels.models import json
class ClassCreationTestCase(unittest.TestCase):
def setUp(self):
class SimpleModel(micromodels.Model):
nam... | true |
2aa8d71beda047e08a4476d6bc0dc0760fa84908 | Python | akstorg/stepik | /1_12_4.py | UTF-8 | 581 | 3.609375 | 4 | [] | no_license | print('')
fig = str(input())
# a = int(input())
if fig == 'круг':
print('enter radius')
r = int(input())
p = 3.14 * r**2
print(p)
if fig == 'треугольник':
print('enter a')
a = int(input())
print('enter b')
b= int(input())
print('enter c')
c = int(input())
p = sum([a, b, c... | true |
8cc560fd7bc3b6bcae0424825dcfd4a326162cc9 | Python | ErikWeisz5/digitalSolutions2020 | /Chapter2/PoundToKilos.py | UTF-8 | 89 | 3.625 | 4 | [] | no_license | p = int(input("Enter the number of Pounds you'd like to convert:"))
print(p * 0.454,"kg") | true |
2fa0ae63286221bf10572b8f0e36a0fb0b98827a | Python | ImmortalHalfWu/StockOrder | /Win32FindWindow.py | UTF-8 | 3,618 | 2.875 | 3 | [] | no_license | # coding=utf-8
import win32con
from pandas import json
import log
from UserInfoBean import SingleUserInfo
import test
from Util import SingleUtil
__author__ = 'Administrator'
__doc__ = '''
pythonwin中win32gui的用法
本文件演如何使用win32gui来遍历系统中所有的顶层窗口,
并遍历所有顶层窗口中的子窗口
'''
import win32gui
from pprint import pprint
def gbk2utf... | true |
2336a73b8b6e5d8c7c82e387ee549a82201a6112 | Python | XDUxuyuting/deep-learning-guide | /RNN_8.py | UTF-8 | 7,207 | 3.25 | 3 | [] | no_license | #循环神经网络模仿二进制减法
#用python写的,没用tf框架
import copy
import numpy as np
#定义sigmoid函数
def sigmoid(x):
output = 1/(1+ np.exp(-x))
return output
#定义sigmoid函数的导数,用于计算梯度下降
#output是sigmoid函数的输出
def sigmoid_output_to_derivative(output):
return output * (1-output)
#定义十进制数转二进制映射
#二进制的位数,这里只计算8位
binary_dim = 8
#8位二进制的最大数... | true |
ec9cb57b6dfcd0dcbc9fcc9765f46e6bf4d774dd | Python | ailin546/pyxuexi | /8.面向对象编程基础/练习1.数字时钟.py | UTF-8 | 1,046 | 3.84375 | 4 | [] | no_license | from time import sleep
import os
class Clock(object):
"""数字时钟"""
def __init__(self,hour=0,month=0,second=0):
"""
:param hour:时
:param month:分
:param second:秒
"""
self.hour = hour
self.month = month
self.second = second
def run(self):
... | true |
515525b9149074618e57fd9e0bfd6cd38e3efa20 | Python | vglmarcos/Simulacion-de-sistemas-en-Python | /P1/R1/caminatav3.py | UTF-8 | 351 | 2.984375 | 3 | [] | no_license | from random import random, randint
from time import time
def caminata(dim, pasos):
tiempo1 = time()
pos = [0] * dim
for t in range(pasos):
cambiar = randint(0, dim - 1)
cambio = 1 if random() < 0.5 else -1
pos[cambiar] += cambio
tiempo2 = time()
tiempo = tiempo2 - tiempo1
... | true |
1797351f50b9275b81f2aa38330c4325c4f3ca9d | Python | come-million/triangulator | /detect2.py | UTF-8 | 7,065 | 2.84375 | 3 | [] | no_license | #!/usr/bin/env python
'''
Detect
===============================
detect detect detect
detect detect detect
detect detect detect
Usage
-----
detect.py [<video_source>]
Keys
----
ESC - exit
SPACE - start tracking
r - toggle RANSAC
'''
# Python 2/3 compatibility
from __future__ import print_function
import... | true |
85383af46efa3b7bc807208917148b2f82e6afda | Python | bonarmada/voxr-api | /app/users/validator.py | UTF-8 | 870 | 2.625 | 3 | [] | no_license | from model import User
def validate(username, password, first_name, last_name, email):
if username is None:
print "Username is required"
return 'Username is required', 400
if password is None:
print "Password is required"
return 'Password is required', 400
if first_name i... | true |
3f77f48f8897bd133f6d6fd4c7a6e0864144ec3d | Python | Aasthaengg/IBMdataset | /Python_codes/p03089/s031605909.py | UTF-8 | 343 | 2.796875 | 3 | [] | no_license | N = int(input())
B = list(map(int, input().split()))
res = []
while len(B) > 0:
p = -1
for i, b in enumerate(B[::-1]):
j = len(B) - i
if b == j:
p = j
break
if p == -1:
print(-1)
exit()
else:
res.append(p)
B.pop(p - 1)
for r in r... | true |
97543e37dd2a3409d05005923140da929812b143 | Python | toddbryant/leetcode | /058_length_of_last_word.py | UTF-8 | 459 | 3.828125 | 4 | [] | no_license | """
Given a string s consisting of words and spaces, return the length of the last word in the string.
A word is a maximal substring consisting of non-space characters only.
"""
class Solution:
def lengthOfLastWord(self, s: str) -> int:
word_length = 0
for i in range(len(s)-1, -1, -1):
... | true |
629fd92b3256b312bddc1a272c7b6a11e9251bac | Python | asadi8/GAN | /chris_experiment/network_helpers.py | UTF-8 | 9,996 | 2.515625 | 3 | [] | no_license | import tensorflow as tf
import numpy as np
#from transformer import transformer
def binarizer(x, num_bits, batch_size):
x_size = x.get_shape()[1].value
w_bin = tf.get_variable('wbin', shape=[x_size, num_bits],
initializer=tf.contrib.layers.xavier_initializer())
b_bin = tf.get_var... | true |
5af4660356b00ade5d0dd54e13533912c562ed5d | Python | ignaciorosso/Practica-diaria---Ejercicios-Python | /Estructura condicional compuesta/condicionalCompuesta2.py | UTF-8 | 787 | 4.75 | 5 | [] | no_license | # Realizar un programa que solicite la carga por teclado de dos números,
# si el primero es mayor al segundo informar su suma y diferencia, en caso contrario
# informar el producto y la división del primero respecto al segundo.
num1 = int(input('Ingrese un numero: '))
num2 = int(input('Ingrese otro numero: '))
... | true |
81a5d735f641f5a8b9b7517d6b0376e1e58e5d60 | Python | martru118/2018-python | /lab_/lab08.py | UTF-8 | 3,049 | 3.765625 | 4 | [] | no_license | class Character():
def __init__(self, name, hp, attackpower, defensepower, magic = 0):
self.name = name
self.hp = hp
self.attackpower = attackpower
self.defensepower = defensepower
self.magic = magic
def isDead(self):
if self.hp <= 0:
return True
... | true |
349bb3d9697eb2d1b8163ae37cb25dee030670c5 | Python | junwon-0313/PythonBasic | /python/ContainerLoop/1.py | UTF-8 | 85 | 3.03125 | 3 | [
"Unlicense"
] | permissive | score=['10','20','30','100점']
i=0
while i<len(score):
print(score[i])
i=i+1 | true |
2ba75b9e22e9dc5584b6fddb8d70736b9283fdfe | Python | kncdw988/DatabaseAccess | /mod_redis/redis_access.py | UTF-8 | 3,670 | 2.53125 | 3 | [] | no_license | import json
import time
from datetime import datetime
import redis
from config import Config
from .utils import RedisDataSerializer
class RedisAccess:
def __init__(self, db=0):
self.pool = redis.ConnectionPool(
host = Config.REDIS_HOST,
port = Config.REDIS_PORT,
db = ... | true |
f94a49d226ddecfd0ec460d9de936241a74d68d3 | Python | daniel-bicu/HWs_CS_degree | /Numerical Calculus/L3/main.py | UTF-8 | 903 | 2.765625 | 3 | [] | no_license | import rare_matrix
import operations
def bonus():
A_Triag = rare_matrix.create_tridiag(f'{dir_path}/bonus_a.txt')
B_Triag = rare_matrix.create_tridiag(f'{dir_path}/bonus_b.txt')
C_Triag = operations.multiply_triag(A_Triag, B_Triag)
print('C_Triag')
operations.display_matrix(C_Triag)
if __name__... | true |
c3e59611e0d79a8ce7d94e838bd79a0ce48e294d | Python | AyoubDaoudia/bootcamp_python_codes | /day00/ex07/filterwords.py | UTF-8 | 1,022 | 3.484375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import string
import sys
def words_pythonest(text,n):
words=[]
c=""
j=0
while text[j].isspace():
j+=1
for i in range(j,len(text)):
if text[i].isalpha():
c+=text[i]
if i==len(text... | true |
3fa73b1966b417063145432a2b2926e6035feec9 | Python | tobyt99/pythoncolt | /repeater.py | UTF-8 | 117 | 3.6875 | 4 | [] | no_license | days = int(input("How many days are you going to work this week? "))
for day in range(days):
print("Go to work") | true |
8c7bf49a5fa58abcd270c9d640e81064ce761276 | Python | joginder-github/hackerrank | /Day-6/10.py | UTF-8 | 105 | 2.578125 | 3 | [] | no_license | N=int(input())
list=list(set(map(int,input().strip().split(" "))))
list.sort(reverse=True)
print(list[1]) | true |
d139769a12b5853f57f9ab1a7a04821e24dce577 | Python | yongjun823/codetesting | /csv_gen/mmmm.py | UTF-8 | 344 | 3.078125 | 3 | [] | no_license | import csv
import random
from tqdm import tqdm
f1 = open('str_note.csv', 'r', encoding='utf-8')
f2 = open('note.csv', 'w', encoding='utf-8')
wr = csv.writer(f2)
rd = csv.reader(f1)
data_arr = []
for ll in tqdm(rd):
data_arr.append(ll)
random.shuffle(data_arr)
for data in tqdm(data_arr):
wr.writerow(data)... | true |
e392097a6c9946f726fe9d81e049de35f8199bfa | Python | diegorafaelvieira/Programacao-1 | /Aula 02/Códigos Professor/SeuNome.py | UTF-8 | 75 | 3.546875 | 4 | [
"MIT"
] | permissive | # YourName.py
nome = input("Qual é o seu nome?\n")
print("Olá, ", nome)
| true |
273b048ec65857891afa1f626f0e6d64e003c486 | Python | jf248/scrape-the-plate | /fixtures/fixtures/csv.py | UTF-8 | 2,719 | 3.265625 | 3 | [
"MIT"
] | permissive | import os
import json
import csv
import ast
class CsvToFixtureFactory(object):
"""
Utility for converting initial data in CSV data into JSON format.
Execute the classmethod create_fixture(path) to create json file in path
from the csv files stored in path/csv/
Do '$ ./fixtures.py [path]' to creat... | true |
f92c471edf1cb258fe57f559ed46d6c66947b0a6 | Python | wiwitrifai/competitive-programming | /hackerearth/july-circuits-19/special-binary-tree.py | UTF-8 | 1,016 | 2.953125 | 3 | [] | no_license | def main():
N = 2 * 10 ** 6
mod = 10 ** 9 + 7
def fact_generator(n):
cur = 1
for i in range(n+1):
if i:
cur = cur * i % mod
yield cur
fact = list(fact_generator(N))
def inv_generator(n):
cur = pow(fact[n], mod-2, mod)
for i in r... | true |
af606331e1aa662f254c1b64a6406946979ffcac | Python | ayazwani/fileconversions-data- | /multiplec2j.py | UTF-8 | 1,184 | 2.671875 | 3 | [] | no_license | """
@author ayaz wani
below is a python progam to convert multiple csv files to aa single json file
"""
import csv,json
import glob
jsonFilePath = 'multiple.json'
data={}
data_folder="csvs"
for filename in glob.iglob(data_folder+"/*.csv"):
with open(filename) as csvf:
csv_reader = csv.DictReader(csvf)
for index... | true |
b729d49dda7fbe0ccac8822ee22cc0a339528143 | Python | fabiomeendes/nanocourses-python | /Cap5_Files/Texts.py | UTF-8 | 137 | 3.4375 | 3 | [] | no_license | text = "Fabio and Luana"
#012345678901234
#543210987654321
print(text[0:5:2])
print(text[10:])
print(text[-5:])
print(text[::-1])
| true |
dc61b472e30369a7e966a019bebbb306732e6ce5 | Python | pazpok/raspberry-domotique | /temperature/hello.py | UTF-8 | 1,431 | 2.75 | 3 | [] | no_license | from flask import Flask
app = Flask(__name__)
from TemperatureSensor import TemperatureSensor
from Led import Led
from flask import render_template
lightr = Led(18)
lightb = Led(24)
pierre = TemperatureSensor()
@app.route('/hello')
def hello_world():
return 'Hello World!'
@app.route('/')
def index():
return ren... | true |
254005280f30b51476412cbcfde9f941cc101756 | Python | alex15964/Python_zerojudge | /a034.py | UTF-8 | 389 | 3.78125 | 4 | [] | no_license | try:
while True:
x = int(input())
if x == 1:
ans = '1'
elif x == 0:
ans = '0'
else:
ans = ''
while x > 1:
ans += str(x % 2)
x = int(x / 2)
if x == 1 or x == 0:
... | true |
7c48101abffec86993b5e890cc81f81d852a3b2f | Python | koxudaxi/pydantic | /docs/examples/validation_decorator_raw_function.py | UTF-8 | 300 | 3.15625 | 3 | [
"MIT"
] | permissive | from pydantic import validate_arguments
@validate_arguments
def repeat(s: str, count: int, *, separator: bytes = b'') -> bytes:
b = s.encode()
return separator.join(b for _ in range(count))
a = repeat('hello', 3)
print(a)
b = repeat.raw_function('good bye', 2, separator=b', ')
print(b)
| true |
2178563c1ed7d0e7759ac3082499e62ed4383d8a | Python | j9rdan/Python-Practice-Exercises | /App Login.py | UTF-8 | 704 | 3.40625 | 3 | [] | no_license |
attempt = 1
success = False
user_list = {
"user1":"password1",
"user2":"password2",
"user3":"password3"
}
# checks attempt <=3 and login isn't successful
while attempt <= 3 and success == False:
username = input("Enter your username: ")
password = input("Enter Your Password: ")
# password is password s... | true |
9ee81c16053917f165d0a315b1a34169407bdc9f | Python | v-lad/Python-Algorithms | /Dijkstra/Dijkstra.py | UTF-8 | 1,774 | 3.109375 | 3 | [] | no_license | from pprint import pprint
import numpy as np
from collections import OrderedDict, deque
class Dijkstra:
def __init__(self, matrix, start, end):
self.matrix = matrix
self.distances = self.direct_pass(start, end, self.matrix)
self.path = self.reverse_pass(start, end, self.matrix, self.distan... | true |
a7f0772391b4c1ab30fb3815fdf3e839b809f7c0 | Python | polyglotm/coding-dojo | /coding-challange/codewars/7kyu/~2021-07-25/simple-fun-152-invite-more-women/simple-fun-152-invite-more-women.py | UTF-8 | 451 | 3.125 | 3 | [] | no_license | """
simple-fun-152-invite-more-women
codewars/7kyu/Simple Fun #152: Invite More Women?
Difficulty: 7kyu
URL: https://www.codewars.com/kata/58acfe4ae0201e1708000075/
"""
def invite_more_women(arr):
return sum(arr) > 0
def test_invite_more_women():
assert invite_more_women([1, -1, 1]) == True
assert invit... | true |
531e5e53217007c08ace5b3d0ad5bb182c1e1331 | Python | thahnen/ias-praktikum | /ias/app/view.py | UTF-8 | 994 | 2.859375 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Zur Erstellung/ Generierung von (Web-)Seiten:
# ============================================
#
# 1. Statische Seite zurückgeben
# => einfach aus Datei einlesen
#
# 2. Alle JS-Templates anfordern
# => einlesen aller(!) Dateien
# => Dictionary mit Dateiname... | true |
7c19c31da8fbfd5da508d4efec1523e5f9456293 | Python | bojinyao/projGroup | /part-1/graph_gen.py | UTF-8 | 2,269 | 3.453125 | 3 | [] | no_license | import networkx as nx
import matplotlib.pyplot as plt
"""
To write gml file use -- nx.write_gml(G, path) <-- path is string literal
To read gml file use -- H = nx.read_gml(path)
To Draw a graph:
ex.
G = nx.generators.random_graphs.gnm_random_graph(300, 100)
nx.draw(G, with_labels=True, font_weight='bold')
plt.show... | true |
8703934b1d8db1db590a40b7cbc7ae22b59c2f93 | Python | nitnelave/advent_of_code_2020 | /15/solution.py | UTF-8 | 543 | 3.453125 | 3 | [] | no_license | #! /usr/bin/env python
numbers = list(map(int, next(open('input')).split(',')))
def compute_turn(numbers, target_turn):
last_mention = [-1] * target_turn
for i, c in enumerate(numbers[:-1]):
last_mention[c] = i
last_number = numbers[-1]
for i in range(len(numbers) - 1, target_turn - 1):
... | true |
5f85572f08e653a20b98eec6666b5c9983e515ce | Python | NicholasAKovacs/SkillsWorkshop2018 | /Week01/Problem02/AChoi_02.py | UTF-8 | 511 | 3.765625 | 4 | [
"BSD-3-Clause"
] | permissive | def fib(x):
#x represents the the number of terms in fibonacci sequence
fibseq = []
for i in range(x):
if i <= 1:
fibseq.append(1)
else:
num = fibseq[i-1]+fibseq[i-2]
fibseq.append(num)
counter = 0
for n in fibseq:
if n %2 == 0 and counter+n < 4000000:
counter = counter + n
if counter+n > 40... | true |
c57c1a2dac596ca77874670379c67e15f264a6f6 | Python | anajarc/Kazino | /igra1.py | UTF-8 | 557 | 3.4375 | 3 | [] | no_license | # coding=utf-8
__author__ = 'ujarc'
attempts = 0
number = 7
while attempts < 3:
guess = raw_input("Ugani stevilko!")
guess = int(guess)
attempts = attempts + 1
if guess < number:
print('Probaj visijo stevilko')
if guess > number:
print('Probaj manjso stevilko')
if guess == ... | true |
9c2b20154111b2de82643e3a6e475742c02faabb | Python | permin/Olymp | /codeforces/268/C/sol.py | UTF-8 | 107 | 2.90625 | 3 | [] | no_license | #!/usr/bin/env python
s = 45 * 18 * 10**17
a = int(raw_input())
s %= a
print (a - s), 10**18 + (a-s) - 1
| true |
3308300e2764d687f8d239351d0f149e935427ca | Python | ikemerrixs/Au2018-Py210B | /students/aminavi/session03/slicing_lab.py | UTF-8 | 1,116 | 3.890625 | 4 | [] | no_license | seq = [4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]
str = "lets do something with this"
# seq
def exchange_first_last(x):
return x[-1:]+ x[1:-1]+ x[:1]
# print(exchange_first_last(str))
assert exchange_first_last(seq) == [21,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,4]
assert exchange_first_last(str) == 'sets ... | true |
3196bf59ca590d0d70836040cdb1c034bd43fc85 | Python | mauricioolarte/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py | UTF-8 | 3,101 | 3.34375 | 3 | [] | no_license | #!/usr/bin/python3
"""this module if for a class base
Attributes:
def __init__: constructor method
"""
from models.base import Base
from models.rectangle import Rectangle
class Square(Rectangle):
""" this a base class
Attributes:
__init__: construct method
to_json_string(list_dictionarie... | true |
408c72cb9c0641e48733921380785f48b07fae3b | Python | bhanubeings/SmartAssistant | /tests/unity_server.py | UTF-8 | 1,599 | 3.46875 | 3 | [] | no_license | #
# Hello World server in Python
# Binds REP socket to tcp://*:5555
# Expects b"Hello" from client, replies with b"World"
#
import zmq
import time
class UnityComm(object):
def __init__(self, Agent):
self.Agent = Agent
context = zmq.Context()
self.socket = context.socket(zmq.REP)
self.sock... | true |
1a4af07b78058b88628bf98fceb72420528dad04 | Python | simonfqy/SimonfqyGitHub | /lintcode/easy/642_moving_average_from_data_stream.py | UTF-8 | 771 | 3.875 | 4 | [] | no_license | '''
Link: https://www.lintcode.com/problem/642/
'''
# My own solution. Simple, using Python deque. The optimization of keeping a local total_sum field ensures that the next()
# function has O(1) time complexity, no O(size).
from collections import deque
class MovingAverage(object):
"""
@param: size: An integer... | true |
9ef4f3f13a0f655729235cb6540d2c66eea110ca | Python | ryantpayton/Swordie | /scripts/portal/blackHeaven_boss.py | UTF-8 | 1,277 | 2.546875 | 3 | [
"MIT"
] | permissive | # Lotus entry NPC
# mode, req level, map, death count
destinations = [
["Normal", 210, 350060700, 5], # p2 350060800 | p3 350060900
["Hard", 235, 350060400, 5], # p2 350060500 | p3 350060600
]
def is_party_eligible(reqlevel, party):
# TODO: check prequest
for member in party.getMembers():
if member.getLevel() ... | true |
9409c09b42c026592b2921a35614b52f0a3a2d5a | Python | vivianna1/spider_learning | /test/spider.py | UTF-8 | 1,203 | 2.609375 | 3 | [] | no_license | import requests
import json
from bs4 import BeautifulSoup
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362'}
def start_request(url):
response = requests.get(url,headers=headers)
soup = BeautifulSoup(... | true |
ce7fa348851e1e6c67773f1620e18e9a18da74b2 | Python | AdamZhouSE/pythonHomework | /Code/CodeRecords/2299/60832/316933.py | UTF-8 | 2,147 | 3.625 | 4 | [] | no_license | class BinaryNode:
def __init__(self, e: chr):
self.element = e
self.left = None
self.right = None
def add_BST_recursion(r: BinaryNode, e: chr):
if r is not None:
if e < r.element:
add_BST_recursion(r.left, e)
elif e > r.element:
add_BST_recursion... | true |
8a75d986105ee9e50eecbdf588c4ef155e9976f1 | Python | vnatesh/Code_Eval_Solutions | /Easy/armstrong_numbers.py | UTF-8 | 711 | 4.09375 | 4 | [] | no_license | """
ARMSTRONG NUMBERS
CHALLENGE DESCRIPTION:
An Armstrong number is an n-digit number that is equal to the sum of the n'th powers of its digits. Determine if the input numbers are Armstrong numbers.
INPUT SAMPLE:
Your program should accept as its first argument a path to a filename. Each line in this file has a p... | true |
81348ef53e2e72fcb792890b9ad62501bd99bda8 | Python | egaban/Uri | /matematica/1722.py | UTF-8 | 317 | 3.5625 | 4 | [] | no_license | fib = []
fib.append(1)
fib.append(2)
for i in range(498):
fib.append(fib[i]+fib[i+1])
while True:
a, b = map(int, input().split())
if (a == b == 0):
break
comeco = 0
fim = 499
while fib[comeco] < a:
comeco += 1
while fib[fim] > b:
fim -= 1
print(fim-comeco+1) | true |
ec1bd40eb567903a344808654c181b931a44d20d | Python | bhumikav07/Cuisine-Culture | /resizer.py | UTF-8 | 430 | 2.703125 | 3 | [] | no_license | import os
import cv2
for images in os.listdir('static/images'):
img = cv2.imread('static/images/'+images, cv2.IMREAD_UNCHANGED)
scale_percent = 60 # percent of original size
width = int(img.shape[1] * scale_percent / 100)
height = int(img.shape[0] * scale_percent / 100)
dim = (width, height)
re... | true |
a446d21494608866845cece92b5ce598ade33608 | Python | JoeBugajski/python-examples | /Chapter 3/types-boolean.py | UTF-8 | 325 | 3.625 | 4 | [] | permissive | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
# x = True
# x = 7 < 8
x = None
print('x is {}'.format(x))
print(type(x))
# None evaluates as False
# 0 evaluates as False
# Empty string '' evaluates as false
# Pretty much anything else will evaluate as True
if x:
print("True")
else:
print("Fa... | true |
6f1fe3b218c7b4eed429468fe16f7ef730b8c459 | Python | webclinic017/stocks-9 | /stocks/etrade_watchlist.py | UTF-8 | 1,922 | 2.546875 | 3 | [] | no_license | #!/usr/bin/env python
import subprocess
import click
import stocks
import sys
WATCHLISTS = {'watchlist': 'watching portfolio', 'canopy': 'canopy', 'chinese': 'Chinese', 'largecap': 'largecap', 'vgvcr': 'vgvcr', 'vgvdc': 'vgvdc', 'vgvgt': 'vgvgt', 'midcap': 'midcap', 'smallcap': 'smallcap', 'cyber': 'cyber', 'david':... | true |
92421f914eb22d9d2d13b8588d88459d1aab6e50 | Python | vishrutdixit/projecteuler | /p18.py | UTF-8 | 1,011 | 3.109375 | 3 | [] | no_license | '''
pyramid maximum path sum
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53... | true |
c1a5b887452711a2715ec4474724dd9728744efe | Python | iamanobject/Lv-568.2.PythonCore | /HW_4/ruslanliska/Kata_3.py | UTF-8 | 180 | 4.0625 | 4 | [] | no_license | def greet(name):
if name == "Johnny":
return "Hello, my love"
else:
return f"Hello, {name}"
greet_name = input("Enter yout name: ")
print(greet(greet_name)) | true |
7786eb6b316755b4207572976bf93dab756733c4 | Python | abhilal007/SoftwareEngineeringProject | /sql.py | UTF-8 | 1,433 | 3.203125 | 3 | [] | no_license | import MySQLdb as my
import json
class DumpToSQL:
db = None
def __init__(self):
with open('local_settings.json') as jsonfile:
data = json.load(jsonfile)
host = data['host']
username = data['user']
password = data['password']
database = data['... | true |
068bd178fbda757e788e9a533f08e2a52b887f17 | Python | Design-comb/EZ_combustor_calculator | /EZ_calculator.py | UTF-8 | 17,720 | 2.59375 | 3 | [] | no_license | import os
import tkinter
from tkinter import *
def resource_path(relative_path):
try:
base_path = sys_MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
import tkinter as tk
from tkinter import ttk
import math
import P... | true |
71a47a6370c6440ea68059d6c376c5e143e03ed0 | Python | p2c2e/icici_irr | /Orders.py | UTF-8 | 4,017 | 2.578125 | 3 | [] | no_license |
# coding: utf-8
# In[82]:
import csv
import numpy as np
import pandas as pd
from dateutil.parser import parse
import datetime
import glob
import numpy as np
from scipy.optimize import fsolve
from datetime import date
portfolio_file_name = "XXXXXXXXXX_PortFolioMF.xls"
def load_xls_files(path='.',... | true |
877a5f6a9708042754579e5057d19b18018862e4 | Python | bryonkucharski/robot-catcher | /python_scripts/vision/video/live/discretize_vid_live.py | UTF-8 | 802 | 2.609375 | 3 | [] | no_license | import cv2
import numpy as np
import collections
import sys
import time
sys.path.append("../../") #go back to vision folder
import discretize_vision as v
# Capture from webcam
#1 for usb webcam
#0 for integrated webcam
cap = cv2.VideoCapture(1)
scale_factor = 1
first_frame = True
grid_dim = (5, 8)
# Enumerations to... | true |
7eff98a94b1c71fe878955fad1d909dbae3e61f1 | Python | eginwong/coding-bat-scratch-pad | /python/warmup-1/near_hundred.py | UTF-8 | 240 | 3.84375 | 4 | [] | no_license | # Given an int n, return true if it is within 10 of 100 or 200. Note: Math.abs(num) computes the absolute value of a number.
def near_hundred(n):
if n > 100-11 and n < 100+11 or n > 200-11 and n < 200 + 11:
return True
return False | true |
2d471ff65d337fb56267632eeed8305f0e69ab9a | Python | expectopatronum/pytorch-lightning | /pytorch_lightning/logging/tensorboard.py | UTF-8 | 4,470 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | import os
from warnings import warn
from argparse import Namespace
from pkg_resources import parse_version
import torch
import pandas as pd
from torch.utils.tensorboard import SummaryWriter
from .base import LightningLoggerBase, rank_zero_only
class TensorBoardLogger(LightningLoggerBase):
r"""
Log to local... | true |
52311b56c4d50f68b73c5dc207dbaeb1f72c20c9 | Python | proformatique/algo | /tp11/huffman.py | UTF-8 | 1,978 | 2.953125 | 3 | [] | no_license | from queue import PriorityQueue
def double(d, f):
if f - d > 4:
return [d, d+1, double(d+2, f-2), f-1, f]
else:
return [d, d+1, f-1, f]
def recto(livret):
if len(livret) > 4:
pages = [livret[1]] + [livret[3]]
pages += recto(livret[2])
else:
page... | true |
1eab2ffa81b6913f992a33f9eeb9f3463d385428 | Python | SaraRayne/Commerce | /commerce/auctions/util.py | UTF-8 | 727 | 2.734375 | 3 | [] | no_license | from .models import User, Listing, Bid, Watchlist
from decimal import *
def find_bid(listing_id):
"""
Returns highest bid for given listing
"""
all_bids = list(Bid.objects.filter(listing=listing_id))
bid_list = []
for i in range(len(all_bids)):
bid_list.append(all_bids[i].amount)
if... | true |
1f9290711cd0f69247e36fc88da8a7c3335540e7 | Python | Karma-Cat/coursera_last_case | /run.py | UTF-8 | 658 | 2.59375 | 3 | [] | no_license | #!/usr/bin/env python3
import requests
import os
path = "/supplier-data/descriptions/"
dataKeys = ['name', 'weight', 'description', 'image_name']
files = os.listdir("path")
for file in files:
dataDict = {}
with open(path+file, 'r') as file_r:
lines = file_r.readlines()
weight = int(lines[1].spli... | true |
b2b0fc271310bdc727229f2fa8c39347a04b5ec9 | Python | zcx1218029121/suck_crawler_collection | /src/main/coroutines.py | UTF-8 | 3,680 | 2.578125 | 3 | [] | no_license | import queue
import time
import requests
import threading
from bs4 import BeautifulSoup
import re
flag = True
g_num = 5
mutex = threading.Lock()
header = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
"Connection": "keep-a... | true |
9ccb4f5c7d127768e1e655c5dfc1dd98c552cdda | Python | shen-huang/selfteaching-python-camp | /exercises/1901010076/1001S02E06_stats_word.py | UTF-8 | 1,935 | 4.34375 | 4 | [] | no_license | #作者:邓超
#作业:封装’按照字母降序统计英文词频‘的函数
def stats_text_en(text): #定义一个函数
text = text.replace('.', '').replace(',','').replace('*','').replace('-','')
text = text.split() #转换成列表 #去除标点符号
import collections
m=collections.Counter(text) #遍历排序
return (m)
#示例:
a =... | true |
b128b5190aa4d625b817d5a4dd5b5ab1ec42adf4 | Python | sjs7007/randomStuff | /pd/part5.py | UTF-8 | 2,446 | 3.65625 | 4 | [] | no_license | # program portion to calculate probability that active user is of same personality types as some other user
import math #for exponent
import csv #for reading csb database
def readDB(allUsers,fileName):
for i in range (2,32):
temp=[]
with open(fileName, 'rb') as f:
reader = csv.reader(f)
f... | true |
fd6a4a0eaa3f929c002211d0c2bdef06ce704344 | Python | pvsr/CS470-EP | /generator.py | UTF-8 | 1,537 | 2.90625 | 3 | [] | no_license | import random
import sys
import argparse
import itertools
parser = argparse.ArgumentParser(description="generate a random votefile")
parser.add_argument("-c, --num_cands", metavar="N", type=int,
dest="cands", default=6, help="number of candidates, default 6")
parser.add_argument("-m, --min_votes", ... | true |
92e40bf54ebd51d09e8d3a98bae068fe4630606c | Python | eeach520/XiDan | /Geometry/Triangle.py | UTF-8 | 2,643 | 2.828125 | 3 | [] | no_license | from .Point import Point
from .Line import Line
from .Vector import Vector
from .LineSegment import LineSegment
class Triangle:
def __init__(self, A: Point, B: Point, C: Point, index, is_entrance=False, eva_dir=None, near_index=-1,
min_eva_dis=9999999, bA=False, bB=False, bC=False):
if ev... | true |
92606a13b6888228a896262657710d427b4da0fc | Python | inwk6312fall2019/wordplay-Chintan1491 | /9.3.py | UTF-8 | 359 | 3.671875 | 4 | [] | no_license | #prog 9.3
def avoids(word,forbidden):
for letter in word:
if letter in forbidden:
return False
return True
fin = open('words.txt')
count = 0
forbidden_letters = input('Enter any forbidden letters: ')
for line in fin:
word = line.strip()
if avoids(word, forbidden_letters) == ... | true |
97b733348faf85fba3c837f2df3dda1a6b8d9566 | Python | Zjoris/NLPmodels | /RNN/RNN.py | UTF-8 | 9,644 | 3.203125 | 3 | [] | no_license | '''
This file contains an implementation of a Recurrent Neural Network
built from scratch using numpy, ... etc
This site was very helpful:
https://d2l.ai/chapter_recurrent-neural-networks/bptt.html
Notes to self or to do list:
- implement backpropagation
- Implement deep hidden layer (weight initialization)... | true |
4befc7df5d0fd869d91d427f4ed6a044a3a6aae8 | Python | gri201/LSTM_Instagram | /train.py | UTF-8 | 4,924 | 2.75 | 3 | [] | no_license | import pandas as pd
import numpy as np
import pickle
import csv
import pymorphy2
import re
import matplotlib.pyplot as plt
import keras.utils
from keras.preprocessing import sequence
from keras.preprocessing.text import Tokenizer
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activati... | true |
ffb9debf37ce9e98fffb12c51246cb933282fb9c | Python | anmol/algorithm_python | /tree/tree_serde.py | UTF-8 | 2,308 | 3.53125 | 4 | [] | no_license | #!/usr/bin/env python2.7
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
... | true |
8765b72033402efc0d95c5307d12bf517b461e0c | Python | zhyordanova/Python-Basics | /03-Conditional-Statements-Advanced/Exercise/08_on_time_for the_exam.py | UTF-8 | 835 | 3.703125 | 4 | [] | no_license | exam_hour = int(input())
exam_minute = int(input())
arrive_hour = int(input())
arrive_minute = int(input())
exam_in_minutes = (exam_hour * 60) + exam_minute
arrive_in_minutes = (arrive_hour * 60) + arrive_minute
diff = exam_in_minutes - arrive_in_minutes
if diff < 0:
print("Late")
hours = abs(diff) // 60
... | true |
17ef2921241a8f8ad6007170b8cb0494ee549d66 | Python | touranisatyajit/mlp | /train.py | UTF-8 | 4,135 | 2.546875 | 3 | [] | no_license | import torch
import torchvision
import random
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.metrics import classification_report
device = 'cuda'
#hyper parameters
input_size = 2
output_size = 1
hl1_size = 600
h... | true |
fddce85076ee3db19877c018fc1676f88359856b | Python | MaciejWasilewski/PythonUdemyCourse | /Section_12/Lecture_128/enemy.py | UTF-8 | 1,850 | 3.75 | 4 | [] | no_license | import random
class Enemy(object):
def __init__(self, name="Enemy", hit_points=0, lives=1):
self._name = name
self._hit_points = hit_points
self._lives = lives
self._alive = True
self._points = self._hit_points
def take_damage(self, damage):
remaining_points = ... | true |
8ae3675c1ecb18349048867edd011d9a44bb31bb | Python | Handsomewl/Rubik-Cube-Robot | /CVdetection/color_feature.py | UTF-8 | 2,709 | 3.265625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
'''
颜色特征识别
'''
import numpy as np
import cv2
def color_block_finder(img, LowUp_range, all_rects, min_w=0, max_w=None, min_h=0, max_h=None):
'''
->img_binary, rects
色块识别 返回二值化图像,矩形信息
'''
# 转换色彩空间 HSV
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# 根据颜色阈值转换为二值化图像
... | true |
0148f0cbbcbf97d9aa84e1e12f848c08d42204f8 | Python | athenaaw/shenshan_python | /logging/src/logging_sample_1.py | UTF-8 | 386 | 2.703125 | 3 | [
"Apache-2.0"
] | permissive | import logging
logger = logging.Logger("sample_1_logger")
file_handler = logging.FileHandler("sample_1.log")
file_handler.setLevel(logging.INFO)
formatter = logging.Formatter("Timestamp:%(asctime)s Line number: %(lineno)d Information:%(message)s ")
file_handler.setFormatter(formatter)
logger.addHandler(file_handl... | true |
ba2a6f9a42e42a572e302eea57dab5effe355568 | Python | namnamgit/pythonProjects | /miles2km.py | UTF-8 | 88 | 2.984375 | 3 | [] | no_license | def miles2km():
miles = int( input('Milhas: '))
km = miles * 1609
print(km)
input()
| true |