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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
97677712971d82eb6fab74a5f0b154c1517ae609 | Python | ashidagithub/ASD_WinForms | /try_controls_1/try4_frame/try_frame2.py | UTF-8 | 1,178 | 3.28125 | 3 | [
"Apache-2.0"
] | permissive | # -*- coding: UTF-8 -*-
# ------------------------(max to 80 columns)-----------------------------------
# author by : (学员ID)
# created: 2019.11
# Description:
# 初步学习 WinForm 编程 ( LabelFrame )
# ------------------------(max to 80 columns)-----------------------------------
import tkinter as tk
from tkinter import ttk
# tk._test() # 测试 tkinter 是否正常工作
# create root window
top_win = tk.Tk()
# naming root window
top_win.title('Hello World Window')
# resize root window
win_size_pos = '800x600'
top_win.geometry(win_size_pos)
# Step1: Create frame
frame_root1 = tk.Frame(top_win, bg="grey", width=760, height=200)
# frame_root1.pack()
frame_root1.place(x=20, y=20)
# Step2: Appedn other controls
lbl_test = tk.Label(frame_root1, text='text in frame')
lbl_test.place(x=20, y=60)
# Step3: Create Label Frame
frame_root2 = tk.LabelFrame(top_win, bg="grey", width=760, height=200, text='My Frame')
# frame_root1.pack()
frame_root2.place(x=20, y=240)
# Step4: Appedn other controls
lbl_test = tk.Label(frame_root2, text='text in label frame')
lbl_test.place(x=20, y=60)
# show window and get into event loop
top_win.mainloop()
| true |
83690268f39e173de1c79d98f0debcfdc4dcd1fd | Python | kubracetinkaya/OpenCV | /3/book5.py | UTF-8 | 704 | 2.59375 | 3 | [] | no_license | import cv2
import numpy as np
import argparse
import imutils
ap=argparse.ArgumentParser()
ap.add_argument('-i','--image',required=True,help='Path to the image')
args=vars(ap.parse_args())
image=cv2.imread(args['image'])
cv2.imshow('Original',image)
#goruntunun sekline image.shape[] ile ulasilir
M=np.float32([[1,0,25],[90,1,50]])
shifted=cv2.warpAffine(image,M,(image.shape[1],image.shape[0]))
cv2.imshow('Shifted Down and Right',shifted)
M=np.float32([[1,0,-50],[0,1,-90]])
shifted=cv2.warpAffine(image,M,(image.shape[1],image.shape[0]))
cv2.imshow('Shifted Up and Left',shifted)
shifted=imutils.translate(image,0,100)
cv2.imshow('Shifted Down',shifted)
cv2.waitKey(0)
| true |
3909be7039e53abbf36d9278483da1dc7558b9f3 | Python | krkmn/checkio | /scientific_expedition/fastest_horse.py | UTF-8 | 770 | 3.921875 | 4 | [] | no_license | def fastest_horse(horses: list) -> int:
times = [secondize(x) for one_race in horses for x in one_race]
races = len(times)//len(horses)
sum_times = []
for i in range(races):
sum_times.append(sum(times[i::races]))
return sum_times.index(min(sum_times)) + 1
def secondize(string_time):
minute , second = string_time.split(':')
return int(minute)*60 + int(second)
if __name__ == '__main__':
print("Example:")
print(fastest_horse([['1:13', '1:26', '1:11']]))
#These "asserts" using only for self-checking and not necessary for auto-testing
assert fastest_horse([['1:13', '1:26', '1:11'], ['1:10', '1:18', '1:14'], ['1:20', '1:23', '1:15']]) == 3
print("Coding complete? Click 'Check' to earn cool rewards!") | true |
ad96529c6ccba58e5015e216bc83f45d6d15b9e5 | Python | jimmykobe1171/hmm | /hidden_markov_model/viterbi.py | UTF-8 | 2,518 | 2.53125 | 3 | [] | no_license | class VitebiAlgorithm(object):
def __init__(self, hmm, observations):
self.hmm = hmm
self.observations = observations
def get_result(self):
observations = self.observations
hmm = self.hmm
hidden_states_set = hmm.hidden_states_set
dp_max_probs = []
dp_step_trace = []
# dp_dic: {'state_2': {'p': 0.4, 'trace': ['state_1', 'state_2']}}
# iterately update dp_dic
for i in range(len(observations)):
observation = observations[i]
dp_max_probs_dic = {}
dp_step_trace_dic = {}
if i == 0:
for state in hidden_states_set:
start_p = hmm.get_start_probability(state)
emission_p = hmm.get_emission_probability(state, observation)
dp_max_probs_dic[state] = start_p * emission_p
dp_step_trace_dic[state] = None
else:
for state in hidden_states_set:
max_p, max_pre_state = None, None
for pre_state in hidden_states_set:
pre_p = dp_max_probs[i-1][pre_state]
transition_p = hmm.get_transsition_probability(pre_state, state)
tmp_p = pre_p * transition_p
if max_p is None:
max_p = tmp_p
max_pre_state = pre_state
elif tmp_p > max_p:
max_p = tmp_p
max_pre_state = pre_state
# update new_dp_dic
emission_p = hmm.get_emission_probability(state, observation)
dp_max_probs_dic[state] = max_p * emission_p
dp_step_trace_dic[state] = max_pre_state
dp_max_probs.append(dp_max_probs_dic)
dp_step_trace.append(dp_step_trace_dic)
# find out the most probable one in dp_dic
arr = sorted(dp_max_probs[-1].items(), key=lambda t: t[1], reverse=True)
print dp_max_probs
print dp_step_trace
last_state = arr[0][0]
# back trace hidden state
hidden_states = [last_state]
state_trace = last_state
for i in range(len(observations)-1, 0, -1):
hidden_states.append(dp_step_trace[i][state_trace])
state_trace = dp_step_trace[i][state_trace]
hidden_states = list(reversed(hidden_states))
return hidden_states
| true |
42a03405a475500ed8adfe1d1795f37d8884ffa2 | Python | Aasthaengg/IBMdataset | /Python_codes/p02883/s204027873.py | UTF-8 | 796 | 3.015625 | 3 | [] | no_license | from math import ceil
N, K = map(int, input().split())
A = sorted(list(map(int, input().split())), reverse=True)
F = sorted(list(map(int, input().split())))
def is_valid(A, F, K, T):
for a, f in zip(A, F):
if a*f > T:
k = ceil(a - T/f)
if k <= K:
K -= k
else:
return False
return True
def solve(N, K, A, F):
i = 0
left, right = 0, 10**12
while left < right:
mid = (left + right) // 2
if is_valid(A, F, K, mid):
right = mid
else:
left = mid + 1
if is_valid(A, F, K, mid-1) and (not is_valid(A, F, K, mid)):
return mid-1
elif is_valid(A, F, K, mid):
return mid
else:
return mid+1
print(solve(N, K, A, F))
| true |
d7f8b107955e5d858fda25cb3771686bf17eaee4 | Python | Slugskickass/Teaching_python | /Week 2/13.) Basic Images.py | UTF-8 | 533 | 3.15625 | 3 | [] | no_license | from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
file_name = '../Week 2/Data/640.tif'
img = Image.open(file_name)
print('The Image is', img.size, 'Pixels.')
print('With', img.n_frames, 'frames.')
imgArray = np.zeros((img.size[1], img.size[0], img.n_frames), np.uint16)
for I in range(img.n_frames):
img.seek(I) # Pointing
imgArray[:, :, I] = np.asarray(img) # copying
img.close()
for I in range(1, 10):
plt.subplot(3, 3, I)
plt.imshow(imgArray[:, :, I-1])
plt.show()
| true |
9c43617570811593c6f2b3c26ba9bba08ad0b3d1 | Python | doyager/play_around | /python/boiler_plate.py | UTF-8 | 1,695 | 2.734375 | 3 | [] | no_license | import os
import shutil
from sys import argv
import time
import warnings
#env dir setup
def env_dir_check():
preprocess_dir='/tmp/preprocess'
if not os.path.exists(preprocess_dir):
os.makedirs(preprocess_dir)
#env dir clean up
def env_dir_cleanup():
if os.path.exists(preprocess_dir):
shutil.rmtree(preprocess_dir)
#method to add our python files dir to the python run time
def env_setup():
code_dir = os.path.expanduser(project_dir)
if code_dir not in sys.path:
sys.path.append(code_dir)
warnings.filterwarnings("ignore")
#main process
def process():
try:
#do something
start_time = time.time()
#after process
print("\n Process finished in %s minutes \n" % ((time.time() - start_time) / 60))
#cleanup
env_dir_cleanup()
exit(0)
except Exception as e:
print ("[ERROR] Process Failed ")
print ("ERROR : ")
print (e)
env_dir_cleanup()
exit(1)
if __name__ == "__main__":
if len(argv) == 3 :
print (">>>>Args Passed: Loading the arguments")
project_dir = argv[1]
tmp_dir = argv[2]
threshold = argv[3]
print (">>>>Args Received: "+"\n project_dir: "+project_dir+"\n tmp_dir: "+tmp_dir+"\n threshold: "+threshold)
env_setup()
env_dir_check()
process()
else:
print("ERROR: Invalid Args length !!!")
print (">>>>Usage:<project dir> <tmp_path> <threshold(0 to 0.99)>")
for i in argv:
print (i+"\n")
exit(1)
| true |
bd5aa6d1ba935680099a1d66512db82ab9931ca6 | Python | dgetskova/Programming101-3_hack_bg | /week8/2-SQL-Over-Northwind/northwind.py | UTF-8 | 2,419 | 2.734375 | 3 | [] | no_license | # List of names and titles for all employees
"""SELECT FirstName, LastName, Title
FROM Employees"""
# List all employees from Seattle.
"""SELECT FirstName, LastName
FROM Employees
WHERE City LIKE "Seattle""""
# List all employees from London.
"""SELECT FirstName, LastName
FROM Employees
WHERE City = "Seattle""""
# List all employees that work in the Sales department.
"""SELECT FirstName, LastName
FROM Employees
WHERE Title LIKE "%Sales%""""
# List all females employees that work in the Sales department.
"""SELECT FirstName, LastName
FROM Employees
WHERE Title LIKE "%Sales%" AND (TitleOfCourtesy = "Mr." OR TitleOfCourtesy = "Mrs.")""""
# List the 5 oldest employees.
"""SELECT *
FROM Employees
ORDER BY BirthDay ASC
LIMIT 5"""
# List the first 5 hires of the company.
"""SELECT *
FROM Employees
ORDER BY HireDate ASC
LIMIT 5"""
# List the employee who reports to no one (the boss)
"""SELECT *
FROM Employees
WHERE ReportsTo is NULL"""
# List all employes by their first and last name, and the first and last name of the employees that they report to.
"""SELECT a.FirstName, a.LastName, b.FirstName, b.LastName
FROM Employees a
JOIN Employees b
WHERE a.ReportsTo = b.EmployeeID"""
# Count all female employees.
"""SELECT COUNT(EmployeeID)
FROM Employees
WHERE TitleOfCourtesy = "Mr." OR TitleOfCourtesy = "Mrs.""""
# Count how many employees are there from the different cities. For example, there are 4 employees from London.
"""SELECT COUNT(EmployeeID) AS Count_Persons, City
FROM Employees
GROUP BY City"""
# List all OrderIDs and the shipper name that the order is going to be shipped via.
"""SELECT OrderID, CompanyName
FROM orders
JOIN Shippers
ON Orders.Shipvia = Shippers.ShipperID"""
# List all contries and the total number of orders that are going to be shipped there.
"""SELECT COUNT(OrderID) AS OrdersCount, ShipCountry
FROM Orders
GROUP BY ShipCountry"""
# Find the customer that has placed the most orders.
"""SELECT COUNT(OrderID) AS OrdersCount, FirstName
FROM Orders
JOIN employees
ON Orders.EmployeeID = Employees.EmployeeID
GROUP BY Orders.EmployeeID
ORDER BY OrdersCount DESC
LIMIT 1"""
# List all orders, with the employee serving them and the customer, that has placed them.
""" SELECT OrderID, ContactName AS Customer_Name, FirstName as Employee_Name
FROM Orders
JOIN Customers
ON Orders.CustomerID = Customers.CustomerID
JOIN Employees
ON Orders.EmployeeID = Employees.EmployeeID """
| true |
ccb07a96f165eb655ca4f195587929a53012fe78 | Python | carlosvq1337/Data-visualization | /src/grapher.py | UTF-8 | 7,044 | 2.640625 | 3 | [] | no_license | #! python3
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import time
from os import listdir
from os.path import isfile, join
import argparse
import sys
plt.ion()
class DynamicUpdate():
def __init__(self, path_to_dir, max_col):
self.path_to_dir = path_to_dir
self.paths_to_files = []
self.x_labels = []
self.y_labels = []
self.max_col = int(max_col)
self.onlyfiles = [f for f in listdir(path_to_dir) if isfile(join(path_to_dir, f))]
for file in self.onlyfiles:
if file != "flags":
self.paths_to_files.append(path_to_dir + "/" + file)
f = open(path_to_dir + "/" + file, "r")
lines = f.readlines()
linex = lines[0].split(' ')
linex = [i for i in linex if i != '']
self.x_labels.append(linex[0])
self.y_labels.append(linex[1])
f.close()
else:
self.flag = linex[0]
self.path_to_flags = path_to_dir + "/" + file
self.min_x = 1
self.max_x = 2000
self.number_of_lines = self.get_lines()
self.dct = {}
self.number_of_files = len(self.paths_to_files)
def update_data(self):
self.number_of_lines = self.get_lines()
for file_path in self.paths_to_files:
y_values = []
x_values = []
f = open(file_path, "r")
lines = f.readlines()
for x in range(1, self.number_of_lines):
linex = lines[x].split(' ')
linex = [i for i in linex if i != '' and i != '\n']
x_values.append(float(linex[0].strip()))
y_values.append(float(linex[1].strip()))
self.dct[self.y_labels[self.paths_to_files.index(file_path)]] = y_values
self.dct[self.x_labels[self.paths_to_files.index(file_path)]] = x_values
f.close()
f = open(self.path_to_flags, "r")
lines = f.readlines()
self.flag = lines[0]
def get_lines (self): #gets the number of lines in the file with least lines (to prevent errors)
min_lines = 99999
for file_path in self.paths_to_files:
with open(file_path) as f:
for i, l in enumerate(f):
pass
f.close()
if i + 1 < min_lines:
min_lines = i + 1
return min_lines
def on_launch(self):
#determine dimensions of figure
if self.number_of_files < self.max_col:
self.rows = []
self.rows.append(self.number_of_files)
self.figure, self.ax = plt.subplots(len(self.rows),self.rows[0])
self.lines = []
for c in range(0, self.rows[0]):
self.lines.append(self.ax[c].plot([],[]))
#Autoscale on unknown axis and known lims on the other
self.ax[c].set_autoscaley_on(True)
self.ax[c].set_titlel(self.y_labels[c])
if self.flag == "1":
self.ax[c].set_xscale("log")
self.ax[c].axes.get_yaxis().set_visible(False)
self.ax[c].axes.get_xaxis().set_visible(False)
#Other stuff
self.ax[c].grid()
else:
if self.number_of_files%self.max_col == 0:
self.rows = [self.max_col]*(int(self.number_of_files/self.max_col))
else:
self.rows = [self.max_col]*(int(self.number_of_files/self.max_col))
self.rows.append(self.number_of_files%self.max_col)
#Set up plot
self.figure, self.ax = plt.subplots(len(self.rows),self.rows[0])
self.lines = []
for r in range (0, len(self.rows)):
for c in range(0, self.rows[r]):
self.lines.append(self.ax[r][c].plot([],[]))
#Autoscale on unknown axis and known lims on the other
self.ax[r][c].set_autoscaley_on(True)
self.ax[r][c].set_title(self.y_labels[c+self.max_col*r])
self.ax[r][c].axes.get_yaxis().set_visible(False)
self.ax[r][c].axes.get_xaxis().set_visible(False)
if self.flag == "1":
self.ax[r][c].set_xscale("log")
if self.flag == "0":
self.ax[r][c].set_xscale("linear")
#Other stuff
self.ax[r][c].grid()
if self.number_of_files%self.max_col != 0:
for c in range(self.rows[len(self.rows)-1], self.max_col):
self.ax[len(self.rows)-1][c].axes.get_yaxis().set_visible(False)
self.ax[len(self.rows)-1][c].axes.get_xaxis().set_visible(False)
self.ax[len(self.rows)-1][c].grid()
def on_running(self):
if self.flag == "1":
self.figure.suptitle("APCSA Fitting" + ": " + str(self.get_lines() - 1) + " WITH LOG SCALE ON X", fontsize = 15)
if self.flag == "0":
self.figure.suptitle("APCSA Fitting" + ": " + str(self.get_lines() - 1) + " WITH LINEAR SCALE ON X", fontsize = 15)
if self.number_of_files < self.max_col:
for c in range(0,self.rows[0]):
self.lines[c][0].set_xdata(self.dct[self.x_labels[c]])
self.lines[c][0].set_ydata(self.dct[self.y_labels[c]])
#Need both of these in order to rescale
self.ax[c].relim()
self.ax[c].autoscale_view()
else:
#Update data (with the new _and_ the old points)
for r in range (0, len(self.rows)):
for c in range(0,self.rows[r]):
self.lines[c+self.max_col*r][0].set_xdata(self.dct[self.x_labels[c+self.max_col*r]])
self.lines[c+self.max_col*r][0].set_ydata(self.dct[self.y_labels[c+self.max_col*r]])
self.ax[r][c].set_title(self.y_labels[c+self.max_col*r] + " =" + str(self.dct[self.y_labels[c+self.max_col*r]][-1]), fontsize =8)
if self.flag == "1":
self.ax[r][c].set_xscale("log")
if self.flag == "0":
self.ax[r][c].set_xscale("linear")
#Need both of these in order to rescale
self.ax[r][c].relim()
self.ax[r][c].autoscale_view()
#We need to draw *and* flush
self.figure.canvas.draw()
self.figure.canvas.flush_events()
#Example
def __call__(self):
self.on_launch()
while self.number_of_lines < self.max_x:
self.update_data()
self.on_running()
time.sleep(0.25)
if __name__ == "__main__":
dyn = DynamicUpdate(sys.argv[1], sys.argv[2])
dyn()
| true |
4b7370f67a1f6850419eb5bd5807df7871b4a917 | Python | shg9411/algo | /algo_py/boj/bj12865.py | UTF-8 | 447 | 2.8125 | 3 | [] | no_license | import io
import os
import sys
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def solve():
n, k = map(int, input().split())
dp = {0: 0}
for _ in range(n):
w, v = map(int, input().split())
t = {}
for ck, cv in dp.items():
if ck+w <= k and dp.get(ck+w, 0) < cv+v:
t[ck+w] = cv+v
dp.update(t)
print(max(dp.values()))
if __name__ == "__main__":
solve()
| true |
12135e6fbb73d6e244377c3b2f8ec7a505d73572 | Python | yhou46/openvpn_config | /scripts/edit_file.py | UTF-8 | 4,846 | 2.625 | 3 | [] | no_license | #!/usr/bin/python3
import codecs
import argparse
import sys
# Self libraries
import configFileEditor
#-------------------------------------------------
# Constants
#-------------------------------------------------
argsMode = \
{
"ipv4_mode": "ipv4",
"ufw_before_rules_mode": "ufw_bef", # ufw before rules
"ufw_forward_mode": "ufw_for", # ufw forward rules
"replace_line_mode": "replace", # replace line in file
}
#-------------------------------------------------
# Functions
#-------------------------------------------------
# TODO: cannot handle if # mark is not the 1st character of the line
# Change file content to enable ipv4 forwarding
# key is to make "net.ipv4.ip_forward=1"
def enableIpv4Forwarding(filename):
lines = []
with codecs.open(filename, "r+", "utf-8") as file:
lines = file.readlines()
enableKeyword = "net.ipv4.ip_forward=1"
disableKeyword = "net.ipv4.ip_forward=0"
# TODO: not a good way to do this, need to change
newFileLines = []
isEnableChanged = False
for line in lines:
if enableKeyword in line:
if line[0] == "#":
newFileLines.append(enableKeyword + "\n")
else:
newFileLines.append(line)
isEnableChanged = True
elif disableKeyword in line and line[0] == "#":
newFileLines.append(line)
else:
newFileLines.append(line)
# if no enableKeywork is found, add it to the end of file
if not isEnableChanged:
newFileLines.append(enableKeyword + "\n")
with codecs.open(filename, "w", "utf-8") as file:
file.writelines(newFileLines)
return
def changeUfwBeforeRules(filename, publicInterfaceName):
insertLine = "\n# START OPENVPN RULES\n" + \
"# NAT table rules\n" + \
"*nat\n" + \
":POSTROUTING ACCEPT [0:0]\n" + \
"# Allow traffic from OpenVPN client to " + publicInterfaceName + "\n" + \
"-A POSTROUTING -s 10.8.0.0/8 -o " + publicInterfaceName + \
" -j MASQUERADE\n" + \
"COMMIT\n" + \
"# END OPENVPN RULES\n\n"
configFileEditor.addLineToBeginning(filename, insertLine, commentSignList = ["#"])
return
def enableUfwForwardedPackets(filename):
configFileEditor.replaceLineInFile(filename = filename,
keyword = "DEFAULT_FORWARD_POLICY",
newLine = "DEFAULT_FORWARD_POLICY=\"ACCEPT\"",
commentSignList =["#"],
count = 1)
return
def initializeCommandParser():
parser = argparse.ArgumentParser(description = "Change config files for openvpn installation")
parser.add_argument( "-m", "--mode", type=str, required=True, choices=argsMode.values(),
help="Mode for this script")
parser.add_argument( "-f", "--file", type=str, required=True, help="File name for the change")
parser.add_argument( "-p", "--pub", type=str, help="Public Interface Name")
parser.add_argument( "-o", "--old", type=str, help="Old line to be replaced (in quotes)")
parser.add_argument( "-n", "--new", type=str, help="New line in quotes")
return parser
def main(inputArgs):
# Initialize command line parser and parse
parser = initializeCommandParser()
parsedArgs = parser.parse_args(inputArgs)
filename = ""
publicInterfaceName = "eth0"
if parsedArgs.file != None:
filename = parsedArgs.file
if parsedArgs.pub != None:
publicInterfaceName = parsedArgs.pub
if parsedArgs.mode == argsMode.get("ipv4_mode"):
enableIpv4Forwarding(filename)
elif parsedArgs.mode == argsMode.get("ufw_before_rules_mode"):
changeUfwBeforeRules(filename, publicInterfaceName)
elif parsedArgs.mode == argsMode.get("ufw_forward_mode"):
enableUfwForwardedPackets(filename)
elif parsedArgs.mode == argsMode.get("replace_line_mode"):
if parsedArgs.old != None and parsedArgs.new != None:
configFileEditor.replaceLineInFile(filename = filename,
keyword = parsedArgs.old,
newLine = parsedArgs.new,
commentSignList = ["#",";"],
count = 1)
else:
print("Error: no -o and -n command specified in <replace> mode, please see help for instructions")
sys.exit(1)
# TODO: add command line parser
if __name__ == "__main__":
main(sys.argv[1:])
#enableIpv4Forwarding("./backup/sysctl.conf")
#changeUfwBeforeRules("test", "eth0")
| true |
de6573fc2615e0302df55881f0cadef5992cdc8f | Python | quandl/quandl-python | /test/factories/dataset_data.py | UTF-8 | 418 | 2.53125 | 3 | [
"MIT"
] | permissive | import factory
import six
class DatasetDataFactory(factory.Factory):
class Meta:
model = dict
column_names = [six.u('Date'), six.u('column.1'), six.u('column.2'), six.u('column.3')]
data = [['2015-07-11', 444.3, 10, 3], ['2015-07-13', 433.3, 4, 3],
['2015-07-14', 437.5, 3, 3], ['2015-07-15', 440.0, 2, 3]]
start_date = '2014-02-01'
end_date = '2015-7-29'
order = 'asc'
| true |
63e185b47b1c89805c200ee6a9b997719eeb20bb | Python | hanwjdgh/NLU-basic | /2. Preprocessing/8. One-hot encoding/test2.py | UTF-8 | 850 | 3.375 | 3 | [] | no_license | from keras_preprocessing.text import Tokenizer
text="나랑 점심 먹으러 갈래 점심 메뉴는 햄버거 갈래 갈래 햄버거 최고야"
t = Tokenizer()
t.fit_on_texts([text]) # [] 형태 주의
print(t.word_index)
"""
→ {'갈래': 1, '점심': 2, '햄버거': 3, '나랑': 4, '먹으러': 5, '메뉴는': 6, '최고야': 7}
"""
vocab_size = len(t.word_index)
from keras.utils import to_categorical
x = to_categorical(x, num_classes=vocab_size+1) # 실제 단어 집합의 크기보다 +1로 크기를 만들어야함.
# 자동으로 원-핫 인코딩을 만들어 주는 유용한 도구
print(x)
"""
→
[[0. 0. 1. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 1. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 1. 0.]
[0. 0. 0. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 1.]]
""" | true |
921028ed3aeb1af2351ad7fbae21b8d47023d91c | Python | jackdewinter/pymarkdown | /pymarkdown/application_configuration_helper.py | UTF-8 | 7,398 | 2.953125 | 3 | [
"MIT"
] | permissive | """
Module to handle the processing of configuration for the application.
"""
import argparse
import json
import logging
import os
from typing import Callable, Optional
import yaml
from application_properties import (
ApplicationProperties,
ApplicationPropertiesJsonLoader,
ApplicationPropertiesUtilities,
ApplicationPropertiesYamlLoader,
)
LOGGER = logging.getLogger(__name__)
# pylint: disable=too-few-public-methods
class ApplicationConfigurationHelper:
"""
Class to handle the processing of configuration for the application.
"""
__default_configuration_file = ".pymarkdown"
__default_yaml_configuration_file_extension = ".yaml"
__other_default_yaml_configuration_file_extension = ".yml"
@staticmethod
def apply_configuration_layers(
args: argparse.Namespace,
properties: ApplicationProperties,
handle_error: Callable[[str, Optional[Exception]], None],
) -> None:
"""
Apply any general python configuration files followed by any configuration
files specific to this project.
"""
LOGGER.debug("Looking for any standard python configuration files.")
ApplicationPropertiesUtilities.process_standard_python_configuration_files(
properties, handle_error
)
LOGGER.debug("Looking for application specific configuration files.")
ApplicationConfigurationHelper.__process_project_specific_json_configuration(
args,
properties,
handle_error,
)
@staticmethod
def __process_project_specific_json_configuration(
args: argparse.Namespace,
application_properties: ApplicationProperties,
handle_error_fn: Callable[[str, Optional[Exception]], None],
) -> None:
"""
Load configuration information from JSON configuration files.
"""
# Look for the default configuration files in the current working directory.
ApplicationConfigurationHelper.__process_default_configuration_files(
application_properties, handle_error_fn
)
# A configuration file specified on the command line has a higher precedence
# than anything except a specific setting applied on the command line.
if args.configuration_file:
if not os.path.isfile(args.configuration_file):
handle_error_fn(
f"Specified configuration file `{args.configuration_file}` does not exist.",
None,
)
LOGGER.debug(
"Determining file type for specified configuration file '%s'.",
args.configuration_file,
)
try:
with open(args.configuration_file, encoding="utf-8") as infile:
json.load(infile)
did_load_as_json = True
except json.decoder.JSONDecodeError:
did_load_as_json = False
try:
with open(args.configuration_file, "rb") as infile:
loaded_document = yaml.safe_load(infile)
did_load_as_yaml = not isinstance(loaded_document, str)
except yaml.MarkedYAMLError:
did_load_as_yaml = False
if did_load_as_json:
LOGGER.debug(
"Attempting to load configuration file '%s' as a JSON file.",
args.configuration_file,
)
ApplicationPropertiesJsonLoader.load_and_set(
application_properties,
args.configuration_file,
handle_error_fn=handle_error_fn,
clear_property_map=False,
check_for_file_presence=False,
)
elif did_load_as_yaml:
LOGGER.debug(
"Attempting to load configuration file '%s' as a YAML file.",
args.configuration_file,
)
ApplicationPropertiesYamlLoader.load_and_set(
application_properties,
args.configuration_file,
handle_error_fn=handle_error_fn,
clear_property_map=False,
check_for_file_presence=False,
)
else:
formatted_error = f"Specified configuration file '{args.configuration_file}' was not parseable as a JSON file or a YAML file."
LOGGER.warning(formatted_error)
handle_error_fn(formatted_error, None)
# A specific setting applied on the command line has the highest precedence.
if args.set_configuration:
LOGGER.debug(
"Attempting to set one or more provided manual properties '%s'.",
args.set_configuration,
)
application_properties.set_manual_property(args.set_configuration)
@staticmethod
def __process_default_configuration_files(
application_properties: ApplicationProperties,
handle_error_fn: Callable[[str, Optional[Exception]], None],
) -> None:
abs_file_name = os.path.abspath(
ApplicationConfigurationHelper.__default_configuration_file
)
LOGGER.debug(
"Attempting to find/load '%s' as a default JSON configuration file.",
abs_file_name,
)
(
did_apply_map,
did_have_one_error,
) = ApplicationPropertiesJsonLoader.load_and_set(
application_properties,
abs_file_name,
handle_error_fn=handle_error_fn,
clear_property_map=False,
check_for_file_presence=True,
)
if not did_apply_map and not did_have_one_error:
new_file_name = (
abs_file_name
+ ApplicationConfigurationHelper.__default_yaml_configuration_file_extension
)
LOGGER.debug(
"Attempting to find/load '%s' as a default YAML configuration file.",
new_file_name,
)
(
did_apply_map,
did_have_one_error,
) = ApplicationPropertiesYamlLoader.load_and_set(
application_properties,
new_file_name,
handle_error_fn=handle_error_fn,
clear_property_map=False,
check_for_file_presence=True,
)
if not did_apply_map and not did_have_one_error:
new_file_name = (
abs_file_name
+ ApplicationConfigurationHelper.__other_default_yaml_configuration_file_extension
)
LOGGER.debug(
"Attempting to find/load '%s' as a default YAML configuration file.",
new_file_name,
)
(
did_apply_map,
did_have_one_error,
) = ApplicationPropertiesYamlLoader.load_and_set(
application_properties,
new_file_name,
handle_error_fn=handle_error_fn,
clear_property_map=False,
check_for_file_presence=True,
)
if not did_apply_map:
LOGGER.debug("No default configuration files were loaded.")
# pylint: enable=too-few-public-methods
| true |
baaabd88a30af5883c6623b55b0c1495679848f0 | Python | lgaud/minesweeper | /game/views.py | UTF-8 | 1,837 | 2.546875 | 3 | [] | no_license | import json
from django.shortcuts import render, get_object_or_404, redirect
from django.http import Http404, JsonResponse
from django.db.models import Avg, Min
from .models import Game
# Create your views here.
def index(request):
return render(request, 'game/index.html')
def create_game(request):
rows = int(request.POST['rows'])
columns = int(request.POST['columns'])
mines = int(request.POST['mines'])
game = Game(x_cells=columns, y_cells=rows, num_mines=mines)
game.create_game()
return redirect('game', game_id=game.id)
def game(request, game_id):
game = get_object_or_404(Game, pk=game_id)
grid = game.get_display_grid()
# add clear logic
context = {
'game_id': game_id,
'state': game.state,
'grid': grid,
}
return render(request, 'game/game.html', context)
def reveal(request, game_id):
x = int(request.POST['x'])
y = int(request.POST['y'])
game = get_object_or_404(Game, pk=game_id)
result = game.reveal_cell(x, y)
return JsonResponse(result)
def toggle_marking(request, game_id):
x = int(request.POST['x'])
y = int(request.POST['y'])
game = get_object_or_404(Game, pk=game_id)
result = game.toggle_cell_marking(x, y)
return JsonResponse({"state": result})
def stats(request):
total_games_won = Game.objects.filter(state="W").count()
total_games_lost = Game.objects.filter(state="L").count()
total_games_completed = total_games_won + total_games_lost
unlucky = Game.objects.filter(state="L", num_moves=1).count()
context = {
'total_games_completed': total_games_completed,
'total_games_won': total_games_won,
'total_games_lost': total_games_lost,
'unlucky': unlucky
}
return render(request, 'game/stats.html', context) | true |
35264ce64598d8bebcec6ac2e140a7ed37d777e4 | Python | AKuiY/CarND-Traffic-Sign-Classifier-Project | /iamge.py | UTF-8 | 735 | 2.921875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 20 10:33:22 2017
@author: yang
"""
from skimage import exposure
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
imgpath = "new-traffic-signs/11.jpg"
image = mpimg.imread(imgpath)
#Convert to single channel Y
y_image = 0.299 * image[:, :, 0] + 0.587 * image[:, :, 1] + 0.114 * image[:, :, 2]
plt.figure()
plt.subplot(2,2,1)
plt.imshow(image)
plt.subplot(2,2,2)
plt.imshow(y_image,cmap='gray')
nom_image = (y_image / 255.).astype(np.float32)
sharp_image = exposure.equalize_adapthist(nom_image)
sharp_image = (sharp_image*255)
plt.figure()
plt.subplot(2,2,1)
plt.imshow(nom_image,cmap='gray')
plt.subplot(2,2,2)
plt.imshow(sharp_image,cmap='gray') | true |
b64bb085a01bfad241eeae90c9c85c5ec986b975 | Python | Shadybloom/amber-in-the-dark | /scripts/dict/amber_model_factories_cloth.py | UTF-8 | 93,325 | 2.734375 | 3 | [
"WTFPL"
] | permissive | #----
# Заметки:
# Ширина холста (ручное ткачество) -- 36-38 сантиметров
# https://ru.wikisource.org/wiki/ЭСБЕ/Хлопчатобумажные_ткани
# https://ru.wikisource.org/wiki/ЭСБЕ/Бумагопрядение
# https://ru.wikisource.org/wiki/ЭСБЕ/Хлопчатобумажное_производство
# https://ru.wikisource.org/wiki/ЭСБЕ/Исследование_прядильных_волокон
# https://ru.wikisource.org/wiki/ЭСБЕ/Волокнистые_вещества
# НОРМЫ ТЕХНОЛОГИЧЕСКОГО ПРОЕКТИРОВАНИЯ ПРЕДПРИЯТИЙ ЛЕГКОЙ ПРОМЫШЛЕННОСТИ
# РАЗДЕЛ 15. ШВЕЙНАЯ ПРОМЫШЛЕННОСТЬ:
# http://www.libussr.ru/doc_ussr/usr_12954.htm
#----
# Производства (судовое имущество)
metadict_detail['_Производство утвари, парус 100x100 (брезент)'] = {
# Некоторые паруса имеют нашивки:
# https://ru.wikisource.org/wiki/ЭСБЕ/Бант
# Паруса связывают вертикальными стежками, прочным пеньковым шнуром.
'Ткань льняная, брезент (квадратный метр)':1.0 / 0.95,
'Бечева пеньковая швейная (метр)':10,
'+Ткань льняная, лоскуты (доступно/квадратный метр)':((1.0 / 0.95) - 1.0) * 1,
}
#----
# Производства (экипировка)
metadict_detail['_Производство одежды, пояс страховой (джут)'] = {
# Для строителей, широкий ремень под брюхо с креплениями для канатов
'_Производство утвари текстильной (рабочих часов)':5 / 60,
'Ткань джутовая, ковровая (квадратный метр)':0.1 * 1.0 / 0.9,
'Бечева пеньковая швейная (метр)':2.2,
}
metadict_detail['_Производство одежды, маска (хлопок)'] = {
# Пылевая маска, для рабочих. Лучше чем ничего.
# Голова, шея, капюшон: 0.4 × 0.4 × 3 = 0.48 м²
# Ушки: 0.15 × 0.25 × 2 × 2 = 0.15 м²
# Всего 0.65 кв.м ткани. Выкройка 95%
'_Производство одежды (рабочих часов)':0.2,
'Ткань хлопчатая, бязь (квадратный метр)':0.65 / 0.95,
'Нить хлопчатая швейная (метр)':100,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':((0.65 / 0.95) - 0.65),
}
#----
# Производства (утварь)
metadict_detail['_Производство утвари, ковёр 100x100 (хлопок)'] = {
# 1.0 × 1.0 = 1 м²
'_Производство утвари текстильной (рабочих часов)':5 / 60,
'Ткань хлопчато-джутовая, ковровая (квадратный метр)':1.0 * 1.0,
'Нить джутовая швейная (метр)':(1.0 + 1.0) * 2 * 4,
}
metadict_detail['_Производство утвари, ковёр 100x100 (джут)'] = {
'_Производство утвари текстильной (рабочих часов)':2 / 60,
'Ткань джутовая, ковровая (квадратный метр)':1.0 * 1.0,
'Нить джутовая швейная (метр)':(1.0 + 1.0) * 2 * 4,
}
metadict_detail['_Производство утвари, ковёр 100x100 (солома)'] = {
# Используются также и в строительстве.
# Производство соломенных ковров.
'Соломенные ковры 25-мм (квадратный метр)':1,
}
metadict_detail['_Производство утвари, шторы 100x100 (хлопок)'] = {
'_Производство утвари текстильной (рабочих часов)':3 / 60,
'Ткань хлопчатая, бязь (квадратный метр)':1.0 * 1.0,
'Нить хлопчатая швейная (метр)':(1.0 + 1.0) * 2 * 4,
}
metadict_detail['_Производство утвари, шторы 100x100 (брезент)'] = {
# Водонепроницаемые.
'_Производство утвари текстильной (рабочих часов)':3 / 60,
'Ткань льняная, брезент (квадратный метр)':1.0 * 1.0,
'Нить льняная швейная (метр)':(1.0 + 1.0) * 2 * 4,
}
metadict_detail['_Производство утвари, скатерть 220x130 (хлопок)'] = {
# 2.2 × 1.3 = 2.86 м²
'_Производство утвари текстильной (рабочих часов)':5 / 60,
'Ткань хлопчатая, бязь (квадратный метр)':2.2 * 1.3,
'Нить хлопчатая швейная (метр)':(2.2 + 1.3) * 2 * 4,
}
metadict_detail['_Производство утвари, полотенце 40x60 вафельное (хлопок)'] = {
# 0.4 × 0.6 = 0.24 м²
'_Производство утвари текстильной (рабочих часов)':1 / 60,
'Ткань хлопчатая, вафельная (квадратный метр)':0.4 * 0.6,
'Нить хлопчатая швейная (метр)':(0.4 + 0.6) * 2 * 4,
}
metadict_detail['_Производство утвари, полотенце 50x90 вафельное (хлопок)'] = {
'_Производство утвари текстильной (рабочих часов)':2 / 60,
'Ткань хлопчатая, вафельная (квадратный метр)':0.5 * 0.9,
'Нить хлопчатая швейная (метр)':(0.5 + 0.9) * 2 * 4,
}
metadict_detail['_Производство утвари, полотенце 70x140 махровое (хлопок)'] = {
'_Производство утвари текстильной (рабочих часов)':5 / 60,
'Ткань хлопчатая, махровая (квадратный метр)':0.7 * 1.4,
'Нить хлопчатая швейная (метр)':(0.7 + 1.4) * 2 * 8,
}
metadict_detail['_Производство утвари, холст 80x120 (лён)'] = {
# 0.8 × 1.2 = 0.96 м²
'_Производство утвари текстильной (рабочих часов)':1 / 60,
'Ткань льняная, мешковина (квадратный метр)':0.9 * 1.2,
'Нить хлопчатая швейная (метр)':(0.9 + 1.2) * 2 * 4,
}
metadict_detail['_Производство утвари, мешочек (лён)'] = {
# 0.2 × 0.2 = 0.04 м²
'_Производство утвари текстильной (рабочих часов)':1 / 60,
'Ткань льняная, мешковина (квадратный метр)':0.2 * 0.2 * 2,
'Нить хлопчатая швейная (метр)':(0.2 + 0.2) * 2 * 4,
}
metadict_detail['_Производство утвари, сито (джут)'] = {
# 0.2 × 0.2 = 0.04 м²
'_Производство утвари текстильной (рабочих часов)':1 / 60,
'Ткань джутовая (квадратный метр)':0.2 * 0.2,
}
metadict_detail['_Производство утвари, решето (джут)'] = {
# 0.5 × 0.5 = 0.25 м²
'_Производство утвари текстильной (рабочих часов)':3 / 60,
'Ткань джутовая (квадратный метр)':0.5 * 0.5,
}
metadict_detail['_Производство утвари, мешок 100-литровый, 50x50x60 (джут)'] = {
# Высота -- 0.6 метра, радиус -- 0.25 метра. Форма цилиндрическая.
# Площадь цилиндра: 2 * 3.14 * 0.25 * (0.6 + 0.25) = 1.34 кв.метра
# Объём цилиндра: 3.14 * 0.25 ^ 2 * 0.6 = 1.18 кубометров (заполнение 85%)
'_Производство утвари текстильной (рабочих часов)':2 / 60,
'Ткань джутовая (квадратный метр)':2 * 3.14 * 0.25 * (0.6 + 0.25),
'Нить джутовая швейная (метр)':(0.5 + 0.6) * 4,
}
metadict_detail['_Производство утвари, ветошь (лоскуты)'] = {
# Бывшее полотенце, кусок простыни, скатерти, одежды.
# 0.4 × 0.6 = 0.24 м²
'_Производство утвари текстильной (рабочих часов)':1 / 60,
'-Ткань, лоскуты (требуется/квадратный метр)':0.4 * 0.6,
}
#----
# Производства (бельё)
# Площадь одежды (размеры для людей):
# Площадь тела человека — 1.8 м²
# Простыня: 1.5 × 2 = 3 м²
# Одеяло: 1.5 × 2 × 2 = 6 м²
# Подушка: 0.6 × 0.6 × 2 = 0.72 м²
# Матрац: 0.7 × 1.9 × 2 = 2.7 м²
metadict_detail['_Производство белья, матрац (вата)'] = {
# Вата 6 см -- 1.5 кг/кв.метр
# Чехол (бязь) -- 2.7 кв.метра
# Пикование (прошивка): 40+40 нитей на метр матраца
'_Производство белья (рабочих часов)':60 / 60,
'Ткань хлопчатая, бязь (квадратный метр)':0.7 * 1.9 * 2,
'Ватная подкладка 6-см (квадратный метр)':0.7 * 1.9,
'Нить хлопчатая швейная (метр)':(0.7 * 1.9) * (40 + 40),
}
metadict_detail['_Производство белья, одеяло стёганное (вата)'] = {
# Вата 3 см -- 0.75 кг/кв.метр
# Чехол (бязь) -- 6 кв.метра
# Пикование (прошивка): 40+40 нитей на метр матраца
'_Производство белья (рабочих часов)':60 / 60,
'Ткань хлопчатая, бязь (квадратный метр)':1.5 * 2.0 * 2,
'Ватная подкладка 3-см (квадратный метр)':1.5 * 2.0,
'Нить хлопчатая швейная (метр)':(1.5 * 2.0) * (40 + 40),
}
metadict_detail['_Производство белья, подушка стёганная (вата)'] = {
# Вата 12 см -- 3 кг/кв.метр
# Чехол (бязь) -- 0.72 кв.метра
# Есть мнение, что вата для набивки не годится.
'_Производство белья (рабочих часов)':10 / 60,
'Ткань хлопчатая, бязь (квадратный метр)':0.6 * 0.6 * 2,
'Ватная подкладка 12-см (квадратный метр)':0.6 * 0.6,
}
metadict_detail['_Производство белья, простыня (хлопок)'] = {
'_Производство белья (рабочих часов)':6 / 60,
'Ткань хлопчатая, бязь (квадратный метр)':1.5 * 2.0,
'Нить хлопчатая швейная (метр)':(1.5 + 2.0) * 2 * 4,
}
metadict_detail['_Производство белья, простыня махровая (хлопок)'] = {
'_Производство белья (рабочих часов)':6 / 60,
'Ткань хлопчатая, махровая (квадратный метр)':1.5 * 2.0,
'Нить хлопчатая швейная (метр)':(1.5 + 2.0) * 2 * 4,
}
metadict_detail['_Производство белья, одеяло лоскутное (вата)'] = {
# Делается сельской единорожкой из старой одежды, поэтому трудозатраты выше.
# Вата 3 см -- 0.75 кг/кв.метр
# Чехол (бязь) -- 6 кв.метра
# Пикование (прошивка): 20+20 нитей на метр матраца
'_Производство белья (рабочих часов)':120 / 60,
'Ватная подкладка 3-см (квадратный метр)':1.5 * 2.0,
'Нить хлопчатая швейная (метр)':(1.5 * 2.0) * (20 + 20),
'-Ткань, лоскуты (требуется/квадратный метр)':1.5 * 2.0 * 2,
}
metadict_detail['_Производство белья, простыня (парусина)'] = {
# Прошивается по краю в 4 нити
'_Производство белья (рабочих часов)':6 / 60,
'Ткань полульняная, парусина (квадратный метр)':1.5 * 2.0,
'Нить льняная швейная (метр)':(1.5 + 2.0) * 2 * 4,
}
metadict_detail['_Производство белья, чехол тюфяка (мешковина)'] = {
# По сути мешок, набитый соломой.
'_Производство белья (рабочих часов)':6 / 60,
'Ткань льняная, мешковина (квадратный метр)':0.9 * 2.0,
'Нить льняная швейная (метр)':(0.9 + 2.0) * 2 * 4,
}
#----
# Производства (одежда)
# Нормы расхода швейных ниток на различные виды швейных изделий
# http://www.modnaya.ru/library/012/012.htm
# http://www.modnaya.ru/library/012/013.htm
# Производство одежды:
# Брюки (фабрика) -- 2.5 нормо-часов/пара
# Жилеты (фабрика) -- 0.37 нормо-часа/штука
# Жакеты (фабрика) -- 0.92 нормо-часа/штука
# *Костюмы (фабрика) -- 8 нормо-часов/штука
# Пальто (фабрика) -- 8 нормо-часов/штука
# Рубаха (ручной труд) -- 4 нормо-часов/штука
# Износ -- 3 комплекта рубах и панталон в год, 2 костюма, 1 пальто, 1 ботинки.
# * Костюм -- 3 метра шерстяной ткани, 1.5 кг
# https://istmat.org/node/27433
# Пропорции пони:
# https://raw.githubusercontent.com/Shadybloom/amber-in-the-dark/master/images/glow.png
# Рост в холке — 75 см
# Рост в ушках — 120 см
# Длина передних ног — 50 см (до перехода в грудь, если смотреть спереди)
# Длина задней ноги до сустава — 48 см
# Диаметр копыта (мера длины, хуф) — 10 см
# Длина тела (от хвоста до груди) — 45 см
# Ширина тела (груди) — 35 см
# Размеры головы:
# Длина — 40 см (от кончика носа до затылка)
# Ширина — 40 см (от скулы до скулы)
# Высота — 32 см (от затылка до шеи)
# Площадь тела пони — 1.75 м²
metadict_detail['_Производство одежды, бушлат (хлопок)'] = {
# Замшевый бушлат, короткое пальто, Peacoat.
# https://derpibooru.org/images/2383102
# https://derpibooru.org/images/2225845
# https://upload.wikimedia.org/wikipedia/commons/2/22/US_Navy_p_coat_wiki.jpg
# На 20 см ниже живота:
# Грудь, круп: 0,4 × 0,4 × 2 = 0,32 м²
# Спина, живот: 0,5 × 0,4 × 2 = 0.4 м²
# Рукава, на все 4 ноги: ((2 × 3,14 × 0,05 × (0,05 + (20 / 50))) × (20 / 50)) × 4 = 0.23 м²
# Бока, круп, полы: 0.5 × (0,4 + 0.2) × 3 = 0,9 м²
# Всего 1.85 кв.м ткани. Выкройка 85%
'_Производство одежды (рабочих часов)':8,
'Ткань хлопчатая, замша (квадратный метр)':1.85 / 0.85,
'Ткань хлопчатая, сатин (квадратный метр)':1.85 / 0.85 * 2,
'Ватная подкладка 1-см (квадратный метр)':1.85,
'Нить хлопчатая швейная (метр)':600,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':((1.85 / 0.85) - 1.85) * 3,
}
metadict_detail['_Производство одежды, пальто (хлопок)'] = {
# Простонародная одежда. Trenchcoat
# Всепогодное защитное снаряжение пегасов и множества прочих работяг.
# В огромном количестве производится для погодной службы. Без одежды невесело летать.
# https://derpibooru.org/images/1931802
# Всего 1.85 кв.м ткани. Выкройка 85%
'_Производство одежды (рабочих часов)':8,
'Ткань полульняная, парусина (квадратный метр)':1.85 / 0.85,
'Ткань хлопчатая, бязь (квадратный метр)':1.85 / 0.85 * 2,
'Ватная подкладка 1-см (квадратный метр)':1.85,
'Нить хлопчатая швейная (метр)':600,
'+Ткань льняная, лоскуты (доступно/квадратный метр)':((1.85 / 0.85) - 1.85) * 1,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':((1.85 / 0.85) - 1.85) * 2,
}
metadict_detail['_Производство одежды, кафтан (хлопок)'] = {
# Зимний, с поясом. Удобно надевать и снимать для земнопони.
# На 30 см ниже живота:
# Грудь: 0,4 × 0,4 × 1 = 0,16 м²
# Спина, живот: 0,5 × 0,4 × 2 = 0.4 м²
# Рукава, на 2 ноги: ((2 × 3,14 × 0,05 × (0,05 + (30 / 50))) × (30 / 50)) × 2 = 0.25 м²
# Бока, круп, полы: 0.5 × (0,4 + 0.3) × 3 = 1,05 м²
# https://derpibooru.org/images/2224134
# https://derpibooru.org/images/1640096
# Всего 1.86 кв.м ткани. Выкройка 85%
'_Производство одежды (рабочих часов)':8,
'Ткань хлопчатая, бархат (квадратный метр)':1.85 / 0.85,
'Ткань хлопчатая, сатин (квадратный метр)':1.85 / 0.85 * 2,
'Ватная подкладка 1-см (квадратный метр)':1.85,
'Нить хлопчатая швейная (метр)':600,
'Нить хлопчатая швейная (метр)':430,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':((1.85 / 0.85) - 1.85) * 3,
}
metadict_detail['_Производство одежды, платье (хлопок)'] = {
# Красиво облегает всё тело. Если собственная шёрстка недостаточно хороша.
# На 30 см ниже живота:
# Грудь, круп: 0,4 × 0,4 × 2 = 0,32 м²
# Спина, живот: 0,5 × 0,4 × 2 = 0.4 м²
# Рукава, на все 4 ноги: ((2 × 3,14 × 0,05 × (0,05 + (30 / 50))) × (30 / 50)) × 4 = 0.5 м²
# Бока, круп, полы: 0.5 × (0,4 + 0.3) × 3 = 1,05 м²
# https://derpibooru.org/images/2609193
# Всего 2.3 кв.м ткани. Выкройка 85%
'_Производство одежды (рабочих часов)':8,
'Ткань хлопчатая, бархат (квадратный метр)':2.3 / 0.85,
'Нить хлопчатая швейная (метр)':450,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':((2.3 / 0.85) - 2.3),
}
metadict_detail['_Производство одежды, жакет (хлопок)'] = {
# Рубаха с рукавами на половину длины передних ног:
# На 30 см ниже живота:
# Грудь, круп: 0,4 × 0,4 × 2 = 0,32 м²
# Спина, живот, бока: 0,5 × 0,4 × 4 = 0.8 м²
# Рукава, на 2 ноги: ((2 × 3,14 × 0,05 × (0,05 + (30 / 50))) × (30 / 50)) × 2 = 0.25 м²
# https://derpibooru.org/images/1188131
# Всего 1.37 кв.м ткани. Выкройка 85%
'_Производство одежды (рабочих часов)':2,
'Ткань хлопчатая, замша (квадратный метр)':1.4 / 0.85,
'Ткань хлопчатая, сатин (квадратный метр)':1.4 / 0.85,
'Нить хлопчатая швейная (метр)':280,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':((1.4 / 0.85) - 1.4) * 2,
}
metadict_detail['_Производство одежды, пиджак (хлопок)'] = {
# Рубаха с рукавами на половину длины передних ног:
# Всего 1.37 кв.м ткани. Выкройка 85%
'_Производство одежды (рабочих часов)':2,
'Ткань хлопчатая, замша (квадратный метр)':1.4 / 0.85,
'Ткань хлопчатая, сатин (квадратный метр)':1.4 / 0.85,
'Нить хлопчатая швейная (метр)':250,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':((1.4 / 0.85) - 1.4) * 2,
}
metadict_detail['_Производство одежды, жилет (хлопок)'] = {
# Безрукавка, защита груди под упряжь. Как у Брейбёрна.
# Грудь, круп: 0,4 × 0,4 × 2 = 0,32 м²
# Спина, живот, бока: (0,5 / 2) × 0,4 × 4 = 0.4 м²
# https://mlp.fandom.com/wiki/Braeburn
# Всего 0.7 кв.м ткани. Выкройка 85%
'_Производство одежды (рабочих часов)':1,
'Ткань хлопчатая, замша (квадратный метр)':0.7 / 0.85,
'Ткань хлопчатая, сатин (квадратный метр)':0.7 / 0.85,
'Нить хлопчатая швейная (метр)':200,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':((0.7 / 0.85) - 0.7) * 2,
}
metadict_detail['_Производство одежды, жилет (парусина)'] = {
# Всего 0.7 кв.м ткани. Выкройка 85%
'_Производство одежды (рабочих часов)':0.4,
'Ткань полульняная, парусина (квадратный метр)':0.7 / 0.85,
'Нить льняная швейная (метр)':200,
'+Ткань льняная, лоскуты (доступно/квадратный метр)':((0.7 / 0.85) - 0.7),
}
metadict_detail['_Производство одежды, плащ (хлопок)'] = {
# Зимний, с завязкой на груди. С капюшоном и ушками.
# На 30 см ниже живота:
# Грудь: 0,4 × 0,4 × 1 = 0,16 м²
# Спина: 0,5 × 0,4 × 1 = 0.2 м²
# Бока, круп, полы: 0.5 × (0,4 + 0.3) × 3 = 1,05 м²
# Голова, шея, капюшон: 0.4 × 0.4 × 3 = 0.48 м²
# Ушки: 0.15 × 0.25 × 2 × 2 = 0.15 м²
# Всего 2.04 кв.м ткани. Выкройка 95%
'_Производство одежды (рабочих часов)':1,
'Ткань хлопчатая, замша (квадратный метр)':2.1 / 0.95,
'Ткань хлопчатая, сатин (квадратный метр)':2.1 / 0.95 * 2,
'Ватная подкладка 1-см (квадратный метр)':2.1,
'Нить хлопчатая швейная (метр)':380,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':((2.1 / 0.95) - 2.1) * 3,
}
metadict_detail['_Производство одежды, плащ (брезент)'] = {
# Тёплый и непромокаемый. Для простых и практичных пони.
# Всего 2.04 кв.м ткани. Выкройка 95%
'_Производство одежды (рабочих часов)':1,
'Ткань льняная, брезент (квадратный метр)':2.1 / 0.95,
'Ткань хлопчатая, бязь (квадратный метр)':2.1 / 0.95 * 2,
'Ватная подкладка 1-см (квадратный метр)':2.1,
'Нить льняная швейная (метр)':380,
'+Ткань льняная, лоскуты (доступно/квадратный метр)':((2.1 / 0.95) - 2.1) * 1,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':((2.1 / 0.95) - 2.1) * 2,
}
metadict_detail['_Производство одежды, ветровка (брезент)'] = {
# Рубаха с рукавами на половину длины передних ног. С капюшоном и ушками.
# На 30 см ниже живота:
# Грудь, круп: 0,4 × 0,4 × 2 = 0,32 м²
# Спина, живот, бока: 0,5 × 0,4 × 4 = 0.8 м²
# Рукава, на 2 ноги: ((2 × 3,14 × 0,05 × (0,05 + (30 / 50))) × (30 / 50)) × 2 = 0.25 м²
# Голова, шея, капюшон: 0.4 × 0.4 × 3 = 0.48 м²
# Ушки: 0.15 × 0.25 × 2 × 2 = 0.15 м²
# https://derpibooru.org/images/1605206
# https://derpibooru.org/images/1065758
# Всего 2.0 кв.м ткани. Выкройка 85%
'_Производство одежды (рабочих часов)':0.5,
'Ткань полульняная, парусина (квадратный метр)':2.0 / 0.85,
'Ткань хлопчатая, бязь (квадратный метр)':2.0 / 0.85,
'Нить льняная швейная (метр)':380,
'+Ткань льняная, лоскуты (доступно/квадратный метр)':((2.0 / 0.85) - 2.0),
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':((2.0 / 0.85) - 2.0),
}
metadict_detail['_Производство одежды, чепчик (хлопок)'] = {
# Тканевый платок, чтобы гриву не замарать.
# Голова, шея, капюшон: 0.4 × 0.4 × 3 = 0.48 м²
# Ушки: 0.15 × 0.25 × 2 × 2 = 0.15 м²
# Всего 0.65 кв.м ткани. Выкройка 95%
'_Производство одежды (рабочих часов)':0.2,
'Ткань хлопчатая, бязь (квадратный метр)':0.65 / 0.95,
'Нить хлопчатая швейная (метр)':100,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':((0.65 / 0.95) - 0.65),
}
metadict_detail['_Производство одежды, шапка (хлопок)'] = {
# Тёплая зимняя шапочка, вроде наших ушанок. С подстёжкой, чтобы уши не мёрзли.
# Всего 0.65 кв.м ткани. Выкройка 85%
'_Производство одежды (рабочих часов)':1,
'Ткань хлопчатая, замша (квадратный метр)':0.65 / 0.85,
'Ткань хлопчатая, бязь (квадратный метр)':0.65 / 0.85 * 2,
'Ватная подкладка 1-см (квадратный метр)':0.65,
'Нить хлопчатая швейная (метр)':100,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':((0.65 / 0.85) - 0.65) * 3,
}
metadict_detail['_Производство одежды, шляпа (солома)'] = {
# Широкополая, 10 см.
# Голова, шляпа, круг: 3.14 × (0.2 + 0.1) ^ 2 = 0.28 м²
# Голова, шляпа, цилиндр: (2 × 3,14 × 0,2) × 0,2 = 0.25 м²
# Всего 0.53 кв.м ткани. Выкройка 85%
'_Производство одежды (рабочих часов)':0.3,
'Ткань соломенная, домотканная (квадратный метр)':0.53 / 0.85,
'Нить льняная швейная (метр)':50,
}
metadict_detail['_Производство одежды, шляпа (хлопок)'] = {
# Летняя, с ремешком на подбородок.
# Всего 0.53 кв.м ткани. Выкройка 85%
'_Производство одежды (рабочих часов)':0.3,
'Ткань хлопчатая, замша (квадратный метр)':0.53 / 0.85,
'Нить хлопчатая швейная (метр)':50,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':((0.53 / 0.85) - 0.53),
}
metadict_detail['_Производство одежды, чулки (хлопок)'] = {
# На всю длину ног. Четвероногие, не забывай!
# Рукава, на 4 ноги: ((2 × 3,14 × 0,05 × (0,05 + 0.5)) × 0.5) × 4 = 0.34 м²
# Онучи были бы практичнее, но земным чулки удобнее.
# https://ru.wikipedia.org/wiki/Онучи
# Всего 0.35 кв.м ткани. Выкройка 95%
'_Производство одежды (рабочих часов)':0.8 * 2,
'Ткань хлопчатая, фланель (квадратный метр)':0.35 / 0.95,
'Нить хлопчатая швейная (метр)':220,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':((0.35 / 0.95) - 0.35),
}
#----
# Производства (обувь)
# Производство обуви:
# ботинки (ручной труд) -- 8 нормо-часов/пара,
# ботинки (фабрика, 200 рабочих) -- 1.83 нормо-часа/пара.
# Пара кожаной обуви -- 0.8 кг (материал 0.375 стоимости). Срок службы -- 1 год
# https://istmat.org/node/27431
# Нормы расходования ниток, клея, краски, растворителей, воска, парафина, грунта и т.д. на 100 пар обуви.
# http://shoeslib.ru/books/item/f00/s00/z0000004/index.shtml
metadict_detail['_Производство обуви, ботинки (кирза)'] = {
# TODO: Производство обуви. Допилить. Клей для обуви.
# Пропорции пони:
# Длина передних ног — 50 см (до перехода в грудь, если смотреть спереди)
# Длина задней ноги до сустава — 48 см
# Диаметр копыта (мера длины, хуф) — 10 см
# Размеры обуви:
# Площадь круга: S = Pi × r ^ 2
# Площадь цилиндра: S = 2 × Pi × r × (h + r)
# Высота туфель -- 10 см
# Высота ботинок -- 20 см
# Диаметр подошвы -- 12 см.
# Толщина жёсткой резиновой подошвы -- 2 см
# Площадь подошвы: 3.14 * 0.06 ** 2 = 0.01 кв.метра
# Площадь ткани (туфля): 2 * 3.14 * 0.06 * (0.1 + 0.06) = 0.06 кв.метра
# Площадь ткани (ботинок): 2 * 3.14 * 0.06 * (0.2 + 0.06) = 0.1 кв.метра
# Пони не имитируют текстуру кожи. Их накопытники обычно повторяют цвет верхней одежды.
# Пони -- четвероногие, посему и носят по четыре сапога.
'_Производство обуви (рабочих часов)':4 * 2,
'Ткань хлопчатая, махровая (квадратный метр)':0.1 * 4 / 0.9,
'Ткань хлопчато-каучуковая, кирзовая (квадратный метр)':0.1 * 4 / 0.9,
'Подошва резиновая, 3-см (квадратный метр)':0.01 * 4 / 0.9,
}
metadict_detail['_Производство обуви, галоши (резина)'] = {
# TODO: Галоши делают из каучука, отливом. Без кирзовой ткани.
'_Производство обуви (рабочих часов)':1 * 2,
'Ткань хлопчато-каучуковая, кирзовая (квадратный метр)':0.06 * 4 / 0.9,
'Подошва резиновая, 3-см (квадратный метр)':0.01 * 4 / 0.9,
}
metadict_detail['_Производство обуви, туфли (кирза)'] = {
'_Производство обуви (рабочих часов)':2 * 2,
'Ткань хлопчато-каучуковая, кирзовая (квадратный метр)':0.06 * 4 / 0.9,
'Подошва резиновая, 3-см (квадратный метр)':0.01 * 4 / 0.9,
}
metadict_detail['_Производство обуви, туфли (джут)'] = {
# Эспадрильи, двойная джутовая подошва.
'_Производство обуви (рабочих часов)':0.3 * 2,
'Ткань джутовая (квадратный метр)':0.06 * 4 / 0.9,
'Ткань джутовая, ковровая (квадратный метр)':(0.01 * 4) * 2 / 0.9,
}
#----
# Утилизация (экипировка)
metadict_detail['_Утилизация одежды, маска (хлопок)'] = {
'_-Утилизация одежды (нормо-часов)':2 / 60,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':0.65,
}
metadict_detail['_Утилизация одежды, пояс страховой (джут)'] = {
'_-Утилизация одежды (нормо-часов)':2 / 60,
'+Ткань джутовая, лоскуты (доступно/квадратный метр)':0.1 * 1.0,
}
#----
# Утилизация (утварь)
metadict_detail['_Утилизация утвари, шторы 100x100 (хлопок)'] = {
'_-Утилизация утвари (нормо-часов)':1 / 60,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':1.0 * 1.0,
}
metadict_detail['_Утилизация утвари, шторы 100x100 (брезент)'] = {
'_-Утилизация утвари (нормо-часов)':1 / 60,
'+Ткань льняная, лоскуты (доступно/квадратный метр)':1.0 * 1.0,
}
metadict_detail['_Утилизация утвари, полотенце 40x60 вафельное (хлопок)'] = {
'_-Утилизация утвари (нормо-часов)':1 / 60,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':0.4 * 0.6,
}
metadict_detail['_Утилизация утвари, полотенце 50x90 вафельное (хлопок)'] = {
'_-Утилизация утвари (нормо-часов)':1 / 60,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':0.5 * 0.9,
}
metadict_detail['_Утилизация утвари, полотенце 70x140 махровое (хлопок)'] = {
'_-Утилизация утвари (нормо-часов)':1 / 60,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':0.7 * 0.14,
}
metadict_detail['_Утилизация утвари, скатерть 220x130 (хлопок)'] = {
'_-Утилизация утвари (нормо-часов)':3 / 60,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':2.2 * 1.3,
}
metadict_detail['_Утилизация утвари, холст 80x120 (лён)'] = {
'_-Утилизация утвари (нормо-часов)':1 / 60,
'+Ткань льняная, лоскуты (доступно/квадратный метр)':0.9 * 1.2,
}
metadict_detail['_Утилизация утвари, мешочек (лён)'] = {
'_-Утилизация утвари (нормо-часов)':1 / 60,
'+Ткань льняная, лоскуты (доступно/квадратный метр)':0.2 * 0.2,
}
metadict_detail['_Утилизация утвари, мешок 100-литровый, 50x50x60 (джут)'] = {
'_-Утилизация утвари (нормо-часов)':1 / 60,
'+Ткань джутовая, лоскуты (доступно/квадратный метр)':0.4 * 0.4 * 5,
}
metadict_detail['_Утилизация утвари, сито (джут)'] = {
}
metadict_detail['_Утилизация утвари, решето (джут)'] = {
}
metadict_detail['_Утилизация утвари, ветошь (лоскуты)'] = {
}
metadict_detail['_Утилизация утвари, парус 100x100 (брезент)'] = {
'_-Утилизация утвари (нормо-часов)':5 / 60,
'+Ткань льняная, брезент, лоскуты (доступно/квадратный метр)':1,
}
metadict_detail['_Утилизация утвари, ковёр 100x100 (джут)'] = {
'_-Утилизация утвари (нормо-часов)':5 / 60,
'+Ткань джутовая, ковровая, лоскуты (доступно/квадратный метр)':1,
}
metadict_detail['_Утилизация утвари, ковёр 100x100 (хлопок)'] = {
# Ворс стирается на 50%, остаётся основа.
'_-Утилизация утвари (нормо-часов)':5 / 60,
'+Пакля хлопчатая (доступно/килограмм)':1,
'+Ткань джутовая, ковровая, лоскуты (доступно/квадратный метр)':1,
}
metadict_detail['_Утилизация утвари, ковёр 100x100 (солома)'] = {
# Солома и бечева стирается на 25%, ковры меняют раз в год.
'_-Утилизация утвари (нормо-часов)':1 / 60,
'+Солома ковровая (доступно/килограмм)':2.5 * 0.75,
'+Бечева пеньковая швейная (доступно/метр)':120 * 0.75,
}
#----
# Утилизация (бельё)
metadict_detail['_Утилизация белья, матрац (вата)'] = {
# Disassemble!
'_-Утилизация белья (нормо-часов)':10 / 60,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':0.7 * 1.9 * 2,
'+Вата техническая (доступно/кубометр)':0.7 * 1.9 * 0.06,
}
metadict_detail['_Утилизация белья, одеяло лоскутное (вата)'] = {
# 50% лоскутков всё ещё годятся в дело. На тряпки, например.
'+Ткань смешанная, лоскуты (доступно/квадратный метр)':(1.5 * 2.0 * 2) * 0.5,
'+Вата техническая (доступно/кубометр)':1.5 * 2.0 * 0.03,
'_-Утилизация белья (нормо-часов)':10 / 60,
}
metadict_detail['_Утилизация белья, одеяло стёганное (вата)'] = {
'_-Утилизация белья (нормо-часов)':10 / 60,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':1.5 * 2.0 * 2,
'+Вата техническая (доступно/кубометр)':1.5 * 2.0 * 0.03,
}
metadict_detail['_Утилизация белья, подушка стёганная (вата)'] = {
'_-Утилизация белья (нормо-часов)':1 / 60,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':0.6 * 0.6 * 2,
'+Вата техническая (доступно/кубометр)':0.6 * 0.6 * 0.12,
}
metadict_detail['_Утилизация белья, простыня (хлопок)'] = {
'_-Утилизация белья (нормо-часов)':1 / 60,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':1.5 * 2.0,
}
metadict_detail['_Утилизация белья, простыня махровая (хлопок)'] = {
'_-Утилизация белья (нормо-часов)':1 / 60,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':1.5 * 2.0,
}
metadict_detail['_Утилизация белья, простыня (парусина)'] = {
'_-Утилизация белья (нормо-часов)':1 / 60,
'+Ткань льняная, лоскуты (доступно/квадратный метр)':1.5 * 2.0,
}
metadict_detail['_Утилизация белья, чехол тюфяка (мешковина)'] = {
'_-Утилизация белья (нормо-часов)':1 / 60,
'+Ткань льняная, лоскуты (доступно/квадратный метр)':0.9 * 2.0,
}
#----
# Утилизация (одежда)
metadict_detail['_Утилизация одежды, бушлат (хлопок)'] = {
'_-Утилизация одежды (нормо-часов)':20 / 60,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':1.85 * 3,
'+Вата техническая (доступно/кубометр)':1.85 * 0.01,
}
metadict_detail['_Утилизация одежды, пальто (хлопок)'] = {
'_-Утилизация одежды (нормо-часов)':20 / 60,
'+Ткань льняная, лоскуты (доступно/квадратный метр)':1.85 * 1,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':1.85 * 2,
'+Вата техническая (доступно/кубометр)':1.85 * 0.01,
}
metadict_detail['_Утилизация одежды, платье (хлопок)'] = {
'_-Утилизация одежды (нормо-часов)':10 / 60,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':2.3,
}
metadict_detail['_Утилизация одежды, кафтан (хлопок)'] = {
'_-Утилизация одежды (нормо-часов)':20 / 60,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':1.85 * 3,
'+Вата техническая (доступно/кубометр)':1.85 * 0.01,
}
metadict_detail['_Утилизация одежды, плащ (хлопок)'] = {
'_-Утилизация одежды (нормо-часов)':10 / 60,
'+Ткань льняная, лоскуты (доступно/квадратный метр)':2.1 * 1,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':2.1 * 2,
'+Вата техническая (доступно/кубометр)':2.1 * 0.01,
}
metadict_detail['_Утилизация одежды, жакет (хлопок)'] = {
'_-Утилизация одежды (нормо-часов)':5 / 60,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':1.4 * 2,
}
metadict_detail['_Утилизация одежды, пиджак (хлопок)'] = {
'_-Утилизация одежды (нормо-часов)':5 / 60,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':1.4 * 2,
}
metadict_detail['_Утилизация одежды, жилет (хлопок)'] = {
'_-Утилизация одежды (нормо-часов)':5 / 60,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':0.7 * 2,
}
metadict_detail['_Утилизация одежды, чепчик (хлопок)'] = {
'_-Утилизация одежды (нормо-часов)':2 / 60,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':0.65,
}
metadict_detail['_Утилизация одежды, шапка (хлопок)'] = {
'_-Утилизация одежды (нормо-часов)':2 / 60,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':0.65 * 3,
}
metadict_detail['_Утилизация одежды, шляпа (хлопок)'] = {
'_-Утилизация одежды (нормо-часов)':2 / 60,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':0.53,
}
metadict_detail['_Утилизация одежды, чулки (хлопок)'] = {
'_-Утилизация одежды (нормо-часов)':2 / 60,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':0.95,
}
metadict_detail['_Утилизация одежды, жилет (парусина)'] = {
'_-Утилизация одежды (нормо-часов)':2 / 60,
'+Ткань льняная, лоскуты (доступно/квадратный метр)':0.7,
}
metadict_detail['_Утилизация одежды, ветровка (брезент)'] = {
'_-Утилизация одежды (нормо-часов)':2 / 60,
'+Ткань льняная, лоскуты (доступно/квадратный метр)':2.0,
'+Ткань хлопчатая, лоскуты (доступно/квадратный метр)':2.0,
}
metadict_detail['_Утилизация одежды, плащ (брезент)'] = {
'_-Утилизация одежды (нормо-часов)':10 / 60,
'+Ткань льняная, лоскуты (доступно/квадратный метр)':2.1 * 3,
'+Вата техническая (доступно/кубометр)':2.1 * 0.01,
}
metadict_detail['_Утилизация одежды, шляпа (солома)'] = {
# Лол, зачем?
}
#----
# Утилизация (обувь)
metadict_detail['_Утилизация обуви, ботинки (кирза)'] = {
'_-Утилизация обуви (нормо-часов)':5 / 60,
'+Ткань кирзовая, лоскуты (доступно/квадратный метр)':0.1 * 4,
'+Подошва резиновая, 3-см, старая (доступно/квадратный метр)':0.01 * 4,
}
metadict_detail['_Утилизация обуви, галоши (резина)'] = {
'_-Утилизация обуви (нормо-часов)':3 / 60,
'+Ткань кирзовая, лоскуты (доступно/квадратный метр)':0.06 * 4,
'+Подошва резиновая, 3-см, старая (доступно/квадратный метр)':0.01 * 4,
}
metadict_detail['_Утилизация обуви, туфли (кирза)'] = {
'_-Утилизация обуви (нормо-часов)':3 / 60,
'+Ткань кирзовая, лоскуты (доступно/квадратный метр)':0.06 * 4,
'+Подошва резиновая, 3-см, старая (доступно/квадратный метр)':0.01 * 4,
}
metadict_detail['_Утилизация обуви, туфли (джут)'] = {
'_-Утилизация обуви (нормо-часов)':3 / 60,
'+Ткань джутовая, лоскуты (доступно/квадратный метр)':0.06 * 4,
'+Ткань джутовая, ковровая, лоскуты (доступно/квадратный метр)':0.01 * 4,
}
#----
# Производства (текстильная промышленность)
# (Германия 1895 года, 52.5 млн. человек)
# https://istmat.org/node/27434
# Расход льняного полотна -- 0.8 кг/человека
# Производство шерстяной ткани -- 0.8 кг/человека (потребность 2 кг/человека)
#----
# Производства (шитьё)
# Профессии (Германия 1895 года, 52.5 млн. человек)
# Швей -- 55 на 10 000 населения
# Портных и портних -- 87 на 10 000 населения
# Конфекционных рабочих -- 11 на 10 000 населения
# Изготовителей украшений -- 10 на 10 000 населения
# На производстве обуви -- 77 на 10 000 населения
# Значительная часть одежды и белья изготавливается в семье
# - чулки (мелкий опт, 4 раб) -- 0.8 рубля/пара (6.4 нормо-часа)
# - рукавицы кожаные (мелкий опт, 12 раб) -- 0.4 рубля/пара (0.4 нормо-часа)
# - туфли (мелкий опт, 20 раб) -- 0.75 руб/пара (0.8 нормо-часа)
# - перчатки (опт, 45 раб) -- 0.7 руб/пара (1.44 нормо-часа)
# - фуражки (опт, 25 раб) -- 0,87 руб/штука (0.67 нормо-часа)
metadict_detail['_Производство белья (рабочих часов)'] = {
# В мастерской 12 рабочих, 19 200 нормо-часов/год
'_-Работа швеи (нормо-часов)':1,
'_Швейная мастерская (годовой оборот)':1 / 20000,
}
metadict_detail['_Производство утвари текстильной (рабочих часов)'] = {
'_-Работа швеи (нормо-часов)':1,
'_Швейная мастерская (годовой оборот)':1 / 20000,
}
metadict_detail['_Производство одежды (рабочих часов)'] = {
# Работа над одеждой требует лучших навыков:
'_-Работа портного (нормо-часов)':1,
'_Швейная мастерская (годовой оборот)':1 / 20000,
}
metadict_detail['_Производство обуви (рабочих часов)'] = {
'_-Работа сапожника (нормо-часов)':1,
'_Швейная мастерская (годовой оборот)':1 / 20000,
}
#----
# Производства (ткачество)
# Плотность материалов:
# бязь -- 120 грамм/кв.метр
# сатин -- 120 грамм/кв.метр
# сатин-жаккард -- 140 грамм/кв.метр
# Льняная ткань -- 150 грамм/кв.метр
# фланель -- 200 грамм/кв.метр
# бархат -- 300 грамм/кв.метр
# Хопчатобумажная замша -- 410 грамм/кв.метр
# Льняная парусина -- 450-550 грамм/кв.метр
# Вата швейная (набивка) -- 25 кг/кубометр
# Асбестовая ткань АТ-1С -- 1.6 мм, 1000 грамм/кв.метр (130-400°C)
# https://tessuti-ital.ru/news/plotnost-tkanej/
# https://ru.wikisource.org/wiki/ЭСБЕ/Хлопчатобумажные_ткани
# https://ru.wikisource.org/wiki/Категория:ЭСБЕ:Ткани
# https://ru.wikipedia.org/wiki/Список_типов_тканей
# https://ru.wikipedia.org/wiki/Шаблон:Текстиль
# http://asbestpromsnab.ru/production/asbestos-technical/insulation/asbestos-cloth
metadict_detail['_Производство бязи (квадратный метр)'] = {
# Бязь -- 120 грамм/кв.метр
# В мастерской 100 рабочих (две смены), 100 механических станков, 160 000 нормо-часов/год
# Единороги в наушниках. Работают из галереи над станками, чтобы пылью не дышать.
# Ткачи меняют катушки, правят обрывы и по мелочам чинят станки.
# Костромская губерня. Фабрика Коновалова, обработка хлопка:
# - Выработка ткани суровой -- 877 000 рублей/год
# - Выработка пряжи хлопчатобумажной -- 849 000 рублей/год
# - Число рабочих -- 1126 человек (1533 рубля/работника)
# - Паровые двигатели -- 1730 лошадиных сил (1300 кВт, 1.15 кВт/человека)
# https://istmat.org/node/26498
# Трудозатраты 0.6 нормо-часов/кв.метр
'_-Производство бязи (квадратный метр)':1,
'_-Беление ткани хлорной известью и содой (килограмм)':0.12,
'_-Окраска тканей аниловыми красками (килограмм)':0.12,
'Пряжа хлопчатая (килограмм)':0.12 / 0.95,
'_Ткацкая мастерская (годовой оборот)':1 / (160000 / 0.6),
}
metadict_detail['_Производство вафельной ткани (квадратный метр)'] = {
# https://ru.wikisource.org/wiki/ЭСБЕ/Хлопчатобумажные_ткани
'_-Производство вафельной ткани (квадратный метр)':1,
'_-Беление ткани хлорной известью и содой (килограмм)':0.2,
'_-Окраска тканей аниловыми красками (килограмм)':0.2,
'Пряжа хлопчатая (килограмм)':0.2 / 0.95,
'_Ткацкая мастерская (годовой оборот)':1 / (160000 / 0.6),
}
metadict_detail['_Производство махровой ткани (квадратный метр)'] = {
'_-Производство махровой ткани (квадратный метр)':1,
'_-Беление ткани хлорной известью и содой (килограмм)':0.5,
'_-Окраска тканей аниловыми красками (килограмм)':0.5,
'Пряжа хлопчатая (килограмм)':0.5 / 0.95,
'_Ткацкая мастерская (годовой оборот)':1 / (160000 / 1.2),
}
metadict_detail['_Производство фланели (квадратный метр)'] = {
'_-Производство фланели (квадратный метр)':1,
'_-Беление ткани хлорной известью и содой (килограмм)':0.25,
'_-Окраска тканей аниловыми красками (килограмм)':0.25,
'Пряжа хлопчатая (килограмм)':0.25 / 0.95,
'_Ткацкая мастерская (годовой оборот)':1 / (160000 / 0.8),
}
metadict_detail['_Производство бархата (квадратный метр)'] = {
# TODO: Бархат на обивку мягкой мебели
# Обивка дивана -- 4.2 кв.метра
# Обивка мягкого стула -- 0.7 кв.метра
# 1/10 домохозяйств, 2 дивана и 12 мягкий стульев в год.
# Плюш, вельвет.
# бархат -- 300 грамм/кв.метр
'_-Производство бархата (квадратный метр)':1,
'_-Беление ткани хлорной известью и содой (килограмм)':0.3,
'_-Окраска тканей аниловыми красками (килограмм)':0.3,
'Пряжа хлопчатая (килограмм)':0.3 / 0.95,
'_Ткацкая мастерская (годовой оборот)':1 / (160000 / 5),
}
metadict_detail['_Производство замши (квадратный метр)'] = {
# замша -- 410 грамм/кв.метр
'_-Производство замши (квадратный метр)':1,
'_-Беление ткани хлорной известью и содой (килограмм)':0.41,
'_-Окраска тканей аниловыми красками (килограмм)':0.41,
'Пряжа хлопчатая (килограмм)':0.41 / 0.95,
'_Ткацкая мастерская (годовой оборот)':1 / (160000 / 3),
}
metadict_detail['_Производство сатина (квадратный метр)'] = {
# сатин -- 120 грамм/кв.метр
'_-Производство сатина (квадратный метр)':1,
'_-Беление ткани хлорной известью и содой (килограмм)':0.12,
'_-Окраска тканей аниловыми красками (килограмм)':0.12,
'Пряжа хлопчатая (килограмм)':0.12 / 0.95,
'_Ткацкая мастерская (годовой оборот)':1 / (160000 / 2.4),
}
metadict_detail['_Производство льняной ткани (квадратный метр)'] = {
'_-Производство льняной ткани (квадратный метр)':1,
'_-Беление ткани хлорной известью и содой (килограмм)':0.15,
'_-Окраска тканей аниловыми красками (килограмм)':0.15,
'Пряжа льняная (килограмм)':0.15 / 0.95,
'_Ткацкая мастерская (годовой оборот)':1 / (160000 / 0.6),
}
metadict_detail['_Производство парусины (квадратный метр)'] = {
# - Домотканная (ручной станок) -- 14 нормо-часов/кв.метр
# полульняная 50% льна, 50% хлопка
# парусина -- 500 грамм/кв.метр
'_-Производство парусины (квадратный метр)':1,
'_-Беление ткани хлорной известью и содой (килограмм)':0.5,
'Пряжа хлопчатая (килограмм)':(0.5 / 0.95) / 2,
'Пряжа льняная (килограмм)':(0.5 / 0.95) / 2,
'_Ткацкая мастерская (годовой оборот)':1 / (160000 / 0.3),
}
metadict_detail['_Производство брезента (квадратный метр)'] = {
# Брезент пропитывают горным воском (озокеритом)
# https://ru.wikisource.org/wiki/ЭСБЕ/Брезент
# https://ru.wikisource.org/wiki/ЭСБЕ/Озокерит
# Брезент (для парусов) -- 900 грам/кв.метр
'_-Производство брезента (квадратный метр)':1,
'_-Беление ткани хлорной известью и содой (килограмм)':0.9,
'Пряжа льняная (килограмм)':0.9 / 0.95,
'_Ткацкая мастерская (годовой оборот)':1 / (160000 / 0.3),
}
metadict_detail['_Производство джутовой ткани (квадратный метр)'] = {
'_-Производство джутовой ткани (квадратный метр)':1,
'_-Беление ткани хлорной известью и содой (килограмм)':0.4,
'Пряжа джутовая (килограмм)':0.4 / 0.95,
'_Ткацкая мастерская (годовой оборот)':1 / (160000 / 0.3),
}
metadict_detail['_Производство мешковины (квадратный метр)'] = {
# TODO: Мешковину делают из волокнистых остатков льна. "Пакля льняная"
# Мешковина, рогожа. Из рогоза, лыка, пеньки.
# Плотность 200-450 грамм/кв.метр
# Не белят и не окрашивают.
'_-Производство мешковины (квадратный метр)':1,
'Пряжа пеньковая (килограмм)':0.4 / 0.95,
'_Ткацкая мастерская (годовой оборот)':1 / (160000 / 0.3),
}
metadict_detail['_Производство кирзовой ткани (квадратный метр)'] = {
# TODO: Производство кирзовой ткани. Можно детализовать.
# 1) тканевая основа.
# 2) На трехслойную ткань наносится бензоводный или латексный раствор каучука
# с различными наполнителями, красителями и вулканизирующими компонентами.
# 3) Термокамера -- на поверхности сукна образуется плёнка.
# 4) Каландрирование -- уплотнение материала
# 5) Тиснение
# https://tkanitex.ru/index.php/tkan-kirza-2/
# Трудозатраты (пока что оценочно) 1.8 нормо-часов/кв.метр
'_-Производство сукна для кирзовой ткани (квадратный метр)':1,
'Пряжа хлопчатая (килограмм)':0.3 / 0.95,
'Резина вулканизированная (килограмм)':0.1 / 0.95,
'_Ткацкая мастерская (годовой оборот)':1 / (160000 / 1.8),
}
metadict_detail['_Производство соломенной ткани (квадратный метр)'] = {
# Плотность плетёнки: 15 пудов соломы на 365 мотков (65 аршин/моток) -- 10 грамм/аршин
# Плетёнка №0 (самая тонкая) -- 6 аршин/день от лучшего мастера
# Плетёнка №5 (толстая) -- 25 аршин/день от неумехи
'_-Производство соломенной ткани (квадратный метр)':1,
'Солома сухая (килограмм)':0.6 / 0.5,
'_Ткацкая мастерская, кустарная (годовой оборот)':1 / (16000 / 0.6),
}
metadict_detail['_Производство соломенных ковров (квадратный метр)'] = {
# "Наставление к изготовлению соломенно-ковровых несгораемых крыш"
# Фермы красноуфимского реального училища.
# Пуда бечевы хватает на 400-520 аршин ковра (284-370 метров)
# Ширина станка -- 1.25 аршина (0.89 метра).
# Квадратный метр ковра -- 56 грамм бечевы.
# Ткётся двумя рабочими по 80-130 аршин/день, (57-92 метра, 50-82 кв.метра)
# Производительность труда -- 2.5-4 кв.метров/нормо-час
# 25% бечевы берут из старых ковров.
'_-Производство соломенных ковров (квадратный метр)':1,
'Солома сухая (килограмм)':2.5,
'Бечева пеньковая швейная (метр)':120 * 0.75,
'-Бечева пеньковая швейная (требуется/метр)':120 * 0.25,
'_Ткацкая мастерская, кустарная (годовой оборот)':1 / (16000 / 0.3),
}
metadict_detail['_Производство хлопчатых ковров (квадратный метр)'] = {
# Джутовая основа и хлопчатый ворс.
'_-Производство хлопчатых ковров (квадратный метр)':1,
'_-Беление ткани хлорной известью и содой (килограмм)':4.0,
'_-Окраска тканей аниловыми красками (килограмм)':4.0,
'Пряжа джутовая (килограмм)':2 / 0.95,
'Пряжа хлопчатая (килограмм)':2 / 0.95,
'_Ткацкая мастерская (годовой оборот)':1 / (160000 / 3),
}
metadict_detail['_Производство джутовых ковров (квадратный метр)'] = {
'_-Производство джутовых ковров (квадратный метр)':1,
'_-Беление ткани хлорной известью и содой (килограмм)':2.0,
'Пряжа джутовая (килограмм)':2 / 0.95,
'_Ткацкая мастерская (годовой оборот)':1 / (160000 / 0.6),
}
#----
# Производства (нити, канаты)
metadict_detail['_Производство хлопчатой нити (килограмм)'] = {
# Швейные нити белят и окрашивают.
'_-Окраска пряжи аниловыми красками (килограмм)':1 / 0.95,
'_-Беление пряжи хлорной известью и содой (килограмм)':1 / 0.95,
'Пряжа хлопчатая (килограмм)':1 / 0.95,
}
metadict_detail['_Производство льняной нити (килограмм)'] = {
'_-Окраска пряжи аниловыми красками (килограмм)':1 / 0.95,
'_-Беление пряжи хлорной известью и содой (килограмм)':1 / 0.95,
'Пряжа льняная (килограмм)':1 / 0.95,
}
metadict_detail['_Производство пеньковой нити (килограмм)'] = {
'_-Беление пряжи хлорной известью и содой (килограмм)':1 / 0.95,
'Пряжа пеньковая (килограмм)':1 / 0.95,
}
metadict_detail['_Производство пеньковой бечевы (килограмм)'] = {
# TODO: бечеву сплетают из нитей на механическом станке.
'_-Беление пряжи хлорной известью и содой (килограмм)':1 / 0.95,
'Пряжа пеньковая (килограмм)':1 / 0.95,
}
metadict_detail['_Производство джутовой нити (килограмм)'] = {
'_-Беление пряжи хлорной известью и содой (килограмм)':1 / 0.95,
'Пряжа джутовая (килограмм)':1 / 0.95,
}
#----
# Производства (пряжа)
# Производительность:
# 100 кг грязной шерсти = 50 кг чистой = 42 кг пряжи = 40 кг ткани
# 100 кг семенных коробочек хлопчатника = 26 кг хлопка-сырца = 22 кг пряжи = 21 кг ткани
# 1 веретено (10 ватт) = 0.0084 кг пряжи/час (42 кг пряжи/год)
# 1 рабочий на 250 веретен (0.5 нормо-часа/килограмм пряжи)
# 1 рабочий на 2 ткацких станка (0.6 нормо-часа/метр ткани, 2600 метров/год)
# https://ru.wikisource.org/wiki/ЭСБЕ/Пряжа
# https://istmat.org/node/27434
# Нормальное содержание влаги (1875 год):
# от веса высушенного продукта.
# - для хлопка — 8.5%,
# - шерсти гребенной — 18.25%
# - шерсти кардной — 17%,
# - искусственной — 13%,
# - льна — 12%,
# - джута — 14%,
# - шелка — 10%
metadict_detail['_Производство хлопчатой пряжи (килограмм)'] = {
# Техпроцессы:
# 1) рыхление и выколачивание сырца (волк-машина)
# 2) очистка сырца (сетчатые барабаны с вентиляторами)
# 3) смешивание сырца (для однородности)
# 4) трепание (трепальная машина)
# 5) чесание* (чесальные машины)
# 6) предпрядение ровнины на толстопрядильной машине (40-100 веретен)
# 7) прядение на веретенах
# * чесание нужно, чтобы волокна лежали в одном направлении.
# https://dic.academic.ru/dic.nsf/bse/124740/Прядильное
# https://ru.wikisource.org/wiki/ЭСБЕ/Прядение
# https://ru.wikisource.org/wiki/ЭСБЕ/Бумагопрядение
# https://ru.wikisource.org/wiki/ЭСБЕ/Чесание_волокнистых_материалов
# https://ru.wikisource.org/wiki/ЭСБЕ/Хлопчатобумажное_производство
# https://ru.wikisource.org/wiki/ЭСГ/Хлопчатобумажное_производство
# https://dic.academic.ru/dic.nsf/bse/140963/Трепание
# https://dic.academic.ru/dic.nsf/bse/124740/Прядильное
# Список фабрик и заводов Российской империи (1907-1909 годы):
# Бумагопрядильная фабрика, Переславль-Залесский,
# Число рабочих -- 2 441
# Двигатели паровые -- 1700 кВт (1.4 кВт/килограмм пряжи)
# Выработка -- 5 116 000 рублей (~5.1 млн. кг пряжи, 2100 кг/рабочего, 0.8-1.4 нормо-часа/кг)
# - хлопок (1900 год, Тифлис) -- 7-9 руб/пуд (0.43-0.55 рубля/кг)
# - пряжа (1898 год, Москва, биржа) -- 15.7-16.5 руб/пуд (1 рубль/кг)
# 1 рабочий на 250 веретен (0.5 нормо-часа/килограмм пряжи)
# 30 минут/кг на прядение, 18 минут/кг на прочие задачи.
# Выход пряжи:
# Работа оборудования -- 4100 часов/год (коэффициент работы оборудования -- 0.85)
# Ожидается (4100 часов) -- 1220 кг пряжи/час, 1460 кг сырья/час
# 85% -- после вторичной обработки и прядения.
# 7% -- короткого волокна. Пакля.
'_-Рыхление сырца на выколачивающей машине (килограмм)':1 / 0.85,
'_-Очистка сырца на сетчатом барабане с вентилятором (килограмм)':1 / 0.85 * 0.93,
'_-Смешивание сырца разных партий перед трепанием (килограмм)':1 / 0.85 * 0.93,
'_-Трепание сырца на трепальной машине с ленточным конвейером (килограмм)':1 / 0.85 * 0.85,
'_-Чесание сырца на чесальной машине с ленточным конвейером (килограмм)':1 / 0.85 * 0.85,
'_-Предпрядение сырца на ровничной машине (килограмм)':1 / 0.85 * 0.85,
'_-Прядение ровнины на тонкопрядильной машине (килограмм)':1 / 0.85 * 0.85,
'Хлопок-сырец (килограмм)':1 / 0.85,
'+Пакля хлопчатая (доступно/килограмм)':(1 / 0.85) * 0.07,
'_Прядильная фабрика (годовой оборот)':1 / 5000000,
}
metadict_detail['_Производство льняной пряжи (килограмм)'] = {
# Лён трёпаный (на пряжу) -- 30% массы волокна
# Волокно льняное короткое (очёс) -- 60-70% массы
# https://ru.wikipedia.org/wiki/Кудель
'_-Рыхление сырца на выколачивающей машине (килограмм)':1 / 0.30,
'_-Очистка сырца на сетчатом барабане с вентилятором (килограмм)':1 / 0.30 * 0.9,
'_-Смешивание сырца разных партий перед трепанием (килограмм)':1 / 0.30 * 0.9,
'_-Трепание сырца на трепальной машине с ленточным конвейером (килограмм)':1 / 0.30 * 0.9,
'_-Чесание сырца на чесальной машине с ленточным конвейером (килограмм)':1 / 0.30 * 0.6,
'_-Предпрядение сырца на ровничной машине (килограмм)':1 / 0.30 * 0.3,
'_-Прядение ровнины на тонкопрядильной машине (килограмм)':1 / 0.30 * 0.3,
'Лён-сырец (килограмм)':1 / 0.30,
'+Пакля льняная (доступно/килограмм)':(1 / 0.30) * 0.6,
'_Прядильная фабрика (годовой оборот)':1 / 5000000,
}
metadict_detail['_Производство джутовой пряжи (килограмм)'] = {
# TODO: Производство джутовой пряжи. Уточнить пропорции сырца.
'_-Рыхление сырца на выколачивающей машине (килограмм)':1 / 0.50,
'_-Очистка сырца на сетчатом барабане с вентилятором (килограмм)':1 / 0.50 * 0.9,
'_-Смешивание сырца разных партий перед трепанием (килограмм)':1 / 0.50 * 0.9,
'_-Трепание сырца на трепальной машине с ленточным конвейером (килограмм)':1 / 0.50 * 0.9,
'_-Чесание сырца на чесальной машине с ленточным конвейером (килограмм)':1 / 0.50 * 0.7,
'_-Предпрядение сырца на ровничной машине (килограмм)':1 / 0.50 * 0.5,
'_-Прядение ровнины на тонкопрядильной машине (килограмм)':1 / 0.50 * 0.5,
'Джут-сырец (килограмм)':1 / 0.5,
'+Пакля джутовая (доступно/килограмм)':(1 / 0.5) * 0.5,
'_Прядильная фабрика (годовой оборот)':1 / 5000000,
}
metadict_detail['_Производство пеньковой пряжи (килограмм)'] = {
# TODO: Производство пеньковой пряжи. Уточнить пропорции годной/негодной пеньки.
'_-Рыхление сырца на выколачивающей машине (килограмм)':1 / 0.50,
'_-Очистка сырца на сетчатом барабане с вентилятором (килограмм)':1 / 0.50 * 0.9,
'_-Смешивание сырца разных партий перед трепанием (килограмм)':1 / 0.50 * 0.9,
'_-Трепание сырца на трепальной машине с ленточным конвейером (килограмм)':1 / 0.50 * 0.9,
'_-Чесание сырца на чесальной машине с ленточным конвейером (килограмм)':1 / 0.50 * 0.7,
'_-Предпрядение сырца на ровничной машине (килограмм)':1 / 0.50 * 0.5,
'_-Прядение ровнины на тонкопрядильной машине (килограмм)':1 / 0.50 * 0.5,
'Пенька-сырец (килограмм)':1 / 0.5,
'+Пакля конопляная (доступно/килограмм)':(1 / 0.5) * 0.5,
'_Прядильная фабрика (годовой оборот)':1 / 5000000,
}
#----
# Производства (пакля)
metadict_detail['_Производство хлопчатой ваты (килограмм)'] = {
# Делают из отходов производства пряжи. Белят и прессуют.
# Рязанская губерня, фабрика Пырикова, изготовление ваты:
# - Годовое производство -- 32 000 рублей
# - Выручка по заказу -- 2300 рублей
# - Паровые двигатели -- 28 лошадиных сил
# - Рабочих -- 28 человек (1143 рубля продукции, 82 рубля дохода)
# https://istmat.org/node/26498
# Плотность -- 25 кг/кубометр
'_-Беление ваты хлорной известью и содой (килограмм)':1 / 0.95,
'_-Прессование ваты (кубометр)':1 / 25,
'-Пакля хлопчатая (требуется/килограмм)':1 / 0.95,
}
metadict_detail['_Производство пакли (килограмм)'] = {
# Плотность прессованной пакли -- 55 килограмм/кубометр
# Пресс даёт 5 кубометров/час (275 килограмм/час, 0.22 минуты/килограмм)
'_-Прессование пакли (кубометр)':1 / 55,
'-Пакля льняная (требуется/килограмм)':1 / 0.95 * 0.4,
'-Пакля джутовая (требуется/килограмм)':1 / 0.95 * 0.4,
'-Пакля конопляная (требуется/килограмм)':1 / 0.95 * 0.1,
'-Вата техническая (требуется/килограмм)':1 / 0.95 * 0.1,
}
#----
# Производства (сырьё)
metadict_detail['_Производство хлопка-сырца (килограмм)'] = {
# Коттон-джин, лучший (1000 рублей, 70 пил, 30 кВт) -- 2500 кг сырца в сутки (600 кг/час сырья)
# Батарея в 15 коттон-джинов, 60 дней сезон -- 2 250 000 кг сырца (8 550 000 кг сырья, 7 500 гектар)
# Одиночный коттон-джин, 60 дней сезон -- 150 000 кг сырца (570 000 сырья, 500 гектар)
# https://ru.wikisource.org/wiki/ЭСБЕ/Хлопчатник
# https://ru.wikisource.org/wiki/ЭСБЕ/Бумагопрядение
# https://ru.wikisource.org/wiki/ЭСБЕ/Хлопчатобумажное_производство
# https://ru.wikisource.org/wiki/ЭСБЕ/Хлопчатниковое_масло
# Санкт-Петербургская губерня. Товарищество Рубенчик и Рудникий, хлопкоочистка:
# - Выработка хлопка очищенного -- 150 000 рублей
# - Вырботка семян хлопка -- 12 000 рублей
# - Выручка по заказу -- 3000 рублей
# - Двигатели газовые -- 70 лошадиных сил
# - Рабочих -- 36 человек (4500 рублей продукции/работника, 83 рубля дохода/работника)
# 26% -- хлопка при первичной обработке сырца.
'_-Очистка хлопчатника технического на коттон-джине (килограмм)':1 / 0.26,
'_-Распределение хлопка-сырца из элеватора (кубометр)':1,
'_-Прессование хлопка-сырца (кубометр)':1,
'Хлопчатник технический, семенные коробочки (килограмм)':1 / 0.26,
'+Пакля хлопчатая (доступно/килограмм)':1 / 0.26 * 0.15,
'+Семена хлопчатника (доступно/килограмм)':1 / 0.26 * 0.25,
'|=Корзина семян хлопка (килограмм)':1 / 0.26 * 0.25,
'_Производство хлопка-сырца (годовой оборот)':1 / 150000,
}
metadict_detail['_Производство льна-сырца (килограмм)'] = {
# Льняное волокно -- 35% массы высушенного стебля (19% влажность)
# Лён трёпаный (на пряжу) -- 10% массы стебля
# Волокно льняное короткое (очёс) -- 25% массы стебля
# Семена -- 15% массы стебля.
# Костра -- 50% массы стебля.
# https://ru.wikipedia.org/wiki/Треста
# https://ru.wikipedia.org/wiki/Костра
# https://ru.wikisource.org/wiki/ЭСБЕ/Мочка_льна
# Льноводство / [Отв.ред.А.Р.Рогаш]. - М.: Колос, 1967
# МЯТЬЕ ТРЕСТЫ; ТРЕПАНИЕ ЛЬНА; ПЕРЕРАБОТКА ТРЕСТЫ НА ЛЬНОЗАВОДАХ
# https://www.booksite.ru/fulltext/flax/lno/vod/stv/o2/9.htm
# https://www.booksite.ru/fulltext/flax/lno/vod/stv/o2/66.htm
# https://www.booksite.ru/fulltext/flax/lno/vod/stv/o2/67.htm
# https://www.booksite.ru/fulltext/flax/lno/vod/stv/o2/74.htm
# ТИПОВЫЕ МЯЛЬНО-ТРЕПАЛЬНЫЕ ПУНКТЫ ПЕРВИЧНОЙ ОБРАБОТКИ ЛЬНА
# https://www.booksite.ru/fulltext/flax/lno/vod/stv/o2/69.htm
'_-Сортировка сырца технических растений (килограмм)':1 / 0.35,
'_-Дробление сырца на мяльной машине (килограмм)':1 / 0.35,
'_-Очистка сырца на трепальной машине (килограмм)':1 / 0.35,
'_-Прессование сырца на винтовом прессе (кубометр)':1 / 0.35 * 0.5,
'_-Сушка сырца технических растений (килограмм)':1 / 0.35 * 0.5,
'Лён технический (килограмм)':1 / 0.35,
'+Костра льняная (доступно/килограмм)':1 / 0.35 * 0.50,
'+Семена льна (доступно/килограмм)':1 / 0.35 * 0.15,
'|=Корзина семян льна (килограмм)':1 / 0.35 * 0.15,
'_Производство волокнистого сырья (годовой оборот)':1 / 75000,
}
metadict_detail['_Производство пеньки (килограмм)'] = {
# TODO: Производства пеньки. Уточнить детали.
# Замачивание в проточной воде за срок 1-3 года очищает волокна.
# Растения требуется размять, но трепание не нужно.
# Волокно -- 20% массы высушенного стебля
# Семена -- 15% массы стебля.
# Костра -- 50% массы стебля.
# https://ru.wikipedia.org/wiki/Конопля
# https://ru.wikisource.org/wiki/ЭСБЕ/Пенька
'_-Сортировка сырца технических растений (килограмм)':1 / 0.20,
'_-Дробление сырца на мяльной машине (килограмм)':1 / 0.20,
'_-Замачивание сырца технических растений в проточной воде (килограмм)':1 / 0.20,
'_-Очистка сырца на трепальной машине (килограмм)':1 / 0.20,
'_-Прессование сырца на винтовом прессе (кубометр)':1 / 0.20 * 0.3,
'_-Сушка сырца технических растений (килограмм)':1 / 0.20 * 0.3,
'Конопля техническая (килограмм)':1 / 0.2,
'+Костра конопляная (доступно/килограмм)':1 / 0.2 * 0.50,
'+Семена конопли (доступно/килограмм)':1 / 0.2 * 0.15,
'|=Корзина семян конопли (килограмм)':1 / 0.2 * 0.15,
}
metadict_detail['_Производство джута-сырца (килограмм)'] = {
# TODO: Производства джута-сырца. Уточнить долю волокна.
# Волокно -- 20% массы высушенного стебля
# https://en.wikipedia.org/wiki/Jute#Production
# https://en.wikipedia.org/wiki/Retting
# https://en.wikipedia.org/wiki/Jute_trade
# https://en.wikipedia.org/wiki/Jute_cultivation
# - 20 дней замачивают.
# - 3 дня сушат
'_-Сортировка сырца технических растений (килограмм)':1 / 0.20,
'_-Замачивание сырца технических растений в проточной воде (килограмм)':1 / 0.20,
'_-Дробление сырца на мяльной машине (килограмм)':1 / 0.20,
'_-Очистка сырца на трепальной машине (килограмм)':1 / 0.20,
'_-Прессование сырца на винтовом прессе (кубометр)':1 / 0.20 * 0.3,
'_-Сушка сырца технических растений (килограмм)':1 / 0.20 * 0.3,
'Джут технический (килограмм)':1 / 0.2,
'+Костра джутовая (доступно/килограмм)':(1 / 0.2) * 0.50,
'+Семена джута (доступно/килограмм)':(1 / 0.2) * 0.15,
'|=Корзина семян джута (килограмм)':(1 / 0.2) * 0.15,
}
#----
# Фабрики (капитализация)
metadict_detail['_Прядильная фабрика (годовой оборот)'] = {
#'Прядение фабрика (капитализация)':1/10,
#'Наёмные рабочие (прядильщики)':2400,
}
metadict_detail['_Производство хлопка-сырца (годовой оборот)'] = {
#'Прядение фабрика (капитализация)':1/10,
#'Наёмные рабочие (хлопок-сырец)':4,
}
metadict_detail['_Производство волокнистого сырья (годовой оборот)'] = {
#'Прядение фабрика (капитализация)':1/10,
#'Наёмные рабочие (технические растения)':15,
}
metadict_detail['_Швейная мастерская (годовой оборот)'] = {
#'Швейная мастерская (капитализация)':1/5,
#'Наёмные рабочие (швеи)':12,
}
metadict_detail['_Ткацкая мастерская (годовой оборот)'] = {
#'Ткацкая мастерская (капитализация)':1/5,
#'Наёмные рабочие (ткачи)':12,
}
metadict_detail['_Ткацкая мастерская, кустарная (годовой оборот)'] = {
#'Ткацкая мастерская (капитализация)':1/3,
#'Наёмные рабочие (ткачи)':12,
}
| true |
ed44de7459c0de500c4b7d8a362efc00721c24d9 | Python | auspicious3000/autovc | /model_vc.py | UTF-8 | 6,621 | 2.65625 | 3 | [
"MIT"
] | permissive | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class LinearNorm(torch.nn.Module):
def __init__(self, in_dim, out_dim, bias=True, w_init_gain='linear'):
super(LinearNorm, self).__init__()
self.linear_layer = torch.nn.Linear(in_dim, out_dim, bias=bias)
torch.nn.init.xavier_uniform_(
self.linear_layer.weight,
gain=torch.nn.init.calculate_gain(w_init_gain))
def forward(self, x):
return self.linear_layer(x)
class ConvNorm(torch.nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=1, stride=1,
padding=None, dilation=1, bias=True, w_init_gain='linear'):
super(ConvNorm, self).__init__()
if padding is None:
assert(kernel_size % 2 == 1)
padding = int(dilation * (kernel_size - 1) / 2)
self.conv = torch.nn.Conv1d(in_channels, out_channels,
kernel_size=kernel_size, stride=stride,
padding=padding, dilation=dilation,
bias=bias)
torch.nn.init.xavier_uniform_(
self.conv.weight, gain=torch.nn.init.calculate_gain(w_init_gain))
def forward(self, signal):
conv_signal = self.conv(signal)
return conv_signal
class Encoder(nn.Module):
"""Encoder module:
"""
def __init__(self, dim_neck, dim_emb, freq):
super(Encoder, self).__init__()
self.dim_neck = dim_neck
self.freq = freq
convolutions = []
for i in range(3):
conv_layer = nn.Sequential(
ConvNorm(80+dim_emb if i==0 else 512,
512,
kernel_size=5, stride=1,
padding=2,
dilation=1, w_init_gain='relu'),
nn.BatchNorm1d(512))
convolutions.append(conv_layer)
self.convolutions = nn.ModuleList(convolutions)
self.lstm = nn.LSTM(512, dim_neck, 2, batch_first=True, bidirectional=True)
def forward(self, x, c_org):
x = x.squeeze(1).transpose(2,1)
c_org = c_org.unsqueeze(-1).expand(-1, -1, x.size(-1))
x = torch.cat((x, c_org), dim=1)
for conv in self.convolutions:
x = F.relu(conv(x))
x = x.transpose(1, 2)
self.lstm.flatten_parameters()
outputs, _ = self.lstm(x)
out_forward = outputs[:, :, :self.dim_neck]
out_backward = outputs[:, :, self.dim_neck:]
codes = []
for i in range(0, outputs.size(1), self.freq):
codes.append(torch.cat((out_forward[:,i+self.freq-1,:],out_backward[:,i,:]), dim=-1))
return codes
class Decoder(nn.Module):
"""Decoder module:
"""
def __init__(self, dim_neck, dim_emb, dim_pre):
super(Decoder, self).__init__()
self.lstm1 = nn.LSTM(dim_neck*2+dim_emb, dim_pre, 1, batch_first=True)
convolutions = []
for i in range(3):
conv_layer = nn.Sequential(
ConvNorm(dim_pre,
dim_pre,
kernel_size=5, stride=1,
padding=2,
dilation=1, w_init_gain='relu'),
nn.BatchNorm1d(dim_pre))
convolutions.append(conv_layer)
self.convolutions = nn.ModuleList(convolutions)
self.lstm2 = nn.LSTM(dim_pre, 1024, 2, batch_first=True)
self.linear_projection = LinearNorm(1024, 80)
def forward(self, x):
#self.lstm1.flatten_parameters()
x, _ = self.lstm1(x)
x = x.transpose(1, 2)
for conv in self.convolutions:
x = F.relu(conv(x))
x = x.transpose(1, 2)
outputs, _ = self.lstm2(x)
decoder_output = self.linear_projection(outputs)
return decoder_output
class Postnet(nn.Module):
"""Postnet
- Five 1-d convolution with 512 channels and kernel size 5
"""
def __init__(self):
super(Postnet, self).__init__()
self.convolutions = nn.ModuleList()
self.convolutions.append(
nn.Sequential(
ConvNorm(80, 512,
kernel_size=5, stride=1,
padding=2,
dilation=1, w_init_gain='tanh'),
nn.BatchNorm1d(512))
)
for i in range(1, 5 - 1):
self.convolutions.append(
nn.Sequential(
ConvNorm(512,
512,
kernel_size=5, stride=1,
padding=2,
dilation=1, w_init_gain='tanh'),
nn.BatchNorm1d(512))
)
self.convolutions.append(
nn.Sequential(
ConvNorm(512, 80,
kernel_size=5, stride=1,
padding=2,
dilation=1, w_init_gain='linear'),
nn.BatchNorm1d(80))
)
def forward(self, x):
for i in range(len(self.convolutions) - 1):
x = torch.tanh(self.convolutions[i](x))
x = self.convolutions[-1](x)
return x
class Generator(nn.Module):
"""Generator network."""
def __init__(self, dim_neck, dim_emb, dim_pre, freq):
super(Generator, self).__init__()
self.encoder = Encoder(dim_neck, dim_emb, freq)
self.decoder = Decoder(dim_neck, dim_emb, dim_pre)
self.postnet = Postnet()
def forward(self, x, c_org, c_trg):
codes = self.encoder(x, c_org)
if c_trg is None:
return torch.cat(codes, dim=-1)
tmp = []
for code in codes:
tmp.append(code.unsqueeze(1).expand(-1,int(x.size(1)/len(codes)),-1))
code_exp = torch.cat(tmp, dim=1)
encoder_outputs = torch.cat((code_exp, c_trg.unsqueeze(1).expand(-1,x.size(1),-1)), dim=-1)
mel_outputs = self.decoder(encoder_outputs)
mel_outputs_postnet = self.postnet(mel_outputs.transpose(2,1))
mel_outputs_postnet = mel_outputs + mel_outputs_postnet.transpose(2,1)
mel_outputs = mel_outputs.unsqueeze(1)
mel_outputs_postnet = mel_outputs_postnet.unsqueeze(1)
return mel_outputs, mel_outputs_postnet, torch.cat(codes, dim=-1)
| true |
d9f243bc7e8c5623924700012385492527c16056 | Python | jeancre11/PYTHON-2020 | /clase python con IDLE/listas_metodo pop.py | UTF-8 | 471 | 3.671875 | 4 | [] | no_license | """uso de datos y metodos"""
#lista1
#append y pop son METODOS.
lista1=[10, 20, 30]
print(lista1)
#lista2
lista2=[5,2,3,100]
print(lista2)
#concatenar listas
print('SE TIENE COMO CONCATENACIÓN')
print(lista1+lista2)
#sacar un elemento de la ultima posicion de la lista1, defoult ()
val=lista1.pop()
print('despues del metodo pop a lista1=', lista1)
#print(lista2)
valo=lista2.pop(2)
print('queda despues de pop en lista2=',lista2,'valor quitado:', valo)
#objeto.metodo
| true |
a8e67d1c1611209836ac07d49a9f06645bb7acc6 | Python | OwenFeik/roguelike | /components/stairs.py | UTF-8 | 227 | 3.1875 | 3 | [] | no_license | class Stairs:
def __init__(self,floor):
self.floor=floor
def to_json(self):
return {'floor':self.floor}
@staticmethod
def from_json(json_data):
return Stairs(json_data.get('floor')) | true |
f8aeb05c25b4f525bfe5ef55d7a89423328d3b56 | Python | qiluo617/DeepLearning | /luoq_assignment4/prob1_3.py | UTF-8 | 714 | 3.046875 | 3 | [] | no_license |
import numpy as np
def sigmoid(z):
return 1.0/(1.0+np.exp(-z))
def sigmoid_prime(z):
return sigmoid(z)*(1-sigmoid(z))
x1 = np.array([[0.05], [0.1]])
w1 = np.array([[0.15, 0.2], [0.25, 0.3]])
b1 = np.array([[0.35], [0.35]])
h = sigmoid(np.dot(w1, x1) + b1)
w2 = np.array([[0.4, 0.45], [0.5, 0.55]])
b2 = np.array([[0.6], [0.6]])
o = sigmoid(np.dot(w2, h) + b2)
out = np.array([[0.01], [0.99]])
output_err = o - out
delta_1 = np.multiply(np.dot(np.transpose(w2), output_err), sigmoid_prime(np.dot(w1, x1) + b1))
print(delta_1)
print(output_err)
weight_layer1 = np.dot(x1, np.transpose(delta_1))
print(weight_layer1)
weight_layer2 = np.dot(h, np.transpose(output_err))
print(weight_layer2)
| true |
e9b7ae256bf5d2a0c2b7e3268c3290086a9e5c24 | Python | luisibarra06/python | /turtle12.py | UTF-8 | 160 | 2.703125 | 3 | [] | no_license | # turtle12 lai
rgb(0, 102, 187)
begin_fill()
while True:
forward(200)
left(170)
print (pos)
if abs(pos()) < 1:
break
end_fill()
done()
| true |
66ed9abc912efb15b5f882e9b2f2fbeb85cef114 | Python | BelongtoU/nguyentienanh-labs-C4E26 | /lab2/homework/3_te.py | UTF-8 | 174 | 3.53125 | 4 | [] | no_license | from turtle import *
def draw_square (lenght, color):
s = Turtle()
s.color (color)
for _ in range(4):
s.forward(lenght)
s.left(90)
mainloop() | true |
b5fd2a7bd444226c4e206495a4c96d337ca89964 | Python | BYY2100/xopy | /X-O..py | UTF-8 | 4,097 | 4.1875 | 4 | [] | no_license | #X O Game
#BY: BYY2100
import random
from os import system, name
from time import sleep
def clear():
if name == 'nt':
_ = system('cls')
else:
_ = system('clear')
def display_board(board):
#print("\n"*100)
clear()
#sleep(1.5)
print(board[7] + ' | ' + board[8] + ' | ' + board[9])
print('---------')
print(board[4] + ' | ' + board[5] + ' | ' + board[6])
print('---------')
print(board[1] + ' | ' + board[2] + ' | ' + board[3])
def player_input():
mark = ''
while mark != 'X' and mark != 'O':
mark = input('Please choose wether you wanna play with X or O: ')
p1 = mark
if p1 == 'X':
p2 = 'O'
else:
p2 == 'X'
return (p1,p2)
def place_marker(board, marker, position):
board[position] = marker
def win_check(board, mark):
return ((board[7] == mark and board[8] == mark and board[9] == mark) or # across the top
(board[4] == mark and board[5] == mark and board[6] == mark) or # across the middle
(board[1] == mark and board[2] == mark and board[3] == mark) or # across the bottom
(board[7] == mark and board[4] == mark and board[1] == mark) or # down the middle
(board[8] == mark and board[5] == mark and board[2] == mark) or # down the middle
(board[9] == mark and board[6] == mark and board[3] == mark) or # down the right side
(board[7] == mark and board[5] == mark and board[3] == mark) or # diagonal
(board[9] == mark and board[5] == mark and board[1] == mark)) # diagonal
def choose_first():
first = random.randint(0,1)
if first == 0:
return 'Player 1'
else:
return 'Player 2'
def space_check(board, position):
if board[position] != '':
return True
else:
return False
def full_board_check(board):
for i in range (1, 10):
if space_check(board,i):
return False
return True
def player_choice(board):
pos = 0
while pos not in [1,2,3,4,5,6,7,8,9] or not space_check(board,position):
pos = int(input("Please enter the position > "))
return pos
def replay():
con = input('Do you wanna play again? (enter y to continue) > ')
if con == 'y' or con == 'Y':
return True
else:
return False
#################################################################################
#The main game
print('Welcome to Tic Tac Toe!')
print('This Was Programmed By: BYY2100')
while True:
theBoard = [' ']*10
s = input('Do you wanna play? (enter y to start playing)> ')
p1 , p2 = player_input()
turn = choose_first()
print(f'{turn} will go first!')
sleep(1.5)
if s == 'y' or s == 'Y':
game_play = True
else:
game_play = False
position = 0
while game_play:
if turn == 'Player 1':
display_board(theBoard)
position = player_choice(theBoard)
place_marker(theBoard,p1,position)
if win_check(theBoard,p1):
display_board(theBoard)
print('Congrats Player 1! You Won!!')
game_play = False
else:
if full_board_check(theBoard):
print('Draw!')
game_play = False
else:
turn = 'Player 2'
else:
display_board(theBoard)
position = player_choice(theBoard)
place_marker(theBoard,p2,position)
if win_check(theBoard,p2):
display_board(theBoard)
print('Congrats Player 2! You Won!!')
game_play = False
else:
if full_board_check(theBoard):
print('Draw!')
game_play = False
else:
turn = 'Player 1'
if not replay():
break | true |
1b2293885a2ca8e8e73d5a352d8e97ddc72ce458 | Python | davidemartini/Knapsack-Problem | /Test/LaTex/maketex.py | UTF-8 | 1,086 | 2.59375 | 3 | [] | no_license | import os
path = './tex/'
files = os.listdir(path)
count = 0
deffile = []
for i in range(len(files)):
file = files[i].split('.')
index = 0
if len(file) > 1:
if file[1] == 'tex':
#print(files[i])
f = open(path+files[i], "r")
rows = f.read().split('\n')
#print(rows)
for j in range(len(rows)):
if count != 0:
if rows[j] == "\\tableofcontents":
#print(rows[j])
j += 1
#j = index
#print(rows)
#print(rows[j])
##controllare ultima parte
if count < (len(files)-1):
if rows[j] != '\\input{chapters}':
#print(rows[j])
deffile.append(rows[j])
else:
deffile.append(rows[j])
f.close()
count += 1
f = open("def.tex", "w")
for i in range(len(deffile)):
f.write(deffile[i])
f.write('\n')
f.close()
#print(deffile)
| true |
b7067884c29c9a48d47ad4f57b80c12eb6f8be04 | Python | nj-vs-vh/github-repos-as-presedential-elections | /wiki_election_page_parser.py | UTF-8 | 6,495 | 2.84375 | 3 | [] | no_license | import re
import yaml
from collections import defaultdict
from tqdm import tqdm
import requests
from bs4 import BeautifulSoup, Tag
from countries_adapter import country_matching_re, get_common_name
WIKI_URL = 'https://en.wikipedia.org'
class ElectionsParsingError(Exception):
pass
def concat_substrings(tag):
return (' '.join(s.strip() for s in tag.strings)).strip()
def parse_country_and_year(soup):
main_div = soup.find(id='mw-content-text')
country, year = None, None
for paragraph in main_div.find_all('p'):
text = concat_substrings(paragraph)
try:
if country is None:
match = next(country_matching_re.finditer(text))
country = get_common_name(match.group())
except StopIteration:
pass
try:
if year is None:
match = next(re.finditer(r'\d{4,4}', text))
year = match.group()
except StopIteration:
pass
if country and year:
return country, year
raise ElectionsParsingError("Unable to parse country or year")
def find_election_results_section(soup):
for header in soup.find_all(["h2", "h3", "h4"]):
for tag in header.contents:
if tag.string == 'Results':
return header
raise ElectionsParsingError("Results table not found")
def first_table_under_header(header):
for tag in header.next_siblings:
if tag.name == 'table':
return tag
raise ElectionsParsingError("Results table not found")
def parse_table_for_election_results(table, headers_log):
def find_string_idx_in_list_by_ordered_pattern_list(strings, patterns):
for pattern in patterns:
for i, string in enumerate(strings):
if re.match(pattern, string, flags=re.IGNORECASE):
return i
return None
def parse_vote_count(string):
try:
string = string.strip()
string = string.replace(',', '')
string = string.strip('%')
string = string.split('(')[0]
string = string.split('[')[0]
return float(string)
except Exception:
raise ElectionsParsingError(f"Error while parsing vote count '{string}'")
tbody = table.find('tbody')
header_row = tbody.find('tr')
column_headers = header_row.find_all('th')
# use colspan attr to determine 'true' column indices
# each column is repeated as many times as its colspan
column_headers_plaincolumns = []
for col in column_headers:
try:
repeat = int(col['colspan'])
except Exception:
repeat = 1
for _ in range(repeat):
column_headers_plaincolumns.append(col)
column_names = [concat_substrings(th) for th in column_headers_plaincolumns]
headers_log.write(' | '.join(column_names) + '\n')
columns_count = len(column_names)
candidate_patterns = ['presidential candidate', 'candidate', 'electoral values']
vote_patterns = ['electoral vote', 'vote', r'%', 'public vote', 'total']
stopword_patterns = [r'.*round']
candidate_i = find_string_idx_in_list_by_ordered_pattern_list(column_names, candidate_patterns)
vote_i = find_string_idx_in_list_by_ordered_pattern_list(column_names, vote_patterns)
if find_string_idx_in_list_by_ordered_pattern_list(column_names, stopword_patterns) is not None:
raise ElectionsParsingError("Election with first and second round")
if candidate_i is None or vote_i is None:
raise ElectionsParsingError(f"Unable to identify candidate or vote column among {column_names}")
election_results = dict()
for row in header_row.next_siblings:
if not isinstance(row, Tag):
# skip line-break strings
continue
if 'th' in {tag.name for tag in row.children}:
# skip sub-header
continue
tds = row.find_all('td')
if len(tds) < columns_count:
# to detect and stop parsing on 'Total' row or something alike
break
if not concat_substrings(tds[0]):
# to account for colored badges before first column
i_shift = 1
else:
i_shift = 0
candidate = concat_substrings(tds[i_shift + candidate_i])
votes = parse_vote_count(concat_substrings(tds[vote_i]))
if not candidate:
raise ElectionsParsingError(f"Error while parsing candidate: {tds[i_shift + candidate_i]}")
if re.match('total', candidate, flags=re.IGNORECASE):
break
election_results[candidate] = votes
if not election_results:
raise ElectionsParsingError(f"No rows found: {tbody.prettify()}")
else:
total = sum(election_results.values())
return {cand: votes / total for cand, votes in sorted(election_results.items(), key=lambda item: item[1])}
def parse_and_save_election_page(election_page, output_stream):
r = requests.get(WIKI_URL + election_page)
soup = BeautifulSoup(r.text, 'html.parser')
elections_data = defaultdict(dict)
try:
country, year = parse_country_and_year(soup)
elections_data[election_page]['country'] = country
elections_data[election_page]['year'] = year
except ElectionsParsingError:
pass
with open('data/wiki_election_pages_parsing_errors.txt', 'a') as f:
try:
results_header = find_election_results_section(soup)
table = first_table_under_header(results_header)
with open('data/headers_log.txt', 'a') as headers_log:
elections_data[election_page]['results'] = parse_table_for_election_results(table, headers_log)
yaml.dump(dict(elections_data), output_stream)
except ElectionsParsingError as e:
f.write(f'Error while parsing {WIKI_URL + election_page}:\n\t{str(e)}\n\n')
pages_filename = 'data/election_wiki_pages.txt'
with open(pages_filename) as f:
for total, l in enumerate(f):
pass
total += 1
with open(pages_filename, 'r') as pages_file, open('data/election_results.yaml', 'w') as results_file:
for page in tqdm(pages_file, total=total):
page = page.strip()
parse_and_save_election_page(page, results_file)
# sample_election_page = '/wiki/2006_Finnish_presidential_election'
# with open('temp.yaml', 'w') as f:
# parse_and_save_election_page(sample_election_page, f)
| true |
f93ce18f7aa27a4149f26ad746c611d423b2fa30 | Python | ofek/colour | /colour/models/rgb/transfer_functions/dci_p3.py | UTF-8 | 2,037 | 2.84375 | 3 | [
"BSD-3-Clause"
] | permissive | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
DCI-P3 Colourspace
==================
Defines the *DCI-P3* colourspace opto-electrical transfer function
(OETF / OECF) and electro-optical transfer function (EOTF / EOCF):
- :func:`oetf_DCIP3`
- :func:`eotf_DCIP3`
See Also
--------
`RGB Colourspaces Jupyter Notebook
<http://nbviewer.jupyter.org/github/colour-science/colour-notebooks/\
blob/master/notebooks/models/rgb.ipynb>`_
References
----------
.. [1] Digital Cinema Initiatives. (2007). Digital Cinema System
Specification - Version 1.1. Retrieved from
http://www.dcimovies.com/archives/spec_v1_1/\
DCI_DCinema_System_Spec_v1_1.pdf
"""
from __future__ import division, unicode_literals
import numpy as np
__author__ = 'Colour Developers'
__copyright__ = 'Copyright (C) 2013-2017 - Colour Developers'
__license__ = 'New BSD License - http://opensource.org/licenses/BSD-3-Clause'
__maintainer__ = 'Colour Developers'
__email__ = 'colour-science@googlegroups.com'
__status__ = 'Production'
__all__ = ['oetf_DCIP3', 'eotf_DCIP3']
def oetf_DCIP3(XYZ):
"""
Defines the *DCI-P3* colourspace opto-electronic transfer function
(OETF / OECF).
Parameters
----------
XYZ : numeric or array_like
*CIE XYZ* tristimulus values.
Returns
-------
numeric or ndarray
Non-linear *CIE XYZ'* tristimulus values.
Examples
--------
>>> oetf_DCIP3(0.18) # doctest: +ELLIPSIS
461.9922059...
"""
XYZ = np.asarray(XYZ)
return 4095 * (XYZ / 52.37) ** (1 / 2.6)
def eotf_DCIP3(XYZ_p):
"""
Defines the *DCI-P3* colourspace electro-optical transfer function
(EOTF / EOCF).
Parameters
----------
XYZ_p : numeric or array_like
Non-linear *CIE XYZ'* tristimulus values.
Returns
-------
numeric or ndarray
*CIE XYZ* tristimulus values.
Examples
--------
>>> eotf_DCIP3(461.99220597484737) # doctest: +ELLIPSIS
0.18...
"""
XYZ_p = np.asarray(XYZ_p)
return 52.37 * (XYZ_p / 4095) ** 2.6
| true |
6bee9440160f2272b922369bfec8c5c99a5c59e1 | Python | qyxiao/machine-learning-2016-spring | /scripts/results.py | UTF-8 | 3,563 | 2.8125 | 3 | [] | no_license | """Display results and analysis"""
__author__ = 'Charlie Guthrie'
import numpy as np
import pandas as pd
import cPickle as pickle
import matplotlib.pyplot as plt
import seaborn as sns
CONTEXT='notebook'
def get_results_df(result_path):
log = pickle.load(open( result_path, "rb" ))
raw_df = pd.DataFrame.from_dict(log)
available_columns = list(raw_df.columns)
desired_columns = ['strat_column','strat_value','model','best_score','train_accuracy','test_accuracy','num_cases','num_features','num_opinion_shards']
desired_and_available = list(set(desired_columns) & set(available_columns))
df = raw_df[desired_and_available]
return df
def print_weighted_accuracy(df):
models = df['model'].unique()
for model in models:
mdf = df.loc[df['model']==model,:]
total_cases = sum(mdf['num_cases'])
weighted_accuracy = sum(mdf['test_accuracy']*mdf['num_cases']/total_cases)
print "model: %s, weighted accuracy: %s%%" %(model,round(weighted_accuracy*100,1))
def identify_best_of_each_model(df,metric):
baseline_scores = {'best_score':'train_accuracy','test_accuracy':'test_accuracy'}
score_list = []
models = df['model'].unique()
print "Best values for each model:"
for model in models:
df2 = df.loc[df['model']==model]
if model=='baseline':
best_score=max(df2[baseline_scores[metric]])
print df2.loc[df2[baseline_scores[metric]]==best_score,('model','best_params')].values[0]
else:
best_score = max(df2[metric])
print df2.loc[df2[metric]==best_score,('model','best_params')].values[0]
score_list.append(best_score)
return models,score_list
def best_model_accuracy_bars(df,fig_path,metric,context):
'''
df: data frame
context: paper,talk, notebook, poster
'''
font_size = {
'paper':8,
'poster':16,
'notebook':10,
'talk':13
}
sns.set_context(context)
model_list,score_list = identify_best_of_each_model(df,metric)
#size and position of bars
bar_pos = np.arange(len(model_list))
bar_size = score_list
bar_labels = model_list
#plot
fig = plt.figure()
plt.barh(bar_pos,bar_size, align='center', alpha=0.4)
plt.yticks(bar_pos, bar_labels)
plt.xticks([],[]) #no x-axis
#Add data labels
for x,y in zip(bar_size,bar_pos):
plt.text(x+0.01, y, '%.2f' % x, ha='left', va='center',fontsize=font_size[context])
pretty_metric = {'test_accuracy':'Test','best_score':'CV'}
plt.title('Optimized %s Accuracy of Each Model' % pretty_metric[metric])
fig.savefig(fig_path, bbox_inches='tight')
def main():
STRATIFIED_RESULT_PATH = "../results/model_results.pkl.20150510-022044.20150510-022044.min_required_count.50.all_features.accuracy"
UNSTRAT_RESULT_PATH = "../results/model_results.pkl.20150509-052203.20150509-052203.min_required_count.100.chi2.accuracy.geniss"
RESULTS_CSV_PATH="../results/stratified_results.csv"
CONTEXT='notebook'
sdf=get_results_df(STRATIFIED_RESULT_PATH)
print "Stratified model results saved to %s" %RESULTS_CSV_PATH
sdf.to_csv(RESULTS_CSV_PATH)
print_weighted_accuracy(sdf)
df = get_results_df(UNSTRAT_RESULT_PATH)
fig_path="../results/stratified_best_score.png"
best_model_accuracy_bars(df,fig_path,'best_score',CONTEXT)
fig_path="../results/stratified_test_accuracy.png"
best_model_accuracy_bars(df,fig_path,'test_accuracy',CONTEXT)
if __name__ == '__main__':
main() | true |
06d6255691a015a1fdb04e86b45a08d714cc058e | Python | Armand-Morin/Emotions_Detection_on_videos | /emotion_recognition/affichage_resultats_categorie_pdf.py | UTF-8 | 2,016 | 3.3125 | 3 | [
"MIT"
] | permissive | import os
import cv2
from reportlab.pdfgen import canvas
#### C'est un code que l'on peut mettre a la fin de emotion_recognition.py mais c'est pas
# conseillé car c'est deja trop lourd a lui tout seul
Emotions = {'happy': 27.1,
'surprised': 1.7,
'sad': 24.2,
'neutral': 42.6,
'angry': 4.1
}
# fonction qui renvoie le max d'un dictionnaire
def max(dic):
maxi = 0
for x in dic:
if dic[x] > maxi:
maxi = x
return x
theme = max(Emotions)
# Pour changer la taille d'une image (dim est de la forme dim=(largeur,hauteur))
def resize_image(photo, dim):
image = cv2.imread(photo, 1)
img = cv2.resize(image, dim)
cv2.imwrite(str('resized_') + str(photo), img)
def cartouche(Y, nom, photo, statistiques, pdf):
pdf.line(0, Y, 600, Y)
pdf.line(0, Y + 100, 600, Y + 100)
pdf.setFont("Helvetica-Bold", 15)
pdf.drawInlineImage(photo, 20, Y + 10)
pdf.drawString(110, Y + 10, "Le film est :")
pdf.drawString(200, Y + 10, nom)
pdf.drawString(300, Y + 10, "avec probabilité de :")
pdf.drawString(517, Y + 10, str(statistiques))
pdf.drawString(560, Y + 10, "%")
if os.path.exists("Résultat.pdf"):
os.remove("Résultat.pdf")
pdf = canvas.Canvas("Résultat.pdf")
pdf.setFont("Helvetica-Bold", 18)
pdf.drawCentredString(300, 800, "Statistiques sur le type de film")
pdf.drawCentredString(300, 720, "Le film annalysé est: Confinés")
cartouche(600, 'joyeux', 'resized_happy.jpg', Emotions['happy'], pdf)
cartouche(500, 'triste', 'resized_sad.jpg', Emotions['sad'], pdf)
cartouche(400, 'surprenant', 'resized_surprised.jpg', Emotions['surprised'], pdf)
cartouche(300, 'neutre', 'resized_neutral.jpg', Emotions['neutral'], pdf)
cartouche(200, 'colérique', 'resized_angry.jpg', Emotions['angry'], pdf)
pdf.drawString(20, 100, "L'analyse des émotions des acteurs nous indique que le genre est : " + str(theme))
pdf.save()
| true |
da5bcdd95438c9a472cbd921e9d75bb9bd0e9236 | Python | bnsmcx/project_euler | /euler2.py | UTF-8 | 266 | 3.78125 | 4 | [] | no_license | #! /usr/bin/env python3
# finding the sum of all even fibonacci numbers below 4 million
sequence = [1, 2]
while sequence[-1] < 4_000_000:
sequence.append(sequence[-1] + sequence[-2])
even_numbers = [n for n in sequence if n % 2 == 0]
print(sum(even_numbers))
| true |
63434e605c034d55203f7bb4a99c1f381f0efdee | Python | senior88oqz/MachineLearningPractice | /DigitRecognition/largerCNN/CNN.py | UTF-8 | 2,826 | 2.875 | 3 | [] | no_license | import numpy as np
import matplotlib.pyplot as plt
data = np.load("./data.npz")
X = data['train_X']
y = data['train_y']
X_test = data['test_X']
X_train = X
y_train = y
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Flatten
from keras.layers import Dropout
from keras.layers.core import Activation
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils
# reshape to be [samples][depth/pixels][width][height]
X_train = X_train.reshape(X_train.shape[0], 1, 64, 64).astype('float32') #grey-scale -> depth = 1; RBG -> depth =3
# normalize inputs from 0-255 to 0-1
X_train = X_train / 255
# convert 1d class arrays to 10d class matrix
y_train = np_utils.to_categorical(y_train)
num_classes = y_train.shape[1]
def save_model():
# serialize model to JSON
model_json = model.to_json()
with open("CNN.json", "w") as json_file:
json_file.write(model_json)
# serialize weights to HDF5
model.save_weights("CNN.h5")
print("Saved model to disk")
# construct CNN model
def set_model():
# create model
model = Sequential()
#first layer
model.add(Conv2D(30, (4, 4), input_shape=(1, 64, 64), activation='relu')) # Conv2D(a,b,c)-> a: number of convolution filter,
#b/c: number of column rows/columns in each convolutional kernel
#input_shape-> shape of 1 sampel (e.g. X_train.shape)
#second layer
model.add(Conv2D(60, (4, 4), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(Activation('relu'))
model.add(Dropout(0.1))
#third layer
model.add(Conv2D(120, (4, 4), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(Dropout(0.1))
#Fully connected Dense layer
model.add(Flatten())
model.add(Dense(500, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
# Compile model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
# build the model
model = set_model()
def model_train():
# Fit the model
#model.fit(X_train, y_train, validation_data=(X_heldout, y_heldout), epochs=1, batch_size=1000, verbose=2)
model.fit(X_train, y_train, epochs=1, batch_size=1000, verbose=2)
save_model()
for i in range (20):
print("Total epoch= ", i + 1)
model_train()
X_test = X_test.reshape(X_test.shape[0], 1, 64, 64).astype('float32')
X_test /= 255
predictions = model.predict(X_test, batch_size=500, verbose=0)
predict = predictions.argmax(1)
import csv
f = open('CNN_predict.csv', 'w')
writer = csv.writer(f)
index = np.linspace(1, 500, 500)
writer.writerow(index)
writer.writerow(predict)
| true |
595f26dcf4bee39d3d40171dc60e8c9980e0e5fb | Python | finnp/fahrkarten-technikmuseum | /find_tickets.py | UTF-8 | 2,902 | 2.859375 | 3 | [] | no_license | import cv2
import numpy as np
import sys
from functools import reduce
# options
min_ticket_size = 450000
retr_type = cv2.RETR_LIST
contour_algorithm = cv2.CHAIN_APPROX_SIMPLE
erode_kernel = np.ones((11,11),np.uint8)
dilate_kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(40,40))
def grey(img):
return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
def blur(img):
return cv2.GaussianBlur(img, (7,7), 0)
def threshold(img):
_, binary = cv2.threshold(img, 174, 255, cv2.THRESH_BINARY)
return binary
def dilate(img):
return cv2.dilate(img, dilate_kernel)
def erode(img):
return cv2.erode(img,erode_kernel,iterations = 1)
def canny(img):
return cv2.Canny(img, 0, 85, apertureSize=3)
def find_contours (img):
_, contours, _ = cv2.findContours(img.copy(), retr_type, contour_algorithm)
contours = list(filter(lambda cont: cv2.contourArea(cont) > min_ticket_size, contours))
rects = []
polygons = []
for cont in contours:
polygon = cv2.approxPolyDP(cont, 40, True).copy().reshape(-1, 2)
polygon = cv2.convexHull(polygon)
if (len(polygon) > 15): continue # possibly not needed when comparing the areas
area = cv2.contourArea(polygon)
rect = cv2.boundingRect(polygon)
x,y,width,height = rect
if (width > 2.3*height or height > 2.3*width): continue # unusual shape
rect_area = width * height
area_diff = abs(rect_area - area)
if (area_diff > 60000): continue
rects.append(rect)
polygons.append(polygon)
return (rects, polygons)
steps = [
grey,
blur,
threshold,
dilate,
erode,
canny
]
def calculate_distance(x1, y1, x2, y2):
return (x2 - x1)**2 + (y2 - y1)**2
def find_tickets(img):
for step in steps:
img = step(img)
(rects, contours) = find_contours(img)
for ticket_a in rects:
x1, y1, w1, h1 = ticket_a
for ticket_b in rects:
x2, y2, w2, h2 = ticket_b
distance = calculate_distance(x1, y1, x2, y2)
if (distance < 10000):
rects.remove(ticket_b)
tickets = []
for ticket in rects:
x,y,w,h = ticket
tickets.append({
'x': x,
'y': y,
'width': w,
'height': h,
})
return tickets
def debug_tickets(original, img):
for index, step in enumerate(steps):
img = step(img)
cv2.imwrite(str(index) + '-' + step.__name__ + '.jpg', img)
(rects, contours) = find_contours(img)
print(len(rects))
cv2.drawContours(original,contours,-1,(0,255,0),3)
cv2.imwrite('final.jpg', original)
if __name__ == "__main__":
if (len(sys.argv) > 1):
file_name = sys.argv[1]
else:
file_name = 'img/III.5.01-01.jpg'
print('reading', file_name)
original = cv2.imread(file_name)
debug_tickets(original, original.copy())
| true |
8412592d8e928c854f01d058fd386628da5a74df | Python | johndpope/VoiceReplication-VoiceRep | /train.py | UTF-8 | 2,470 | 2.625 | 3 | [] | no_license | """
train.py by TayTech
Train the model
"""
from model import Model
import tensorflow as tf
from utils import plot_alignments
from config import CHECK_VALS, LOG_DIR, SR, MODEL_NAME
import librosa
import os
from tqdm import tqdm
import time
def train():
"""
Load the model from a checkpoint and train it.
Saves the model periodically based on the value of CHECK_VALS
"""
# Stats
time_count = 0
time_sum = 0
loss_count = 0
loss_sum = 0
# Paths
check_path = os.path.join(LOG_DIR, 'model')
check_path2 = os.path.join(LOG_DIR, MODEL_NAME)
g = Model()
print("Graph for training loaded.")
# Session
with tf.Session() as sess:
# run and initialize
sess.run(tf.global_variables_initializer())
coord = tf.train.Coordinator()
tf.train.start_queue_runners(sess=sess, coord=coord)
# Load the model
saver = tf.train.Saver()
if os.path.isfile(check_path2):
print("LOADED")
saver = tf.train.import_meta_graph(check_path2)
saver.restore(sess, tf.train.latest_checkpoint(LOG_DIR))
# Run the session
for _ in tqdm(range(g.num_batch), total=g.num_batch, ncols=70, leave=False, unit='b'):
start_time = time.time()
# training
g_step, g_loss, g_opt = sess.run([g.global_step, g.loss, g.opt_train])
# Generate stats
time_count += 1
loss_count += 1
time_sum += time.time() - start_time
loss_sum += g_loss
# Message
message = 'Step %-7d [%.03f sec/step, loss=%.05f, avg_loss=%.05f]' % \
(g_step, time_sum/time_count, g_loss, loss_sum/loss_count)
print(message)
# Save
if g_step % CHECK_VALS == 0:
print("Saving checkpoint to %s at step %d" % (check_path, g_step))
saver.save(sess, check_path, global_step=g_step)
# Saving the audio and alignment
print('Saving audio and alignment...')
audio_out, alignments = sess.run([g.audio_out, g.alignments[0]])
# The wav file
librosa.output.write_wav(os.path.join(LOG_DIR, 'step-%d-audio.wav' % g_step), audio_out, SR)
# plot alignments
plot_alignments(alignments, global_step=g_step)
if __name__ == '__main__':
train()
print("Done")
| true |
8cd4b3c52f1d59cc8b269bab925022bd562bd396 | Python | andrericca/Food_app_college_project | /Pedidodb.py | UTF-8 | 1,696 | 2.75 | 3 | [] | no_license | from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import sqlite3
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////Users/andreyoshdia/Documents/secretapp/food.db'
db = SQLAlchemy(app)
conn = sqlite3.connect('food.db')
print ("Opened database successfully")
conn.execute('CREATE TABLE pedido (ID INTEGER PRIMARY KEY AUTOINCREMENT, CNPJ INTEGER, produto_id INTEGER, quantidade INTEGER, CPF INTEGER, valor FLOAT, horario DATETIME, entregador_id INTEGER, uuid TEXT, status_pedido TEXT, FOREIGN KEY(CNPJ) REFERENCES restaurante(CNPJ), FOREIGN KEY(CPF) REFERENCES user(CPF), FOREIGN KEY(entregador_id) REFERENCES entregador(ID), FOREIGN KEY(produto_id) REFERENCES cardapio(ID))')
print ("Table created successfully")
conn.close()
class Pedido(db.Model):
ID = db.Column ('ID', db.Integer,primary_key=True, unique=True)
CNPJ = db.Column('CNPJ', db.Integer, unique=False, nullable=False)
quantidade = db.Column('quantidade', db.Integer, unique=False, nullable=False)
CPF = db.Column('CPF', db.Integer, unique=False, nullable=False)
valor = db.Column('valor', db.Float, unique=False, nullable=False)
horario = db.Column('horario', db.DateTime, unique=False, nullable=False)
entregador_id = db.Column('entregador_id', db.Integer, unique=False, nullable=False)
uuid = db.Column('uuid', db.String(800), unique=False, nullable=False)
status_pedido = db.Column('status_pedido', db.String(800), unique=False, nullable=False)
def __repr__(self):
return f"user('{self.ID}', '{self.CNPJ}', '{self.quantidade}', '{self.CPF}', '{self.valor}', '{self.horario}', '{self.entregador_id}', '{self.uuid}', '{self.status_pedido}')"
| true |
c2abd2fa9f6f806f104b6f0d5a9b9feca2a6bbff | Python | BearGroysenHe/CubeResolver | /resolving_cube.py | UTF-8 | 1,028 | 2.84375 | 3 | [] | no_license | import numpy as np
import random
from input_cube import *
from function import *
relations = input_relation()
rela_str = make_rela_str(relations)
cube = input_cube(rela_str)
np.save('cube',cube)
while True:
cube = np.load('cube.npy')
operations = []
count = 0
print('开始重新尝试')
while count < 10000:
condition = check(cube)
if condition == True:
break
axis = random.randint(0,2)
num = random.randint(1,3)
init_cube = np.load('cube.npy')
direction = random.randint(0,1)
if axis == 0:
axis = 'x'
elif axis == 1:
axis = 'y'
else:
axis = 'z'
rotation_cube(cube,axis,num,direction)
equal = init_cube == cube
operations.append(axis + str(num)+str(direction))
count += 1
print('正在尝试第%d次'%(count))
else:
print('尝试超过次数')
if condition == True:
break
print('共用了%d步'%(count))
print(operations)
| true |
744802677f45d381740e2bb231aac218d3b586a0 | Python | joedougherty/cgtips | /closestpair.py | UTF-8 | 3,980 | 3.375 | 3 | [] | no_license | import math
from random import randint
import matplotlib
import matplotlib.pyplot as plt
from cgtips_helper import pairwise
matplotlib.interactive(True)
TEST_POINTS = [(3, 4), (7, 4), (2, 4), (1, 3), (5, 5), (4, 7), (0, 5),
(3, 5), (8, 10), (10, 6), (9, 1)]
def dist(point_a, point_b):
return math.sqrt((point_a[0] - point_b[0])**2 + (point_a[1] - point_b[1])**2)
def closest_pair_brute(list_of_points):
"""
Test all pairwise combinations of points.
If the current distance is smaller than the established min_dist:
* set min_dist to current_dist
* store the salient coordintate pair in min_pair
"""
min_dist = float('inf')
for pair in pairwise(list_of_points):
point_a, point_b = pair
current_dist = dist(point_a, point_b)
if current_dist < min_dist:
min_dist = current_dist
min_pair = [point_a, point_b]
return (min_dist, min_pair)
def closest_pair_planar(list_of_points):
num_of_points = len(list_of_points)
if num_of_points < 4:
return closest_pair_brute(list_of_points)
# Step 1 -- sort points!
points_by_x = sorted(list_of_points, key=lambda p: p[0])
points_by_y = sorted(list_of_points, key=lambda p: p[1])
# Step 2 -- split points into left and right halves
left_half, right_half = split_list(points_by_x)
# Step 3 -- recurse!
left_side_min_dist = closest_pair_planar(left_half)
right_side_min_dist = closest_pair_planar(right_half)
# Step 4 -- What about the middle "strip"?
#
# Find the upperbound of the distance "around" the vertical partition line
if left_side_min_dist[0] < right_side_min_dist[0]:
d, min_pair = left_side_min_dist
else:
d, min_pair = right_side_min_dist
# Use the average of these two points to locate
# the midpoint x-coordinate of the partitioning vertical ray
x_ray = (left_half[-1][0] + right_half[0][0])/2.0
points_around_x_ray = build_strip(points_by_y, x_ray, d)
# Check only the first 7 points
#
# In its current form, this builds a collection of (min_dist, [point_a, point_b]) tuples.
strip_dist_collection = []
for idx, point in enumerate(points_around_x_ray):
strip_dist_collection.append(check_next_seven_points(points_around_x_ray, idx))
# Easiest thing to do for now is find the min dist in this collection
smallest_dist_in_strip = float('inf')
for dist_tuple in [item for item in strip_dist_collection if item != False]:
if dist_tuple[0] < smallest_dist_in_strip:
smallest_dist_in_strip = dist_tuple[0]
point_pair = dist_tuple[1]
if d < smallest_dist_in_strip:
return (d, min_pair)
else:
return (smallest_dist_in_strip, point_pair)
def build_strip(list_of_points, x_ray_coord, dist_bound):
strip = []
left_bound = x_ray_coord - dist_bound
right_bound = x_ray_coord + dist_bound
for point in list_of_points:
if point[0] > left_bound and point[1] < right_bound:
strip.append(point)
return strip
def check_next_seven_points(points_collection, starting_point_idx):
# This can likely be replaced with a more salient value
# (You ought to be able to pass in a dist value at invocation time)
min_dist = float('inf')
point_in_question = points_collection[starting_point_idx]
# Next seven points
relevant_points = points_collection[starting_point_idx+1:starting_point_idx+8]
if len(relevant_points) < 1:
return False
for point in relevant_points:
curr_dist = dist(point_in_question, point)
if curr_dist < min_dist:
min_dist = curr_dist
min_pair = [point_in_question, point]
return (min_dist, min_pair)
def split_list(list_of_points):
midpoint = len(list_of_points)//2
return (list_of_points[:midpoint], list_of_points[midpoint:])
| true |
663bb6cdebbdea8b8b61731004dd2faceed1d440 | Python | artbohr/codewars-algorithms-in-python | /7-kyu/product-of-maximums.py | UTF-8 | 1,471 | 4.40625 | 4 | [] | no_license | from functools import reduce
import operator
def max_product(lst, n_largest_elements):
return reduce(operator.mul, sorted(lst)[-n_largest_elements:])
'''
Introduction and Warm-up (Highly recommended)
Playing With Lists/Arrays Series
Task
Given an array/list [] of integers , Find the product of the k maximal numbers.
Notes
Array/list size is at least 3 .
Array/list's numbers Will be mixture of positives , negatives and zeros
Repetition of numbers in the array/list could occur.
Input >> Output Examples
maxProduct ({4, 3, 5}, 2) ==> return (20)
Explanation:
Since the size (k) equal 2 , then the subsequence of size 2 whose gives
product of maxima is 5 * 4 = 20 .
maxProduct ({8, 10 , 9, 7}, 3) ==> return (720)
Explanation:
Since the size (k) equal 3 , then the subsequence of size 2 whose gives
product of maxima is 8 * 9 * 10 = 720 .
maxProduct ({10, 8, 3, 2, 1, 4, 10}, 5) ==> return (9600)
Explanation:
Since the size (k) equal 5 , then the subsequence of size 2 whose gives
product of maxima is 10 * 10 * 8 * 4 * 3 = 9600 .
maxProduct ({-4, -27, -15, -6, -1}, 2) ==> return (4)
Explanation:
Since the size (k) equal 2 , then the subsequence of size 2 whose gives
product of maxima is -4 * -1 = 4 .
maxProduct ({10, 3, -1, -27} , 3) return (-30)
Explanation:
Since the size (k) equal 3 , then the subsequence of size 2 whose gives
product of maxima is 10 * 3 * -1 = -30 .
'''
| true |
746083a503e39ec88f9873ddd708699d160ea601 | Python | danielicapui/teoria_computacao | /pilha_autonomo.py | UTF-8 | 6,076 | 3.25 | 3 | [] | no_license | class Estado:
def __init__(self,nome,tipo,ligacao):
self.nome=nome
self.tipo=tipo
self.ligacao=ligacao
def getNome(self):
return self.nome
def getTipo(self):
return self.tipo
def getLigacao(self):
return self.ligacao
def moverEstado(self,simbolo,pilha_topo):
#percorre as ligações
for indice in self.getLigacao():
#busca ligações em que o simbolo da cadeia é igual a variavel simbolo e topo é igual a pilha_topo
if indice[0]==simbolo and indice[1]==pilha_topo:
return indice[2],indice[3]
return 666,666
def __str__(self):
return ("Nome:{}\nInicial:{}\nFinal:{}\nLigações:{}\n".format(self.getNome(),self.getTipo()[0],self.getTipo()[1],self.getLigacao()))
class Pilha:
def __init__(self,valorinicial):
self.fila=valorinicial
def getFila(self):
return self.fila
def adicionaFila(self,valor):
if self.isVazia()==False:
self.removerFila()
for i in reversed(valor):
self.getFila().insert(0,i)
def removerFila(self):
self.getFila().pop(0)
def isVazia(self):
if self.getFila()==[] or self.getFila()[0] in ["l","lambda","666"]:
print("Fila:",self.getFila())
return True
else:
return False
def __str__(self):
return ("Contéudo:{}".format(self.getFila()))
class Teste:
def __init__(self,estados,pilha,cadeia):
self.estados=estados
self.pilha=pilha
self.cadeia=cadeia
self.atual=estados[0]
def getEstados(self):
return self.estados
def getPilha(self):
return self.pilha
def getCadeia(self):
return self.cadeia
def getEstado_Inicial(self):
#pega o estado inicial
for i in (self.getEstados()):
if i.getTipo()[0]==1:
self.atual=i
return i
def getAtual(self,destino):
#pega o estado atual
for i in self.getEstados():
if i.getNome()==destino:
self.atual=i
return i
print("Cadeia não aceita")
return False
def trilha(self):
c=0
letra="nada"
self.getEstado_Inicial()
for simbolo in self.getCadeia():
if self.getPilha().isVazia()==True:
topo="l"
else:
topo=self.getPilha().getFila()[0]
print("Simbolo:",simbolo)
print("Fila:",topo)
print("Estado atual:",self.atual.getNome())
dado=self.atual.moverEstado(simbolo,topo)
print("Destino:{}\nProdução:{}".format(dado[0],dado[1]))
if dado[0]==666 and dado[1]==666:
print("Cadeia não aceita")
return False
elif dado[1] in ["l","lambda","666"]:
self.getPilha().removerFila()
else:
self.getPilha().adicionaFila(dado[1])
print("Pilha: {}".format(self.getPilha().getFila()))
print("\n")
self.atual=self.getAtual(dado[0])
c=c+1
letra=simbolo
print(self.atual)
if self.atual.getTipo()[1]==1 and str(c)==str(len(self.getCadeia())) and str(letra)==str(self.getCadeia()[-1]) and self.getPilha().isVazia()==True:
print("cadeia aceita")
return True
else:
print("cadeia não aceita")
return False
def criarAutonomo():
#Preciso da quantidade de estados do autonomo, do nome,do tipo
quantidade=int(input("Digite a quantidade de estados:\n"))
estados=[]
print("0==falso\n1==Verdade\n")
for i in range(quantidade):
tipos=[]
nome=input("Digite o nome do estado:\n")
tipos.append(int(input("Este é um estado inicial:\n")))
tipos.append(int(input("Este é um estado final:\n")))
numero=int(input("Defina quantas ligações {} tem:\n".format(nome)))
ligacao=[]
print("Ligações são da forma e são separadas pelo símbolo ',' [entrada,pilha_topo,destino,producao]")
#Aqui nós escreveremos as ligações
for t in range(numero):
l=input("Digite a ligação de número l{}:\n".format(t)).split(",")
ligacao.append(l)
#Essas duas últimas linhas é para criar o Estado com os dados digitados e armazenar
state=Estado(nome,tipos,ligacao)
estados.append(state)
return estados
def criarPilha():
#Precisa de um valor inicial
valor=[]
t=input("Digite o símbolo inicial:\n")
for letra in t:
valor.append(letra)
p=Pilha(valor)
return p
def criarCadeia():
#Criar uma cadeia para ser lida
palavra=input("Digite a cadeia que vai ser testada:\n")
cadeia=[]
for letra in palavra:
cadeia.append(letra)
return cadeia
def interface():
#laço principal e variaveis principais com letra em maisculas
is_game_over=False
ESTADOS=[]
CADEIA=[]
PILHA=[]
while(not is_game_over):
op=int(input("Digite 0 para criar um autonomo;\nDigite 1 para criar a pilha;\nDigite 2 para criar a cadeia de entrada;\nDigite 3 para testar a cadeia;\nDigite 666 para sair do programa:\n"))
if op==0:
ESTADOS=criarAutonomo()
elif op==1:
PILHA=criarPilha()
elif op==2:
CADEIA=criarCadeia()
elif op==3:
print("\n")
teste=Teste(ESTADOS,PILHA,CADEIA)
teste.getEstado_Inicial()
teste.trilha()
elif op==666:
is_game_over=True
else:
print("Opção não válida.")
def main():
interface()
if __name__ == "__main__":
main() | true |
83f53a6a7e988ab65e37083197b2acc4040271b8 | Python | SIDDHANTSEHGAL1198/Sparks-Foundation | /Task 4/Task 4.py | UTF-8 | 7,713 | 2.953125 | 3 | [] | no_license | #!/usr/bin/env python
# coding: utf-8
# # Siddhant Sehgal
# ### Task 4- Perform Exploratory Data Analysis on dataset Global Terrorism
# # Importing dataset
# In[1]:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import plotly.express as px
import chart_studio.plotly as py
get_ipython().run_line_magic('matplotlib', 'inline')
import cufflinks as cf
from plotly.offline import download_plotlyjs,init_notebook_mode,plot,iplot
init_notebook_mode(connected=True)
cf.go_offline()
# In[2]:
dataset=pd.read_csv(r'G:\Study Material\Projects\Data Analysis for Terrorism Dataset\globalterrorismdb_0718dist.csv',encoding='ISO-8859-1',engine='python')
# In[3]:
dataset.isnull().sum()
# In[4]:
dataset=dataset.dropna(thresh=160000,axis=1)
dataset
# In[ ]:
# In[5]:
dataset.columns
# In[6]:
dataset=dataset.drop(['eventid'],axis=1)
dataset
# In[7]:
dataset.isnull().sum()
# In[8]:
print("Country attcked most number of times",dataset['country_txt'].value_counts().index[0])
print("Region attcked most number of times",dataset['region_txt'].value_counts().index[0])
print(f"Maximum number of people killed is {dataset['nkill'].max()} that took place in {dataset.loc[dataset['nkill'].idxmax()].country_txt}")
print(f"Year with most number of attacks = {dataset['iyear'].value_counts().idxmax()}")
print(f"Month with most number of attacks = {dataset['imonth'].value_counts().idxmax()}")
print(f"Most common attcks={dataset['attacktype1_txt'].value_counts().idxmax()}")
# In[9]:
dataset['Casualities']=dataset['nkill'].fillna(0)+dataset['nwound'].fillna(0)
countries_affected = dataset.groupby(['country_txt'])['Casualities'].sum().sort_values(ascending = False)
# In[10]:
countries_affected
# In[ ]:
# In[11]:
import plotly.graph_objects as go
# In[12]:
trace=go.Bar(x=countries_affected[:15].index,
y=countries_affected[:15].values)
layout=go.Layout(title="Countries with most casualities",xaxis=dict(title="Countries"),yaxis=dict(title="Num of Casualiies"))
fig=go.Figure(data=[trace],layout=layout)
iplot(fig)
# Fom the above graph we can tell that Iraq is the most affected by Terrorism as there are about 214k casualities.
# After that comes countries like Afganistan,Pakistan and India which are asian countries and are most targeted by terrorist.
# In[ ]:
# In[13]:
yearly_killed=dataset.groupby(['iyear'])['nkill'].sum().reset_index()
yearly_wounded=dataset.groupby(['iyear'])['nwound'].sum().reset_index()
trace1=go.Bar(x=yearly_killed['iyear'],
y=yearly_killed['nkill'],
name="Killed",
marker=dict(color='black'))
trace2=go.Bar(x=yearly_wounded['iyear'],
y=yearly_wounded['nwound'],
name="Wounded",
marker=dict(color='red',
opacity=0.4))
layout=go.Layout(title="Casualties caused yearwise", xaxis=dict(title="Year"),barmode='stack')
fig=go.Figure(data=[trace1,trace2],layout=layout)
iplot(fig)
# Attacks which were successful yearwise
# In[14]:
s1=dataset[dataset['success']==1]
sucess_attck=dataset.groupby(['iyear'])['success'].sum()
# In[ ]:
# In[15]:
trace1=go.Bar(x=sucess_attck.index,
y=sucess_attck.values,
name="Success Attack",
marker=dict(color='red'))
# In[16]:
layout=go.Layout(title="Terrorism attacks successful year wise", xaxis=dict(title="Year"))
fig=go.Figure(data=[trace1],layout=layout)
iplot(fig)
# There were more than 14k successful terrorist attacks happened in year 2014.
# We can see over the years the attempts to attcak is been increased from year 2008
# In[ ]:
# In[17]:
dataset['targtype1_txt'].value_counts()
# In[18]:
trgt1=dataset['targtype1_txt'].value_counts()[:10]
trgt1
# In[19]:
l1=trgt1.index.tolist()
# In[20]:
l1
# In[21]:
trace=go.Pie(values=trgt1.values,
labels=l1)
fig=go.Figure(data=[trace])
iplot(fig)
# Most common target has been Private Citizens and Milatary departments
# In[ ]:
# In[22]:
k=dataset['attacktype1_txt'].value_counts()
# In[23]:
k
# In[24]:
trace=go.Bar(x=k.index,
y=k.values)
layout=go.Layout(title="Most attacks caused by", xaxis=dict(title="Attack Type"))
fig=go.Figure(data=[trace],layout=layout)
iplot(fig)
# In[ ]:
# In[ ]:
# Terrorist group which attacks more frequently
# In[25]:
l1=dataset['gname'].value_counts()[1:11]
# In[26]:
l1
# These are top 10 terrorist organisations which have attacked more frequently over the years
# In[ ]:
# In[27]:
trace=go.Bar(x=l1.index,
y=l1.values,
marker_color='lightslategrey')
layout=go.Layout(title="Notorious Terrorist Groups b/w 1970-2017",xaxis=dict(title="Terrorist groups"),yaxis=dict(title="Number of times"))
fig=go.Figure(data=[trace],layout=layout)
iplot(fig)
# In[ ]:
# In[28]:
dataset
# In[29]:
dataset.isnull().sum()
# In[30]:
df=pd.DataFrame()
# In[31]:
col=['iyear','Casualities','country_txt','region_txt','gname','nkill','nwound','latitude','longitude']
df=pd.DataFrame(dataset[col])
# In[32]:
df
# In[33]:
df=df.dropna(axis=0).reset_index()
# In[34]:
df
# In[35]:
import plotly.express as px
px.set_mapbox_access_token(open(r"C:\Users\user\mapbox_token.txt").read())
fig = px.scatter_mapbox(df, lat="latitude", lon="longitude", size='Casualities' , hover_data=['region_txt','country_txt','iyear' ] ,color="Casualities",color_continuous_scale="Portland", size_max=15, zoom=10,height=700)
fig.update_layout(mapbox_style="basic")
fig.show()
# In[36]:
col1=['iyear','region_txt','country_txt','crit1','crit2','crit3','weaptype1_txt','Casualities']
df1=pd.DataFrame(dataset[col1])
df1
# When Violent attack is aimed for Different criterias
#
# In[37]:
ct1=df1[df1['crit1']==1]
ct1
# In[38]:
ct2=df1[df1['crit2']==1]
ct2
# In[39]:
ct3=df1[df1['crit3']==1]
ct3
# In[40]:
plt.figure(figsize=(20,12))
sns.lineplot(y='Casualities',x='iyear',data=ct1,color='red')
sns.lineplot(y='Casualities',x='iyear',data=ct2,color='blue')
sns.lineplot(y='Casualities',x='iyear',data=ct3,color='black')
# In[41]:
ind=dataset[dataset['country_txt']=='India']
ind
# In[42]:
ind=ind.dropna(axis=0).reset_index()
ind
# So we can see in this dataframe that India has been attacked so many times
# In[ ]:
# fig=px.scatter_geo(ind,lat="latitude",lon="longitude",hover_data=['Casualities','imonth','iday','attacktype1_txt'],hover_name='provstate',animation_frame="iyear",color_continuous_scale="Portland")
fig.update_layout(title='Attacked India over the span of years')
fig.update_layout(mapbox_style="open-street-map",mapbox_center_lon=0)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
# In[44]:
dataset['dbsource'].unique()
# In[45]:
dbg=dataset.groupby(['dbsource'])['nkill'].sum().sort_values(ascending=False)
dbg
# In[46]:
lr=dbg[:10].index.to_list()
lr
# In[47]:
trace=go.Pie(values=dbg[:10].values,
labels=lr)
layout=go.Layout(title="Field iddentifying attack at that time")
fig=go.Figure(data=[trace],layout=layout)
iplot(fig)
# In[ ]:
# In[48]:
kid=dataset[dataset['ishostkid']==1]
kid
# In[49]:
kid = kid.groupby(['country_txt'])['Casualities'].sum().sort_values(ascending = False)
# In[50]:
hostage_count=kid[:15]
hostage_count
# In[51]:
trace=go.Bar(x=hostage_count.index,
y=hostage_count.values,
marker_color=hostage_count.values)
layout=go.Layout(title="Countries in which kids were hostage",xaxis=dict(title="Countries"),yaxis=dict(title="How many times it happened"))
fig=go.Figure(data=[trace],layout=layout)
iplot(fig)
# In[ ]:
| true |
b2bdeae2cda6d146e13c64417b91b45a55eaab50 | Python | JustinHtay/coursegraph | /resources/Grouch/grouch/parsers/restriction_parser.py | UTF-8 | 2,413 | 3 | 3 | [
"MIT"
] | permissive | import re
import w3lib
from grouch.parsers.parser import Parser
class RestrictionParser(Parser):
requirement_type = re.compile("(May not be|Must be) enrolled (?:as|in one of) the following (.*?):")
"""
A parser to convert OSCAR html into json
From an analysis of an OSCAR data dump, here are some statements about the
restrictions and their format:
its divided into lines, these lines can be one of three things:
<br>
requirement
object
a requirement is a statement in the form
"(?:May not be|Must be) enrolled (?:as|in one of) the following (.*?):"
where the following is one of
"Campuses", "Levels", "Majors", "Classifications", "Programs", "Colleges"
Following the requirement, there are a series of lines each containing an
object, these objects can be a variety of things, from "Applied Biology" to
"Undergraduate Semester", depending on the requirement
"""
def __init__(self):
self.methods = [self.remove_tags, self.split, self.clean, self.remove_empty, self.parse]
@staticmethod
def remove_tags(item):
return w3lib.html.remove_tags(item)
@staticmethod
def split(item):
return item.splitlines()
@staticmethod
def clean(item):
item = [line.replace(u'\\u00a0', "") for line in item]
return [line.strip() for line in item]
@staticmethod
def remove_empty(item):
return [line for line in item if line]
@staticmethod
def parse(item):
d = {'restrictions': []}
active = None
for line in item:
if RestrictionParser.requirement_type.search(line):
# the line is an outer line
match = RestrictionParser.requirement_type.search(line)
d['restrictions'].append(match.group(2))
d[match.group(2)] = {}
positive = None
if match.group(1) == "Must be":
positive = True
else:
positive = False
d[match.group(2)]['positive'] = positive
d[match.group(2)]['requirements'] = []
active = match.group(2)
else:
d[active]['requirements'].append(line)
return d
| true |
fe1376905e232817053ba12b4503b3818c17ec56 | Python | avirathtib/f1 | /main.py | UTF-8 | 4,825 | 2.65625 | 3 | [] | no_license | import streamlit as st
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import plotly.express as px
import plotly.graph_objects as go
dataResults = pd.read_csv("f1db_csv/results.csv")
dataRaces = pd.read_csv("f1db_csv/races.csv")
dataDrivers = pd.read_csv("f1db_csv/drivers.csv")
dataLapTimes = pd.read_csv("f1db_csv/lap_times.csv")
dataQuali = pd.read_csv("f1db_csv/qualifying.csv")
dataConstructorResults = pd.read_csv("f1db_csv/constructor_results.csv")
dataDriverStandings = pd.read_csv("f1db_csv/driver_standings.csv")
dataConstructorStandings = pd.read_csv("f1db_csv/constructor_standings.csv")
dataPitStops = pd.read_csv("f1db_csv/pit_stops.csv")
dataConstructors = pd.read_csv("f1db_csv/constructors.csv")
dataDriverResults = pd.merge(dataDrivers, dataResults, on="driverId")
dataDriverResultsRaces = pd.merge(dataDriverResults, dataRaces, on="raceId")
dataDriverResultsRaces = dataDriverResultsRaces[dataDriverResultsRaces.year > 2009]
dataDriverResultsRaces["driver"] = dataDriverResultsRaces["forename"] + " " + dataDriverResultsRaces["surname"]
dataAveragePoints = dataDriverResultsRaces[['driver', 'points']].groupby("driver").mean().reset_index()
dataCountPoints = dataDriverResultsRaces[['driver', 'raceId']].groupby("driver").count().reset_index()
dataCountPoints = dataCountPoints[dataCountPoints.raceId > 100]
datafinalAverage = pd.merge(dataAveragePoints, dataCountPoints, on="driver")
avgfig = px.scatter(datafinalAverage, x = "raceId", y = "points", size="points", hover_name="driver", hover_data={'raceId':False, 'points':True})
st.plotly_chart(avgfig)
st.dataframe(datafinalAverage)
dataTotalPoints = dataDriverResultsRaces.groupby("driver").sum()
st.write('Pole to Podium Conversion Rates')
dfpole = (dataResults[dataResults.grid == 1 ]).sort_values(by=['driverId'])
#dataframe of drivers starting at pole, replaced all finish positions below 3 by 0, and all podium finishes by 1
dfpole['position'] = dfpole['position'].replace(['4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','\\N'],'0')
dfpole['position'] = dfpole['position'].replace(['3','2'],'1')
dfpole.position = pd.to_numeric(dfpole.position, errors='coerce').fillna(0).astype(np.int64)
#finds total no of poles, podiums from pole, division gives conversion rate, I've calculated for drivers with >3 poles
dfpole = dfpole[['driverId','grid','position']]
dfgrids = dfpole.groupby(["driverId"]).grid.sum().reset_index()
dfwins = dfpole.groupby(["driverId"]).position.sum().reset_index()
dfconcatenated=pd.merge(dfgrids, dfwins, on="driverId")
dfconcatenated = dfconcatenated[dfconcatenated.grid>3]
dfconcatenated.rename(columns = {'grid':'Total number of pole positions', 'position':'Total number of podium finishes from pole'}, inplace = True)
dfdrivers = dataDrivers[['driverId','forename','surname']]
dfconversion=pd.merge(dfdrivers, dfconcatenated, on="driverId")
dfconversion["driver"] = dfconversion["forename"] + " " + dfconversion["surname"]
def conversioncalc(row):
return ((row['Total number of podium finishes from pole']/row['Total number of pole positions'])*100)
dfconversion["Pole to Podium conversion rate (%)"] = dfconversion.apply ((lambda row: conversioncalc(row)), axis=1)
dfconversion = dfconversion.sort_values(by=['Pole to Podium conversion rate (%)'], ascending=False)
del dfconversion["forename"]
del dfconversion["surname"]
dfconversion
conversionfig = px.scatter(dfconversion, x = "Total number of pole positions", y = "Total number of podium finishes from pole", size="Pole to Podium conversion rate (%)", hover_name="driver",hover_data={'driverId':False, 'Total number of podium finishes from pole':False, "Total number of pole positions": False ,"Pole to Podium conversion rate (%)":True })
st.plotly_chart(conversionfig)
#multiselect for teams
teamoptions = st.multiselect('Choose teams to compare points by year', dataConstructors.name.tolist(), default='Mercedes')
#creating dataframe that groups points by year and team
dfConstructors = pd.merge(dataConstructorResults,dataConstructors, on="constructorId")
dfConstructors = pd.merge(dfConstructors, dataRaces, on="raceId")
dfConstructors['year'] = pd.DatetimeIndex(dfConstructors['date']).year
dfConstructors= dfConstructors[['raceId', 'year', 'constructorId', 'name_x', 'points']]
pointsBySeason = dfConstructors.groupby(['year','constructorId']).agg({'points': 'sum'}).reset_index()
pointsBySeason = pd.merge(pointsBySeason, dataConstructors, on="constructorId")
pointsBySeason= pointsBySeason[['year', 'constructorId', 'name', 'points']]
#returns dataframe with selected teams, line chart for points by season
points = pointsBySeason[pointsBySeason['name'].isin(teamoptions)]
fig = px.line(points, x="year", y="points", color='name')
st.plotly_chart(fig) | true |
12e282f7a400696ad39abf9082df2853c9d816ec | Python | AlgorithmLibrary/Basic-Data-Structures | /Randomized Selection.py | UTF-8 | 1,250 | 3.34375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 15 10:05:56 2020
@author: Grant
"""
from random import randrange
unsorted_list = [35, 1, 8, 2, 6, 11, 15, 9, 7]
order_statistic = 3
result = 0
def Swap(x, y):
global unsorted_list
temp = unsorted_list[x]
unsorted_list[x] = unsorted_list[y]
unsorted_list[y] = temp
def Partition(left, right):
global unsorted_list
p = unsorted_list[left]
i = left + 1
for j in range(left + 1, right):
if unsorted_list[j] < p:
Swap(i, j)
i += 1
Swap(left, i-1)
return i-1
def Rselect(left, right, i):
global unsorted_list
global result
if right - left == 1:
result = unsorted_list[left]
return
pivot = randrange(left, right)
Swap(left, pivot)
position = Partition(left, right)
if position + 1 == i:
result = unsorted_list[position]
return
if position + 1 > i:
Rselect(left, position, i)
if position + 1 < i:
Rselect(position + 1, right, i)
len_unsorted_list = len(unsorted_list)
Rselect(0, len(unsorted_list), order_statistic)
print(result) | true |
e620021ca59fa531243f3889f8c1db3555ad4274 | Python | Danyache/blockchain_project | /blockchain_project.py | UTF-8 | 11,311 | 2.734375 | 3 | [] | no_license | import math
from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor
import requests
import re
from random import randint
from functools import reduce
import random
last_film = {}
imdb_links = {}
TOKEN = '764982895:AAG4Lt2sYm9HguSdX0lHeztTp_I7ZqrgxaE'
bot = Bot(token=TOKEN)
dp = Dispatcher(bot)
def gcd(x, y):
if x == 0:
return y
return gcd(y % x, x)
def euler_function(n):
num = 1 # initialization, because there's always a 1
for _ in range(2, n):
if gcd(n, _) == 1:
num += 1
return num
def fast_pow(x, n, mod=0):
if n < 0:
return fast_pow(1/x, -n, mod=mod)
if n == 0:
return 1
if n == 1:
if mod == 0:
return x
else:
return x % mod
if n % 2 == 0:
if mod == 0:
return fast_pow(x * x, n / 2, mod=mod)
else:
return fast_pow(x * x, n / 2, mod=mod) % mod
else:
if mod == 0:
return x * fast_pow(x * x, (n - 1) / 2, mod=mod)
else:
return x * fast_pow(x * x, (n - 1) / 2, mod=mod) % mod
def discrete_log(a, b, p):
"""
In this function we are using an assumption that p is a prime number
"""
H = math.ceil(math.sqrt(p - 1))
hash_table = {fast_pow(a, i, p): i for i in range(H)}
c = fast_pow(a, H * (p - 2), p)
for j in range(H):
x = (b * fast_pow(c, j, p)) % p
if x in hash_table:
return j * H + hash_table[x]
return None
def crt(n, a):
sum = 0
prod = reduce(lambda a, b: a*b, n)
for n_i, a_i in zip(n, a):
p = prod / n_i
sum += a_i * mul_inv(p, n_i) * p
return sum % prod
def mul_inv(a, b):
b0 = b
x0, x1 = 0, 1
if b == 1: return 1
inv = eea(a,b)[0]
if inv < 1: inv += b
return inv
def eea(a,b):
if b==0:return (1,0)
(q,r) = (a//b,a%b)
(s,t) = eea(b,r)
return (t, s-(q*t))
def find_inverse(x,y):
inv = eea(x,y)[0]
if inv < 1: inv += y
return inv
def fast_pow(x, n, mod=0):
if n < 0:
return fast_pow(1/x, -n, mod=mod)
if n == 0:
return 1
if n == 1:
if mod == 0:
return x
else:
return x % mod
if n % 2 == 0:
if mod == 0:
return fast_pow(x * x, n / 2, mod=mod)
else:
return fast_pow(x * x, n / 2, mod=mod) % mod
else:
if mod == 0:
return x * fast_pow(x * x, (n - 1) / 2, mod=mod)
else:
return x * fast_pow(x * x, (n - 1) / 2, mod=mod) % mod
def egcd(a, b):
if (a == 0):
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def is_prime(num, test_count):
if num == 1:
return False
if test_count >= num:
test_count = num - 1
for x in range(test_count):
val = randint(1, num - 1)
if pow(val, num-1, num) != 1:
return False
return True
def generate_big_prime(n, test_count=1000):
found_prime = False
while not found_prime:
p = randint(2**(n-1), 2**n)
if is_prime(p, test_count):
return p
def generate_modulo(bitlen, tc=1000):
p = generate_big_prime(bitlen//2, tc)
q = 1
n = p * q
while (math.ceil(math.log(n, 2)) != bitlen):
q = generate_big_prime(bitlen - bitlen//2, tc)
n = p * q
return n, (p-1)*(q-1)
def rsa_generate_keys(bitlen, tc=1000):
'''
inputs:
bitlen - bitwise size of the keys
tc - number of iterations for cheking the primality
returns:
private_key: (modulo, exponent), public_key: (modulo, exponent)
'''
p1 = generate_big_prime(bitlen, tc)
p2 = generate_big_prime(bitlen, tc)
n = p1 * p2
phi = (p1 - 1)*(p2 - 1)
for i in range(3, phi):
if gcd(i, phi) == 1:
e = i
break
d = find_inverse(e, phi)
return (n, d), (n, e)
def rsa_encrypt(public_key, message, modulo):
return fast_pow(message, public_key, modulo)
def rsa_decrypt(private_key, message, modulo):
return fast_pow(message, private_key, modulo)
def rsa_sign(private_key, h, modulo):
'''
h - hash
'''
return fast_pow(h, private_key, modulo)
def rsa_check(public_key, h, g, modulo):
'''
h - received hash value
g - computed hash value
'''
return fast_pow(h, public_key, modulo) == g
"""
Дальше идут команды для бота
"""
@dp.message_handler(commands=['rsa_gen_keys'], commands_prefix='!/')
async def process_help_command(message: types.Message):
text = message.text
text = text[13:]
s = text.split()
bitlen = int(s[0])
tc = 1000
p1 = generate_big_prime(bitlen, tc)
p2 = generate_big_prime(bitlen, tc)
await bot.send_message(message.from_user.id, 'First generated prime is {}'.format(p1))
await bot.send_message(message.from_user.id, 'Second generated prime is {}'.format(p2))
n = p1 * p2
phi = (p1 - 1)*(p2 - 1)
await bot.send_message(message.from_user.id, 'Phi is {}'.format(phi))
e = random.randrange(1, phi)
#Use Euclid's Algorithm to verify that e and phi(n) are comprime
g = gcd(e, phi)
while g != 1:
await bot.send_message(message.from_user.id, 'Random e is {}. GCD is {}.'.format(e, g))
e = random.randrange(1, phi)
g = gcd(e, phi)
await bot.send_message(message.from_user.id, 'Final e is {}. GCD is {}.'.format(e, g))
d = find_inverse(e, phi)
await bot.send_message(message.from_user.id, 'Inverse for e in terms of mod phi is {}'.format(d))
result = [(n, d), (n, e)]
await bot.send_message(message.from_user.id, 'Private key is {}'.format(result[0]))
await bot.send_message(message.from_user.id, 'Public key is {}'.format(result[1]))
@dp.message_handler(commands=['rsa_encrypt'], commands_prefix='!/')
async def process_help_command(message: types.Message):
text = message.text
text = text[12:]
s = text.split()
pub, m, mod = s
pub, m, mod = int(pub), int(m), int(mod)
result = rsa_encrypt(pub, m, mod)
await bot.send_message(message.from_user.id, result)
@dp.message_handler(commands=['rsa_decrypt'], commands_prefix='!/')
async def process_help_command(message: types.Message):
text = message.text
text = text[12:]
s = text.split()
priv, m, mod = s
priv, m, mod = int(priv), int(m), int(mod)
result = rsa_decrypt(priv, m, mod)
await bot.send_message(message.from_user.id, result)
@dp.message_handler(commands=['rsa_sign'], commands_prefix='!/')
async def process_help_command(message: types.Message):
text = message.text
text = text[9:]
s = text.split()
p, h, m = s
p, h, m = int(p), int(h), int(m)
result = rsa_sign(p, h, m)
await bot.send_message(message.from_user.id, result)
@dp.message_handler(commands=['rsa_check'], commands_prefix='!/')
async def process_help_command(message: types.Message):
text = message.text
text = text[10:]
s = text.split()
p, h, g, m = s
p, h, g, m = int(p), int(h), int(g), int(m)
result = rsa_check(p, h, g, m)
await bot.send_message(message.from_user.id, str(result))
@dp.message_handler(commands=['start'], commands_prefix='!/')
async def process_start_command(message: types.Message):
await message.reply("Это бот показывает работу некоторых функций")
@dp.message_handler(commands=['help'], commands_prefix='!/')
async def process_help_command(message: types.Message):
await bot.send_message(message.from_user.id, "\
Выдаю результаты некоторых функций \n \
Все аргементы данных функций вводятся после команды подряд через пробел \n \
/fast_pow(x, n, mod=None) -- возвожу число в степень методом fast powering \n \
/disc_log(a, b, p) -- нахожу логарифм для двух чисел в поле вычетов простого числа p \n \
/euler(x) -- нахожу значение функции Эйлера для заданного числа \n \
/crt(array_x, array_n) -- решаю задачу китайской теоремы об остатках (первый и второй массивы вводятся подряд через пробел) \n \
/find_inverse(x, mod) -- обобщенный алгоритм евклида \n \
/rsa_gen_keys(bitlen) -- сгенерировать ключи \n \
/rsa_encrypt(e, message, n) -- encrypt message \n \
/rsa_decrypt(d, message, n) -- decrypt message \n \
/rsa_sign(d, h, n) -- create sign \n \
/rsa_check(e, h, g, n) -- check sign \n ")
@dp.message_handler(commands=['fast_pow'], commands_prefix='!/')
async def process_help_command(message: types.Message):
text = message.text
text = text[9:]
s = text.split()
if len(s) == 2:
a, b = s
a, b = int(a), int(b)
result = fast_pow(a, b)
else:
a, b, m = s
a, b, m = int(a), int(b), int(m)
result = fast_pow(a, b, m)
await bot.send_message(message.from_user.id, result)
@dp.message_handler(commands=['disc_log'], commands_prefix='!/')
async def process_help_command(message: types.Message):
text = message.text
text = text[9:]
s = text.split()
a, b, p = s
a, b, p = int(a), int(b), int(p)
result = discrete_log(a, b, p)
await bot.send_message(message.from_user.id, result)
@dp.message_handler(commands=['euler'], commands_prefix='!/')
async def process_help_command(message: types.Message):
text = message.text
text = text[6:]
s = text.split()
a = int(s[0])
n = a
num = 1
for _ in range(2, n):
if gcd(n, _) == 1:
await bot.send_message(message.from_user.id, 'One more number is {}'.format(_))
num += 1
await bot.send_message(message.from_user.id, 'Total amount is {}'.format(num))
@dp.message_handler(commands=['crt'], commands_prefix='!/')
async def process_help_command(message: types.Message):
text = message.text
text = text[4:]
s = text.split()
length = len(s)
n = []
a = []
for i in range(int(length/2)):
n.append(int(s[i]))
a.append(int(s[i+int(length/2)]))
result = crt(n, a)
await bot.send_message(message.from_user.id, result)
@dp.message_handler(commands=['find_inverse'], commands_prefix='!/')
async def process_help_command(message: types.Message):
text = message.text
text = text[13:]
s = text.split()
a, b = s
a, b = int(a), int(b)
result = find_inverse(a, b)
await bot.send_message(message.from_user.id, result)
@dp.message_handler(commands=['echo'], commands_prefix='!/')
async def process_help_command(message: types.Message):
text = message.text
await bot.send_message(message.from_user.id, text)
@dp.message_handler()
async def film_info(msg: types.Message):
text = msg.text
await bot.send_message(msg.from_user.id, 'Я тебя не понимаю')
if __name__ == '__main__':
executor.start_polling(dp) | true |
063e8a8fd34798343347168ec5bd3b659ea7226a | Python | DeepLearningHB/PythonMentoring | /PythonMentoring_OT/20155176_황찬우_Lab01/20155176_황찬우_Lab01_Task03.py | UTF-8 | 193 | 3.109375 | 3 | [] | no_license | user = ['서울', '대전', '대구', '부산', '울산', '인천']
#수정이 필요한 부분 보이지 않음
for i in user :
print("나는 %s사는 사람입니다." %i, end = " ")
| true |
75600c6d00219ab827c965109c399bad9afcd1d0 | Python | JediChou/jedichou-study-algo | /onlinejudge/nowcoder/lab6-zhiprint.py | UTF-8 | 1,012 | 4.21875 | 4 | [] | no_license | # -*- coding:utf-8 -*-
#####################################################################
# 题目描述
# 对于一个矩阵,请设计一个算法,将元素按“之”字形打印。具体见样例。
#
# 给定一个整数矩阵mat,以及他的维数nxm,请返回一个数组,其中元素依次为打印的数字。
#
# 测试样例:
# [[1,2,3],[4,5,6],[7,8,9],[10,11,12]],4,3
# 返回:[1,2,3,6,5,4,7,8,9,12,11,10]
#####################################################################
class Printer:
def printMatrix(self, mat, n, m):
pmat = []
for idx in range(n):
if (idx+1) % 2 == 0:
pmat = pmat + mat[idx][::-1]
else:
pmat = pmat + mat[idx]
return pmat
if __name__ == "__main__":
# define
mat = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
row, col = 4, 3
printer = Printer()
result = printer.printMatrix(mat, row, col)
# output
print(result)
| true |
d114a2ff68609401c12cf64147f21b28f710ba24 | Python | Mrpedi/baseline-vqa | /preprocess.py | UTF-8 | 1,705 | 3.28125 | 3 | [] | no_license | import json
from collections import Counter
csv_delimiter = '~'
default_data_path = './data/data_filename.json'
def get_default_data_path():
return default_data_path
def get_default_processed_data_path():
return generate_processed_path(default_data_path)
def generate_processed_path(data_filename):
data_dir = data_filename[0:find_last_idx('/', data_filename) + 1]
return data_dir + 'data_processed.csv'
def find_last_idx(char,str):
pos = []
str_len = len(str)
for i in range(str_len):
if char == str[i]:
pos.append(i)
return pos[-1]
# takes in file path to json data
# parses it in csv, comma-delimited format
# and saves to same directory under
# the name 'data_processed.csv'
def process_json(data_filename=default_data_path):
# open data file and parse
dataFileR = open(data_filename, 'r')
datasetJSON = dataFileR.read()
dataset = json.loads(datasetJSON)
dataFileR.close()
# Input: arrow of answers
# takes majority vote
def majorityAnswer(answers):
answer, count = Counter(answers).most_common(1)[0]
return answer
processed_data_file = generate_processed_path(data_filename);
# open file for writing processed training examples
dataFileW = open(processed_data_file, 'w')
for imgId in dataset:
questions = dataset[imgId]
# each question counts as its own training example
for question in questions:
trainExampleStr = str(imgId) + csv_delimiter + str(question) + csv_delimiter + str(majorityAnswer(questions[question]))
dataFileW.write(trainExampleStr + '\n')
print "finished processing data..."
# close up shop
dataFileW.close()
return processed_data_file
if __name__ == "__main__":
# execute only if run as a script
process_json() | true |
5f183c0ae64f7b48e974a381d0a0233310aff20a | Python | mengpanqingyun/optkit | /python/optkit/tests/C/test_cg.py | UTF-8 | 16,362 | 2.546875 | 3 | [] | no_license | import os
import numpy as np
from scipy.sparse import csr_matrix, csc_matrix
from ctypes import c_uint, c_void_p, byref, POINTER
from optkit.libs.cg import ConjugateGradientLibs
from optkit.tests.C.base import OptkitCTestCase, OptkitCOperatorTestCase
CG_QUIET = 1
class ConjugateGradientLibsTestCase(OptkitCOperatorTestCase):
"""TODO: docstring"""
@classmethod
def setUpClass(self):
self.env_orig = os.getenv('OPTKIT_USE_LOCALLIBS', '0')
os.environ['OPTKIT_USE_LOCALLIBS'] = '1'
self.libs = ConjugateGradientLibs()
self.tol_cg = 1e-12
self.rho_cg = 1e-4
self.maxiter_cg = 1000
self.A_test = self.A_test_gen
self.A_test_sparse = self.A_test_sparse_gen
@classmethod
def tearDownClass(self):
os.environ['OPTKIT_USE_LOCALLIBS'] = self.env_orig
def setUp(self):
self.x_test = np.random.rand(self.shape[1])
def tearDown(self):
self.free_all_vars()
self.exit_call()
def register_preconditioning_operator(self, lib, A_py, rho):
n = A_py.shape[1]
p_vec, p_, p_ptr = self.register_vector(lib, n, 'p_vec')
# calculate diagonal preconditioner
for j in range(A_py.shape[1]):
p_[j] = 1. / (rho + np.linalg.norm(A_py[:, j])**2)
self.assertCall( lib.vector_memcpy_va(p_vec, p_ptr, 1) )
p = lib.diagonal_operator_alloc(p_vec)
self.register_var('p', p.contents.data, p.contents.free)
return p_, p_vec, p
def test_libs_exist(self):
libs = []
for (gpu, single_precision) in self.CONDITIONS:
libs.append(self.libs.get(single_precision=single_precision,
gpu=gpu))
self.assertTrue(any(libs))
def assert_cgls_exit(self, A, x, b, rho, flag, tol):
# checks:
# 1. exit flag == 0
# 2. KKT condition A'(Ax - b) + rho (x) == 0 (within tol)
self.assertTrue( flag == 0 )
KKT = A.T.dot(A.dot(x) - b) + rho * x
self.assertTrue( np.linalg.norm(KKT) <= tol )
def test_cgls_helper_alloc_free(self):
m, n = self.shape
for (gpu, single_precision) in self.CONDITIONS:
lib = self.libs.get(single_precision=single_precision, gpu=gpu)
if lib is None:
continue
h = lib.cgls_helper_alloc(self.shape[0], self.shape[1])
self.register_var('h', h, lib.cgls_helper_free)
self.assertTrue( isinstance(h.contents.p, lib.vector_p) )
self.assertTrue( isinstance(h.contents.q, lib.vector_p) )
self.assertTrue( isinstance(h.contents.r, lib.vector_p) )
self.assertTrue( isinstance(h.contents.s, lib.vector_p) )
self.assertCall( lib.cgls_helper_free(h) )
self.unregister_var('h')
def test_cgls_nonallocating(self):
"""
cgls_nonallocating test
given operator A, vector b and scalar rho,
cgls method attemps to solve
min. ||Ax - b||_2^2 + rho ||x||_2^2
to specified tolerance _tol_ by performing at most _maxiter_
CG iterations on the above least squares problem
"""
m, n = self.shape
tol = self.tol_cg
maxiter = self.maxiter_cg
rho = 1e-2
for (gpu, single_precision) in self.CONDITIONS:
lib = self.libs.get(single_precision=single_precision, gpu=gpu)
if lib is None:
continue
self.register_exit(lib.ok_device_reset)
ATOLN = n**0.5 * 10**(-7 + 3 * single_precision)
TOL = tol * 10**(5 * single_precision)
RHO = rho * 10**(1 * single_precision)
# -----------------------------------------
# test cgls for each operator type defined in self.op_keys
for op_ in self.op_keys:
print("test cgls (nonallocating), operator type:", op_)
x, x_, x_ptr = self.register_vector(lib, n, 'x')
b, b_, b_ptr = self.register_vector(lib, m, 'b')
b_ += np.random.rand(m)
self.assertCall( lib.vector_memcpy_va(b, b_ptr, 1) )
A_, A, o = self.register_operator(lib, op_)
h = lib.cgls_helper_alloc(m, n)
self.register_var('h', h, lib.cgls_helper_free)
flag = np.zeros(1).astype(c_uint)
flag_p = flag.ctypes.data_as(POINTER(c_uint))
self.assertCall( lib.cgls_nonallocating(h, o, b, x, RHO, TOL,
maxiter, CG_QUIET,
flag_p) )
self.assertTrue( flag[0] <= lib.CGLS_MAXFLAG )
self.assertCall( lib.vector_memcpy_av(x_ptr, x, 1) )
self.assert_cgls_exit(A_, x_, b_, RHO, flag[0], ATOLN)
self.free_vars('o', 'A', 'h', 'x', 'b')
self.assertCall( lib.ok_device_reset() )
def test_cgls_allocating(self):
tol = self.tol_cg
maxiter = self.maxiter_cg
rho = 1e-2
m, n = self.shape
for (gpu, single_precision) in self.CONDITIONS:
lib = self.libs.get(single_precision=single_precision, gpu=gpu)
if lib is None:
continue
self.register_exit(lib.ok_device_reset)
ATOLN = n**0.5 * 10**(-7 + 3 * single_precision)
TOL = tol * 10**(5 * single_precision)
RHO = rho * 10**(1 * single_precision)
# -----------------------------------------
# allocate x, b in python & C
x, x_, x_ptr = self.register_vector(lib, n, 'x')
b, b_, b_ptr = self.register_vector(lib, m, 'b')
b_ += np.random.rand(m)
self.assertCall( lib.vector_memcpy_va(b, b_ptr, 1) )
# -----------------------------------------
# test cgls for each operator type defined in self.op_keys
for op_ in self.op_keys:
print("test cgls (allocating), operator type:", op_)
x, x_, x_ptr = self.register_vector(lib, n, 'x')
b, b_, b_ptr = self.register_vector(lib, m, 'b')
b_ += np.random.rand(m)
self.assertCall( lib.vector_memcpy_va(b, b_ptr, 1) )
A_, A, o = self.register_operator(lib, op_)
flag = np.zeros(1).astype(c_uint)
flag_p = flag.ctypes.data_as(POINTER(c_uint))
self.assertCall( lib.cgls(o, b, x, RHO, TOL, maxiter,
CG_QUIET, flag_p) )
self.assertTrue( flag[0] <= lib.CGLS_MAXFLAG )
self.assertCall( lib.vector_memcpy_av(x_ptr, x, 1) )
self.assert_cgls_exit(A_, x_, b_, RHO, flag[0], ATOLN)
self.free_vars('o', 'A', 'x', 'b')
self.assertCall( lib.ok_device_reset() )
def test_cgls_easy(self):
tol = self.tol_cg
maxiter = self.maxiter_cg
rho = 1e-2
m, n = self.shape
for (gpu, single_precision) in self.CONDITIONS:
lib = self.libs.get(single_precision=single_precision, gpu=gpu)
if lib is None:
continue
self.register_exit(lib.ok_device_reset)
ATOLN = n**0.5 * 10**(-7 + 3 * single_precision)
TOL = tol * 10**(5 * single_precision)
RHO = rho * 10**(1 * single_precision)
# -----------------------------------------
# test cgls for each operator type defined in self.op_keys
for op_ in self.op_keys:
print("test cgls (easy), operator type:", op_)
x, x_, x_ptr = self.register_vector(lib, n, 'x')
b, b_, b_ptr = self.register_vector(lib, m, 'b')
b_ += np.random.rand(m)
self.assertCall( lib.vector_memcpy_va(b, b_ptr, 1) )
A_, A, o = self.register_operator(lib, op_)
cgls_work = lib.cgls_init(m, n)
self.register_var('work', cgls_work, lib.cgls_finish)
flag = np.zeros(1).astype(c_uint)
flag_p = flag.ctypes.data_as(POINTER(c_uint))
self.assertCall( lib.cgls_solve(cgls_work, o, b, x, RHO,
TOL, maxiter, CG_QUIET,
flag_p) )
self.assertTrue( flag[0] <= lib.CGLS_MAXFLAG )
self.free_var('work')
self.assertCall( lib.vector_memcpy_av(x_ptr, x, 1) )
self.assert_cgls_exit(A_, x_, b_, RHO, flag[0], ATOLN)
self.free_vars('o', 'A', 'x', 'b')
self.assertCall( lib.ok_device_reset() )
def test_pcg_helper_alloc_free(self):
m, n = self.shape
for (gpu, single_precision) in self.CONDITIONS:
lib = self.libs.get(single_precision=single_precision, gpu=gpu)
if lib is None:
continue
h = lib.pcg_helper_alloc(self.shape[0], self.shape[1])
self.register_var('h', h, lib.pcg_helper_free)
self.assertTrue( isinstance(h.contents.p, lib.vector_p) )
self.assertTrue( isinstance(h.contents.q, lib.vector_p) )
self.assertTrue( isinstance(h.contents.r, lib.vector_p) )
self.assertTrue( isinstance(h.contents.z, lib.vector_p) )
self.assertTrue( isinstance(h.contents.temp, lib.vector_p) )
self.assertCall( lib.pcg_helper_free(h) )
self.unregister_var('h')
def test_diagonal_preconditioner(self):
tol = self.tol_cg
rho = 1e-2
maxiter = self.maxiter_cg
m, n = self.shape
for (gpu, single_precision) in self.CONDITIONS:
lib = self.libs.get(single_precision=single_precision, gpu=gpu)
if lib is None:
continue
self.register_exit(lib.ok_device_reset)
RTOL = 2e-2
ATOLN = RTOL * n**0.5
# -----------------------------------------
# test pcg for each operator type defined in self.op_keys
for op_ in self.op_keys:
print("test pcg (nonallocating), operator type:", op_)
A_, A, o = self.register_operator(lib, op_)
T = rho * np.eye(n)
T += A_.T.dot(A_)
p_vec, p_, p_ptr = self.register_vector(lib, n, 'p_vec')
# calculate diagonal preconditioner
p_py = np.zeros(n)
for j in range(n):
p_py[j] = 1. / (rho + np.linalg.norm(T[:, j])**2)
self.assertCall( lib.diagonal_preconditioner(o, p_vec, rho) )
self.assertCall( lib.vector_memcpy_av(p_ptr, p_vec, 1) )
self.assertVecEqual( p_py, p_, ATOLN, RTOL )
self.free_vars('o', 'A', 'p_vec')
self.assertCall( lib.ok_device_reset() )
def register_pcg_operators(self, lib, optype, rho, n):
A_, A, o = self.register_operator(lib, optype)
T = rho * np.eye(n)
T += A_.T.dot(A_)
p_py, p_vec, p = self.register_preconditioning_operator(lib, T, rho)
return A, o, T, p_vec, p
def test_pcg_nonallocating(self):
"""
pcg_nonallocating test
given operator A, vector b, preconditioner M and scalar rho,
pcg method attemps to solve
(rho * I + A'A)x = b
to specified tolerance _tol_ by performing at most _maxiter_
CG iterations on the system
M(rho * I + A'A)x = b
"""
tol = self.tol_cg
maxiter = self.maxiter_cg
m, n = self.shape
for (gpu, single_precision) in self.CONDITIONS:
lib = self.libs.get(single_precision=single_precision, gpu=gpu)
if lib is None:
continue
self.register_exit(lib.ok_device_reset)
DIGITS = 7 - 5 * single_precision - 1 * gpu
RTOL = 10**(-DIGITS)
ATOLN = RTOL * n**0.5
RHO = self.rho_cg * 10**(4 * single_precision)
# -----------------------------------------
# test pcg for each operator type defined in self.op_keys
for op_ in self.op_keys:
print("test pcg (nonallocating), operator type:", op_)
x, x_, x_ptr = self.register_vector(lib, n, 'x')
b, b_, b_ptr = self.register_vector(lib, n, 'b')
b_ += np.random.rand(n)
self.assertCall( lib.vector_memcpy_va(b, b_ptr, 1) )
A, o, T, p_vec, p = self.register_pcg_operators(lib, op_, RHO,
n)
h = lib.pcg_helper_alloc(m, n)
self.register_var('h', h, lib.pcg_helper_free)
iter_ = np.zeros(1).astype(c_uint)
iter_p = iter_.ctypes.data_as(POINTER(c_uint))
self.assertCall( lib.pcg_nonallocating(
h, o, p, b, x, RHO, tol, maxiter, CG_QUIET, iter_p) )
self.assertCall( lib.vector_memcpy_av(x_ptr, x, 1) )
self.assertTrue( iter_[0] <= maxiter )
self.assertVecEqual( T.dot(x_), b_, ATOLN, RTOL )
self.free_vars('p', 'p_vec', 'o', 'A', 'h', 'x', 'b')
self.assertCall( lib.ok_device_reset() )
def test_pcg_nonallocating_warmstart(self):
"""TODO: DOCSTRING"""
tol = self.tol_cg
maxiter = self.maxiter_cg
m, n = self.shape
for (gpu, single_precision) in self.CONDITIONS:
lib = self.libs.get(single_precision=single_precision, gpu=gpu)
if lib is None:
continue
self.register_exit(lib.ok_device_reset)
DIGITS = 7 - 5 * single_precision - 1 * gpu
RTOL = 10**(-DIGITS)
ATOLN = RTOL * n**0.5
RHO = self.rho_cg * 10**(4 * single_precision)
# -----------------------------------------
# test pcg for each operator type defined in self.op_keys
for op_ in self.op_keys:
print("test pcg (nonallocating) warmstart, operator type:", op_)
x, x_, x_ptr = self.register_vector(lib, n, 'x')
b, b_, b_ptr = self.register_vector(lib, n, 'b')
b_ += np.random.rand(n)
self.assertCall( lib.vector_memcpy_va(b, b_ptr, 1) )
A, o, T, p_vec, p = self.register_pcg_operators(lib, op_, RHO,
n)
h = lib.pcg_helper_alloc(m, n)
self.register_var('h', h, lib.pcg_helper_free)
iter_ = np.zeros(1).astype(c_uint)
iter_p = iter_.ctypes.data_as(POINTER(c_uint))
# first run
self.assertCall( lib.pcg_nonallocating(
h, o, p, b, x, RHO, tol, maxiter, CG_QUIET, iter_p) )
iters1 = iter_[0]
self.assertCall( lib.vector_memcpy_av(x_ptr, x, 1) )
self.assertVecEqual( T.dot(x_), b_, ATOLN, RTOL )
# second run
self.assertCall( lib.pcg_nonallocating(
h, o, p, b, x, RHO, tol, maxiter, CG_QUIET, iter_p) )
iters2 = iter_[0]
self.assertCall( lib.vector_memcpy_av(x_ptr, x, 1) )
self.assertVecEqual( T.dot(x_), b_, ATOLN, RTOL )
print('cold start iters:', iters1)
print('warm start iters:', iters2)
self.assertTrue(iters1 <= maxiter)
self.assertTrue(iters2 <= maxiter)
self.assertTrue(iters2 <= iters1)
self.free_vars('p', 'p_vec', 'o', 'A', 'h', 'x', 'b')
self.assertCall( lib.ok_device_reset() )
def test_pcg_allocating(self):
tol = self.tol_cg
maxiter = self.maxiter_cg
m, n = self.shape
for (gpu, single_precision) in self.CONDITIONS:
lib = self.libs.get(single_precision=single_precision, gpu=gpu)
if lib is None:
continue
self.register_exit(lib.ok_device_reset)
DIGITS = 7 - 5 * single_precision - 1 * gpu
RTOL = 10**(-DIGITS)
ATOLN = RTOL * n**0.5
RHO = self.rho_cg * 10**(4 * single_precision)
# -----------------------------------------
# test pcg for each operator type defined in self.op_keys
for op_ in self.op_keys:
print("test pcg (allocating), operator type:", op_)
x, x_, x_ptr = self.register_vector(lib, n, 'x')
b, b_, b_ptr = self.register_vector(lib, n, 'b')
b_ += np.random.rand(n)
self.assertCall( lib.vector_memcpy_va(b, b_ptr, 1) )
A, o, T, p_vec, p = self.register_pcg_operators(lib, op_, RHO,
n)
h = lib.pcg_helper_alloc(m, n)
self.register_var('h', h, lib.pcg_helper_free)
iter_ = np.zeros(1).astype(c_uint)
iter_p = iter_.ctypes.data_as(POINTER(c_uint))
self.assertCall( lib.pcg(o, p, b, x, RHO, tol, maxiter,
CG_QUIET, iter_p) )
self.assertTrue( iter_[0] <= maxiter )
self.assertCall( lib.vector_memcpy_av(x_ptr, x, 1) )
self.assertVecEqual( T.dot(x_), b_, ATOLN, RTOL )
self.free_vars('h', 'p', 'p_vec', 'o', 'A', 'x', 'b')
self.assertCall( lib.ok_device_reset() )
def test_pcg_easy(self):
tol = self.tol_cg
maxiter = self.maxiter_cg
m, n = self.shape
for (gpu, single_precision) in self.CONDITIONS:
lib = self.libs.get(single_precision=single_precision, gpu=gpu)
if lib is None:
continue
self.register_exit(lib.ok_device_reset)
DIGITS = 7 - 5 * single_precision - 1 * gpu
RTOL = 10**(-DIGITS)
ATOLN = RTOL * n**0.5
RHO = self.rho_cg * 10**(4 * single_precision)
# -----------------------------------------
# test pcg for each operator type defined in self.op_keys
for op_ in self.op_keys:
print("test pcg (easy), operator type:", op_)
x, x_, x_ptr = self.register_vector(lib, n, 'x')
b, b_, b_ptr = self.register_vector(lib, n, 'b')
b_ += np.random.rand(n)
self.assertCall( lib.vector_memcpy_va(b, b_ptr, 1) )
A, o, T, p_vec, p = self.register_pcg_operators(lib, op_, RHO,
n)
h = lib.pcg_helper_alloc(m, n)
self.register_var('h', h, lib.pcg_helper_free)
pcg_work = lib.pcg_init(m, n)
self.register_var('work', pcg_work, lib.pcg_finish)
iter_ = np.zeros(1).astype(c_uint)
iter_p = iter_.ctypes.data_as(POINTER(c_uint))
self.assertCall( lib.pcg_solve(pcg_work, o, p, b, x, RHO, tol,
maxiter, CG_QUIET, iter_p) )
iters1 = iter_[0]
self.assertTrue( iters1 <= maxiter )
self.assertCall( lib.vector_memcpy_av(x_ptr, x, 1) )
self.assertVecEqual( T.dot(x_), b_, ATOLN, RTOL )
self.assertCall( lib.pcg_solve(pcg_work, o, p, b, x, RHO, tol,
maxiter, CG_QUIET, iter_p) )
iters2 = iter_[0]
self.assertTrue(iters2 <= maxiter)
self.assertCall( lib.vector_memcpy_av(x_ptr, x, 1) )
self.assertVecEqual( T.dot(x_), b_, ATOLN, RTOL )
print('cold start iters:', iters1)
print('warm start iters:', iters2)
self.assertTrue(iters2 <= iters1)
self.free_vars('work', 'h', 'p', 'p_vec', 'o', 'A', 'x', 'b')
self.assertCall( lib.ok_device_reset() ) | true |
d571e6c1a5f32fbfe26c1649c680c215b88c8e9b | Python | duffyco/PowerMonitor | /predict.py | UTF-8 | 1,305 | 2.515625 | 3 | [] | no_license | import sys;
from datetime import datetime, date, timedelta
import pygal;
import parsePMData;
SECONDS = 10
while True:
parsePMData.readOtherFile( "powerlog-hourly.txt" )
endTime = datetime.now();
startTime = endTime - timedelta( seconds=10 );
usage = []
for i in range( 0, SECONDS ):
nextTime = startTime + timedelta( seconds=i );
# print "Time: ", str( nextTime);
minuteIndicies = parsePMData.getData( nextTime.strftime( "%H:%M:%S"), parsePMData.times );
if len( minuteIndicies ) > 0 :
minuteWatts = parsePMData.subVec( parsePMData.watts, minuteIndicies );
usage.append( minuteWatts[0] );
if parsePMData.SHOW_COSTS :
for i in range( 0, len( usage ) ):
if( endTime.hour < 7 or endTime.hour > 19 ):
usage[i] = parsePMData.getCost( usage[i], parsePMData.OFFPEAK );
elif endTime.hour > 11 and endTime.hour < 17 :
usage[i] = parsePMData.getCost( usage[i], parsePMData.ONPEAK );
else:
usage[i] = parsePMData.getCost( usage[i], parsePMData.MIDPEAK );
totalUsage = len(usage);
if len( usage ) > 2 :
totalUsage = (int)(usage[len(usage)-1] - usage[0]);
sys.stdout.write("Estimated : " + str( totalUsage * (3600/SECONDS) ) + "kWh @ " + str( totalUsage ) + "/" + str( SECONDS ) + " sec\r");
sys.stdout.flush();
| true |
fa96f6a04b722e6cde82420fd51c21053a6b8fc6 | Python | ypiatkevich/automatic-synonym-detection | /corpora_processing.py | UTF-8 | 473 | 2.84375 | 3 | [] | no_license | import os
from text_processing import *
def read_file(file):
file = open(file, "r")
return [line for line in file.readlines() if line != '\n']
def read_text(file):
file = open(file, "r")
text = file.read()
return split_into_sentences(text)
def write_triples_to_file(triples):
open("output/triples.txt", "w").close()
file = open("output/triples.txt", "r+")
for triple in triples:
file.write(triple.__str__())
file.close()
| true |
3d54297cd8bad5660860520c3dd25f202da61f60 | Python | liao1234566/SMSA | /tools.py | UTF-8 | 2,494 | 3.078125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
@author: JieJ
一些文本操作的基本函数
"""
import os
import re
######################################### 文件读写工具 ######################################
def load_lexicon(fname, convert_func):
'''加载文件为字典数据类型'''
lst = [x.strip().split('\t') for x in open(fname).readlines()]
word_dict = {}
for l in lst:
word_dict[l[0]] = convert_func(l[1])
return word_dict
def store_lexicon(tar_dict, fname):
'''加载文件为字典数据类型'''
with open(fname, 'w') as xs:
for key, val in tar_dict.iteritems():
xs.write(str(key) +'\t' + str(val) + '\n')
def store_rule_result(result_dict_lst,info_names,output_dir):
'''存储规则算法结果'''
for info in info_names:
f = open(output_dir+os.sep+info,'w')
for res in result_dict_lst:
f.write(str(res[info])+'\n')
f.close()
def write_score_file(final_score_list, fname):
'''规则得分写入文件'''
f = open(fname,'w')
f.writelines([str(x) + '\n' for x in final_score_list])
f.close()
def write_score_file_2(index_score_list, fname):
'''规则得分及对应序号写入文件'''
with open(fname, 'w') as xs:
for item in index_score_list:
xs.write(str(item[0]) + '\t' + str(item[1]) + '\n')
######################################### 功能性函数 ######################################
def cal_len(doc):
'''计算一篇文档的长度'''
ss = ''.join(doc)
ss = ss.replace(' ','').replace('\t','')
ss = re.sub('\[.*?\]','',ss)
return len(ss.decode('utf8','ignore'))
def cut_sentence(block,puncs_list):
'''按照标点分割子句'''
start = 0
i = 0 #记录每个字符的位置
sents = []
ct = 0
for word in block:
if word in puncs_list:
lst = block[start:i+1]
if len(lst)==1:
if ct>=1:
sents[ct-1].append(lst[0])
else:
sents.append(block[start:i+1])
ct += 1
start = i + 1 #start标记到下一句的开头
i += 1
else:
i += 1 #若不是标点符号,则字符位置继续前移
if start < len(block):
sents.append(block[start:]) #这是为了处理文本末尾没有标点符号的情况
return sents
| true |
1cb4425f3abe2b6d17e27c102285fb8b45600652 | Python | arunsangar/Sorting-Algorithms | /SortingAlgorithms/quick_sort.py | UTF-8 | 1,027 | 3.671875 | 4 | [] | no_license | def quick_sort(list, type='iterative'):
if(type == 'iterative'):
quick_sort_i(list)
else:
quick_sort_r(list)
def quick_sort_i(list):
left = 0
right = len(list)
stack = []
stack.append((left, right))
while(len(stack) > 0):
left, right = stack.pop()
list[left:right], split = partition(list[left:right])
split += left
if(split > left):
stack.append((left, split))
if(split+1 < right):
stack.append((split+1, right))
return list
def quick_sort_r(list):
if(len(list) > 1):
list, split = partition(list)
list[0:split] = quick_sort_r(list[0:split])
list[split+1:len(list)] = quick_sort_r(list[split+1:len(list)])
return list
def partition(list):
pivot = len(list)-1
i = 0
for j in range(len(list)-1):
if(list[j] <= list[pivot]):
list[i], list[j] = list[j], list[i]
i += 1
list[i], list[pivot] = list[pivot], list[i]
return list, i
| true |
d811341a8c4ae0850f3214d241293fa71c7afea8 | Python | Social-CodePlat/Comptt-Coding-Solutions | /Codeforces Problems/Drinks/Drinks.py | UTF-8 | 122 | 2.8125 | 3 | [
"MIT"
] | permissive | n=int(input())
arr=[float(x) for x in input().split()]
perc=((sum(arr)/(100*len(arr)))*100)
print("{:.11f}".format(perc))
| true |
4d1db6ffd39afb9098112880f3a41a4de565e986 | Python | SubMirk/12345 | /Sprider/263dm_spider.py | UTF-8 | 1,676 | 2.765625 | 3 | [] | no_license | from urllib.request import urlopen
import urllib.request
import os
import sys
import time
import re
import requests
# 全局声明的可以写到配置文件,这里为了读者方便看,故只写在一个文件里面
# 图片地址
picpath = r'E:\Python_Doc\Images'
# 网站地址
mm_url = "http://www.263dm.com/html/ai/%s.html"
# 保存路径的文件夹,没有则自己创建文件夹,不能创建上级文件夹
def setpath(name):
path = os.path.join(picpath, name)
if not os.path.isdir(path):
os.mkdir(path)
return path
def getUrl(url):
aa = urllib.request.Request(url)
html = urllib.request.urlopen(aa).read()
p = r"(http://www\S*/\d{4}\.html)"
return re.findall(p, str(html))
def get_image(savepath, url):
aa = urllib.request.Request(url)
html = urllib.request.urlopen(aa).read()
p = r"(http:\S+\.jpg)"
url_list = re.findall(p, str(html))
for ur in url_list:
save_image(ur, ur, savepath)
def save_image(url_ref, url, path):
headers = {"Referer": url_ref,
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 '
'(KHTML, like Gecko)Chrome/62.0.3202.94 Safari/537.36'}
content = requests.get(url, headers=headers)
if content.status_code == 200:
with open(path + "/" + str(time.time()) + '.jpg', 'wb') as f:
for chunk in content:
f.write(chunk)
def do_task(savepath, index):
print("正在保存页数:%s " % index)
url = mm_url % i
get_image(savepath, url)
if __name__ == '__main__':
# 文件名
filename = "Adult"
# filepath = setpath(filename)
for i in range(10699, 9424, -1):
filepath = setpath(filename+'\\'+str(i))
do_task(filepath, i) | true |
11c9ddd8602e938cbab9519674da52e5b7c53670 | Python | Tansiya/tansiya-training-prgm | /sample_question/tuple_assendingorder.py | UTF-8 | 435 | 3.984375 | 4 | [] | no_license | """Find the (name, age, height) tuplesby assending order where the name is string, age and height are numbers.the tuples are input by console"""
from operator import itemgetter, attrgetter
#assign a list
l = []
#using while loop
while True:
s = input()
#using if loop
if not s:
break;
#list append the tuple
l.append(tuple(s.split(",")))
#print the sorted tupleand asendingorder
print(sorted(l, key = itemgetter (0, 1, 2)))
| true |
f6990562e19f61c32fefc5ff74f2e2bcb8a726c4 | Python | dou-du/THOR-database | /calc_average.py | UTF-8 | 5,457 | 2.78125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 9 11:37:31 2021
@author: Zsuzsanna Koczor-Benda, UCL
"""
import numpy as np
import math
def full_average_IR(d):
full_av=(math.pow(d[0],2) + math.pow(d[1],2) + math.pow(d[2],2))/3
return full_av
# parallel in-out fields
def full_average_R(p):
full_av=(3*math.pow(p[0, 0],2) + math.pow(p[0, 1] + p[1, 0],2) +
3*math.pow(p[1, 1],2) + math.pow(p[0, 2] + p[2, 0],2) +
math.pow(p[1, 2] + p[2, 1],2) + 2*p[1, 1]*p[2, 2] +
3*math.pow(p[2, 2],2) + 2*p[0, 0]*(p[1, 1] + p[2, 2]))/15
return full_av
# orthogonal in-out fields
def full_average_R_orth(p):
gamma=3*math.pow(p[0, 1],2)+3*math.pow(p[0, 2],2)+ 3*math.pow(p[1, 2],2)+ 0.5*(math.pow(p[0, 0] - p[1, 1],2) +
math.pow(p[1, 1] - p[2, 2],2) +
math.pow(p[2, 2] - p[0, 0],2))
alpha=1/9* math.pow(p[0, 0] + p[1, 1]+p[2,2],2)
rii=(45*alpha+4*gamma)/45
rji=3*gamma/45
full_av=rii+rji
# depolarization ratio:
depol=1/(1+rji/rii)
return full_av,depol
def full_average(d,p):
full_av=(3*(5*math.pow(d[0],2) + math.pow(d[1],2) + math.pow(d[2],2))*math.pow(p[0, 0],2) +
(3*math.pow(d[0],2) + 3*math.pow(d[1],2) + math.pow(d[2],2))*math.pow(p[0, 1],2) +
3*math.pow(d[0],2)*math.pow(p[0, 2],2) + math.pow(d[1],2)*math.pow(p[0, 2],2) +
3*math.pow(d[2],2)*math.pow(p[0, 2],2) + 2*(3*math.pow(d[0],2) + 3*math.pow(d[1],2) +
math.pow(d[2],2))*p[0, 1]*p[1, 0] + 4*d[1]*d[2]*p[0, 2]*
p[1, 0] + 3*math.pow(d[0],2)*math.pow(p[1, 0],2) +
3*math.pow(d[1],2)*math.pow(p[1, 0],2) + math.pow(d[2],2)*math.pow(p[1, 0],2) +
4*d[0]*d[2]*p[0, 2]*p[1, 1] + 12*d[0]*d[1]*p[1, 0]*
p[1, 1] + 3*math.pow(d[0],2)*math.pow(p[1, 1],2) +
15*math.pow(d[1],2)*math.pow(p[1, 1],2) + 3*math.pow(d[2],2)*math.pow(p[1, 1],2) +
4*d[0]*d[1]*p[0, 2]*p[1, 2] + 4*d[0]*d[2]*p[1, 0]*
p[1, 2] + 12*d[1]*d[2]*p[1, 1]*p[1, 2] +
math.pow(d[0],2)*math.pow(p[1, 2],2) + 3*math.pow(d[1],2)*math.pow(p[1, 2],2) +
3*math.pow(d[2],2)*math.pow(p[1, 2],2) + 6*math.pow(d[0],2)*p[0, 2]*p[2, 0] +
2*math.pow(d[1],2)*p[0, 2]*p[2, 0] + 6*math.pow(d[2],2)*p[0, 2]*
p[2, 0] + 4*d[1]*d[2]*p[1, 0]*p[2, 0] +
4*d[0]*d[2]*p[1, 1]*p[2, 0] + 4*d[0]*d[1]*p[1, 2]*
p[2, 0] + 3*math.pow(d[0],2)*math.pow(p[2, 0],2) + math.pow(d[1],2)*math.pow(p[2, 0],2) +
3*math.pow(d[2],2)*math.pow(p[2, 0],2) + 4*d[0]*d[1]*p[0, 2]*p[2, 1] +
4*d[0]*d[2]*p[1, 0]*p[2, 1] + 12*d[1]*d[2]*p[1, 1]*
p[2, 1] + 2*math.pow(d[0],2)*p[1, 2]*p[2, 1] +
6*math.pow(d[1],2)*p[1, 2]*p[2, 1] + 6*math.pow(d[2],2)*p[1, 2]*
p[2, 1] + 4*d[0]*d[1]*p[2, 0]*p[2, 1] +
math.pow(d[0],2)*math.pow(p[2, 1],2) + 3*math.pow(d[1],2)*math.pow(p[2, 1],2) +
3*math.pow(d[2],2)*math.pow(p[2, 1],2) + 12*d[0]*d[2]*p[0, 2]*
p[2, 2] + 4*d[0]*d[1]*p[1, 0]*p[2, 2] +
2*math.pow(d[0],2)*p[1, 1]*p[2, 2] + 6*math.pow(d[1],2)*p[1, 1]*
p[2, 2] + 6*math.pow(d[2],2)*p[1, 1]*p[2, 2] +
12*d[1]*d[2]*p[1, 2]*p[2, 2] +
12*d[0]*d[2]*p[2, 0]*p[2, 2] +
12*d[1]*d[2]*p[2, 1]*p[2, 2] +
3*math.pow(d[0],2)*math.pow(p[2, 2],2) + 3*math.pow(d[1],2)*math.pow(p[2, 2],2) +
15*math.pow(d[2],2)*math.pow(p[2, 2],2) + 4*p[0, 1]*
(3*d[0]*d[1]*p[1, 1] + d[2]*(d[0]*p[1, 2] +
d[1]*(p[0, 2] + p[2, 0]) + d[0]*p[2, 1]) +
d[0]*d[1]*p[2, 2]) + 2*p[0, 0]*
(6*d[0]*d[1]*p[0, 1] + 6*d[0]*d[1]*p[1, 0] +
(3*math.pow(d[0],2) + 3*math.pow(d[1],2) + math.pow(d[2],2))*p[1, 1] +
2*d[2]*(3*d[0]*p[0, 2] + 3*d[0]*p[2, 0] +
d[1]*(p[1, 2] + p[2, 1])) +
(3*math.pow(d[0],2) + math.pow(d[1],2) + 3*math.pow(d[2],2))*p[2, 2]))/105
return full_av
def numerical_sector_average(d,p,k=1,l=1,a=0,b=0,c=0,nump=30):
e=np.array([0.,0.,1.0])
R0z=np.array([[math.cos(a), -math.sin(a),0],[math.sin(a),math.cos(a),0],[0,0,1]])
R0x=np.array([[1,0,0],[0,math.cos(b), -math.sin(b)],[0,math.sin(b),math.cos(b)]])
R0z2=np.array([[math.cos(c), -math.sin(c),0],[math.sin(c),math.cos(c),0],[0,0,1]])
R0=np.matmul(R0z2,np.matmul(R0x,R0z))
q=np.matmul(np.transpose(R0),e)
ir_av=0
r_av=0
p_av=0
maxtheta=math.pi/k
maxphi=2*math.pi/l
minjj=math.cos(maxtheta)
for i in range(nump):
phi=maxphi*i/nump
# print("phi ",phi)
Rz=np.array([[math.cos(phi), -math.sin(phi),0],[math.sin(phi),math.cos(phi),0],[0,0,1]])
for j in range(0,nump):
jj=1-(1-minjj)*j/nump
theta=math.acos(jj)
Rx=np.array([[1,0,0],[0,math.cos(theta), -math.sin(theta)],[0,math.sin(theta),math.cos(theta)]])
for m in range(nump):
xi=2*m*math.pi/nump
Rz2=np.array([[math.cos(xi), -math.sin(xi),0],[math.sin(xi),math.cos(xi),0],[0,0,1]])
R=np.matmul(Rz2,np.matmul(Rx,Rz))
# R=np.matmul(Rx,Rz)
# print(xi,math.pow(np.matmul(q,np.matmul(np.matmul(R,np.matmul(p,np.transpose(R))),np.transpose(q))),2))
ir=math.pow(np.matmul(q,np.matmul(R,d)),2)
r=math.pow(np.matmul(q,np.matmul(np.matmul(R,np.matmul(p,np.transpose(R))),np.transpose(q))),2)
ir_av+=ir
r_av+=r
p_av+=ir*r
ir_av=ir_av/math.pow(nump,3)
r_av=r_av/math.pow(nump,3)
p_av=p_av/math.pow(nump,3)
return ir_av,r_av,p_av
| true |
03b44ad2e138ae018db000f76144bf393bd0a985 | Python | axlan/laser_stars | /laser_stars/analysis/tracker.py | UTF-8 | 5,536 | 2.734375 | 3 | [] | no_license | import sys
import argparse
import cv2
import numpy
from laser_stars.utils import FPSCheck
class TrackerAnalysis(object):
def __init__(self, cv_loop, hue_min=20, hue_max=160,
sat_min=100, sat_max=255, val_min=200, val_max=256, transform=None, side_len=None, outfile='out/tracker.avi', show=False):
"""
HSV color space Threshold values for a RED laser pointer are determined
by:
* ``hue_min``, ``hue_max`` -- Min/Max allowed Hue values
* ``sat_min``, ``sat_max`` -- Min/Max allowed Saturation values
* ``val_min``, ``val_max`` -- Min/Max allowed pixel values
If the dot from the laser pointer doesn't fall within these values, it
will be ignored.
"""
self.hue_min = hue_min
self.hue_max = hue_max
self.sat_min = sat_min
self.sat_max = sat_max
self.val_min = val_min
self.val_max = val_max
self.outfile = outfile
self.show = show
self.transform = transform
self.side_len = side_len
FPS = 10
self.update_check = FPSCheck(FPS)
self.cv_loop = cv_loop
if side_len is not None:
self.cam_width = side_len
self.cam_height = side_len
else:
self.cam_width = cv_loop.cam_width
self.cam_height = cv_loop.cam_height
if outfile:
self.out = cv2.VideoWriter(self.outfile ,cv2.VideoWriter_fourcc(*'XVID'), FPS, (self.cam_width,self.cam_height))
self.channels = {
'hue': None,
'saturation': None,
'value': None,
'laser': None,
}
self.previous_position = None
self.trail = numpy.zeros((self.cam_height, self.cam_width, 3),
numpy.uint8)
cv_loop.processing_list.append(self.cv_func)
def threshold_image(self, channel):
if channel == "hue":
minimum = self.hue_min
maximum = self.hue_max
elif channel == "saturation":
minimum = self.sat_min
maximum = self.sat_max
elif channel == "value":
minimum = self.val_min
maximum = self.val_max
(t, tmp) = cv2.threshold(
self.channels[channel], # src
maximum, # threshold value
0, # we dont care because of the selected type
cv2.THRESH_TOZERO_INV # t type
)
(t, self.channels[channel]) = cv2.threshold(
tmp, # src
minimum, # threshold value
255, # maxvalue
cv2.THRESH_BINARY # type
)
def track(self, frame, mask):
"""
Track the position of the laser pointer.
Code taken from
http://www.pyimagesearch.com/2015/09/14/ball-tracking-with-opencv/
"""
center = None
countours = cv2.findContours(mask, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)[-2]
# only proceed if at least one contour was found
if len(countours) > 0:
# find the largest contour in the mask, then use
# it to compute the minimum enclosing circle and
# centroid
c = max(countours, key=cv2.contourArea)
((x, y), radius) = cv2.minEnclosingCircle(c)
moments = cv2.moments(c)
if moments["m00"] > 0:
center = int(moments["m10"] / moments["m00"]), \
int(moments["m01"] / moments["m00"])
else:
center = int(x), int(y)
# only proceed if the radius meets a minimum size
if radius > 1:
# draw the circle and centroid on the frame,
cv2.circle(frame, (int(x), int(y)), int(radius),
(0, 255, 255), 2)
cv2.circle(frame, center, 5, (0, 0, 255), -1)
# then update the ponter trail
if self.previous_position:
cv2.line(self.trail, self.previous_position, center,
(255, 255, 255), 2)
cv2.add(self.trail, frame, frame)
self.previous_position = center
def detect(self, frame):
hsv_img = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# split the video frame into color channels
h, s, v = cv2.split(hsv_img)
self.channels['hue'] = h
self.channels['saturation'] = s
self.channels['value'] = v
# Threshold ranges of HSV components; storing the results in place
self.threshold_image("hue")
self.threshold_image("saturation")
self.threshold_image("value")
# Perform an AND on HSV components to identify the laser!
self.channels['laser'] = cv2.bitwise_and(
self.channels['hue'],
self.channels['value']
)
self.channels['laser'] = cv2.bitwise_and(
self.channels['saturation'],
self.channels['laser']
)
self.track(frame, self.channels['laser'])
def cv_func(self, frame, is_done):
if is_done:
self.out.release()
return
if frame is not None and self.update_check.check():
if self.transform is not None:
frame = cv2.warpPerspective(frame, self.transform, (self.side_len, self.side_len))
self.detect(frame)
self.out.write(frame)
if self.show:
cv2.imshow('LaserPointer', frame)
| true |
e87a9ebfb6d4303f37ce181ffa750d120191f156 | Python | d-bingaling/project-3.0 | /Learning Python/ex5.py | UTF-8 | 636 | 4.40625 | 4 | [] | no_license | # Exercise 5 - More Variables and Printing
my_name = 'Dan Bingaling'
my_age = 26
my_height = 69.6 # inches
my_weight = 154 # lbs
my_eyes = 'Brown'
my_teeth = 'Yellow'
my_hair = 'Purple'
print(f"Let's talk about {my_name}.")
print(f"He's {my_height} inches tall.")
print(f"He's {my_weight} pounds heavy.")
print("Actually that's not too heavy.")
print(f"He's got {my_eyes} eyes and {my_hair} hair.")
print(f"His teeth are usually {my_teeth} depending on the peppermint tea.")
# this line is tricky, try to get it exactly right
total = my_age + my_height + my_weight
print(f"If I add {my_age}, {my_height}, and {my_weight} I get {total}.") | true |
a9979c575b57cd002cc4df772d09bb580ea115ba | Python | choo0618/TIL | /algoritm/20상반기 코딩테스트/.Algorithm정리/.Sort/버블정렬.py | UTF-8 | 420 | 3.359375 | 3 | [] | no_license | import sys
sys.stdin = open('sort.txt','r')
# 버블정렬
# 시간복잡도 O(N^2)
# 현재위치에서 뒤쪽으로 리스트를 확인하며 자리를 바꾼다.
def bubble_sort(List):
for i in range(len(List)-1):
for j in range(len(List)-1):
if List[j] > List[j+1]:
List[j],List[j+1]=List[j+1],List[j]
N=int(input())
L=[int(input())for x in range(N)]
bubble_sort(L)
print(L) | true |
d52ef7555a6550304d10ad3c277db851ef515c6d | Python | Frank-LSY/nlp4note | /src/test.py | UTF-8 | 631 | 2.53125 | 3 | [] | no_license | import re
import jsonlines
import json
import time
# a = '[NOTES]20120112[DISCHARGE_SUMMARY].txt'
# b = re.sub(r'\[\w+\]','',a)
# a = a.strip('.txt').replace(']','').replace('[','')
# a= re.sub(r'\d{8}','-',a)
# print(a)
# print(b)
# with open('../stat/output2.jsonl','r') as f:
# for item in jsonlines.Reader(f):
# print('linex_index: ',item['linex_index'])
# # print('token: ', item['features'][0]['token'])
# print('layers: ', item['features'][0]['layers'][0]['index'])
# print('len_val: ', len(item['features'][0]['layers'][0]['values']))
# # print(item)
# # time.sleep(0.5) | true |
dd068b92f83dd8b15c9d854d1ecadffaa058165b | Python | wimpywarlord/hacker_earth_and_hacker_rank_solutions | /K Devices.py | UTF-8 | 366 | 2.828125 | 3 | [] | no_license | import math
z=input()
n,k=z.split()
n=int(n)
k=int(k)
xi=input()
x=xi.split()
for i in range(0,len(x)):
x[i]=int(x[i])
yi=input()
y=yi.split()
for i in range(0,len(y)):
y[i]=int(y[i])
#print(x)
#print(y)
use=[]
for i in range(0,len(x)):
use.append(((x[i])**2+(y[i])**2)**(1/2))
use.sort()
#print(use)
check=use[k-1]
#print(check)
print(math.ceil(check))
| true |
6ab853cbb40c7d3eb177a315ec65e5fe85fb0299 | Python | sesameman/solve-tov-equation | /solve_new_.py | UTF-8 | 4,748 | 2.703125 | 3 | [] | no_license | # !/usr/bin/python3.9
# author:kangjiayin
# time:\now?
import json
import time
import math
# import matplotlib.pyplot as plt
tik=time.time()
# 尝试给出质量半径关系
global step
global times
beta=0.03778
r_0=1.476
A_NR=2.4216
A_R=2.8663
step=0.01
times=2500
def ini(n):
#summass is the tot mass of R
global pressure
global mass
pressure=[]
mass=[0]
# print("----------------------------------------------------------------------")
# print("----------------------------------------------------------------------")
# print('---------------made by kangjiayin,powed by inertia--------------------')
# print("----------------------------------------------------------------------")
# print("----------------------------------------------------------------------")
# print('pls input pressure in the middle,ps:try 0.01')
pressure.append(float(n))
#epsilon是压强的函数,输入一个压强x
def epsilon(p):
###这里我老是报错,说是上边会出现虚数,我看了下也就是p的五分之三次方会产生虚数
###也就是说p在某种情况下变为负数了
###也就是下面我们计算下一个点质量的时候,因为精度限制,会跳到负值(只有p的导数是负的,所以只限制p就可以)
###所以加一个判断
# if p<=0:
# p=1e-10
out=A_NR*p**0.6+A_R*p
return out
#质量对于半径的导数
def massRight(r,p):
out=beta*r**2*epsilon(p)
return out
#压强对于半径的导数
def pressureRight(r,m,p):
#之前老是报错,说是不能除以0,我就把可能出0的地方改了改
out=-r_0*epsilon(p)*(1+p/epsilon(p))*(m+beta*r**3*p)/(r**2-2*r_0*m*r)
return out
#这个函数输入一个n,在此n处已知半径、压强、质量,我们能得到下一组半径、压强、质量
def getNext(n):
#将r、m、p定下来,避免整个数组传参,影响运行速度
r=rad[n]
p=pressure[n]
m=mass[n]
#进行四阶Runge-Kutta近似
#相较于正常的做了一些改动
#km系列是对于质量mass的导数的估计值,kp系列是对于压强p导数的估计值
km_1=massRight(r,p)
kp_1=pressureRight(r,m,p)
km_2=massRight(r+step/2,p+step/2*kp_1)
kp_2=pressureRight(r+step/2,m+step/2*km_1,p+step/2*kp_1)
km_3=massRight(r+step/2,p+step/2*kp_2)
kp_3=pressureRight(r+step/2,m+step/2*km_2,p+step/2*kp_2)
km_4=massRight(r+step,p+step*kp_3)
kp_4=pressureRight(r+step,m+step*km_3,p+step*kp_3)
##############################################################
new_m=m+(km_1+2*km_2+2*km_3+km_4)*step/6
new_p=p+(kp_1+2*kp_2+2*kp_3+kp_4)*step/6
#本来想整个精度的,但这样会收敛到0,报错,所以就不
# new_m=round(m+(km_1+km_2+km_3+km_4)*step/6,10)
# new_p=round(p+(kp_1+kp_2+kp_3+kp_4)*step/6,10)
if new_p<0:
new_p=p/2
mass.append(new_m)
pressure.append(new_p)
#制作一个半径的表格
def makerad():
global rad
rad=[]
for i in range(times+1):
rad.append(i*step+0.0001)
# def showtime():
# print('请输入您要看的图像\n1.质量半径关系(一个中子星的)\n2.压强半径关系')
# showwhat=int(input())
# if showwhat==1:
# plt.plot(rad,mass)
# plt.ylabel(r'M/$\mathrm{M_\odot}$')
# elif showwhat==2:
# plt.plot(rad,pressure)
# else:
# plt.plot(rad,mass)
# plt.plot(rad,pressure)
# plt.xlabel('r/km')
# plt.grid(True)
# plt.show()
def main(n):
ini(n)
makerad()
for j in range(times):
getNext(j)
#这里做一个判断若两次质量之差小于十的五次方,则认为这个中子星到头了,我们记录这个点的质量与半径
#这里加了几条判断,我们认为没有太小的中子星(主要因为老是出接近0质量的中子星,没有意义)
if mass[j]-mass[j-1]<1e-5 and j>50 and rad[j]>2:
#将这个点的中子星半径与质量记录下来
sumMass.append(mass[j])
sumR.append(rad[j])
break
#showtime()
def truemain():
#这两个变量记录质量半径关系
global sumMass
global sumR
sumMass=[]
sumR=[]
filepre='inipre.json'
with open(filepre) as preData:
ini_pressure=json.load(preData)
for n in ini_pressure:
main(n)
#将这个质量半径关系数组输入文件
MassData='MassData.json'
RadData='RadData.json'
with open(RadData,'w') as datarad:
json.dump(sumR, datarad)
with open(MassData,'w') as datamass:
json.dump(sumMass, datamass)
truemain()
tik=round(time.time()-tik,0)
print("总用时为"+str(tik)+'s') | true |
efcd6e593563f581ddd2d700399e9f0903f10a0d | Python | prayash-khati/college-projects | /Shop billing system/StockUpdate.py | UTF-8 | 221 | 2.890625 | 3 | [] | no_license | def read(a,b,c):
file=open("Stock.txt","w")
file.write(str(a))
file.write(str("\n"))
file.write(str(b))
file.write(str("\n"))
file.write(str(c))
file.write(str("\n"))
file.close()
| true |
974cc0bd0a1b6fe58cea4de6c72724e1ca96e51a | Python | hzhang934748656/hello-world | /Leetcode/Leetcode525.py | UTF-8 | 513 | 2.5625 | 3 | [] | no_license | class Solution:
def findMaxLength(self, nums: List[int]) -> int:
lenth = 0
total = 0
dic = {}
for i in range(len(nums)):
if nums[i] == 1:
total += 1
else:
total -= 1
if total in dic:
lenth = max(lenth,i-dic[total])
else:
dic[total] = i
if total == 0:
lenth = i+1
return lenth
| true |
4163940e6ee602b5d977565bda585afcd2cfc32a | Python | Karnakarmarla/ADFAssignments | /Day1/Second.py | UTF-8 | 318 | 3.5625 | 4 | [] | no_license | #2. Program to read a CSV (CSV with n number of columns) and store it in DICT of list.
try:
import csv
ex=[]
with open("E:\ADF Assignments/secondInput.txt",mode='r') as file:
for val in csv.DictReader(file):
ex.append(val)
print(ex)
except:
print("An error occured")
| true |
9830f47475bd8f0cae9387e4942bcdf6615412aa | Python | sendurr/spring-grading | /submission - lab6/set2/DUSTIN S MULLINS_9460_assignsubmission_file_Lab 6/f2c_qa3.py | UTF-8 | 469 | 3.453125 | 3 | [] | no_license | #3.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-f','--f', type=float,
default=-999.0, help='1st parameter')
parser.add_argument('-c', '--c', type=float,
default=-999.0, help='2nd parameter')
args = parser.parse_args()
f = args.f
c = args.c
if f != -999:
C = (f-32)*(5/9.0)
print "input(F):",f
print "output(C):",C #C based on equation
if c != -999:
F = (9.0/5)*(c+32)
print "input(C):",c
print "output(F):",F #F based on equation | true |
e14afbdab836464421e2453ccb47ee065080c763 | Python | rtohid/pearc20_reproducibility | /lra.py | UTF-8 | 1,180 | 2.671875 | 3 | [] | no_license | import time
import numpy as np
from phylanx import Phylanx
from phylanx import PhylanxSession
num_threads = 2
PhylanxSession.init(num_threads)
def lra(x, y, alpha, num_iterations, enable_output=False):
weights = np.zeros(np.shape(x)[1])
transx = np.transpose(x)
pred = np.zeros(np.shape(x)[0])
error = np.zeros(np.shape(x)[0])
gradient = np.zeros(np.shape(x)[1])
step = 0
while step < num_iterations:
if (enable_output):
print("step: ", step, ", ", weights)
pred = 1.0 / (1.0 + np.exp(-np.dot(x, weights)))
error = pred - y
gradient = np.dot(transx, error)
weights = weights - (alpha * gradient)
step += 1
return weights
file_name = "/home/jovyan/10kx10k.csv"
print("reading file, it may take a little while ...")
data = np.genfromtxt(file_name, skip_header=1, delimiter=",")
print("done reading.")
alpha = 1e-5
num_iterations = (10, 10)
phy_lra = Phylanx(lra)
print('num_threads', num_threads)
for n in num_iterations:
phy_lra_start = time.time()
phy_lra(data[:, :-1], data[:, -1], alpha, n)
phy_lra_stop = time.time()
print('phy_lra', phy_lra_stop - phy_lra_start)
| true |
9a43b34a09503399988efad0ddd0baac41441049 | Python | ashifujjmanRafi/code-snippets | /python3/learn-python/built-in-functions/delattr.py | UTF-8 | 967 | 4.34375 | 4 | [
"MIT"
] | permissive | """
The delattr() deletes an attribute from the object (if the object allows it).
delattr(object, name)
* object - the object from which name attribute is to be removed
* name - a string which must be the name of the attribute to be removed from the object
"""
class Coordinate:
x = 10
y = -5
z = 30
point1 = Coordinate()
print("-- Before deleting z --")
print('x = ', point1.x)
print('y = ', point1.y)
print('z = ', point1.z)
a = delattr(Coordinate, 'z')
print(a) # None, nothing return
print("-- After deleting z --")
print('x = ', point1.x)
print('y = ', point1.y)
print('z = ', point1.z)
# using del keyword
class Coordinate:
x = 10
y = -5
z = 30
point1 = Coordinate()
print("-- Before deleting z --")
print('x = ', point1.x)
print('y = ', point1.y)
print('z = ', point1.z)
del Coordinate.z
print("-- After deleting z --")
print('x = ', point1.x)
print('y = ', point1.y)
print('z = ', point1.z)
| true |
1e96d7f6350697060fd070552cc0dd9194ebd2ae | Python | dp834/CS380 | /assignments/3/random_player.py | UTF-8 | 155 | 2.671875 | 3 | [] | no_license | from player import Player
import random
class RandomPlayer(Player):
def getMove(self, board):
return random.choice(self.getNextMoves(board))
| true |
7bd5e844bc50201950dedc272c34ba00de4ce667 | Python | TomHuix/fine_tuning | /encoders.py | UTF-8 | 2,920 | 2.609375 | 3 | [] | no_license | ###This file represents all encoders used in this projet,
## An encoder uses 2 functions, encode: transform e string into encoded vector
## Train: train the model
## For the moment: tfidf, Doc2vec, skip-thoughts, Quick-thoughts, Word2Vec moyenne, Sbert
from nltk.tokenize import word_tokenize
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from sklearn.feature_extraction.text import TfidfVectorizer
from sentence_transformers import SentenceTransformer
import pandas as pd
import numpy as np
import re
from sklearn.metrics.pairwise import cosine_similarity
import matplotlib.pyplot as plt
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from gensim.models import Word2Vec
from gensim.test.utils import common_texts
class encoder_tfidf:
def train(self, corpus):
print("[SYSTEME] train tfidf")
vocabulary = np.unique(word_tokenize(' '.join(corpus)))
self.pipe = Pipeline([('count', CountVectorizer(vocabulary=vocabulary)), ('tfid',TfidfTransformer())]).fit(corpus)
def encode(self, text):
return(self.pipe.transform([text]).toarray()[0])
class encoder_Doc2vec:
def __init__(self, vec_size, max_epochs):
self.model = Doc2Vec(vector_size=vec_size, batch_words=50)
self.max_epochs = max_epochs
def train(self, corpus):
print("[SYSTEME] train d2v")
tagged_data = [TaggedDocument(words=word_tokenize(str(_d).lower()), tags=[str(i)]) for i, _d in enumerate(corpus)]
self.model.build_vocab(tagged_data)
for _ in range(self.max_epochs):
self.model.train(tagged_data,
total_examples=self.model.corpus_count,
epochs=self.model.epochs)
self.model.alpha -= 0.0002
self.model.min_alpha = self.model.alpha
def encode(self, text):
return(self.model.infer_vector([text]))
class mean_word2vec:
def __init__(self, output_size, window, workers, sg):
self.output_size = output_size
self.window = window
self.workers = workers
self.sg =sg
def train(self, corpus):
print("[SYSTEME] train w2v")
corpus = [word_tokenize(sentence) for sentence in corpus]
self.model = Word2Vec(corpus, size=self.output_size, window=self.window, min_count=1, workers=self.workers, sg=self.sg)
def encode(self, text):
vectors = []
for word in word_tokenize(text):
try:
vectors.append(self.model.wv[word])
except:
()
return(np.mean(vectors, axis=0))
#class quick_thoughts:
class encoder_sbert:
def train(self, corpus):
print("[SYSTEME] train sbert")
self.model = SentenceTransformer('bert-base-nli-mean-tokens')
def encode(self, text):
return(self.model.encode([text])[0])
| true |
8e92bd2933097252eb1f78bb49a90d7c07661b4f | Python | nilesh1168/DS-in-Python | /linkedlist.py | UTF-8 | 2,556 | 4.34375 | 4 | [
"MIT"
] | permissive | class Node(object):
def __init__(self,value):
self.value = value
self.next = None
class LinkedList(object):
def __init__(self):
self.head = None
def printList(self):
"""
Prints the contents of the List.
"""
if self.head == None:
print("List is empty!!")
else:
temp = self.head
while temp != None:
print(temp.value)
temp = temp.next
print("End of list")
def insertAtEnd(self,value):
"""
Appends given value at the end of the List.
"""
newNode = Node(value)
if self.head == None:
self.head = newNode
else:
print("inside else")
temp = self.head
while temp.next != None:
temp = temp.next
print("in while")
temp.next = newNode
def insertAtStart(self,value):
"""
Appends given value at the start of the List.
"""
newNode = Node(value)
if self.head == None:
self.head = newNode
else:
temp = self.head
newNode.next = temp
self.head = newNode
def insertBefore(self,nodeValue,value):
"""
Adds node before the given nodeValue.
"""
newNode = Node(value)
if nodeValue == self.head.value:
self.insertAtStart(value)
else:
temp = self.head
while temp:
if temp.next.value == nodeValue:
break
temp = temp.next
newNode.next = temp.next
temp.next = newNode
def insertAfter(self,nodeValue,value):
"""
Adds node before the given nodeValue.
"""
newNode = Node(value)
temp = self.head
while temp:
if temp.value == nodeValue:
break
temp = temp.next
newNode.next = temp.next
temp.next = newNode
def deleteNode(self,value):
"""
Deletes the given node from the list
"""
temp = self.head
while temp:
if temp.next.value == value:
break
temp = temp.next
temp.next = temp.next.next
l = LinkedList()
l.insertAtEnd(2)
l.insertAtEnd(4)
l.insertAtStart(1)
l.printList()
l.insertBefore(1,20)
l.printList()
l.insertAfter(1,30)
l.printList()
l.deleteNode(30)
l.printList() | true |
b6dec768f64e9b10fdd0a73746765555b0a2f73e | Python | dhy12s/dds | /6.19/6.19练习昨晚.py | UTF-8 | 1,234 | 3.328125 | 3 | [] | no_license | class Array:
def __init__(self, capacity):
self.array = [None] * 2 * capacity
self.size = 0
def insert(self, index, element):
"""
:param index:
:type index:
:param element:
:type element:
:return:
:rtype:
"""
if index < 0 or index > self.size:
raise Exception('越界')
if self.size >= len(self.array):
self.kuojie()
for i in range(self.array - 1, index - 1, -1):
self.array[i + 1] = self.array[i]
self.array[index] = element
self.size += 1
def kuojie(self):
new_array = [None] * len(self.array) * 2
for i in range(self.size):
new_array[i] = self.array[i]
self.array = new_array
def shuchu(self):
for i in range(self.size):
print(self.array[i], end='-->')
def remove(self, index):
if index < 0 or index > self.size:
raise Exception('越界')
for i in range(index, self.size):
self.array[i] = self.array[i + 1]
self.size -= 1
"""
:Author: Mr.Dong
:Create: 2020/6.23/19 10:04
:Github: null
Copyright (c) 2020, Mr.Dong Group All Rights Reserved.
""" | true |
8dd7d29dba7b09afad81a9b3b425d1f1a676fdf6 | Python | Prerna13149/NLP_projects | /p2/mynlplib/naive_bayes.py | UTF-8 | 4,421 | 2.9375 | 3 | [] | no_license | from mynlplib.constants import OFFSET
from mynlplib import clf_base, evaluation, preproc
import numpy as np
from collections import defaultdict, Counter
def get_nb_weights(trainfile, smoothing):
"""
estimate_nb function assumes that the labels are one for each document, where as in POS tagging: we have labels for
each particular token. So, in order to calculate the emission score weights: P(w|y) for a particular word and a
token, we slightly modify the input such that we consider each token and its tag to be a document and a label.
The following helper code converts the dataset to token level bag-of-words feature vector and labels.
The weights obtained from here will be used later as emission scores for the viterbi tagger.
inputs: train_file: input file to obtain the nb_weights from
smoothing: value of smoothing for the naive_bayes weights
:returns: nb_weights: naive bayes weights
"""
token_level_docs=[]
token_level_tags=[]
for words,tags in preproc.conll_seq_generator(trainfile):
token_level_docs += [{word:1} for word in words]
token_level_tags +=tags
nb_weights = estimate_nb(token_level_docs, token_level_tags, smoothing)
return nb_weights
# Can copy from P1
def get_corpus_counts(x,y,label):
"""
Compute corpus counts of words for all documents with a given label.
:param x: list of counts, one per instance
:param y: list of labels, one per instance
:param label: desired label for corpus counts
:returns: defaultdict of corpus counts
:rtype: defaultdict
"""
counts = Counter()
for i in range(len(x)):
if(y[i]==label):
counts.update(x[i])
#print(counts)
res = defaultdict(int, counts)
return res
# Can copy from P1
def estimate_pxy(x,y,label,smoothing,vocab):
'''
Compute smoothed log-probability P(word | label) for a given label.
:param x: list of counts, one per instance
:param y: list of labels, one per instance
:param label: desired label
:param smoothing: additive smoothing amount
:param vocab: list of words in vocabulary
:returns: defaultdict of log probabilities per word
:rtype: defaultdict of log probabilities per word
'''
corpus_ct = get_corpus_counts(x, y, label)
#print(corpus_ct)
deno = 0;
for word in vocab:
deno = deno + corpus_ct[word]
prob = 1
logprob_dict={}
for word in vocab:
prob = np.log((corpus_ct[word] + smoothing)/(deno + smoothing*len(vocab)))
logprob_dict[word] = prob
res = defaultdict(float, logprob_dict)
return res
# Can copy from P1
def estimate_nb(x,y,smoothing):
"""
estimate a naive bayes model
:param x: list of dictionaries of base feature counts
:param y: list of labels
:param smoothing: smoothing constant
:returns: weights
:rtype: defaultdict
"""
count = Counter()
for small_bow in x:
count.update(small_bow)
prob_labels={}
vocab = []
for ele in count:
vocab.append(ele)
#print(vocab)
label_count = Counter(y)
#print(label_count)
labels = set(y)
for lbl in labels:
prob_labels[lbl] = np.log(label_count[lbl]/len(y))
#print(prob_labels)
weights=defaultdict(float)
for lbl in labels:
temp = estimate_pxy(x, y, lbl, smoothing, vocab)
temp[OFFSET] = prob_labels[lbl]
weights[lbl] = temp
result = defaultdict(float)
for lbl in weights.keys():
for key2 in weights[lbl].keys():
result[(lbl, key2)] = weights[lbl][key2]
# result = defaultdict(float, weights)
return result
# Can copy from P1
def find_best_smoother(x_tr,y_tr,x_dv,y_dv,smoothers):
'''
find the smoothing value that gives the best accuracy on the dev data
:param x_tr: training instances
:param y_tr: training labels
:param x_dv: dev instances
:param y_dv: dev labels
:param smoothers: list of smoothing values
:returns: best smoothing value
:rtype: float
'''
my_acc_dict = {}
max_score = 0.0;
for i in range(len(smoothers)):
weights = estimate_nb(x_tr, y_tr, smoothers[i])
y_hat = clf_base.predict_all(x_dv,weights,y_dv)
acc = evaluation.acc(y_hat,y_dv)
if( acc > max_score):
max_score = acc
my_acc_dict[smoothers[i]] = acc
return max_score, my_acc_dict
| true |
c83f5f59ac08fd96a6a071624cceb2eae78b3fb2 | Python | deepakpunjabi/ntp_time_synchronization | /clustering.py | UTF-8 | 6,774 | 2.796875 | 3 | [] | no_license | #! /usr/bin/python
from numpy import mean, sqrt, square, arange
# ------------------------------------------------------input Given by filtering algorithm--------------------------------------------------------------------
#server vector with each element containing O(i)=offset and r(i)=root distance
#peerjitter vector with each element containing peerjitter for each server
server=[[1.2432343,0.56565],[1.8923232,1.2323],[0.433232,0.43545],[1.202323,0.1112],[0.222323,1.34343],[1.2223232,1.2323],[0.133434343,0.245544]]
peerjitter=[0.454545,0.65756556,0.545432323,0.787878787,0.45454,0.67676, 0.1004343]
#-------------------------------------------------------------------------------------------------------------------------------------------------------------
correcteness_interval=[]#for each server construct[O(i)-r(i),O(i)+r(i)]
jitterlist=[] #select jitter relative to each cadidate in truechimers each element is a list
lowpoint=[]#lowest point of correctness interval
midpoint=[]#mid point of correctness interval
highpoint=[]#highest point of correctness interval
selectjitter=[] #root mean squred of each element in jitterlist
temp=[]#lowest, mid and highest point in sorted order
currentlowpoint=[]#lower end of intersection interval
currenthighpoint=[]#higher end of inter section interval
minclock=2#we keep at least 2 clocks as threshold
print server
#***************************************Clock Selection Algorithm****************************************************
#Input: servers in form of server vector
#Output: Prune servers in form of server vector
#----------------------------------------for each server construct[O(i)-r(i),O(i)+r(i)]-------------------------------
for x in server:
temp=[]
temp.append(x[0]-x[1])
temp.append(x[0]+x[1])
correcteness_interval.append(temp)
#-----------------------------------------------------------------------------------------------------------------------------
#-----------------for each correctness interval find lowest, mid and highest point and sorting them------------------------
temp=[]
for x in correcteness_interval:
temp.append(x[0])
lowpoint.append(x[0])
temp.append((x[0]+x[1])/2)
midpoint.append((x[0]+x[1])/2)
temp.append(x[1])
highpoint.append(x[1])
temp=sorted(temp)
#-------------------------------------------------------------------------------------------------------------------------
#-------------------------------Code to find intersection interval-----------------------------------------------------------
flag=0
f=0
while True:
n=0
for x in temp:
if x in lowpoint:
n=n+1
if x in highpoint:
n=n-1
if (n>=len(server)-f):
currentlowpoint=x
break
n=0
for x in reversed(temp):
if x in lowpoint:
n=n-1
if x in highpoint:
n=n+1
if (n>=len(server)-f):
currenthighpoint=x
break
if (currentlowpoint<currenthighpoint):
flag=1
break
if f<(len(server)/2):
f=f+1
else:
break
if flag==1:
print currentlowpoint
print currenthighpoint
if flag==0:
print "Not found"
#-----------------------------------------------------------------------------------------------------------------------------
#---------------------Finding server which lies between intersction interval, prune false server------------------------------
for x in correcteness_interval:
if (x[1]>currentlowpoint) and (x[0]<currenthighpoint):
pass
else:
if ((len(server))-1)==(correcteness_interval.index(x)):
del server[-1]
else:
server.pop(correcteness_interval.index(x))
print server
#-------------------------------------------------------------------------------------------------------------------------------
#***********************************End of Clock Selection Algorithm*************************************************************
#***********************************Clustering Algorithm*************************************************************************
#The clock cluster algorithm processes the pruned servers produced by the clock select algorithm to produce a list of survivors.
jitterlist=[] #jitter relative to the ith candidate is calculated as follows.
selectjitter=[] #computed as the root mean square (RMS) of the di(j) as j ranges from 1 to n
#----------------------------------relative jitter for each server----------------------------------------------------------------
while len(server)>minclock:
selectjitter=[]
jitterlist=[]
for x in server:
temp=[]
for y in server:
if x!=y:
z=abs((y[0]-x[0]))*x[1]
temp.append(z)
jitterlist.append(temp)
#print jitterlist
#------------------------------------------------------------------------------------------------------------------------------------
#--------------------------------omputed as the root mean square (RMS)--------------------------------------------------------------
for x in jitterlist:
rms = sqrt(mean(square(x)))
selectjitter.append(rms)
#print selectjitter
#print peerjitter
#------------------------------------------------------------------------------------------------------------------------------------
#---------------------------------clustering algorithm to generate final servers-------------------------------------------------------
maximum_select_jitter=max(selectjitter)
minimum_peer_jitter=min(peerjitter)
#print maximum_select_jitter
#print minimum_peer_jitter
if maximum_select_jitter>minimum_peer_jitter:
index=selectjitter.index(maximum_select_jitter)
if ((len(server))-1)==index:
del server[-1]
else:
server.pop(index)
else:
break
print server
#---------------------------------------------------------------------------------------------------------------------------------------
#***********************************End of clustering algorithm*************************************************************************
#***********************************Clock Combining Algorithm***************************************************************************
#------------------------------------Calculate normalization constat a-------------------------------------------------------------------
y=0
for x in server:
y=y+(1/x[1])
a=1/y
print a
#----------------------------------------------------------------------------------------------------------------------------------------
#-----------------------------------------Finding final offset value ---------------------------------------------------
y=0
for x in server:
y=y+(x[0]/x[1])
T=a*y
print T
# T is our final offset value
#----------------------------------------------------------------------------------------------------------------------------------------
#***************************************8End of Clock combining algorithm******************************************************************* | true |
395b779317e9bbbe9ad2e262fb55ec96033e75c8 | Python | auriix/M3 | /Python_comentado/17-03-20/plantilla_bucle.py | UTF-8 | 271 | 3.8125 | 4 | [] | no_license | #coding: utf-8
#Variables
salir = False
#Condició d'entrada al bucle.
while (salir == False) :
#Print
print ("Hola")
#Read
tecla = raw_input ("Sal con s o S:")
#Condició de sortida del bucle.
if (tecla == "S" or tecla == "s" ) :
print ("Adiós")
salir = True
| true |
5ef54a711d27cbe0618e7512b172f8065e7ab36c | Python | Jmosesee/python-challenge | /PyPoll/main.py | UTF-8 | 1,487 | 2.65625 | 3 | [
"MIT"
] | permissive | import os
import csv
folder_name = os.path.join('C:', '\\Users', 'jmose', 'Downloads', 'UDEN201805DATA1-master', 'UDEN201805DATA1-master', 'Week3 - Python', 'Python HW', 'PyPoll', 'raw_data')
csvpath1 = os.path.join(folder_name, 'election_data_1.csv')
csvpath2 = os.path.join(folder_name, 'election_data_2.csv')
report_path = os.path.join(folder_name, 'report.txt')
with open(csvpath1) as f_in:
reader = csv.reader(f_in)
next(reader) #Skip header row
data = list(reader)
voter_id_column = 0
county_column = 1
candidate_column = 2
vote_list = [row[candidate_column] for row in data]
total_votes = len(vote_list)
candidate_list = list(set([row[candidate_column] for row in data]))
vote_count = [vote_list.count(candidate) for candidate in candidate_list]
vote_percentage = [c/sum(vote_count) for c in vote_count]
(max_votes, max_i) = max((v,i) for i,v in enumerate(vote_count))
winner = candidate_list[max_i]
output_text = []
output_text.append("Election Results")
output_text.append("----------------------------")
output_text.append("Total Votes: {}".format(total_votes))
output_text.append("----------------------------")
for i,v in enumerate(candidate_list):
output_text.append("{}: {}% ({})".format(candidate_list[i], vote_percentage[i], vote_count[i]))
output_text.append("----------------------------")
output_text.append("Winner: {}".format(winner))
with open(report_path, "w+") as f_out:
for line in output_text:
print(line)
f_out.write(line)
f_out.write("\r\n")
| true |
0c35760e2dca99f2fd28d86dde786bffe492e39e | Python | marcus-goncalves/udemy-tdd | /section2/test_fizz_buzz.py | UTF-8 | 1,359 | 4.21875 | 4 | [] | no_license | """
USE CASES:
- Call FizzBuzz function
- Get "1" when 1 is passed
- Get "2" when 2 is passed
- Get "Fizz" when 3 is passed
- Get "Buzz" when 5 is passed
- Get "Fizz" when a multiple of 3 is passed (6)
- Get "Buzz" when a multiple of 5 is passed (10)
- Gut "FizzBuzz" when a multiple of 3 and 5 is passed (15)
"""
# Support Functions
def check_fizz_buzz(val: int, expected: str) -> None:
result = fizz_buzz(val)
assert result == expected
def is_multiple(val: int, mod: int) -> bool:
return val % mod == 0
# FUNCTION TO BE TESTED
def fizz_buzz(number: int) -> str:
if is_multiple(number, 3) and is_multiple(number, 5):
return "FizzBuzz"
if is_multiple(number, 3):
return "Fizz"
if is_multiple(number, 5):
return "Buzz"
return str(number)
# UNIT TEST FUNCTIONS
def test_return1With1PassedIn() -> None:
check_fizz_buzz(1, "1")
def test_return2With2PassedIn() -> None:
check_fizz_buzz(2, "2")
def test_returnFizzWith3PassedIn() -> None:
check_fizz_buzz(3, "Fizz")
def test_returnBuzzWith5PassedIn() -> None:
check_fizz_buzz(5, "Buzz")
def test_returnFizzWith6PassedIn() -> None:
check_fizz_buzz(6, "Fizz")
def test_returnFizzWith10PassedIn() -> None:
check_fizz_buzz(10, "Buzz")
def test_returnFizzBuzzWith15PassedIn() -> None:
check_fizz_buzz(15, "FizzBuzz")
| true |
827b40b8f3f40a00f6964d80ee7cddbaeecb7c03 | Python | syurskyi/Algorithms_and_Data_Structure | /_algorithms_challenges/w3resource/W3resource-exercises-master/12. Print calender of a given month.py | UTF-8 | 205 | 3.6875 | 4 | [] | no_license | import calendar
c_year, c_month = int(input("Write the year, you want the calendar from: ")), int(input("Write the number of the month you want the calendar from: "))
print(calendar.month(c_year, c_month)) | true |
c3070b78f03dc7d74081a1dc14e7255571d5ff92 | Python | VincentGaoHJ/Sword-For-Offer | /rsc/1_easy/offer_58_1.py | UTF-8 | 1,289 | 4.1875 | 4 | [] | no_license | # coding=utf-8
"""
@Time : 2020/10/27 9:45
@Author : Haojun Gao (github.com/VincentGaoHJ)
@Email : vincentgaohj@gmail.com haojun.gao@u.nus.edu
@Sketch : 剑指 Offer 58 - I. 翻转单词顺序
https://leetcode-cn.com/problems/fan-zhuan-dan-ci-shun-xu-lcof/
"""
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
s = s.strip() # 删除首尾空格
i = j = len(s) - 1
res = []
while i >= 0:
while i >= 0 and s[i] != ' ': # 搜索首个空格
i -= 1
res.append(s[i + 1:j + 1]) # 添加单词
while s[i] == ' ': # 跳过单词间空格
i -= 1
j = i # j 指向下个单词的尾字符
return ' '.join(res) # 拼接并返回
def offer_58(s):
"""
输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。
为简单起见,标点符号和普通字母一样处理。
例如输入字符串 "I am a student.",则输出 "student. a am I"。
:param s:
:return:
"""
solution = Solution()
output = solution.reverseWords(s)
print(output)
if __name__ == '__main__':
# 剑指 Offer 58 - I. 翻转单词顺序
offer_58("the sky is blue")
| true |
edf6acc9d16c366e12443d939ef9ca6f06e0c295 | Python | gabeart10/pi_stuff | /binary_clock | UTF-8 | 1,871 | 2.890625 | 3 | [] | no_license | #!/usr/bin/env python3
import RPi.GPIO as GPIO
import time
import colors as c
GPIO.setmode(GPIO.BCM)
pins = [17,27,22,5,6,13,19,26]
set_num = 0
num = 0
set_num2 = 0
off_num = 0
GPIO.setwarnings(False)
for item in pins:
GPIO.setup(pins[set_num], GPIO.OUT)
set_num += 1
GPIO.setup(24, GPIO.IN)
try:
while True:
inputValue = GPIO.input(24)
for item2 in pins:
GPIO.output(pins[set_num2], 0)
set_num2 += 1
set_num2 = 0
if inputValue == True or num == 254:
speed = input("What Speed?\n")
for num in range(255):
current_binary = 0
current_pin = 0
binary = list(bin(num)[:1:-1])
for z in pins:
GPIO.output(pins[off_num], 0)
set_num += 1
if num < 2:
repeat_times = 1
elif num > 1 and num < 4:
repeat_times = 2
elif num > 3 and num < 8:
repeat_times = 3
elif num > 7 and num < 16:
repeat_times = 4
elif num > 15 and num < 32:
repeat_times = 5
elif num > 31 and num < 64:
repeat_times = 6
elif num > 63 and num < 128:
repeat_times = 7
elif num < 127:
repeat_times = 8
print(c.clear)
inputValue = GPIO.input(24)
if inputValue == True:
print(c.blue + "Let Go!" + c.reset)
time.sleep(1.5)
break
for o in range(repeat_times):
GPIO.output(pins[current_pin], int(binary[current_binary]))
current_binary += 1
current_pin += 1
print("Number:" + str(num))
print(binary)
time.sleep(float(speed))
except KeyboardInterrupt:
GPIO.cleanup()
exit()
| true |
b56a2c8f87dbff07cfa916b69b0cf5bb7bd16409 | Python | diegobonilla98/Deep-Face-Creator | /API_20.py | UTF-8 | 1,878 | 2.59375 | 3 | [] | no_license | from keras.engine.saving import load_model
import numpy as np
import cv2
from tkinter import Tk, Label, Scale, VERTICAL
from PIL import Image, ImageTk
class API:
def __init__(self, master):
self.master = master
master.title("Face Creation")
self.model = load_model('run\\weights\\decoder_VAE_faces_20_dim.h5')
self.labels = ["Edad", "Sonrisa", "Ojos", "Redondez", "Dientes", "Genero", "Edad", "NaN", "Raza", "Tono piel",
"Calidez", "Angulo cabeza", "Edad", "Color pelo", "Nan", "Nan", "Tono piel", "Genero", "Nan", "Luz"]
self.image_size = (256, 256)
self.image = ImageTk.PhotoImage(Image.fromarray(np.zeros((self.image_size[0], self.image_size[1], 3), 'uint8')))
self.canvas = Label(master, image=self.image)
self.canvas.grid(column=0, row=0)
self.scales = []
for i in [2, 4]:
for j in range(10):
self.label = Label(master, text=self.labels[j if i == 2 else (j + 10)])
self.label.grid(column=j+2, row=i-1)
self.scales.append(Scale(master, from_=-50, to=50, orient=VERTICAL, command=self.updateValue))
self.scales[-1].grid(column=j+2, row=i)
def updateValue(self, event):
input_tensor = []
for scale in self.scales:
input_tensor.append(scale.get() / 10)
input_tensor = np.array(input_tensor, 'float32').reshape((1, 20))
output_tensor = self.model.predict(input_tensor)[0]
output_image = (output_tensor * 255).astype('uint8')
output_image = cv2.resize(output_image, self.image_size, cv2.INTER_CUBIC)
image = ImageTk.PhotoImage(Image.fromarray(output_image))
self.canvas.configure(image=image)
self.canvas.image = image
root = Tk()
my_gui = API(root)
root.mainloop()
| true |
b5a8933e83b16936c13ed6b9dd7fefc44648fa02 | Python | Hethsi/project | /91.py | UTF-8 | 161 | 2.96875 | 3 | [] | no_license | def cuboid(1,h,w):
return(l*h*w)
def scuboid(l,h,w):
return(2*1*w+2*w*h+2*1+h)
l=1
h=5
w=7
print("V=",cuboid(l,h,w))
print("total surface area=",scuboid(l,h,w))
| true |
58b55699c9a23a90d774e21d19cd0d33bb70a189 | Python | Zaka/muia-tfm-neuralnet | /neural-net-deep.py | UTF-8 | 2,054 | 2.953125 | 3 | [] | no_license | import numpy
import pandas
import time
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasRegressor
from keras.regularizers import l2
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import TimeSeriesSplit
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.metrics import mean_absolute_error
# Visualization
from keras.utils.visualize_util import plot
# load dataset
dataframe = pandas.read_csv("../muia-tfm-data/data-set.csv")
# length = len(dataframe)
# dataframe = dataframe[(length - 20):length]
dataset = dataframe.values
# split into input (X) and output (Y) variables
X = dataset[:,1:-1]
Y = dataset[:,-1]
seed = 7
numpy.random.seed(seed)
print("Building the model.")
# Define NNs structure
def deeper_model():
# create model
model = Sequential()
model.add(Dense(10, input_dim=18,
init='normal',
W_regularizer = l2(0.001),
activation='relu'))
model.add(Dense(10, init='normal',
activation='relu',
W_regularizer = l2(0.001)))
model.add(Dense(1, activation='linear',
W_regularizer = l2(0.001)))
# Compile model
model.compile(loss='mean_squared_error',
optimizer='adam')
return model
t0 = time.time()
mlp = KerasRegressor(build_fn=deeper_model,
nb_epoch=1000, batch_size=32,
verbose=0)
print("Performing Time Series Cross Validation.")
tscv = TimeSeriesSplit(n_splits = len(X) - 1)
results = cross_val_score(mlp, X, Y, cv=tscv)
t1 = time.time()
mae = mean_absolute_error(Y[1:], results)
market_price_stddev = 218.3984954558443689621
market_price_mean = 155.3755406486043852965
real_mae = (mae * market_price_stddev) + market_price_mean
print("Normalized MAE: %.4f" % (mae))
print("\"Denormalized\" MAE: %.4f USD" %(real_mae))
print("It took %f seconds" % (t1 - t0))
print("Finished.")
| true |
ccf6c209ee063a96ae5c3503274bd2f9a9352a69 | Python | yo16/tips_python | /numpy/HelloNumpy.py | UTF-8 | 1,401 | 3.3125 | 3 | [
"MIT"
] | permissive | # はじめてのNumPy
# 参考 http://qiita.com/wellflat/items/284ecc4116208d155e01
# 2016/1/16
import numpy as np
a = np.array([[1,2,3], [4,5,6], [7,8,9], [10,11,12]])
print(a)
print(a.flags)
# C_CONTIGUOUS : True ## データがメモリ上に連続しているか(C配列型)
# F_CONTIGUOUS : False ## 同上(Fortran配列型)
# OWNDATA : True ## 自分のデータかどうか、ビュー(後述)の場合はFalse
# WRITEABLE : True ## データ変更可能か
# ALIGNED : True ## データ型がアラインされているか
# UPDATEIFCOPY : False ## Trueには変更できないので特に気にしなくて良い
# 次元数
print( "%d次元" % a.ndim )
# 2
# 要素数
print( "要素数:%d" % a.size )
# 12
# 各次元の要素数(行数, 列数)
print( "各次元の要素数(行数, 列数):(%d, %d)" % a.shape )
# (4, 3)
# 1要素のバイト数
print( "1要素のバイト数:%d" % a.itemsize )
# 4
# 64bit版だと、8かも
# 次の行までのバイト数
# 24バイトで次の行、8バイトで次の列
print( "%dバイトで次の行, %dバイトで次の列" % a.strides )
# (12, 4)
# 1,2,3
# 4,5,6
# の順で直列に並んでいるということ。
# 配列全体のバイト数
print( "配列全体のバイト数:%dbyte" % a.nbytes )
# 48 # a.itemsize * a.size
# 要素のデータ型
print( "型:%s" % a.dtype )
# int32
| true |
2b6dd3dd77810200fa26f8d7380ba92a6a4ee45e | Python | sumit15bt/SuperVisedML | /speechReco.py | UTF-8 | 908 | 2.6875 | 3 | [
"Apache-2.0"
] | permissive | import speech_recognition as sr
import pyaudio
r = sr.Recognizer()
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source)
print("speak with ur sweet vocal-cord ...")
audio = r.listen(source) # get audio from the microphone
print("Done")
try:
text=r.recognize_google(audio,language='hi-IN') #google api for hindi
print("You said .." )
print(text) #printing your sweet voice to text form
except sr.UnknownValueError:
print("Could not understand audio")
except sr.RequestError as e:
print("Could not request results; {0}".format(e))
'''
if your voice does not recognize
pip install --upgrade gcloud
pip install --upgrade google-api-python-client
'''
| true |
4563a476cf837b446e5975f1e85ca7a0b3d58178 | Python | spawnmarvel/API_Lib | /app/database/repository.py | UTF-8 | 551 | 2.59375 | 3 | [] | no_license | import logging
class Repository():
"""docstring for Repository"""
def __init__(self):
self.log = logging.getLogger(self.__class__.__name__)
self.log.info("init repository")
def load_repository(self):
self.log.info("started load repository")
data_repository = [
{
"id": 1,
"name": u"tag1",
"value": 492.2,
u"quality": "good"
},
{
"id": 2,
"name": u"tag2",
"value": 692.2,
u"quality": "good"
}
]
return data_repository
| true |
7f8c195e32c6625dd9a69c999b89806d166bc198 | Python | njgheorghita/ethpm-cli | /tests/core/_utils/test_etherscan.py | UTF-8 | 1,295 | 2.515625 | 3 | [
"MIT"
] | permissive | import pytest
from ethpm_cli._utils.etherscan import is_etherscan_uri
@pytest.mark.parametrize(
"uri,expected",
(
("etherscan://0x6b5DA3cA4286Baa7fBaf64EEEE1834C7d430B729:1", True),
("etherscan://0x6b5DA3cA4286Baa7fBaf64EEEE1834C7d430B729:3", True),
("etherscan://0x6b5DA3cA4286Baa7fBaf64EEEE1834C7d430B729:4", True),
("etherscan://0x6b5DA3cA4286Baa7fBaf64EEEE1834C7d430B729:5", True),
("etherscan://0x6b5DA3cA4286Baa7fBaf64EEEE1834C7d430B729:42", True),
("etherscan://:1", False),
("etherscan://invalid:1", False),
# non-checksummed
("etherscan://0x6b5da3ca4286baa7fbaf64eeee1834c7d430b729:1", False),
# bad path
("etherscan://0x6b5DA3cA4286Baa7fBaf64EEEE1834C7d430B729/1", False),
# no chain_id
("etherscan://0x6b5DA3cA4286Baa7fBaf64EEEE1834C7d430B729", False),
("etherscan://0x6b5DA3cA4286Baa7fBaf64EEEE1834C7d430B729:", False),
("etherscan://0x6b5DA3cA4286Baa7fBaf64EEEE1834C7d430B729:10", False),
("://0x6b5DA3cA4286Baa7fBaf64EEEE1834C7d430B729:1", False),
("xetherscan://0x6b5DA3cA4286Baa7fBaf64EEEE1834C7d430B729:1", False),
),
)
def test_is_etherscan_uri(uri, expected):
actual = is_etherscan_uri(uri)
assert actual == expected
| true |
f29eeae3c6818b1a2551619ce02337a241cc199d | Python | bpRsh/b1_research_lib | /read_some_columns.py | UTF-8 | 768 | 2.578125 | 3 | [] | no_license | #!/usr/local/bin/env python3
# -*- coding: utf-8 -*-#
#
# Author : Bhishan Poudel; Physics Graduate Student, Ohio University
# Date : Feb 11, 2017
# Last update :
# Est time :
# Imports
import pandas as pd
import numpy as np
infile = 'centroidsf8.csv'
# read first 2 columns
df = pd.read_csv(infile, sep=' ', skipinitialspace=True, header=None)
df2 = df.loc[:, [0, 1]]
# df2.to_csv(infile, header=None, index=None, sep=' ')
print(df2.head())
# usecols
df2 = pd.read_csv(infile, sep='\s+', skipinitialspace=True, header=None,
usecols=[0, 1])
print(df2.head())
# numpy.genfromtxt and np.savetxt
data = np.genfromtxt(infile, delimiter=None, usecols=(0, 1), dtype=int)
print(data[:4])
np.savetxt('temp.csv', data, fmt='%.0f', delimiter=' ')
| true |
4b033a5de5e06297ab2c6d2bfecb8fd2638afa26 | Python | AgustinParmisano/tecnicatura_analisis_sistemas | /programacion1/practica2/ejemplo_cond.py.save | UTF-8 | 161 | 3.296875 | 3 | [
"Python-2.0"
] | permissive | #!/usr/bin/python
a = (3 > 1)
b = (3 > 3)
c = (5 % 2) == 0
d = "hola"[2] == "l"
if a and b:
print("hola")
elif(d or b):
print("chau")
else:
print("aloha")
| true |
e07e632ab4c882744b28565f50746949fea4e4fa | Python | MyakininMikhail/Dec25 | /Lesson_02-Example_10.py | UTF-8 | 204 | 3.6875 | 4 | [] | no_license | i = 0
number = int(input())
while number > 0:
if number % 10 == 5:
i += 1
number = number // 10
print(i)
"""
Задача 10.
Найти количество цифр 5 в числе
""" | true |
f4b635e94880987534742e61f18eb0133aeb7d6b | Python | vladddev/altec_backend | /app/helpers/model_helpers.py | UTF-8 | 623 | 2.609375 | 3 | [] | no_license | import json
from datetime import datetime
def add_history_action_to_model(model, action_str):
if hasattr(model, 'actions_json'):
actions_json = model.actions_json
if actions_json == "":
json_log = list()
else:
json_log = json.loads(actions_json)
timestamp = round(datetime.now().timestamp())
json_log.append({
'timestamp': timestamp,
'action': action_str
})
new_log = json.dumps(json_log)
model.actions_json = new_log
model.save(update_fields=['actions_json'])
| true |
f7bc3d9a4810af288a6ca2947b72f2be11c662f3 | Python | EloyMartinez/AI-TP1-UQAC | /bfsTest/test.py | UTF-8 | 140 | 2.984375 | 3 | [
"MIT"
] | permissive | test = []
if test == [] :
print('hey')
test.append('hey')
if test == [] :
print('hey2')
if test != [] :
print('hey3') | true |
34e8bf8e180361f666d865bede78f232d89522e7 | Python | Agile555/GEDCOMProj | /modules/us21.py | UTF-8 | 1,309 | 3.125 | 3 | [] | no_license | """
User story 21 prints an error if the mother is not female
and the Husband is not Male.
@author: Besnik Balaj
"""
from lib.user_story import UserStory
from datetime import datetime
class UserStory21(UserStory):
def print_rows(self, rows):
for row in rows:
if row[0] == 'F':
print('REPORT: INDIVIDUAL: US21: Husband {} is the incorrect gender for their role, Individual is Female. when they should be Male'.format(row[1]))
else:
print('REPORT: INDIVIDUAL: US21: Wife {} is the incorrect gender for their role, Individual is Male. when they should be Female'.format(row[1]))
def get_rows(self, conn):
c = conn.cursor()
res = []
HusbandGend = c.execute('SELECT INDI.Gender, FAM."Husband ID" FROM FAM INNER JOIN INDI ON (INDI.ID=Fam."Husband ID") WHERE INDI.Gender != "NA" AND Fam."Husband ID"!="NA"').fetchall()
WifeGend = c.execute('SELECT INDI.Gender, FAM."Wife ID" FROM FAM INNER JOIN INDI ON (INDI.ID=Fam."Wife ID") WHERE INDI.Gender != "NA" AND Fam."Wife ID"!="NA"').fetchall()
for HCheck in HusbandGend:
if HCheck[0] == "F":
res.append(HCheck)
for WCheck in WifeGend:
if WCheck[0] == "M":
res.append(WCheck)
return res
| true |
5edf20a8f823fb2474ee24073688d6b092f646a9 | Python | Vincent36912/python200818 | /turtle 1.py | UTF-8 | 217 | 3.59375 | 4 | [] | no_license | import turtle
import time
a=turtle.Turtle()
a.forward(100)
time.sleep(2)
a.left(90)
a.forward(100)
time.sleep(2)
a.left(90)
a.forward(100)
time.sleep(2)
a.left(90)
a.forward(100)
time.sleep(2)
a.left(90) | true |
5772403a2648d984f43af46e28596e9ee6053ce5 | Python | hellosandeep1999/Machine_Learning | /tshirts_DBSCAN.py | UTF-8 | 1,656 | 3.15625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 30 17:49:43 2020
@author: user
"""
"""
Q2. (Create a program that fulfills the following specification.)
tshirts.csv
T-Shirt Factory:
You own a clothing factory. You know how to make a T-shirt given the height
and weight of a customer.
You want to standardize the production on three sizes: small, medium, and large.
How would you figure out the actual size of these 3 types of shirt to better
fit your customers?
Import the tshirts.csv file and perform Clustering on it to make sense out of
the data as stated above.
"""
import numpy as np
import pandas as pd
from sklearn.cluster import DBSCAN
from sklearn import metrics
from sklearn.datasets.samples_generator import make_blobs
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
dataset = pd.read_csv('tshirts.csv')
features = dataset.iloc[:, [1, 2]].values
plt.scatter(features[:,0], features[:,1])
plt.show()
db = DBSCAN(eps=5, min_samples=3)
model = db.fit(features)
labels = model.labels_
n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
n_noise_ = list(labels).count(-1)
#sample_cores = np.zeros_like(labels, dtype=bool)
#sample_cores[db.core_sample_indices_] = True
plt.scatter(features[labels== 0,0], features[labels == 0,1],c='red', marker='+' )
plt.scatter(features[labels == 1,0], features[labels == 1,1],c='green', marker='o' )
plt.scatter(features[labels == -1,0],features[labels == -1,1],c='yellow', marker='*' )
print(metrics.silhouette_score(features,labels)) #0.4634948611025891
------------------------------------------------------------------------------------- | true |
567611736cf57ee4c17d190ffb78b092e54b081b | Python | rorymcgrath/ludum-dec12 | /jsbuild.py | UTF-8 | 1,602 | 2.625 | 3 | [] | no_license | #!/usr/bin/env python
"""Shitty JS project build script v0.2"""
import os
from PIL import Image
def buildProject(outname, templatename):
template = open(templatename, "r")
outfile = open(outname, "w")
levelDir = os.path.abspath("data")
outfile.write("var levelData = {\n")
for fileName in os.listdir(levelDir):
outfile.write(fileName.split(".")[0] + "Pixels")
outfile.write(" : [")
im = Image.open(os.path.join("data", fileName))
w, h = im.size
for r in range(h):
for c in range(w):
outfile.write(",".join([str(p) for p in im.getpixel((c, r))]))
outfile.write(",")
outfile.write("],\n")
outfile.write("%sWidth : %s,\n" % (fileName.split(".")[0], w))
outfile.write("%sHeight : %s,\n" % (fileName.split(".")[0], h))
outfile.write("}\n")
for i, line in enumerate(template):
if "#include" in line:
incfile = line.split()[1]
jspath = os.path.abspath(incfile)
if os.path.exists(jspath):
f = open(jspath, "r")
for x in f:
outfile.write(x)
else:
print 'ERROR in: "%s", line: %i' % (templatename, i + 1)
print 'File "%s" not found, FAILED.' % incfile
outfile.close()
os.remove(outname)
sys.exit()
else:
outfile.write(line)
template.close()
outfile.close()
print "BUILD COMPLETE"
if __name__ == "__main__":
buildProject("game.js", "template.js")
| true |
12b488a0cefc2a3276edf1e234b97ef8dc05c06b | Python | akkayaburak/NN-DL-getting-started | /Logistic Regression with a Neural Network.py | UTF-8 | 6,598 | 2.84375 | 3 | [] | no_license | import numpy as np
import matplotlib.pyplot as plt
import h5py
import scipy
from PIL import Image
from scipy import ndimage
from lr_utils import load_datasets
#%matplotlib inline
# Loading the data (cat/non-cat)
train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()
# Example of a picture
index = 10
plt.imshow(train_set_x_orig[index])
print ("y = " + str(train_set_y[:, index]) + ", it's a '" + classes[np.squeeze(train_set_y[:, index])].decode("utf-8") + "' picture.")
m_train = train_set_x_orig.shape[0]
m_test = test_set_x_orig.shape[0]
num_px = train_set_x_orig.shape[1]
print ("Number of training examples: m_train = " + str(m_train))
print ("Number of testing examples: m_test = " + str(m_test))
print ("Height/Width of each image: num_px = " + str(num_px))
print ("Each image is of size: (" + str(num_px) + ", " + str(num_px) + ", 3)")
print ("train_set_x shape: " + str(train_set_x_orig.shape))
print ("train_set_y shape: " + str(train_set_y.shape))
print ("test_set_x shape: " + str(test_set_x_orig.shape))
print ("test_set_y shape: " + str(test_set_y.shape))
# Reshape the training and test examples
train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T
test_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T
print ("train_set_x_flatten shape: " + str(train_set_x_flatten.shape))
print ("train_set_y shape: " + str(train_set_y.shape))
print ("test_set_x_flatten shape: " + str(test_set_x_flatten.shape))
print ("test_set_y shape: " + str(test_set_y.shape))
print ("sanity check after reshaping: " + str(train_set_x_flatten[0:5,0]))
train_set_x = train_set_x_flatten/255.
test_set_x = test_set_x_flatten/255.
def sigmoid(z):
s = 1. / ( 1 + np.exp(-z))
return s
print ("sigmoid([0, 2]) = " + str(sigmoid(np.array([0,2]))))
# GRADED FUNCTION: initialize_with_zeros
def initialize_with_zeros(dim):
w = np.zeros(shape=(dim, 1), dtype=np.float32)
b = 0
assert(w.shape == (dim, 1))
assert(isinstance(b, float) or isinstance(b, int))
return w, b
dim = 2
w, b = initialize_with_zeros(dim)
print ("w = " + str(w))
print ("b = " + str(b))
# GRADED FUNCTION: propagate
def propagate(w, b, X, Y):
m = X.shape[1]
# FORWARD PROPAGATION (FROM X TO COST)
A = sigmoid(np.dot(w.T, X) + b) # compute activation
cost = (-1. /m) * np.sum((Y*np.log(A) + (1 - Y)*np.log(1-A)), axis=1)
# BACKWARD PROPAGATION (TO FIND GRAD)
dw = (1./m)*np.dot(X,((A-Y).T))
db = (1./m)*np.sum(A-Y, axis=1)
assert(dw.shape == w.shape)
assert(db.dtype == float)
cost = np.squeeze(cost)
assert(cost.shape == ())
grads = {"dw": dw,
"db": db}
return grads, cost
w, b, X, Y = np.array([[1.],[2.]]), 2., np.array([[1.,2.,-1.],[3.,4.,-3.2]]), np.array([[1,0,1]])
grads, cost = propagate(w, b, X, Y)
print ("dw = " + str(grads["dw"]))
print ("db = " + str(grads["db"]))
print ("cost = " + str(cost))
# GRADED FUNCTION: optimize
def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False):
costs = []
for i in range(num_iterations):
grads, cost = propagate(w=w, b=b, X=X, Y=Y)
# Retrieve derivatives from grads
dw = grads["dw"]
db = grads["db"]
# update rule
w = w - learning_rate * dw
b = b - learning_rate * db
# Record the costs
if i % 100 == 0:
costs.append(cost)
# Print the cost every 100 training iterations
if print_cost and i % 100 == 0:
print ("Cost after iteration %i: %f" %(i, cost))
params = {"w": w,
"b": b}
grads = {"dw": dw,
"db": db}
return params, grads, costs
params, grads, costs = optimize(w, b, X, Y, num_iterations= 100, learning_rate = 0.009, print_cost = False)
print ("w = " + str(params["w"]))
print ("b = " + str(params["b"]))
print ("dw = " + str(grads["dw"]))
print ("db = " + str(grads["db"]))
# GRADED FUNCTION: predict
def predict(w, b, X):
m = X.shape[1]
Y_prediction = np.zeros((1,m))
w = w.reshape(X.shape[0], 1)
# Compute vector "A" predicting the probabilities of a cat being present in the picture
A = A = sigmoid(np.dot(w.T, X) + b)
for i in range(A.shape[1]):
# Convert probabilities A[0,i] to actual predictions p[0,i]
if A[0, i] >= 0.5:
Y_prediction[0, i] = 1
else:
Y_prediction[0, i] = 0
assert(Y_prediction.shape == (1, m))
return Y_prediction
w = np.array([[0.1124579],[0.23106775]])
b = -0.3
X = np.array([[1.,-1.1,-3.2],[1.2,2.,0.1]])
print ("predictions = " + str(predict(w, b, X)))
# GRADED FUNCTION: model
def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False):
# initialize parameters with zeros
w, b = initialize_with_zeros(X_train.shape[0])
# Gradient descent
parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost)
# Retrieve parameters w and b from dictionary "parameters"
w = parameters["w"]
b = parameters["b"]
# Predict test/train set examples
Y_prediction_test = predict(w, b, X_test)
Y_prediction_train = predict(w, b, X_train)
# Print train/test Errors
print("train accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100))
print("test accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100))
d = {"costs": costs,
"Y_prediction_test": Y_prediction_test,
"Y_prediction_train" : Y_prediction_train,
"w" : w,
"b" : b,
"learning_rate" : learning_rate,
"num_iterations": num_iterations}
return d
d = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 2000, learning_rate = 0.005, print_cost = True)
# Example of a picture that was wrongly classified.
index = 1
plt.imshow(test_set_x[:,index].reshape((num_px, num_px, 3)))
print ("y = " + str(test_set_y[0,index]) + ", you predicted that it is a \"" + classes[d["Y_prediction_test"][0,index]].decode("utf-8") + "\" picture.")
# Plot learning curve (with costs)
costs = np.squeeze(d['costs'])
plt.plot(costs)
plt.ylabel('cost')
plt.xlabel('iterations (per hundreds)')
plt.title("Learning rate =" + str(d["learning_rate"]))
plt.show()
| true |
776bc1df3722f999855569d19c68c2614c1bcbd4 | Python | aminerezgui/tp_py | /prime.py | UTF-8 | 599 | 3.234375 | 3 | [] | no_license | from random import randint
import math
def random_odd(k):
r = randint(2**(k - 1), 2**k)
while(r % 2 == 0):
r = randint(2**(k - 1), 2**k)
return r
def isprime(n):
if n % 2 == 0 and n!= 2:
return False
d = 3
while(d <= math.sqrt(n)):
if n % d == 0:
return False
d = d + 2
return True
def generate(k, primality):
r = random_odd(k)
while(not(primality(r))):
r = random_odd(k)
return r
def fermat_test(n):
for a in range(1, n):
if (a**(n-1) % n) != 1:
return False
return True
| true |
a8dba84dbe7eb651f6915d8f3310b589d09a83fb | Python | tnakaicode/jburkardt-fipy | /heat_steady/heat_steady_03.py | UTF-8 | 2,938 | 3.140625 | 3 | [] | no_license | #! /usr/bin/env python3
#
from fenics import *
def heat_steady_03():
#*****************************************************************************80
#
## heat_steady_03, 2D steady heat equation on a rectangle.
#
# Discussion:
#
# Heat equation in a long rectangle with varying thermal diffusivity k(x,y).
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 23 October 2018
#
# Author:
#
# John Burkardt
#
import matplotlib.pyplot as plt
#
# Define the mesh.
#
x_left = 0.0
x_right = 5.0
y_bottom = 0.0
y_top = 5.0
sw = Point(x_left, y_bottom)
ne = Point(x_right, y_top)
mesh = RectangleMesh(sw, ne, 50, 50)
#
# Define the function space.
#
V = FunctionSpace(mesh, "Lagrange", 1)
#
# Define boundary conditions on left, and top/bottom.
#
u_left = Expression("100 * x[1] * ( 5.0 - x[1] )", degree=3)
def on_left(x, on_boundary):
return (x[0] <= x_left + DOLFIN_EPS)
bc_left = DirichletBC(V, u_left, on_left)
u_tb = 0.0
def on_tb(x, on_boundary):
return (x[1] <= y_bottom + DOLFIN_EPS or y_top - DOLFIN_EPS <= x[1])
bc_tb = DirichletBC(V, u_tb, on_tb)
bc = [bc_left, bc_tb]
#
# Define the trial functions (u) and test functions (v).
#
u = TrialFunction(V)
v = TestFunction(V)
#
# Write the bilinear form.
#
k = Expression("1.0 + 100 * ( 5.0 - x[1] ) * x[1]", degree=3)
Auv = k * inner(grad(u), grad(v)) * dx
#
# Write the linear form.
#
f = Constant(0.0)
Lv = f * v * dx
#
# Solve the variational problem with boundary conditions.
#
u = Function(V)
solve(Auv == Lv, u, bc)
#
# Plot the solution.
#
plot(u, title='heat_steady_03')
filename = 'heat_steady_03.png'
plt.savefig(filename)
print("Saving graphics in file '%s'" % (filename))
plt.close()
#
# Terminate.
#
return
def heat_steady_03_test():
#*****************************************************************************80
#
## heat_steady_03_test tests heat_steady_03.
#
# Modified:
#
# 21 October 2018
#
# Author:
#
# John Burkardt
#
import time
print(time.ctime(time.time()))
#
# Report level = only warnings or higher.
#
level = 30
set_log_level(level)
print('')
print('heat_steady_03_test:')
print(' FENICS/Python version')
print(' Solve the heat equation over a square')
print(' with smoothly-varying thermal diffusivity.')
heat_steady_03()
#
# Terminate.
#
print('')
print('heat_steady_03_test:')
print(' Normal end of execution.')
print('')
print(time.ctime(time.time()))
return
if (__name__ == '__main__'):
heat_steady_03_test()
| true |
7f57a5da1dde5d1f9ed27575cbe400fa535a6711 | Python | ptMcGit/unbound-sinkhole | /unbound_sinkhole/tests/test_db.py | UTF-8 | 2,960 | 2.859375 | 3 | [] | no_license | """Test db module.
"""
import sqlite3
import unittest
import unbound_sinkhole.conf as conf
import unbound_sinkhole.db as db
conf.initialize_confs('unbound_sinkhole/tests/inputs/test_config')
db.SINKHOLE_DB = conf.SINKHOLE_DB
class TestDb(unittest.TestCase):
"""Test db module.
"""
def setUp(self):
"""Initialize the database.
"""
db.init_db()
def tearDown(self):
"""Purge all records from the DB.
"""
db.purge_db()
def get_records(self):
""" Helper method to get all records
"""
with sqlite3.connect(conf.SINKHOLE_DB) as con:
return con.execute("SELECT * FROM {0}".format(db.DB_SINKHOLE_TABLE)).fetchall()
def test_update_records(self):
""" Various checks for method for
inserting records. """
records1 = [("0.0.0.0", "yahoo.com.")]
db.update_records(records1, blacklist=True)
# insert duplicate
db.update_records(records1, blacklist=True)
recs = self.get_records()
self.assertEqual(len(recs), 1)
self.assertEqual(recs[0][1], 'TRUE')
# update sinkhole boolean
db.update_records(records1, blacklist=False)
recs = self.get_records()
self.assertEqual(len(recs), 1)
self.assertEqual(recs[0][1], 'FALSE')
# attempt insert record with same ip, different host
db.update_records([("0.0.0.0", "google.com.")]
, blacklist=False)
recs = self.get_records()
self.assertEqual(len(recs), 2)
# record with different ip same host
db.update_records([("1.1.1.1", "google.com.")],
blacklist=True)
recs = self.get_records()
self.assertEqual(len(recs), 3)
def test_delete_records(self):
""" Test deleting records.
"""
a_rec = ("0.0.0.0", "a.com")
b_rec = ("1.1.1.1", "b.com")
c_rec = ("2.2.2.2", "c.com")
db.update_records([a_rec,
b_rec,
c_rec],
blacklist=True)
db.delete_records([a_rec, b_rec])
recs = self.get_records()
self.assertEqual(len(recs), 1)
db.delete_records([c_rec])
# delete twice
db.delete_records([c_rec])
recs = self.get_records()
self.assertEqual(len(recs), 0)
def test_get_blacklist(self):
""" Test getting the blacklist.
"""
a_rec = ("0.0.0.0", "a.com")
b_rec = ("1.1.1.1", "b.com")
db.update_records([a_rec,
b_rec],
blacklist=True)
db.update_records([("2.2.2.2", "c.com")], blacklist=False)
recs = list(db.get_blacklist())
self.assertEqual(recs[0], a_rec)
self.assertEqual(recs[1], b_rec)
self.assertEqual(len(recs), 2)
if __name__ == '__main__':
unittest.main()
| true |
004bf19c75dafa13b071632027768f6735f8c2a6 | Python | MegumiDavid/python-projects | /OOP_lesson/animal_OOP.py | UTF-8 | 952 | 4.15625 | 4 | [] | no_license | class Animal():
def __init__(self):
self.eyes = 2
def breathe(self):
print("Inhale & Exhale")
class Fish(Animal):
def __init__(self, name):
super().__init__()
self.name = name
def breathe(self):
super().breathe()
print("Under the water")
def swim(self):
print("Swimming ~~~")
nemo = Fish("Angel Fish")
print(nemo.name)
print(nemo.eyes)
nemo.breathe()
nemo.swim()
class Dog:
def __init__(self):
self.temperament = "loyal"
class Labrador(Dog):
def __init__(self):
super().__init__()
self.temperament = "gentle"
class Dog:
def __init__(self):
self.temperament = "loyal"
def bark(self):
print("Woof, woof!")
class Labrador(Dog):
def __init__(self):
super().__init__()
self.is_a_good_boy = True
def bark(self):
super().bark()
print("Greetings, good sir. How do you do?") | true |