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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
dbc0c8908d4c901cd4e39ea3a86c826f0ef504db | Python | sun1279/pythontest | /mail_test.py | UTF-8 | 2,465 | 2.640625 | 3 | [] | no_license | #this case is used to test sending mail
import smtplib
#email format
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
#POP_SERVER = "pop.gmail.com"
#SMTP_SERVER = "smtp.gmail.com"
POP_SERVER = "pop.163.com"
SMTP_SERVER = "smtp.163.com"
IMAP_SERVER = "imap.163.com"
SENDER = "@163.com"
RECEIVER = "@163.com"
PASSWD = ""
title = "[你好 我今天工作 以此邮件为准]HELLO WORLD"
content = "今天 星期一 周末 你好 谷歌浏览器 \n 南宋的开放\n"
MESSAGE = "123 HELLO WORLD 456"
#An SMTP_SSL instance behaves exactly the same as instances of SMTP. SMTP_SSL should be used for situations where SSL is required from the beginning of the connection
smtp = smtplib.SMTP_SSL(SMTP_SERVER)
#Identify yourself to an ESMTP server using EHLO
smtp.ehlo(SMTP_SERVER)
#smtp.set_debuglevel(1)
smtp.login(SENDER, PASSWD)
class SendMail(object):
def __init__(self, mailto,subject,content,attach=[]):
self.__mailto__ = mailto
self.__subject__ = subject
self.__content__ = content
self.__attach__ = attach
def send(self):
print("Send")
if len(self.__attach__) == 0: #pure text
msg=MIMEText(self.__content__, "plain", "utf-8")
msg["Subject"] = Header(self.__subject__, "utf-8")
msg["From"] = SENDER
msg["To"] = self.__mailto__
else:
#mail with attachment
msg = MIMEMultipart()
msg["Subject"] = Header(self.__subject__)
msg["From"] = SENDER
msg["To"] = self.__mailto__
msg.attach(MIMEText(self.__content__, "html", "utf-8"))
#filenames=list()
#filenames.append("air.sqlite")
#filenames.append("a.out")
#filenames.append("domain.py")
#TODO file in to a list
for filename in self.__attach__:
att1 = MIMEText(open(filename, "rb").read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename='+filename
msg.attach(att1)
smtp.sendmail(SENDER, self.__mailto__, msg.as_string())
smtp.quit()
filelist=['All.csv','DomesticAirCode.csv','InternationalAirCode.csv']
s=SendMail("@163.com", "[kaihui]别忘了明天一起开会", "见标题", filelist)
s.send()
| true |
76d4467110e6b7be183b8d2315593d0e1877aa12 | Python | renyuanL/cguTranslate | /tc_Demo/python31_demo/tc_paint.py | UTF-8 | 1,199 | 3.390625 | 3 | [] | no_license | #!/usr/bin/python
""" turtle-example-suite:
tdemo_paint.py
A simple eventdriven paint program
- use left mouse button to move turtle
- middle mouse button to change color
- right mouse button do turn filling on/off
-------------------------------------------
Play around by clicking into the canvas
using all three mouse buttons.
-------------------------------------------
To exit press STOP button
-------------------------------------------
"""
from turtle_tc import *
def 切換提筆下筆(x=0, y=0):
if 筆()["pendown"]:
結束填()
提筆()
else:
下筆()
開始填()
def 改變顏色(x=0, y=0):
global 顏色們
顏色們 = 顏色們[1:]+顏色們[:1]
顏色(顏色們[0])
def 主函數():
global 顏色們
形狀("circle")
重設大小模式("user")
形狀大小(.5)
筆寬(3)
顏色們=[紅, 綠, 藍, 黃]
顏色(顏色們[0])
切換提筆下筆()
在點擊幕時(前往,1)
在點擊幕時(改變顏色,2)
在點擊幕時(切換提筆下筆,3)
return "EVENTLOOP"
if __name__ == "__main__":
訊息 = 主函數()
印(訊息)
主迴圈()
| true |
41f527772585fe7b550f66bca051ba5dd3d6d7d1 | Python | shawnlobo96/sttp_DL | /Lab/Day-1/lab-2_error surface.py | UTF-8 | 8,099 | 3.25 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 12 11:52:47 2017
@author: abc
"""
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import ListedColormap
from matplotlib.colors import colorConverter
#%%
nb_of_samples_per_class = 20 # The number of sample in each class
blue_mean = [0] # The mean of the blue class
red_left_mean = [-2] # The mean of the red class
red_right_mean = [2] # The mean of the red class
std_dev = 0.7 # standard deviation of both classes
# Generate samples from both classes
x_blue = np.random.rand(nb_of_samples_per_class,1) * std_dev + blue_mean
x_red_left = np.random.rand(10, 1) * std_dev + red_left_mean
x_red_right = np.random.rand(10, 1) * std_dev + red_right_mean
# Merge samples in set of input variables x, and corresponding set of
# output variables t
x = np.vstack((x_blue, x_red_left, x_red_right))
t = np.vstack((np.ones((x_blue.shape[0],1)),
np.zeros((x_red_left.shape[0],1)),
np.zeros((x_red_right.shape[0], 1))))
plt.figure(figsize=(8,0.5))
plt.xlim(-3,3)
plt.ylim(-1,1)
# Plot samples
plt.plot(x_blue, np.zeros_like(x_blue), 'b|', ms = 30)
plt.plot(x_red_left, np.zeros_like(x_red_left), 'r|', ms = 30)
plt.plot(x_red_right, np.zeros_like(x_red_right), 'r|', ms = 30)
plt.gca().axes.get_yaxis().set_visible(False)
plt.title('Input samples from the blue and red class')
plt.xlabel('$x$', fontsize=15)
plt.show()
#%%
# Define the rbf function
def rbf(z):
return np.exp(-z**2)
# Plot the rbf function
z = np.linspace(-6,6,100)
plt.figure(2)
plt.plot(z, rbf(z), 'b-')
plt.xlabel('$z$', fontsize=15)
plt.ylabel('$e^{-z^2}$', fontsize=15)
plt.title('RBF function')
plt.grid()
plt.show()
#%%
# Define the logistic function
def logistic(z):
return 1 / (1 + np.exp(-z))
# Function to compute the hidden activations
def hidden_activations(x, wh):
return rbf(x * wh)
# Define output layer feedforward
def output_activations(h , wo):
return logistic(h * wo - 1)
# Define the neural network function
def nn(x, wh, wo):
return output_activations(hidden_activations(x, wh), wo)
# Define the neural network prediction function that only returns
# 1 or 0 depending on the predicted class
def nn_predict(x, wh, wo):
return np.around(nn(x, wh, wo))
# Define the cost function
def cost(y, t):
return -np.sum(np.multiply(t, np.log(y)) + np.multiply((1-t), np.log(1-y)))
# Define a function to calculate the cost for a given set of parameters
def cost_for_param(x, wh, wo, t):
return cost(nn(x, wh, wo) , t)
#%%
# Plot the cost in function of the weights
# Define a vector of weights for which we want to plot the cost
nb_of_ws = 200 # compute the cost nb_of_ws times in each dimension
wsh = np.linspace(-10, 10, num=nb_of_ws) # hidden weights
wso = np.linspace(-10, 10, num=nb_of_ws) # output weights
ws_x, ws_y = np.meshgrid(wsh, wso) # generate grid
cost_ws = np.zeros((nb_of_ws, nb_of_ws)) # initialize cost matrix
# Fill the cost matrix for each combination of weights
for i in range(nb_of_ws):
for j in range(nb_of_ws):
cost_ws[i,j] = cost(nn(x, ws_x[i,j], ws_y[i,j]) , t)
# Plot the cost function surface
fig = plt.figure(3)
ax = Axes3D(fig)
# plot the surface
surf = ax.plot_surface(ws_x, ws_y, cost_ws, linewidth=0, cmap=cm.pink)
ax.view_init(elev=60, azim=-30)
cbar = fig.colorbar(surf)
ax.set_xlabel('$w_h$', fontsize=15)
ax.set_ylabel('$w_o$', fontsize=15)
ax.set_zlabel('$\\xi$', fontsize=15)
cbar.ax.set_ylabel('$\\xi$', fontsize=15)
plt.title('Cost function surface')
plt.grid()
plt.show()
#%%
# Define the error function
def gradient_output(y, t):
return y - t
# Define the gradient function for the weight parameter at the output layer
def gradient_weight_out(h, grad_output):
return h * grad_output
# Define the gradient function for the hidden layer
def gradient_hidden(wo, grad_output):
return wo * grad_output
# Define the gradient function for the weight parameter at the hidden layer
def gradient_weight_hidden(x, zh, h, grad_hidden):
return x * -2 * zh * h * grad_hidden
# Define the update function to update the network parameters over 1 iteration
def backprop_update(x, t, wh, wo, learning_rate):
# Compute the output of the network
# This can be done with y = nn(x, wh, wo), but we need the intermediate
# h and zh for the weight updates.
zh = x * wh
h = rbf(zh) # hidden_activations(x, wh)
y = output_activations(h, wo)
# Compute the gradient at the output
grad_output = gradient_output(y, t)
# Get the delta for wo
d_wo = learning_rate * gradient_weight_out(h, grad_output)
# Compute the gradient at the hidden layer
grad_hidden = gradient_hidden(wo, grad_output)
# Get the delta for wh
d_wh = learning_rate * gradient_weight_hidden(x, zh, h, grad_hidden)
# return the update parameters
return (wh-d_wh.sum(), wo-d_wo.sum())
#%%
# Run backpropagation
# Set the initial weight parameter
wh = 2
wo = -5
# Set the learning rate
learning_rate = 0.2
# Start the gradient descent updates and plot the iterations
nb_of_iterations = 50 # number of gradient descent updates
lr_update = learning_rate / nb_of_iterations # learning rate update rule
w_cost_iter = [(wh, wo, cost_for_param(x, wh, wo, t))] # List to store the weight values over the iterations
for i in range(nb_of_iterations):
learning_rate -= lr_update # decrease the learning rate
# Update the weights via backpropagation
wh, wo = backprop_update(x, t, wh, wo, learning_rate)
w_cost_iter.append((wh, wo, cost_for_param(x, wh, wo, t))) # Store the values for plotting
# Print the final cost
print('final cost is {:.2f} for weights wh: {:.2f} and wo: {:.2f}'.format(cost_for_param(x, wh, wo, t), wh, wo))
fig = plt.figure()
ax = Axes3D(fig)
surf = ax.plot_surface(ws_x, ws_y, cost_ws, linewidth=0, cmap=cm.pink)
ax.view_init(elev=60, azim=-30)
cbar = fig.colorbar(surf)
cbar.ax.set_ylabel('$\\xi$', fontsize=15)
# Plot the updates
for i in range(1, len(w_cost_iter)):
wh1, wo1, c1 = w_cost_iter[i-1]
wh2, wo2, c2 = w_cost_iter[i]
# Plot the weight-cost value and the line that represents the update
ax.plot([wh1], [wo1], [c1], 'w+') # Plot the weight cost value
ax.plot([wh1, wh2], [wo1, wo2], [c1, c2], 'w-')
# Plot the last weights
wh1, wo1, c1 = w_cost_iter[len(w_cost_iter)-1]
ax.plot([wh1], [wo1], c1, 'w+')
# Shoz figure
ax.set_xlabel('$w_h$', fontsize=15)
ax.set_ylabel('$w_o$', fontsize=15)
ax.set_zlabel('$\\xi$', fontsize=15)
plt.title('Gradient descent updates on cost surface')
plt.grid()
plt.show()
#%%
# Plot the resulting decision boundary
# Generate a grid over the input space to plot the color of the
# classification at that grid point
nb_of_xs = 100
xs = np.linspace(-3, 3, num=nb_of_xs)
ys = np.linspace(-1, 1, num=nb_of_xs)
xx, yy = np.meshgrid(xs, ys) # create the grid
# Initialize and fill the classification plane
classification_plane = np.zeros((nb_of_xs, nb_of_xs))
for i in range(nb_of_xs):
for j in range(nb_of_xs):
classification_plane[i,j] = nn_predict(xx[i,j], wh, wo)
# Create a color map to show the classification colors of each grid point
cmap = ListedColormap([
colorConverter.to_rgba('r', alpha=0.25),
colorConverter.to_rgba('b', alpha=0.25)])
# Plot the classification plane with decision boundary and input samples
plt.figure(figsize=(8,0.5))
plt.contourf(xx, yy, classification_plane, cmap=cmap)
plt.xlim(-3,3)
plt.ylim(-1,1)
# Plot samples from both classes as lines on a 1D space
plt.plot(x_blue, np.zeros_like(x_blue), 'b|', ms = 30)
plt.plot(x_red_left, np.zeros_like(x_red_left), 'r|', ms = 30)
plt.plot(x_red_right, np.zeros_like(x_red_right), 'r|', ms = 30)
plt.gca().axes.get_yaxis().set_visible(False)
plt.title('Input samples and their classification')
plt.xlabel('x')
plt.show() | true |
d6d2fab9d0dcb1dea0c0747d1c7de07a1e3fd025 | Python | michaelbrownuc/GadgetSetAnalyzer | /src/static_analyzer/Gadget.py | UTF-8 | 28,398 | 3.03125 | 3 | [
"MIT"
] | permissive | """
Gadget class
"""
# Standard Library Imports
# Third Party Imports
# Local Imports
from static_analyzer.Instruction import Instruction
class Gadget(object):
"""
The Gadget class represents a single gadget.
"""
def __init__(self, raw_gadget):
"""
Gadget constructor
:param str raw_gadget: raw line output from ROPgadget
"""
# Parse the raw line
self.offset = raw_gadget[:raw_gadget.find(":")]
self.instruction_string = raw_gadget[raw_gadget.find(":") + 2:]
# Parse instruction objects
self.instructions = []
for instr in self.instruction_string.split(" ; "):
self.instructions.append(Instruction(instr))
# Initialize score
self.score = 0.0
def is_useless_op(self):
"""
:return boolean: Returns True if the first instruction opcode is in the "useless" list, False otherwise
Default behavior is to consider opcodes useful unless otherwise observed.
"""
first_opcode = self.instructions[0].opcode
# Bulk catch for all "jump" opcodes: No reason to include the instruction, just use the suffix directly
if first_opcode.startswith("j"):
return True
# Bulk catch for bounds checked jumps, same reason as above
if first_opcode.startswith("bnd"):
return True
# Bulk catch for all "ret" opcodes: Bug in ROP gadget finds some gadgets that start with this GPI
if first_opcode.startswith("ret"):
return True
# Bulk catch for all "iret" opcodes: Bug in ROP gadget finds some gadgets that start with this GPI
if first_opcode.startswith("iret"):
return True
# Bulk catch for all "call" opcodes: Bug in ROP gadget finds some gadgets that start with this GPI
if first_opcode.startswith("call"):
return True
# Useless opcodes:
# NOP - No reason to include the instruction, just use the suffix directly
# LJMP - Same reason as "jump" opcodes above
useless = ["nop", "fnop", "ljmp"]
return first_opcode in useless
def contains_unusable_op(self):
"""
:return boolean: Returns True if any instruction opcode is unusable. False otherwise
unusable instructions are Ring-0 opcodes that trap in user mode and some other exceptional ops.
"""
for instr in self.instructions:
# Bulk catch for all "invalidate" opcodes: Ring-0 instructions
if instr.opcode.startswith("inv"):
return True
# Bulk catch for all "Virtual-Machine" opcodes: Ring-0 instructions
if instr.opcode.startswith("vm") and instr.opcode != "vminsd" and instr.opcode != "vminpd":
return True
# Bulk catch for all "undefined" opcodes
if instr.opcode.startswith("ud"):
return True
# Other Ring-0 opcodes and RSM, LOCK prefix
unusable = ["clts", "hlt", "lgdt", "lidt", "lldt", "lmsw", "ltr", "monitor", "mwait",
"swapgs", "sysexit", "sysreturn", "wbinvd", "wrmsr", "xsetbv", "rsm", "lock"]
if instr.opcode in unusable:
return True
# Check for ring-0 operands (control, debug, and test registers)
if instr.op1 is not None:
if instr.op1.startswith("cr") or instr.op1.startswith("tr") or instr.op1.startswith("db"):
return True
if instr.op2 is not None:
if instr.op2.startswith("cr") or instr.op2.startswith("tr") or instr.op2.startswith("db"):
return True
return False
def is_gpi_only(self):
"""
:return boolean: Returns True if the gadget is a single instruction and starts with 'ret', 'jmp', or 'call',
False otherwise
"""
if len(self.instructions) == 1:
opcode = self.instructions[0].opcode
if opcode.startswith("ret") or opcode.startswith("jmp") or opcode.startswith("call"):
return True
return False
def is_invalid_branch(self):
"""
:return boolean: Returns True if the gadget is 'jmp' or 'call' ending and the call target is a constant offset
or does not target a recognized register family. False otherwise
"""
last_instr = self.instructions[len(self.instructions)-1]
if last_instr.opcode.startswith("call") or last_instr.opcode.startswith("jmp"):
if Instruction.get_operand_register_family(last_instr.op1) is None:
return True
return False
def has_invalid_ret_offset(self):
"""
:return boolean: Returns True if the gadget is 'ret' ending and contains a constant offset that is not byte
aligned or is greater than 32 bytes, False otherwise
"""
last_instr = self.instructions[len(self.instructions)-1]
if last_instr.opcode.startswith("ret") and last_instr.op1 is not None:
offset = Instruction.get_operand_as_constant(last_instr.op1)
if (offset % 2 != 0) or (offset > 32):
return True
return False
def clobbers_created_value(self):
"""
:return boolean: Returns True if the gadget completely overwrites the value created in the first instruction,
False otherwise.
"""
first_instr = self.instructions[0]
# Check if the first instruction creates a value or is an xchg operand (excluded as an edge case)
if not first_instr.creates_value() or "xchg" in first_instr.opcode:
return False
# Check op1 to find the register family to protect
first_family = Instruction.get_operand_register_family(first_instr.op1)
# Most likely means first operand is a constant, exclude from analysis
if first_family is None:
return False
# Iterate through intermediate instructions, determine if it overwrites protected value (or part of it)
for i in range(1, len(self.instructions)-1):
cur_instr = self.instructions[i]
# Ignore instructions that do not create values
if not cur_instr.creates_value() or "xchg" in cur_instr.opcode:
continue
# Check for non-static modification of the register family
if first_family == Instruction.get_operand_register_family(cur_instr.op1):
if (cur_instr.op2 is None and cur_instr.opcode not in ["inc", "dec", "neg", "not"]) or \
(cur_instr.op2 is not None and not Instruction.is_constant(cur_instr.op2)):
return True
return False
def creates_unusable_value(self):
"""
:return boolean: Returns True if the gadget creates a value in segment or extension registers, or are
RIP-relative, or are constant memory locations; False otherwise.
"""
# Check if the first instruction creates a value (or may potentially set a flag
first_instr = self.instructions[0]
if first_instr.opcode in ["cmp", "test", "push"] or first_instr.op1 is None:
return False
# Check if first operand is not a constant and it does not belong to a recognized register family
if not Instruction.is_constant(first_instr.op1) and \
Instruction.get_operand_register_family(first_instr.op1) is None:
return True
return False
def contains_intermediate_GPI(self):
"""
:return boolean: Returns True if the gadget's intermediate instructions contain a GPI (or a generic interrupt),
False otherwise.
"""
for i in range(len(self.instructions)-1):
cur_opcode = self.instructions[i].opcode
cur_target = self.instructions[i].op1
if cur_opcode.startswith("ret") or \
cur_opcode == "syscall" or cur_opcode == "sysenter" or cur_opcode.startswith("int") or \
("jmp" in cur_opcode and not Instruction.is_constant(cur_target)) or \
("call" in cur_opcode and not Instruction.is_constant(cur_target)):
return True
return False
def clobbers_stack_pointer(self):
"""
:return boolean: Returns True if the ROP gadget's instructions assign a non-static value to the stack pointer
register, False otherwise.
"""
# Only check ROP gadgets
last_instr = self.instructions[len(self.instructions) - 1]
if last_instr.opcode.startswith("ret"):
for i in range(len(self.instructions) - 1):
cur_instr = self.instructions[i]
# Ignore instructions that do not create values
if not cur_instr.creates_value():
continue
# Check for non-static modification of the stack pointer register family
if Instruction.get_operand_register_family(cur_instr.op1) == 7: # RSP, ESP family number
if (cur_instr.op2 is None and cur_instr.opcode not in ["inc", "dec", "pop"]) or \
(cur_instr.op2 is not None and not Instruction.is_constant(cur_instr.op2)):
return True
return False
def clobbers_indirect_target(self):
"""
:return boolean: Returns True if the JOP/COP gadget's instructions modify the indirect branch register in
certain ways, False otherwise.
"""
# Get the register family of the indirect jump / call
last_instr = self.instructions[len(self.instructions)-1]
if last_instr.opcode.startswith("jmp") or last_instr.opcode.startswith("call"):
family = Instruction.get_operand_register_family(last_instr.op1)
# Check each instruction to see if it clobbers the value
for i in range(len(self.instructions)-1):
cur_instr = self.instructions[i]
# First check if the instruction modifies the target
if cur_instr.op1 in Instruction.register_families[family]:
# Does the instruction zeroize out the target?
if cur_instr.opcode == "xor" and cur_instr.op1 == cur_instr.op2:
return True
# Does the instruction perform a RIP-relative LEA into the target?
if cur_instr.opcode == "lea" and ("rip" in cur_instr.op2 or "eip" in cur_instr.op2):
return True
# Does the instruction load a string or a value of an input port into the target?
if cur_instr.opcode.startswith("lods") or cur_instr.opcode == "in":
return True
# Does the instruction overwrite the target with a static value or segment register value?
if "mov" in cur_instr.opcode and (Instruction.is_constant(cur_instr.op2) or
Instruction.get_operand_register_family(cur_instr.op2) is None):
return True
return False
def has_invalid_int_handler(self):
"""
:return boolean: Returns True if the gadget's instructions assign a non-static value to the stack pointer
register, False otherwise.
"""
last_instr = self.instructions[len(self.instructions) - 1]
if last_instr.opcode.startswith("int") and last_instr.op1 != "0x80":
return True
return False
def is_rip_relative_indirect_branch(self):
"""
:return boolean: Returns True if the gadget is a JOP/COP gadget relying on a RIP relative indirect branch,
False otherwise.
"""
last_instr = self.instructions[len(self.instructions) - 1]
if last_instr.opcode.startswith("jmp") or last_instr.opcode.startswith("call"):
if "rip" in last_instr.op1 or "eip" in last_instr.op1:
return True
return False
def contains_static_call(self):
for i in range(1, len(self.instructions)-1):
cur_instr = self.instructions[i]
if cur_instr.opcode.startswith("call") and Instruction.is_constant(cur_instr.op1):
return True
return False
def is_equal(self, rhs):
"""
:return boolean: Returns True if the gadgets are an exact match, including offset. Used for gadget locality.
"""
return self.offset == rhs.offset and self.instruction_string == rhs.instruction_string
def is_duplicate(self, rhs):
"""
:return boolean: Returns True if the gadgets are a semantic match. Used for non-locality gadget metrics.
Semantic match is defined as the exact same sequence of equivalent instructions.
"""
if len(self.instructions) != len(rhs.instructions):
return False
for i in range(len(self.instructions)):
if not self.instructions[i].is_equivalent(rhs.instructions[i]):
return False
return True
def is_JOP_COP_dispatcher(self):
"""
:return boolean: Returns True if the gadget is a JOP or COP dispatcher. Defined as a gadget that begins with a
arithmetic operation on a register and ends with a branch to a deference of that register. Used
to iterate through instructions in payload. Only restrictions on the arithmetic operation is
that it doesn't use the same register as both operands.
"""
first_instr = self.instructions[0]
last_instr = self.instructions[len(self.instructions) - 1]
# Only consider gadgets that end in dereference of a register and start with opcodes of interest
if "[" in last_instr.op1 and \
first_instr.opcode in ["inc", "dec", "add", "adc", "sub", "sbb"] and "[" not in first_instr.op1:
gpi_target = Instruction.get_operand_register_family(last_instr.op1)
arith_target_1 = Instruction.get_operand_register_family(first_instr.op1)
# Secondary check: if the second op is a constant ensure it is in range [1, 32]
if Instruction.is_constant(first_instr.op2):
additive_value = Instruction.get_operand_as_constant(first_instr.op2)
if additive_value < 1 or additive_value > 32:
return False
arith_target_2 = Instruction.get_operand_register_family(first_instr.op2)
return gpi_target == arith_target_1 and arith_target_1 != arith_target_2
return False
def is_JOP_COP_dataloader(self):
"""
:return boolean: Returns True if the gadget is a JOP or COP data loader. Defined as a gadget that begins with a
pop opcode to a non-memory location, that is also not the target of the GPI. Used to pop a
necessary value off stack en masse before redirecting to the dispatcher.
"""
first_instr = self.instructions[0]
if first_instr.opcode == "pop" and "[" not in first_instr.op1:
gpi_target = Instruction.get_operand_register_family(self.instructions[len(self.instructions) - 1].op1)
pop_target = Instruction.get_operand_register_family(first_instr.op1)
return gpi_target != pop_target
return False
def is_JOP_initializer(self):
"""
:return boolean: Returns True if the gadget is a JOP Initializer. Defined as a gadget that begins with a
"pop all" opcode, used to pop necessary values off stack en masse before redirecting to the
dispatcher.
"""
return self.instructions[0].opcode.startswith("popa")
def is_JOP_trampoline(self):
"""
:return boolean: Returns True if the gadget is a JOP trampoline. Defined as a gadget that begins with a
pop opcode to a non-memory location, and that ends in a dereference of that value. Used to
redirect execution to value stored in memory.
"""
first_instr = self.instructions[0]
gpi_target_op = self.instructions[len(self.instructions) - 1].op1
if first_instr.opcode == "pop" and "[" not in first_instr.op1:
gpi_target = Instruction.get_operand_register_family(gpi_target_op)
pop_target = Instruction.get_operand_register_family(first_instr.op1)
return gpi_target == pop_target and "[" in gpi_target_op
return False
def is_COP_initializer(self):
"""
:return boolean: Returns True if the gadget is a COP initializer. Defined as a gadget that begins with a
"pop all" opcode, does not use register bx/cx/dx/di as the call target, and does not clobber
bx/cx/dx or the call target in an intermediate instruction
"""
first_instr = self.instructions[0]
last_instr = self.instructions[len(self.instructions)-1]
call_target = Instruction.get_operand_register_family(last_instr.op1)
if first_instr.opcode.startswith("popa") and call_target not in [1, 2, 3, 5]: # BX, CX, DX, DI families
# Build collective list of register families to protect from being clobbered
protected_families = [1, 2, 3, call_target]
protected_registers = []
for family in protected_families:
for register in Instruction.register_families[family]:
protected_registers.append(register)
# Scan intermediate instructions to ensure they do not clobber a protected register
for i in range(1, len(self.instructions)-1):
cur_instr = self.instructions[i]
# Ignore instructions that do not create values
if not cur_instr.creates_value():
continue
# Check for non-static modification of the register family
if cur_instr.op1 in protected_registers:
if (cur_instr.op2 is None and cur_instr.opcode not in ["inc", "dec", "neg", "not"]) or \
(cur_instr.op2 is not None and not Instruction.is_constant(cur_instr.op2)):
return False
return True
return False
def is_COP_strong_trampoline(self):
"""
:return boolean: Returns True if the gadget is a COP strong trampoline. Defined as a gadget that begins with a
pop opcode, and contains at least one other pop operation. The last non-pop all operation must
target the call target.
"""
first_instr = self.instructions[0]
last_instr = self.instructions[len(self.instructions) - 1]
call_target = Instruction.get_operand_register_family(last_instr.op1)
# Only consider instructions that start with a pop
if first_instr.opcode == "pop" and "[" not in first_instr.op1:
cnt_pops = 1
last_pop_target = first_instr.op1
# Scan intermediate instructions for pops
for i in range(1, len(self.instructions)-1):
cur_instr = self.instructions[i]
if cur_instr.opcode.startswith("popa"):
cnt_pops += 1
if cur_instr.opcode == "pop" and "[" not in cur_instr.op1:
cnt_pops += 1
last_pop_target = cur_instr.op1
# Check that at least two pops occurred and the last pop target is the call target
if cnt_pops > 1 and last_pop_target in Instruction.register_families[call_target]:
return True
return False
def is_COP_intrastack_pivot(self):
"""
:return boolean: Returns True if the gadget is a COP Intra-stack pivot gadget. Defined as a gadget that begins
with an additive operation on the stack pointer register. Used to move around in shellcode
during COP exploits. Only restriction on the arithmetic operation is that the second operand
is not a pointer.
"""
first_instr = self.instructions[0]
if first_instr.opcode in ["inc", "add", "adc", "sub", "sbb"] and "[" not in first_instr.op1:
arith_target = Instruction.get_operand_register_family(first_instr.op1)
if arith_target == 7: # RSP, ESP family number
if first_instr.op2 is None or "[" not in first_instr.op2:
return True
return False
def check_contains_leave(self):
"""
:return void: Increases gadget's score if the gadget has an intermediate "leave" instruction.
"""
for i in range(1, len(self.instructions)-1):
if self.instructions[i].opcode == "leave":
self.score += 2.0
return # Only penalize gadget once
def check_sp_target_of_operation(self):
"""
:return void: Increases gadget's score if the gadget has an intermediate instruction that performs certain
operations on the stack pointer register family.
"""
# Scan instructions to determine if they modify the stack pointer register family
for i in range(len(self.instructions)-1):
cur_instr = self.instructions[i]
# Ignore instructions that do not create values
if not cur_instr.creates_value():
continue
# Increase score by 4 for move, load address, and exchange ops, 3 for shift/rotate ops, and 2 for others
if Instruction.get_operand_register_family(cur_instr.op1) == 7: # RSP, ESP family number
if "xchg" in cur_instr.opcode or "mov" in cur_instr.opcode or cur_instr.opcode in ["lea"]:
self.score += 4.0
elif cur_instr.opcode in ["shl", "shr", "sar", "sal", "ror", "rol", "rcr", "rcl"]:
self.score += 3.0
elif cur_instr.opcode == "pop":
self.score += 1.0
else:
self.score += 2.0 # Will be a static modification, otherwise it would have been rejected earlier
def check_negative_sp_offsets(self):
"""
:return void: Increases gadget's score if its cumulative register offsets are negative.
"""
sp_offset = 0
# Scan instructions to determine if they modify the stack pointer
for i in range(len(self.instructions)):
cur_instr = self.instructions[i]
if cur_instr.opcode == "push":
sp_offset -= 8
elif cur_instr.opcode == "pop" and cur_instr.op1 not in Instruction.register_families[7]:
sp_offset += 8
elif cur_instr.opcode in ["add", "adc"] and cur_instr.op1 in Instruction.register_families[7] and \
Instruction.is_constant(cur_instr.op2):
sp_offset += Instruction.get_operand_as_constant(cur_instr.op2)
elif cur_instr.opcode in ["sub", "sbb"] and cur_instr.op1 in Instruction.register_families[7] and \
Instruction.is_constant(cur_instr.op2):
sp_offset -= Instruction.get_operand_as_constant(cur_instr.op2)
elif cur_instr.opcode == "inc" and cur_instr.op1 in Instruction.register_families[7]:
sp_offset += 1
elif cur_instr.opcode == "dec" and cur_instr.op1 in Instruction.register_families[7]:
sp_offset -= 1
elif cur_instr.opcode.startswith("ret") and cur_instr.op1 is not None:
sp_offset += Instruction.get_operand_as_constant(cur_instr.op1)
if sp_offset < 0:
self.score += 2.0
def check_contains_conditional_op(self):
"""
:return void: Increases gadget's score if it contains conditional instructions like jumps, sets, and moves.
"""
# Scan instructions to determine if they modify the stack pointer
for i in range(len(self.instructions)-1):
cur_instr = self.instructions[i]
if cur_instr.opcode.startswith("j") and cur_instr.opcode != "jmp":
self.score += 3.0
elif "cmov" in cur_instr.opcode or "cmpxchg" in cur_instr.opcode:
self.score += 2.0
elif "set" in cur_instr.opcode:
self.score += 1.0
def check_register_ops(self):
"""
:return void: Increases gadget's score if it contains operations on a value carrying or a bystander register
"""
first_instr = self.instructions[0]
# Check if the first instruction creates a value or is an xchg operand (excluded as an edge case)
if not first_instr.creates_value() or "xchg" in first_instr.opcode:
first_family = None
else:
# Check op1 to find the register family to protect
first_family = Instruction.get_operand_register_family(first_instr.op1)
for i in range(1, len(self.instructions)-1):
cur_instr = self.instructions[i]
# Ignore instructions that do not create values
if not cur_instr.creates_value():
continue
# If the new value is a modification of the value-carrying register
if first_family is not None and first_family == Instruction.get_operand_register_family(cur_instr.op1):
if cur_instr.opcode in ["shl", "shr", "sar", "sal", "ror", "rol", "rcr", "rcl"]:
self.score += 1.5
else:
self.score += 1.0 # Will be a static modification, otherwise it would have been rejected earlier
elif "xchg" not in cur_instr.opcode and cur_instr.opcode != "pop":
# The modification is to a "bystander register". static mods +0.5, non-static +1.0
if cur_instr.op2 is not None and Instruction.get_operand_register_family(cur_instr.op2) is not None:
self.score += 1.0
else:
self.score += 0.5
def check_branch_target_of_operation(self):
"""
:return void: Increases gadget's score if the gadget has an intermediate instruction that performs certain
operations on the indirect branch target register family.
"""
last_instr = self.instructions[len(self.instructions)-1]
target_family = Instruction.get_operand_register_family(last_instr.op1)
# Scan instructions to determine if they modify the target register family
for i in range(len(self.instructions) - 1):
cur_instr = self.instructions[i]
# Ignore instructions that do not create values
if not cur_instr.creates_value():
continue
# Increase score by 3 for shift/rotate ops, and 2 for others
if Instruction.get_operand_register_family(cur_instr.op1) == target_family:
if cur_instr.opcode in ["shl", "shr", "sar", "sal", "ror", "rol", "rcr", "rcl"]:
self.score += 3.0
else: # All other modifications to target register
self.score += 2.0
def check_memory_writes(self):
"""
:return void: Increases gadget's score if the gadget has an instruction that writes to memory.
"""
# Iterate through instructions except GPI
for i in range(len(self.instructions)-1):
cur_instr = self.instructions[i]
# Ignore instructions that do not create values
if not cur_instr.creates_value():
continue
# Have to check both operands for xchg instrucitons
if "xchg" in cur_instr.opcode and ("[" in cur_instr.op1 or "[" in cur_instr.op2):
self.score += 1.0
elif cur_instr.op1 is not None and "[" in cur_instr.op1:
self.score += 1.0
| true |
c25d9cd35d667f92e0a6c2906acf901cc01c0a7e | Python | mdelpozobanos/sqlebra | /test_sqlebra/test_dtype/test_list.py | UTF-8 | 5,200 | 2.828125 | 3 | [] | no_license | import unittest
import os
from sqlebra.sqlite import SQLiteDB as DB
from sqlebra.dtype import list_ as SQLlist
from sqlebra.dtype import int_ as SQLint
from sqlebra import exceptions as ex
FILE = 'unittest.sqlebra.db'
class TestInit(unittest.TestCase):
value = [10, 11, 12]
@classmethod
def setUpClass(cls):
cls.dbfile = DB(FILE, mode='w').open()
def test_1_set(self):
self.dbfile['A'] = self.value
self.assertEqual([None] + self.value, [r[6] for r in self.dbfile.select(where={'id': 0})])
def test_2_get(self):
self.assertIsInstance(self.dbfile['A'], SQLlist)
@classmethod
def tearDownClass(cls):
cls.dbfile.disconnect()
os.remove(FILE)
class TestInitNested(unittest.TestCase):
value = [[10, 11, 12], [13, 14], 15]
@classmethod
def setUpClass(cls):
cls.dbfile = DB(FILE, mode='w').open()
def test_1_set(self):
self.dbfile['A'] = self.value
self.assertEqual(['list', 'list', 'list', 'int'], [r[2] for r in self.dbfile.select(where={'id': 0})])
self.assertEqual([None, None, None, 15], [r[6] for r in self.dbfile.select(where={'id': 0})])
self.assertEqual([None] + self.value[0], [r[6] for r in self.dbfile.select(where={'id': 1})])
self.assertEqual([None] + self.value[1], [r[6] for r in self.dbfile.select(where={'id': 2})])
def test_2_get(self):
self.assertIsInstance(self.dbfile['A'], SQLlist)
def test_3_py(self):
self.dbfile[0]
self.assertEqual(self.value, self.dbfile['A'].py)
@classmethod
def tearDownClass(cls):
cls.dbfile.disconnect()
os.remove(FILE)
class TestSingle(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.dbfile = DB(FILE, mode='w').open()
value = [10, 11, 12]
cls.dbfile['A'] = value
cls.x = [value, cls.dbfile['A']]
def test_01_get_item(self):
self.assertIsInstance(self.x[1][0], SQLint)
def test_02_py(self):
self.assertEqual(self.x[0], self.x[1].py)
def test_02_1_py_item(self):
self.assertEqual(self.x[0][0], self.x[1][0].py)
def test_03_edit(self):
self.x[0] = [20, 21, 22]
self.x[1].py = [20, 21, 22]
self.assertEqual(self.x[0], self.x[1].py)
def test_04_1_edit_item(self):
for xn in self.x:
xn[1] = 100
self.assertEqual(self.x[0], self.x[1].py)
def test_05_append(self):
for xn in self.x:
xn.append(5)
self.assertEqual(self.x[0], self.x[1].py)
def test_06_extend(self):
for xn in self.x:
xn.extend([6, 3, 0])
self.assertEqual(self.x[0], self.x[1].py)
def test_07_insert(self):
for xn in self.x:
xn.insert(2, 7)
self.assertEqual(self.x[0], self.x[1].py)
def test_08_index(self):
self.assertEqual(self.x[0].index(100), self.x[1].index(100))
def test_09_remove(self):
self.assertEqual(self.x[0].remove(100), self.x[1].remove(100))
def test_10_pop(self):
self.assertEqual(self.x[0].pop(), self.x[1].pop())
self.assertEqual(self.x[0], self.x[1].py)
def test_11_count(self):
self.assertEqual(self.x[0].count(5), self.x[1].count(5))
def test_12_iter(self):
for x0, x1 in zip(self.x[0], self.x[1]):
self.assertEqual(x0, x1.py)
def test_99_delete(self):
self.x[1].delete()
with self.assertRaises(ex.VariableError):
self.dbfile['A']
@classmethod
def tearDownClass(cls):
cls.dbfile.disconnect()
os.remove(FILE)
class TestNested(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.dbfile = DB(FILE, mode='w').open()
value = [[10, 11, 12], [13, 14], 15]
cls.dbfile['A'] = value
cls.x = [value, cls.dbfile['A']]
def test_01_get_item(self):
self.assertIsInstance(self.x[1][0], SQLlist)
self.assertIsInstance(self.x[1][2], SQLint)
def test_02_py(self):
self.assertEqual(self.x[0], self.x[1].py)
def test_02_1_py_item(self):
self.assertEqual(self.x[0][0], self.x[1][0].py)
def test_03_edit(self):
self.x[0] = [[20, 21, 22], [23, 24], 25]
self.x[1].py = self.x[0]
self.assertEqual(self.x[0], self.x[1].py)
def test_03_1_edit_item(self):
for xn in self.x:
xn[0] = 100
self.assertEqual(self.x[0], self.x[1].py)
@classmethod
def tearDownClass(cls):
cls.dbfile.disconnect()
os.remove(FILE)
class TestEmpty(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.dbfile = DB(FILE, mode='w').open()
def test_1_set(self):
self.dbfile['A'] = []
def test_2_get(self):
self.assertIsInstance(self.dbfile['A'], SQLlist)
def test_3_py(self):
self.assertEqual([], self.dbfile['A'].py)
@classmethod
def tearDownClass(cls):
cls.dbfile.disconnect()
os.remove(FILE)
if __name__ == '__main__':
try:
unittest.main()
except Exception as e:
if os.path.exists(FILE):
os.remove(FILE)
raise e
| true |
214c11dfc8a2438f5f29623ce751b91852a7a9ca | Python | juan250897/Prueba-_Tecnica_TSAKANA | /2_prueba_logica/cifrado_cesar.py | UTF-8 | 1,036 | 4.03125 | 4 | [] | no_license | abc = "ABCDEFGHIJKLMNÑOPQRSTUVWXYZ"
# COLOQUE LA FUNCION CIFRAR() CON EL FIN DE PROBAR LA EFECTIVIDAD DE DECIFRAR()
def cifrar (texto, desplazamiento):
texto_cifrar = ""
for letra in texto:
suma = abc.find(letra) + desplazamiento
modulo = int(suma) % len(abc)
texto_cifrar = texto_cifrar + str(abc[modulo])
return texto_cifrar
def descifrar (texto_cifrado, desplazamiento):
texto_decifrar = ""
for letra in texto_cifrado:
suma = abc.find(letra) - desplazamiento
modulo = int(suma) % len(abc)
texto_decifrar = texto_decifrar + str(abc[modulo])
return texto_decifrar
texto = (input ("cual es el texto a cifrar: ")).upper()
desplazamiento1 = int(input ("cual es el desplazamiento: "))
print (f"el texto cifrado es: {cifrar(texto,desplazamiento1)}")
texto_cifrado = (input ('cual es el texto a decifrar: ')).upper()
desplazamiento2 = int(input ('cual es el desplazamiento: '))
print (f"el texto descifrado es: {descifrar(texto_cifrado,desplazamiento2)}")
| true |
712dae9b76021ce3fb5c4ee2443dea263e669797 | Python | sp0gg/exercism | /python/bank-account/bank_account.py | UTF-8 | 1,369 | 3.078125 | 3 | [] | no_license | from functools import wraps
from threading import Lock
lock = Lock()
def validate_open(fn):
@wraps(fn)
def _validate_open(self, *args, **kwargs):
if not self._is_open:
raise ValueError('u dun goofed')
return fn(self, *args, **kwargs)
return _validate_open
def validate_amount(fn):
@wraps(fn)
def _validate_amount(self, *args, **kwargs):
if args[0] <= 0:
raise ValueError('wtf hax0r?')
return fn(self, *args, **kwargs)
return _validate_amount
def validate_sufficient_funds(fn):
@wraps(fn)
def _validate_sufficient_funds(self, *args, **kwargs):
if self._balance < args[0]:
raise ValueError('u broke son')
return fn(self, *args, **kwargs)
return _validate_sufficient_funds
class BankAccount(object):
def __init__(self):
self._balance = 0
self._is_open = False
@validate_open
def get_balance(self):
return self._balance
@validate_amount
@validate_open
def deposit(self, amount):
with lock:
self._balance += amount
@validate_sufficient_funds
@validate_amount
@validate_open
def withdraw(self, amount):
with lock:
self._balance -= amount
def open(self):
self._is_open = True
def close(self):
self._is_open = False
| true |
3a773c255e8d4b2b6ea80f6718ae8f0541cd7cdf | Python | mikeyQuantR/BitTwit | /main.py | UTF-8 | 1,404 | 3.109375 | 3 | [] | no_license | '''
Welcome to BitTwit. This application tries to analyse the general sentiment about $BTC on Twitter
and predict prices based on them. It rests on the assumption that fluctuations in the positive attitude
towards $BTC relayed on social media will affect its price on market.
BitTwit comprises
1) twitter_scraper.py that scrapes 24hrs worth of bitcoin tweets at 00:00 UTC and stores them into a csv
with respective follower count.
2) pricecollect.py that pulls bitcoin price trend data from BitcoinAverage's API, minute-wise. The price data
is also stored in a csv.
3) VADER, which is a sentiment analysis library. All the scraped tweets from the previous day are fed into it
and it will assign them a "Polarity Score" that is represented by a single scalar we call "compound value".
4) SentimentStatistics.py that takes compound values from VADER, follower counts from twitter_scraper and
scales the sentiments with the follower count. After scaling, it calculates the variance, median and average
for the compound values. These are stored in daily txt files.
'''
import twitter_scraper as ts
import pricecollect as pc
import VADER
import SentimentStatistics as SenStat
import time
date = time.gmtime()
while True:
followers = ts.scrapetwitter(date)
pc.pull_price(date)
compoundlist = VADER.sentiment(date)
SenStat.analyzer(compoundlist, followers, date)
time.sleep(86400) | true |
100a468a43ca82411e6fda16b2c3db7078072c5b | Python | cuauv/software | /hydrocode/modules/pinger/scatterplot.py | UTF-8 | 2,118 | 2.703125 | 3 | [
"BSD-3-Clause"
] | permissive | import math
import queue
import time
import numpy as np
from common import const, plot
class ScatterPlot(plot.PlotBase):
def plot(self, hdg, elev):
try:
self._q.put_nowait((hdg, elev))
except queue.Full:
pass
@staticmethod
def _daemon(q):
from matplotlib.ticker import AutoMinorLocator
(pyplot, fig) = plot.PlotBase._daemon_init()
pyplot.suptitle('Relative Heading/Elevation Scatter Plot')
(ax, points, text) = ScatterPlot._define_plot(fig, AutoMinorLocator)
hdg_list = []
elev_list = []
while True:
try:
(hdg, elev) = q.get_nowait()
hdg_list.append(hdg)
elev_list.append(elev)
points.set_data(hdg_list, elev_list)
text.set_text(
'HDG std: ' + '{:.2f}'.format(np.std(hdg_list)) + '\n' +
'HDG mean: ' + '{:.2f}'.format(np.mean(hdg_list)) + '\n' +
'ELEV std: ' + '{:.2f}'.format(np.std(elev_list)) + '\n' +
'ELEV mean: ' + '{:.2f}'.format(np.mean(elev_list)))
pyplot.draw()
pyplot.show(block=False)
except queue.Empty:
pass
fig.canvas.flush_events()
time.sleep(const.GUI_UPDATE_TIME)
@staticmethod
def _define_plot(fig, AutoMinorLocator):
ax = fig.add_subplot(111)
ax.set_xlabel('Heading (rad)')
ax.set_ylabel('Elevation (rad)')
ax.set_xticks([-3, -2, -1, 0, 1, 2, 3])
ax.set_yticks([-1, 0, 1])
ax.xaxis.set_minor_locator(AutoMinorLocator(10))
ax.yaxis.set_minor_locator(AutoMinorLocator(10))
ax.set_xlim(-math.pi, math.pi)
ax.set_ylim(-math.pi / 2, math.pi / 2)
ax.set_aspect('equal', adjustable='box')
ax.grid(True, which='major', linestyle='-')
ax.grid(True, which='minor', linestyle=':')
points = ax.plot([], [], color='r', marker='.', ls='', markersize=1)
text = ax.text(-3, 1.6, '')
return (ax, points[0], text) | true |
126279fa0ff2509b9c83e1fa0384fd10fd302405 | Python | sboerlage/Mitochondrial-Image-Analysis-Scripts | /calculatedAverages.py | UTF-8 | 2,043 | 2.953125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 22 15:44:38 2016
@author: Sophie Boerlage
"""
import pandas as pd
import os
# Directory must be set up with a different file for each imaging condition and all the images for that condition contained within their files
# Currently, any different directry structure will not work, so the directory must not contain any other file types
directory = "C:\\Users\\Norsys\\Desktop\\PythonTest\\"
# Loop over the files of different image conditions
for subdir in os.listdir(directory):
# Initialize the csv file that will be used as the Master Summary
'''
header = pd.DataFrame(['Count','Area','Perim.','Circ.','AR','Round','Solidity','MTG','TMRE','Ratio','FormFactor'])
tranHeader = header.transpose()
tranHeader.to_csv(directory + subdir + "\\Analysis\\Master Summary.csv", index=False)
'''
# Loop over all the images within each image condition file
for file in os.listdir(directory + subdir + "\\Analysis"):
data = pd.read_csv(directory + subdir + "\\Analysis\\" + file + "\\Summary.csv")
# Take the add the form factor, 1/circularity
average = data.mean()
TMRE_MTGRatio = pd.Series((average[8]/average[7]), index=["Ratio"])
FFSeries = pd.Series(1/average[4])
countSeries = pd.Series(len(data), index=["Count"])
avgSeries = countSeries.append(average[1:9])
ratioSeries = avgSeries.append(TMRE_MTGRatio)
finSeries = ratioSeries.append(FFSeries)
df = pd.DataFrame(finSeries)
tdf = df.transpose()
with open(directory + subdir + "\\Analysis\\Master Summary.csv", 'a') as f:
tdf.to_csv(f, header=False, index=False)
f.close()
# with open(directory + subdir + "\\Analysis\\Master Summary.csv", 'a') as f:
| true |
58d1460c7c52025291be4b786628dab7f2bde843 | Python | James-Bedford/Python | /remove_duplicates.py | UTF-8 | 227 | 3.65625 | 4 | [] | no_license | '''
function to remove duplicates
'''
def remove_duplicates(sequence):
output = [5]
for x in sequence:
if x not in output:
output.append(x)
return output
print(remove_duplicates([1,1,2,2,5]))
| true |
01647121ce38d3faef5dcfda81041e67646de719 | Python | kartikdutt18/LeetCode-CLI | /src/create_snippet.py | UTF-8 | 1,851 | 2.890625 | 3 | [
"MIT"
] | permissive | from cfg import INCLUDE_LIBS_KEY, MAIN_KEY, SNIPPET_PATH
import json
import os
class CreateSnippet():
def __init__(self) :
super().__init__()
self.extentionLanguage = {'cpp': 'cpp', 'py': 'python', 'java': 'java'}
def WriteCode(self, text : str, filename : str) :
"""
Creates a file with given texted commented. Additionaly it will incorporate
pre-defined snippets.
args:
text : Text which will be commented.
filename : File in which text will be copied.
Returns None.
"""
extention = filename.split('.')[1]
snippetPath = os.path.join(
SNIPPET_PATH, self.extentionLanguage[extention] + "_snippet.json")
if os.path.exists(snippetPath) :
with open(snippetPath, 'r') as snippetMap:
snippet = json.load(snippetMap)
try :
text = self.Commentify(text, self.extentionLanguage[extention])
code = snippet[INCLUDE_LIBS_KEY] + text + snippet[MAIN_KEY]
file = open(os.path.join(os.getcwd(), filename), 'w')
file.write(code)
except KeyError:
print("Error Refer to sample snippets to see how snippets are made.")
return None
text = self.Commentify(text = text, language = self.extentionLanguage[extention])
file = open(os.path.join(os.getcwd(), filename), 'w')
file.write(text)
return None
def Commentify(self, text : str, language : str) :
"""
Commentify the given text based on language.
args:
text : Text which will be commented.
language : One of cpp, java or python.
Returns commented text.
"""
if language == "cpp" or language == "java":
text = "\n\n/**\n * " + text.replace('\n', '\n * ') + "\n**/\n\n"
return text
elif language == "python":
text = "\n\n\"\"\" \n" + text + "\n\"\"\"\n\n"
return text
return text
| true |
48f32b81205a3a2a25528a1049133415b1f885a8 | Python | trantu86/gridtools | /gridgen_example.py | UTF-8 | 3,815 | 2.71875 | 3 | [] | no_license | """
This script is for testing the use of gridgen from
octant where I am using the examples given by
Pavel Sakov.
"""
import sys
import os
try:
from octant.grid import Gridgen
except ImportError:
try:
from pygridgen.grid import Gridgen
except ImportError:
if os.name is 'posix':
os.system('clear')
else:
os.system('cls')
print "=========================================="
print ""
print "Check where is your gridgen module located"
print ""
print "=========================================="
print ""
sys.exit()
import numpy as np
from matplotlib.pyplot import plot, show, xlabel, ylabel, title, clf, close, figure, tight_layout
from matplotlib import rcParams
from matplotlib.backends.backend_pdf import PdfPages
rcParams.update({'font.size':7})
with PdfPages('gridgen_python.pdf') as pdf:
for i in xrange(6):
params = {}
#read the parameter files and store in a dictionary
with open('prm.'+str(i)) as tempfile:
for row in tempfile.readlines():
if row.split()[0] in ['nx','ny','nnodes','newton']:
params[row.split()[0]] = int(row.split()[1])
elif row.split()[0] == 'precision':
params[row.split()[0]] = float(row.split()[1])
else:
params[row.split()[0]] = row.split()[1]
#read the coordinates files and add them to lists
coordinates = []
beta = []
with open(params['input']) as inputfile:
for row in inputfile.readlines():
if row.startswith('#'):
pass
elif row == '\n':
pass
else:
coordinates.append([float(row.split()[0]), float(row.split()[1])])
if len(row.split()) > 2:
if row.split()[-1][-1] == '*':
if len(row.split()[-1]) == 2:
beta.append(float(row.split()[-1][:1]))
else:
beta.append(float(row.split()[-1][:2]))
else:
beta.append(float(row.split()[-1]))
else:
beta.append(float(0))
coordinates = np.array(coordinates)
#print params['nx'], params['ny']
#generate grid using gridgen class from octant
#it should work similary with prygridgen,
#by changing modifying the name above
grid = Gridgen(coordinates[:,0], coordinates[:,1], beta, (params['ny'],\
params['nx']), ul_idx=0, nnodes=params['nnodes'],\
precision=params['precision'], verbose=True)
#generate the figures and save them to the pdf file
fig = figure(figsize=(4, 4))
if i == 0:
marker1 = 'k.-'; marker2='b.-'
else:
marker1 = 'k-'; marker2='b-'
ax = fig.add_subplot(111)
ax.plot(coordinates[:,0], coordinates[:,1], marker1, lw=0.3, markersize=1.2)
ax.plot(grid.x, grid.y, marker2, lw=0.3, markersize=1.2)
ax.plot(grid.x.T, grid.y.T, marker2, lw=0.3, markersize=1.2)
ax.scatter(coordinates[:,0], coordinates[:,1], 10, \
c=beta, marker='o',facecolors='none')
ax.set_xlim(coordinates[:,0].min() - 0.5, coordinates[:,0].max() + 0.5)
ax.set_ylim(coordinates[:,1].min() - 0.5, coordinates[:,1].max() + 0.5)
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_title('grid.'+str(i))
tight_layout()
#savefig('grid_'+str(i)+'.png', dpi=300, bbox_inches='tight')
pdf.savefig()
clf()
close('all')
| true |
821182730be05428eca75c129c35f90978e33f22 | Python | Hansari346/Facial_Recognition_Capstone | /Taking_Video/VidsFrames_upd3.py | UTF-8 | 3,175 | 2.796875 | 3 | [] | no_license | import numpy as np
import cv2
import os
from mtcnn.mtcnn import MTCNN
import time
def TakeVideo():
#move video files to "Videos" folder
os.chdir(VideosPath)
#update video name based on time
video_name = format(int(round(time.time() * 100000))) + '.avi'
out = cv2.VideoWriter(video_name,fourcc, frame_rate, (frame_width,frame_height))
#turn webcam on while interrupt is not triggered
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'): #set interrupt here - set to "q" for now
break
else:
break
#release everything if job is finished
cap.release()
out.release()
cv2.destroyWindow('frame')
#video to frames function
def FrameCapture(path):
#change directory to "Frames" folder. Here the frames will be saved
os.chdir(FramesPath)
#run through each video
for vid in os.listdir(path):
videoObj = cv2.VideoCapture(path+ "/" + vid) #select desired video
success = 1
#save each frame
while success:
success, frame = videoObj.read()
cv2.imwrite(format(int(round(time.time() * 100000))) + '.jpg', frame) #save frame in "Frames" folder
#Crop faces from frames
def BoundingBox(path, detector):
#store detected faces in "Faces" folder
os.chdir(FacesPath)
#for each photo in "Frames" folder
for img in os.listdir(path):
if os.path.getsize(path + "/" + img) != 0:
image = cv2.imread(path + "/" + img)
result = detector.detect_faces(image) #feedforward image to MTCNN network
if result != []: #if no face detected, result = []
for person in result: #could be multiple detected faces in one image
bounding_box = person['box']
x = bounding_box[0] #x coordinate of top-left pixel for bounding box
y = bounding_box[1] #y coordinate of top-left pixel for bounding box
width = bounding_box[2] #width of bounding box
height = bounding_box[3] #height of bounding box
cv2.imwrite(format(int(round(time.time() * 100000))) + '.jpg', image[y:y+height, x:x+width]) #crop the bounding box
#load MTCNN network once to save time
detector = MTCNN()
#Paths used in Project
VideosPath = "/home/hewitt/Desktop/Project/Videos" #folder for videos
FramesPath = "/home/hewitt/Desktop/Project/Frames" #folder for frames
FacesPath = "/home/hewitt/Desktop/Project/Faces" #folder for faces
#USB web cam
cap = cv2.VideoCapture(1)
#resolution
cap.set(3, 1280)
cap.set(4,720)
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
#frame rate
frame_rate = 30
cap.set(5,frame_rate)
#define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
#Take Video
TakeVideo()
#Turn videos into frames
FrameCapture(VideosPath)
#Run MTCNN network to crop faces from frames
BoundingBox(FramesPath, detector)
| true |
8512f6bcbe4e89658c3862d9905f0094127fa3d6 | Python | RuiNian7319/Machine_learning_toolbox | /Feature_Selector.py | UTF-8 | 22,922 | 3.015625 | 3 | [] | no_license | """
Feature Selector Class for Willowglen Project
Rui Nian
Last Updated: Jan-15-2018
"""
import pandas as pd
import numpy as np
import pickle
import matplotlib.pyplot as plt
import seaborn as sns
from copy import deepcopy
# from Data_loader import data_loader
import random
import gc
from itertools import chain
import os
class FeatureSelector:
"""
Attributes:
------
features_removed: A list of all the removed features
removal_ops: Dictionary of removal operations ran and associated features for removal identified by
that removal method
record_missing: Records fraction of missing values for features with missing fraction
above threshold
missing_threshold: Threshold for missing values for column to be considered "removal quality"
missing_stats: Index are all the features, first column is all the % missing stats
record_single_unique: Records features with single unique value
unique_stats: Data frame of each feature and its corresponding number of unique values
record_collinear: Records pairs of features with collinear features about threshold
correlation_threshold: Correlation required between 2 features to be identified as highly correlated
corr_matrix: Correlation matrix between all features within the data set
record_near_unique: Data frame of all features that have a very imbalanced boolean distribution
Methods:
-------
identify_mssing: Identifies all columns with missing columns above threshold
plot_missing: Plots histograms of # of features vs. % missing value
identify_single_unique: Identifies all columns with a single unique value
plot_single_unique: Plots histogram of # of features vs. # of unique values in that column
identify_collinear: Identifies all correlations between all features within the data set
plot_collinear: Plots a correlation heat map between all features
remove_near_unique: Identifies all boolean data types whose data is highly imbalanced
plot_near_unique: Plots # of features vs the % of data in the positive class
identify_feature: Removes any SINGLE features selected by operator
readd_feature: Re-adds any SINGLE features selected by operator
check_identified: Returns all features that are currently marked for deletion
removal: Removes the features marked for deletion
unique_value: Static Method. Used to find a unique set of the original data
remove_idtype: Method only applicable to Suncor/Willowglen. Removes all features with a certain IDType
"""
def __init__(self):
self.features_removed = []
# Dictionary to hold removal operations
self.removal_ops = {'custom': []}
# Missing threshold attributes
self.record_missing = None
self.missing_threshold = None
self.missing_stats = None
# Unique values attributes
self.record_single_unique = None
self.unique_stats = None
# Collinear attributes
self.record_collinear = None
self.correlation_threshold = None
self.corr_matrix = None
# Custom ID removal attributes
self.record_id_removal = None
# Near unique attributes
self.record_near_unique = None
def __str__(self):
return "Select featured based on missing values, single unique values, and collinearity"
def __repr__(self):
return "FeatureSelector()"
def identify_missing(self, data, missing_threshold, json_file=False):
"""
Method that removes columns with missing value percentage above a threshold defined by: missing_threshold
"""
self.missing_threshold = missing_threshold
# Calculates fraction of missing in each column
missing_series = data.isnull().sum() / data.shape[0]
# Make the missing_series into a data frame
self.missing_stats = pd.DataFrame(missing_series).rename(columns={'index': 'feature', 0: 'missing_fraction'})
# Find columns with missing stats above threshold
record_missing = pd.DataFrame(missing_series[missing_series > missing_threshold]).reset_index().rename(
columns={'index': 'feature', 0: 'missing_fraction'})
# Make a list of all the headers in the record_missing data frame
drop = list(record_missing['feature'])
self.record_missing = record_missing
self.removal_ops['missing'] = drop
print('{} features with greater than {}% of missing values. \n'.format(len(self.removal_ops['missing']),
self.missing_threshold * 100))
if json_file:
bin_list = np.linspace(-0.001, 1, 21)
histogram_json = self.missing_stats.groupby(pd.cut(self.missing_stats.iloc[:, 0], bin_list)).count()
print(histogram_json)
histogram_json.to_json('JSON/missing_values_plot.json', orient='split')
def plot_missing(self):
"""
Method for visualization of missing values
"""
if self.missing_stats is None:
raise NotImplementedError("No missing data, or the identify missing method was not ran")
plt.figure()
self.missing_stats.plot.hist(color='red', edgecolor='k', figsize=(6, 4), fontsize=14)
plt.ylabel('# of Features', size=18)
plt.xlabel('% of Missing Data', size=18)
plt.xlim([0, 1])
plt.title('Missing Data Histogram', size=18)
plt.show()
def identify_single_unique(self, data, json_file=False):
"""
Method to identify columns with single unique values, meaning they have no predictive power
"""
# Calculates the unique counts in each column
unique_counts = data.nunique()
self.unique_stats = pd.DataFrame(unique_counts).rename(columns={'index': 'features', 0: 'nunique'})
# Find columns with only one value
record_single_unique = pd.DataFrame(unique_counts[unique_counts == 1]).reset_index().rename(columns={
'index': 'features',
0: 'Number Unique'
})
# Find columns with two unique values
record_boolean_values = pd.DataFrame(unique_counts[unique_counts == 2]).reset_index().rename(columns={
'index': 'features',
0: 'Number Boolean'
})
drop = list(record_single_unique['features'])
self.record_single_unique = record_single_unique
self.removal_ops['single_unique'] = drop
print('{} features has only one unique value. \n'.format(len(self.removal_ops['single_unique'])))
print('{} features are boolean values. \n'.format(len(record_boolean_values)))
if json_file:
# Take the log space
bin_list = np.logspace(0, np.log10(self.unique_stats.iloc[:, 0].max()), 15)
histogram_json = self.unique_stats.groupby(pd.cut(self.unique_stats.iloc[:, 0], bin_list)).count()
histogram_json.to_json('JSON/unique_value_plot.json', orient='split')
print(histogram_json)
def plot_single_unique(self):
"""
Histogram of # of unique values in each column
"""
if self.unique_stats is None:
raise NotImplementedError("No features are unique, or single unique method was not ran.")
plt.figure()
self.unique_stats.plot.hist(color='blue', edgecolor='k', figsize=(6, 4), fontsize=14,
bins=np.logspace(0, np.log10(self.unique_stats.iloc[:, 0].max()), 15))
plt.ylabel('# of Features')
plt.xlabel('Unique Values')
plt.gca().set_xscale('log')
plt.title("Unique Value Histogram")
plt.show()
def identify_collinear(self, data, correlation_threshold, json_file=False):
"""
Identify highly collinear features. Collinear features highly reduce predictive powers.
Reference: https://www.quora.com/Why-is-multicollinearity-bad-in-laymans-terms-In-feature-selection-for-a-
regression-model-intended-for-use-in-prediction-why-is-it-a-bad-thing-to-have-multicollinearity-or-highly-
correlated-independent-variables
Identifies any columns of data with highly correlated data, correlation threshold is determined by using
using the correlation_threshold.
"""
self.correlation_threshold = correlation_threshold
# Calculates the correlations between each column. https://en.wikipedia.org/wiki/Pearson_correlation_coefficient
corr_matrix = data.corr()
self.corr_matrix = corr_matrix
# Extract upper triangular of the correlation matrix, since the matrix is symmetrical. Does not take diagonal
# since diagonal is all 1
upper = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(np.bool))
# Select the features with correlations above the threshold (absolute value is used in case of neg corr)
drop = [column for column in upper.columns if any(upper[column].abs() > correlation_threshold)]
# Remember correlated pairs
record_collinear = pd.DataFrame(columns=['drop_feature', 'corr_feature', 'corr_value'])
# Iterate through columns to identify which to drop
for column in drop:
# Find correlated features
corr_features = list(upper.index[upper[column].abs() > correlation_threshold])
# Find the correlated values
corr_values = list(upper[column][upper[column].abs() > correlation_threshold])
drop_features = [column for _ in range(len(corr_features))]
# Record the information
temp_df = pd.DataFrame.from_dict({'drop_feature': drop_features,
'corr_feature': corr_features,
'corr_value': corr_values})
# Add to DataFrame
record_collinear = record_collinear.append(temp_df, ignore_index=True, sort=True)
self.record_collinear = record_collinear
self.removal_ops['collinear'] = drop
print("{} features with a correlation greater than {}%. \n".format(len(self.removal_ops['collinear']),
correlation_threshold * 100))
if json_file:
collinear_json = self.corr_matrix.loc[list(self.record_collinear['corr_feature']),
list(self.record_collinear['drop_feature'])]
collinear_json.to_json("JSON/collinear_plot.json", orient='split')
def plot_collinear(self):
"""
Heatmap of the features with correlations above the correlated threshold in the data.
Notes
--------
- Not all of the plotted correlations are above the threshold because this plots
all the variables that have been identified as having even one correlation above the threshold
- The features on the x-axis are those that will be removed. The features on the y-axis
are the correlated feature with those on the x-axis
"""
if self.record_collinear is None:
raise NotImplementedError('Collinear features have not been idenfitied. Run `identify_collinear`.')
# Identify the correlations that were above the threshold
corr_matrix_plot = self.corr_matrix.loc[list(self.record_collinear['corr_feature']),
list(self.record_collinear['drop_feature'])]
# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(10, 8))
# Generate a custom diverging colormap
cmap = sns.diverging_palette(220, 10, as_cmap=True)
# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(corr_matrix_plot, cmap=cmap, center=0,
linewidths=.25, cbar_kws={"shrink": 0.6})
ax.set_yticks([x + 0.5 for x in list(range(corr_matrix_plot.shape[0]))])
ax.set_yticklabels(list(corr_matrix_plot.index), size=int(160 / corr_matrix_plot.shape[0]))
ax.set_xticks([x + 0.5 for x in list(range(corr_matrix_plot.shape[1]))])
ax.set_xticklabels(list(corr_matrix_plot.columns), size=int(160 / corr_matrix_plot.shape[1]))
plt.xlabel('Features to Remove', size=8)
plt.ylabel('Correlated Feature', size=8)
plt.title("Correlations Above Threshold", size=14)
plt.show()
def remove_near_unique(self, data, threshold, json_file=False):
"""
Removes binary, trinary, etc. columns that are mostly one value
threshold: % of total being equal to 1. For a column with 100 examples, at a threshold of 0.03 (3%), any
columns with less than 3% of values being 1 or greater than 97% of values being 1 will be set for deletion.
DOES NOT FILTER OUT MULTI-CLASS CATEGORIES AT THE MOMENT
"""
drop = []
positives = []
# Iterate over the different columns
for i in range(data.shape[1]):
# Pass any columns that are not boolean. Greater than 3 means it filters floats that are higher than 3.
# Less than 0.99 means it filters any floats that possibly have very low values or negative values.
if abs(data.iloc[:, i].max()) > 1 or abs(data.iloc[:, i].min()) > 1 or abs(data.iloc[:, i].max()) < 0.99:
pass
else:
# Sum up that column
total_count = sum(data.iloc[:, i])
# If the total of a class is less than 2% or higher than 98%, append column
if total_count < (threshold * data.shape[0]) or total_count > ((1 - threshold) * data.shape[0]):
drop.append(data.columns[i])
positives.append(total_count / data.shape[0])
# Construct the record_near_unique data frame
self.record_near_unique = pd.DataFrame([drop, positives]).T.rename(columns={0: 'features', 1: 'pos'})
self.removal_ops['near_unique'] = drop
print('{} features near unique with threshold {}%'.format(len(self.removal_ops['near_unique']),
threshold * 100))
if json_file:
bin_json = np.linspace(0, 1, 21)
near_unique = self.record_near_unique.groupby(pd.cut(self.record_near_unique.iloc[:, 1], bin_json)).count()
near_unique.drop(columns=['features'])
near_unique.to_json('data/near_unique_plot.json', orient='split')
print(near_unique)
def plot_near_unique(self):
"""
Plots the near unique histogram, showing how the positive class is distributed
"""
if self.record_near_unique is None:
raise NotImplementedError('No near unique values, perhaps the method was not ran')
plt.figure()
self.record_near_unique.plot.hist(color='red', edgecolor='k', figsize=(6, 4), fontsize=14)
plt.xlim([0, 1])
plt.title('Near Unique Histogram', size=18)
plt.xlabel("% of Positive Data Class")
plt.ylabel("# Of Features")
plt.show()
def identify_feature(self, data, col_name):
"""
Allows user to add additional features to the removal list
"""
if col_name in list(data):
self.removal_ops['custom'].append(col_name)
else:
print("Column name not found!")
def readd_feature(self, col_name):
"""
Removes feature(s) from the removal list if the operator decides that the feature is important
"""
# Iterate through all the keys in the dictionary
for key in self.removal_ops.keys():
# If the col_name is found in one of the removal ops
if col_name in self.removal_ops[key]:
# Enumerate across all col names in that removal ops list
for i, col_names in enumerate(self.removal_ops[key]):
# If the col name is found, delete it
if col_names == col_name:
del self.removal_ops[key][i]
def check_identified(self):
"""
Prints out a list of all the variables set for removal
"""
# Identifies all variables set for deletion
all_identified = list(chain(*list(self.removal_ops.values())))
print("{} features are identified for removal".format(len(all_identified)))
return all_identified
def removal(self, data, methods):
"""
Removes the columns set for removal with accordance to the specific method.
Methods: Delete all features identified with this particular method, if all is passed, deletes all columns in
the removal ops dictionary
keys: ['missing], ['single_unique'], ['collinear'], ['id_type'], ['near_unique'], ['custom']
"""
features_to_drop = []
# data = pd.get_dummies(data)
if methods == 'all':
print('{} method(s) has been ran.'.format(list(self.removal_ops.keys())))
# Find the unique features to drop
features_to_drop = list(chain(*list(self.removal_ops.values())))
else:
# Iterate through the specified methods
for method in methods:
# Check to make sure the method has been run
if method not in self.removal_ops.keys():
raise NotFittedError('{} method has not been ran.'.format(method))
# Append the features identified for removal
else:
features_to_drop.append(self.removal_ops[method])
# Find the unique features to drop
features_to_drop = set(list(chain(*features_to_drop)))
# Find unique features, instead of trying to drop the same column twice
features_to_drop, _ = self.unique_value(features_to_drop)
# Remove the features and return the data
data = data.drop(columns=features_to_drop)
self.features_removed = features_to_drop
print('Removed {} features. The new data has {} features.'.format(len(features_to_drop), data.shape[1]))
return data, self.features_removed
@staticmethod
def online_removal(data, features_to_drop):
"""
Feature removal online to ensure the ML models are receiving correct number of inputs
Inputs
---
data: Data from SCADA
features_to_drop: Useless features identified from previous
Returns
---
data: Data with "features_to_drop" removed.
"""
data = data.drop(columns=features_to_drop)
return data
"""
Identifies unique values
"""
@staticmethod
def unique_value(data):
s = []
duplicate = 0
for x in data:
if x in s:
duplicate += 1
pass
else:
s.append(x)
return s, duplicate
# Methods below this line are only applicable to Suncor Pipeline
def remove_idtype(self, data, col_name="name"):
"""
Deletes custom columns
"""
drop = []
# If a list of values to drop was given
if type(col_name) == list:
for value in col_name:
# If the value does not have _, because all the headers in pipeline are 37879814_302, we need to add _
if value[0] != "_":
# Add the _
value = "_" + value
# Create a list of drop columns
drop = drop + list(data.filter(regex=value))
# If only 1 value was given
else:
# If the col_name is not specified with _ in front, add the _
if col_name[0] != "_":
col_name = "_" + col_name
# Create a list of drop columns
drop = drop + list(data.filter(regex=col_name))
self.removal_ops['id_type'] = drop
if __name__ == "__main__":
# day_minutes = 60 * 24
#
# Data, Original_data = data_loader('data/downsampled_data.csv', chunk_size=day_minutes, num_of_chunks=1000)
Data = pd.read_csv('test_datasets/CoffeeBeanData.csv')
# Builds Feature Selector object
feature_selection = FeatureSelector()
"""
From Google Docs:
input: 0 (missing value method), % missing, data file from previously
"""
# Identifies missing values
feature_selection.identify_missing(Data, missing_threshold=0.3, json_file=False)
feature_selection.plot_missing()
"""
From Google Docs:
input: 1 (unique value method), data file from previously
"""
# Identifies unique values
feature_selection.identify_single_unique(Data, json_file=False)
feature_selection.plot_single_unique()
"""
From Google Docs:
input: 2 (collinear value method), correlation, data file from previously
"""
# Identifies missing values
feature_selection.identify_collinear(Data, correlation_threshold=0.97, json_file=False)
feature_selection.plot_collinear()
"""
From Google Docs:
input: 3 (near unique method), amount of one class, data file from previously
"""
# Identifies near unique columns
feature_selection.remove_near_unique(Data, threshold=0.05, json_file=False)
feature_selection.plot_near_unique()
"""
Delete all the _319 and _322 IDType features
input: col IDTypes, data file from previously
"""
feature_selection.remove_idtype(Data, col_name=['319', '322'])
"""
Removes one custom entry
input: column name, data file from previously
"""
feature_selection.identify_feature(Data, '175643118_630')
"""
Re-add a feature that was accidently deleted
"""
feature_selection.readd_feature('175643118_630')
"""
Remove the features
"""
Data, features_removed = feature_selection.removal(Data, 'all')
# Online feature selection test
Data2 = pd.read_csv('test_datasets/CoffeeBeanDatav2.csv')
Data2 = feature_selection.online_removal(Data2, features_removed)
assert(Data2.shape[1] == Data.shape[1])
# import json
#
# json_featurelist = json.dumps(feature_selection.removal_ops, separators=(',', ':'))
# json_featurelist = json.loads(json_featurelist)
# with open('./data.json', 'w') as outfile:
# json.dump(json_featurelist, outfile)
| true |
c1c91ccb623d29405247099f4178c5e4796860b8 | Python | jiwookseo/problem-solving | /SWEA/sol/1859.py | UTF-8 | 203 | 2.875 | 3 | [] | no_license | for t in range(1,int(input())+1):
n,s,=int(input()),list(map(int, input().split()));m,r=s[-1],0
for i in range(n-2,-1,-1):
if s[i]>m:m =s[i]
else:r+=m-s[i]
print(f"#{t} {r}")
| true |
de0138e7e331474d26b9cb06471d89d3395d97c4 | Python | wellington16/BSI-UFRPE | /Programas feitos/PYTHON/Praticando Python Basico/exercicio4.1 b.py | UTF-8 | 115 | 3.4375 | 3 | [] | no_license | a=int(input("Digite quantos anos do carro tem:"))
if a < 3:
print ("carro novo")
else:
print ("Carro Velho")
| true |
3250045f170c5446b2dd51d67f0a82eaabe678cc | Python | Mercy435/python--zero-to-mastery | /try.py | UTF-8 | 1,241 | 3.125 | 3 | [] | no_license | domain_names = {'Google': 'gmail', 'Yahoo': 'yahoo', 'MyFantasy': 'myfantasy',
'Microsoft': 'outlook'}
email = input('enter a valid email address: ')
# d = email[email.index('@') + 1:]
# print(d)
a = email.split('@')[1]
# print(a) # this splits the email in two, the first half is index 0 and the other is index 1
b = a.split('.')[0]
# print(b)
# if b == domain_names.value():
# key = domain_names[b]
# print(key)
# 7 email slicer
domain_names = ['Google', 'MyFantasy', 'Microsoft', 'Yahoo']
email = input('enter a valid email address: ')
split_email = email.split('@')[1]
name = email.split('.')[0]
split_domain_name = split_email.split('.')[0]
if split_domain_name == 'gmail':
print(f"Hey {name}, I see your email is registered with {domain_names[0]}. That's cool!.")
elif split_domain_name == 'myfantasy':
print(f"Hey {name}, looks like you've got your own custom setup at {domain_names[1]}. Impressive!")
elif split_domain_name == 'outlook':
print(f"Hey {name}, I see your email is registered with {domain_names[2]}. That's cool!.")
else:
print(f"Hey {name}, looks like you've got your own custom setup at {domain_names[-1]}. Impressive!")
import re
a = re.findall('[\w-]+@[\w-]+', email)
# print(a)
| true |
ffa86daa5bc06a6f3e4ee08a482968f0a161c995 | Python | andrewztan/foobar | /string_cleaning.py | UTF-8 | 3,143 | 4.4375 | 4 | [] | no_license | """
String cleaning
===============
Your spy, Beta Rabbit, has managed to infiltrate a lab of mad scientists who are turning rabbits into zombies. He sends a text transmission to you, but it is intercepted by a pirate, who jumbles the message by repeatedly inserting the same word into the text some number of times. At each step, he might have inserted the word anywhere, including at the beginning or end, or even into a copy of the word he inserted in a previous step. By offering the pirate a dubloon, you get him to tell you what that word was. A few bottles of rum later, he also tells you that the original text was the shortest possible string formed by repeated removals of that word, and that the text was actually the lexicographically earliest string from all the possible shortest candidates. Using this information, can you work out what message your spy originally sent?
For example, if the final chunk of text was "lolol," and the inserted word was "lol," the shortest possible strings are "ol" (remove "lol" from the beginning) and "lo" (remove "lol" from the end). The original text therefore must have been "lo," the lexicographically earliest string.
Write a function called answer(chunk, word) that returns the shortest, lexicographically earliest string that can be formed by removing occurrences of word from chunk. Keep in mind that the occurrences may be nested, and that removing one occurrence might result in another. For example, removing "ab" from "aabb" results in another "ab" that was not originally present. Also keep in mind that your spy's original message might have been an empty string.
chunk and word will only consist of lowercase letters [a-z].
chunk will have no more than 20 characters.
word will have at least one character, and no more than the number of characters in chunk.
Test cases
==========
Inputs:
(string) chunk = "lololololo"
(string) word = "lol"
Output:
(string) "looo"
Inputs:
(string) chunk = "goodgooogoogfogoood"
(string) word = "goo"
Output:
(string) "dogfood"
"""
def answer(chunk, word):
possible = []
for i in range(len(chunk) - len(word)):
text = remove_word(chunk, word, i)
if text not in possible and text != chunk:
possible.append(text)
return sorted(possible)[0]
def remove_word(chunk, word, start):
"""
Remove first occurence of word beginning from index start.
Then remove all remaining occurences.
"""
if word not in chunk[start:]:
return chunk
l = len(word)
# remove first occurence beginning from index start
index = chunk.find(word, start)
chunk = chunk[:index] + chunk[index + l:]
# remove remaining occurences
while word in chunk:
chunk = chunk.replace(word, '')
return chunk
def test():
chunk = "lololololo"
word = "lol"
assert "looo" == answer(chunk, word)
chunk = "goodgooogoogfogoood"
word = "goo"
assert "dogfood" == answer(chunk, word)
chunk = "aabb"
word = "ab"
assert "" == answer(chunk, word)
chunk = "lolol"
word = "lol"
assert "lo" == answer(chunk, word)
test()
| true |
a027a3b09d381ba29f54c94bc4291a1d2f42bd24 | Python | DierSolGuy/Python-Programs | /puja.py | UTF-8 | 204 | 3.4375 | 3 | [] | no_license | # S=(x/1)+(x/4)+(x/7)...n terms
import math
n=int(input("Enter the limit: "))
x=int(input("Enter the value of numerator: "))
sum=0
k=1
for i in range(1,n+1):
sum=sum+(x/k)
k+=3
print(sum) | true |
bad4e975b3fc893bea41ab614dc569b05124cc83 | Python | spedl/uw_python | /week07_assignment/wsgi_simple_server.py | UTF-8 | 749 | 3.03125 | 3 | [] | no_license | """
Simple WSGI application runner, including its own WSGI server
Usage: python simple_wsgi_server.py <application> <port>
Example: python simple_wsgi_server.py test.wsgi 8080
Default application is wsgi_test, default port is 8000
The application module can be named anything, but the
application callable it provides MUST be named 'application'
"""
import sys
from wsgiref.simple_server import make_server
appname = 'wsgi_test'
port = 8000
nargs = len(sys.argv)
if nargs > 1:
appname = sys.argv[1]
if nargs > 2:
port = int(sys.argv[2])
app = __import__(appname)
httpd = make_server('', port, app.application)
print "Running %s on port %s ..." % (appname, port)
# Respond to requests until process is killed
httpd.serve_forever()
| true |
02da3811eafb22ab042b28dfe12c160bb1427a30 | Python | prathamesh2901/Flask_Corona_App_Write | /models/state.py | UTF-8 | 858 | 2.828125 | 3 | [] | no_license | from db import db
class StateModel(db.Model):
__tablename__= 'states'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
cases = db.Column(db.Integer)
deaths = db.Column(db.Integer)
recoveries = db.Column(db.Integer)
def __init__(self, name, cases, deaths, recoveries):
self.name = name
self.cases = cases
self.deaths = deaths
self.recoveries = recoveries
def json(self):
return {'name': self.name, 'cases': self.cases, 'deaths': self.deaths, 'recoveries': self.recoveries}
@classmethod
def find_by_state(cls, name):
return cls.query.filter_by(name=name).first()
def save_to_db(self):
db.session.add(self)
db.session.commit()
def delete_from_db(self):
db.session.delete(self)
db.session.commit()
| true |
ab9d5bc6d545afd0fba7b14765e9b4beca67f0b6 | Python | gbrlas/NENR | /NN/input_processing/data_processing.py | UTF-8 | 1,347 | 2.75 | 3 | [] | no_license | import os
import numpy as np
from input_processing import data_transformation
symbols = ['alpha', 'beta', 'gamma', 'delta', 'epsilon']
data_path = os.path.abspath(__file__ + '/../../data')
def get_symbol(i):
return symbols[i]
def load_data():
X = 0
y = 0
for i, symbol in enumerate(symbols):
yi = np.zeros(len(symbols))
yi[i] = 1
file = data_path + '/' + symbol + '.txt'
open(file, 'a+')
xi = np.genfromtxt(file)
yi = np.array([yi for i in range(len(xi))])
if i == 0:
X = xi
y = yi
else:
X = np.vstack((X, xi))
y = np.vstack((y, yi))
return X, y
def save_data(x, symbol, n_features):
if len(x) < n_features:
return False
x = data_transformation.process_points(x, n_features)
file = data_path + '/' + symbol + '.txt'
open(file, 'a+')
data = np.genfromtxt(file)
if len(data) == 0:
data = x
else:
data = np.vstack((data, x))
file = data_path + '/' + symbol + '.txt'
f = open(file, 'a+')
np.savetxt(file, data, fmt='%.6f')
f.flush()
return True
def delete_data():
try:
for symbol in symbols:
file = data_path + '/' + symbol + '.txt'
os.remove(file)
except FileNotFoundError:
return
| true |
8d3d56548bfb1733fc91d443e105310c300bc9a9 | Python | estraviz/codewars | /8_kyu/Even or Odd/test_even_or_odd.py | UTF-8 | 402 | 2.703125 | 3 | [] | no_license | from even_or_odd import even_or_odd
def test_even_or_odd():
assert even_or_odd(2) == "Even"
assert even_or_odd(1) == "Odd"
assert even_or_odd(0) == "Even"
assert even_or_odd(1545452) == "Even"
assert even_or_odd(7) == "Odd"
assert even_or_odd(78) == "Even"
assert even_or_odd(17) == "Odd"
assert even_or_odd(74156741) == "Odd"
assert even_or_odd(100000) == "Even"
| true |
2f6d6a4e13ec9671669e7361b5d0e7feb5867713 | Python | risoyo/CodingInterviews | /排序/快排.py | UTF-8 | 626 | 3.078125 | 3 | [] | no_license | #coding=utf-8
def quick_sort(ary):
return qsort(ary, 0, len(ary)-1)
def qsort(ary, left, right):
mark = ary[left]
lp = left
rp = right
if lp >= rp:
return ary
while lp < rp:
while ary[rp] >= mark and lp < rp:
rp = rp - 1
while ary[lp] <= mark and lp < rp:
lp = lp + 1
ary[lp], ary[rp] = ary[rp], ary[lp]
ary[left], ary[lp] = ary[lp], ary[left]
qsort(ary, left, lp-1)
qsort(ary, lp+1, right)
return ary
if __name__ == '__main__':
num = [3, 1, 5, 7, 2, 4, 9, 6]
num = quick_sort(num)
for i in num:
print i,
| true |
0ad71d874c7819da9e3af0f27be4fde702e751fa | Python | Nandinishra/nanoPython | /Exercise5.py | UTF-8 | 3,374 | 3.5 | 4 | [] | no_license | # Create a food log file for each client
# Create an exercise log file for each client.
# Ask the user whether they want to log or retrieve client data.
# Write a function that takes the user input of the client's name.
# After the client's name is entered, it will display a message as "What you want to log- Diet or Exercise".
# Use function def getdate():
# import datetime
# return datetime.datetime.now()
# The purpose of this function is to give time with every record of food or exercise added in the file.
# Write a function to retrieve exercise or food file records for any client.
def func1(n1,d1):
if d1==1:
if n1==1:
print("Diet for Ram, please enter here:")
dt1=input()
with open("Ram_Food.txt","a") as var1:
var1.write("At "+str(getdate())+": "+ dt1)
elif n1 == 2:
print("Diet for Shyam, please enter here:\n")
dt1 = input()
with open("Shyam_Food.txt", "a") as var1:
var1.write("At "+ str(getdate())+ ": "+ dt1)
elif n1 == 3:
print("Diet for Radha, please enter here:\n")
dt1 = input()
with open("Radha_Food.txt", "a") as var1:
var1.write("At "+ str(getdate())+ ": "+ dt1)
elif de1==2:
if n1 == 1:
print("Workout for Ram, please enter here:\n")
dt2 = input()
with open("Ram_Workout.txt", "a") as var1:
var1.write("At "+ str(getdate())+ ": "+ dt2)
elif n1 == 2:
print("Workout for Shyam, please enter here:\n")
dt2 = input()
with open("Shyam_Workout.txt", "a") as var1:
var1.write("At "+ str(getdate())+ ": "+ dt2)
elif n1 == 3:
print("Workout for Radha, please enter here:\n")
dt2 = input()
with open("Radha_workout.txt", "a") as var1:
var1.write("At "+ str(getdate())+ ": "+ dt2)
def func2(n2,de2):
if de2==1:
if n2==1:
with open("Ram_Food.txt") as var1:
for i in var1:
print(i)
elif n2==2:
with open("Shyam_Food.txt") as var1:
for i in var1:
print(i)
elif n2 == 3:
with open("Radha_Food.txt") as var1:
for i in var1:
print(i)
elif de2==2:
if n2 == 1:
with open("Ram_Workout.txt") as var1:
for i in var1:
print(i)
elif n2 == 2:
with open("Shyam_Workout.txt") as var1:
for i in var1:
print(i)
elif n2 == 3:
with open("Radha_workout.txt") as var1:
for i in var1:
print(i)
def getdate():
import datetime
return datetime.datetime.now()
print("Select Option: \n0 for logging \n1 for Retrieving")
log1=int(input())
if log1==0:
print("Please choose the client \n1. Ram \n2. Shyam \n3. Radha")
nam1=int(input())
print("Select the option: \n1. Diet \n2. Exercise")
op1=int(input())
func1(nam1, op1)
else:
print("Please choose the client \n1. Ram \n2. Shyam \n3. Radha")
pname = int(input())
print("Select the option: \n1. Diet \n2. Exercise")
op1 = int(input())
func2(pname, op1)
| true |
95816e3bead92f89c7ae25ecd0ccdd5edcf36710 | Python | Siriapps/hackerrankPython | /re.start&re.end.py | UTF-8 | 350 | 3.203125 | 3 | [] | no_license | #https://www.hackerrank.com/challenges/re-start-re-end/problem
import re
s = input()
k = input()
index = 0
if re.search(k,s):
while len(k) < len(s):
m = re.search(k,s[index:])
if m!= None:
print((index+m.start(), index+m.end()-1))
else:
break
index += m.start()+1
else:
print((-1, -1))
| true |
c66f9ef75542b903335ce6cc165faad6b5a81218 | Python | RyanLiu6/ML-Intro | /Class_3/utils.py | UTF-8 | 863 | 2.546875 | 3 | [] | no_license | import os
import cv2
thresh = 150
ABSPATH = os.path.dirname(os.path.realpath(__file__))
class pyImage:
def __init__(self, imageName):
self.imageName = imageName
self.imageMat = cv2.imread(imageName, cv2.IMREAD_UNCHANGED)
def cleanImage(image):
# Convert image to Grayscale
grayScale = cv2.cvtColor(image.imageMat, cv2.COLOR_RGB2GRAY)
#absPath = os.path.join(os.path.dirname(os.path.realpath(__file__)), MOD)
cv2.imwrite(os.path.join(ABSPATH, "grayscale_" + image.imageName), grayScale)
# Apply threshold to get true Binary represenation of image
ret, grayScale = cv2.threshold(grayScale, thresh, 255, cv2.THRESH_BINARY)
# Denoise image
grayScale = cv2.fastNlMeansDenoising(grayScale, 10, 10, 7, 21)
cv2.imwrite(os.path.join(ABSPATH, "cleaned_" + image.imageName), grayScale)
return grayScale
| true |
b6a9e2fe79492a0efdcd95eed673d8e05a14a15d | Python | qorjiwon/LevelUp-Algorithm | /Easy/Baek_1085.py | UTF-8 | 348 | 3.09375 | 3 | [] | no_license | """
@ Baek 1085 직사각형에서 탈출
@ Prob. https://www.acmicpc.net/problem/1085
Ref.
Ref Prob.
@ Algo: 구현(수학)
@ Start day: 20. 01. 06
@ End day: 20. 01. 06
"""
curX, curY, W, H = map(int, input().split())
step = min(curX, W-curX)
step = min(step, min(curY, H-curY))
print(step)
"""
6 2 10 3
>
1
""" | true |
bd321a8c327c62fd0a1a8713cf1c3003af6c7be8 | Python | Dtomazzi/CS50 | /Mario in Python/mario.py | UTF-8 | 503 | 3.65625 | 4 | [] | no_license | from cs50 import get_int
def main():
height=get_height("What is the height?:")
space=height-1
hash=1
for x in range(height):
spaces(space)
hashes(hash)
space=space - 1
hash=hash + 1
def get_height(height):
while True:
n = get_int(height)
if n > 0 and n < 9:
break
return n
def spaces(y):
for y in range(y):
print(" ", end="")
def hashes(z):
for z in range(z):
print("#", end="")
print()
if __name__ == "__main__":
main() | true |
0f1a25a241447aa6981ec1755bca396792083317 | Python | smolynets/class | /jj.py | UTF-8 | 712 | 4.28125 | 4 | [] | no_license | # -*- coding: utf-8 -*-
# функція меню
def menu(list, question):
for entry in list:
print 1 + list.index(entry),
print ") " + entry
try:
return input(question) - 1
except NameError:
print 'Будь-ласка, введіть число від 1 до 8'
# визначаэмо наш список опцій для меню
options = ['A','B','C','D','E','F','H','I']
# викликаємо нашу функцію
answer = menu(options, 'Яка ваша улюблена літера? ')
try:
print 'Ваша відповідь ' + (options[answer])
except:
print 'Неправильна відповідь. Спробуйте ще раз.'
| true |
5f0633dce715f34facb91246d2b2c1b35ccf97fe | Python | kobelzy/LeetCode | /python/matplotlib/plot.py | UTF-8 | 304 | 3.296875 | 3 | [] | no_license | import numpy as np
import matplotlib.pyplot as plt
#线性图
fig,zx=plt.subplots()
x=np.linspace(-1,10,20)
y1=100*x +10
y2=2**x
plt.plot(x,y1,'r+',color='r',linewidth=1.0,linestyle='-',label='line1')
plt.plot(x,y2,'bo',color="b",linewidth=1.0,linestyle='--',label="line2")
plt.xlim(-2,11)
plt.show() | true |
17190f8e048e19465ad93a002842cd58e0f26a65 | Python | AMaoYouDianFang/learnpython | /mofanpython/01PrintDemo.py | UTF-8 | 301 | 3.859375 | 4 | [
"Apache-2.0"
] | permissive | print('a')
print("hello" + "world")
print("hello" + str(4))
print(int("5") + 4)
print(float("3.2") + 7)
print("the c is ", 5)
price = 1000
count = 10
print("price ", price, " count is", count)
name = input("Enter you name:")
print("hello", name)
tt = True
if tt and False:
print("Impossible") | true |
e3833926e0825526f30943ce5b72c90629aef4c9 | Python | ZinoKader/X-Pilot-AI | /attacking/attacker.py | UTF-8 | 2,729 | 3 | 3 | [] | no_license | import helpfunctions
import math
class Attacker:
def __init__(self, ai):
self.ai = ai
self.ai.setTurnSpeed(64)
def target_alive(self, target):
pass
def attack_player(self, target = None, target_id = None):
# if server id and ship id have not been matched yet
if not target_id:
for i in range(self.ai.playerCountServer()):
for y in range(self.ai.shipCountScreen()):
player_id = self.ai.playerId(i)
ship_id = self.ai.shipId(y)
if player_id == ship_id and self.ai.playerName(i) == target:
target_id = y
px, py = helpfunctions.get_wrapped_coordinates(self.ai, target_id)
px, py = helpfunctions.get_wrapped_coordinates(self.ai, target_id)
vx, vy = (self.ai.shipVelX(target_id) - self.ai.selfVelX(), self.ai.shipVelY(target_id) - self.ai.selfVelY())
bulletspeedx = (30 * math.cos(self.ai.selfHeadingRad())) + self.ai.selfSpeed()
bulletspeedy = (30 * math.sin(self.ai.selfHeadingRad())) + self.ai.selfSpeed()
bulletspeed = ( (bulletspeedx ** 2) + (bulletspeedy ** 2) ) ** (1 / 2)
time_of_impact = helpfunctions.time_of_impact(px, py, vx, vy, bulletspeed)
targetX = px + (vx * time_of_impact)
targetY = py + (vy * time_of_impact)
aim_direction = math.atan2(targetY, targetX)
if self.ai.shipCountScreen() > 0:
self.ai.turnToRad(aim_direction)
self.ai.fireShot()
def attack_nearest(self):
selfX = ( self.ai.selfRadarX() / self.ai.radarWidth() ) * self.ai.mapWidthPixels()
selfY = ( self.ai.selfRadarY() / self.ai.radarHeight() ) * self.ai.mapHeightPixels()
# match server id with ship id and put closest targets in a dictionary
ship_distances = {}
for i in range(self.ai.playerCountServer()):
for y in range(self.ai.shipCountScreen()):
player_id = self.ai.playerId(i)
ship_id = self.ai.shipId(y)
if player_id == ship_id and player_id != self.ai.selfId():
px, py = helpfunctions.get_wrapped_coordinates(self.ai, y)
rel_distance = ( ( px ** 2) + ( py ** 2) ) ** ( 1/2 )
ship_distances[rel_distance] = y
break
if not ship_distances:
print("No targets nearby.")
return
print("***")
print(ship_distances)
print("***")
# pick out the closest target from the dictionary
closest_target_id = ship_distances.get(min(ship_distances))
self.attack_player(None, closest_target_id)
| true |
7d16076363c67aff3b085007bf6acdeeb1d45afc | Python | aratnamirasugab/cp-interview-things | /code/Split a String in Balanced Strings.py | UTF-8 | 805 | 3.390625 | 3 | [] | no_license | class Solution:
def balancedStringSplit(self, s: str) -> int:
res = 0
if s[0] == 'L':
s[::-1]
left, right = [],[]
i = 0
while i < len(s):
if len(left) == len(right) and len(left) != 0:
res += 1
left.clear()
right.clear()
else:
if s[i] == 'L':left.append('L')
else: right.append('R')
if len(left) == len(right) and len(left) != 0:
res += 1
left.clear()
right.clear()
i += 1
return res
if __name__ == '__main__' :
s = "LLLLRRRR"
sol = Solution().balancedStringSplit(s)
print(sol)
| true |
423d3efda96c8185694a2b4738b31e5db0418157 | Python | kosazna/atsurvey | /converter/formater.py | UTF-8 | 1,968 | 2.703125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
from atsurvey.primitives import *
class TraverseFormatter:
def __init__(self, data: Any):
self.df = load_data(data)
self.angles = None
self.dists = None
self._traverse = None
@staticmethod
def join_stops_for_angle(midenismos, stasi, metrisi) -> str:
return '-'.join([midenismos, stasi, metrisi])
@staticmethod
def join_stops_for_dist(station, fs) -> str:
return '-'.join(sorted([station, fs]))
def get_data(self) -> pd.DataFrame:
return self._traverse.copy()
def tranform(self):
self.df.fillna('<NA>', inplace=True)
s_dist = SlopeDistances(self.df['slope_dist'])
h_dist = s_dist.to_horizontal(self.df['v_angle'])
dz_temp = s_dist.to_delta(self.df['v_angle'],
self.df['station_h'],
self.df['target_h'])
self.df['angle'] = self.df.apply(
lambda x: self.join_stops_for_angle(x.bs, x.station, x.fs),
axis=1)
self.df['dist'] = self.df.apply(
lambda x: self.join_stops_for_dist(x.station, x.fs),
axis=1)
self.angles = self.df['angle'].values
self.dists = self.df['dist'].values
self.df['stop_dist'] = h_dist.values
miki = self.df.groupby('dist')['stop_dist'].mean()
self.df['h_dist'] = self.df['dist'].map(miki)
self.df['stop_dh'] = dz_temp.values
self.df['abs_dh'] = abs(self.df['stop_dh'])
dz = self.df.groupby('dist')['abs_dh'].mean()
self.df['abs_avg_dh'] = self.df['dist'].map(dz)
self.df['dz_temp'] = mean_dh_signed(self.df['stop_dh'],
self.df['abs_avg_dh'])
self._traverse = self.df.loc[
self.df['h_angle'] != 0, ['mid', 'bs', 'station', 'fs',
'h_angle', 'h_dist', 'dz_temp', ]]
return self
| true |
be03bc12f26bd9b389bd6f4dc628a87ce03488c9 | Python | trimcrae/Question-Answering-Deep-NLP | /code/BiLSTM.py | UTF-8 | 2,137 | 3.515625 | 4 | [] | no_license | from __future__ import division, print_function, absolute_import
import tflearn
from tflearn.data_utils import to_categorical, pad_sequences
#from tflearn.datasets import imdb
from tflearn.layers.core import input_data, dropout, fully_connected
from tflearn.layers.embedding_ops import embedding
from tflearn.layers.recurrent import bidirectional_rnn, BasicLSTMCell
from tflearn.layers.estimator import regression
# IMDB Dataset loading
#train, test, _ = imdb.load_data(path='imdb.pkl', n_words=10000,
# valid_portion=0.1)
trainX, trainY = train
testX, testY = test
# Data preprocessing
# Sequence padding
trainX = pad_sequences(trainX, maxlen=200, value=0.)
testX = pad_sequences(testX, maxlen=200, value=0.)
# Converting labels to binary vectors
trainY = to_categorical(trainY, nb_classes=2)
testY = to_categorical(testY, nb_classes=2)
# Network building
net = input_data(shape=[None, 200]) #same shape as the max length
net = embedding(net, input_dim=20000, output_dim=128) #creates embedding matrix. Not sure if I need this for project 4
net = bidirectional_rnn(net, BasicLSTMCell(128), BasicLSTMCell(128)) #has two LSTMs with 128 units go in forward and backward directions.
net = dropout(net, 0.5) #dropout with keep probability of 0.5. All are finalized
net = fully_connected(net, 2, activation='softmax') #makes softmax probabilities over 2 categories, true and false
net = regression(net, optimizer='adam', loss='categorical_crossentropy') #runs adam optimizer on net minimizing catagorical cross entropy loss
# Training
model = tflearn.DNN(net, clip_gradients=5, tensorboard_verbose=1) # clips gradients at 5. Prints out loss, accuracy and gradients. All are finalized
model.fit(trainX, trainY, n_epoch=10, validation_set=0.05, show_metric=True, batch_size=32) #trains on train data for 10 epochs reserving 5% for dev
#t showing accuracy at every stap with batch size of 64.
#show_metric and batch_size are finalized. Not sure about incorporating validation set
#or # of epochs as a time concern. | true |
14d73a25e49d21cc00cbd0c2d67ca1e396b42fd5 | Python | brucehzhai/Python-JiangHong | /源码/Python课后上机实践源代码/ch5-系列数据类型/P5-prg-2-List1Distinct.py | UTF-8 | 177 | 3.359375 | 3 | [] | no_license | ##list1=[1,2,3,2,3,4]
##set1=set(list1)
##list1=list(set1)
list1=[1,2,3,2,3,4]
list2=[]
for i in list1:
if i not in list2:
list2.append(i)
print(list2)
| true |
aac91293e3e663a94d39a585f34249992a190ccc | Python | hpcn-uam/ccore | /tests/test_cparser.py | UTF-8 | 18,611 | 3.03125 | 3 | [
"Apache-2.0"
] | permissive | # -*- coding: utf-8 -*-
import pytest
import cparser
import pandas as pd
import pytz
from utils import ip2int
class Test_RecordList(object):
def test_new(self):
parser = cparser.RecordList()
assert parser is not None
def test_read___gets_all_records(self, macconvs_file, sample_values):
parser = cparser.RecordList()
params = {
'srcMAC': (0, 'string'),
'dstMAC': (1, 'string'),
'frames': (2, 'int'),
'bytes': (3, 'int'),
'ts_start': (4, 'double'),
'ts_end': (5, 'double'),
}
parser.read(macconvs_file.strpath, params)
assert len(parser) == sample_values['num_records']
def test_read__records_are_correct(self, macconvs_file, sample_values):
parser = cparser.RecordList()
params = {
'srcMAC': (0, 'string'),
'dstMAC': (1, 'string'),
'frames': (2, 'int'),
'bytes': (3, 'int'),
'ts_start': (4, 'double'),
'ts_end': (5, 'double'),
}
parser.read(macconvs_file.strpath, params)
record = parser[0]
assert record.srcMAC == sample_values['mac1']
assert record.dstMAC == sample_values['mac2']
assert record.frames == sample_values['frames']
assert record.bytes == sample_values['bytes']
assert record.ts_start == sample_values['ts_start_epoch']
assert record.ts_end == sample_values['ts_end_epoch']
def test_iter__can_iterate(self, macconvs_file, sample_values):
parser = cparser.RecordList()
params = {
'srcMAC': (0, 'string'),
'dstMAC': (1, 'string'),
'frames': (2, 'int'),
'bytes': (3, 'int'),
'ts_start': (4, 'double'),
'ts_end': (5, 'double'),
}
parser.read(macconvs_file.strpath, params)
num_iterated = 0
for record in parser:
assert record.srcMAC == sample_values['mac1']
assert record.dstMAC == sample_values['mac2']
assert record.frames == sample_values['frames']
assert record.bytes == sample_values['bytes']
assert record.ts_start == sample_values['ts_start_epoch']
assert record.ts_end == sample_values['ts_end_epoch']
num_iterated += 1
assert num_iterated == sample_values['num_records']
def test_read__can_read_IPs(self, ipconvs_file, sample_values):
parser = cparser.RecordList()
params = {
'srcIP': (0, 'ip')
}
parser.read(ipconvs_file.strpath, params)
assert len(parser) > 0
assert parser[0].srcIP == ip2int(sample_values['ip1'])
def test_read__can_read_pandas_Timestamps(self, macconvs_file, sample_values):
parser = cparser.RecordList(sample_values['tz'])
params = {
'ts_start': (4, 'tstamp'),
}
parser.read(macconvs_file.strpath, params)
assert len(parser) > 0
tstamp = parser[0].ts_start
assert isinstance(tstamp, pd.Timestamp)
assert tstamp == sample_values['ts_start']
def test_read__can_read_pandas_Timestamps__timezone_is_correct(self, macconvs_file, sample_values):
parser = cparser.RecordList('Canada/East-Saskatchewan') # Because why not
params = {
'ts_start': (4, 'tstamp'),
}
parser.read(macconvs_file.strpath, params)
assert len(parser) > 0
tstamp = parser[0].ts_start
assert isinstance(tstamp, pd.Timestamp)
assert tstamp == sample_values['ts_start']
assert tstamp.tz.zone == 'Canada/East-Saskatchewan'
def test_read__negative_timestamps__ignored(self, sessiondir):
fout = sessiondir.join('negtest.dat')
fout.write("-1\n")
params = {
'ts_start': (0, 'tstamp'),
}
parser = cparser.RecordList()
parser.read(fout.strpath, params)
assert len(parser) > 0
tstamp = parser[0].ts_start
assert isinstance(tstamp, pd.Timestamp)
assert tstamp.value == 0
def test_read__negative_timestamps_fallback_available__falls_back(self, sessiondir):
fout = sessiondir.join('fallbacktest.dat')
fout.write("232131 -1\n")
params = {
'ts_start': (0, 'tstamp'),
'other_ts': (1, 'tstamp'),
}
parser = cparser.RecordList()
parser.read(fout.strpath, params)
assert len(parser) > 0
tstamp = parser[0].ts_start
assert isinstance(tstamp, pd.Timestamp)
assert tstamp.value == 232131000000000
tstamp = parser[0].other_ts
assert isinstance(tstamp, pd.Timestamp)
assert tstamp.value == 232131000000000
def test_read__stores_max_min_tstamps(self, macconvs_file, sample_values):
parser = cparser.RecordList(sample_values['tz'])
params = {
'srcMAC': (0, 'string'),
'dstMAC': (1, 'string'),
'frames': (2, 'int'),
'bytes': (3, 'int'),
'ts_start': (4, 'tstamp'),
'ts_end': (5, 'tstamp'),
}
parser.read(macconvs_file.strpath, params)
assert len(parser) == sample_values['num_records']
assert parser.min_timestamp == sample_values['ts_start']
assert parser.max_timestamp == sample_values['ts_end']
def test_read__no_stamps_in_file__min_max_tstamps_are_valid(self, macconvs_file, sample_values):
parser = cparser.RecordList()
params = {
'srcMAC': (0, 'string'),
'dstMAC': (1, 'string'),
'frames': (2, 'int'),
'bytes': (3, 'int'),
'ts_start': (4, 'double'),
'ts_end': (5, 'double'),
}
parser.read(macconvs_file.strpath, params)
assert len(parser) == sample_values['num_records']
assert parser.min_timestamp == pd.Timestamp(0)
assert parser.max_timestamp == pd.Timestamp(0)
def test_read__negative_zero_timestamps__ignored_min_max(self, sessiondir):
fout = sessiondir.join('negtest.dat')
lines = ["-1", "0", "200"]
fout.write("\n".join(lines))
params = {
'ts_start': (0, 'tstamp'),
}
parser = cparser.RecordList()
parser.read(fout.strpath, params)
assert len(parser) == 3
assert parser.min_timestamp == pd.Timestamp(200, unit = 's')
assert parser.max_timestamp == pd.Timestamp(200, unit = 's')
def test_read__bool_as_c_integers__parsed_as_bools(self, sessiondir):
fout = sessiondir.join('booltest.dat')
lines = ["-1", "0", "1"]
fout.write("\n".join(lines))
params = {
'test': (0, 'bool'),
}
parser = cparser.RecordList()
parser.read(fout.strpath, params)
assert len(parser) == 3
assert isinstance(parser[0].test, bool)
assert parser[0].test is True
assert parser[1].test is False
assert parser[2].test is True
def test_read__big_number__does_not_overflow(self, sessiondir):
fout = sessiondir.join('booltest.dat')
num = 21474836470
lines = [str(num)]
fout.write("\n".join(lines))
params = {
'test': (0, 'long'),
}
parser = cparser.RecordList()
parser.read(fout.strpath, params)
assert len(parser) == 1
assert parser[0].test == num
def test_read__shorts__can_read_shorts(self, sessiondir):
fout = sessiondir.join('booltest.dat')
num_1 = 80
num_2 = 1238791
lines = [str(num_1), str(num_2)]
fout.write("\n".join(lines))
params = {
'test': (0, 'short'),
}
parser = cparser.RecordList()
parser.read(fout.strpath, params)
assert len(parser) == 2
assert parser[0].test == num_1
assert parser[1].test == num_2 % 65536
def test_read__can_build_values(self, macconvs_file, sample_values):
parser = cparser.RecordList()
params = {
'srcMAC': (0, 'string'),
'dstMAC': (1, 'string'),
'frames': (2, 'int'),
'bytes': (3, 'int'),
'doubles': (3, 'int', lambda x: 2 * int(x)),
'ts_start': (4, 'double'),
'ts_end': (5, 'double'),
}
parser.read(macconvs_file.strpath, params)
assert len(parser) == sample_values['num_records']
record = parser[0]
assert record.doubles == 2 * sample_values['bytes']
def test_read__string_end_of_line__newline_discarded(self, sessiondir):
fout = sessiondir.join('booltest.dat')
lines = ["test", "test"]
fout.write("\n".join(lines))
params = {
'test': (0, 'string'),
}
parser = cparser.RecordList()
parser.read(fout.strpath, params)
assert len(parser) == 2
assert parser[0].test == "test"
def test_read__different_separator__reads_correct_values(self, sessiondir):
fout = sessiondir.join('separatortest.dat')
num_1 = 80
num_2 = 90
line = "{0}|{1}".format(num_1, num_2)
lines = [line] * 3
fout.write("\n".join(lines))
params = {
'num1': (0, 'short'),
'num2': (1, 'short')
}
parser = cparser.RecordList(pytz.timezone('UTC'), "|")
parser.read(fout.strpath, params)
assert len(parser) == len(lines)
for record in parser:
assert record.num1 == num_1
assert record.num2 == num_2
def test_tstamp_range__only_iterates_in_range(self, sessiondir):
fout = sessiondir.join('rangetest.dat')
lines = [str(n) for n in range(1000)]
fout.write("\n".join(lines))
params = {
'test': (0, 'tstamp')
}
parser = cparser.RecordList()
parser.read(fout.strpath, params)
assert len(parser) == 1000
rng = parser.tstamp_range(100*10**9, 400*10**9, ['test'])
count = 0
for r in rng:
count += 1
assert 100 <= r.test.value // 10 ** 9 <= 400
assert count == 400 - 100 + 1
def test_field_as_numpy__double__creates_a_numpy_array(self, macconvs_file, sample_values):
import numpy as np
parser = cparser.RecordList()
params = {
'srcMAC': (0, 'string'),
'dstMAC': (1, 'string'),
'frames': (2, 'int'),
'bytes': (3, 'int'),
'ts_start': (4, 'double'),
'ts_end': (5, 'double'),
}
parser.read(macconvs_file.strpath, params)
assert len(parser) == sample_values['num_records']
nparr = parser.field_as_numpy('ts_start')
assert isinstance(nparr, np.ndarray)
assert len(nparr) == len(parser)
for i in range(len(nparr)):
from_nparr = nparr[i]
from_parser = parser[i].ts_start
assert from_nparr == from_parser
def test_field_as_numpy__double__creates_a_numpy_array(self, macconvs_file, sample_values):
import numpy as np
parser = cparser.RecordList()
params = {
'srcMAC': (0, 'string'),
'dstMAC': (1, 'string'),
'frames': (2, 'int'),
'bytes': (3, 'int'),
'ts_start': (4, 'double'),
'ts_end': (5, 'double'),
}
parser.read(macconvs_file.strpath, params)
assert len(parser) == sample_values['num_records']
nparr = parser.field_as_numpy('frames')
assert isinstance(nparr, np.ndarray)
assert len(nparr) == len(parser)
for i in range(len(nparr)):
from_nparr = nparr[i]
from_parser = parser[i].frames
assert from_nparr == from_parser
def test_field_as_numpy__tstamp__creates_a_numpy_array(self, macconvs_file, sample_values):
import numpy as np
parser = cparser.RecordList()
params = {
'srcMAC': (0, 'string'),
'dstMAC': (1, 'string'),
'frames': (2, 'int'),
'bytes': (3, 'int'),
'ts_start': (4, 'tstamp'),
'ts_end': (5, 'double'),
}
parser.read(macconvs_file.strpath, params)
assert len(parser) == sample_values['num_records']
nparr = parser.field_as_numpy('ts_start')
assert isinstance(nparr, np.ndarray)
assert len(nparr) == len(parser)
for i in range(len(nparr)):
from_nparr = nparr[i]
from_parser = parser[i].ts_start
assert from_nparr == from_parser.to_datetime64()
def test_field_as_numpy__tstamp_defaut_value__creates_a_numpy_array(self, sessiondir):
import pandas as pd
import numpy as np
fout = sessiondir.join('deftstampvals.dat')
tstamps = [pd.Timestamp('2000-10-10'), pd.Timestamp('2000-10-11')]
tstamps_str = ["0", str(pd.Timestamp('2000-10-11').value // 10 ** 9)]
fout.write("\n".join(tstamps_str))
params = {
'test': (0, 'tstamp')
}
parser = cparser.RecordList()
parser.read(fout.strpath, params)
assert len(parser) == 2
nparr = parser.field_as_numpy('test', tstamps[0].value)
assert isinstance(nparr, np.ndarray)
assert len(nparr) == len(parser)
for i in range(len(parser)):
from_nparr = nparr[i]
expected = tstamps[i]
assert from_nparr == expected.to_datetime64()
def test_filter_fields__only_iterates_in_range(self, sessiondir):
fout = sessiondir.join('filter.dat')
lines = [str(n) + " " + str(n % 2) for n in range(1000)]
fout.write("\n".join(lines))
params = {
'test': (0, 'tstamp'),
'test2': (1, 'int')
}
parser = cparser.RecordList()
parser.read(fout.strpath, params)
assert len(parser) == 1000
rng = parser.filter_fields(1, ['test2'])
count = 0
for r in rng:
count += 1
assert r.test2 == 1
assert count == 1000 / 2
def test_tstamp_range_and_filter__only_iterates_in_range(self, sessiondir):
fout = sessiondir.join('combinediter.dat')
lines = [str(n) + " " + str(n % 2) for n in range(1000)]
fout.write("\n".join(lines))
params = {
'test': (0, 'tstamp'),
'test2': (1, 'int')
}
parser = cparser.RecordList()
parser.read(fout.strpath, params)
assert len(parser) == 1000
rng = parser.tstamp_range(100*10**9, 400*10**9, ['test']).filter_fields(1, ['test2'])
count = 0
for r in rng:
count += 1
assert 100 <= r.test.value // 10 ** 9 <= 400 and r.test2 == 1
assert count == (400 - 100 + 1) / 2
def test_field_as_numpy__after_tstamp_range_and_filter__correct_array(self, sessiondir):
import numpy as np
fout = sessiondir.join('fieldafterfilters.dat')
lines = [str(n) + " " + str(n % 2) for n in range(1000)]
fout.write("\n".join(lines))
params = {
'test': (0, 'tstamp'),
'test2': (1, 'int')
}
parser = cparser.RecordList()
parser.read(fout.strpath, params)
assert len(parser) == 1000
rng = parser.tstamp_range(100*10**9, 400*10**9, ['test']).filter_fields(1, ['test2'])
array = rng.field_as_numpy('test2')
assert isinstance(array, np.ndarray)
assert len(array) == (400 - 100 + 1) / 2
assert all(array == 1)
def test_filter_fields__multiple_iterators__separated_state(self, sessiondir):
fout = sessiondir.join('multipleiter.dat')
lines = [str(n) + " " + str(n % 2) for n in range(1000)]
fout.write("\n".join(lines))
params = {
'test': (0, 'tstamp'),
'test2': (1, 'int')
}
parser = cparser.RecordList()
parser.read(fout.strpath, params)
assert len(parser) == 1000
rng = parser.tstamp_range(100*10**9, 400*10**9, ['test'])
test1 = rng.filter_fields(1, ['test2'])
test0 = rng.filter_fields(0, ['test2'])
rng_count = 0
for r in rng:
rng_count += 1
assert rng_count == 400 - 100 + 1
test1_count = 0
for r in test1:
test1_count += 1
assert r.test2 == 1
assert test1_count == (400 - 100 + 1) / 2
test0_count = 0
for r in test0:
test0_count += 1
assert r.test2 == 0
assert test0_count == (400 - 100 + 1) / 2 + 1
def test_filter_fields__iterator_is_RecordListIter(self, sessiondir):
fout = sessiondir.join('instanceiter.dat')
lines = [str(n) + " " + str(n % 2) for n in range(1000)]
fout.write("\n".join(lines))
params = {
'test': (0, 'tstamp'),
'test2': (1, 'int')
}
parser = cparser.RecordList()
parser.read(fout.strpath, params)
assert isinstance(parser.filter_fields(1, ['test2']), cparser.RecordListIter)
assert isinstance(parser.tstamp_range(1*10**9, 2*10**9, ['test']), cparser.RecordListIter)
def test_filter_fields__is_filtering_field__true(self, sessiondir):
fout = sessiondir.join('field_bool.dat')
lines = [str(n) + " " + str(n % 2) for n in range(1000)]
fout.write("\n".join(lines))
params = {
'test': (0, 'tstamp'),
'test2': (1, 'int')
}
parser = cparser.RecordList()
parser.read(fout.strpath, params)
it = parser.filter_fields(1, ['test2'])
assert it.is_filtering_field
assert not it.is_filtering_range
def test_filter_fields__is_filtering_range__true(self, sessiondir):
fout = sessiondir.join('range_bool.dat')
lines = [str(n) + " " + str(n % 2) for n in range(1000)]
fout.write("\n".join(lines))
params = {
'test': (0, 'tstamp'),
'test2': (1, 'int')
}
parser = cparser.RecordList()
parser.read(fout.strpath, params)
it = parser.tstamp_range(1*10**9, 2*10**9, ['test'])
assert not it.is_filtering_field
assert it.is_filtering_range
def test_filter__supports_multiple_iterations(self, sessiondir):
fout = sessiondir.join('filter.dat')
lines = [str(n) + " " + str(n % 2) for n in range(1000)]
fout.write("\n".join(lines))
params = {
'test': (0, 'tstamp'),
'test2': (1, 'int')
}
parser = cparser.RecordList()
parser.read(fout.strpath, params)
assert len(parser) == 1000
rng = parser.filter_fields(1, ['test2'])
count = 0
for r in rng:
count += 1
assert r.test2 == 1
assert count == 1000 / 2
count = 0
for r in rng:
count += 1
assert r.test2 == 1
assert count == 1000 / 2
def test_read__empty_lines__ignored(self, sessiondir):
fout = sessiondir.join('negtest.dat')
lines = ["-1 0", "", "200 200"]
fout.write("\n".join(lines))
params = {
'a': (0, 'int'),
'b': (1, 'int'),
}
parser = cparser.RecordList()
parser.read(fout.strpath, params)
assert len(parser) == 2
def test_read__empty_lines__ignored(self, sessiondir):
fout = sessiondir.join('emptytest.dat')
lines = ["-1 0", "", "200 200"]
fout.write("\n".join(lines))
params = {
'a': (0, 'int'),
'b': (1, 'int'),
}
parser = cparser.RecordList()
parser.read(fout.strpath, params)
assert len(parser) == 2
def test_read__invalid_timestamp__does_not_crash(self, sessiondir):
fout = sessiondir.join('invformat.dat')
lines = ["asdsasd 0", "200 200"]
fout.write("\n".join(lines))
params = {
'a': (0, 'tstamp'),
'b': (1, 'string'),
}
parser = cparser.RecordList()
parser.read(fout.strpath, params)
assert len(parser) == 2
def test_read__invalid_ip__does_not_crash(self, sessiondir):
fout = sessiondir.join('invformat.dat')
lines = ["asdsasd 0", "200 200"]
fout.write("\n".join(lines))
params = {
'a': (0, 'ip'),
'b': (1, 'string'),
}
parser = cparser.RecordList()
parser.read(fout.strpath, params)
assert len(parser) == 2
def test_read__consecutive_spaces__ignored(self, sessiondir):
fout = sessiondir.join('invformat.dat')
lines = ["asdsasd 0", "200 300"]
fout.write("\n".join(lines))
params = {
'a': (0, 'string'),
'b': (1, 'string'),
}
parser = cparser.RecordList()
parser.read(fout.strpath, params)
assert len(parser) == 2
assert parser[0].a == "asdsasd"
assert parser[0].b == "0"
assert parser[1].a == "200"
assert parser[1].b == "300"
def test_read__consecutive_special_char_separator__not_ignored(self, sessiondir):
fout = sessiondir.join('invformat.dat')
lines = ["asdsasd||0", "200||300", "200|aaa|300"]
fout.write("\n".join(lines))
params = {
'a': (0, 'string'),
'b': (1, 'string'),
'c': (2, 'string'),
}
parser = cparser.RecordList(pytz.timezone('UTC'), "|")
parser.read(fout.strpath, params)
assert len(parser) == 3
assert parser[0].a == "asdsasd"
assert parser[0].b == ""
assert parser[0].c == "0"
assert parser[1].a == "200"
assert parser[1].b == ""
assert parser[1].c == "300"
assert parser[2].a == "200"
assert parser[2].b == "aaa"
assert parser[2].c == "300"
| true |
9af3183526d9758c620fa19fee751e945fd00686 | Python | haradahugo/cursoemvideopython | /ex083.py | UTF-8 | 456 | 3.90625 | 4 | [] | no_license | ## Validando expressões matemáticas
expr = str(input('Digite a expressão matemática: '))
pilha = []
for simb in expr:
if simb == '(':
pilha.append('(')
elif simb == ')':
if len(pilha) > 0:
pilha.pop() #Retira o último elemento da lista pilha
else:
pilha.append(')')
break
if len(pilha) == 0:
print('Sua expressão está válida!')
else:
print('Suas expressão está errada!') | true |
189568e2d63443bf19ccaf1c31dd93f13817b9ed | Python | Rusta12/projects_parsing_mieltn | /TSVTunload/tsvttool.py | UTF-8 | 9,516 | 2.859375 | 3 | [] | no_license | import os
import shutil
import time
from datetime import datetime
from itertools import islice
import zipfile
from dbfread import DBF
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
url = 'http://stat.customs.gov.ru/unload'
def init_driver(driver_path, url):
'''
Function that initializes the web-driver and set to TSVT unload page.
'''
driver = webdriver.Chrome(os.path.join(driver_path, 'chromedriver.exe'))
driver.get(url)
return driver
def time_filters():
'''
Function to let a user choose months to download.
Returns dictionary with character and numeric representation of time filter.
'''
months_dict = {
1: 'январь',
2: 'февраль',
3: 'март',
4: 'апрель',
5: 'май',
6: 'июнь',
7: 'июль',
8: 'август',
9: 'сентябрь',
10: 'октябрь',
11: 'ноябрь',
12: 'декабрь',
}
all_years = [
year for year in range(datetime.now().year - 3, datetime.now().year + 1)
]
allm_dict = {
str(month) + str(year):' '.join([months_dict[month], str(year), 'г.'])
for year in all_years
for month in months_dict
}
shortcut = int(input(
'''
Setting filters for time period.
Please, enter the corresponding number to choose one of the options:
1 - download the last available month only
2 - enter time interval manually
'''
))
if shortcut == 1:
if datetime.now().month > 2:
m = str(datetime.now().month - 2) + str(datetime.now().year)
return {m: allm_dict[m]}
m = str(12 + datetime.now().month - 2) + str(datetime.now().year - 1)
return {m: allm_dict[m]}
elif shortcut == 2:
period_input = input(
'''
Please, enter months or time interval needed in the following form:
M(M).YYYY, M(M).YYYY
or
M(M).YYYY-M(M).YYYY
'''
)
if '.' in period_input and len(period_input) in [6, 7]:
m = ''.join(period_input.split('.'))
return {m: allm_dict[m]}
elif ',' in period_input:
subset = [''.join(period.split('.')) for period in period_input.split(', ')]
return {m_short: m_long for m_short, m_long in allm_dict.items() if m_short in subset}
start, end = [''.join(period.split('.')) for period in period_input.split('-')]
return dict(
islice(
allm_dict.items(),
list(allm_dict.keys()).index(start),
list(allm_dict.keys()).index(end) + 1
)
)
return time_filters()
def download_stat(driver, month, downloads):
'''
Downloads the statistics from TSVT unload page using selenium webdriver.
Sends periods recieved from time_filters function as filters.
After unload renames an archive and moves it to the destination storage folder.
'''
level = driver.find_element_by_xpath('//div/input[@id="react-select-tnvedLevelsSelect-input"]')
level.send_keys('10 знаков')
level.send_keys(Keys.RETURN)
time.sleep(1)
period = driver.find_element_by_xpath('//div/input[@id="react-select-periodSelect-input"]')
period.send_keys(month)
period.send_keys(Keys.RETURN)
time.sleep(1)
while not os.path.exists(os.path.join(downloads, 'DATTSVT.dbf.zip')):
submit_button = driver.find_element_by_xpath('//button[@type="submit"]')
submit_button.click()
time.sleep(10)
remove_filters = driver.find_element_by_xpath(
'//button[@class="ButtonLink__buttonLink' + \
' ButtonLink__buttonLink_color_green' + \
' buttonLink_size_normal buttonLink_theme_default"]'
)
remove_filters.click()
def move_unzip_rename(month, downloads, dest_folder):
'''
Function to move zip archive to the destination folder after downloading.
Ten, unzips and renames it.
'''
file = os.path.join(downloads, 'DATTSVT.dbf.zip')
new_file = f'TSVTdata_{month}.zip'
shutil.move(
os.path.join(downloads, file),
os.path.join(dest_folder, file)
)
with zipfile.ZipFile(os.path.join(dest_folder, file), 'r') as zip_file:
zip_info = zip_file.getinfo('DATTSVT.dbf')
zip_info.filename = f'TSVTdata_{month}.dbf'
zip_file.extract(zip_info, path=dest_folder)
os.rename(
os.path.join(dest_folder, file),
os.path.join(dest_folder, new_file)
)
def dbf_to_csv(dest_folder):
'''
Converts dbf from zip archive to csv.
'''
file = [file for file in os.listdir(dest_folder) if file.endswith('dbf')][0]
new_file = '.'.join([file.split('.')[0], 'csv'])
data = [row for row in DBF(os.path.join(dest_folder, file), encoding='cp866')]
df = pd.DataFrame(data)
df.to_csv(os.path.join(dest_folder, new_file), index=False, encoding='utf-8')
to_remove = [file for file in os.listdir(dest_folder) if '.csv' not in file]
for file in to_remove:
os.remove(os.path.join(dest_folder, file))
return df
def prepare_stat(df, dest_folder):
'''
Converts dtypes, aggregates by Russia.
'''
for col in ['Stoim', 'Netto', 'Kol']:
df[col] = df[col].astype(str).str.replace(',', '.').astype(float)
df = (
df
.groupby(['period', 'napr', 'strana', 'tnved'])
.sum()
.loc[:, ['Stoim', 'Netto', 'Kol']]
.reset_index()
)
return df
def add_info_aggregate(df, dest_folder):
'''
Merges with country groups and branches.
Adds group subtotal by 2, 4 and 6 digits to main dataframe.
'''
country_groups = pd.read_excel('ФТС блоки стран.xlsx', keep_default_na=False)
branches = pd.read_excel('ФТС отрасли.xlsx')
df['tnved'] = df.tnved.astype(str)
df.loc[df.tnved.str.len() == 9, 'tnved'] = \
df.loc[df.tnved.str.len() == 9, 'tnved'].apply(lambda x: '0' + x)
df['tnved2'] = df.tnved.astype(str).apply(lambda x: x[:2])
df['tnved4'] = df.tnved.astype(str).apply(lambda x: x[:4])
df['tnved6'] = df.tnved.astype(str).apply(lambda x: x[:6])
df = df.rename({'tnved': 'tnved10'}, axis=1)
df = (
df
.merge(
country_groups.loc[:, ['KOD', 'Блок_стран']],
how='left',
left_on='strana',
right_on='KOD'
)
.merge(
branches.loc[:, ['KOD4', 'GPB-BRANCH-NEW']],
how='left',
left_on='tnved4',
right_on='KOD4'
)
).rename({'Блок_стран': 'country_groups', 'GPB-BRANCH-NEW': 'branch'}, axis=1)
df = df.drop([col for col in df.columns if 'KOD' in col], axis=1)
groupby2 = df.groupby(
['period', 'napr', 'strana', 'country_groups', 'branch', 'tnved2']
).sum().loc[:, ['Stoim', 'Netto', 'Kol']].reset_index().rename({'tnved2': 'tnved'}, axis=1)
groupby4 = df.groupby(
['period', 'napr', 'strana', 'country_groups', 'branch', 'tnved4']
).sum().loc[:, ['Stoim', 'Netto', 'Kol']].reset_index().rename({'tnved4': 'tnved'}, axis=1)
groupby6 = df.groupby(
['period', 'napr', 'strana', 'country_groups', 'branch', 'tnved6']
).sum().loc[:, ['Stoim', 'Netto', 'Kol']].reset_index().rename({'tnved6': 'tnved'}, axis=1)
df = df.drop(['tnved2', 'tnved4', 'tnved6'], axis=1).rename({'tnved10': 'tnved'}, axis=1)
for grouped_df in [groupby2, groupby4, groupby6]:
df = df.append(grouped_df).reset_index(drop=True)
df['n_digits'] = df.tnved.str.len()
return df
def encode_labels(df, dest_folder):
'''
Encodes character columns to codes with corresponding dictionaries.
'''
countries = pd.read_excel('ФТС блоки стран.xlsx', keep_default_na=False)
country_dict = {
row[1]['KOD']: row[1]['CTPAHA_CODE'] for row in countries.iterrows()
}
df['strana'] = df.strana.replace(country_dict)
country_groups = pd.read_csv('country_groups.csv', keep_default_na=False)
country_groups_dict = {
row[1].country_group: row[1].group_code for row in country_groups.iterrows()
}
df['country_groups'] = df['country_groups'].replace(country_groups_dict)
unique_branch = pd.read_csv('branches.csv', keep_default_na=False)
unique_branch_dict = {
row[1].branch: row[1].branch_code for row in unique_branch.iterrows()
}
df['branch'] = df['branch'].replace(unique_branch_dict)
df['napr'] = df.napr.replace({'ИМ': 1, 'ЭК': 2})
periods = pd.read_csv('periods.csv')
periods_dict = {
row[1].period: row[1].period_code for row in periods.iterrows()
}
df['period'] = df.period.replace(periods_dict)
return df
def upload_to_file(df, path):
'''
Uploads processed dataframe to an existing file with all data.
Creates a new one if there is no file for storage.
'''
if os.path.exists(os.path.join(path, 'TSVTdata.csv')):
df.to_csv(os.path.join(path, 'TSVTdata.csv'), mode='a', index=False, header=False)
else:
df.to_csv(os.path.join(path, 'TSVTdata.csv'), index=False)
| true |
7dd0e79a216372423316363731e009a01a565e8b | Python | freebz/Introducing-Python | /ch04/ex4-11.py | UTF-8 | 1,051 | 4.25 | 4 | [] | no_license | # 4.11 에러 처리하기: try, except
short_list = [1, 2, 3]
position = 5
short_list[position]
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# IndexError: list index out of range
short_list = [1, 2, 3]
position = 5
try:
short_list[position]
except:
print('Need a position between 0 and', len(short_list)-1, ' but got',
position)
# Need a position between 0 and 2 but got 5
short_list = [1, 2, 3]
while True:
value = input('Position [q to quit]? ')
if value == 'q':
break
try:
position = int(value)
print(short_list[position])
except IndexError as err:
print('Bad index:', position)
except Exception as other:
print('Something else broke:', other)
# Position [q to quit]? 1
# 2
# Position [q to quit]? 0
# 1
# Position [q to quit]? 2
# 3
# Position [q to quit]? 3
# Bad index: 3
# Position [q to quit]? 2
# 3
# Position [q to quit]? two
# Something else broke: invalid literal for int() with base 10: 'two'
# Position [q to quit]? q
| true |
644d049a2ff5ebff77d443a91d17a1f2a11b43ae | Python | Arya-Programmer/TodoApp-Flutter | /TodoBackend/backend/resources/validations.py | UTF-8 | 1,041 | 2.71875 | 3 | [] | no_license | from models import User
def validate(json_data):
try:
firstname = json_data["firstname"]
lastname = json_data["lastname"]
username = json_data["username"]
email = json_data["email"]
password = json_data["password"]
except Exception:
return {"message": "Required fields aren't provided"}, 400
user_check = User.query.filter_by(username=username).first()
email_check = User.query.filter_by(email=email).first()
if user_check:
if email_check:
return {"message": "Username and email are taken. Want to sign in?"}, 400
else:
return {"message": "A user with that username already exists"}, 400
if email_check:
return {"message": "this email address already exists. Have you forgotten your password?"}, 400
if password in email:
return {"message": "Email and Password too similar"}, 400
if username in password:
return {"message": "Username and password are too similar"}, 400
return True | true |
a3f70768a337c282edba6842bc8f32af587ebb43 | Python | theoneandonlywoj/Object-Shape-Classification-Utilizing-Magnetic-Field-Disturbance-and-Supervised-Machine-Learning | /import_data.py | UTF-8 | 4,268 | 3.109375 | 3 | [
"Apache-2.0"
] | permissive | import pandas as pd
import numpy as np
from tflearn.data_utils import to_categorical
from import_data import *
def import_csv(file_path, shuffle = False):
data = pd.read_csv(file_path)
print('*' * 70)
print('Import CSV file has been successful!')
if shuffle == True:
data.reindex(np.random.permutation(data.index))
print('The data has been shuffled!')
else:
print('The data has not been shuffled!')
return data
def labels_info(output_data):
labels_names = np.unique(output_data)
number_of_labels = labels_names.shape[0]
print('*' * 70)
print("Number of uniques categories:", number_of_labels)
labels_as_numbers = np.arange(number_of_labels)
print("Categories as numbers", labels_as_numbers)
for _ in labels_as_numbers:
print('Category ' + str(_) + ' is ' + str(labels_names[_]))
return number_of_labels
def labels_as_numbers(output_data):
_, output_data_as_numbers = np.unique(output_data, return_inverse=True)
return output_data_as_numbers
# -------------------------------------------------------------------------------
# Acquiring the data
def get_data_MNIST():
folder = 'Digit Recognizer'
file_name = 'train.csv'
specific_dataset_source = folder + '/' + file_name
output_columns = ['label']
data = import_csv(specific_dataset_source, shuffle = True)
# Data split into the input and output
x_data = data
y_data = np.array(data.pop('label'))
print('Shape of the input data:', x_data.shape)
print('Shape of the output data:', y_data.shape)
# Standalization
x_data = x_data / 255
num_samples = x_data.shape[0]
input_features = x_data.shape[1]
print('Number of samples:', num_samples)
print('Number of the input features:', input_features)
y_data_as_numbers = labels_as_numbers(y_data)
# Cross validation data preparation
split_percentage = 80
split_index = int(x_data.shape[0]/(100/split_percentage))
x_train = np.array(x_data[:split_index])
x_val = np.array(x_data[split_index:])
y_train = np.array(y_data_as_numbers[:split_index])
y_val = np.array(y_data_as_numbers[split_index:])
# Information about the data
print(x_train.shape)
print(x_val.shape)
print(y_train.shape)
print(y_val.shape)
# Shaping data into the correct shape.
x_train = x_train.reshape([-1, 28, 28, 1])
x_val = x_val.reshape([-1, 28, 28, 1])
y_train = to_categorical(y_train, nb_classes = 10)
y_val = to_categorical(y_val, nb_classes = 10)
return x_train, x_val, y_train, y_val
def get_data_MNIST_test():
# Loading the test data
file_name_test = 'test.csv'
folder = 'Digit Recognizer'
source = folder + '/' + file_name_test
data = pd.read_csv(source)
test_input = data.loc[:, :]
return test_input.as_matrix()
# Oxford Flowers Dataset
def get_data_oxford_flowers():
import tflearn.datasets.oxflower17 as oxflower17
X, Y = oxflower17.load_data(one_hot = True, resize_pics = (227, 227))
split_percentage = 80
split_index = int(X.shape[0]/(100/split_percentage))
x_train = np.array(X[:split_index])
x_val = np.array(X[split_index:])
y_train = np.array(Y[:split_index])
y_val = np.array(Y[split_index:])
return x_train, x_val, y_train, y_val
def get_data_CIFAR10(dataset = 'Train + Val'):
from tflearn.datasets import cifar10
(X, Y), (X_test, Y_test) = cifar10.load_data(one_hot=True)
# Size is 32, 32, 3
split_percentage = 100
split_index = int(X.shape[0]/(100/split_percentage))
x_train = np.array(X[:split_index])
x_val = np.array(X[split_index:])
y_train = np.array(Y[:split_index])
y_val = np.array(Y[split_index:])
if dataset == 'Train + Val':
return x_train, x_val, y_train, y_val
else:
return X_test, Y_test
def get_data_MNIST_native(dataset = 'Train + Val'):
import tflearn.datasets.mnist as mnist
X, Y, X_test, Y_test = mnist.load_data(one_hot =True)
X = X.reshape([-1, 28, 28, 1])
X_test = X_test.reshape([-1, 28, 28, 1])
# Size is 28, 28, 1
split_percentage = 100
split_index = int(X.shape[0]/(100/split_percentage))
x_train = np.array(X[:split_index])
x_val = np.array(X[split_index:])
y_train = np.array(Y[:split_index])
y_val = np.array(Y[split_index:])
if dataset == 'Train + Val':
return x_train, x_val, y_train, y_val
else:
return X_test, Y_test
| true |
51027ab33f56df1dcc282cd6f0a256b0a5bc89f7 | Python | frankieliu/problems | /leetcode/python/47/original/47.permutations-ii.0.py | UTF-8 | 609 | 3.015625 | 3 | [] | no_license | #
# @lc app=leetcode id=47 lang=python3
#
# [47] Permutations II
#
# https://leetcode.com/problems/permutations-ii/description/
#
# algorithms
# Medium (38.72%)
# Total Accepted: 215.1K
# Total Submissions: 555.5K
# Testcase Example: '[1,1,2]'
#
# Given a collection of numbers that might contain duplicates, return all
# possible unique permutations.
#
# Example:
#
#
# Input: [1,1,2]
# Output:
# [
# [1,1,2],
# [1,2,1],
# [2,1,1]
# ]
#
#
#
class Solution:
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
| true |
702a47b99ee52e59bcf917e2d5b44f8df880554b | Python | TheXichao/pp | /work/chapter4.py | UTF-8 | 524 | 3.796875 | 4 | [] | no_license | def task1():
import random
totalNum = int()
for _ in range(10):
num = random.randint(1,10)
print('you got the number: ', num)
totalNum += num
print('total of the number: ',totalNum)
def task2():
import random
totalNum = int()
for _ in range(1000):
num = random.randint(1,10)
totalNum += num
print('the average is: ',totalNum/1000)
def task3():
productCode = input('enter your product code, it should begin with AB or AS followed by 3 number: ')
| true |
c1e12644ef78aa6f49a49bed7f4da900cf5c3db8 | Python | femog008/UdacityCapstoneProject | /automatedtesting/selenium/login.py | UTF-8 | 6,496 | 2.734375 | 3 | [] | no_license | #!/usr/bin/env python
import time
import logging
from selenium import webdriver
#from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.common.exceptions import NoSuchElementException
#Logging Config
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s",
datefmt="%m/%d/%Y %I:%M:%S %p",
filename='selenium-test.log',
)
chrome_path = '/usr/local/bin/chromedriver'
# Start the browser and login with standard_user
def login (user, password):
print ('Starting the browser...')
# --uncomment when running in Azure DevOps.
options = ChromeOptions()
options.add_argument("--headless")
driver = webdriver.Chrome(chrome_path, options=options)
baseUrl = "https://www.saucedemo.com"
#driver = webdriver.Chrome(chrome_path)
print ('Browser started successfully. Navigating to the demo page to login.')
logging.info('Browser started successfully. Navigating to the demo page to login.')
driver.get(baseUrl)
driver.find_element_by_css_selector("input[id='user-name']").send_keys(user)
driver.find_element_by_css_selector("input[id='password']").send_keys(password)
driver.find_element_by_css_selector("input[id='login-button']").click()
print(driver.current_url)
print(baseUrl + "/inventory.html")
logging.info(baseUrl + "/inventory.html")
#assert baseUrl + "/inventory.html" == driver.current_url
if baseUrl + "/inventory.html" == driver.current_url:
print("### TEST PASSED - " + user + " Logged in Successfully")
logging.info("### TEST PASSED - " + user + " Logged in Successfully")
else:
print("### TEST FAILED - " + user + " unable to login")
logging.warning("### TEST FAILED - " + user + " unable to login")
#Add all items to cart
logging.info("### Start adding items to cart...###")
items = driver.find_elements_by_css_selector("div.inventory_item")
successful_btn_index = []
for item in items:
btn = item.find_element_by_css_selector("button.btn_primary.btn_inventory")
item_name = item.find_element_by_css_selector("div.inventory_item_name")
cart_value_before = 0 if not is_selector_exist("span.shopping_cart_badge", driver) else driver.find_element_by_css_selector("span.shopping_cart_badge").text
btn.click()
cart_value_after = driver.find_element_by_css_selector("span.shopping_cart_badge").text
item_index = items.index(item)
if int(cart_value_after) == int(cart_value_before) + 1:
print(item_name.text + " has been added to cart")
logging.info(item_name.text + " has been added to cart")
successful_btn_index.append(item_index)
else:
print("Failed to add " + item_name.text + " to cart")
logging.warning("Failed to add " + item_name.text + " to cart")
time.sleep(1)
#Check if cart contains all added items
logging.info("### Checking if items were added to cart... ###")
cart_value = 0 if not is_selector_exist("span.shopping_cart_badge", driver) else driver.find_element_by_css_selector("span.shopping_cart_badge").text
print("### Total number of items on Page is: " + str(len(items)))
logging.info("### Total number of items on Page is: " + str(len(items)))
print("### Total items in the cart is " + str(cart_value))
logging.info("### Total items in the cart is " + str(cart_value))
if str(cart_value) == str(len(items)):
print("### TEST PASSED - Cart contains all added items for user: " + user)
logging.info("### TEST PASSED - Cart contains all added items for user: " + user)
else:
print("### TEST FAILED- Cart does not contain all added items for user: " + user)
logging.warning("### TEST FAILED- Cart does not contain all added items for user: " + user)
#Remove all items from cart
logging.info("### Start removing items from cart... ###")
for index in successful_btn_index:
btn = items[index].find_element_by_css_selector("button.btn_secondary.btn_inventory")
item_name = items[index].find_element_by_css_selector("div.inventory_item_name")
old_cart_value = int(driver.find_element_by_css_selector("span.shopping_cart_badge").text)
btn.click()
if len(driver.find_elements_by_css_selector("span.shopping_cart_badge")) != 0:
new_cart_value = int(driver.find_element_by_css_selector("span.shopping_cart_badge").text)
if new_cart_value == old_cart_value - 1:
print(item_name.text + " has been successfully removed from cart")
logging.info(item_name.text + " has been successfully removed from cart")
else:
print("Failed to remove " + item_name.text + " from cart")
logging.warning("Failed to remove " + item_name.text + " from cart")
else:
print(item_name.text + " has been removed from cart")
logging.info(item_name.text + " has been removed from cart")
print("No more item in the cart")
logging.info("No more item in the cart")
#time.sleep(1)
#Confirm cart is empty
logging.info("### Confirming cart is empty... ###")
if not is_selector_exist("span.shopping_cart_badge", driver):
print("### TEST PASSED- All items successfully removed from cart for user: " + user)
logging.info("### TEST PASSED- All items successfully removed from cart for user: " + user)
else:
print("### TEST FAILED- Unable to remove some items from the cart for user: " + user)
logging.warning("### TEST FAILED- Unable to remove some items from the cart for user: " + user)
driver.close()
def is_selector_exist(selector, driver = None, webelement = None):
if driver != None:
counter_element = driver.find_elements_by_css_selector(selector)
else:
if webelement != None:
counter_element = webelement.find_elements_by_css_selector(selector)
else:
counter_element = driver.find_elements_by_css_selector(selector)
if len(counter_element) == 0:
return False
else:
return True
login('standard_user', 'secret_sauce')
login('locked_out_user', 'secret_sauce')
login('problem_user', 'secret_sauce')
login('performance_glitch_user', 'secret_sauce')
| true |
9cb6657a5f3de4a08a8d84f39c33a3c30560d731 | Python | jxnkb/project_WEB | /zhouxiaofang/0909作业/0909代码重敲/05其他操作.py | UTF-8 | 725 | 2.796875 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#====#====#====#====
#Author:
#CreatDate:
#Version:
#====#====#====#====
from selenium import webdriver
import time
dr=webdriver.Firefox()
# dr.get('https://www.baidu.com')
# e=dr.find_element_by_id('kw')
# e.send_keys('软件测试')
# time.sleep(2)
# #回车
# e.submit()
# #获取页面标题
# print(dr.title)
# #获取页面的地址
# print(dr.current_url)
# time.sleep(2)
# dr.quit()
#案例:在淘宝首页上的搜索栏中输入软件测试,然后按回车,之后打印本页的标题和url
dr.get('https://www.taobao.com')
e=dr.find_element_by_id('q')
e.send_keys('软件测试')
time.sleep(2)
e.submit()
print(dr.title)
print(dr.current_url)
time.sleep(2)
dr.quit() | true |
a2f8d17700135f5d83ffaa35775a122fb07bea36 | Python | beartype/beartype | /beartype/vale/__init__.py | UTF-8 | 7,787 | 2.59375 | 3 | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2023 Beartype authors.
# See "LICENSE" for further details.
'''
**Beartype validator API.**
This submodule publishes a PEP-compliant hierarchy of subscriptable (indexable)
classes enabling callers to validate the internal structure of arbitrarily
complex scalars, data structures, and third-party objects. Like annotation
objects defined by the :mod:`typing` module (e.g., :attr:`typing.Union`), these
classes dynamically generate PEP-compliant type hints when subscripted
(indexed) and are thus intended to annotate callables and variables. Unlike
annotation objects defined by the :mod:`typing` module, these classes are *not*
explicitly covered by existing PEPs and thus *not* directly usable as
annotations.
Instead, callers are expected to (in order):
#. Annotate callable parameters and returns to be validated with
:pep:`593`-compliant :attr:`typing.Annotated` type hints.
#. Subscript those hints with (in order):
#. The type of those parameters and returns.
#. One or more subscriptions of classes declared by this submodule.
'''
# ....................{ TODO }....................
#FIXME: [FEATURE] Add a new "beartype.vale.IsInline" validator factory,
#elegantly resolving issue #82 and presumably other future issues, too. The
#core idea here is that "beartype.vale.IsInline" will enable callers to
#directly embed arbitrary test code substrings in the bodies of wrapper
#functions dynamically generated by @beartype. The signature resembles:
# beartype.vale.IsInline[code: str, arg_1: object, ..., arg_N: object]
#...where:
#* "arg_1" through "arg_N" are optional arbitrary objects to be made available
# through the corresponding format variables "{arg_1}" through "{arg_N}" in
# the "code" substring. These arguments are the *ONLY* safe means of exposing
# non-builtin objects to the "code" substring.
#* "code" is a mandatory arbitrary test code substring. This substring *MUST*
# contain at least this mandatory format variable:
# * "{obj}", expanding to the current object being validated. Should this
# perhaps be "{pith}" instead for disambiguity? *shrug*
# Additionally, for each optional "arg_{index}" object subscripting this
# "IsInline" factory, this "code" substring *MUST* contain at least one
# corresponding format variable "{arg_{index}}". For example:
# # This is valid.
# IsInline['len({obj}) == len({arg_1})', ['muh', 'list',]]
#
# # This is invalid, because the "['muh', 'list',]" list argument is
# # *NEVER* referenced via "{arg_1}" in this code snippet.
# IsInline['len({obj}) == 2', ['muh', 'list',]]
# Lastly, this substring may additionally contain these optional format
# variables:
# * "{indent}", expanding to the current indentation level. Specifically:
# * Any "code" substring beginning with a newline *MUST* contain one or more
# "{indent}" variables.
# * Any "code" substring *NOT* beginning with a newline must *NOT* contain
# any "{indent}" variables.
#FIXME: As intelligently requested by @Saphyel at #32, add support for
#additional classes support constraints resembling:
#
#* String constraints:
# * Email.
# * Uuid.
# * Choice.
# * Language.
# * Locale.
# * Country.
# * Currency.
#* Comparison constraints
# * IdenticalTo.
# * NotIdenticalTo.
# * LessThan.
# * GreaterThan.
# * Range.
# * DivisibleBy.
#FIXME: Add a new BeartypeValidator.find_cause() method with the same
#signature and docstring as the existing ViolationCause.find_cause()
#method. This new BeartypeValidator.find_cause() method should then be
#called by the "_peperrorannotated" submodule to generate human-readable
#exception messages. Note that this implies that:
#* The BeartypeValidator.__init__() method will need to additionally accept a new
# mandatory "find_cause: Callable[[], Optional[str]]" parameter, which
# that method should then localize to "self.find_cause".
#* Each __class_getitem__() dunder method of each "_BeartypeValidatorFactoryABC" subclass will need
# to additionally define and pass that callable when creating and returning
# its "BeartypeValidator" instance.
#FIXME: *BRILLIANT IDEA.* Holyshitballstime. The idea here is that we can
#leverage all of our existing "beartype.is" infrastructure to dynamically
#synthesize PEP-compliant type hints that would then be implicitly supported by
#any runtime type checker. At present, subscriptions of "Is" (e.g.,
#"Annotated[str, Is[lambda text: bool(text)]]") are only supported by beartype
#itself. Of course, does anyone care? I mean, if you're using a runtime type
#checker, you're probably *ONLY* using beartype. Right? That said, this would
#technically improve portability by allowing users to switch between different
#checkers... except not really, since they'd still have to import beartype
#infrastructure to do so. So, this is probably actually useless.
#
#Nonetheless, the idea itself is trivial. We declare a new
#"beartype.is.Portable" singleton accessed in the same way: e.g.,
# from beartype import beartype
# from beartype.is import Portable
# NonEmptyStringTest = Is[lambda text: bool(text)]
# NonEmptyString = Portable[str, NonEmptyStringTest]
# @beartype
# def munge_it(text: NonEmptyString) -> str: ...
#
#So what's the difference between "typing.Annotated" and "beartype.is.Portable"
#then? Simple. The latter dynamically generates one new PEP 3119-compliant
#metaclass and associated class whenever subscripted. Clearly, this gets
#expensive in both space and time consumption fast -- which is why this won't
#be the default approach. For safety, this new class does *NOT* subclass the
#first subscripted class. Instead:
#* This new metaclass of this new class simply defines an __isinstancecheck__()
# dunder method. For the above example, this would be:
# class NonEmptyStringMetaclass(object):
# def __isinstancecheck__(cls, obj) -> bool:
# return isinstance(obj, str) and NonEmptyStringTest(obj)
#* This new class would then be entirely empty. For the above example, this
# would be:
# class NonEmptyStringClass(object, metaclass=NonEmptyStringMetaclass):
# pass
#
#Well, so much for brilliant. It's slow and big, so it seems doubtful anyone
#would actually do that. Nonetheless, that's food for thought for you.
# ....................{ IMPORTS }....................
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# WARNING: To avoid polluting the public module namespace, external attributes
# should be locally imported at module scope *ONLY* under alternate private
# names (e.g., "from argparse import ArgumentParser as _ArgumentParser" rather
# than merely "from argparse import ArgumentParser").
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
from beartype.vale._is._valeis import _IsFactory
from beartype.vale._is._valeistype import (
_IsInstanceFactory,
_IsSubclassFactory,
)
from beartype.vale._is._valeisobj import _IsAttrFactory
from beartype.vale._is._valeisoper import _IsEqualFactory
# ....................{ SINGLETONS }....................
# Public factory singletons instantiating these private factory classes.
Is = _IsFactory(basename='Is')
IsAttr = _IsAttrFactory(basename='IsAttr')
IsEqual = _IsEqualFactory(basename='IsEqual')
IsInstance = _IsInstanceFactory(basename='IsInstance')
IsSubclass = _IsSubclassFactory(basename='IsSubclass')
# Delete all private factory classes imported above for safety.
del (
_IsFactory,
_IsAttrFactory,
_IsEqualFactory,
_IsInstanceFactory,
_IsSubclassFactory,
)
| true |
4c7ccbb582075b35397562037a837065b486061e | Python | tomoyk/misc | /paiza/b053/a.py | UTF-8 | 747 | 3.203125 | 3 | [] | no_license | #!/usr/bin/env python
H,W = [int(i) for i in input().split()]
a = [ [int(i) for i in input().split()] for _ in range(2) ]
diff_x = a[0][1] - a[0][0]
diff_y = a[1][0] - a[0][0]
ans=[]
# print(a)
# print(diff_x, diff_y)
# 最初の2行だけ片付ける
for y in range(2):
tmp=[a[y][0], a[y][1]]
start = a[y][1]
diff_x = a[y][1] - a[y][0]
for x in range(1, W-1):
# print(x, diff_x)
tmp.append( start + x*diff_x )
ans.append(tmp)
# print(ans)
# 2行より後ろを片付ける
for y in range(2, H):
tmp = []
for x in range(0, W):
diff_y = ans[y-1][x] - ans[y-2][x]
tmp.append( ans[y-1][x] + diff_y )
ans.append(tmp)
for i in ans:
print( ' '.join( str(c) for c in i ) )
| true |
dd8fbb56c8307630bacc141fe3f0f2f11fa45d72 | Python | brianliu2/cs231n_mySolution | /assignment_2/why_batchNorm_is_important.py | UTF-8 | 2,116 | 3.0625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 5 13:20:40 2017
@author: xliu
"""
import numpy as np
import matplotlib.pyplot as plt
D = np.random.randn(1000, 500)
hidden_layers_size = [500] * 10
# choose a nonlinear function to be the activation function
nonlinearities = ['relu'] * len(hidden_layers_size)
act = {'relu': lambda x: np.maximum(0, x), 'tanh': lambda x: np.tanh(x)}
Hs = {}
for i in range(len(hidden_layers_size)):
if i == 0:
X = D
else:
X = Hs[i-1]
fan_in = X.shape[1]
fan_out = hidden_layers_size[i]
# 1. naive tiny value initialization
# W = 0.01 * np.random.randn(fan_in, fan_out)
# 2. Xavier weight initialization: force points to have variance value to be one
# -- disadvantage: doesn't account nonliearity of activation:
# e.g. tanh in this example has relatively week nonlinearity.
# if we change the activation to ReLu, we basically kill half of points to zero,
# which means we half the variance
# W = (1/np.sqrt(fan_in)) * np.random.randn(fan_in, fan_out)
# 3. He weight initialization: after ReLu, half points are killed, as a result
# of which, variance is manually halved. So in the weight initialization, we
# manually double its variance. We would saturate outputs from hidden layers.
W = (1/(np.sqrt(fan_in/2))) * np.random.randn(fan_in, fan_out)
H = np.dot(X, W)
H = act[nonlinearities[i]](H)
Hs[i] = H
# look at distributions at each layer
print('input layer had mean %f and std %f' % (np.mean(D), np.std(D)))
layer_means = [np.mean(H) for i, H in Hs.items()]
layer_stds = [np.std(H) for i, H in Hs.items()]
for i, H in Hs.items():
print('hidden layer %d had mean %f and std %f' % (i+1, layer_means[i], layer_stds[i]))
# plot means and standard deviations
keys = [key for key in Hs.keys()]
plt.figure()
plt.subplot(121)
plt.plot(keys, layer_means, 'ob-')
plt.title('layer mean')
plt.subplot(122)
plt.plot(keys, layer_stds, 'or-')
plt.title('layer std')
# plot the raw distributions
plt.figure()
for i, H in Hs.items():
plt.subplot(1, len(Hs), i+1)
plt.hist(H.ravel(), 30, range=(-1,1))
| true |
c86465c4f1bdb202409e73625eaaa71a8751e09a | Python | Luckyaxah/leetcode-python | /组合.py | UTF-8 | 567 | 2.6875 | 3 | [] | no_license | class Solution:
def combine(self, n: int, k: int):
n_list = list(range(1,n+1))
def fun(n_list ,n,k):
ret = []
if n <= 0 or k<=0:
return [[]]
for i in range(n-k+1):
first = n_list[i]
t = fun(n_list[i+1:],n-i-1,k-1)
for j in range(len(t)):
ret.append([first]+t[j])
return ret
return fun(n_list,n,k)
if __name__ == "__main__":
a = Solution()
print(a.combine(4,2))
pass | true |
39084937bd38f65de424fac72bff8dda9e77a98e | Python | KDYao/mtad-gat-pytorch | /prediction.py | UTF-8 | 9,408 | 2.71875 | 3 | [
"MIT"
] | permissive | import json
from tqdm import tqdm
from eval_methods import *
from utils import *
class Predictor:
"""MTAD-GAT predictor class.
:param model: MTAD-GAT model (pre-trained) used to forecast and reconstruct
:param window_size: Length of the input sequence
:param n_features: Number of input features
:param pred_args: params for thresholding and predicting anomalies
"""
def __init__(self, model, window_size, n_features, pred_args, summary_file_name="summary.txt"):
self.model = model
self.window_size = window_size
self.n_features = n_features
self.dataset = pred_args["dataset"]
self.target_dims = pred_args["target_dims"]
self.scale_scores = pred_args["scale_scores"]
self.q = pred_args["q"]
self.level = pred_args["level"]
self.dynamic_pot = pred_args["dynamic_pot"]
self.use_mov_av = pred_args["use_mov_av"]
self.gamma = pred_args["gamma"]
self.reg_level = pred_args["reg_level"]
self.save_path = pred_args["save_path"]
self.batch_size = 256
self.use_cuda = True
self.pred_args = pred_args
self.summary_file_name = summary_file_name
def get_score(self, values):
"""Method that calculates anomaly score using given model and data
:param values: 2D array of multivariate time series data, shape (N, k)
:return np array of anomaly scores + dataframe with prediction for each channel and global anomalies
"""
print("Predicting and calculating anomaly scores..")
data = SlidingWindowDataset(values, self.window_size, self.target_dims)
loader = torch.utils.data.DataLoader(data, batch_size=self.batch_size, shuffle=False)
device = "cuda" if self.use_cuda and torch.cuda.is_available() else "cpu"
self.model.eval()
preds = []
recons = []
with torch.no_grad():
for x, y in tqdm(loader):
x = x.to(device)
y = y.to(device)
y_hat, _ = self.model(x)
# Shifting input to include the observed value (y) when doing the reconstruction
recon_x = torch.cat((x[:, 1:, :], y), dim=1)
_, window_recon = self.model(recon_x)
preds.append(y_hat.detach().cpu().numpy())
# Extract last reconstruction only
recons.append(window_recon[:, -1, :].detach().cpu().numpy())
preds = np.concatenate(preds, axis=0)
recons = np.concatenate(recons, axis=0)
actual = values.detach().cpu().numpy()[self.window_size:]
if self.target_dims is not None:
actual = actual[:, self.target_dims]
anomaly_scores = np.zeros_like(actual)
df = pd.DataFrame()
for i in range(preds.shape[1]):
df[f"Forecast_{i}"] = preds[:, i]
df[f"Recon_{i}"] = recons[:, i]
df[f"True_{i}"] = actual[:, i]
a_score = np.sqrt((preds[:, i] - actual[:, i]) ** 2) + self.gamma * np.sqrt(
(recons[:, i] - actual[:, i]) ** 2)
if self.scale_scores:
q75, q25 = np.percentile(a_score, [75, 25])
iqr = q75 - q25
median = np.median(a_score)
a_score = (a_score - median) / (1+iqr)
anomaly_scores[:, i] = a_score
df[f"A_Score_{i}"] = a_score
anomaly_scores = np.mean(anomaly_scores, 1)
df['A_Score_Global'] = anomaly_scores
return df
def predict_anomalies(self, train, test, true_anomalies, load_scores=False, save_output=True,
scale_scores=False):
""" Predicts anomalies
:param train: 2D array of train multivariate time series data
:param test: 2D array of test multivariate time series data
:param true_anomalies: true anomalies of test set, None if not available
:param save_scores: Whether to save anomaly scores of train and test
:param load_scores: Whether to load anomaly scores instead of calculating them
:param save_output: Whether to save output dataframe
:param scale_scores: Whether to feature-wise scale anomaly scores
"""
if load_scores:
print("Loading anomaly scores")
train_pred_df = pd.read_pickle(f"{self.save_path}/train_output.pkl")
test_pred_df = pd.read_pickle(f"{self.save_path}/test_output.pkl")
train_anomaly_scores = train_pred_df['A_Score_Global'].values
test_anomaly_scores = test_pred_df['A_Score_Global'].values
else:
train_pred_df = self.get_score(train)
test_pred_df = self.get_score(test)
train_anomaly_scores = train_pred_df['A_Score_Global'].values
test_anomaly_scores = test_pred_df['A_Score_Global'].values
train_anomaly_scores = adjust_anomaly_scores(train_anomaly_scores, self.dataset, True, self.window_size)
test_anomaly_scores = adjust_anomaly_scores(test_anomaly_scores, self.dataset, False, self.window_size)
# Update df
train_pred_df['A_Score_Global'] = train_anomaly_scores
test_pred_df['A_Score_Global'] = test_anomaly_scores
if self.use_mov_av:
smoothing_window = int(self.batch_size * self.window_size * 0.05)
train_anomaly_scores = pd.DataFrame(train_anomaly_scores).ewm(span=smoothing_window).mean().values.flatten()
test_anomaly_scores = pd.DataFrame(test_anomaly_scores).ewm(span=smoothing_window).mean().values.flatten()
# Find threshold and predict anomalies at feature-level (for plotting and diagnosis purposes)
out_dim = self.n_features if self.target_dims is None else len(self.target_dims)
all_preds = np.zeros((len(test_pred_df), out_dim))
for i in range(out_dim):
train_feature_anom_scores = train_pred_df[f"A_Score_{i}"].values
test_feature_anom_scores = test_pred_df[f"A_Score_{i}"].values
epsilon = find_epsilon(train_feature_anom_scores, reg_level=2)
train_feature_anom_preds = (train_feature_anom_scores >= epsilon).astype(int)
test_feature_anom_preds = (test_feature_anom_scores >= epsilon).astype(int)
train_pred_df[f"A_Pred_{i}"] = train_feature_anom_preds
test_pred_df[f"A_Pred_{i}"] = test_feature_anom_preds
train_pred_df[f"Thresh_{i}"] = epsilon
test_pred_df[f"Thresh_{i}"] = epsilon
all_preds[:, i] = test_feature_anom_preds
# Global anomalies (entity-level) are predicted using aggregation of anomaly scores across all features
# These predictions are used to evaluate performance, as true anomalies are labeled at entity-level
# Evaluate using different threshold methods: brute-force, epsilon and peaks-over-treshold
e_eval = epsilon_eval(train_anomaly_scores, test_anomaly_scores, true_anomalies, reg_level=self.reg_level)
p_eval = pot_eval(train_anomaly_scores, test_anomaly_scores, true_anomalies,
q=self.q, level=self.level, dynamic=self.dynamic_pot)
if true_anomalies is not None:
bf_eval = bf_search(test_anomaly_scores, true_anomalies, start=0.01, end=2, step_num=100, verbose=False)
else:
bf_eval = {}
print(f"Results using epsilon method:\n {e_eval}")
print(f"Results using peak-over-threshold method:\n {p_eval}")
print(f"Results using best f1 score search:\n {bf_eval}")
for k, v in e_eval.items():
if not type(e_eval[k]) == list:
e_eval[k] = float(v)
for k, v in p_eval.items():
if not type(p_eval[k]) == list:
p_eval[k] = float(v)
for k, v in bf_eval.items():
bf_eval[k] = float(v)
# Save
summary = {"epsilon_result": e_eval, "pot_result": p_eval, "bf_result": bf_eval}
with open(f"{self.save_path}/{self.summary_file_name}", "w") as f:
json.dump(summary, f, indent=2)
# Save anomaly predictions made using epsilon method (could be changed to pot or bf-method)
if save_output:
global_epsilon = e_eval["threshold"]
test_pred_df["A_True_Global"] = true_anomalies
train_pred_df["Thresh_Global"] = global_epsilon
test_pred_df["Thresh_Global"] = global_epsilon
train_pred_df[f"A_Pred_Global"] = (train_anomaly_scores >= global_epsilon).astype(int)
test_preds_global = (test_anomaly_scores >= global_epsilon).astype(int)
# Adjust predictions according to evaluation strategy
if true_anomalies is not None:
test_preds_global = adjust_predicts(None, true_anomalies, global_epsilon, pred=test_preds_global)
test_pred_df[f"A_Pred_Global"] = test_preds_global
print(f"Saving output to {self.save_path}/<train/test>_output.pkl")
train_pred_df.to_pickle(f"{self.save_path}/train_output.pkl")
test_pred_df.to_pickle(f"{self.save_path}/test_output.pkl")
print("-- Done.")
| true |
fce4caeeadec5e00479b95072a66a233507b41fb | Python | IgoAlgo/Problem-Solving | /AejiJeon/baekjoonOJ/shortestpath/7_law_of_step6.py | UTF-8 | 876 | 3.375 | 3 | [] | no_license |
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
INF = int(1e9)
# 모든 vertex 쌍의 v1 -> v2 최단경로 담는 array
distance = [[INF]*(n+1) for _ in range(n+1)]
for i in range(1, n+1):
distance[i][i] = 0
# append edges
for _ in range(m):
a, b = map(int,input().split())
distance[a][b] = 1
distance[b][a] = 1
# apply floyd warshall algorithm
for k in range(1, n+1):
for i in range(1, n+1):
for j in range(1, n+1):
distance[i][j] = min(distance[i][j], distance[i][k]+distance[k][j])
min_val = INF
result = 0
for i in range(1, n+1):
bacon = 0
# 모든 vertices에 대해서
# i -> vertex 최단거리 합 구하기
for j in range(1, n+1):
bacon += distance[i][j]
# bacon 최솟값 구하기
if min_val > bacon:
result = i
min_val = bacon
print(result) | true |
8905e33980a3cc21fad92f2c6112aed6076641ef | Python | JankDev/battleship | /main/computer.py | UTF-8 | 6,755 | 2.65625 | 3 | [] | no_license | import random
try:
import pymongo as mg
except ImportError as err:
print(err)
exit()
maxSevSelDelay = 2
try:
myclient = mg.MongoClient("mongodb://localhost:27017/", serverSelectionTimeoutMS=maxSevSelDelay)
except mg.errors.ServerSelectionTimeoutError as err:
print(err)
exit()
mydb = myclient["battleship"]
random.seed()
used_random_points = list()
used_points = list()
class Computer:
def __init__(self):
self.ships = list()
self.hunt_mode = False
self.player_ships = list()
used_points.clear()
used_random_points.clear()
def place_ship(self, length):
temp_list = list()
first = True
while first or are_points_not_on_board(temp_list) or contains_point(temp_list):
first = False
temp_list.clear()
vertical = bool(random.getrandbits(1))
horizontal = bool(random.getrandbits(1))
x = random.randint(0, 9)
y = random.randint(0, 9)
temp_list.append((x, y))
if horizontal:
if vertical:
for j in range(1, length):
temp_list.append((x + j, y))
else:
for j in range(1, length):
temp_list.append((x - j, y))
else:
if vertical:
for j in range(1, length):
temp_list.append((x, y + j))
else:
for j in range(1, length):
temp_list.append((x, y - j))
for point in temp_list:
used_points.append(point)
for point in temp_list:
add_near_points(point[0], point[1])
return temp_list
def set_board(self):
self.ships.append(self.place_ship(2))
self.ships.append(self.place_ship(2))
self.ships.append(self.place_ship(3))
self.ships.append(self.place_ship(4))
self.ships.append(self.place_ship(5))
def get_all_points(self):
self.ships = [x for y in self.ships for x in y]
return self.ships
def point_selection(self):
random.seed()
if not self.hunt_mode:
point = []
first = True
while point in used_random_points or first:
point = (random.randint(0, 9), random.randint(0, 9))
first = False
else:
point = self.hunt_mode_selection()
used_random_points.append(point)
return point
def goto_hunt_mode_selection(self, pointGuess):
if not self.hunt_mode:
max_ship = 0
for ship in self.player_ships:
if len(ship) > max_ship:
max_ship = len(ship)
mydb["points"].remove({})
pointsVG = [point for point in [(pointGuess[0], pointGuess[1] + i) for i in range(1, max_ship)] if
pointGuess[1] < point[1] <= 9]
pointsVL = [point for point in [(pointGuess[0], pointGuess[1] + i) for i in range(1, -1 * (max_ship), -1)]
if
0 <= point[1] < pointGuess[1]]
pointsHG = [point for point in [(pointGuess[0] + i, pointGuess[1]) for i in range(1, max_ship)] if
pointGuess[0] < point[0] <= 9]
pointsHL = [point for point in [(pointGuess[0] + i, pointGuess[1]) for i in range(1, -1 * (max_ship), -1)]
if
0 <= point[0] < pointGuess[0]]
if pointsVG and pointsVG[0] not in used_random_points:
mydb["points"].insert({"name": "VG", "points": pointsVG})
if pointsVL and pointsVL[0] not in used_random_points:
mydb["points"].insert({"name": "VL", "points": pointsVL})
if pointsHG and pointsHG[0] not in used_random_points:
mydb["points"].insert({"name": "HG", "points": pointsHG})
if pointsHL and pointsHL[0] not in used_random_points:
mydb["points"].insert({"name": "HL", "points": pointsHL})
def hunt_mode_selection(self):
self.player_ships = [point for ship in self.player_ships for point in ship]
if not list(mydb["points"].find({})):
self.hunt_mode = False
return self.point_selection()
points = mydb["points"].find_one({}, {'_id': 0})
while len(points["points"]) == 0:
mydb["points"].remove({"name": points["name"]})
points = mydb["points"].find_one({}, {'_id': 0})
if not points:
return self.point_selection()
point = tuple(points["points"].pop(0))
mydb["points"].update_one({"name": points["name"]}, {"$set": {"points": points["points"]}})
if point not in self.player_ships:
mydb["points"].remove({"name": points["name"]})
if point in self.player_ships:
if points["name"] in ["VG", "VL"]:
mydb["points"].remove({"name": "HG"})
mydb["points"].remove({"name": "HL"})
else:
mydb["points"].remove({"name": "VG"})
mydb["points"].remove({"name": "VL"})
used_random_points.append((point[0] + 1, point[1] + 1))
used_random_points.append((point[0] + 1, point[1] - 1))
used_random_points.append((point[0] - 1, point[1] + 1))
used_random_points.append((point[0] - 1, point[1] - 1))
return point
def remove_empty_ships(self):
for ship in self.ships:
if not ship:
self.ships.remove(ship)
break
def remove_point_from_ship(self, coord: list):
for ship in self.ships:
if coord in ship:
ship.remove(coord)
break
def got_ship_hit(self, point):
for ship in self.ships:
if point in ship:
return True
return False
def add_near_points(x_coord, y_coord):
used_points.append((x_coord + 1, y_coord + 1))
used_points.append((x_coord - 1, y_coord - 1))
used_points.append((x_coord + 1, y_coord))
used_points.append((x_coord, y_coord + 1))
used_points.append((x_coord - 1, y_coord))
used_points.append((x_coord, y_coord - 1))
used_points.append((x_coord + 1, y_coord - 1))
used_points.append((x_coord - 1, y_coord + 1))
def contains_point(temp_list):
for point in temp_list:
if point in used_points:
return True
return False
def are_points_not_on_board(temp_list):
for point in temp_list:
if 9 < point[0] or 9 < point[1] or point[0] < 0 or point[1] < 0:
return True
return False
| true |
2d183f6efadc667707e7bcf93844cb1f8ae441eb | Python | anyuhanfei/study_PyQt5 | /078~088-QAbstractButton/081-QAbstractButton-图标设置.py | UTF-8 | 1,674 | 3.640625 | 4 | [] | no_license | '''
081-QAbstractButton-图标设置
图标设置的 API :
setIcon(QIcon(image_path)) -- 设置图标(QSize() 方法在 PyQt5.QtGui 类中)
setIconSize(QSize(w, h)) -- 设置图标大小(QIcon() 方法在 PyQt5.QtCore 类中)
() -- 获取图标
iconSize() -- 获取图标大小
'''
import sys
from PyQt5.QtWidgets import QWidget, QApplication, QPushButton, QLabel
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QSize
class Window(QWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setWindowTitle('081_QAbstractButton_图标设置')
self.resize(500, 500)
self.btn = QPushButton(self)
self.btn.resize(60, 100)
'''设置按钮图标'''
# 设置一个图标对象
icon_obj = QIcon('./xxx.png')
# 将图标对象设置为按钮图标
self.btn.setIcon(icon_obj)
'''设置按钮图标大小'''
# 创建尺寸对象
size_obj = QSize(60, 100)
self.btn.setIconSize(size_obj)
'''读取按钮图标信息'''
# 获取图标对象
icon_obj_get = self.btn.icon()
self.label_one = QLabel(self)
self.label_one.move(5, 110)
self.label_one.setText('图标对象:' % (str(icon_obj_get)))
# 获取图标尺寸对象
icon_size_get = self.btn.iconSize()
self.label_two = QLabel(self)
self.label_two.move(5, 140)
self.label_two.setText('图标尺寸对象:%s' % (str(icon_size_get)))
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
| true |
2c992d1e494251f37fe1d3e5b020a7a65f4388a1 | Python | GauravAmarnani/Python-Basics | /com/college/practicals/practical12/program2.py | UTF-8 | 277 | 4.5 | 4 | [] | no_license | # Q. Finding Area and Circumference of a Circle using Python Inbuilt Math Module.
import math
radius = float(input("Enter Radius of Circle: "))
area = math.pi * radius ** 2
circumference = 2 * math.pi * radius
print("Area = ", area, " and Circumference = ", circumference)
| true |
dfa06852f6a281f6c9a9ee152fa74a73a5083b8f | Python | raphaeldelacruz/Cryptography | /Simon64CTR.py | UTF-8 | 2,944 | 3.046875 | 3 | [] | no_license | from Crypto import Random
from Crypto.Random import get_random_bytes
from simon import SimonCipher
def makeBlocks(messageString,size):
blocks = []
i = 0
length = size
while i < len(messageString):
if i+length < len(messageString):
blocks.append(messageString[i:i+length])
else:
blocks.append(messageString[i:len(messageString)])
i += length
return blocks
#Retrieved from https://stackoverflow.com/questions/10237926/convert-string-to-list-of-bits-and-viceversa
def tobits(s):
result = []
for c in s:
bits = bin(ord(c))[2:]
bits = '00000000'[len(bits):] + bits
result.extend([int(b) for b in bits])
return result
#Retrieved from https://stackoverflow.com/questions/10237926/convert-string-to-list-of-bits-and-viceversa
def frombits(bits):
chars = []
for b in range(int(len(bits) / 8)):
byte = bits[b*8:(b+1)*8]
chars.append(chr(int(''.join([str(bit) for bit in byte]), 2)))
return ''.join(chars)
#Encryption using Simon64/128
def encryptSimon(key,nonce,messageBlocks):
ctxt = []
intKey = int(key,16)
cipher = SimonCipher(intKey, block_size=64, key_size=128, mode='CTR', counter =1, init = int(nonce,16))
for i in range(len(messageBlocks)):
blocktxt = bytes.fromhex(hex(cipher.encrypt(int(messageBlocks[i].encode("iso-8859-1").hex(), 16)))[2:].rjust(16,"0")).decode("iso-8859-1")
ctxt.append(blocktxt)
return "".join(ctxt)
#Decryption using Simon64/128
def decryptSimon(key,nonce,messageBlocks):
ptxt = []
intKey = int(key,16)
cipher = SimonCipher(intKey, block_size=64, key_size=128, mode='CTR', counter =1, init = int(nonce,16))
for i in range(len(messageBlocks)):
blocktxt = bytes.fromhex(hex(cipher.decrypt(int(messageBlocks[i].encode("iso-8859-1").hex(), 16)))[2:].rjust(16,"0")).decode("iso-8859-1")
ptxt.append(blocktxt)
return "".join(ptxt)
def main():
print("Simon64 CTR mode")
simonKey = get_random_bytes(16).hex()
print("Here is the key used for the simon cipher: {}".format(simonKey))
simonNonce = get_random_bytes(8).hex()
print("Here is the nonce used for the simon cipher: {}".format(simonNonce))
message = "I can't think of a message, so I am just typing something until it seems to be long enough okay."
print("Here is the message we are encrypting: {}".format(message))
ctxt = encryptSimon(simonKey,simonNonce,makeBlocks(message,8))
print("Here is the generated ciphertext: {}".format(ctxt.encode('iso-8859-1').hex()))
ptxt = decryptSimon(simonKey,simonNonce,makeBlocks(ctxt,8))
print("Here is the plaintext: {}".format(ptxt))
hashKey = get_random_bytes(16).hex()
print("The following message should be True if the plaintext is the same as the original message: {}".format(message == ptxt))
main() | true |
bfea49c5d92c5b63baffc949c5d97ddc3169a66e | Python | ladouceuf/gift-cli | /gift/commands/register.py | UTF-8 | 2,330 | 3.171875 | 3 | [] | no_license | """The register command."""
import pickle
from .base import Base
#This class inherit from the Base class
class Register(Base):
"""Register to the gift exchange event"""
#this method is run when the command "register" is parsed
def run(self):
#warning for user
print("\n**********************************************************************************************************\nWARNING\nAny changes to the guest list performed after the draw will not be taken into account until the next draw.\nThe changes (add/removal of a name) will appear on the results of the next gift exchange.\n**********************************************************************************************************\n")
#read the guest list stored in memory
guests=dict()
with open('gift/obj/guests.pkl', 'rb') as f:
guests=pickle.load(f)
#this block of code runs when the option '--add_name' is parsed
if(self.options['--add_name']):
name=raw_input('\nWhat is your name? ')
while True:
is_partner=raw_input('Do you have a partner? [Y/n] ')
is_partner=is_partner.lower()
if is_partner=='y' or is_partner=='yes':
partner=raw_input('What is his/her name? ')
print('\n')
guests[name]=partner
print("Please make sure that your partner registers too.\n")
break
elif is_partner=='n' or is_partner=='no':
print('No worries, there are plenty of fishes in the sea!\n')
guests[name]=None
break
else:
print("You must answer by 'Y' or 'n'")
#this block of code runs when the option '--remove_name' is parsed
elif(self.options['--remove_name']):
name=raw_input('\nWhat is your name? ')
if name in guests.keys():
del guests[name]
print("Your name has been removed from the guest list.\n")
else:
print("Could not remove your name, it does not appear on the guest list.\n")
#user typed in an invalid option to the command "register" (This is just precaution, the program should raise an error before that)
else:
raise ValueError("The register option should be '--add_name' or '--remove_name'")
#write the guest list back to memory
with open('gift/obj/guests.pkl', 'wb') as f:
pickle.dump(guests, f, pickle.HIGHEST_PROTOCOL)
| true |
10c52bab91e8ab5c57ad96c109d6b098dc0ec3ce | Python | kuzeko/nanorc | /examples/Python.py | UTF-8 | 403 | 3.1875 | 3 | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | permissive | #!/usr/bin/env python
# encoding: utf-8
import numpy as np
from sys import io
class Foo():
def __init__(self, name = "World!"):
self.name = name
self.is_test = True
if __name__ == "__main__":
instance = Foo()
print "Hello, %s" % instance.name
# Comments
for i in range( 1, 100):
a = [ x+1 for x in range(1, i) ]
# print "Mixing tabs and spaces is bad"
| true |
3614201a60f7902da369802b0e9a9f3d6e6e9e9a | Python | apapadoi/Numerical-Analysis-Projects | /Second Project/Exercise5/util.py | UTF-8 | 2,331 | 3.625 | 4 | [
"MIT"
] | permissive | from math import sqrt
def matrix_mult(a, b):
"""
Function that multiplies two matrices a and b
Parameters
----------
a,b : matrices
Returns
-------
new_array : matrix
The matrix product of the inputs
"""
new_array = []
for i in range(len(a)):
new_array.append([0 for i in range(len(b[0]))])
for j in range(len(b[0])):
for k in range(len(a[0])):
new_array[i][j] += a[i][k] * b[k][j]
return new_array
def matrix_vector_mult(matrix, vector):
new_vector = []
for row in range(len(matrix)):
new_vector.append(0)
for column in range(len(matrix[row])):
new_vector[row] += matrix[row][column] * vector[column]
return new_vector
def print_matrix(matrix):
for row in matrix:
for val in row:
print('{:4}'.format(val), end=" ")
print()
print()
def vector_inf_norm(vector):
maximum = abs(vector[0])
for i in range(1, len(vector)):
if abs(vector[i]) > maximum:
maximum = abs(vector[i])
return maximum
def sub_vector(vector1, vector2):
new_vector = []
for i in range(len(vector1)):
new_vector.append(vector1[i] - vector2[i])
return new_vector
def vector_mult(vector1, vector2):
new_matrix = []
for i in range(len(vector1)):
new_matrix.append([0 for i in range(len(vector2))])
for j in range(len(vector2)):
new_matrix[i][j] = vector1[i]*vector2[j]
return new_matrix
def transpose(matrix):
transposed_matrix = []
[transposed_matrix.append([0.0 for i in range(len(matrix))]) for j in range(len(matrix[0]))]
for column_index in range(len(matrix[0])):
temp_list = []
for row_index in range(len(matrix)):
temp_list.append(matrix[row_index][column_index])
transposed_matrix[column_index] = temp_list
return transposed_matrix
def equal_matrices(matrix1, matrix2):
for i in range(len(matrix1)):
for j in range(len(matrix1)):
if matrix1[i][j] != matrix2[i][j]:
return False
return True
def vector_magnitude(vector):
magnitude = 0
for i in range(len(vector)):
magnitude += vector[i]*vector[i]
return sqrt(magnitude) | true |
1d01e9cb6f4f3adf89e057b56211711ee99e616a | Python | szes/data_visual | /random_walk/random_walk.py | UTF-8 | 1,425 | 3.5625 | 4 | [] | no_license | # -*- coding=utf-8 -*-
# add by gaozhi
import random
class RandomWalk(object):
"""一个生成随机漫步数据的类"""
def __init__(self, num_point=5000):
"""初始化随机漫步的属性"""
self.num_point = num_point
# 所以随机漫步都始于(0, 0)
self.x_values = [0]
self.y_values = [0]
def get_step(self):
direction = random.choice([1,-1])
distance = random.choice([1,2,3,4])
return direction * distance
def fill_walk(self):
"""计算随机漫步包含的所有坐标点"""
# 不断漫步,直到生成所有的坐标点
while len(self.x_values) < self.num_point:
# 计算X轴下一个坐标点的方向及距离
# x_direction = random.choice([1,-1])
# x_distance = random.choice([1,2,3,4])
# x_step = x_direction * x_distance
x_step = self.get_step()
# 计算X轴下一个坐标点的方向及距离
# y_direction = random.choice([1,-1])
# y_distance = random.choice([1,2,3,4])
# y_step = y_direction * y_distance
y_step = self.get_step()
if x_step ==0 and y_step == 0:
continue
# 计算下一个点的X值和Y值
self.x_values.append(self.x_values[-1] + x_step)
self.y_values.append(self.y_values[-1] + y_step)
| true |
62ed08af841e0b95c8b6b4c9d777f1a98cf9dffe | Python | future1111/GraphGallery | /graphgallery/gallery/gallery_model/tensorflow/densegcn.py | UTF-8 | 4,924 | 2.828125 | 3 | [
"MIT"
] | permissive | import tensorflow as tf
from graphgallery.gallery import GalleryModel
from graphgallery.sequence import FullBatchSequence
from graphgallery.nn.models.pytorch import GCN as pyGCN
from graphgallery.nn.models.tensorflow import DenseGCN as tfGCN
from graphgallery import functional as gf
class DenseGCN(GalleryModel):
"""
Implementation of Dense version of Graph Convolutional Networks (GCN).
`[`Semi-Supervised Classification with Graph Convolutional Networks <https://arxiv.org/abs/1609.02907>`
Tensorflow 1.x `Sparse version` implementation: <https://github.com/tkipf/gcn>
Pytorch `Sparse version` implementation: <https://github.com/tkipf/pygcn>
"""
def __init__(self,
graph,
adj_transform="normalize_adj",
attr_transform=None,
graph_transform=None,
device="cpu",
seed=None,
name=None,
**kwargs):
r"""Create a Dense Graph Convolutional Networks (DenseGCN) model.
This can be instantiated in the following way:
model = DenseGCN(graph)
with a `graphgallery.data.Graph` instance representing
A sparse, attributed, labeled graph.
Parameters:
----------
graph: An instance of `graphgallery.data.Graph`.
A sparse, attributed, labeled graph.
adj_transform: string, `transform`, or None. optional
How to transform the adjacency matrix. See `graphgallery.functional`
(default: :obj:`'normalize_adj'` with normalize rate `-0.5`.
i.e., math:: \hat{A} = D^{-\frac{1}{2}} A D^{-\frac{1}{2}})
attr_transform: string, `transform`, or None. optional
How to transform the node attribute matrix. See `graphgallery.functional`
(default :obj: `None`)
graph_transform: string, `transform` or None. optional
How to transform the graph, by default None.
device: string. optional
The device where the model is running on.
You can specified ``CPU``, ``GPU`` or ``cuda``
for the model. (default: :str: `cpu`, i.e., running on the `CPU`)
seed: interger scalar. optional
Used in combination with `tf.random.set_seed` & `np.random.seed`
& `random.seed` to create a reproducible sequence of tensors across
multiple calls. (default :obj: `None`, i.e., using random seed)
name: string. optional
Specified name for the model. (default: :str: `class.__name__`)
kwargs: other custom keyword parameters.
"""
super().__init__(graph, device=device, seed=seed, name=name,
adj_transform=adj_transform,
attr_transform=attr_transform,
graph_transform=graph_transform,
**kwargs)
self.process()
def process_step(self):
graph = self.transform.graph_transform(self.graph)
adj_matrix = self.transform.adj_transform(graph.adj_matrix).toarray()
node_attr = self.transform.attr_transform(graph.node_attr)
X, A = gf.astensors(node_attr, adj_matrix, device=self.device)
# ``A`` and ``X`` are cached for later use
self.register_cache("X", X)
self.register_cache("A", A)
# use decorator to make sure all list arguments have the same length
@gf.equal()
def build(self,
hiddens=[16],
activations=['relu'],
dropout=0.5,
weight_decay=5e-4,
lr=0.01,
use_bias=False):
if self.backend == "tensorflow":
with tf.device(self.device):
self.model = tfGCN(self.graph.num_node_attrs,
self.graph.num_node_classes,
hiddens=hiddens,
activations=activations,
dropout=dropout,
weight_decay=weight_decay,
lr=lr,
use_bias=use_bias)
else:
self.model = pyGCN(self.graph.num_node_attrs,
self.graph.num_node_classes,
hiddens=hiddens,
activations=activations,
dropout=dropout,
weight_decay=weight_decay,
lr=lr,
use_bias=use_bias).to(self.device)
def train_sequence(self, index):
labels = self.graph.node_label[index]
sequence = FullBatchSequence(
[self.cache.X, self.cache.A, index],
labels,
device=self.device)
return sequence
| true |
776f335d8913b046b0f4a4273319a8e7605c94dd | Python | pedrolucas27/exercising-python | /list03/exer_09.py | UTF-8 | 371 | 4.3125 | 4 | [
"MIT"
] | permissive | #Faça um programa que receba dois números inteiros e gere os números inteiros
# que estão no intervalo compreendido por eles.
n1 = int(input("Informe um número:"))
n2 = int(input("Informe outro número:"))
if n1 < n2:
for i in range(n1+1,n2):
print(i)
elif n1 > n2:
for i in range(n1-1,n2,-1):
print(i)
else:
print("Número iguais !!!") | true |
f5b8364e5d789f0fb20eff54d668ddafe3fc3191 | Python | raysmith619/Introduction-To-Programming | /exercises/turtle/from_others/turtle_keypress_move.py | UTF-8 | 1,662 | 4.40625 | 4 | [] | no_license | # Turtle Animation using Screen Events - Arrow Keys.
# From: https://softwareprogramming4kids.com/turtle-animation/
import turtle
screen = turtle.Screen()
screen.setup(320,320) # Set screen size.
screen.tracer(0) # Stop animation until frame is completed.
screen.title('TURTLE ANIMATION USING ARROW KEYS')
trtl = turtle.Turtle()
trtl.hideturtle() # We do not want to see the turtle image on the screen.
trtl.color("blue")
# Initialize variables.
x, y, x_step, y_step = 0, 0, 10, 10 # Initialize global variables.
def next_frame():
trtl.clear() # Clear the screen before each next frame.
# x-step and y_step are the pexels the image moves at each key press.
trtl.penup()
trtl.goto(x, y)
trtl.pendown()
trtl.dot(100) # Draw a black dot of radius = 20
screen.ontimer(next_frame, 10) # Call next_frame 10 msec later
screen.update()
###### DEFINE KEY PRESS EVENT HANDLER FUNCTIONS ######
def move_left():
global x
print('left arrow key pressed')
x = x - x_step
def move_right():
global x
print('right arrow key pressed')
x = x + x_step
def move_down():
global y
print('down arrow key pressed')
y = y - y_step
def move_up():
global y
print('up arrow key pressed')
y = y + y_step
###### BIND EVENTS TO THE FOUR ARROW KEYS ######
screen.onkey(move_left, 'Left') # Left arrow key bind to handler 'move_left'.
screen.onkey(move_right, 'Right')
screen.onkey(move_down, 'Down')
screen.onkey(move_up, 'Up')
###### CALL next-frame() FUNCTION ######
next_frame()
screen.listen() # Check if key is pressed
screen.mainloop()
| true |
937ca7898a165dc03a6e928ccfd38f6a721a1380 | Python | aditi0330/Codecademy-Python-for-Data-Science | /Data Visualisation/Different_plot_types.py | UTF-8 | 2,950 | 3.484375 | 3 | [] | no_license | #Simple Bar Chart
from matplotlib import pyplot as plt
drinks = ["cappuccino", "latte", "chai", "americano", "mocha", "espresso"]
sales = [91, 76, 56, 66, 52, 27]
plt.bar(range(len(drinks)), sales)
ax = plt.subplot()
ax.set_xticks(range(len(drinks)))
ax.set_xticklabels(drinks)
plt.show()
#Side by side bars
from matplotlib import pyplot as plt
drinks = ["cappuccino", "latte", "chai", "americano", "mocha", "espresso"]
sales1 = [91, 76, 56, 66, 52, 27]
sales2 = [65, 82, 36, 68, 38, 40]
n = 1 # This is our first dataset (out of 2)
t = 2 # Number of datasets
d = 6 # Number of sets of bars
w = 0.8 # Width of each bar
store1_x = [t*element + w*n for element in range(d)]
plt.bar(store1_x, sales1)
n = 2 # This is our second dataset (out of 2)
t = 2 # Number of datasets
d = 6 # Number of sets of bars
w = 0.8 # Width of each bar
store2_x = [t*element + w*n for element in range(d)]
plt.bar(store2_x, sales2)
plt.show()
#Stacked bars
drinks = ["cappuccino", "latte", "chai", "americano", "mocha", "espresso"]
sales1 = [91, 76, 56, 66, 52, 27]
sales2 = [65, 82, 36, 68, 38, 40]
plt.bar(range(len(drinks)), sales1)
plt.bar(range(len(drinks)), sales2, bottom = sales1)
plt.legend(['Location 1', 'Location 2'])
plt.show()
#Error Bars
drinks = ["cappuccino", "latte", "chai", "americano", "mocha", "espresso"]
ounces_of_milk = [6, 9, 4, 0, 9, 0]
error = [0.6, 0.9, 0.4, 0, 0.9, 0]
plt.bar(range(len(drinks)), ounces_of_milk, yerr = error, capsize = 5 )
plt.show()
#Fill Between
from matplotlib import pyplot as plt
months = range(12)
month_names = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
revenue = [16000, 14000, 17500, 19500, 21500, 21500, 22000, 23000, 20000, 19500, 18000, 16500]
ax = plt.subplot()
ax.set_xticks(months)
ax.set_xticklabels(month_names)
y_lower = [i - 0.1*i for i in revenue]
y_upper = [i + 0.1*i for i in revenue]
plt.fill_between(months, revenue, y_lower, y_upper, alpha = 0.2)
plt.plot(months, revenue)
plt.show()
#Pie Chart
from matplotlib import pyplot as plt
import numpy as np
payment_method_names = ["Card Swipe", "Cash", "Apple Pay", "Other"]
payment_method_freqs = [270, 77, 32, 11]
plt.pie(payment_method_freqs)
plt.axis('equal')
plt.show()
#Pie Chart Labelling
payment_method_names = ["Card Swipe", "Cash", "Apple Pay", "Other"]
payment_method_freqs = [270, 77, 32, 11]
plt.pie(payment_method_freqs, autopct = '%0.1f%%')
plt.legend(payment_method_names)
plt.axis('equal')
plt.show()
#Histogram
from matplotlib import pyplot as plt
from script import sales_times
plt.hist(sales_times, bins =20)
plt.show()
#Multiple Histograms
from matplotlib import pyplot as plt
from script import sales_times1
from script import sales_times2
plt.hist(sales_times1, bins=20, alpha = 0.4, normed=True)
plt.hist(sales_times2, bins=20, alpha = 0.4, normed=True)
plt.show() | true |
40947c350a09b47afa062d017d2d0a52a7aeb6eb | Python | andreaskami/Multi-Agent_GPS_Planning_Tool | /utility/path_search.py | UTF-8 | 2,373 | 3.484375 | 3 | [] | no_license | import heapq as hq
from utility.misc import distance
def a_star_search(grid, start, goal, max_dist):
"""
Performs A* search on a grid, from start to goal.
start and goal should be of the Node object type (see utility/grid.py)
If start is more than max_dist away from the goal, the path is not considered and an empty route is returned.
"""
open_nodes = [] # list of open nodes with f_costs - is a priority queue implemented with heapq
open_nodes_searchmap = {} # parallel dict to open_nodes for faster searching using a hashmap
start.g = 0
start.f = _heuristic(start, goal)
if start.f > max_dist:
return [], max_dist
hq.heappush(open_nodes, (start.f, start.hash, start))
open_nodes_searchmap[start.hash] = True
while open_nodes:
_, _, current_node = hq.heappop(open_nodes)
open_nodes_searchmap[current_node.hash] = False
if current_node == goal:
return _construct_path(current_node) # goal found
neighbours = [grid.node_at_index(*n) for n in current_node.neighbours]
for n, neighbour in enumerate(neighbours):
temp_g = _heuristic(current_node, neighbour, neighbour_dist=True, neighbour_idx=n)
if temp_g < neighbour.g:
neighbour.parent = current_node
neighbour.g = temp_g
neighbour.f = _heuristic(neighbour, goal)
if not open_nodes_searchmap.get(start.hash, False):
hq.heappush(open_nodes, (neighbour.f, neighbour.hash, neighbour))
open_nodes_searchmap[neighbour.hash] = True
# print("A* search failed to find a path to the goal location.")
return [], max_dist
def _heuristic(node, other_node, neighbour_dist=False, neighbour_idx=0):
"""Heuristic utility function for A* search."""
if neighbour_dist:
return node.g + node.dists[neighbour_idx]
else:
return node.g + distance(node.real_pos, other_node.real_pos)
def _construct_path(current_node):
"""Constructs the resulting path by retracing parent nodes. Returns a list of index pairs."""
path = [(current_node.x, current_node.y)]
length = current_node.g
while current_node.parent is not None:
current_node = current_node.parent
path.insert(0, (current_node.x, current_node.y))
return path, length
| true |
082a16be1c45ac82a947a0642ee964042e65f360 | Python | TolarianNinja/bagoftricks | /ddate.py | UTF-8 | 6,439 | 3.140625 | 3 | [] | no_license | import datetime
# ddate.py Prints the current date of the Discordian Calendar and any
# Holydays/Whollydays of that date to the console.
# Date can be edited by changing current_date variable
# Written by Alex Hartshorn
current_date = datetime.datetime.now() # Today
#current_date = datetime.datetime(2005, 3, 19) # Mojoday
#current_date = datetime.datetime(2005, 1, 10) # Backwards Day
#current_date = datetime.datetime(2018, 12, 16) # St. Melvin's Day
#current_date = datetime.datetime(2018, 12, 31) # End of Year/Last day of Aftermath
# Return the day name
def day_name(num):
day_names = {
1: "Sweetmorn",
2: "Boomtime",
3: "Pungenday",
4: "Prickle-Prickle",
0: "Setting Orange"
}
return day_names.get(num, "NaD")
# Return the season name
def season_name(num):
season_names = {
1: "Chaos",
2: "Discord",
3: "Confusion",
4: "Bureaucracy",
5: "The Aftermath"
}
return season_names.get(num, "NaS")
# Return the post-number based on date
def num_post(num):
if num < 13:
num_p = num % 13
else:
num_p = num % 10
num_posts = {
1: "st",
2: "nd",
3: "rd"
}
return num_posts.get(num_p, "th")
# Return the name of the current Holyday, or False if it isn't one
def get_holyday(season_num, season_day):
if season_num == 1:
chao_days = {
5: "Mungday",
50: "Chaoflux",
}
return chao_days.get(season_day, False)
elif season_num == 2:
discord_days = {
5: "Mojoday",
50: "Discoflux",
}
return discord_days.get(season_day, False)
elif season_num == 3:
confusion_days = {
5: "Syaday",
50: "Confuflux",
}
return confusion_days.get(season_day, False)
elif season_num == 4:
bureaucracy_days = {
5: "Zaraday",
50: "Bureflux",
}
return bureaucracy_days.get(season_day, False)
elif season_num == 5:
aftermath_days = {
5: "Maladay",
50: "Afflux",
}
return aftermath_days.get(season_day, False)
else:
return False
# Return the name of the current Whollyday, or False if it isn't one
# Whollyday list found at http://discordia.wikia.com/wiki/Whollyday
# with additions by the Honorable Pope Akavien
def get_whollyday(season_num, season_day):
if season_num == 1:
chao_days = {
1: "Nude Year's Day",
10: "demrofeR, yaD sdrawkcaB",
18: "Pat Pineapple Day",
21: "Hug Day",
26: "lanoitidarT, yaD sdrawkcaB",
46: "Springfield Day",
49: "The Mary Day",
51: "Pet Loving Day",
69: "Head Chicken Day"
}
return chao_days.get(season_day, False)
elif season_num == 2:
discord_days = {
11: "Discordians for Jesus/Love Your Neighbor Day",
18: "Amateur's Day",
19: "St. John the Blasphemist's Day",
23: "Jake Day",
32: "Universal Ordination Day",
70: "Jake Day Jr.",
72: "Towel Day"
}
return discord_days.get(season_day, False)
elif season_num == 3:
confusion_days = {
11: "537 Day",
15: "Mad Hatter Day",
20: "Doomed TV Seriews Rememberance Day",
26: "Captain Tuttle Day",
28: "St. George's Day",
37: "Mid Year's Day",
55: "Mal-2 Day",
57: "John Dillinger Day"
}
return confusion_days.get(season_day, False)
elif season_num == 4:
bureaucracy_days = {
3: "Multiversal Underwear Day",
18: "Festival of Hanky-Panky Spankies",
33: "Pussyfoot Day",
37: "Mass of Planet Eris",
55: "Feats of St. John the Blasphemist",
57: "Shamlicht Kids Club Day",
59: "Gonkulator Day",
60: "Mad Hatter Day",
66: "Habeas Corpus Rememberance Day"
}
return bureaucracy_days.get(season_day, False)
elif season_num == 5:
aftermath_days = {
28: "Ek-sen-triks CluborGuild Day",
36: "Spanking Fest",
37: "537 Day",
46: "Hug Day II",
58: "St. Melvin's Day",
67: "Giftmas",
72: "New Year's Eve Eve"
}
return aftermath_days.get(season_day, False)
else:
return False
def ddate(current_date):
date_num = int(current_date.strftime("%j"))
# Account for February 29
if current_date.year % 400 == 0 or (current_date.year % 4 == 0 and current_date.year % 100 != 0):
if current_date.month > 2:
date_num = int(current_date.strftime("%j")) - 1
season_num = (date_num / 74) + 1 # Each season is 73 days long (offset for 1-5)
season_day = date_num % 73 # Which day of the season it is
date_day = (date_num % 5) # Which day of the week it is
year_num = int(current_date.strftime("%Y")) + 1166 # Current year in YOLD format
# Account for the last day of each season
if season_day == 0:
season_day = 73
dday_name = day_name(date_day)
dd_season_name = season_name(season_num)
season_post = num_post(season_day)
holyday = get_holyday(season_num, season_day)
whollyday = get_whollyday(season_num, season_day)
# Check if it is St Tib's Day, else print in standard format
if current_date.month == 2 and current_date.day == 29:
print("Today is {}, St Tib's Day, {} YOLD.".format(dday_name, year_num))
else:
print("Today is {}, the {}{} day of {}, YOLD {}.".format(
dday_name, season_day, season_post, dd_season_name, year_num))
# If it is a holyday or whollyday, print which day it is.
if holyday != False:
print("Today is the holyday of {}!".format(holyday))
if whollyday != False:
print("Today is the whollyday of {}!".format(whollyday))
ddate(current_date)
| true |
32fc9e94ce17520402bc3cece0292f1a11afbe88 | Python | NevilleMthw/library-system | /bookReturn.py | UTF-8 | 786 | 3.796875 | 4 | [
"MIT"
] | permissive | from database import Database
class ReturnBook:
"""
This class returns the result with the bookID,
thereby checking the bookID entry and performing the respective functions.
"""
def __init__(self) -> None:
"""Initializing the database class to use the functions from that python module."""
self.Database = Database()
def returns(self, book_id_entry: str) -> str:
"""
This function checks whether the bookID entered is right for the return.
@param book_id_entry: Will take the BookID input.
"""
return_result = self.Database.book_Return(book_id_entry)
if book_id_entry == return_result:
print("This works")
if __name__ == "__main__":
R_BOOK = ReturnBook()
R_BOOK.returns()
| true |
cde6bb33df361411d0c7e374334480371ee6fa77 | Python | mmascher/WMCore | /src/python/Utils/IterTools.py | UTF-8 | 677 | 3.421875 | 3 | [] | no_license | #! /usr/bin/env python
from __future__ import division, print_function
from itertools import islice
from itertools import chain
def grouper(iterable, n):
"""
:param iterable: List of other iterable to slice
:type: iterable
:param n: Chunk size for resulting lists
:type: int
:return: iterator of the sliced list
Source: http://stackoverflow.com/questions/3992735/python-generator-that-groups-another-iterable-into-groups-of-n
"""
iterable = iter(iterable)
return iter(lambda: list(islice(iterable, n)), [])
def flattenList(doubleList):
"""
Make flat a list of lists.
"""
return list(chain.from_iterable(doubleList))
| true |
cfbb904bd5d2eb954bce5766edee77208351f965 | Python | CedricKen/Python-GUI | /Images/MAGE 1/IMAGE.py | UTF-8 | 279 | 2.796875 | 3 | [] | no_license | from tkinter import *
from tkinter import ttk
root = Tk()
calculator = ttk.Button(root, text="CALCULATOR")
calculator.grid(row=0, column=0)
logo = PhotoImage(file="calculator.PNG").subsample(5, 5)
calculator.configure(image=logo, compound=BOTTOM)
root.mainloop()
| true |
58318632c7fd74718eea20a41442ceae6707af75 | Python | hpl002/erlingPython | /del_3.py | UTF-8 | 820 | 3.765625 | 4 | [] | no_license | # du kan definere flere hjelpefunksjoner om du trenger dem
def print_diamond(N): # ikke endre den linjen
print('Tall:', N)
if int(N) > 0:
for i in range(int(N)):
for m in range (int(N) - i):
print(" ", end="")
for j in range((i * 2) - 1):
print("X", end="")
print()
for i in range(int(N), 0, -1):
for m in range (int(N) - i):
print(" ", end="")
for j in range((i * 2) - 1):
print("X", end="")
print()
# ikke endre noe nedenfor
if __name__ == "__main__":
print_diamond(25)
print()
print_diamond(2)
print()
print_diamond(3)
print()
print_diamond(4)
print()
print_diamond(10)
| true |
012926ab251cec2f59bf19a563dd58f9ad6057c4 | Python | panzerkampfy/fastapi-test | /src/workshop/tables.py | UTF-8 | 648 | 2.625 | 3 | [] | no_license | from sqlalchemy import Column, Integer, Date, String, Float, Text, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
email = Column(Text, unique=True)
username = Column(Text, unique=True)
password = Column(Text)
class Operation(Base):
__tablename__ = 'operations'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.id'))
date = Column(Date)
kind = Column(String)
amount = Column(Float(10, 2))
description = Column(String, nullable=True)
| true |
eff5ca3e2bd5bf70792f9d6336c883156eb2bb55 | Python | delphix/delphixpy-examples | /lib/GetReferences.py | UTF-8 | 9,856 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | """
Module that provides lookups of references and names of Delphix objects.
"""
import re
from datetime import datetime
from dateutil import tz
from delphixpy.v1_8_0.exceptions import HttpError
from delphixpy.v1_8_0.exceptions import JobError
from delphixpy.v1_8_0.exceptions import RequestError
from delphixpy.v1_8_0.web import database
from delphixpy.v1_8_0.web import job
from delphixpy.v1_8_0.web import repository
from delphixpy.v1_8_0.web import source
from delphixpy.v1_8_0.web import sourceconfig
from delphixpy.v1_8_0.web.service import time
from .DlpxException import DlpxException
from .DxLogging import print_debug
from .DxLogging import print_exception
VERSION = "v.0.2.0019"
def convert_timestamp(engine, timestamp):
"""
Convert timezone from Zulu/UTC to the Engine's timezone
engine: A Delphix engine session object.
timestamp: the timstamp in Zulu/UTC to be converted
"""
default_tz = tz.gettz("UTC")
engine_tz = time.time.get(engine)
try:
convert_tz = tz.gettz(engine_tz.system_time_zone)
utc = datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S")
utc = utc.replace(tzinfo=default_tz)
converted_tz = utc.astimezone(convert_tz)
engine_local_tz = "{} {} {}".format(
str(converted_tz.date()),
str(converted_tz.time()),
str(converted_tz.tzname()),
)
return engine_local_tz
except TypeError:
return None
def find_all_objects(engine, f_class):
"""
Return all objects from a given class
engine: A Delphix engine session object
f_class: The objects class. I.E. database or timeflow.
:return: List of objects
"""
return_lst = []
try:
return f_class.get_all(engine)
except (JobError, HttpError) as e:
raise DlpxException(
"{} Error encountered in {}: {}\n".format(engine.address, f_class, e)
)
def find_obj_specs(engine, obj_lst):
"""
Function to find objects for replication
engine: Delphix Virtualization session object
obj_lst: List of names for replication
:return: List of references for the given object names
"""
rep_lst = []
for obj in obj_lst:
rep_lst.append(find_obj_by_name(engine, database, obj).reference)
return rep_lst
def get_running_job(engine, target_ref):
"""
Function to find a running job from the DB target reference.
:param engine: A Virtualization engine session object
:param target_ref: Reference to the target of the running job
:return:
"""
return job.get_all(engine, target=target_ref, job_state="RUNNING")[0].reference
def find_obj_list(obj_lst, obj_name):
"""
Function to find an object in a list of objects
obj_lst: List containing objects from the get_all() method
obj_name: Name of the object to match
:return: The named object. None is returned if no match is found.`
"""
for obj in obj_lst:
if obj_name == obj.name:
return obj
return None
def find_obj_by_name(engine, f_class, obj_name, active_branch=False):
"""
Function to find objects by name and object class, and return object's
reference as a string
engine: A Delphix engine session object
f_class: The objects class. I.E. database or timeflow.
obj_name: The name of the object
active_branch: Default = False. If true, return list containing
the object's reference and active_branch. Otherwise, return
the reference.
"""
return_list = []
try:
all_objs = f_class.get_all(engine)
except AttributeError as e:
raise DlpxException(
"Could not find reference for object class" "{}.\n".format(e)
)
for obj in all_objs:
if obj.name == obj_name:
if active_branch is False:
return obj
# This code is for JS objects only.
elif active_branch is True:
return_list.append(obj.reference)
return_list.append(obj.active_branch)
return return_list
return obj
# If the object isn't found, raise an exception.
raise DlpxException(
"{} was not found on engine {}.\n".format(obj_name, engine.address)
)
def find_source_by_dbname(engine, f_class, obj_name, active_branch=False):
"""
Function to find sources by database name and object class, and return object's
reference as a string
engine: A Delphix engine session object
f_class: The objects class. I.E. database or timeflow.
obj_name: The name of the database object in Delphix
active_branch: Default = False. If true, return list containing
the object's reference and active_branch. Otherwise, return
the reference.
"""
return_list = []
try:
all_objs = f_class.get_all(engine)
except AttributeError as e:
raise DlpxException(
"Could not find reference for object class" "{}.\n".format(e)
)
for obj in all_objs:
if obj.name == obj_name:
print_debug("object: {}\n\n".format(obj))
print_debug(obj.name)
print_debug(obj.reference)
source_obj = source.get_all(engine, database=obj.reference)
print_debug("source: {}\n\n".format(source_obj))
return source_obj[0]
# If the object isn't found, raise an exception.
raise DlpxException(
"{} was not found on engine {}.\n".format(obj_name, engine.address)
)
def get_obj_reference(engine, obj_type, obj_name, search_str=None, container=False):
"""
Return the reference for the provided object name
engine: A Delphix engine object.
results: List containing object name
search_str (optional): string to search within results list
container (optional): search for container instead of name
"""
ret_lst = []
results = obj_type.get_all(engine)
for result in results:
if container is False:
if result.name == obj_name:
ret_lst.append(result.reference)
if search_str:
if re.search(search_str, result.reference, re.IGNORECASE):
ret_lst.append(True)
else:
ret_lst.append(False)
return ret_lst
else:
if result.container == obj_name:
ret_lst.append(result.reference)
return ret_lst
raise DlpxException("Reference not found for {}".format(obj_name))
def find_obj_name(engine, f_class, obj_reference):
"""
Return the obj name from obj_reference
engine: A Delphix engine object.
f_class: The objects class. I.E. database or timeflow.
obj_reference: The object reference to retrieve the name
"""
try:
obj_name = f_class.get(engine, obj_reference)
return obj_name.name
except RequestError as e:
raise DlpxException(e)
except (JobError, HttpError) as e:
raise DlpxException(e.message)
def find_dbrepo(engine, install_type, f_environment_ref, f_install_path):
"""
Function to find database repository objects by environment reference and
install path, and return the object's reference as a string
You might use this function to find Oracle and PostGreSQL database repos.
engine: Virtualization Engine Session object
install_type: Type of install - Oracle, ASE, SQL
f_environment_ref: Reference of the environment for the repository
f_install_path: Path to the installation directory.
return: delphixpy.web.vo.SourceRepository object
"""
print_debug(
"Searching objects in the %s class for one with the "
"environment reference of %s and an install path of %s"
% (install_type, f_environment_ref, f_install_path)
)
# import pdb;pdb.set_trace()
all_objs = repository.get_all(engine, environment=f_environment_ref)
for obj in all_objs:
if "OracleInstall" == install_type:
if obj.type == install_type and obj.installation_home == f_install_path:
print_debug("Found a match %s".format(obj.reference))
return obj
elif "MSSqlInstance" == install_type:
if obj.type == install_type and obj.instance_name == f_install_path:
print_debug("Found a match {}".format(obj.reference))
return obj
else:
raise DlpxException(
"No Repo match found for type {}.\n".format(install_type)
)
def find_sourceconfig(engine, sourceconfig_name, f_environment_ref):
"""
Function to find database sourceconfig objects by environment reference and
sourceconfig name (db name), and return the object's reference as a string
You might use this function to find Oracle and PostGreSQL database
sourceconfigs.
engine: Virtualization Engine Session object
sourceconfig_name: Name of source config, usually name of db
instnace (ie. orcl)
f_environment_ref: Reference of the environment for the repository
return: delphixpy.web.vo.SourceConfig object
"""
print_debug(
"Searching objects in the SourceConfig class for one with the "
"environment reference of %s and a name of %s"
% (f_environment_ref, sourceconfig_name)
)
all_objs = sourceconfig.get_all(engine, environment=f_environment_ref)
for obj in all_objs:
if obj.name == sourceconfig_name:
print_debug("Found a match %s".format(obj.reference))
return obj
else:
raise DlpxException(
"No sourceconfig match found for type {}."
"\n".format(sourceconfig_name)
)
| true |
aa4c6c12c1ecbd3aa78bd9d2b46049406247a3a9 | Python | jwg4/t-tetromino | /writing/five.py | UTF-8 | 400 | 3.0625 | 3 | [] | no_license | from drawings import preamble, postamble, draw_cropped_square, draw_tetromino, draw_square
if __name__ == '__main__':
preamble()
draw_cropped_square(0, 0, 5)
tetrominos = [(0.5, 3.5, 3), (2.5, 4.5, 0), (2.5, 1.5, 1), (3.5, 1.5, 3), (4.5, 3.5, 1)]
for x, y, t in tetrominos:
draw_tetromino(x, y, t)
draw_square(1, 2, extras=['pattern = north east lines'])
postamble()
| true |
e4fad8ca54b742e191c2798dc8006f4fdfc7f0e4 | Python | cboopen/algorithm004-04 | /Week 02/id_069/LeetCode-169-069.py | UTF-8 | 397 | 3.375 | 3 | [] | no_license | #20191027
"""
暴力解法:计数
"""
class Solution:
def majorityElement(self, nums):
numdict = {}
for num in nums:
if num not in numdict:
numdict[num] = 1
else:
numdict[num] += 1
return max(numdict.keys(), key=numdict.get)
s = Solution()
print(s.majorityElement([1,1,1,1,2,3,4,5,6])) | true |
586e496cd45f2a26b46f38d0f2593f7e81113bb1 | Python | cao-cp/remote-management | /obey_command.py | UTF-8 | 313 | 2.75 | 3 | [] | no_license | import os
class boeyCommand():
def __init__(self):
pass
def obey(self,command):
if command.split(":")[0] == "cmd":
result = os.popen(command.split(":")[1]).read()
return result
else:
return "Sorry I can't understand what you want"
| true |
822fb782cb61c0238192854c4aae417e23aa80d7 | Python | AlecS19/EECS504_Project_F20 | /dataCreation.py | UTF-8 | 931 | 2.578125 | 3 | [] | no_license | import cv2
import os
import pandas as pd
import numpy as np
def load_images_from_folder(folder):
images = []
labels = []
for filename in os.listdir(folder):
img = cv2.imread(os.path.join(folder,filename))
if img is not None:
images.append(img)
labels.append(ord(filename[0]) -97)
return images, labels
folder="testImages"
imgs, labels= load_images_from_folder(folder)
col = pd.read_csv('/home/alecsoc/Desktop/mygit/EECS504_Project_F20/sign_mnist_test.csv').columns
data1 = pd.read_csv('/home/alecsoc/Desktop/mygit/EECS504_Project_F20/sign_mnist_test.csv')
data = np.zeros((len(imgs), 28*28+1))
for i in range(len(imgs)):
gray = cv2.cvtColor(imgs[i], cv2.COLOR_BGR2GRAY)
grayF = gray.reshape((1,28*28))
data[i,:] = np.insert(grayF,0,labels[i])
newData = pd.DataFrame(data,columns = col)
data2 = data1.append(newData)
data2.to_csv('AlecData.csv',index =False)
| true |
35e534ab0b0af634cabc4aa358c9df75fab58887 | Python | qinyanjuidavid/Self-Learning | /CreatingModules.py | UTF-8 | 478 | 3.25 | 3 | [] | no_license | #Check the script myFunctions in the folder named myDirectory
from myDirectory import myFunctions
# import myDirectory.myFunctions #Another way of importing scripts
#import myDirectory.myFunctions as func #Another alternative
#from myDirectory import myFunctions as func #Alternative
import myModule
print("Add:",myModule.add(2,3))
print("Multiplication:",myModule.Multipy(2,3))
#Files from a different folder
print(myFunctions.Divide(6,2))
print(myFunctions.Substraction(6,2)) | true |
d4af7da28286b15de0a4da931cbf8a7564dff28d | Python | Brandsatz/Audio-Video-Programmierung | /Hausaufgaben/Projekt/Python/test.py | UTF-8 | 2,253 | 2.625 | 3 | [] | no_license | import rtmidi
import mido
import cv2
import numpy as np
import time
# midiOutput = mido.open_output("IAC-Treiber Bus 1")
midiOutput = mido.open_output("LoopBe Internal MIDI 1")
name = mido.get_input_names()
print(name)
# inport = mido.open_input('IAC-Treiber Bus 1')
inport = mido.open_input('LoopBe Internal MIDI 0')
msg = inport.receive()
def sendNoteOn(farbe, position):
message = mido.Message('note_on', note = farbe, velocity = position)
midiOutput.send(message)
print(message)
if(msg):
sendNoteOn(5,1)
sendNoteOn(1,2)
sendNoteOn(2,3)
sendNoteOn(3,4)
sendNoteOn(4,5)
sendNoteOn(4,6)
sendNoteOn(3,7)
sendNoteOn(2,8)
def do_nothing():
return
cap = cv2.VideoCapture(0)
cv2.namedWindow("Video")
cv2.createTrackbar("Blau", "Video", 30, 55, do_nothing)
cv2.createTrackbar("Gruen", "Video", 30, 55, do_nothing)
cv2.createTrackbar("Rot", "Video", 30, 55, do_nothing)
blauWert = 0
gruenWert = 0
rotWert = 0
while cap.isOpened():
ret, frame = cap.read()
b, g, r = cv2.split(frame)
b_Threshold = cv2.getTrackbarPos("Blau", "Video")
g_Threshold = cv2.getTrackbarPos("Gruen", "Video")
r_Threshold = cv2.getTrackbarPos("Rot", "Video")
b_Mask = cv2.inRange(b, blauWert-b_Threshold, blauWert+b_Threshold)
g_Mask = cv2.inRange(g, gruenWert-g_Threshold, gruenWert+g_Threshold)
r_Mask = cv2.inRange(r, rotWert-r_Threshold, rotWert+r_Threshold)
mask = r_Mask * g_Mask * b_Mask
contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
maxArea = 0
#groesste schwarze Flaeche
for index in range(len(contours)):
area = cv2.contourArea(contours[index])
if area > maxArea:
maxArea = area
i = index
M = cv2.moments(contours[i])
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
x,y,w,h = cv2.boundingRect(contours[i])
cv2.rectangle(frame,(x,y),(x+w,y+h),(10,10,10),2)
cv2.putText(frame, "X: {0} Y: {1} ".format(cx,cy), (cx, cy), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 200, 0), 1)
cv2.imshow('Video', mask)
if cv2.waitKey(25) != -1:
break
print("Message recieved")
print(msg)
cap.release()
cv2.destroyAllWindows()
| true |
f6c4eedfcd0848d8ffdaf41be0e9dcf062e2deea | Python | rinkeyrahman/EUC_ST_ML | /machine_learning/attribute.py | UTF-8 | 12,332 | 2.765625 | 3 | [] | no_license | from __future__ import print_function
import scipy.stats as stats
from scipy.stats import chisquare
from scipy.stats import pearsonr
import pymysql
import pandas as pd
import numpy as np
import json
import sys
import config as cfg
SIGNIFICANCE_LEVEL=0.05
class Attribute:
"""
This class maintains procedure of collecting user intention,
dataset selection.
Parameters
----------
dataset: dict
dataset information
output_attr : string
name of output attribute
attr_list : list
list of selected attributes for training data set
attr_no : int
total number of selected attributes for training data set
x_type : string
data type of output attribute
"""
def __init__(self):
self.dataset={ "Dataset_name": "",
"Type": "",
"Attribute_characteristics":"",
"Number_of_instances":"",
"Number_of_attributes":"",
"Missing_value":""
}
self.output_attr=""
self.attr_list=[]
self.attr_no=0
def connect_database(self):
"""
connect database according to selected domain.
:return: cursor, database name and table name
"""
self.db_name=cfg.user["Domain"][0]
self.tb_name=cfg.user["Domain"][1]
db = pymysql.connect(cfg.mysql['host'],cfg.mysql['user'],cfg.mysql['password'],db=self.db_name)
cursor = db.cursor()
return cursor,self.db_name,self.tb_name
def get_attribute_correlation(self,X,X_type,Y,Y_type,unique_value_x,unique_value_y):
"""
determine correlation between output (X) and other attributes (Y) using three statistical methods.
:return: p value
"""
if(X_type=="categorical" and Y_type=="categorical"):
if(unique_value_x==unique_value_y):
print("Chisquare test...",file=sys.stderr)
X_num=np.unique(X,return_counts=True)
Y_num=np.unique(Y,return_counts=True)
#print(X_num,Y_num, file=sys.stderr)
print("Calculating p value...",file=sys.stderr)
n=chisquare(X_num[1],Y_num[1])
self.s=n[1]
else:
self.s=0
elif(X_type=="quantitative" and Y_type=="quantitative"):
print("Pearson's correlation...",file=sys.stderr)
n=pearsonr(X,Y)
print("Calculating p value...",file=sys.stderr)
self.s=n[1]
else:
if(X_type=="categorical"):
n=np.unique(X,return_counts=True)
data1=X
data2=Y
else:
n=np.unique(Y,return_counts=True)
data1=Y
data2=X
#print(n,file=sys.stderr)
var1=[]
var2=[]
print("One way analysis of variance...",file=sys.stderr)
for i in range(len(data2)):
if(n[0][1]==data1[i]):
var1.append(data2[i])
elif(n[0][2]==data1[i]):
var2.append(data2[i])
print("Calculating p value...",file=sys.stderr)
n=stats.f_oneway(var1,var2)
self.s=n[1]
print("p value: ",self.s,file=sys.stderr)
return self.s
def determine_learning_problem(self):
"""
determine whether the learning problem is supervised or unsupervised.
:return: p value
"""
self.x_type=""
cursor,self.db_name,self.tb_name=self.connect_database()
col="SHOW COLUMNS from %s"%(self.tb_name)
cursor.execute(col)
self.res=cursor.fetchall()
keyword=[]
s_num=cfg.user["Number_of_service"]
for index in range(0,s_num):
t=cfg.user["Services"][index]["Conditional_keywords"]
keyword.append(t)
print(keyword,file=sys.stderr)
self.all_col={}
print("Determining whether the learning problem is supervised or unsupervised",file=sys.stderr)
l=len(keyword)-1
for i in range(0,len(self.res)):
col_name=self.res[i][0]
self.all_col[col_name]=i
print(col_name,file=sys.stderr)
search="SELECT %s from %s WHERE "%(col_name,self.tb_name)
for j in range(len(keyword)):
if(j==l):
search+="%s LIKE "%(col_name)
search+= "'%"
search+="%s"%(keyword[j])
search+="%'"
else:
search+="%s LIKE "%(col_name)
search+= "'%"
search+="%s"%(keyword[j])
search+="%' OR "
cursor.execute(search)
r=cursor.fetchall()
if(r is not None):
self.x_type=cfg.attr_info["Attribute_info"][i]["Type"]
self.output_attr=col_name
self.output=1
else:
self.output=0
Attribute.x_type=self.x_type
Attribute.output_attr=self.output_attr
return self.output
def supervised_attribute_set(self):
"""
compare attribute set for supervised training data selection.
:return:
"""
self.x=[]
self.d_type={}
self.score={}
cursor,self.db_name,self.tb_name=self.connect_database()
print("The learning problem is supervised",file=sys.stderr)
#type checking
q="SELECT COUNT( DISTINCT %s )FROM %s"%(self.output_attr,self.tb_name)
cursor.execute(q)
unique_value=cursor.fetchall()
self.unique_value_x=unique_value[0][0]
Attribute.unique_value_x=self.unique_value_x
value="SELECT %s from %s "%(self.output_attr,self.tb_name)
cursor.execute(value)
row=cursor.fetchall()
for i in range(len(row)):
t=row[i][0]
self.x.append(t)
x_init=pd.Series(self.x)
type=x_init.dtype.name
if(type=="object"):
a=np.array(self.x)
a_enc = pd.factorize(a)
self.x=a_enc[0]
print("Selecting training data set for machine learning...",file=sys.stderr)
for i in range(0,len(self.res)):
self.y=[]
col_name=self.res[i][0]
q="SELECT %s FROM %s"%(col_name,self.tb_name)
cursor.execute(q)
row=cursor.fetchall()
for j in range(len(row)):
t=row[j][0]
self.y.append(t)
y_init=pd.Series(self.y)
type=y_init.dtype.name
if(type=="object"):
a=np.array(self.y)
a_enc = pd.factorize(a)
self.y=a_enc[0]
self.y_type=cfg.attr_info["Attribute_info"][i]["Type"]
if(self.output==1):
if(col_name is not self.output_attr):
print("Determining correlation between...",file=sys.stderr)
print(col_name,"and",self.output_attr,file=sys.stderr)
self.d_type[col_name]=self.y_type
p="SELECT COUNT( DISTINCT %s )FROM %s"%(col_name,self.tb_name)
cursor.execute(p)
unique_value=cursor.fetchall()
self.unique_value_y=unique_value[0][0]
self.score[col_name]=self.get_attribute_correlation(self.x,self.x_type,self.y,self.y_type,self.unique_value_x,self.unique_value_y)
def unsupervised_attribute_set(self):
"""
compare attribute set for unsupervised training data selection.
:return:
"""
self.x=[]
self.d_type={}
self.score={}
cursor,self.db_name,self.tb_name=self.connect_database()
print("The learning problem is unsupervised",file=sys.stderr)
sensor_data=cfg.user["Sensor_name"]
sensor_data=sensor_data.replace(' ','_')
q="SELECT COUNT( DISTINCT %s )FROM %s"%(self.output_attr,self.tb_name)
cursor.execute(q)
unique_value=cursor.fetchall()
self.unique_value_x=unique_value[0][0]
Attribute.unique_value_x=self.unique_value_x
value="SELECT %s from %s "%(sensor_data,self.tb_name)
cursor.execute(value)
row=cursor.fetchall()
for i in range(len(row)):
t=row[i][0]
self.x.append(t)
x_init=pd.Series(self.x)
type=x_init.dtype.name
id=self.all_col[sensor_data]
self.x_type=cfg.attr_info["Attribute_info"][id]["Type"]
if(type=="object"):
a=np.array(self.x)
a_enc = pd.factorize(a)
self.x=a_enc[0]
print("Selecting training data set for machine learning...",file=sys.stderr)
for i in range(0,len(self.res)):
self.y=[]
col_name=self.res[i][0]
q="SELECT %s FROM %s"%(col_name,self.tb_name)
cursor.execute(q)
row=cursor.fetchall()
for j in range(len(row)):
t=row[j][0]
self.y.append(t)
y_init=pd.Series(self.y)
type=y_init.dtype.name
if(type=="object"):
a=np.array(self.y)
a_enc = pd.factorize(a)
self.y=a_enc[0]
self.y_type=cfg.attr_info["Attribute_info"][i]["Type"]
if(col_name is not sensor_data):
print("Determining correlation between...",file=sys.stderr)
print(col_name,"and",sensor_data,file=sys.stderr)
self.d_type[col_name]=self.y_type
p="SELECT COUNT( DISTINCT %s )FROM %s"%(col_name,self.tb_name)
cursor.execute(p)
unique_value=cursor.fetchall()
self.unique_value_y=unique_value[0][0]
self.score[col_name]=self.get_attribute_correlation(self.x,self.x_type,self.y,self.y_type,self.unique_value_x,self.unique_value_y)
def generate_attribute_set(self):
"""
select training dataset by comparing p value with significance level.
:return:
"""
cursor,self.db_name,self.tb_name=self.connect_database()
count=0
Attribute.attr_dtype_list=[]
select="SELECT "
for key in self.score:
count=count+1
if(self.score[key]>=SIGNIFICANCE_LEVEL):
self.attr_no=self.attr_no+1
self.attr_list.append(key)
Attribute.attr_dtype_list.append(self.d_type[key])
select+="%s,"%key
last_key=key
select+="%s from %s "%(last_key,self.tb_name)
print(select, file=sys.stderr)
cursor.execute(select)
s_res=cursor.fetchall()
Attribute.attr_list=self.attr_list
Attribute.attr_no=self.attr_no
print("Selected attribute set: ",Attribute.attr_list, file=sys.stderr)
def dataset_information(self):
"""
generate selected data set information.
:return: data set information.
"""
cursor,self.db_name,self.tb_name=self.connect_database()
#dataset info
self.dataset["Dataset_name"]=self.tb_name
self.dataset["Type"]=self.db_name
cat=0
qn=0
for i in range(len(Attribute.attr_dtype_list)):
if(Attribute.attr_dtype_list[i]=="categorical"):
cat=1
elif(Attribute.attr_dtype_list[i]=="quantitative"):
qn=1
if(cat==1 and qn==1):
self.dataset["Attribute_characteristics"]=["categorical","quantitative"]
elif(cat==1 and qn==0):
self.dataset["Attribute_characteristics"]=["categorical"]
else:
self.dataset["Attribute_characteristics"]=["quantitative"]
q1="SELECT count(*) from %s"%self.tb_name
cursor.execute(q1)
i_res=cursor.fetchall()
self.dataset["Number_of_instances"]=i_res[0][0]
#self.dataset["Number_of_attributes"]=len(self.res)
self.dataset["Missing_value"]=0
with open('info/selected_dataset_info.json', 'w') as f:
json.dump(self.dataset,f)
return self.dataset
def xtype(self):
"""
:return: output attribute data type.
"""
return Attribute.x_type
def unique_x(self):
"""
:return: unique values of output attribute(x).
"""
return Attribute.unique_value_x
def attribute_info(self):
"""
:return: output attribute name, selected training attribute list, number of selected attribute.
"""
return Attribute.output_attr,Attribute.attr_no,Attribute.attr_list
def database_info(self):
"""
collect database information.
:return: database information.
"""
cursor,self.db_name,self.tb_name=self.connect_database()
return self.db_name,self.tb_name
| true |
331e649b2853b890dbd10e8c2dc6ae33818d0906 | Python | jukent/GeoCAT-examples | /Gallery/Contours/NCL_polar_1.py | UTF-8 | 4,190 | 2.921875 | 3 | [
"Apache-2.0"
] | permissive | """
NCL_polar_1.py
==============
This script illustrates the following concepts:
- Drawing black-and-white contours over a polar stereographic map
- Drawing the northern hemisphere of a polar stereographic map
See following URLs to see the reproduced NCL plot & script:
- Original NCL script: https://www.ncl.ucar.edu/Applications/Scripts/polar_1.ncl
- Original NCL plot: https://www.ncl.ucar.edu/Applications/Images/polar_1_lg.png
"""
###############################################################################
# Import packages:
import numpy as np
import xarray as xr
import cartopy.feature as cfeature
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import geocat.datafiles as gdf
import geocat.viz as gv
###############################################################################
# Read in data:
# Open a netCDF data file using xarray default engine and load the data into xarrays
ds = xr.open_dataset(gdf.get("netcdf_files/uv300.nc"))
U = ds.U[1, :, :]
###############################################################################
# Fix the artifact of not-shown-data around 0 and 360-degree longitudes
wrap_U = gv.xr_add_cyclic_longitudes(U, "lon")
###############################################################################
# Plot:
# Generate axes, using Cartopy, drawing coastlines, and adding features
fig = plt.figure(figsize=(10, 10))
projection = ccrs.NorthPolarStereo()
ax = plt.axes(projection=projection)
ax.add_feature(cfeature.LAND, facecolor='lightgray')
# Set map boundary to include latitudes between 0 and 40 and longitudes
# between -180 and 180 only
gv.set_map_boundary(ax, [-180, 180], [0, 40], south_pad=1)
# Set draw_labels to False so that you can manually manipulate it later
gl = ax.gridlines(ccrs.PlateCarree(),
draw_labels=False,
linestyle="--",
color='black')
# Manipulate latitude and longitude gridline numbers and spacing
gl.ylocator = mticker.FixedLocator(np.arange(0, 90, 15))
gl.xlocator = mticker.FixedLocator(np.arange(-180, 180, 30))
# Manipulate longitude labels (0, 30 E, 60 E, ..., 30 W, etc.)
ticks = np.arange(0, 210, 30)
etick = ['0'] + [
r'%dE' % tick for tick in ticks if (tick != 0) & (tick != 180)
] + ['180']
wtick = [r'%dW' % tick for tick in ticks[::-1] if (tick != 0) & (tick != 180)]
labels = etick + wtick
xticks = np.arange(0, 360, 30)
yticks = np.full_like(xticks, -5) # Latitude where the labels will be drawn
for xtick, ytick, label in zip(xticks, yticks, labels):
if label == '180':
ax.text(xtick,
ytick,
label,
fontsize=14,
horizontalalignment='center',
verticalalignment='top',
transform=ccrs.Geodetic())
elif label == '0':
ax.text(xtick,
ytick,
label,
fontsize=14,
horizontalalignment='center',
verticalalignment='bottom',
transform=ccrs.Geodetic())
else:
ax.text(xtick,
ytick,
label,
fontsize=14,
horizontalalignment='center',
verticalalignment='center',
transform=ccrs.Geodetic())
# Contour-plot U-data
p = wrap_U.plot.contour(ax=ax,
vmin=-8,
vmax=16,
transform=ccrs.PlateCarree(),
levels=np.arange(-12, 44, 4),
linewidths=0.5,
cmap='black',
add_labels=False)
ax.clabel(p, np.arange(-8, 17, 8), fmt='%d', inline=1, fontsize=14)
# Use geocat.viz.util convenience function to add left and right titles
gv.set_titles_and_labels(ax, lefttitle="Zonal Wind", righttitle="m/s")
# Add lower text box
ax.text(1.0,
-.10,
"CONTOUR FROM -12 TO 40 BY 4",
horizontalalignment='right',
transform=ax.transAxes,
bbox=dict(boxstyle='square, pad=0.25',
facecolor='white',
edgecolor='black'))
# Show the plot
plt.show()
| true |
83c32d88883eaf95ccd79150139564f08bf6293a | Python | ghlee0304/tensorflow-basic-and-advanced | /Basic/lab01-4_linear_regression_compute_gradient.py | UTF-8 | 2,163 | 2.84375 | 3 | [] | no_license | import tensorflow as tf
import load_data
def create_weight_variable(shape):
W = tf.get_variable(name = 'W', shape = shape, dtype = tf.float32, initializer= tf.truncated_normal_initializer())
b = tf.get_variable(name = 'b', shape = shape, dtype = tf.float32, initializer= tf.constant_initializer(0.0))
return W, b
NPOINTS = 1000
TOTAL_EPOCH = 1000
dataX, dataY = load_data.generate_data_for_linear_regression(NPOINTS)
tf.set_random_seed(0)
X = tf.placeholder(shape = [None, 1], dtype = tf.float32, name = 'X')
Y = tf.placeholder(shape = [None, 1], dtype = tf.float32, name = 'Y')
W, b = create_weight_variable([1])
hypothesis = tf.nn.bias_add(tf.multiply(X, W), b, name = 'hypothesis')
loss = tf.reduce_mean(tf.square(Y-hypothesis), name = 'loss')
optim = tf.train.GradientDescentOptimizer(learning_rate = 0.001)
grads = optim.compute_gradients(loss)
apply_gradients = optim.apply_gradients(grads)
#it is equal to tf.train.GradientDescentOptimizer(learning_rate = 0.001).minimize(loss)
grads_and_vars_list = [[_grad, _var] for _grad, _var in grads]
'''
for grads_and_vars in grads:
print(grads_and_vars)
(<tf.Tensor 'gradients/Mul_grad/tuple/control_dependency_1:0' shape=(1,) dtype=float32>, <tf.Variable 'W:0' shape=(1,) dtype=float32_ref>)
(<tf.Tensor 'gradients/hypothesis_grad/tuple/control_dependency_1:0' shape=(1,) dtype=float32>, <tf.Variable 'b:0' shape=(1,) dtype=float32_ref>)
'''
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)
for epoch in range(TOTAL_EPOCH):
l, _ = sess.run([loss, apply_gradients], feed_dict={X: dataX, Y: dataY})
if (epoch+1) %100 == 0:
print("Epoch [{:3d}/{:3d}], loss = {:.6f}".format(epoch + 1, TOTAL_EPOCH, l))
'''
Epoch [100/1000], loss = 0.174033
Epoch [200/1000], loss = 0.118036
Epoch [300/1000], loss = 0.080456
Epoch [400/1000], loss = 0.055220
Epoch [500/1000], loss = 0.038261
Epoch [600/1000], loss = 0.026852
Epoch [700/1000], loss = 0.019166
Epoch [800/1000], loss = 0.013979
Epoch [900/1000], loss = 0.010470
Epoch [1000/1000], loss = 0.008087
'''
| true |
3e27a3c18794112cad1617f6acc79ac5e9eb4cbf | Python | johnsonpk/School-work | /325CSC/3Homework/hw2_funcs.py | UTF-8 | 4,911 | 3.671875 | 4 | [] | no_license | ############################
# Name: Pablo Johnson
# Class: CSC 325 - Adv. Data Structures and Algorithms
# Assignment: Implementation of KMP Algorithm
# Due: Oct 31, 2017 (Spooky)
############################
import time, sys
# Time to compare speed of algorithms
# Sys to read from stdin
# I'm going to refrain from adding more comments since these
# algorithms were provided
def compute_kmp_fail(P):
# Utility that computes and returns KMP 'fail' list.
m = len(P)
fail = [0] * m # by default, presume overlap of 0 everywhere
j = 1
k = 0
while j < m: # compute f(j) durint this pass, if nonzero
if P[j] == P[k]: # k + 1 characters match thus far
fail[j] = k + 1
j += 1
k += 1
elif k > 0: # k follows a matching prefix
k = fail[k-1]
else: # no match found starting at j
j += 1
return fail
def find_fmp(T,P):
# Return the lowest index of T at which substring begins (or else -1)
n, m = len(T), len(P) # introduce convenient notations
if m == 0: return 0 # trivial search for empty string
fail = compute_kmp_fail(P) # rely on utility to precompute
j = 0 # index into text
k = 0 # index into pattern
while j < n:
if T[j] == P[k]: # P[0:1 + k] matched thus far
if k == m - 1: # match is complete
return j - m + 1
j += 1 # try to extend match
k += 1
elif k > 0:
k = fail[k-1] # reuse suffix of P[0:k]
else:
j += 1
return -1 # reached end without match
def find_boyer_moore(T, P):
# Return the lowest index of T at which substring P begins ( or else -1)
n, m = len(T), len(P) # introduce convenient notations
if m == 0: return 0 # trivial search for empty string
last = {} # build 'last' dictionary
for k in range(m):
last[ P[k]] = k # later occurrence overwrites
# align end of pattern at index m - 1 of text
i = m - 1 # an index into T
k = m - 1 # an index into P
while i < n:
if T[i] == P[k]: # a matching character
if k == 0:
return i # pattern begins at index i of text
else:
i -= 1 # examine previous character
k -= 1 # of both T and P
else:
j = last.get(T[i], -1) # last(T[i]) is -1 if not found
i += m - min(k, j+ 1) # case analysis for jump step
k = m - 1 # restart at end of pattern
return -1
# Set up array containing text to search
# Initialize array
i1 = []
for line in sys.stdin:
i1.append(line.lower()) # We want the input to all be lowercase
pattern_file = open('pattern.in', 'r') # We will read our pattern from pattern.in
pattern = pattern_file.read() # Read the pattern to search for
pattern = pattern.rstrip() # We need to strip any whitespace...
pattern = pattern.lower() # ... but also make our pattern lowercase
pattern_file.close() # close file we are reading from
# Print out the pattern we are searching for
print("Pattern from pattern.in file is: {}\n".format(pattern))
# Time to search using the boyer moore algorithm!
print('boyer_moore')
# We need a global variable so we can check whether our last search was successful
# outside of the for loop
index = 0
# Save our current time in time1
time1 = time.time()
# For each line in our text
for x in range(len(i1)):
# Make sure index is our global one
global index
index = find_boyer_moore(i1[x], pattern)
# If we get a match, print out some info about what was found
if (index != -1):
time1 = time.time() - time1
print("Pattern found at line {} character {} !".format(x, index))
print("It took {} sec to find this pattern!".format(time1))
print("Line {}:".format(x))
print(i1[x])
break
# Because we use break to exit our for loop, we need a global index variable
if index == -1: print("Pattern not found!")
# Time to search using the fmp algorithm!
# Same logic as boyer_moore. No need to recomment
print('fmp')
time1 = time.time()
for x in range(len(i1)):
index = find_fmp(i1[x], pattern)
if (index != -1):
time1 = time.time() - time1
print("Pattern found at line {} character {} !".format(x, index))
print("It took {} sec to find this pattern!".format(time1))
print("Line {}:".format(x))
print(i1[x])
break
if index == -1: print("Pattern not found!")
| true |
9818450deb81e7d40306d5b0473906101acf0e19 | Python | tomboxfan/PythonExample | /loop/WhileExample.py | UTF-8 | 254 | 3.84375 | 4 | [] | no_license | c = 5
while c != 0:
print(c)
c-=1
c=5
while c:
print(c)
c-=1
while True:
response = input() # input() 从Console 获得输入
if int(response) % 7 == 0:
break
else:
print(response, "is not a multiple of 7!") | true |
90bc3b6949c8daa08b93b7f0ea249e7e9e071353 | Python | taufanlubis/mycode | /python/nesting-statement.py | UTF-8 | 212 | 3.515625 | 4 | [] | no_license | thing="fruit"
fruit="mango"
if thing=="fruit":
if fruit=="apple":
print 'this fruit is apple'
else:
print 'this is fruit but i don\'t know what it is'
else:
print 'this is not fruit'
| true |
1c17616b89a0d8a5d487f80d794e67c8e11d9032 | Python | beboxos/ArduinoThings | /picoRGB/backupPicoRGB/random.py | UTF-8 | 571 | 2.625 | 3 | [] | no_license | from rgbkeypad import RgbKeypad
import time
import random
keypad = RgbKeypad()
keys = keypad.keys
delais = 0.1
while True:
keypad.update()
i = random.randint(0,15)
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
keys[i].set_led(r,g,b)
time.sleep(delais)
if keys[3].pressed:
if delais>0.1:
delais=delais-0.1
if keys[15].pressed:
if delais<1:
delais=delais+0.1
if keys[0].pressed:
for i in range(0,16):
keys[i].set_led(0,0,0)
break | true |
97bc4d0aabd93b65d7c1877568df7c78cdace82b | Python | molchiro/AtCoder | /エクサウィザーズ2019/C.py | UTF-8 | 1,114 | 3.359375 | 3 | [] | no_license | def check_alive(n):
p = n
for spell in spells:
if spell[0] == s[p]:
p += 1 if spell[1] == 'R' else -1
if p == -1:
return 'L'
elif p == N:
return 'R'
return 'OK'
N, Q = list(map(int, input().split()))
s = [x for x in input()]
spells = [input().split() for i in range(Q)]
def __main__():
if check_alive(0) == 'R':
print(0)
return
elif check_alive(0) == 'OK':
left_alive = 0
else:
a, b = 0, N-1
while b - a > 1:
m = round((b+a)/2)
if check_alive(m) == 'L':
a = m
else:
b = m
left_alive = b
if check_alive(N-1) == 'L':
print(0)
return
elif check_alive(N-1) == 'OK':
right_alive = N-1
else:
a, b = 0, N-1
while b - a > 1:
m = round((b+a)/2)
if check_alive(m) == 'R':
b = m
else:
a = m
right_alive = a
print(right_alive - left_alive + 1)
if __name__ == "__main__":
__main__()
| true |
ff30351f93c8d1ca919245ad5e7e598b353d6585 | Python | Gosols/ohkete-teht-v-t | /postitoimipaikka.py | UTF-8 | 357 | 2.515625 | 3 | [] | no_license | import urllib.request as r
import json
url = r.urlopen(
"https://raw.githubusercontent.com/theikkila/postinumerot/master/postcode_map_light.json")
html = url.read()
postitoimipaikat = json.loads(html)
postinumero = input("Kirjoita postinumero: ")
print("")
for key in postitoimipaikat:
if key == postinumero:
print(postitoimipaikat[key])
| true |
0c3bcb6d3f3ea33f257b558db553c7d49bfe00d8 | Python | danilomo/PyLernkarten | /pylernkarten/workspace.py | UTF-8 | 1,388 | 2.796875 | 3 | [] | no_license | import sys
import pylernkarten.words as words
import pylernkarten.decks as decks
from pylernkarten.commands import command, parse_command
def workspace():
if sys.argv[1:]:
return sys.argv[1]
else:
return "workspace.txt"
def save_nouns(f):
for noun in words.feminine():
f.write("n die " + noun + "\n")
for noun in words.masculine():
f.write("n der " + noun + "\n")
for noun in words.neutral():
f.write("n das " + noun + "\n")
def save_meanings(f):
for k, v in words.meanings():
#ms = ('"%s"' % s for s in v)
f.write('addmeaning %s "%s"\n' % (k, v))
def save_plurals(f):
for k, v in words.plurals():
f.write('pl %s %s\n' % (k, v))
def save_decks(f):
for k, v in decks.items():
save_deck(f, k, v)
def save_deck(f, name, deck):
f.write("createdeck " + name + "\n")
for word in deck:
f.write("add " + word + "\n")
f.write("closedeck\n")
def save_workspace():
with open( workspace(), "w") as f:
save_nouns(f)
save_meanings(f)
save_decks(f)
save_plurals(f)
def load_workspace():
try:
with open(workspace()) as f:
for line in f:
comm = line.strip()
parse_command(comm)()
except:
pass
@command
def saveworkspace():
save_workspace()
| true |
b4aa318d2bbdd590d2853d346c46dfa5f081b7a1 | Python | 0xHendry/EulerProjectSolution | /Task001.py | UTF-8 | 123 | 3.28125 | 3 | [] | no_license |
i = 0
array = []
while i < 999:
i += 1
if (i % 3) == 0 or (i % 5) == 0:
array.append(i)
print(sum(array))
| true |
4cad2268990c9e58b0ae2677f7c68f657bbf1d74 | Python | johanarangel/condicionales_python | /ejercicios_practica.py | UTF-8 | 9,993 | 4.8125 | 5 | [] | no_license | #!/usr/bin/env python
'''
Condicionales [Python]
Ejercicios de práctica
---------------------------
Autor: Johana Rangel
Version: 1.3
Descripcion:
Programa creado para que practiquen los conocimietos adquiridos durante la semana
'''
__author__ = "Johana Rangel"
__email__ = "johanarang@hotmail.com"
__version__ = "1.2"
def ej1():
print('Ejercicios de práctica con números')
'''
Realice un programa que solicite por consola 2 números
Calcule la diferencia entre ellos e informe por pantalla
si el resultado es positivo, negativo o cero.
'''
numero_1 = float(input('Ingrese el primer número:\n'))
numero_2 = float(input('Ingrese el segundo número:\n'))
resultado = numero_1 - numero_2
if resultado == 0:
print('El resultado de la diferencia entre {} y {} es igual a cero'.format(numero_1, numero_2))
elif resultado > 0:
print('El resultado de la diferencia entre {} y {} es positivo'.format(numero_1, numero_2))
else:
print('El resultado de la diferencia entre {} y {} es negativo'.format(numero_1, numero_2))
def ej2():
print('Ejercicios de práctica con números')
'''
Realice un programa que solicite el ingreso de tres números
enteros, y luego en cada caso informe si el número es par
o impar.
Para cada caso imprimir el resultado en pantalla.
'''
entero_1 = int(input('Ingrese primer número entero:\n'))
entero_2 = int(input('Ingrese segundo número entero:\n'))
entero_3 = int(input('Ingrese tercer número entero:\n'))
if (entero_1 % 2 == 0):
print('El número {} es par'.format(entero_1))
else:
print('El número {} es impar'.format(entero_1))
if (entero_2 % 2 == 0):
print('El número {} es par'.format(entero_2))
else:
print('El número {} es impar'.format(entero_2))
if (entero_3 % 2 == 0):
print('El número {} es par'.format(entero_3))
else:
print('El número {} es impar'.format(entero_3))
def ej3():
print('Ejercicios de práctica con números')
'''
Realice una calculadora, se ingresará por línea de comando dos números
Luego se ingresará como tercera entrada al programa el símbolo de la operación
que se desea ejecutar
- Suma (+)
- Resta (-)
- Multiplicación (*)
- División (/)
- Exponente/Potencia (**)
Se debe efectuar el cálculo correcto según la operación ingresada por consola
Imprimir en pantalla la operación realizada y el resultado
'''
numero_uno = float(input('Ingrese un número: \n'))
numero_dos = float(input('Ingrese otro número: \n'))
simbolo_operacion = str(input('''Ingrese el simbolo de la operación a realizar (+ suma, - resta, * multiplicación, / división, **Potencia ): \n'''))
if (simbolo_operacion == '+'):
resultado = numero_uno + numero_dos
print('El resultado de sumar {} y {} es {}'.format(numero_uno, numero_dos, resultado))
elif (simbolo_operacion == '-'):
resultado = numero_uno - numero_dos
print('El resultado de restar {} y {} es {}'.format(numero_uno, numero_dos, resultado))
elif (simbolo_operacion == '*'):
resultado = numero_uno * numero_dos
print('El resultado de multiplicar {} y {} es {}'.format(numero_uno, numero_dos, resultado))
elif (simbolo_operacion == '/'):
resultado = numero_uno / numero_dos
print('El resultado de dividir {} y {} es {}'.format(numero_uno, numero_dos, resultado))
elif (simbolo_operacion == '**'):
resultado = numero_uno ** numero_dos
print('El resultado de {} a la potencia {} es {}'.format(numero_uno, numero_dos, resultado))
else:
print('Simbolo no corresponde con los indicados')
def ej4():
print('Ejercicios de práctica con cadenas')
'''
Realice un programa que solicite por consola 3 palabras cualesquiera
Luego el programa debe consultar al usuario como quiere ordenar las palabras
1 - Ordenar por orden alfabético (usando el operador ">")
2 - Ordenar por cantidad de letras (longitud de la palabra)
Si se ingresa "1" por consola se deben ordenar las 3 palabras por orden alfabético
e imprimir en pantalla de la mayor a la menor
Si se ingresa "2" por consola se deben ordenar las 3 palabras por cantidad de letras
e imprimir en pantalla de la mayor a la menor
'''
palabra_1 = str(input('Ingrese la primera palabra: \n'))
palabra_2 = str(input('Ingrese la segunda palabra: \n'))
palabra_3 = str(input('Ingrese la tercera palabra: \n'))
consulta = str(input('Cómo quiere ordenar la palabras? \n Ingrese 1, si quiere ordenar por alfabético. \n Ingrese 2, si quiere ordenar por cantidad de palabras?: \n'))
if consulta == '1':
if palabra_1 > palabra_2 > palabra_3:
print('Palabras de mayor a menor, por orden alfabético: {}, {}, {}'.format(palabra_1, palabra_2, palabra_3))
elif palabra_2 > palabra_3 > palabra_1:
print('Palabras de mayor a menor, por orden alfabético: {}, {}, {}'.format(palabra_2, palabra_3, palabra_1))
elif palabra_3 > palabra_1 > palabra_2:
print('Palabras de mayor a menor, por orden alfabético: {}, {}, {}'.format(palabra_3, palabra_1, palabra_2))
elif palabra_1 > palabra_3 > palabra_2:
print('Palabras de mayor a menor, por orden alfabético: {}, {}, {}'.format(palabra_1, palabra_3, palabra_2))
elif palabra_2 > palabra_1 > palabra_3:
print('Palabras de mayor a menor, por orden alfabético: {}, {}, {}'.format(palabra_2, palabra_1, palabra_3))
else:
print('Palabras de mayor a menor, por orden alfabético: {}, {}, {}'.format(palabra_3, palabra_2, palabra_1))
if consulta == '2':
if len(palabra_1) > len(palabra_2) > len(palabra_3):
print('Palabras de mayor a menor, por cantidad de palabras: {}, {}, {}'.format(palabra_1, palabra_2, palabra_3))
elif len(palabra_2) > len(palabra_3) > len(palabra_1):
print('Palabras de mayor a menor, por cantidad de palabras: {}, {}, {}'.format(palabra_2, palabra_3, palabra_1))
elif len(palabra_3) > len(palabra_1) > len(palabra_2):
print('Palabras de mayor a menor, por cantidad de palabras: {}, {}, {}'.format(palabra_3, palabra_1, palabra_2))
elif len(palabra_1) > len(palabra_3) > len(palabra_2):
print('Palabras de mayor a menor, por cantidad de palabras: {}, {}, {}'.format(palabra_1, palabra_3, palabra_2))
elif len(palabra_2) > len(palabra_1) > len(palabra_3):
print('Palabras de mayor a menor, por cantidad de palabras: {}, {}, {}'.format(palabra_2, palabra_1, palabra_3))
else:
print('Palabras de mayor a menor, por cantidad de palabras: {}, {}, {}'.format(palabra_3, palabra_2, palabra_1))
def ej5():
print('Ejercicios de práctica con números')
'''
Realice un programa que solicite ingresar tres valores de temperatura
De las temperaturas ingresadas por consola determinar:
1 - ¿Cuáles de ellas es la máxima temperatura ingresada?
2 - ¿Cuáles de ellas es la mínima temperatura ingresada?
3 - ¿Cuál es el promedio de las temperaturas ingresadas?
En cada caso imprimir en pantalla el resultado
'''
temperatura_1 = float(input('Ingrese el primer valor de temperatura: \n'))
temperatura_2 = float(input('Ingrese el segundo valor de temperatura: \n'))
temperatura_3 = float(input('Ingrese el tercer valor de temperatura: \n'))
promedio = (temperatura_1 + temperatura_2 + temperatura_3)/3
if temperatura_1 > temperatura_2 > temperatura_3:
print('La máxima temperatura es {}'.format(temperatura_1))
print('La mínima temperatura es {}'.format(temperatura_3))
print('El promedio de las temperaturas {}, {}, {} es {}'.format(temperatura_1, temperatura_2, temperatura_3, round(promedio,2)))
elif temperatura_2 > temperatura_3 > temperatura_1:
print('La máxima temperatura es {}'.format(temperatura_2))
print('La mínima temperatura es {}'.format(temperatura_1))
print('El promedio de las temperaturas {}, {}, {} es {}'.format(temperatura_1, temperatura_2, temperatura_3, round(promedio,2)))
elif temperatura_3 > temperatura_1 > temperatura_2:
print('La máxima temperatura es {}'.format(temperatura_3))
print('La mínima temperatura es {}'.format(temperatura_2))
print('El promedio de las temperaturas {}, {}, {} es {}'.format(temperatura_1, temperatura_2, temperatura_3, round(promedio,2)))
elif temperatura_1 > temperatura_3 > temperatura_2:
print('La máxima temperatura es {}'.format(temperatura_1))
print('La mínima temperatura es {}'.format(temperatura_2))
print('El promedio de las temperaturas {}, {}, {} es {}'.format(temperatura_1, temperatura_2, temperatura_3, round(promedio,2)))
elif temperatura_2 > temperatura_1 > temperatura_3:
print('La máxima temperatura es {}'.format(temperatura_2))
print('La mínima temperatura es {}'.format(temperatura_3))
print('El promedio de las temperaturas {}, {}, {} es {}'.format(temperatura_1, temperatura_2, temperatura_3, round(promedio,2)))
else:
print('La máxima temperatura es {}'.format(temperatura_3))
print('La mínima temperatura es {}'.format(temperatura_1))
print('El promedio de las temperaturas {}, {}, {} es {}'.format(temperatura_1, temperatura_2, temperatura_3, round(promedio,2)))
if __name__ == '__main__':
print("Ejercicios de práctica")
ej1()
#ej2()
#ej3()
#ej4()
#ej5()
| true |
6346a26dfe4e269af1280adf01f929d81850ca4d | Python | KaranJaswani/Codes | /LeetCode-Python/376. Wiggle Subsequence.py | UTF-8 | 1,475 | 3.28125 | 3 | [] | no_license | class Solution(object):
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) <= 1:
return len(nums)
res = 1
lastDifference = False
lastNumber = nums[1]
start = 1
for i in range(1, len(nums)):
if nums[i] != nums[0]:
res += 1
if nums[i] - nums[0] > 0:
lastDifference = True
lastNumber = nums[i]
start = i + 1
break
for i in range(start, len(nums)):
if lastDifference:
if nums[i] - lastNumber >= 0:
lastNumber = max(nums[i], lastNumber)
else:
res += 1
lastDifference = False
lastNumber = nums[i]
else:
if nums[i] - lastNumber <= 0:
lastNumber = min(nums[i], lastNumber)
else:
res += 1
lastDifference = True
lastNumber = nums[i]
return res
obj = Solution()
obj.wiggleMaxLength([33,53,12,64,50,41,45,21,97,35,47,92,39,0,93,55,40,46,69,42,6,95,51,68,72,9,32,84,34,64,6,2,26,98,3,43,30,60,3,68,82,9,97,19,27,98,99,4,30,96,37,9,78,43,64,4,65,30,84,90,87,64,18,50,60,1,40,32,48,50,76,100,57,29,63,53,46,57,93,98,42,80,82,9,41,55,69,84,82,79,30,79,18,97,67,23,52,38,74,15]) | true |
7f53ab8b8fd16e4f88422f9eccdc2cbbe78b641e | Python | manishym/algorithms_in_python | /myTurtle.py | UTF-8 | 349 | 3.34375 | 3 | [] | no_license | #!/usr/local/bin/env python
import turtle
myTurtle = turtle.Turtle()
myCanvas = turtle.Screen()
def draw_spiral(mt, lineLen):
if lineLen > 0:
mt.forward(lineLen)
mt.right(90)
draw_spiral(mt, lineLen - 5)
def main():
draw_spiral(myTurtle, 200)
myCanvas.exitonclick()
if __name__ == '__main__':
main()
| true |
92632996d5fb1fd915ffe773fb27d0653ce693f2 | Python | KirillMysnik/SP-UniShop | /srcds/addons/source-python/packages/custom/unishop/items.py | UTF-8 | 1,673 | 2.515625 | 3 | [] | no_license | # =============================================================================
# >> IMPORTS
# =============================================================================
# UniShop
from .engine import unishop_engine
from .plugins import UniShopPlugin
# =============================================================================
# >> CLASSES
# =============================================================================
class ItemClass:
items_consumed_per_use = 1
def __init__(self, unishop_plugin, id_, lang_strings):
if not isinstance(unishop_plugin, UniShopPlugin):
raise ValueError("'unishop_pluign' argument must be a "
"valid UniShopPlugin instance")
self.unishop_plugin = unishop_plugin
self.id = id_
self.lang_strings = lang_strings
unishop_plugin.register_item_class(id_, self)
def get_item_icon(self, item):
return '/'.join((
self.unishop_plugin.plugin_name, "icons", item.subclass + ".png"))
def can_item_be_used(self, item):
return True
def on_item_created(self, item, creation_token):
pass
def on_item_deleted(self, item_id):
pass
def on_item_bought_from_shop(self, item, shop_client, price):
pass
def on_item_used(self, item):
item.quantity -= self.items_consumed_per_use
def create_item(self, subclass_id):
if not unishop_engine.available:
raise RuntimeError("UniShop Engine is not loaded")
creation_token = unishop_engine.create_item(
self.unishop_plugin.plugin_name, self.id, subclass_id)
return creation_token
| true |
43724c85e66c456c0608cdb034cc05a04a337467 | Python | delovoy70/gkbrns | /2_csv.py | UTF-8 | 2,466 | 3.03125 | 3 | [] | no_license | import csv
import re
def getdata(list_of_files):
regex_prod = r'Изготовитель системы:' + '' '+'
regex_name = r'Название ОС:' + '' '+'
regex_code = r'Код продукта:' + '' '+'
regex_type = r'Тип системы:' + '' '+'
main_data = [['Изготовитель системы', 'Название ОС', 'Код продукта', 'Тип системы']]
for file in list_of_files:
with open(file) as f:
os_prod_list = []
os_name_list = []
os_code_list = []
os_type_list = []
lines = f.read().split('\n')
for line in lines:
if re.match(regex_prod, line):
sprod = re.sub(regex_prod, '', line).strip()
os_prod_list.append(sprod)
elif re.match(regex_name, line):
sname = re.sub(regex_name, '', line).strip()
os_name_list.append(sname)
elif re.match(regex_code, line):
scode = re.sub(regex_code, '', line).strip()
os_code_list.append(scode)
elif re.match(regex_type, line):
stype = re.sub(regex_type, '', line).strip()
os_type_list.append(stype)
else:
pass
try:
row_data = [os_prod_list[0], os_name_list[0], os_code_list[0], os_type_list[0]]
file_data = [['Изготовитель системы', 'Название ОС', 'Код продукта', 'Тип системы']]
file_data.append(row_data)
main_data.append(row_data)
except IndexError:
pass
with open('main_data' + file.split('.')[0] + '.csv', 'w', encoding='utf-8') as f_n:
f_n_writer = csv.writer(f_n)
for row in file_data:
f_n_writer.writerow(row)
print(main_data)
return main_data
def write_to_csv(resultfile):
files_to_import = ['info_1.txt']
files_to_import.append('info_2.txt')
files_to_import.append('info_3.txt')
main_data = getdata(files_to_import)
with open(resultfile, 'w', encoding='utf-8', newline='') as f_n:
f_n_writer = csv.writer(f_n, quoting=csv.QUOTE_NONNUMERIC)
f_n_writer.writerows(main_data)
def main():
resultfile = '123.csv'
write_to_csv(resultfile)
main()
| true |
06c4b8fd11859cdac9e37aba78af2669f1fc20a0 | Python | lisapro/co2marine | /b3_map.py | UTF-8 | 5,623 | 2.78125 | 3 | [] | no_license | '''
Created on 15. feb. 2017
@author: ELP
'''
# script creates a map of available
# data. form WOD, field data, modeling input
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from netCDF4 import Dataset
from matplotlib.patches import Ellipse
#read netcdf from WOD with validation data
ncfile = 'data_from_Baltic_small_domain_1980.nc'
fh = Dataset(ncfile, mode='r')
lat_odv = fh.variables['latitude'][:]
lon_odv =fh.variables['longitude'][:]
# coordinated of field data with only physics from Polish institute
lat = [55.4333, 55.45048333 , 55.5052 ,
55.52528333, 55.49421667 ,55.46626667]
lon = [18.15736667,18.14913333, 18.1957,
18.23168333,18.1884, 18.16268333]
# stations names
stations = [18,23, 4, 7,8,16]
# coordinated of field data with
# biogeochemical data from Polish institute
lat_bgch = [55.5372,55.51843333,55.50116667, 55.52833333,
55.5397, 55.50871667, 55.51025,55.48216667,55.45198333,
55.54351667]
lon_bgch = [18.27465, 18.20873333, 18.23761667,18.20283333,
18.25776667, 18.2381,18.25151667, 18.17466667,18.17215,
18.26866667]
st_bgch = [20,22, 11,1,6,9,10,15,17,19]
lat_bgch_gas = [55.52833333,
55.5397, 55.50871667, 55.51025,
55.54351667]
lon_bgch_gas = [18.20283333,
18.25776667, 18.2381,18.25151667,
18.26866667]
st_bgch_gas = [1,6,9,10,19]
# coordinated of TS input from GETM model
b3_getm = [18.1555,55.4863] # E,N
# coordinates of area with climate relaxation data
lon_relax = [17.55, 19.95]
lat_relax = [55.00 , 56.50]
#We do not need the rectangle no more
'''#add path to fill rectangle with relax data
from matplotlib.path import Path
verts = [ # define coordinates of rectangle
(lon_relax[0], lat_relax[0]), # P0
(lon_relax[0], lat_relax[1]), # P1
(lon_relax[1], lat_relax[1]), # P2
(lon_relax[1], lat_relax[0])
,(lon_relax[0], lat_relax[0]) # P3
]
codes = [Path.MOVETO,
Path.LINETO, # specify the
Path.LINETO, # way how to go from
Path.LINETO, # one point to another
Path.LINETO, # it can be filled only with
] # LINETO
path = Path(verts, codes)
'''
# add figure
fig = plt.figure(figsize=(7,9), dpi=100 )
gs = gridspec.GridSpec(2,1)
ax = fig.add_subplot(gs[0])
ax01 = fig.add_subplot(gs[1])
ax.set_title('Available data for B3 field',weight="bold")
ellipse = patches.Ellipse( (18.22,55.5), width=0.2,
height=0.14,angle = 45,
alpha = 0.2, zorder = 1)
area = ax.add_patch(ellipse)
ax.annotate('B3 area',(18.25,55.57),xytext=(55, 25),
arrowprops=dict(facecolor='black', shrink=0,width = 1, headwidth = 7),
ha='right', va='bottom',textcoords='offset points',
weight="bold", zorder = 10)
bgch = ax.scatter(lon_bgch, lat_bgch, zorder = 6,
label='hydrological, geochemical, biological sampling',
edgecolor = '#0d47a1',
s = 18,)
getm = ax.scatter(b3_getm[0],b3_getm[1], color = "#ad1457",
label='Input T,S,Kz data from GETM model (1990-2010) ',
s = 100, zorder = 5)
ax01.scatter(lon_bgch, lat_bgch, zorder = 6,edgecolor = '#0d47a1',
label='hydrological, geochemical, biological sampling',
s = 18,)
gas = ax01.scatter(lon_bgch_gas, lat_bgch_gas, zorder = 6,marker = "*",
label='gas chimney',color = '#ffc107', edgecolor = '#ff6f00',
s = 90,)
ax01.scatter(b3_getm[0],b3_getm[1], color = "#ad1457",
label='Input T,S,Kz data from GETM model (1990-2010) ',
s = 100, zorder = 5)
ax01.annotate('GETM\ninput',(b3_getm[0],b3_getm[1]),
xytext=(15, 5), ha='right', va='bottom',
textcoords='offset points', zorder = 10,
weight="bold")
for i, txt in enumerate(st_bgch):
ax01.annotate(txt, (lon_bgch[i],lat_bgch[i]),xytext=(17, 0),
ha='right', va='bottom',textcoords='offset points' )
wod = ax.scatter(lon_odv,lat_odv, label='Valdiation data from WOD (1980-2010)',
color = '#e0e0e0', edgecolor = '#bdbdbd', zorder = 2)#
#Add patch
#patch = patches.PathPatch(path, facecolor='#b7ebd9', lw=1,alpha = 0.1)
#ax.add_patch(patch)
#xs, ys = zip(*verts)
#ax.plot(xs, ys, lw=2, color='#b7ebd9',
# ms= False,label='Climate relaxation data ', zorder = 1)
ax.plot()
ax.annotate('GETM\ninput',(b3_getm[0],b3_getm[1]),xytext=(-15, 15),
arrowprops=dict(facecolor='black', shrink=0,width = 1, headwidth = 7),
ha='right', va='bottom',textcoords='offset points',
weight="bold", zorder = 10)
# can be added to plot numbers of stations
# removed it because of small scale
'''for i, txt in enumerate(stations):
ax.annotate(txt, (lon[i],lat[i]),xytext=(17, 0),
ha='right', va='bottom',textcoords='offset points' )
for i, txt in enumerate(st_bgch):
ax.annotate(txt, (lon_bgch[i],lat_bgch[i]),xytext=(17, 0),
ha='right', va='bottom',textcoords='offset points' ) '''
#legend = ax.legend( shadow=False, loc='best')
#legend = ax01.legend( shadow=False, loc='best')
plt.legend([bgch,gas,getm,wod,area],
['Field data (2012)',
'Stations with gas diffusion chimneys',
'T,S,Kz data from GETM model\n(1990-2010)',
'Valdiation data from WOD \n(1980-2010)',
'B3 area'],
loc='best')
# if you want to put legent to some fixed positon
#bbox_to_anchor=(0.8, 0.35))
#plt.savefig(filename = 'B3_map.png')
plt.show()
| true |
8b98d1454f98fe4de71b4c3d2739b922fdd07dc4 | Python | Barrett97/Twitter-Sentiment-Analysis | /sentmapper.py | UTF-8 | 211 | 3.046875 | 3 | [] | no_license | import sys
import re
from datetime import datetime
for line in sys.stdin:
line = re.sub(r'\n', '', line)
words = line.split('\t')
print(words[0]+ "\t" + words[1] + "\t" + words[2] + "\t" + words[3]) | true |
c166e2edfe0d6d797b0c4591bb06957f2f41c05c | Python | Pankhuriumich/EECS-182-System-folder | /Lecture_Code/Topic_9_Loops/mymap.py | UTF-8 | 2,724 | 4.125 | 4 | [] | no_license | import pdb
'''
Goal: We want to apply a function like cube to every element of a list and
get back a new list.
Recipe:
result list should be initialized to empty.
Go through each element of the input list:
apply the function to the element and append to the result list.
'''
def mymap(f, L):
'''Apply f to element of L and return the resulting list. L itself
is not modified. We return a new list.'''
result = [];
for element in L:
result.append(f(element));
# end of for loop
return result;
def cube(x):
return x*x*x;
# set_trace sets a breakpoint
#pdb.set_trace();
X = [1, 2, 4, 8];
print "X = ", X;
print "mymap(cube, X):", mymap(cube, X);
def is_odd(x):
return (x % 2 == 1);
X = [1, 2, 4, 8];
print "X = ", X;
print "mymap(is_odd, X):", mymap(is_odd, X);
# Use the Python built-in map function instead
print "Using built-in map, i.e., map(is_odd, X): ", map(is_odd, X)
# Using reduce
def add(x, y):
return x+y;
X = [1, 2, 4, 8];
print "X = ", X;
print "Using built-in reduce as reduce(add, X):", reduce(add, X);
def multiply(x, y):
return x*y;
X = [1, 2, 4, 8];
print "X = ", X;
print "reduce(multiply, X):", reduce(multiply, X);
# TASK: Try writing your own version of reduce. Call it myreduce(f, L), where f
# is function that combines two values into one.
# Combining map and reduce:
# Let's try to sum up cube of values in a list.
A = [1, 2, 3, 4];
# We want to compute cube(1) + cube(2) + cube(3) + cube(4) from A.
print "A = ", A;
print "reduce(add, map(cube, A)): ", reduce(add, map(cube, A));
# Combining filter, map, and reduce:
# Let's try to sum up cube of odd values in a list:
A = [1, 2, 3, 4, 5, 6, 7, 8, 9];
print "A = ", A;
print "sum of cubes of odd values in A as reduce(add, map(cube, filter(is_odd, A))): ", reduce(add, map(cube, filter(is_odd, A)));
# Equivalent code using loops for adding cube of odd values.
sum = 0;
for element in A:
if (element % 2 == 1): # odd
sum = sum + element*element*element;
print "sum of cubes of odd values for A using loop: ", sum;
# The loop code is not too bad. The advantage of map, filter, and reduce
# paradigm is that it provides a generic way of thinking about working
# with data in lists. Another advantage is that map and filter can
# be highly parallelized if the list is really long and partitioned across
# multiple machines, unlike the loop, which is inherently sequential.
# Google uses filter/map/reduce paradigm # extensively for
# some large-scale data analysis tasks.
# Using lambda functions
L = [1, 2, 4, 8];
print "Sum of elements of L: ", reduce(lambda x, y : x+y, L);
print "Product of elements of L: ", reduce(lambda x, y : x*y, L);
| true |
b2df4bf59488a628b919075b640df339dc531fe8 | Python | metamorphe/symbiot-app | /server/interpreter.py | UTF-8 | 2,268 | 3.125 | 3 | [] | no_license | import threading
import sys
import getch
import controller as controller
class KeyEventThread(threading.Thread):
def __init__(self, ard):
super(KeyEventThread, self).__init__()
self.controller = ard
self.char_buffer = []
def run(self):
print "> ",
while True:
c = getch.getch()
# escape key to exit
if ord(c) == ord('\n'):
sys.stdout.write('\n')
self._handle_line()
elif ord(c) == ord('\b'):
self.char_buffer.pop(len(self.char_buffer) - 1)
sys.stdout.write(c)
elif ord(c) == ord('q'):
print "\nBye!"
break;
else:
self.char_buffer.append(c)
sys.stdout.write(c)
def _handle_line(self):
if len(self.char_buffer):
c = self.char_buffer[0]
if ord(c) == ord('o'):
print "Opened serial connection:"
self.controller.open();
elif ord(c) == ord('s'):
address, value = self._parse_send_cmd(self.char_buffer)
print "Actuating ", address, " to ", value
self.controller.actuate(address, value)
elif ord(c) == ord('c'):
print "Closed serial connection"
self.controller.close();
else:
print "Unknown command"
self.char_buffer = []
print "> ",
def _parse_send_cmd(self, buffer):
"""
Destructively parses BUFFER, which should be in the form:
['s', <address chars>, ',', <value chars>]
and returns (address, value) as ints. If BUFFER is not a well-formed,
returns (0, 0)
"""
buffer.pop(0)
address_buffer = []
while (ord(buffer[0]) != ord(',')):
address_buffer.append(buffer[0])
buffer.pop(0)
buffer.pop(0)
try:
address = int(''.join(address_buffer))
value = int(''.join(buffer))
except ValueError:
address, value = 0, 0
return (address, value)
ard = controller.ArduinoSerialConnection();
ard.close();
kethread = KeyEventThread(ard)
kethread.start() | true |