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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
a5c742d776a4aab4a6bcc0269ffc8da6315efb93 | Python | Yian-Kim/Python-Programming-Study | /PythonTest/src/ex19.py | UTF-8 | 845 | 2.90625 | 3 | [] | no_license | # ex19.py
import cx_Oracle as oci
conn = oci.connect('hr/java1234@localhost:1522/xe')
cursor = conn.cursor()
# 단일값
sql = 'select count(*) from tblMemo'
# result = cursor.execute(sql)
# print(result)
cursor.execute(sql)
result = cursor.fetchone(); # rs.next() -> rs.getXXX()
print(result[0])
# 단일값&다중값 -> DTO 반환
sql ... | true |
c6c7e60c4071c5c918e8a749be4c0a23eab4b6d7 | Python | michael21910/zerojudge | /Basic Question Bank/a003/a003.py | UTF-8 | 191 | 3.1875 | 3 | [
"MIT"
] | permissive | num_list = [eval(x) for x in input().split(' ')]
target = (num_list[0] * 2 + num_list[1]) % 3
if target == 0:
print("普通")
elif target == 1:
print("吉")
else:
print("大吉") | true |
a2ee68a54cabe0b76facd0d437a2fe5aa2cddd02 | Python | muzi-ux/complete_python | /test/t2.py | UTF-8 | 652 | 4.09375 | 4 | [] | no_license | # def fibonacci(i):
# if i == 2 or i == 1:
# return 1
# return fibonacci(i - 2) + fibonacci(i - 1)
#
#
# print(fibonacci(20))
# lis = []
# for i in range(25):
# lis.append(50 + i + 1)
#
# print(lis)
# print(len(lis))
# print(sum(lis))
# def my_sum(m, b):
# return m + b
#
#
# def sum1(z, n):
... | true |
3441502571b4d5b7e35482038c0fda1eb6251bf7 | Python | Luiza-Teixeira/Desafio-curso-em-video | /desafio 031.py | UTF-8 | 249 | 3.78125 | 4 | [] | no_license | distancia = float(input('Digite o valor em Km da distância que será percorrida:\n'))
if distancia <= 200:
print('O valor da passagem é:\n {}'.format(distancia*0.50))
else:
print('O valor da passagem é:\n {}'.format(distancia*0.45))
| true |
a2f49c3c92a0cf9d5a4041af71a5d821e49b0394 | Python | arjunsridhar9720/simple-captcha-solver-Python--master | /breakcaptcha.py | UTF-8 | 1,422 | 2.859375 | 3 | [] | no_license | #!/usr/bin/python
# [PoC] tesseract OCR script - tuned for scr.im captcha
#
# Chris John Riley
# blog.c22.cc
# contact [AT] c22 [DOT] cc
# 12/10/2010
# Version: 1.0
#
# Changelog
# 0.1> Initial version taken from Andreas Riancho's \
# example script (bonsai-sec.com)
# 1.0> Altered to use Python-tesse... | true |
940df09e445fedb7eb337ef162d2307fcb1c64f3 | Python | szyymek/Python | /Valid_Parentheses.py | UTF-8 | 372 | 3.625 | 4 | [] | no_license | def valid_parentheses(string):
kontrola=0
for znak in string:
if kontrola<0:
return False
elif znak=="(":
kontrola+=1
elif znak==")":
kontrola-=1
else:
continue
if kontrola==0:
return True
else:
return False
... | true |
f74f73a1fde36e2a7b5bbf9f5eb20373bc5dac93 | Python | hiyounger/sdet05_demo | /yuanhongxu/test4.py | UTF-8 | 335 | 3.046875 | 3 | [] | no_license | #coding:utf-8
kehus=[
{"id":"1","tel":"18812344321","zhekou":"9"},
{"id":"2","tel":"18812344322","zhekou":"8"},
{"id":"3","tel":"18812344323","zhekou":"9.8"}
]
tel="18812344321"
for i in kehus:
if i["tel"]==tel:
print(i["zhekou"])
kehus.append({"id":"4","tel":"18812344324","zhekou":"8"})
prin... | true |
9291aa9a406eeff811c6826237e9878a2f1d81dd | Python | bukexiusi/jzzn | /_python/basic/0-练习/杀死进程.py | UTF-8 | 1,039 | 2.75 | 3 | [] | no_license | # -*- coding: utf-8 -*-
'''
@Time : 2019/8/15 10:57
@Author : 图南
@Email : 935281275@qq.com
@File : 杀死进程.py
@Description : 判断进程是否存在和杀进程
'''
from subprocess import run
import win32com.client
def processExist(processName):
try:
WMI = win32com.client.GetObject('winmgmts:')
processCodeCov = W... | true |
dc18e40e0936723095c865efb3f747533847ca17 | Python | srflp/MTS | /MTS/Domain.py | UTF-8 | 965 | 3.328125 | 3 | [] | no_license | from .notation import notation
class Domain: # dziedzina
def __init__(self, inp=None, mode='normal'):
self.domain = set()
if inp is None:
inp = set()
if mode == 'normal':
self.domain = inp
elif mode == 'rpn': # generowanie dziedziny z inputu
i... | true |
8a26e7780cb3bb897f417ea3668fb6e721dbbb8b | Python | fetchai/agents-aea | /tests/test_docs/helper.py | UTF-8 | 8,612 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | # -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2023 Fetch.AI Limited
#
# 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 ... | true |
df60943aadad6096ae1e1345a1193152331487b1 | Python | hardingnj/anhima | /anhima/dist.py | UTF-8 | 3,548 | 3.15625 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
"""
Genetic distance calculations.
See also the examples at:
- http://nbviewer.ipython.org/github/alimanfoo/anhima/blob/master/examples/dist.ipynb
""" # noqa
from __future__ import division, print_function, absolute_import
# third party dependencies
import numpy as np
import scipy.spatia... | true |
4facb5c0e88ec18afb6e5174717f8c9fdc479344 | Python | DaneRosa/WebMap | /map.py | UTF-8 | 1,414 | 2.8125 | 3 | [] | no_license | import folium
import pandas
data = pandas.read_csv("volcanoes_usa.txt")
lat = list(data["LAT"])
lon = list(data["LON"])
elev = list(data["ELEV"])
print("hello world")
#new machine test
def color_pro(elevation): #this will allow the elevation dictate color of the markers
if elevation < 1000:
return 'gree... | true |
cb896e4740b73a11d5037eb82321490c17d284e1 | Python | jedzej/tietopythontraining-basic | /students/frequency_analisis.py | UTF-8 | 489 | 3.203125 | 3 | [] | no_license | all_words = {}
words = []
for i in range(int(input())):
words = input().split()
for item in words:
all_words.setdefault(item, 0)
all_words[item] += 1
all_words_list = [(count, word) for (word, count) in all_words.items()]
new_dict = {}
for pair in all_words.items():
new_dict.setdefault(p... | true |
9de58b2127fea91264a84bf8c3b62679c0e1db31 | Python | knipknap/exscript | /Exscript/interpreter/scope.py | UTF-8 | 3,776 | 2.6875 | 3 | [
"MIT"
] | permissive | #
# Copyright (C) 2010-2017 Samuel Abels
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy,... | true |
5f35675176be57dcdab55b546f372315a571762a | Python | lorosanu/xi-ml-topicdiscovery | /python/lib/xi/ml/classify/load_classifier.py | UTF-8 | 3,842 | 2.8125 | 3 | [
"MIT"
] | permissive | # -*-coding:utf-8 -*
import pickle
import numpy
from xi.ml.common import Component
from xi.ml.tools import utils
from xi.ml.error import CaughtException
from xi.ml.corpus import StreamCorpus, PushCorpus
class LoadClassifier(Component):
"""
Class used to load classification models
and to predict class an... | true |
9e84a13e338b2c1e535525a94f05fc8dfca3aba4 | Python | noonzib/myStudy | /python/pythonChallenge/level4.py | UTF-8 | 368 | 2.9375 | 3 | [] | no_license | import requests
url = 'http://www.pythonchallenge.com/pc/def/linkedlist.php'
first = "16046"
for i in range(1,400):
params = {'nothing' : first}
response = requests.get(url,params=params)
print(response.text)
ret = response.text
print([int(s) for s in ret.split() if s.isdigit()][0])
first =... | true |
018f475184b5710582f576eda972e607b664e0da | Python | shreyasabharwal/IMT-575 | /3. MapReduce/ShreyaSabharwal-p4_asymmetricfriendships.py | UTF-8 | 794 | 3.1875 | 3 | [] | no_license | import MapReduce
import sys
"""
Word Count Example in the Simple Python MapReduce Framework
"""
mr = MapReduce.MapReduce()
# =============================
# Do not modify above this line
def mapper(record):
persona = record[0] # record[0]: Person
friend = record[1] # record[1]: Friend
mr.emit_interme... | true |
df526c813809369c9df75bfc6ae07cc95f6a0f44 | Python | jungmannlab/picasso | /picasso/imageprocess.py | UTF-8 | 3,907 | 2.703125 | 3 | [
"MIT"
] | permissive | """
picasso/imageprocess
~~~~~~~~~~~~~~~~~~~~
Image processing functions
:author: Joerg Schnitzbauer, 2016
:copyright: Copyright (c) 2016 Jungmann Lab, MPI of Biochemistry
"""
import matplotlib.pyplot as _plt
import numpy as _np
from numpy import fft as _fft
import lmfit as _lmfit
from tqdm import... | true |
97e9888cd7a7afc6b509d02230a1a4e793bcb3ae | Python | snkohail/GraphEmbed | /NodeEmbed.py | UTF-8 | 4,378 | 2.8125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a Node Embedding Based on Matrix Factorization Algorithm
"""
from __future__ import print_function
import collections
import math
import numpy as np
import os
import random
import tensorflow as tf
import networkx as nx
import matplotlib as plt
import zipfile
from matp... | true |
c76aa54fc49d0be4f1b955b53ce7a3008384a2c0 | Python | rtibell/TimeLogger | /python/src/SensorTest-V1.py | UTF-8 | 346 | 2.765625 | 3 | [] | no_license | import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
#GPIO.setmode(GPIO.BOARD)
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN) #Read output from PIR motion sensor
GPIO.setup(22, GPIO.OUT)
for i in range(1,100):
time.sleep(0.5)
sens = GPIO.input(17)
if sens == 1:
print "found item"
elif sens == 0:
... | true |
bfc14360868c8a4793a62ed51e72617ea5a6460a | Python | nevilpatel/flask_project | /test/test_flask_utest.py | UTF-8 | 617 | 2.828125 | 3 | [] | no_license | import unittest
import thermos.thermos as thermos
class UTestCase(unittest.TestCase):
""" Flask provides a framework for testing.
1. Import app and set testing to true.
2. Get the test_client
3. Work with test client to drive the routes
"""
def setUp(self):
thermos.app.t... | true |
c26a8cd9fab8bd6fb0633cb553631fe8ec3e6441 | Python | saurabhpati/python.beginner | /OOP/base_employee.py | UTF-8 | 627 | 3.78125 | 4 | [
"MIT"
] | permissive | class BaseEmployee():
"The base class for an employee."
# Note: Unlike c#, on initiliazing a child class, the base contructor is not called
# unless specifically called.
def __init__(self, id, city):
"Constructor for the base employee class."
print('Base constructor called.');
s... | true |
4d08491b0a231597fb08b810a347a262b0499bac | Python | vshrotriya/Android-Automation-using-Appium | /file_1.py | UTF-8 | 12,801 | 2.5625 | 3 | [
"MIT"
] | permissive | import sys
import csv
import hashlib
import os
import glob
import unittest
from time import sleep
from appium import webdriver
import subprocess
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
email = ''... | true |
326cf1dda309faa30fb21deb6c51e37dfd605d88 | Python | hafidid-baha/python_tkinter | /textInput.py | UTF-8 | 675 | 3.625 | 4 | [] | no_license | from tkinter import *
# create the root window
root = Tk()
root.title("learn python with tkinter")
root.iconbitmap('E:/Programming Projects/python/tinker/img/spider.ico')
# create text input to catch data from users
e = Entry(root, width=20, bg="#eee", fg="black")
e.pack()
# put default text
e.insert(0, "enter your na... | true |
a5a54c6575d4bff127be7a798b2784e7a622c204 | Python | PdxCodeGuild/class_mudpuppy | /Assignments/Manny/Python/lab10.py | UTF-8 | 466 | 4.125 | 4 | [] | no_license | nums = [5, 0, 8, 3, 4, 1, 6] # the starting array of nums
running_sum = 0 #to start need an int of 0 to be able to add
for num in nums:# looping through the list
running_sum = running_sum + num #when looping we are adding and changing out runningsum var ex: 5+runningsum which = 0 will change running sum to 5
... | true |
6e143608a03a3d386a1ddacbec8fa342e76d6ce8 | Python | masterkikoman/PythonBasics | /OOPConcepts/OOPConcepts.py | UTF-8 | 512 | 4.28125 | 4 | [] | no_license | # classes are user defined blueprint or prototype
# will have methods, class variables, instance variables, constructor etc.
# declaring class in Python
class Calculator:
num = 100
# declaring method in class
def getData(self):
print("I am now executing as method in class")
# creating object i... | true |
c10c29eeb7dcce0b501724faecf982722f8cd0ee | Python | OrdinaryCoder00/CODE-WARS-PROBLEMS-SOLUTIONS | /8Kyu - Check the exam.py | UTF-8 | 305 | 2.71875 | 3 | [] | no_license | def check_exam(arr1,arr2):
score = 0
i = 0
while(i<len(arr1)):
if(arr2[i]!=""):
if(arr1[i]==arr2[i]):
score = score + 4
else:
score = score - 1
i = i + 1
if score>0:
return score
else:
return 0
| true |
b926f3155bc1b6679ac3265b467283844cc648a8 | Python | MichalxPZ/AiSD | /LinkedList BST AVL/run.py | UTF-8 | 4,861 | 2.515625 | 3 | [] | no_license | from random import randint
import os
RANGES = [50, 100, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000]
STRUCTS = {"LinkedList": "LinkedList", "BST": "BST", "AVL": "AVL"}
def rosnace():
for struct in STRUCTS.keys():
f = open("txt/result.txt", "w")
f.write("")
... | true |
0ee230d2076b8dfd58bf5475eaf2b466e67da0ab | Python | renji01/learning_python | /junior_spider-master/09-MySQL/topics.py | UTF-8 | 1,965 | 2.859375 | 3 | [] | no_license | from lxml import etree
import re
import requests
from mysql_manager import MysqlManager
mysql_mgr = MysqlManager(4)
class TopicsCrawler:
domain = 'https://www.newsmth.net'
def get_content(self, board_url, page):
querystring = {"ajax":"","p":str(page)}
url = self.domain + board_url
r... | true |
779c896e375e27dc90cd82585c5852d1961aa06e | Python | antoniawang/epicurious | /epicurious_url.py | UTF-8 | 2,442 | 2.671875 | 3 | [] | no_license | import urllib2
import re
from bs4 import BeautifulSoup
#http://www.epicurious.com/tools/searchresults/all?search=ramos%20gin%20fizz&pageNumber=2&pageSize=10&resultOffset=11
search_base_url = "http://www.epicurious.com/tools/searchresults/all?search="
search_term = "Ramos Gin Fizz"
search_suffix = "&pageSize=1000"
star... | true |
434296a55e19fcb9006042faf6c67aa3a77824e3 | Python | plee-lmco/python-algorithm-and-data-structure | /leetcode/101_Symmetric_Tree.py | UTF-8 | 1,535 | 4.25 | 4 | [
"MIT"
] | permissive | # 101. Symmetric Tree (Easy)
# Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
#
# For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
#
# 1
# / \
# 2 2
# / \ / \
# 3 4 4 3
# But the following [1,2,2,null,3,null,3] is not:
# 1
# / \
# 2 2
#... | true |
524ad87241300d5236a79960e64c29fc9d1c49a4 | Python | maharr/adventcode19 | /1/fuelmass.py | UTF-8 | 287 | 2.96875 | 3 | [] | no_license | import os
f = open("mass.txt","r")
all=0
def fuel(m):
global all
f = (m//3)-2
all = all + f
if f > 6:
fuel(f)
return all
total = 0
for x in f:
mass = int(x)
f = fuel(mass)
total = total + f
all = 0
print(total)
f.close()
| true |
b0bdd90994b892a8fe18a4f385ec578d302aeeeb | Python | xuedong/leet-code | /Problems/Algorithms/97. Interleaving String/interleaving_string.py | UTF-8 | 733 | 3.1875 | 3 | [
"MIT"
] | permissive | class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
l1, l2, l3 = len(s1), len(s2), len(s3)
if l3 != l1 + l2:
return False
dp = [[False for _ in range(l2+1)] for _ in range(l1+1)]
for i in range(l1+1):
for j in range(l2+1):
... | true |
2eb57b1fe42d33dc86fa7f26242fe6a4ab18383b | Python | penguinleo/Julian | /Julian.py | UTF-8 | 644 | 3.015625 | 3 | [] | no_license | def Julian(Date):
# Date = {"year":2018,"month":12,"day":29,"hour":19,"minute":16,"second":00,"ms":0}
print(Date)
year = Date["year"]
month = Date["month"]
day = Date["day"]
hour = Date["hour"]
minute = Date["minute"]
second = Date["second"]
ms = Date["ms"... | true |
b53f5cae3cfe8274adf37910bc936ffc3e5948b8 | Python | zwnong/HogwartsSDE17_HomeWork | /utils/dos_cmd.py | UTF-8 | 578 | 2.5625 | 3 | [] | no_license | # coding utf-8
import os
class DosCmd:
# 获取设备信息
def excute_cmd_result(self, command):
result = os.popen(command).readlines()
result_list = []
for i in result:
if i == '\n':
continue
result_list.append(i.strip('\n'))
return result_list
... | true |
666b8b04aa7a50c1e3140929bc39696034acc09d | Python | marat92d/Portfolio | /примеры моего кода на python/durak.py | UTF-8 | 2,242 | 4.0625 | 4 | [] | no_license | value=['6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] #в список записываем все значения карт по возрастанию
first,second=input().split() #читаем две карты
suit=input() #читаем козырную масть
if first[-1]==second[-1]: #если масти двух карт равны
if value.index(first[0:-1])>value.index(second[0:-1]): #то сравнием ... | true |
703ea838bdc5700790640496d4c0f746917b2ff2 | Python | chulhee23/BaekJoon_Online_Judge | /11700~11799/11726.py | UTF-8 | 557 | 3.796875 | 4 | [] | no_license |
# 문제
# 2×n 크기의 직사각형을 1×2, 2×1 타일로 채우는 방법의 수를 구하는 프로그램을 작성하시오.
# 아래 그림은 2×5 크기의 직사각형을 채운 한 가지 방법의 예이다.
#
# 입력
# 첫째 줄에 n이 주어진다. (1 ≤ n ≤ 1,000)
#
# 출력
# 첫째 줄에 2×n 크기의 직사각형을 채우는 방법의 수를 10,007로 나눈 나머지를 출력한다.
dp = [i for i in range(1001)]
N = int(input())
for i in range(3, N + 1):
dp[i] = (dp[i - 2] + dp[i - 1]) % ... | true |
12bee4815c19a4f42ea6a2f6e5ee0ead7bf67e8e | Python | kensugino/jGEM | /jgem/taskqueue.py | UTF-8 | 8,770 | 2.578125 | 3 | [
"MIT"
] | permissive | """
.. module:: taskqueue
:synopsis: multiprocessor stuffs
.. moduleauthor:: Ken Sugino <ken.sugino@gmail.com>
"""
import multiprocessing
from multiprocessing import TimeoutError
try:
from Queue import Empty, Full
except:
from queue import Empty, Full
import time
import traceback
import logging
loggi... | true |
47c6dbbad9316965a6fd7a5d87c7c9eff86ceeab | Python | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_95/1932.py | UTF-8 | 680 | 3.15625 | 3 | [] | no_license | T = int(input())
slownik = {'q': 'z', 'y': 'a', 'e': 'o', 'z': 'q'}
templates = [("ejp mysljylc kd kxveddknmc re jsicpdrysi",
"our language is impossible to understand"),
("rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd",
"there are twenty six factorial possibilities"),
... | true |
db748e69cdb19b273e2fad57256d6df709db8040 | Python | trupalukani/alarm-clock-python | /project.py | UTF-8 | 1,235 | 3.390625 | 3 | [] | no_license | from playsound import playsound
from tkinter import *
from win10toast import ToastNotifier
import datetime
import time
def alarm(set_alarm):
toast = ToastNotifier()
while True:
time.sleep(1)
date = datetime.datetime.now()
now = date.strftime("%H:%M:%S")
print(now)
... | true |
26c0673e139d424ec629eeeb6ca038acdb100b44 | Python | shen-weiran/discrete_fpa_bne | /fpa_bne.py | UTF-8 | 21,930 | 3.015625 | 3 | [
"MIT"
] | permissive |
import math
import numpy as np
from scipy import optimize
from scipy import integrate
import collections
State = collections.namedtuple('State', 'is_active remaining_prob cur_bid cur_value_idx')
class Strategy:
def __init__(self):
self.start_points = []
self.end_points = []
... | true |
462c83c280131866a6bdc784d54bfd7bddb561c4 | Python | uunicorn/pyWeatherLink | /rose/rose.py | UTF-8 | 2,880 | 2.921875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
from PIL import Image, ImageDraw, ImageShow, ImagePath
from math import ceil
from planar import Vec2, Affine
Image.init()
def vec2tuple(v):
return (v.x, v.y)
class Rose(object):
def __init__(self):
size=(400, 400)
rose_radius=170
self.fatness = 5
tran... | true |
cdc496138e2226121bf80bb400ce2ca1b38783b7 | Python | aleemolinal/LSTM-for-trajectory-planning-mobile-robot | /ObstacleController.py | UTF-8 | 1,034 | 3.03125 | 3 | [] | no_license | #! /usr/bin/env python
# Import libraries and messaging
import time
import rospy
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Point, Twist
# Declare variables
x = 0.0
y = 0.0
# Create function to get the position x,y of the dynamic obstacle (tb3_1)
def newOdom (msg):
global x
global y
x = msg.... | true |
64096fcbce9fa2897e22eecbe7a899dc7227c4da | Python | mconwa20/sqlalchemy-challenge | /app.py | UTF-8 | 4,637 | 2.6875 | 3 | [] | no_license | import numpy as np
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
#################################################
# Database Setup
#################################################
engi... | true |
8a7500e24da28bf7da9a97ba3b9eb24ca5e3668e | Python | L1nwatch/leetcode-python | /821.字符的最短距离.py | UTF-8 | 699 | 3.171875 | 3 | [] | no_license | #
# @lc app=leetcode.cn id=821 lang=python3
#
# [821] 字符的最短距离
#
# @lc code=start
class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
last_e_index = -1
length = len(s)
answer = list()
for i in range(length):
if s[i] != c and last_e_index == -1:
... | true |
529b43dd3cacfe45f7357375b8bdb057b83092b2 | Python | Alvin2580du/alvin_py | /start code/routes.py | UTF-8 | 7,785 | 2.625 | 3 | [] | no_license | from flask import render_template, request, redirect, url_for, abort
from flask_login import login_required, current_user
from server import app, system, auth_manager
from datetime import datetime
from src.Location import Location
from src.CarFactory import CarFactory
from src.Booking import BookingError
@app.route(... | true |
c85bb9e123c03a608d1ccd14fe45ffd9e5064c90 | Python | AmrHRAbdeen/Python | /TrackPhoneLoc/main.py | UTF-8 | 818 | 3.203125 | 3 | [] | no_license | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
### Get info about a specific phone number
### Needed Packages ###
### pip install phonenumbers
import phonenumbers
from p... | true |
b7acab7a47a27e08ee394b19603df44d69856569 | Python | vlifanoff/CodewarsKata | /8_kyu/keep_up_the_hoop.py | UTF-8 | 233 | 3.125 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Keep up the hoop: https://www.codewars.com/kata/55cb632c1a5d7b3ad0000145"""
def hoopCount(n):
return "Keep at it until you get it" if n < 10 else "Great, now move on to tricks"
| true |
b02e98a4f82751dd491c7470996767aec889b7da | Python | Ricpalo/Resolving-Python-Problems | /19.py | UTF-8 | 276 | 4 | 4 | [] | no_license | # Display the multiplication table from 1 to 12
for i in range(1, 13):
for j in range(1, 11):
print(i, '*', j, '=', i * j)
print()
i = 1
while i <= 12:
j = 1
while j <= 10:
print(i, '*', j, '=', i * j)
j += 1
print()
i += 1 | true |
74906834b38374a73837c704af215f98449167bb | Python | shashankvemuri/covid19-data | /US_testingRate.py | UTF-8 | 917 | 3.0625 | 3 | [] | no_license | import pandas as pd
import matplotlib.pyplot as plt
import datetime
from pylab import rcParams
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
n = 30 #the number of days of data you wish to see
daily_us = pd.read_json('https://covidtracking.com/api/v1/us/daily.json')
daily_us = ... | true |
d451dcfb6a82cfd47ee842bcb130732d5515de13 | Python | harveylabis/GTx_CS1301 | /codes/CHAPTER_3/Chapter_3.5_Error_Handling/Extra_Course_Practice/PullCapitals.py | UTF-8 | 1,158 | 4.4375 | 4 | [] | no_license | #Write a function called get_capitals. get_capitals should
#accept one parameter, a string. It should return a string
#containing only the capital letters from the original
#string: no lower-case letters, numbers, punctuation marks,
#or spaces.
#
#Remember, capital letters have ordinal numbers between 65
#("A") and 90 ... | true |
990670010c82e86b4bf7cae55e3f02845cc7a96d | Python | deltahalo099/physics-251 | /hw4 - curvefit/hw4_2.py | UTF-8 | 437 | 2.78125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 3 23:04:00 2020
@author: Omar Abdelaal
"""
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
sindata = 'data/sinusoidal_data.csv'
data_set = np.genfromtxt(sindata, delimiter=',')
time = data_set[:, 0]
volts = data_set[:, 1]
plt.p... | true |
dc87eb156944852c3d73beda0911b4bdf0e1101a | Python | mathsman5133/Aussie-Warriors-Bot | /cogs/utils/one_time_setup.py | UTF-8 | 2,534 | 2.78125 | 3 | [
"MIT"
] | permissive | #Does not close the cursor or
import os
import csv
excel_path = os.path.join(os.getcwd(), 'cogs', 'utils', 'Sidekick_Data.csv')
async def oneTimeSetup(coc,connection, coc_token):
'''This only needs to be run one time, it'll create all the tables and populate them with values'''
#Create a cursor & define Tag
... | true |
c8bf935f79044266f3c3cc7c16fac10abf910e44 | Python | sanketwadekar3/Machine-Learning | /Wine Predictor/Wine_Predictor.py | UTF-8 | 931 | 3.25 | 3 | [] | no_license | import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import StandardScaler
def KNNaccuracy(n):
dataset = pd.read_csv('WinePredictor.csv')
data = dataset.iloc[:,1:13]
... | true |
3eb26110e80dd85bec487ec00760512d39f69d86 | Python | spyfire14/FootballAnalysis | /Club/Club_Loader.py | UTF-8 | 2,044 | 2.578125 | 3 | [] | no_license | import requests
from bs4 import BeautifulSoup
import re
import Stadium
import Manager
def main(website):
res = requests.get(Website, headers={'User-Agent': 'Mozilla/5.0'})
content = BeautifulSoup(res.content, 'lxml')
#Team Name#
for HTMLDiv in content.find_all(class_="dataName"):
for HTMLH1 ... | true |
ba2eedd0fcd794a7ee5d498b3909365eea3bfc42 | Python | marmst10/Python-Examples | /Quadratic Solver.py | UTF-8 | 1,213 | 4.15625 | 4 | [] | no_license | #!/usr/bin/env python
# coding: utf-8
# In[14]:
# 2. (6 pts) Create a function that solves the zeros of a quadratic
# equation (note that there are 3 possible outcomes, when finding the real
# zeros of a quadratic equation so your function must be able to handle
# all 3, properly).
import math
def quadratic(a, ... | true |
8d8f7d5557e794c8d2070c86f2d7c410bf43c7e8 | Python | Jonasori/N-Body-Simulator | /run_driver.py | UTF-8 | 956 | 3.28125 | 3 | [] | no_license | """Set up and execute an n-body simulation.
Exoplanets Final Project: N-Body Simulation
@author: Jonas Powell
October 2017
"If you just have a stupid sense of humor,
you'll never run out of things to laugh at."
- Ryan's UBinghamton friend Eli
"The larger our ignorance, the stronger the magnetic field."
- Woltier
"""... | true |
d0d648f86c5a960b46c95af2dcaa37c9d161b0cc | Python | zbay/linear-algebra | /VectorQuizzes/DotProduct/vector-ops.py | UTF-8 | 517 | 3.59375 | 4 | [] | no_license | from vector import Vector
#question 1
vector1 = Vector([7.887, 4.138])
vector2 = Vector([-8.802, 6.776])
print vector1.dot_product(vector2)
#question 2
vector3 = Vector([-5.955, -4.904, -1.874])
vector4 = Vector([-4.496, -8.755, 7.103])
print vector3.dot_product(vector4)
#question 3
vector5 = Vector([3.183, -7.627])... | true |
99cbfb5fcee81d56888d1c7201ad6a868ada8348 | Python | Datawheel/slc-industry-space | /lib/ps_calcs/ps_calcs/complexity.py | UTF-8 | 849 | 2.921875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
''' Import statements '''
import sys
import numpy as np
def complexity(rcas, drop=True):
rcas_clone = rcas.copy()
# drop columns / rows only if completely nan
rcas_clone = rcas_clone.dropna(how="all")
rcas_clone = rcas_clone.dropna(how="all", axis=1)
if rcas_clone.shape != r... | true |
692131771236ee7837162fbedb6a3733c21e8fbf | Python | xxi511/tf_practive | /3.cifar10/test.py | UTF-8 | 70 | 3.046875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
x = [1, 2, 3]
sq = [a**2 for a in x]
print sq | true |
15091b574b490b8d30417fbb47ecb7f7e192ff80 | Python | greatmindsinside/KidsGame | /KidsGame/KidsGame.py | UTF-8 | 16,477 | 2.921875 | 3 | [] | no_license | # Game Created by Lawson
import pygame
import random
import os
from os import path
#-------------------------------
# define colors used in the game
#-------------------------------
white = (255,255,255)
black = (0,0,0)
red = (255, 0, 0)
green = (0,255,0)
blue = (0,0,255)
yellow = (255,255,0)
width = 480
height = 6... | true |
ca7d9deea887d9cf840dbb53ae63f07735746adb | Python | scarlettlite/hackathon | /Tree/ClosestLeaf.py | UTF-8 | 1,071 | 3.71875 | 4 | [] | no_license | """
The idea here is to create a graph from a tree and then do a BFS on the
given node
"""
from collections import defaultdict, deque
class Solution:
def creategraph(self, root, parent, graph):
if parent and root:
graph[parent.val].append(root)
graph[root.val].append(parent)
... | true |
7d8de8fc4bcafd6e5bdfe44efb00d8cc189faeac | Python | hakimmaina510/IDT-Master-Project | /masterymod7.py | UTF-8 | 9,530 | 2.8125 | 3 | [] | no_license | '''
Name: Rohit Nachaloor
Date Submitted: 05/01/2019
Mastery Project
Period: 1
Cowart
'''
import mysql.connector as SQL
from smtplib import *
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
def mail():
dbGrade = SQL... | true |
254697076cfb6ecb27b21d4267d5650e084a5a66 | Python | mahinsagotra/Python | /Itertools/combinations.py | UTF-8 | 207 | 3.46875 | 3 | [] | no_license | from itertools import combinations, combinations_with_replacement
a = [1, 2, 3]
comb = combinations(a, 2) # length mandatory
print(list(comb))
comb = combinations_with_replacement(a, 2)
print(list(comb))
| true |
e9f5dc22d956ea33a3b6f30aaa0a9ab40d3adc18 | Python | Martbov/gevpro-week3 | /spontal_filter.py | UTF-8 | 616 | 2.5625 | 3 | [] | no_license | #!usr/bin/python3.4
import sys
import xml.etree.ElementTree as ET
def main(argv):
"""" Filters wrong data from an XML file """
spontalXML = open((argv[1]), 'r')
tree = ET.parse(spontalXML)
spontalXML.close()
root = tree.getroot()
for point in root:
f0_start = float(point.find('F0_START').text)
f0_end = ... | true |
8134e8e190bb874389f45bda05e1b110fa05cc6d | Python | SoumyaMalgonde/AlgoBook | /python/sorting/Heap Sort.py | UTF-8 | 641 | 3.6875 | 4 | [
"MIT"
] | permissive | # Code for heap sort in Python
def heapify(arr, n , i):
root = i #root
l = 2*i+1 #left child
r = 2*i+2 #right child
if(l<n and arr[i] < arr[l]):
root = l
if(r<n and arr[root] < arr[r]):
root = r
if(root!=i):
arr[i], arr[root] = arr[root], arr[i]
heapify(arr, n, root)
def sort(arr, n):
#Buil... | true |
0e2199a514bb56e055ef450a7aea9a0f8415d3b0 | Python | abdibogor/The-Bad-Tutorial | /05_Python/35_User Defined Functions/user.py | UTF-8 | 572 | 3.625 | 4 | [] | no_license | """
def sample(text):
usample("Hello World!")
"""
"""
def sample():
print("I will print the no matter what!")
return
sample()
"""
"""
def calculator(a,b):
print("Addition:", a+b)
print("Subtraction:", a-b)
print("Multiplication", a*b)
print("Division:", a/b)
return
calculator(155,25)
"""
... | true |
3ef1c44868a6f7c22e88eba3092754029f931afc | Python | htnani/PFB2018_problemsets | /problemsets/trinity/script2.py | UTF-8 | 804 | 2.953125 | 3 | [] | no_license | #!usr/bin/env python3
# this script calculates the number of reads per one gene froma .sam file
import sys
import re
filename = sys.argv[1]
file_sam = open(filename, 'r')
gene_dict = {}
for line in file_sam:
line_list = (line.split('\t'))
transcript_name = line_list[2]
gene = re.search(r'(.+)\^(.+)', trans... | true |
103686498ed03a8ad42e95ca0614ed58def04319 | Python | shreevatsa/misc-math | /chakrabandha.py | UTF-8 | 3,561 | 3.4375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Python program for generating SVGs like these:
https://commons.wikimedia.org/wiki/File:Magha-chakrabandha-iast.svg
https://commons.wikimedia.org/wiki/File:Magha-chakrabandha-devanagari.svg
I seem to have lost the program with which I generated the above, so rewriting from scratch.
For now,... | true |
81f71e4364c0f0416ca888b836bbe3ef50e9ee81 | Python | auron95/briscola-bot | /views.py | UTF-8 | 448 | 2.84375 | 3 | [] | no_license | class View:
def redirect(self,user,session=None):
user.view = self.__class__.__name__
session.add(user)
def get_input(self,user,text):
if text in self.ITA_OPTIONS:
self.ITA_OPTIONS[text](user)
def __init__(self, user, bot)
self.user = user
self.bot = bot
class MainMenu(View):
ITA = 'Menu` princi... | true |
6ae1f8445831de74a54fcb342387215e21ecf9f4 | Python | novotny1akub/py_oop | /OOP_pyladies.py | UTF-8 | 2,890 | 3.796875 | 4 | [] | no_license | # základní vlastnost objektů je to, že obsahují jak data (informace), tak chování – instrukce nebo metody, které s těmito daty pracují
# data každého objektu jsou specifická pro konkrétní objekt
# metody – bývají společné pro všechny objekty daného typu
# společné chování určuje typ (angl. type) neboli třída (angl. cla... | true |
3e4864d212474b6854fce519e544f41b0cce7baf | Python | TUIlmenauAMS/Python-Audio-Coder | /optimfuncMDCT.py | UTF-8 | 2,219 | 2.875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Program for optimizing an MDCT type filter bank with N subbands.
Gerald Schuller, July 2018
"""
def optimfuncMDCT(x, N):
"""Computes the error function for the filter bank optimization
for coefficients x, a 1-d array, N: Number of subbands"""
import numpy as np
... | true |
a281f9497b5f70ab7a3596fb0d77598fdc7acbf9 | Python | Gliganu/CarND-Behavioral-Cloning-P3 | /drive.py | UTF-8 | 4,690 | 2.671875 | 3 | [] | no_license | import numpy as np
import os
import pandas as pd
import PIL
import PIL.Image
from sklearn.utils import shuffle
from matplotlib import pyplot as plt
from keras.models import Sequential, Model
from keras.layers import Input, merge, Activation
from keras.layers.core import Flatten, Dense, Dropout, Lambda
from keras.layer... | true |
d11fbef7943b4ab30735dacb531d5ed9a1c08106 | Python | statickidz/TemarioDAM | /ACTIVIDADES/eclipse-projects/Actividad23/src/Actividad23/Actividad23Main.py | UTF-8 | 474 | 3.53125 | 4 | [] | no_license | # -*- coding: utf-8 -*-
import Actividad23inc
from time import localtime
print "La hora local es %2d:%.2d" % (localtime().tm_hour, localtime().tm_min) #no es necesario el paquete
c = 'N'
while c != 'S':
Actividad23inc.printMenu() #obligatorio el nombre del paquete
c = raw_input("¿Opción?").upper()
if c!... | true |
6760f754d33d0a85af9eb33d37335e13f0ec0bee | Python | Anwarvic/Dan-Jurafsky--Chris-Manning--NLP | /06-CKY/CMPN463 HW06 Data/python/ling/Trees.py | UTF-8 | 14,006 | 3.1875 | 3 | [] | no_license | from Tree import Tree
# TODO: should I replace rendering of tree.label to str(tree.label)??
##################
# Class Methods
##################
ROOT_LABEL = "ROOT"
class TreeTransformer:
"""
Abstract base class for different Tree transformation classes.
"""
@classmethod
def transform_tree(cls,... | true |
5f120ab0564ea50518ea23ee105d111e3b23f5c9 | Python | mijara/postcrypt | /handlers/log_handler.py | UTF-8 | 393 | 2.671875 | 3 | [] | no_license | from services.context import Context
from handlers.handler import Handler
from services.logger import Logger
class LogHandler(Handler):
logger: Logger
context: Context
def handle(self, statement):
text = self.context.render_with_headers(statement.text)
text = text.replace(''', '"')
... | true |
445a0889db212a25f1ed302dec3b012960dd0f4b | Python | luokeychen/blog | /utils/slugify.py | UTF-8 | 919 | 2.609375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
# __author__ = chenchiyuan
from __future__ import division, unicode_literals, print_function
import unicodedata
from pypinyin import lazy_pinyin
try:
from django.utils.encoding import smart_unicode as smart_text
except ImportError:
from django.utils.encoding import smart_text
def sl... | true |
91882abb89c56e292c9e2d113c01b4853d0ffe6b | Python | kunal768/Interviewbit | /Dynamic Programming/Best Time to Buy and Sell Stocks II.py | UTF-8 | 235 | 3.046875 | 3 | [] | no_license | class Solution:
# @param A : tuple of integers
# @return an integer
def maxProfit(self, A):
n = len(A)
profit = 0
for i in range(1,n):
profit += max(A[i]-A[i-1],0)
return profit
| true |
2ccc026c604df47cd51b294931f48acab318d77c | Python | scl2589/Algorithm_problem_solving | /SWEA/3809_화섭이의정수나열/3809.py | UTF-8 | 602 | 3.109375 | 3 | [] | no_license | import math
T = int(input())
for tc in range(1, T+1):
N = int(input())
cards = []
while len(cards)!=N:
cards.extend(input().split())
i = 0
this_number = True
while this_number:
#찾아야 될 숫자 string으로 변환
strings = list(str(i))
for a in range(len(cards)):
i... | true |
8e932b8438cf0f18abc3c247652de419a3d918ce | Python | kalicia106/AlumniPythonClass | /HW6A.py | UTF-8 | 308 | 3.53125 | 4 | [] | no_license | #Write a code that prints out 15 most frequent words from the file words.txt.
import collections
#The re module provides regular expression matching operations
import re
words = re.findall(r'\w+', open('text.txt').read().lower())
most_common = collections.Counter(words).most_common(15)
print(most_common)
| true |
e979ac90c13cbc1934e853353338241db0dd5ea6 | Python | mswift42/project-euler | /euler22.py | UTF-8 | 471 | 3.203125 | 3 | [] | no_license | with open('names.txt', 'r+') as f:
read_data = f.read()
read_data = sorted(read_data.split(','))
def ordvalue(character):
return ord(character) - 64
def getsum(ind):
sum = 0
for i in read_data[ind]:
for j in i:
if ordvalue(j) >=0:
sum += ordvalue(j)
... | true |
dc89e61e3dd8142556a4b5e19c76f0d68c1f7c51 | Python | userbai7888/kai | /网络编程/UDP网络编程/udp_server.py | UTF-8 | 497 | 3.28125 | 3 | [] | no_license | import socket
#创建socket套接字
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
#绑定地址和端口
s.bind(('localhost',8080))
print('信息传输中......')
#全循环
while True:
#接受客户端发来的请求,发一个数据和地址
data,addr=s.recvfrom(1024)
#打印请求的数据并把它解码出来
print('白:',data.decode())
data=input('余:')
#发送给客户端的数据,并且编码
s.se... | true |
02a43c7983110c70c5ad9244fd3b4d6ad906377b | Python | emmas0507/lintcode | /implement_stack_by_two_queue.py | UTF-8 | 1,376 | 3.765625 | 4 | [] | no_license | class Queue(object):
def __init__(self):
self.q = []
def push(self, value):
self.q = self.q + [value]
def size(self):
return len(self.q)
def empty(self):
return len(self.q) == 0
def pop(self):
if not self.empty():
x = self.q[0]
self... | true |
c41b165788ea447e50993ea4337b05ae83b0bf2b | Python | jeffmacinnes/pyneal | /src/GUIs/pynealDashboard/pynealDashboard.py | UTF-8 | 8,085 | 3.15625 | 3 | [
"MIT",
"LicenseRef-scancode-free-unknown"
] | permissive | """ Web server to host the Pyneal Dashboard
Flask-based App to host the backend of the Pyneal Dashboard for monitoring a
real-time scan.
In addition to providing a web server that hosts the dashboard, this tool will
listen for interprocess communication messages sent from the main Pyneal
processes, which it will pars... | true |
572e95a85c257a601c161dbeeb94d069623d6b5e | Python | FelipeGrueso/imput-processing | /Input processing v2.py | UTF-8 | 680 | 3.46875 | 3 | [] | no_license |
triadas = {"000":[0,0], "001":[0,0], "010":[0,0], "011":[0,0], "100":[0,0], "101":[0,0], "110":[0,0], "111":[0,0]}
cadena = "01011"
cantidad_triadas = len(cadena) -2
print ("longitud de la cadena", len(cadena))
print("triadas", cantidad_triadas)
i= 0
while i < len(cadena) - cantidad_triadas :
print(cade... | true |
dfd2616d44ee9b4b57904bc707b5ac7f2cbe8b39 | Python | LoganDavenport/TagPro-Clone | /client.py | UTF-8 | 3,977 | 2.6875 | 3 | [] | no_license | from tkinter import *
import socket, pickle, packet, time, gc
class Client:
def __init__(self):
self.initUI()
self.state = 0
self.i = 0
self.sock = None
self.root.after(1, self.loop)
self.root.mainloop()
def initUI(self):
self.root = Tk()
se... | true |
19bcf39eb8a3a5842d3449f5108a5e4ef8bf25dc | Python | hollyhockberry/track-location | /webapi/user/crud.py | UTF-8 | 1,228 | 2.546875 | 3 | [
"MIT"
] | permissive | # user/crud.py - CRUD functions
# Copyright (c) 2021 Inaba
# This software is released under the MIT License.
# http://opensource.org/licenses/mit-license.php
from sqlalchemy.orm import Session
from sqlalchemy.exc import NoResultFound
from . import model, schemas
def create(db: Session, id: str, data: schemas.UserCr... | true |
e3fa9720a161204da2d03d97b2d424ea1a038b15 | Python | Pressio/pressio-tools | /pressiotools/io/array_read.py | UTF-8 | 1,249 | 2.546875 | 3 | [
"BSD-3-Clause"
] | permissive |
import numpy as np
import math
from pressiotools import linalg as la
def read_binary_array(fileName, nCols):
# read a numpy array from a binary file "fileName"
if nCols==1:
return np.fromfile(fileName)
else:
array = np.fromfile(fileName)
nRows = int(len(array) / float(nCols))
return array.reshap... | true |
970e6ad19f7237c2fe755e16609c56872db91a14 | Python | alexandervpetrov/rosalind | /algo/17-DIJ/heap_test.py | UTF-8 | 1,097 | 3.171875 | 3 | [] | no_license |
import pytest
import heap
def test1():
h = heap.BinaryMinHeap()
h.insert("a", 1)
h.insert("b", 0)
h.insert("c", 2)
h["d"] = 3
assert len(h) == 4
assert 'a' in h
assert 'z' not in h
assert h['a'] == 1
with pytest.raises(KeyError):
h["z"]
with pytest.raises(KeyErr... | true |
f9db7030f5dc06f20a4a54e07be5b080a949ea55 | Python | euggo/meetup | /talks/to_err_is_human/code/e_typd/typd.py | UTF-8 | 400 | 3.546875 | 4 | [] | no_license | #!/usr/bin/env python3
def content(num):
# BGN OMIT
try:
n = int(num)
except ValueError:
return "The value is not an integer."
except TypeError:
return "How about no."
except:
return "The value is wack, yo."
# END OMIT
return "The integer is " + str(n) + "."... | true |
875b6d9527a0230b7a10568295b370807ccf03c1 | Python | girouxa/MachineLearning | /backProp.py | UTF-8 | 2,453 | 2.921875 | 3 | [] | no_license | import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def randMat (d1,d2):
return (2 * np.random.random_sample((d1,d2)) - 1)
def randVect(d1):
return np.array(np.random.randint(5,size=(d1)))
def randVecMat(num, dims):
a = []
for i in range(num-1):
a.appe... | true |
ddf17469f27960ed0a2eca1dc5bc6013e6d505d9 | Python | iamgeniuswei/python | /blockchian/blockchain.py | UTF-8 | 3,220 | 3.25 | 3 | [] | no_license |
import time
import random
import hashlib
class BlockChain(object):
def __init__(self, hash_num):
self.chain_list = []
self.result_list = []
self.gen_block(hash_num)
def get_last_block(self):
if len(self.chain_list):
return self.chain_list[-1]
return None... | true |
28dcbb9a4205a6ff55e36ba8d18b8dcb3216ca05 | Python | Buzz627/AdventOfCode | /2017/day17/day17.py | UTF-8 | 295 | 2.640625 | 3 | [] | no_license | mem=[0]
steps=382
num=1
pos=0
while num<=50000000:
pos=(pos+steps)%num
# print pos
# mem.insert(pos,num)
# print mem
pos+=1
if pos==1:
print num
print pos
# print len(mem)
# print num
# print mem[0]
# print pos
# print ""
num+=1
# print mem[0]
# print mem[mem.index(2017)+1]
| true |
449ff20ad3bad877a7d305945afb1e1bcc4a3c92 | Python | eazow/leetcode | /575_distribute_candies.py | UTF-8 | 357 | 3.078125 | 3 | [] | no_license | class Solution(object):
def distributeCandies(self, candies):
"""
:type candies: List[int]
:rtype: int
"""
return min(len(candies)/2, len(set(candies)))
assert Solution().distributeCandies([1,1,2,2,3,3]) == 3
assert Solution().distributeCandies([1,1,2,3]) == 2
assert Solutio... | true |
ffe7f5cf94d23b4eba1ece5826537fb4b5c77453 | Python | ihokamura/make_ends_meet | /data_manager.py | UTF-8 | 6,796 | 2.734375 | 3 | [] | no_license | """
manage data
"""
from collections import namedtuple
import csv
import datetime
from shutil import copyfile
# translation mapping
GROUP_MAIN_TRANSLATION_TABLE = {
'収入':'income',
'社会保障':'social security',
'住宅':'housing',
'生活基盤':'infrastructure',
'通信':'communication',
'交通':'transportation',
... | true |
8f46bc651377dde19acb64692ab11f4f6a1041b7 | Python | aleferna2001/useful_scripts | /generate_gameboard.py | UTF-8 | 394 | 3.171875 | 3 | [] | no_license | from ascii_art import print_hello
print_hello("making your own game board")
a=' ---'
b='| '
c="|"
size=input("How big do you want your game board? Use commas to tell x and y apart (x,y): ")
size2=size.split(',')
x=int(size2[0])
y=int(size2[1])
with open('gameboard.txt','w') as file:
for i in range(y):
fil... | true |
8166a7d8df49407d4c1e45107f33130db8059f80 | Python | Anwar91-TechKnow/PythonPractice-Set1 | /if_Statments.py | UTF-8 | 468 | 4.46875 | 4 | [] | no_license | #Puython if statement
'''
if it's hot
it's a hot day
drink plenty of water
Otherwise if it's cold
it's a cold day
wear warm clothes
otherwise
it's a lovely day
'''
import time
is_hot=False
is_cold=False
if is_hot:
print("it's a hot day")
print("drink plenty of water")
time.sleep(5)
elif is_cold:
... | true |
60072017fa9bb2fe1e5bd8789d5d3c47d74cc08b | Python | Yejin6911/Algorithm_Study | /yejin/greedy/1946.py | UTF-8 | 1,302 | 3.328125 | 3 | [] | no_license | import sys
t = int(sys.stdin.readline().rstrip())
#처음풀이 - 시간초과
# def solution():
# n = int(sys.stdin.readline().rstrip())
# data = []
# for i in range(n):
# first, second = map(int, sys.stdin.readline().rstrip().split())
# data.append((first, second))
# data.sort()
# result = 1
# ... | true |
83f4e4263f722239fc6ccdccf971df96d7483102 | Python | ledwmp/wine_data | /fetch_lat_lon.py | UTF-8 | 1,710 | 2.703125 | 3 | [] | no_license | import requests
import numpy as np
import urllib.parse
import pandas as pd
import time
import glob
import json
path_tmp = "../frl-wine-producers-and-blenders-ca*.csv"
all_files = glob.glob(path_tmp)
"""
df = (pd.read_csv(f) for f in all_files)
df = pd.concat(df,ignore_index=True)
print(df.columns)
"""
for tmp in all_f... | true |
046dd8f60eec2872b8cb280a18ba3ce0f5131bf1 | Python | Lachlan00/oceancc-yuri | /classify.py | UTF-8 | 7,532 | 2.5625 | 3 | [] | no_license | # Perform model
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegressionCV
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from os import listdir
from os.path import isfile, join
from netCDF4 import Dataset
from progressbar import ProgressBar
impo... | true |