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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
d7c7fa637a169ca06cf885ae5c49d206b9443f07 | Python | SiChiTong/micro_mouse_final | /control_mousebot/scripts/Controller.py | UTF-8 | 7,898 | 3.25 | 3 | [] | no_license | #!/usr/bin/env python3
""" objective - control the robot at a very very high level"""
from Graph import Graph2
from MoveComputer import MoveComputer2
from DriveStep import DriveStep
from PathPlanner import PathPlanner
import rospy
import time
import numpy as np
class Controller(object):
def __init__(self):
... | true |
4a4db97774cb4c878fa370eb21560ed7f696091b | Python | CaiqueSobral/PyLearning | /Code Day 1 - 10/Code Day 9 Dictionaries and Nesting/1_Day 9 First Steps/2_Grades_Exercise.py | UTF-8 | 579 | 3.625 | 4 | [] | no_license | studentScores = {
"Harry": 81,
"Ron": 78,
"Hermione": 99,
"Draco": 74,
"Neville": 62,
}
#ToDo-1: Create an empty dictionary called student_grades.
studentGrades = {}
#ToDo-2: Write your code below to add the grades to student_grades.👇
for key in studentScores:
if studentScores[key] > 90:
studen... | true |
40238bccb1145ebe43f2b71f57fde668b6a9c0e7 | Python | Kefkius/txsc | /txsc/txscript/script_parser.py | UTF-8 | 8,824 | 2.765625 | 3 | [] | no_license | import ast
from ply import lex, yacc
import lexer
class ScriptParser(object):
tokens = lexer.tokens
precedence = lexer.precedence
def __init__(self, **kwargs):
self.debug = False
for k, v in kwargs.items():
setattr(self, k, v)
self.lexer = lex.lex(module=lexer)
... | true |
4aa29a617ae3bd105b54ade9890003f2b2fb9f6b | Python | Anseik/algorithm | /study/정올/Beginner_Coder/j_1338_문자삼각형1.py | UTF-8 | 413 | 3.359375 | 3 | [] | no_license | import sys
for line in sys.stdin:
n = int(line.rstrip())
# print(n)
arr = [[' '] * n for _ in range(n)]
# print(arr)
num = ord('A')
for i in range(n):
k = n - 1
for j in range(i, n):
if num > ord('Z'):
num = ord('A')
arr[j][k] = chr(num)
... | true |
4b6b96a25388bb1a646b1c16343a2921c8018ac6 | Python | MatejBabis/CS-GO-Fantasy-Calculator | /pandas_style.py | UTF-8 | 518 | 3.171875 | 3 | [] | no_license | def color_negative_red(val):
"""
Takes a scalar and returns a string with
the css property `'color: red'` for negative
strings, black otherwise.
"""
color = 'red' if val < 0 else 'black'
return 'color: %s' % color
def highlight_event_winner(s):
'''
highlight the maximum in a Series... | true |
0051152f95ff5ca3b2b3818e846b52e6862a3aba | Python | Janardan-latchumanan/NumberGuessingGame-Pro-97 | /numberGuessingGame( Project 97 ).py | UTF-8 | 489 | 4.28125 | 4 | [] | no_license | import random
print("Number Guessing Game")
print("Guess the number between 1 and 9")
# A.I statements required in this project
guessNumber = random.randint(1,9)
guessChances = 5
userGuess = input("Enter your Guess : ")
# conditional statements required in this project
if (guessChances <= 5):
print(userGue... | true |
de7d8fc2d8c25418f0dabda49e5fb3c94a16565c | Python | JackInTaiwan/DLCV2018SPRING | /hw1/notes.py | UTF-8 | 223 | 2.984375 | 3 | [] | no_license | import numpy as np
x = np.array([[1,2,3], [4,5,6], [7,8,9]])
y = np.array([[0], [0], [1]])
print (np.matmul(x, y))
a = np.array([1,2,3,4]).reshape(-1, 1)
b = np.array([0,1,2,2]).reshape(-1, 1)
print (np.sum((a-b) ** 2)) | true |
c7903afb3c6c58fa835037f2f7e33d6e46ce4335 | Python | Sandeep8447/interview_puzzles | /src/test/python/com/skalicky/python/interviewpuzzles/test_sum_2_binary_numbers_without_converting_to_integer.py | UTF-8 | 1,041 | 3.203125 | 3 | [] | no_license | from unittest import TestCase
from src.main.python.com.skalicky.python.interviewpuzzles.sum_2_binary_numbers_without_converting_to_integer import \
sum_2_binary_numbers_without_converting_to_integer
class Test(TestCase):
def test_sum_2_binary_numbers_without_converting_to_integer__when_0_plus_0__then_result_... | true |
706a40aaa1446e0f555afa2c3e490852bcdf74e9 | Python | xiaolongjia/techTrees | /Python/98_授课/Algorithm development/01_String/02_string_container/sc.py | UTF-8 | 1,616 | 4.0625 | 4 | [] | no_license | #!C:\Python\Python
import array
'''
string container: string a "BNDWDAQWDC", string b "ABA",
please write code to check if all characters in string b are contained in string a
let us asume length of a is n, length of b is m
time complexity: O(n)
space complexity: O(1)
'''
# Brute-force
# T(n) = O(n*m)
def strC... | true |
9c876f973c7f283bbebef4c3f6ea07ea4c4c567c | Python | TheBlackParrot/icecast-stats-python | /icestats.py | UTF-8 | 1,901 | 2.65625 | 3 | [] | no_license | import urllib.request;
import json;
import mimetypes;
import time;
import datetime;
class Stream():
def __init__(self, data):
self.bitrate = None;
if "bitrate" in data:
self.bitrate = int(data["bitrate"]) * 1024;
self.mimetype = None;
if "server_type" in data:
if data["server_type"]:
self.mimetype ... | true |
2bfd071e42d513e24acc054179c815acff9d93dc | Python | raad1masum/ParrotNAV | /controller/correct_horizontal.py | UTF-8 | 2,995 | 2.8125 | 3 | [
"MIT"
] | permissive | import matplotlib.pyplot as plt
import random
from time import sleep
from datetime import datetime
from PID.pid_controller import *
from simulation.sim import *
from states.states import *
from controls import controls
# set constants & gains
kp = horizontal_kp
setpoint = horizontal_setpoint
delay = 0
... | true |
d4d5530c63237ec9e8a54d2d8a3cd71cc90a18ec | Python | DQder/WHN-Codefest-2020 | /code/Problem 13.py | UTF-8 | 117 | 4.09375 | 4 | [] | no_license | Tf = float(input("Enter fahrenheit value: "))
Tc = (Tf - 32) / 1.8
print(Tf, "fahrenheit is equal to", Tc, "celsius") | true |
5dd0aa04ff9c1f207927f63accfc9d01476c29a6 | Python | jorgemira/euler-py | /p003.py | UTF-8 | 288 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive | '''Problem 3 from project Euler: Largest prime factor
https://projecteuler.net/problem=3'''
from utils import prime_factors
RESULT = 6857
def solve():
'''Main function'''
num = 600851475143
return max(prime_factors(num))
if __name__ == '__main__':
print solve()
| true |
b729baa2f985f8e4bfd26b091d524a301e1fe879 | Python | sidharth-potdar/dynamic-bus | /events/request_event.py | UTF-8 | 1,245 | 2.671875 | 3 | [] | no_license | from .event import Event
from .schedule_event import ScheduleEvent
import time
class RequestEvent(Event):
def __init__(self, origin_node, destination_node, ts=None, current_ts=None,priority=1):
super(RequestEvent, self).__init__(ts=ts)
self.origin_node = origin_node
self.destination_node =... | true |
0604f7752b9ec3fcff716e8e7e9dae64231df8c3 | Python | shanekang/Push-up_Algorithm_study | /Stack(Eval_Postfix).py | UTF-8 | 5,392 | 4.5625 | 5 | [] | no_license | class Stack:
def __init__(self):
self.items = list()
def is_empty(self): # 현재 스택이 비었는지 확인하는 함수
return True if len(self.items) == 0 else False
def push(self, item): # 스택에 item을 추가하는 함수
self.items.append(item)
def pop(self): # 스택의 마지막 item을 빼고 그 값을 반환하는 함수
if... | true |
9f933980a146980d3dfe97bcbd57a2a61ff9e04b | Python | kunalkumar37/allpython---Copy | /ex23.py | UTF-8 | 75 | 3.015625 | 3 | [] | no_license | fruits=["apple","abanana","cherry"]
x,y,z=fruits
print(x)
print(y)
print(z) | true |
85137a6087a856cadb0d3dd4a53ffd6575cafb08 | Python | kebab-mai-haddi/zcash_service_status_library | /src/zcash_service_status/communities_and_forums_response_time.py | UTF-8 | 945 | 2.578125 | 3 | [
"MIT"
] | permissive | import requests
import urllib3
urllib3.disable_warnings()
def get_response_time(url):
try:
return(requests.get(url, verify=False).elapsed.total_seconds())
except requests.exceptions.ConnectionError as e:
print(e)
return -1
communities = {
'chat.zcashcommunity.com': {'url... | true |
7d8c7963639380ec1a1963f7828bd8d1a3f53481 | Python | mcjcode/number-theory | /utilities.py | UTF-8 | 14,253 | 3.421875 | 3 | [] | no_license | #!/usr/bin/env python -i
# -*- coding: utf-8 -*-
"""
General purpose, factorization and modular
arithmetic routines.
"""
import time
import itertools
import functools
import operator
import random
import math
from math import sqrt
def prod(xs, start=1):
"""
:param xs: a sequence of elements to multiply
... | true |
90b581fab2014010d7398201ddf9847cef6a0d84 | Python | adarsh0610/python-codes | /evenodd.py | UTF-8 | 131 | 3.21875 | 3 | [] | no_license | n=int(input("enter a number"))
def evenodd():
if n%2==0:
print("the no is even")
else:
print("the number is odd")
evenodd()
| true |
032674fd1d2385459e9fdc31bdb4077875f8722e | Python | ezeqzim/tleng | /tp/calculoLambda/Asserts.py | UTF-8 | 2,170 | 3.5625 | 4 | [] | no_license | from .Type import *
from .Types import *
import copy
class ExpressionMustBeBool(Exception):
pass
class ExpressionMustBeNat(Exception):
pass
class ExpressionMustBeLambda(Exception):
pass
class ExpressionsMustHaveEqualType(Exception):
pass
class ExpressionMustBeApplicable(Exception):
pass
class FreeVariab... | true |
9103890ca3c33c2b08716e7c7caee22eb060ea3a | Python | Aliendood/pairmaker | /pairmaker.py | UTF-8 | 5,780 | 3.265625 | 3 | [
"Apache-2.0"
] | permissive | #!/usr/bin/env python
DEBUG = False
import sys
# Usage message.
USAGE = '''
Usage:
{program} [OPTIONS]
Example:
{program} 0426 Pairs for 04/26
{program} today Pairs for today
{program} help Usage message
Notes:
- Looks for students.txt in directory where script running from
- File stude... | true |
2a86d1bfa5f5a0c7a5e1a210042d798279c9b816 | Python | JeffStodd/StockBot-v2 | /Junk/Experimental Implementation.py | UTF-8 | 5,287 | 2.578125 | 3 | [] | no_license | import pandas as pd
import tensorflow as tf
import numpy as np
import os
import random
'''
Same inputs as original stock bot
2 output nodes for bearish and bullish confidence levels
'''
def loadData(path):
data = pd.read_csv(path, names = ["Change"])
return data
def main():
print("Num GPUs Available: ", ... | true |
516c4f08bedfe51db1e3e7bd44f2f7212cc48cb8 | Python | paulromano/armi | /armi/physics/fuelPerformance/utils.py | UTF-8 | 3,588 | 3.078125 | 3 | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] | permissive | """
Fuel performance utilities.
"""
from armi.reactor.flags import Flags
def enforceBondRemovalFraction(block, bondRemovedFrac):
r"""
Update the distribution of coolant in this block to agree with a fraction
This pulls coolant material out of the bond component and adds it to the other
coolant-conta... | true |
38e7bc429abbf72542f31a0d0a006d48a93ab6ef | Python | kzinmr/tftenarai | /estimator_custom.py | UTF-8 | 2,690 | 3.203125 | 3 | [] | no_license | # Instead of sub-classing Estimator,
# we simply provide Estimator a function `model_fn`
# that tells `tf.estimator` how it can evaluate pred, loss and opt.
# https://www.tensorflow.org/api_docs/python/tf/estimator
import numpy as np
import tensorflow as tf
# Check that we have correct TensorFlow version installed
tf... | true |
de6e0f4b2b7d6b8f91be98bb56f571d08bdbc2cc | Python | Aasthaengg/IBMdataset | /Python_codes/p03828/s914422541.py | UTF-8 | 928 | 2.609375 | 3 | [] | no_license | import sys
from collections import *
import heapq
import math
import bisect
from itertools import permutations,accumulate,combinations,product
from fractions import gcd
def input():
return sys.stdin.readline()[:-1]
def ruiseki(lst):
return [0]+list(accumulate(lst))
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in... | true |
97185534162ddb2be2135b94ee2b9c916556f4d2 | Python | hducati/machine-learning-tests | /keras_credit_data.py | UTF-8 | 1,521 | 3.0625 | 3 | [] | no_license | import pandas as pd
import keras
from sklearn.impute import SimpleImputer
from sklearn.metrics import confusion_matrix, accuracy_score
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Dense
def main():
... | true |
0ad944bea961d4860625323e68efc5b36f2f6fd3 | Python | doyu/hy-data-analysis-with-python-summer-2021 | /part06-e06_nonconvex_clusters/src/nonconvex_clusters.py | UTF-8 | 2,707 | 3.8125 | 4 | [] | no_license | #!/usr/bin/env python3
'''Exercise 6 (nonconvex clusters)
Read the tab separated file "data.tsv" from the src folder into a
DataFrame. The dataset has two features X1 and X2, and the label y.
Cluster the feature matrix using DBSCAN with different values for the
eps parameter. Use values in np.arange(0.05, 0.2, 0.05) f... | true |
71d987430b310029d23c33a8ac4965739100a541 | Python | takoe-sebe/2019-fall-polytech-cs | /sketch_191113a_list23.pyde | UTF-8 | 628 | 3.28125 | 3 | [
"MIT"
] | permissive | def setup():
size(500,500)
smooth()
noLoop()
noStroke()
ellipseMode(CENTER)
def draw():
background(255)
border=50
nw=width-2*border
nh=height-2*border
number=5
nWstep=nw/number
nHstep=nh/number
for i in range(0,number):
for j in range(0,number):
... | true |
929564dbf5a79d055b1a0ae7d88e15a28dcf2ff7 | Python | LiHRaM/P5 | /test_code/streamer.py | UTF-8 | 480 | 2.75 | 3 | [] | no_license | import sys
from nxt.bluesock import BlueSock
bs = BlueSock("00:16:53:12:C0:CA:00")
bs.debug = True
bs.connect()
size_bytes = 256
while True:
payload = [] # Received data
print("Main loop")
while sys.getsizeof(payload) < size_bytes:
print("Awaiting...")
t = bs.sock.recv(size_bytes)
... | true |
4ddd4a257bcbd8215dd768d39720c95fb8905777 | Python | evancjx/Stock_Prediction | /src/helper.py | UTF-8 | 2,523 | 3.0625 | 3 | [] | no_license |
from datetime import date, datetime, timedelta
from dateutil import tz
from os.path import isdir
from os import mkdir
import pickle
def count_number_digits(num):
if isinstance(num, float):
num = str(num).split('.', 1)[0]
elif isinstance(num, int):
num = str(num)
else:
raise ValueEr... | true |
ac9dac1b7a4fb89bdbb21b80ecc1c9c861f01d06 | Python | srijan-singh/CodeChef | /Beginner/Chef Judges a Competition (CO92JUDG)/judge.py | UTF-8 | 322 | 3.4375 | 3 | [
"Apache-2.0"
] | permissive | t = int(input())
while t:
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
A.sort()
B.sort()
A.pop()
B.pop()
if sum(A) > sum(B):
print('Bob')
elif sum(A) < sum(B):
print('Alice')
else:
print('Draw')
t = t... | true |
846cf4d99adb64bea6183ad03c33e03991464e8b | Python | teemlinkSix/spider | /meizi.py | UTF-8 | 2,677 | 2.984375 | 3 | [] | no_license | #!/usr/bin/python
# -*- coding: UTF-8 -*-
from bs4 import BeautifulSoup
import urllib.request
import pymysql
import threading
#设置最大线程锁
thread_lock = threading.BoundedSemaphore(value=5)
def crawl(url):
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61... | true |
f28280b63b07f5c67370eb164dc7922bef627ded | Python | Legend0300/Python-OOP | /OOP_tutorial.py | UTF-8 | 8,333 | 4.1875 | 4 | [] | no_license | # This is the oop code that I have leared step by step
class Game:
def Work(self):
return('This is not a game perhaps -_-')
name = "There is no name of the game"
game1 = Game()
print(game1.Work())
print(game1.name)
class Human:
name = "ahmed"
def person(self):
print(... | true |
4c17aec0ad38909d8a6d7f0aa38b4d6de74060ad | Python | FITM-KMUTNB/TMRS | /Code07.py | UTF-8 | 5,090 | 2.71875 | 3 | [] | no_license | import networkx as nx
import matplotlib.pyplot as plot
import operator
from collections import defaultdict
G = nx.Graph()
G.add_edges_from([('A', 'B'), ('A', 'M'), ('A', 'L'), ('B', 'C'), ('B', 'D'),
('B', 'N'), ('B', 'O'), ('C', 'D'), ('D', 'E'), ('D', 'O'), ('E', 'F'), ('F', 'G'), ('F', 'N'), ('G',... | true |
575e0041bbc3bb7198b8e3e61019be0ca388ab37 | Python | namanpujari/hackerrank-problems | /oneNumbertoAnother.py | UTF-8 | 1,140 | 3.515625 | 4 | [] | no_license | # Complete the function below.
def swapdigits(a, m, index):
a_new = ''
m_new = ''
for i in range(len(a)):
if(i != index):
a_new = a_new + a[i]
else:
a_new = a_new + m[i]
for i in range(len(m)):
if(i != index):
m_new = m_new + m[i]
... | true |
472eaeb699127765a9893e01b33b689c549a1845 | Python | NickShatalov/ml_algorithms | /svm/svm.py | UTF-8 | 8,641 | 3.359375 | 3 | [] | no_license | import numpy as np
from cvxopt import solvers, matrix
from scipy.spatial import distance_matrix
class SVMSolver:
"""
Класс с реализацией SVM через метод внутренней точки.
"""
def __init__(self, C=1.0, method='primal', kernel='linear', gamma=None, degree=None):
"""
C - float, коэффициен... | true |
320d27ddb023b61bc6f9837bcd54ddd73825f202 | Python | lockwo/quantum_computation | /Pennylane/quantum_gradients_200_template.py | UTF-8 | 3,251 | 3.03125 | 3 | [
"MIT"
] | permissive | #! /usr/bin/python3
import sys
import pennylane as qml
import numpy as np
def gradient_200(weights, dev):
r"""This function must compute the gradient *and* the Hessian of the variational
circuit using the parameter-shift rule, using exactly 51 device executions.
The code you write for this chal... | true |
a5d9c8b51b61c745b9a17696bb4beb33eb9367ab | Python | blackox626/python_learn | /leetcode/top100/zijie_no2.py | UTF-8 | 487 | 3.8125 | 4 | [
"MIT"
] | permissive | """
有序链表,找到只出现一次的数字
1->2->2->3->3->5
1,5
"""
class Node:
def __init__(self, val):
self.val = val
self.next = None
instr = input()
lst = instr.split(',')
root = p = Node(lst[0])
for i in lst[1:]:
p.next = Node(i)
p = p.next
stack = []
while root:
top = root.val
stack.append(root... | true |
585cdbbbf6f17aaad435711280259b5fcf46c250 | Python | Jeongeun-Choi/CodingTest | /python_algorithm/Dynamic/BJ14501.py | UTF-8 | 433 | 2.890625 | 3 | [] | no_license | N = int(input())
arr = []
for _ in range(N):
arr.append(list(map(int, input().split())))
t = []
p = []
dp = []
for i in range(N):
t.append(arr[i][0])
p.append(arr[i][1])
dp.append(p[i])
for i in range(1, N):
for j in range(i):
if i - j >= t[j]:
dp[i] = max(p[i] + dp[j], dp[i]... | true |
28738e0d97cccb8242543d51ea2a8c2da6e92034 | Python | sclamons/DNA_Instrument | /seq_reading.py | UTF-8 | 4,709 | 3.15625 | 3 | [] | no_license | from nucleotides import *
from Bio import SeqIO
# Mapping of file endings (i.e., 'fa' in 'a-sequence.fa') to filetypes
# (i.e., 'fasta') for SeqIO.
filetype_map = {'fa' : 'fasta',
'fasta' : 'fasta',
'gb' : 'genbank'}
def sequences_in_file(filename, mode = 'scaffolds'):
'''
... | true |
cd7dc6542ebee3d97d4457208a7c4ac6b97c6821 | Python | soumasish/leetcodely | /python/longest_arithmetic_sequence.py | UTF-8 | 194 | 2.703125 | 3 | [
"MIT"
] | permissive | class Solution:
def longestArithSeqLength(self, A:[int]) -> int:
pass
if __name__ == '__main__':
solution = Solution()
print(solution.longestArithSeqLength([3, 6, 9, 12]))
| true |
1f8e16bbf8ab11174e1e36852cadaab03cf1336c | Python | EllieChanSZ/testDemoPython35 | /SeleniumDemo/select_box.py | UTF-8 | 475 | 2.734375 | 3 | [] | no_license | from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("http://www.baidu.com/")
print("1")
link = driver.find_element_by_link_text("设置").click()
print("2")
driver.find_element_by_link_text("高级搜索").click()
print("3")
driver.find_element_by_css_selector("select[name=\'gpc\']").click(... | true |
cd05c724e1ccb16d3809960309df78da067dfcec | Python | piupiuup/competition | /ijcai/tool.py | UTF-8 | 3,517 | 3.171875 | 3 | [] | no_license | # -*-coding:utf-8 -*-
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import GradientBoostingClassifier #GBM algorithm
from xgboost.sklearn import XGBClassifier
import xgboost as xgb
from sklearn import cross_validation, metrics #Additional scklearn fu... | true |
973b72726593aeb87936ef1d7275609631fb36fd | Python | perthi/deep-learning | /surface2d.py | UTF-8 | 746 | 2.734375 | 3 | [] | no_license |
import pandas as pd
import sys
print (sys.argv[1:] )
df = pd.read_csv('ML_Data_Insight_121016.csv', header=1)
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
#def randrange(n, vmin, vmax):
# '''
# Helper function to make an array of random numbers having shape (n, )... | true |
86346145cc6c8cf3bf28fcedfc17cad7db9e647d | Python | SubhamKumarPandey/DSA | /algorithms/Python/dynamic_programming/fibonacci_series_sum.py | UTF-8 | 690 | 4.46875 | 4 | [
"MIT"
] | permissive | # Find the sum up to nth term of fibonacci series using dynamic approach
# Fibonacci series starts from 0th term
"""
Output:
Sum up to term 10 of fibonacci series is: 143
"""
key = 10
if key < 0:
print("Please enter a valid term.")
exit()
d = {0: 0, 1: 1}
if key == 0:
print(f"Sum up to term {key} of... | true |
cc2ebb0b46e4c361388cbf4b4b8bca6160ab48ed | Python | raphael-deeplearning/nlp | /nmtlab/evaluation/base.py | UTF-8 | 2,871 | 2.625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from shutil import copyfile
from abc import ABCMeta, abstractmethod
import numpy as np
class EvaluationKit(object):
"""Class of evaluating translat... | true |
a8fe49282a76295807363b861493c56f70456a05 | Python | joshuap233/algorithms | /leetcode/jian-zhi-offer/55-I.py | UTF-8 | 827 | 3.53125 | 4 | [] | no_license | # https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/
# 剑指 Offer 55 - I. 二叉树的深度
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
_max... | true |
91b11f4aeec06b0fd9cbc949a6a70d0e00a907b5 | Python | Mumujane/PythonAdvance | /Gevent/Introduction/CanIterable.py | UTF-8 | 232 | 3.46875 | 3 | [] | no_license | """
# 可迭代的对象
"""
from collections import Iterable
a = "1234ksadk"
for temp in a:
print(temp)
print(isinstance(a, Iterable))
# isinstance : 判断类型是否一致, isinstance(a, Iterable) 判断是否可迭代
| true |
0b288537b629ac8153033f541cee8f81b64cd405 | Python | dropbox/dropbox-sdk-python | /example/oauth/commandline-oauth.py | UTF-8 | 851 | 2.765625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3
import dropbox
from dropbox import DropboxOAuth2FlowNoRedirect
'''
This example walks through a basic oauth flow using the existing long-lived token type
Populate your app key and app secret in order to run this locally
'''
APP_KEY = ""
APP_SECRET = ""
auth_flow = DropboxOAuth2FlowNoRedirect(A... | true |
afe3eede18b4bec429f7675300f9cd39c0e7f7e0 | Python | ofisser86/jb-Tic-Tac-Toe-with-AI | /Problems/Recursive multiplication/main.py | UTF-8 | 307 | 3.609375 | 4 | [] | no_license | def multiply(a, b):
if b == 1: # base case
return a
elif b == 0:
return 0
elif b == -1:
return a * -1
# ex 2 * (-3) = -2 - 2 - 2
# - 6 = - 6
elif b < -1:
return (a - multiply(a, b + 1)) * -1
# recursive case
return a + multiply(a, b - 1)
| true |
5788f211f2bb81a1a5565a0965b5dbba14287d66 | Python | atomliang/xling-el | /utils/read_write_vectors.py | UTF-8 | 3,193 | 3.109375 | 3 | [] | no_license | """Utils to read word vectors.
Also normalizes and removes accents, diacritics etc. if required
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gzip
import math
import numpy as np
import sys
import unidecode
import logging
logging.basicConfig(for... | true |
a9988c4009c01a6c1e05a81ea1bbb652203d8574 | Python | 0r3k1/youtube_downloader | /sqlite_3.py | UTF-8 | 3,214 | 2.828125 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sqlite3
import os
from utilidades import _opt
class sqlite_3(object):
def __init__(self):
self.path = os.path.join(os.getcwd(), "dat")
self.exist_dir()
self.exist = False
if self.crear_tabla():
self.con ... | true |
f1c2bbbeb1809b1d4969af1a3a5ace4bcffbc4dc | Python | omeradeel26/sudoku-solver | /game.py | UTF-8 | 15,963 | 3.359375 | 3 | [] | no_license | import pygame as p #import pygame... allows us to create GUI
import copy #import copy... allows for hardcopying variables
from solver import solve, generate, validify, find_empty #import from solver file
import time #creates delay in code at the end
GameScreen = "HOME" #starting screen
SIZE = 700 #set height and widt... | true |
6ca5e8b4511b0a2674da4882d7b88785a0906dd4 | Python | zazolla14/basic-python | /range.py | UTF-8 | 593 | 4.0625 | 4 | [] | no_license | #RANGE digunakan untuk memberi jarak data
#Contoh penulisan tanpa menggunakan range pada list indeks
nomor = [1,2,3,4,5,6,7,8,9,10]
#cara ini tidak efektif jika banyak data yang akan ditulis
#Solusi penulisan angka dengan menggunakn RANGE untuk 1 sampa 10
nomor2 = range(1, 11) #KENAPA 1, 11 karena range didalam an... | true |
6090c1ade662123f2326f3b5e4d5e32f1cc3550d | Python | TSGreen/bangladesh-air-quality | /test_scraping.py | UTF-8 | 1,101 | 2.515625 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Development script:
Used for finding the parameters needed to successfully scrape an individual webpage correctly
before parseing the code to the scrapy spider (which will crawl the full archive).
Created on Thu Aug 6 17:10:09 2020
@author: tim
"""
import requests
... | true |
0d840fde7fcf4160cd58f6b6b5aba5b1bcd93185 | Python | ChrisAllenMing/ConfGF | /confgf/utils/torch.py | UTF-8 | 2,500 | 2.578125 | 3 | [
"MIT"
] | permissive | import copy
import warnings
import numpy as np
import torch
import torch.nn as nn
from torch_geometric.data import Data, Batch
def clip_norm(vec, limit, p=2):
norm = torch.norm(vec, dim=-1, p=2, keepdim=True)
denom = torch.where(norm > limit, limit / norm, torch.ones_like(norm))
return vec * denom
d... | true |
e699e88a8beb9b5b98a111c99640b917863c88c2 | Python | vincent-vega/adventofcode | /2020/day_17/17.py | UTF-8 | 1,250 | 3.140625 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from collections import Counter
from functools import lru_cache
from itertools import combinations
@lru_cache(maxsize=None)
def _deltas(size: int) -> set:
zero_delta = (0,) * size
return { c for c in combinations([-1, 0, 1] * size, size) if c != zero_delta }
@... | true |
1cb76c7b57843abc67ac75b30cae91c8a9c29c35 | Python | cathcart/Cool-code-scraps | /euler/fifteen.py | UTF-8 | 1,891 | 3.46875 | 3 | [] | no_license | '''
#global
paths=[]
def start(n):
x,y=0,0
path=[]
for i in range(n+1):
x=i
path.append((x,y))
for i in range(1,n+1):
x=n
y=i
path.append((x,y))
return path
def flip(path,t):
\'''flip the t th point in the given path\'''
tmp=path[:]
tmp[t]=(tmp[t][0]-1,tmp[t][1]+1)
return tmp
def legal(path,t):
#a... | true |
688174b0ca0be4a52d45f8d11f960c30233ed85e | Python | Jack0427/python_basic | /pypy_test.py | UTF-8 | 263 | 2.78125 | 3 | [] | no_license | import time
def test():
for i in range(1, 10):
n = pow(10, i)
start_time = time.time()
sum(x for x in range(1, n + 1))
end_time = time.time()
print(f'10^{i}:{end_time-start_time}')
test()
# 下載pypy python實現
| true |
a681bba6675f7c8e752bd1629434acab56a4346f | Python | LYblogs/python | /Python1808/第一阶段/day3-变量和运算符/03-运算符.py | UTF-8 | 1,205 | 4.59375 | 5 | [] | no_license | """
Python中的运算符:数学运算符、比较运算符、逻辑运算符、
赋值运算符、位运算符。
1.数学运算符:+,-,*,/,%,//,**
+:加法运算符
-:减法运算
*:乘积运算符
/:除法运算
%:取余
//:取整
**:幂运算符
"""
print(5**2) #5的2次方
"""
2.比较运算符:
>,<,==,!=,<=,>=。
所有的比较运算符的运算结果都是布尔值
3.逻辑运算符:and ,or ,not
逻辑运算符的运算对象是布尔值,运算符结果也是布尔值
a.and(逻辑与运算)相当于生活中的"并且",当多个条件要同时满足就需要and。
值1 and 值2:如果值1和值... | true |
7741636d88afee44fca5a72d7388502c942eab45 | Python | malikahm3d/arabic-letter-frequency-analysis | /LetterFreqDemo.py | UTF-8 | 2,215 | 3.6875 | 4 | [] | no_license | validChars = "اإأبجدهوزحطيكلمنسعفصقرشتثخذضظغؤءئآة"
#using a valid characters varible to check what the file reads against it. And only use what is read if it is valid.
countOfLetters = 0
#using this varible to count all the characters/letters and get the relative frequency
frequencyDictionary = dict()
#intilizing a... | true |
df8fa12fd3db610385a6b7401791d38f4ed20149 | Python | sympy/sympy | /sympy/polys/agca/modules.py | UTF-8 | 46,946 | 3.25 | 3 | [
"BSD-3-Clause",
"MIT"
] | permissive | """
Computations with modules over polynomial rings.
This module implements various classes that encapsulate groebner basis
computations for modules. Most of them should not be instantiated by hand.
Instead, use the constructing routines on objects you already have.
For example, to construct a free module over ``QQ[x... | true |
9c756fc1adeed95b891700d3e0122462fabd712c | Python | Electrostatics/mmcif_pdbx | /tests/test_version.py | UTF-8 | 239 | 2.6875 | 3 | [
"CC0-1.0"
] | permissive | import re
import pdbx
from pdbx import __version__
def test_version_exists():
assert hasattr(pdbx, "__version__")
def test_version():
assert re.match(r"[0-9]+\.[0-9]+\.[0-9]+", __version__)
print(f"VERSION: {__version__}")
| true |
77930bd3ff6c8f7d72f79061a9369a33b463bc34 | Python | fernandoans/problemasPython | /problema26/lerImagem.py | UTF-8 | 732 | 2.546875 | 3 | [] | no_license | # -------------------------------------------------------------
# Optical Character Recognition ou Optical Character Reader
# -------------------------------------------------------------
# sudo apt-get install tesseract-ocr tesseract-ocr-por
# sudo pip install pytesseract
# tesseract LGPD01.png saida -l por
# --------... | true |
8b7c6c72c19c64162b21f71d372227897314fd5b | Python | eloitanguy/wikidiver | /models/ner.py | UTF-8 | 5,702 | 2.671875 | 3 | [] | no_license | from __future__ import unicode_literals, print_function
import spacy
import neuralcoref
import urllib
import json
from models.utils import character_idx_to_word_idx
class CoreferenceResolver(object):
"""
Class for executing coreference resolution on a given text
code from https://github.com/huggingface/... | true |
1b2c0cbd4af374197bd90b0d83d507d4f04458fb | Python | haobo724/cvex4 | /dir_curve.py | UTF-8 | 1,427 | 3.078125 | 3 | [] | no_license | from evaluation import OpenSetEvaluation
from classifier import NearestNeighborClassifier
import matplotlib.pyplot as plt
import numpy as np
# The range of the false alarm rate in logarithmic space to draw DIR curves.
false_alarm_rate_range = np.logspace(-3.0, 0, 1000, endpoint=False)
# Pickle files containing embedd... | true |
6eef48a621cc63ebb3dd486d0b374fcf206740db | Python | NikitaLinberg/write-number-bot | /app/numbers_written_form.py | UTF-8 | 5,648 | 3.1875 | 3 | [] | no_license | import json
import os
import random
NUMBERS_JSON_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "numbers.json")
assert os.path.isfile(NUMBERS_JSON_PATH), f"{NUMBERS_JSON_PATH!r} file must exist!"
NUMBER_COMPONENTS = {int(k): v for k, v in json.load(open(NUMBERS_JSON_PATH)).items()}
WORD_COMPONENTS =... | true |
74c0f7895a5605b49891f63435ca2e89f227bb6b | Python | ryanGT/krauss_misc | /rwkpickle.py | UTF-8 | 382 | 2.90625 | 3 | [] | no_license | import cPickle
def SavePickle(mydict, filepath, protocol=2):
"""Dump dictionary mydict to a Pickle file filepath using cPickle,
protocol=2."""
mypkl = open(filepath,'wb')
cPickle.dump(mydict, mypkl, protocol=protocol)
mypkl.close()
def LoadPickle(filepath):
mypkl = open(filepath,'rb')
myd... | true |
4f10a14ca0e22fd354839cf1a774487c5884a91e | Python | WillieMaddox/pysfm | /bundle_io.py | UTF-8 | 790 | 2.578125 | 3 | [] | no_license | import numpy as np
from bundle import Bundle, Camera, Track
# Eek, currently hardcoded
width = 1480
height = 1360
K = np.array([1500, 0, width / 2, 0, 1500, height / 2, 0, 0, 1], float).reshape((3, 3))
def load(tracks_path, cameras_path):
bundle = Bundle()
bundle.K = K
# Read cameras
camera_data = n... | true |
0a9ef4affdb2524fe54af7f8b4f8a13cc999733b | Python | saurabhariyan/daily_code | /projectEuler/problem3.py | UTF-8 | 140 | 3.25 | 3 | [] | no_license | import math
def sumdiff(n):
return (math.pow(n,4)/4 + math.pow(n,3)/6 - math.pow(n,2)/4 - n/6)
print (sumdiff (10));
print (sumdiff(100)); | true |
cafce2ad5011456ba51c25bf0f72b38deeea2227 | Python | hongjy127/TIL | /07. raspberrypi/python/video-ex/facedetect/ex02.py | UTF-8 | 877 | 2.625 | 3 | [] | no_license | import cv2
import sys
cascade_file = "haarcascade_frontalface_alt.xml"
cascade = cv2.CascadeClassifier(cascade_file)
image_file = "data/face1.jpg"
out_file = "data/face1-mosaic.jpg"
image = cv2.imread(image_file)
image_gs = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
face_list = cascade.detectMultiScale(image_gs, scale... | true |
70af50726ea19e5de7ecf562d937a02144d1b844 | Python | mpajunen/advent-of-code | /2017/src/common/matrix.py | UTF-8 | 515 | 3.3125 | 3 | [] | no_license | def flip_vertical(a):
return a[::-1]
def get_rotations(a):
rotations = [a]
for _ in range(3):
a = rotate_ccw(a)
rotations.append(a)
return rotations
def rotate_ccw(a):
return tuple(reversed(list(zip(*a))))
if __name__ == "__main__":
assert flip_vertical(((1, 0), (0, 0))) =... | true |
53811d45468028b4c28a75fed4ed2c949d3a4788 | Python | raspberry-pi-maker/NVIDIA-Jetson | /face_recognition/findfaces2.py | UTF-8 | 859 | 3.015625 | 3 | [] | no_license | import argparse
import time
from PIL import Image, ImageDraw
import face_recognition
s_time = time.time()
parser = argparse.ArgumentParser(description='face match run')
parser.add_argument('--image', type=str, default='./img/groups/team2.jpg')
args = parser.parse_args()
image = face_recognition.load_image_file(args.... | true |
e11d7ca1d385cc15d2abb226ab13fbbddaf2ada6 | Python | maw501/bayopt-gps | /notebooks/src/data_prep.py | UTF-8 | 1,949 | 2.53125 | 3 | [] | no_license | import gzip
import pickle
from pathlib import Path
import requests
import torch
import torchvision.transforms as transforms
from torch.utils.data import DataLoader, TensorDataset
MNIST_H, MNIST_W = 28, 28
dev = (
torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
)
# torchvision datasets ... | true |
41dbae8f79f9a5894d51b1388faf48d0b67b67bd | Python | Fraznist/prefect | /src/prefect/tasks/prometheus/pushgateway.py | UTF-8 | 9,333 | 2.71875 | 3 | [
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | permissive | import abc
from prometheus_client import (
CollectorRegistry,
Gauge,
pushadd_to_gateway,
push_to_gateway,
)
from collections import namedtuple
from typing import Dict, List, Optional
from prefect import Task
from prefect.utilities.tasks import defaults_from_attrs
class _GaugeToGatewayBase(Task):
@... | true |
e5953421c845098a5d9a2091a57dcc5ca05a43e6 | Python | hjuju/TF_Study-HAN | /Machine_Learning/ml17_pca_mnist5_xgb_gridSearch2.py | UTF-8 | 2,514 | 2.546875 | 3 | [] | no_license | # 0.999 이상의 n_componet=?를 사용하여 xgb 만들것
import numpy as np
from tensorflow.keras.datasets import mnist
from icecream import ic
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sklearn.svm import LinearSVC, SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn... | true |
3d1f83ffa2d5d5d23e6c6aa09b8235aa7457be62 | Python | Scipius02/181020-Hackathon | /181020 Hackathon2.py | UTF-8 | 1,326 | 3.6875 | 4 | [] | no_license | """ Selection of code that opens a plain text file, parses it into the Google Translate API
(whose library must be downloaded via https://github.com/BoseCorp/py-googletrans.git)
translates, then formats translation into a single sentence.
"""
from googletrans import Translator
translator = Translator()
# file-inp... | true |
880355d57e92da6fe03223615f10bb4b700c8726 | Python | kasapenkonata/programming-practice | /pictures/picture2_2.py | UTF-8 | 5,120 | 3.546875 | 4 | [] | no_license | import pygame
from math import pi, cos, sin
def sun_(screen_, color, dx, dy, num_points, radius):
point_list = []
for i in range(num_points * 2):
radius_ = radius
if i % 2 == 0:
radius_ = radius - 5
ang = i * pi / num_points
x = dx + int(cos(ang) * radius_)
... | true |
649c3abad9efe1f9c3a0724352b6d14629dd3b70 | Python | christofrancois/BioSWdev4ASN | /SNN_TUT/scripts/generate/new_stim_gene.py | UTF-8 | 1,230 | 2.953125 | 3 | [] | no_license | # The script writes in the files .stimtimes automatically
from random import randint
import math
import struct
file1 = "stim1.stimtimes"
file2 = "stim2.stimtimes"
fs1 = open(file1, "a+")
fs2 = open(file2, "a+")
MNIST_path = "../../data/train-labels.idx1-ubyte"
flab = open(MNIST_path, "rb")
start = 0
length = 3600 * ... | true |
999b95e729b292c2e1aa96350acf1e8f37e17cc6 | Python | michaeltorku/ML-Classifier | /References/Climate Predictor Model/Code/Demonstration Chuck.py | UTF-8 | 1,561 | 2.9375 | 3 | [] | no_license | import csv
import numpy as np
import pandas as pd
import sklearn
from numpy import genfromtxt
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.decomposition import PCA
from sklearn.externals import joblib
Features = list(csv.reader(open(r'\U... | true |
f5689da757196d92afe71acffa17d9709ba60ec2 | Python | TedCha/open-kattis-problems | /python/a_different_problem_2.7.py | UTF-8 | 166 | 2.703125 | 3 | [] | no_license | # https://open.kattis.com/problems/different
from sys import stdin
for line in stdin:
line = line.strip().split(" ")
print(abs(int(line[0]) - int(line[1]))) | true |
e213e881a00b1053ee3e161c07e36b2fa5fbeef0 | Python | anikpujan/Python-Project | /Bar_Lounge_Reviews.py | UTF-8 | 812 | 2.953125 | 3 | [] | no_license | import requests
from bs4 import BeautifulSoup
import csv
pages = [0,10,20,30,40,50,60,70,80,90,100]
filename = open('bar_lounge.csv', 'w')
f = csv.writer(filename)
header = ['Name', 'Location', 'Reviews']
f.writerow(header)
for page in pages:
req = requests.get('https://www.yelp.com/biz/bar-karaoke-... | true |
5c6b7926b14536e8d4f1f3ac5cee2d94bf8a3b29 | Python | bennettj1087/aoc | /2015/day22.py | UTF-8 | 1,846 | 3.046875 | 3 | [] | no_license | #
# cost, damage, heal, mr, armor, duration
all_spells = { 'mm': [53, 4, 0, 0, 0, 1],
'd': [73, 2, 2, 0, 0, 1],
's': [113, 0, 0, 0, 7, 6],
'p': [173, 3, 0, 0, 0, 6],
'r': [229, 0, 0, 101, 0, 5] }
active_spells = dict()
wins = list()
bd = 10
... | true |
730b050649c34db55d086b3fbd32665967dc2752 | Python | SlavBite/Game_3-AlleyWay- | /_AlleyWay(3)/shop_in.py | UTF-8 | 4,187 | 2.65625 | 3 | [] | no_license | from print_text import *
from enemy import *
from inf import *
def going_to_1():
global click_press
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if 490 < mouse[0] < 800 and 245 < mouse[1] < 450:
win.blit(shop_in_active,(490, 240))
if click[0] == 1 and click_press:
click_pres... | true |
446ea03fbdc4eca72cac7ed2e12ac18640860f27 | Python | Parkyunhwan/BaekJoon | /21_05/ThridWeek/P_Lv2_큰 수 만들기*.py | UTF-8 | 1,043 | 4.09375 | 4 | [] | no_license | '''
스택을 이용하자.
현재 스택의 top보다 작은 값은 무조건 삽입하고
top보다 큰 값은 더 큰 값이 상단에 올때까지 pop()한다.
이 작업을 k == 0이 될 때까지 또는 전체 문자열을 검사할 때 까지 진행한다.
이 작업을 거치면 스택에는 "앞자리 숫자가 가장 큰 순서"를 가지게 된다.
-> 앞자리를 최고 큰 수로 만들기 전략!!
## 주의할 점 ##
k의 갯수보다 적게 삭제하는 경우가 있을 수 있다. ex) 17442, k = 3 -> 처리를 거치면 7442가 나옴
남은 k가 2 이므... | true |
7194af83c2d5be323ed8efc55b50be39feaa77e7 | Python | TimWeaving/z-quantum-core | /tests/zquantum/core/interfaces/ansatz_utils_test.py | UTF-8 | 3,574 | 3.109375 | 3 | [
"Apache-2.0"
] | permissive | """Test cases for ansatz-related utilities."""
import unittest
from unittest import mock
import numpy as np
import numpy.testing
from zquantum.core.interfaces.ansatz_utils import (
DynamicProperty,
ansatz_property,
combine_ansatz_params,
invalidates_parametrized_circuit,
)
class PseudoAnsatz:
n_l... | true |
2926d26198262b6bfbf8dfa00c6ff726133c0940 | Python | cnangel/hyperdex | /test/python/testlib.py | UTF-8 | 984 | 3.578125 | 4 | [
"BSD-3-Clause"
] | permissive | def assertEqualsApprox(actual, expected, tolerance):
# Recurse over all subdocuments
if isinstance(actual, dict) and isinstance(expected, dict):
for k,v in actual.iteritems():
assert k in expected
assertEqualsApprox(v, expected[k], tolerance)
elif isinstance(actual, ... | true |
f211e387afb4744426b783bedefe81b75e19d259 | Python | adamorhenner/Fundamentos-programacao | /exercicios/exercicio-7.py | UTF-8 | 234 | 3.75 | 4 | [] | no_license | print("====Calculo do resto da divisao====")
primeiro = (int)(input("informe o primeiro numero: "))
segundo = (int)(input("informe o segundo numero: "))
print("o resto da divisao de", primeiro, "por", segundo, "eh", primeiro%segundo ) | true |
280770daba19b8fcf4e43a9a2df481616d869967 | Python | maryszmary/xml4webcorpora | /bookxml2xml_for_corp.py | UTF-8 | 9,740 | 2.78125 | 3 | [] | no_license | # coding: utf-8
import os
import re
import lxml.etree
import time
import xml.sax.saxutils
rxWords = re.compile('^([^\\w0-9’ʼ]*)(.+?)([^\\w0-9’́̀ʼ]*)$')
def process_alignment(lines):
lines = re.sub(' *\t *— *([\t\n])', ' —\\1', lines)
lines = [l for l in lines.split('\n') if len(l) > 2]
if le... | true |
bf6536c4d32523cec19f3b5398613608b4cbcde4 | Python | NyWeb/PICOPTER | /sensors/pwm.py | UTF-8 | 1,895 | 2.609375 | 3 | [] | no_license | import threading
import smbus
import random
import time
class pwm(threading.Thread):
bus = False
address = False
k = 2
m = 294
error = False
def __init__(self, address=0x40):
threading.Thread.__init__(self)
self.daemon = True
self.bus = smbus.SMBus(1)
self.ad... | true |
b38ad2bd5f52876832e0d13ec8a9b30ef1fb51cf | Python | matthewrmettler/project-euler | /Problems 1 through 50/problem37_truncatable_primes.py | UTF-8 | 1,165 | 4.09375 | 4 | [] | no_license | '''
Author: Matthew Mettler
Project Euler, Problem 37
https://projecteuler.net/problem=37
The number 3797 has an interesting property. Being prime itself, it is possible
to continuously remove digits from left to right, and remain prime at each
stage: 3797, 797, 97, and 7.
Similarly we can work from right to left: ... | true |
98b19e6001120f617616171d853254e19e9ada45 | Python | akash682/Natural-Language-Processing_UDEMY | /Lesson30/Lesson30.py | UTF-8 | 544 | 3 | 3 | [] | no_license | # Tokenize : Split by " ", "."
# Stemming : Stemming is process of reducing infected or derived words to their word stem, base or root form" - Wikipedia
# intelligence, intelligent, inteligently
# intelligen
# going, goes, gone
# go
# Produced intermediate representation of the word may not have any meaning.
#... | true |
5ae8abf3d661cd9b4bb94652e76206be380d59b1 | Python | a3r0d7n4m1k/YACS | /courses/templatetags/course_tags.py | UTF-8 | 3,398 | 2.703125 | 3 | [
"MIT"
] | permissive | from django import template
from courses.utils import DAYS, ObjectJSONEncoder
from courses.encoder import default_encoder
register = template.Library()
def remove_zero_prefix(timestr):
if timestr[0] == '0':
return timestr[1:]
return timestr
@register.filter
def bold_topics_include(string):
re... | true |
9dd8bb183b9af5af9abdcc8b060854fbc3c08b53 | Python | JannaKim/PS | /ExhaustiveSearch/2422_한윤정.py | UTF-8 | 429 | 2.953125 | 3 | [] | no_license | n, m= map(int, input().split())
nots={}
for _ in range(m):
a,b= map(int,input().split())
if b<a:
a,b= b,a
nots[(a,b)]=True
ans=0
for i in range(1,n-1):
for j in range(i+1,n):
for k in range(j+1, n+1):
if (i,j) in nots:
continue
if (j,k) in nots:
... | true |
1f67c72218127129fce6ca17b4ac993b2b35fc7c | Python | werthergit/MyPyMLRoad | /6-news.py | UTF-8 | 2,261 | 2.96875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 30 09:22:03 2018
@author: zhengyuv
"""
from keras.datasets import reuters
import numpy as np
from keras import models
from keras import layers
import matplotlib.pyplot as plt
from keras import metrics
#read dataset
(train_data, train_labels), (test_data, te... | true |
37859ad59ea89b4ed0c968ff0f4fbcd936fc6308 | Python | yichi-yang/QRantine-backend | /community/management/commands/updatecvdb.py | UTF-8 | 1,661 | 2.515625 | 3 | [] | no_license | from django.core.management.base import BaseCommand, CommandError
from community.models import Community
from bs4 import BeautifulSoup
import urllib.request
import re
url = "http://publichealth.lacounty.gov/media/Coronavirus/locations.htm"
class Command(BaseCommand):
help = 'Update LA Covid-19 database'
de... | true |
93f06f9ada346e390044c0f7622c2c4a4ab0ee3b | Python | brainysmurf/pydir | /pydir/Select.py | UTF-8 | 4,676 | 3.078125 | 3 | [] | no_license | """
Select Module
Subclasses main Dir class so that it presents user a list of choices,
selection.
"""
from dir.Dir import Dir
from dir.Filer import File_list, File_object
from dir.Menu import Menu, BadArguments
from dir.Console import Output
from dir.Command import Shell_Emulator as Shell
from colorama import Fore, Ba... | true |
924f5b36aadc0cfccb1c4c3ae146bbaa7984731d | Python | Python3pkg/pyduino-mk | /python/pyduino_mk/arduino.py | UTF-8 | 7,972 | 2.625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
# Copyright (c) 2015 Nelson Tran
#
# 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, modify,... | true |
1ab2e16c6af4798a7a14b388d5d55b9de08c5969 | Python | ashray-00/Convolution-Model-Step-by-Step | /distribute_value.py | UTF-8 | 644 | 3.59375 | 4 | [] | no_license | import numpy as np
def distribute_value(dz, shape):
"""
Distributes the input value in the matrix of dimension shape
Arguments:
dz -- input scalar
shape -- the shape (n_H, n_W) of the output matrix for which we want to distribute the value of dz
Returns:
a -- Array of size (n_H, n... | true |
7fb4c089f02f5d7dc234cd4b063821824e09e0b8 | Python | qulu622/DTW | /dtw_thre.py | UTF-8 | 5,673 | 3.328125 | 3 | [] | no_license | # DTW_THRE
import numpy as np # matrix
import pandas as pd # dataframe
import math # inf
import time # time
import os # listdir
def dtw_thre(ts1, ts2, minimum_distance): # DTW with threshold
cell = 0
ts1_len = len(ts1) - 1
ts2_len = len(ts2) - 1
dtw_thre_matrix = np.zeros([ts1_len + 1,... | true |