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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
a943f3d1dfc2078095d3139b29321bf241247bde | Python | TheCodingMonkeys/checkin-at-fmi-client | /setup_manager.py | UTF-8 | 1,629 | 2.6875 | 3 | [] | no_license | import os.path
import urllib, urllib2, time
from datetime import datetime
import sqlite3 as lite
class Setup_Manager:
def __init__(self, server_address, reading_device, mac):
self.server_address = server_address
self.reading_device = reading_device
self.mac = mac
self.io_works = False
self.db_works = False
self.server_works = False
def check_io(self):
if os.path.exists(self.reading_device):
self.io_works = True
else:
self.io_works = False
def check_db (self):
try:
connection = lite.connect('checkIn.db')
cursor = connection.cursor()
cursor.execute('create table if not exists checkIns(url text(63), time datetime)')
data = cursor.fetchone()
self.db_works = True
except lite.Error, e:
self.db_works = False
def check_server(self):
url = self.server_address + 'checkin/status/'
values = {'mac' : self.mac,}
try:
print("Checking the server")
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
if response.getcode() == 200:
self.server_works = True;
print(url + " accepted us")
elif response.getcode() == 401:
self.server_works = False
print(url + " did not accept us")
except Exception, detail:
self.server_works = False
print detail
print("Error conectiong to the server")
| true |
60e92cab940356323841686d96646ac14020e0bc | Python | sushruta/cs231n_vision | /assignment2/cs231n/layers.py | UTF-8 | 10,434 | 3.296875 | 3 | [
"MIT"
] | permissive | import numpy as np
def affine_forward(x, w, b):
"""
Computes the forward pass for an affine (fully-connected) layer.
The input x has shape (N, d_1, ..., d_k) where x[i] is the ith input.
We multiply this against a weight matrix of shape (D, M) where
D = \prod_i d_i
Inputs:
x - Input data, of shape (N, d_1, ..., d_k)
w - Weights, of shape (D, M)
b - Biases, of shape (M,)
Returns a tuple of:
- out: output, of shape (N, M)
- cache: (x, w, b)
"""
out = None
x_shape = x.shape
x_reshaped = x.reshape(x_shape[0], np.prod(x_shape[1:]))
out = np.dot(x_reshaped, w) + b
cache = (x, w, b)
return out, cache
def affine_backward(dout, cache):
"""
Computes the backward pass for an affine layer.
Inputs:
- dout: Upstream derivative, of shape (N, M)
- cache: Tuple of:
- x: Input data, of shape (N, d_1, ... d_k)
- w: Weights, of shape (D, M)
Returns a tuple of:
- dx: Gradient with respect to x, of shape (N, d1, ..., d_k)
- dw: Gradient with respect to w, of shape (D, M)
- db: Gradient with respect to b, of shape (M,)
"""
x, w, b = cache
dx, dw, db = None, None, None
x_shape = x.shape
x_mutated = x.reshape(x_shape[0], np.prod(x_shape[1:]))
dx = np.dot(dout, w.T)
dw = np.dot(x_mutated.T, dout)
db = np.sum(dout, axis=0)
dx = dx.reshape(x_shape)
return dx, dw, db
def relu_forward(x):
"""
Computes the forward pass for a layer of rectified linear units (ReLUs).
Input:
- x: Inputs, of any shape
Returns a tuple of:
- out: Output, of the same shape as x
- cache: x
"""
out = None
out = np.maximum(0.0, x)
cache = x
return out, cache
def relu_backward(dout, cache):
"""
Computes the backward pass for a layer of rectified linear units (ReLUs).
Input:
- dout: Upstream derivatives, of any shape
- cache: Input x, of same shape as dout
Returns:
- dx: Gradient with respect to x
"""
dx, x = None, cache
dx = dout
dout[x <= 0] = 0.0
return dx
def conv_forward_naive(x, w, b, conv_param):
"""
A naive implementation of the forward pass for a convolutional layer.
The input consists of N data points, each with C channels, height H and width
W. We convolve each input with F different filters, where each filter spans
all C channels and has height HH and width HH.
Input:
- x: Input data of shape (N, C, H, W)
- w: Filter weights of shape (F, C, HH, WW)
- b: Biases, of shape (F,)
- conv_param: A dictionary with the following keys:
- 'stride': The number of pixels between adjacent receptive fields in the
horizontal and vertical directions.
- 'pad': The number of pixels that will be used to zero-pad the input.
Returns a tuple of:
- out: Output data, of shape (N, F, H', W') where H' and W' are given by
H' = 1 + (H + 2 * pad - HH) / stride
W' = 1 + (W + 2 * pad - WW) / stride
- cache: (x, w, b, conv_param)
"""
out = None
#############################################################################
# TODO: Implement the convolutional forward pass. #
# Hint: you can use the function np.pad for padding. #
#############################################################################
N, C, H, W = x.shape
F, C, HH, WW = w.shape
stride = conv_param['stride']
pad = conv_param['pad']
Hc = 1 + (H + 2 * pad - HH) / stride
Wc = 1 + (H + 2 * pad - WW) / stride
## pad all the images
xp = np.pad(x,
((0, 0), (0, 0), (pad, pad), (pad, pad)),
mode='constant', constant_values=0)
out = np.random.randn(N, F, Hc, Wc)
hc, wc = (0, 0)
for i in xrange(N):
for j in xrange(F):
for hc in xrange(Hc):
for wc in xrange(Wc):
xs = xp[i, :, hc*stride:hc*stride+HH, wc*stride:wc*stride+WW]
out[i, j, hc, wc] = np.sum(xs * w[j,:,:,:]) + b[j]
#############################################################################
# END OF YOUR CODE #
#############################################################################
cache = (x, w, b, conv_param)
return out, cache
def conv_backward_naive(dout, cache):
"""
A naive implementation of the backward pass for a convolutional layer.
Inputs:
- dout: Upstream derivatives.
- cache: A tuple of (x, w, b, conv_param) as in conv_forward_naive
Returns a tuple of:
- dx: Gradient with respect to x
- dw: Gradient with respect to w
- db: Gradient with respect to b
"""
dx, dw, db = None, None, None
#############################################################################
# TODO: Implement the convolutional backward pass. #
#############################################################################
x, w, b, conv_param = cache
N, C, H, W = x.shape
F, C, HH, WW = w.shape
N, F, Hc, Wc = dout.shape
stride = conv_param['stride']
print(dout.shape)
print(x.shape)
print(w.shape)
#dout = np.pad(dout, ((0,0),(0,0),(1,1),(1,1)), mode='constant', constant_values=0)
xp = np.pad(x, ((0,0),(0,0),(1,1),(1,1)), mode='constant', constant_values=0)
db = np.array([np.sum(dout[:,i,:,:]) for i in xrange(F)])
dw = np.random.randn(F, C, HH, WW)
for f in xrange(F):
for c in xrange(C):
for hh in xrange(HH):
for ww in xrange(WW):
dw[f, c, hh, ww] = np.sum(dout[:, f, :, :] * xp[:, c, hh:H+hh:stride, ww:W+ww:stride])
dx = np.zeros(x.shape)
dx = np.pad(dx, ((0,0), (0,0), (1,1), (1,1)), mode='constant', constant_values=0)
for i in xrange(N):
for hh in xrange(HH):
for ww in xrange(WW):
whw = w[:, :, hh, ww].T
for hc in xrange(Hc):
for wc in xrange(Wc):
he = hc * stride + hh
wi = wc * stride + ww
dx[i, :, he, wi] += np.sum(whw * dout[i, :, hc, wc], axis=1)
dx = dx[:, :, 1:-1, 1:-1]
#############################################################################
# END OF YOUR CODE #
#############################################################################
return dx, dw, db
def max_pool_forward_naive(x, pool_param):
"""
A naive implementation of the forward pass for a max pooling layer.
Inputs:
- x: Input data, of shape (N, C, H, W)
- pool_param: dictionary with the following keys:
- 'pool_height': The height of each pooling region
- 'pool_width': The width of each pooling region
- 'stride': The distance between adjacent pooling regions
Returns a tuple of:
- out: Output data
- cache: (x, pool_param)
"""
N, C, H, W = x.shape
pool_height = pool_param['pool_height']
pool_width = pool_param['pool_width']
stride = pool_param['stride']
Hc = (H - pool_height) / stride + 1
Wc = (W - pool_width) / stride + 1
out = np.random.randn(N, C, Hc, Wc)
#############################################################################
# TODO: Implement the max pooling forward pass #
#############################################################################
for i in xrange(N):
for c in xrange(C):
for hc in xrange(Hc):
for wc in xrange(Wc):
out[i, c, hc, wc] = np.max(x[i, c, hc:stride*hc+pool_height, wc:stride*wc+pool_width])
#############################################################################
# END OF YOUR CODE #
#############################################################################
cache = (x, pool_param)
return out, cache
def max_pool_backward_naive(dout, cache):
"""
A naive implementation of the backward pass for a max pooling layer.
Inputs:
- dout: Upstream derivatives
- cache: A tuple of (x, pool_param) as in the forward pass.
Returns:
- dx: Gradient with respect to x
"""
x, pool_params = cache
N, C, H, W = x.shape
pool_height = pool_params['pool_height']
pool_width = pool_params['pool_width']
stride = pool_params['stride']
Hc = (H - pool_height) / stride + 1
Wc = (W - pool_width) / stride + 1
dx = np.zeros(x.shape)
#############################################################################
# TODO: Implement the max pooling backward pass #
#############################################################################
for i in xrange(N):
for c in xrange(C):
for hc in xrange(Hc):
for wc in xrange(Wc):
subx = x[i, c, hc:stride*hc+pool_height, wc:stride*wc+pool_width]
subdx = dx[i, c, hc:stride*hc+pool_height, wc:stride*wc+pool_width]
max_value = np.max(subx)
subdx += (subx == max_value) * dout[i, c, hc, wc]
#############################################################################
# END OF YOUR CODE #
#############################################################################
return dx
def svm_loss(x, y):
"""
Computes the loss and gradient using for multiclass SVM classification.
Inputs:
- x: Input data, of shape (N, C) where x[i, j] is the score for the jth class
for the ith input.
- y: Vector of labels, of shape (N,) where y[i] is the label for x[i] and
0 <= y[i] < C
Returns a tuple of:
- loss: Scalar giving the loss
- dx: Gradient of the loss with respect to x
"""
N = x.shape[0]
correct_class_scores = x[np.arange(N), y]
margins = np.maximum(0, x - correct_class_scores[:, np.newaxis] + 1.0)
margins[np.arange(N), y] = 0
loss = np.sum(margins) / N
num_pos = np.sum(margins > 0, axis=1)
dx = np.zeros_like(x)
dx[margins > 0] = 1
dx[np.arange(N), y] -= num_pos
dx /= N
return loss, dx
def softmax_loss(x, y):
"""
Computes the loss and gradient for softmax classification.
Inputs:
- x: Input data, of shape (N, C) where x[i, j] is the score for the jth class
for the ith input.
- y: Vector of labels, of shape (N,) where y[i] is the label for x[i] and
0 <= y[i] < C
Returns a tuple of:
- loss: Scalar giving the loss
- dx: Gradient of the loss with respect to x
"""
probs = np.exp(x - np.max(x, axis=1, keepdims=True))
probs /= np.sum(probs, axis=1, keepdims=True)
N = x.shape[0]
loss = -np.sum(np.log(probs[np.arange(N), y])) / N
dx = probs.copy()
dx[np.arange(N), y] -= 1
dx /= N
return loss, dx
| true |
9ac2388460f5947cf64cd4338b49d3d1d7015776 | Python | santosfamilyfoundation/Traffic | /trafficintelligence/scripts/init_tracking.py | UTF-8 | 2,584 | 2.828125 | 3 | [
"MIT"
] | permissive | #! /usr/bin/env python
import sys, argparse, os.path, storage, utils
from cvutils import getImagesFromVideo
from matplotlib.pyplot import imsave
# could try to guess the video
# check if there is already a tracking.cfg file
parser = argparse.ArgumentParser(description='The program initilizes the files for tracking: copy tracking.cfg, sets up with the video filename, generates a frame image (frame.png) and prints the next commands')
parser.add_argument('-i', dest = 'videoFilename', help = 'filename of the video sequence', required = True)
args = parser.parse_args()
# assumes tracking.cfg is in the parent directory to the directory of the traffic intelligence python modules
matchingPaths = [s for s in sys.path if 'traffic-intelligence' in s]
#if len(matchingPaths) > 1:
# print('Too many matching paths for Traffic Intelligence modules: {}'.format(matchingPaths))
if len(matchingPaths) == 0:
print('No environment path to Traffic Intelligence modules.\nExiting')
sys.exit()
else:
directoryName = matchingPaths[0]
if directoryName.endswith('/'):
directoryName = directoryName[:-1]
if os.path.exists(directoryName+'/../tracking.cfg') and not os.path.exists('./tracking.cfg'):
f = storage.openCheck(directoryName+'/../tracking.cfg')
out = storage.openCheck('./tracking.cfg', 'w')
for l in f:
if 'video-filename' in l:
tmp = l.split('=')
out.write(tmp[0]+'= '+args.videoFilename+'\n')
elif 'database-filename' in l:
tmp = l.split('=')
out.write(tmp[0]+'= '+utils.removeExtension(args.videoFilename)+'.sqlite\n')
else:
out.write(l)
f.close()
out.close()
print('Configuration file tracking.cfg successfully copied to the current directory with video and database filename adapted')
# extract image from video
image = getImagesFromVideo(args.videoFilename, saveImage = True, outputPrefix = 'frame')
print('first video frame successfully copied to the current directory')
# next commands
print('--------------------------------------\nHere are a sample of the next command to compute the homography,\ntrack features, group them in objects and display object trajectories\n--------------------------------------')
print('compute_homography -i [frame.png] -w [world_image] -n [npoints] -u [unit_per_pixel]')
print('feature-based-tracking tracking.cfg --tf')
print('feature-based-tracking tracking.cfg --gf')
print('display-trajectories --cfg tracking.cfg -t object')
| true |
ed3f51b381e8164a3b71ab670edda71bde50cd80 | Python | ZivGrinblat/ImageProcessingProjects | /Projects/ExerciseOne.py | UTF-8 | 8,979 | 2.796875 | 3 | [] | no_license | import numpy as np
import imageio
import matplotlib.pyplot as plt
from skimage.color import rgb2gray
r_to_y = np.array([[0.299, 0.587, 0.114],
[0.596, -0.275, -0.321],
[0.212, -0.523, 0.311]])
y_to_r = np.array([[1, 0.956, 0.619],
[1, -0.272, -0.647],
[1, -1.106, 1.703]])
def read_image(filename, representation):
"""
Returns representation of image at filename in float64
:param filename: the filename of an image on disk (could be grayscale or RGB)
:param representation: representation code, either 1 or 2 defining whether the output should be a grayscale
image (1) or an RGB image (2)
:return: an image
"""
img = imageio.imread(filename) / 255
return img if representation == 2 else rgb2gray(img)
def imdisplay(filename, representation):
"""
Displays image according to representation
:param filename: the filename of an image on disk (could be grayscale or RGB)
:param representation: representation code, either 1 or 2 defining whether the output should be a grayscale
image (1) or an RGB image (2)
:return: None
"""
img = read_image(filename, representation)
if representation == 1: plt.imshow(img, cmap='gray')
if representation == 2: plt.imshow(img)
plt.show()
def rgb2yiq(imRGB):
"""
Transforms RGB img into the YIQ color space
:param imRGB:
:return: imRGB transformed into YIQ color space
"""
return imRGB @ r_to_y.T
def yiq2rgb(imYIQ):
"""
Transforms YIQ img into the RGB color space
:param imYIQ:
:return: imYIQ transformed into RGB color space
"""
return imYIQ @ y_to_r.T
def histogram_equalize(im_orig):
"""
Perform hist equalization on RGB or grayscale im_orig
:param im_orig:
:return:
"""
im_yiq = None
im_cur = im_orig
if len(im_orig.shape) == 3: # RGB case
im_yiq = rgb2yiq(im_orig)
im_cur = im_yiq[:, :, 0]
# Steps 1-7 of equalization
hist_orig, bins = np.histogram(im_cur, bins = np.arange(257) / 255)
bins = bins[:-1]
hist_cum = hist_orig.cumsum()
hist_cum = 255 * hist_cum / hist_cum[-1]
hist_min, hist_max = hist_cum[hist_cum > 0][0], np.max(hist_cum)
hist_cum = np.round(255 * (hist_cum - hist_min) / (hist_max - hist_min)).astype(np.int)
im_eq = hist_cum[(im_cur * 255).astype(np.int)] / 255
hist_eq, bins_eq = np.histogram(im_eq, bins = np.arange(257) / 255)
if len(im_orig.shape) == 3: # If needed, insert image into YIQ image and transform into RGB
im_yiq[:, :, 0] = im_eq
im_eq = yiq2rgb(im_yiq)
return [im_eq, hist_orig, hist_eq]
def q_calc(z_indices, hist):
"""
Calculate qs based on z indices and histogram
:param z_indices:
:param hist:
:return:
"""
q_arr = np.array([])
for i in range(len(z_indices) - 1):
numerator, denominator = 0, 0
for g in range(int(np.floor(z_indices[i])) + 1, int(np.floor(z_indices[i + 1])) + 1):
numerator += g * hist[g]
denominator += hist[g]
q_arr = np.append(q_arr, numerator / denominator)
return q_arr
def z_calc(q_arr):
"""
Calculate z indices based on q_arr
:param q_arr:
:return:
"""
z_indices = np.array([0])
for q_idx in range(1, len(q_arr)):
z_indices = np.append(z_indices, ((q_arr[q_idx - 1] + q_arr[q_idx]) / 2))
return np.append(z_indices, 255)
def error_calc(hist_orig, z_indices, q_arr):
"""
Calculate error between original image and calculated z and q arrays
:param hist_orig:
:return:
"""
error = 0
for i in range(len(z_indices) - 1):
for g in range(int(np.floor(z_indices[i])) + 1, int(np.floor(z_indices[i + 1])) + 1):
error += ((q_arr[i] - g) ** 2) * hist_orig[g]
return error
def quantize(im_orig, n_quant, n_iter):
"""
Return quantized image and array of errors in each iteration
:param im_orig:
:param n_quant: number of intensities in new image
:param n_iter: number of iterations for computing z and q
:return: quantized image and errors
"""
im_yiq = None
im_cur = im_orig
if len(im_orig.shape) == 3: # RGB case
im_yiq = rgb2yiq(im_orig)
im_cur = im_yiq[:, :, 0]
# Calculate initial z indices
hist_orig, bins_orig = np.histogram(im_cur, bins = np.arange(257) / 255)
z_indices = np.array([0])
for i in range(1, n_quant):
z_indices = np.append(z_indices, np.quantile(im_orig * 255, i / n_quant))
z_indices = np.append(z_indices, 255)
# Calculate initial qs, initialize error array
q_arr = q_calc(z_indices, hist_orig)
error = np.array([])
# Iterate quantization
for step in range(n_iter - 1):
new_z_indices = z_calc(q_arr)
if np.array_equal(z_indices, new_z_indices): break
z_indices = new_z_indices
q_arr = q_calc(z_indices, hist_orig)
error = np.append(error, error_calc(hist_orig, z_indices, q_arr))
z_indices = np.ceil(z_indices).astype(int)
# Create new mapping and apply
new_map = np.array([])
for i in range(len(q_arr)):
new_map = np.append(new_map, np.array([[q_arr[i]] * (z_indices[i + 1] - z_indices[i])]))
new_map = np.append(new_map, q_arr[-1])
im_quant = new_map[(im_cur * 255).astype(np.int)] / 255
if len(im_orig.shape) == 3: # If needed, insert image into YIQ image and transform into RGB
im_yiq[:, :, 0] = im_quant
im_quant = yiq2rgb(im_yiq)
return [im_quant, error]
def greatest_range(im_orig):
"""
Find which color has the greatest difference between max and min
:param img:
:return:
"""
r_range, g_range, b_range = None, None, None
if len(im_orig.shape) == 2:
r_range = np.max(im_orig[:, 0]) - np.min(im_orig[:, 0])
g_range = np.max(im_orig[:, 1]) - np.min(im_orig[:, 1])
b_range = np.max(im_orig[:, 2]) - np.min(im_orig[:, 2])
if len(im_orig.shape) == 3:
r_range = np.max(im_orig[:, :, 0]) - np.min(im_orig[:, :, 0])
g_range = np.max(im_orig[:, :, 1]) - np.min(im_orig[:, :, 1])
b_range = np.max(im_orig[:, :, 2]) - np.min(im_orig[:, :, 2])
arr = np.array([r_range, g_range, b_range])
return np.argmax(arr)
def quantize_rgb_helper(im_orig, n_quant, color_arr, idx):
"""
Recursive function that splits image into boxes and takes the average color.
Adds newly calculated colors to color_arr
:param im_orig:
:param n_quant:
:param x1: left side x bound
:param x2: right side x bound
:param y1: top side y bound
:param y2: bottom side y bound
:return:
"""
# Base case
if n_quant == 1:
im_temp = im_orig.reshape(-1, 3)
new_color = np.mean(im_temp, axis=0)
color_arr[idx[0]] = new_color
idx[0] += 1
else:
# Calculate splits for both halves
small_half, large_half = int(2 ** np.floor(np.log2(n_quant) - 1)), None
if n_quant - small_half < small_half / 2: small_half /= 2
large_half = n_quant - small_half
# Find color with greatest range to split the chunk
color = greatest_range(im_orig)
im_orig = im_orig.reshape(-1, 3)
im_orig = im_orig[im_orig[:, color].argsort()]
first_half = im_orig[:im_orig.shape[0]//2]
second_half = im_orig[im_orig.shape[0]//2:]
quantize_rgb_helper(first_half, small_half, color_arr, idx)
quantize_rgb_helper(second_half, large_half, color_arr, idx)
def quantize_rgb(im_orig, n_quant):
"""
Uses quantize_rgb_helper to calculate new colors, then maps them
:param im_orig:
:param n_quant:
:return: quantized RGB image
"""
copy_im = im_orig.copy()
my_shape = copy_im.shape
color_arr = [0] * n_quant # Array for storing new palette
quantize_rgb_helper(copy_im, n_quant, color_arr, [0])
# Pick R,G or B for quantization and sort it
color = greatest_range(copy_im)
color_arr = np.array(color_arr)
color_arr = color_arr[color_arr[:, color].argsort()]
# Set bounds based on color amount
copy_im = copy_im.reshape(-1, 3)
z_indices = np.array([0])
for i in range(1, n_quant):
z_indices = np.append(z_indices, np.quantile(copy_im[:, color] * 255, i / n_quant))
z_indices = np.append(z_indices, 255) / 255
# Map colors
for i in range(len(color_arr)):
copy_im[np.logical_and(copy_im[:, color] >= z_indices[i], copy_im[:, color] < z_indices[i + 1])] = color_arr[i]
copy_im[copy_im[:, color] == z_indices[-1]] = color_arr[-1] # map color intensities = 1
return copy_im.reshape(my_shape) | true |
82081e02517bacf210027ccbd7c43c56b70539c6 | Python | antonellaBerchesCj/python-exercises | /2_client.py | UTF-8 | 811 | 3.359375 | 3 | [] | no_license | '''
2. [net] Write a client / server pair of sources in which the client requests random numbers of a specific number of digits from the server.
'''
# Client
#!/usr/bin/env python
import socket
import string
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((TCP_IP, TCP_PORT))
#client_socket.send('Send me random nr!')
digits = input("Enter nr of digits for random nr: ")
client_socket.send(str(digits))
randomNr = client_socket.recv(BUFFER_SIZE)
print(randomNr)
#digits = input("Enter nr of digits for random nr: ")
#if digits <= 10:
# client_socket.send(string.digits)
# randomNr = client_socket.recv(BUFFER_SIZE)
# print(randomNr)
#else:
# print('[!] Digit number must be <= 10!')
client_socket.close()
| true |
892eae8642e86e6c69f227c3654a5153271be85a | Python | fuyunguagua/mafengwoqainfo | /qa/restract.py | UTF-8 | 3,599 | 2.671875 | 3 | [] | no_license |
__author__ = 'WY'
import re
from scrapy.selector import Selector
def filter_text2(text,flags):
for item in flags:
if text.find(item) is -1:
pass
else:
text = text.replace(item,' ')
return text
def restract(regex, text, func=None):
pattern = re.compile(regex,re.S)
r = pattern.findall(text)
if func is None:
return r
else:
if callable(func):
func(r)
else:
raise Exception('参数三不可被调用')
def showResult(list):
for i, item in enumerate(list):
print(i,item)
def restract_question_title(htmlText):
question_title_re = '<h1>(.*?)</h1>'
return restract(question_title_re, htmlText)[0].strip()
def restract_address(htmlText):
address_re = 'class="location"><i></i>(.*?)</a>'
return restract(address_re, htmlText)[0]
def restract_question_detail(htmlText):
seletor = Selector(text=htmlText)
result = seletor.xpath('//*[@id="_js_askDetail"]/div[1]/div[2]/text()').extract()
return ''.join(result)
def restract_lables_list(htmlText):
seletor = Selector(text=htmlText)
result = seletor.xpath('//*[@id="_js_askDetail"]/div[1]/div[3]/div[1]').extract_first()
res = '<a class.*?>(.*?)</a>'
return restract(res, result)
def restract_answer_list(htmlText):
seletor = Selector(text=htmlText)
result = seletor.xpath('//*[@id="normal_answer_wrap"]/li').extract()
return result
def restract_one_answer(anwer_div):
# 获得纯文本
anwer_text_re = '<div class="_j_answer_html">(.*)</div>\s*<!-- 问答版权名片 -->'
anwer_text = restract(anwer_text_re, anwer_div)[0]
img_re = '<img src.*?>'
result = re.sub(img_re, '', anwer_text, flags=re.S)
address_re = '<div class="area_tags _j_tip_mdd".*?<a.*?>.*?</a>\s*<div class="at_info.*?></div>\s*?</div>'
result = result.replace('{','《')
result = result.replace('}','》')
address_pass_text = re.sub(address_re, '{}', result, flags=re.S)
address_key_re = '<a data-cs-p="qa_mdd".*?>(.*?)</a>'
address_list = restract(address_key_re, anwer_text)
result = address_pass_text.format(*address_list)
# 清洗特殊字符
answer_text = clean_text(result)
# 获得赞数
num_zan = restract_num_zan(anwer_div)
return [num_zan, answer_text]
def clean_text(result):
filter_re = '<span.*?</span>'
result = re.sub(filter_re, '', result, flags=re.S)
filter_re = '<div.*?</div>'
result = re.sub(filter_re, '', result, flags=re.S)
filter_re = '<div.*?>'
result = re.sub(filter_re, '', result, flags=re.S)
filter_re = '<a.*?</a>'
result = re.sub(filter_re, '', result, flags=re.S)
result = filter_text2(result, ('<br>', '<b>', '</b>', '</div>', '\n'))
filter_re = '图自.*? '
answer_text = re.sub(filter_re, '', result, flags=re.S)
return answer_text
def restract_num_zan(answer_div):
num_vote_re = '<a class="btn-ding _js_zan.*?data-real_num="(\d*?)"'
return restract(num_vote_re, answer_div)[0]
class Restractor(object):
@staticmethod
def restract_qa_info(html):
info = {}
info['title'] = restract_question_title(html)
info['detail'] = restract_question_detail(html)
info['location'] = restract_address(html)
info['lables'] = restract_lables_list(html)
answer_list = []
answer_div_list = restract_answer_list(html)
for answer_div in answer_div_list:
answer_list.append(restract_one_answer(answer_div))
info['answer'] = answer_list
return info
| true |
86fec3e617beb71f861e1c84d52b7d80da69603b | Python | TejasAvinashShetty/qm-computing-projects | /cp6/cp6.py | UTF-8 | 2,899 | 2.640625 | 3 | [] | no_license | #
# cp6: Solution to Computing Project 6: Quantum Wire Project
#
from visual import *
from visual.graph import *
from safcn import SetArrowFromCN # defined in a file safcn.py
gd = gdisplay(title="<x> vs. t", xtitle="t", ytitle="<x>",
foreground=color.black, background=color.white)
g1 = gcurve(color=color.black)
scene.background=color.white
hbar=1.05e-34 # Js
m=0.067*9.1e-31 # and m_eff=kg
NA=80 # how many arrows?
a=5.34e-9 # width for 5 bound states and 1eV well depth.
x = linspace(-2.0*a, 2.0*a, NA) # NA locations from -2a to 2a
z0 = 9*pi/4 # split the difference... between 2*pi and 5*pi/2
k0 = z0/a # get k0
#
# numerical solutions for z when z0 = 9*pi/4
#
z1 = 1.375
z2 = 2.743
k1 = k0*z1/z0
k2 = k0*z2/z0
kap1 = sqrt(k0**2 - k1**2)
kap2 = sqrt(k0**2 - k2**2)
E1 = -(hbar*kap1)**2/(2.0*m)
E2 = -(hbar*kap2)**2/(2.0*m)
w1 = E1/hbar
w2 = E2/hbar
wn=[w1,w2]
t = 0.0
dt = (2*pi/(w2-w1))/200.0
psis = zeros((2,NA),double)
def f1(x):
return cos(k1*x)
def f2(x):
return sin(k2*x)
def f3(x):
return f1(a)*exp(-abs(kap1*x))/exp(-abs(kap1*a))
def f4(x):
return sign(x)*f2(a)*exp(-abs(kap2*x))/exp(-abs(kap2*a))
psis[0] = piecewise(x, [x<-a, (x>=-a)&(x<=a), x>a], [f3, f1, f3])
psis[0] = psis[0]/sqrt((abs(psis[0])**2).sum())
psis[1] = piecewise(x, [x<-a, (x>=-a)&(x<=a), x>a], [f4, f2, f4])
psis[1] = psis[1]/sqrt((abs(psis[1])**2).sum())
#
# Decide how much of each bound state to use in the superposition state:
#
# Edit the "if" statement to pick the one you want. The first
# clause with a '1' wins.
#
if 1:
# Equal parts 1 and 2
c1 = 1.0/sqrt(2)
c2 = 1.0/sqrt(2)
elif 0:
# all 2 and no 1
c1=0.0
c2=1.0
elif 0:
# all 1 and no 2
c1=1.0
c2=0.0
cn=[c1, c2] # array of amplitudes
t = 0.0 # start at t=0
psi = zeros(NA, complex)
for i in range(2):
psi = psi + cn[i]*psis[i]*exp(-1j*wn[i]*t)
arrowScale = a/psis[0][NA/2] # scale to make the middle of psis[0] about 3a high
alist = []
for i in range(NA):
alist.append(arrow(pos=(x[i],0,0), color=color.red))
SetArrowFromCN(arrowScale*psi[i],alist[i])
update=False
while True:
rate(100)
if scene.kb.keys: # event waiting to be processed?
s = scene.kb.getkey() # get keyboard info
if s == ' ':
update ^= 1
if update:
t = t+dt
psi = zeros(NA, complex)
for i in range(2):
psi = psi + cn[i]*psis[i]*exp(-1j*wn[i]*t)
for i in range(NA):
SetArrowFromCN(arrowScale*psi[i],alist[i])
#g1.plot(pos=(t,psi[3*NA/4].real))
xexp=(x*abs(psi*psi)).sum()
g1.plot(pos=(t,xexp))
| true |
5a3c950bc940b6ed8260389e68350c3c476302f3 | Python | bonbonben/BigData | /Parking violations/Task 3/map.py | UTF-8 | 303 | 2.921875 | 3 | [] | no_license | #!/usr/bin/env python
import sys
import csv
import os
import string
reader=csv.reader(sys.stdin,delimiter=',')
#license_type is at the third column
for type in reader:
key=type[2]
try:
value=float(type[12])
except ValueError:
continue
print ('{0:s}\t{1:f}'.format(key,value)) | true |
73d3f3aa8cd9ab6c0248932a1901e1ad13b072b2 | Python | xiwang-chen/encryption_and_decryption | /各种算法/五、加密库pycryptodomex/3、AES.py | UTF-8 | 2,254 | 3.359375 | 3 | [] | no_license | '''
高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法,
是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。
经过五年的甄选流程,高级加密标准由美国国家标准与技术研究院(NIST)于2001年11月26日发布于FIPS PUB 197,
并在2002年5月26日成为有效的标准。2006年,高级加密标准已然成为对称密钥加密中最流行的算法之一。
AES在软件及硬件上都能快速地加解密,相对来说较易于实作,且只需要很少的存储器。
作为一个新的加密标准,目前正被部署应用到更广大的范围。
特点与思想:抵抗所有已知的攻击。 在多个平台上速度快,编码紧凑。 设计简单。
AES为分组密码,分组密码也就是把明文分成一组一组的,每组长度相等,每次加密一组数据,直到加密完整个明文。
在AES标准规范中,分组长度只能是128位,也就是说,每个分组为16个字节(每个字节8位)。密钥的长度可以使用128位、
192位或256位。密钥的长度不同,推荐加密轮数也不同。
'''
from Cryptodome.Cipher import AES
from Cryptodome import Random
from binascii import a2b_hex
# 要加密的明文
data = '南来北往'
# 密钥key必须为 16(AES-128), 24(AES-192), 32(AES-256)
key = b'this is a 16 key'
# 生成长度等于AES 块大小的不可重复的密钥向量
iv = Random.new().read( AES.block_size )
print(iv)
# 使用 key 和iv 初始化AES 对象, 使用MODE_CFB模式
mycipher = AES.new( key, AES.MODE_CFB, iv )
print( mycipher )
# 加密的明文长度必须为16的倍数, 如果长度不为16的倍数, 则需要补足为16的倍数
# 将iv(密钥向量)加到加密的密钥开头, 一起传输
ciptext = iv + mycipher.encrypt( data.encode() )
# 解密的话需要用key 和iv 生成的AES对象
print( ciptext )
mydecrypt = AES.new( key, AES.MODE_CFB, ciptext[:16] )
# 使用新生成的AES 对象, 将加密的密钥解密
decrytext = mydecrypt.decrypt( ciptext[16:] )
print( decrytext.decode() ) | true |
2981eb45c3d96b682b7159a5e7daac26cb0b77c4 | Python | ellisk42/ec | /dreamcoder/domains/misc/napsPrimitives.py | UTF-8 | 8,258 | 2.53125 | 3 | [
"MIT"
] | permissive | #napsPrimitives.py
from dreamcoder.program import Primitive, prettyProgram
from dreamcoder.grammar import Grammar
from dreamcoder.type import tlist, tint, arrow, baseType #, t0, t1, t2
#from functools import reduce
#types
PROGRAM = baseType("PROGRAM")
RECORD = baseType("RECORD")
FUNC = baseType("FUNC")
VAR = baseType("VAR")
STMT = baseType("STMT")
EXPR = baseType("EXPR")
ASSIGN = baseType("ASSIGN")
LHS = baseType("LHS")
IF = baseType("IF")
FOREACH = baseType("FOREACH")
WHILE = baseType("WHILE")
BREAK = baseType("BREAK")
CONTINUE = baseType("CONTINUE")
RETURN = baseType("RETURN")
NOOP = baseType("NOOP")
FIELD = baseType("FIELD")
CONSTANT = baseType("CONSTANT")
INVOKE = baseType("INVOKE")
TERNARY = baseType("TERNARY")
CAST = baseType("CAST")
TYPE = baseType("TYPE")
#other types
function_name = baseType("function_name")
field_name = baseType("field_name")
name = baseType("name") # for records and functions
value = baseType("value")
# definitions:
def _program(records): return lambda funcs: {'types': records, 'funcs': funcs}
# record
def _func(string): return lambda tp: lambda name: lambda vars1: lambda vars2: lambda stmts: [string, tp, name, vars1, vars2, stmts]
def _var(tp): return lambda name: ['var', tp, name]
# stmt
# expr
def _assign(tp): return lambda lhs: lambda expr: ['assign', tp, lhs, expr]
# lhs
def _if(tp): return lambda expr: lambda stmts1: lambda stmts2: ['if', tp, expr, stmts1, stmts2] # TODO
def _foreach(tp): return lambda var: lambda expr: lambda stmts: ['foreach', tp, expr, stmts] # TODO
def _while(tp): return lambda expr: lambda stmts1: lambda stmts1: ['while', tp, expr, stmts1, stmts2] # or: ['while', tp, expr, [stmts1], [stmts2]] #TODO
# break
# continue
def _return(tp): return lambda expr: ['return', tp, expr]
# noop
def _field(tp): return lambda expr: lambda field_name: ['field', tp, expr, field_name]
def _constant(tp): return lambda value: ['val', tp, value] #TODO deal with value
def _invoke(tp): return lambda function_name: lambda exprs: ['invoke', tp, function_name, exprs] # TODO, deal with fn_name and lists
def _ternary(tp): return lambda expr1: lambda expr2: lambda expr3: ['?:', tp, expr1, expr2, expr3]
def _cast(tp): return lambda expr: ['cast', tp, expr]
# types:
# TODO: deal with lists - x
# TODO: deal with names
# TODO: deal with values - x
# TODO: deal with the program/record __main__ and __globals__ stuff
def napsPrimitives():
return [
Primitive("program", arrow(tlist(RECORD), tlist(FUNC), PROGRAM), _program), # TODO
# RECORD
Primitive("func", arrow(TYPE, name, tlist(VAR), tlist(VAR), tlist(VAR), tlist(STMT)), _func('func')), # TODO
Primitive("ctor", arrow(TYPE, name, tlist(VAR), tlist(VAR), tlist(VAR), tlist(STMT)), _func('ctor')),
Primitive("var", arrow(TYPE, name, VAR), _var)
] + [
# STMT ::= EXPR | IF | FOREACH | WHILE | BREAK | CONTINUE | RETURN | NOOP
Primitive("stmt_expr", arrow(EXPR, STMT), lambda x: x),
Primitive("stmt_if", arrow(IF, STMT), lambda x: x),
Primitive("stmt_foreach", arrow(FOREACH, STMT), lambda x: x),
Primitive("stmt_while", arrow(WHILE, STMT), lambda x: x),
Primitive("stmt_break", arrow(BREAK, STMT), lambda x: x),
Primitive("stmt_continue", arrow(CONTINUE, STMT), lambda x: x),
Primitive("stmt_return", arrow(RETURN, STMT), lambda x: x),
Primitive("stmt_noop", arrow(NOOP, STMT), lambda x: x)
] + [
# EXPR ::= ASSIGN | VAR | FIELD | CONSTANT | INVOKE | TERNARY | CAST
Primitive("expr_assign", arrow(ASSIGN, EXPR), lambda x: x),
Primitive("expr_var", arrow(VAR, EXPR), lambda x: x),
Primitive("expr_field", arrow(FIELD, EXPR), lambda x: x),
Primitive("expr_constant", arrow(CONSTANT, EXPR), lambda x: x),
Primitive("expr_invoke", arrow(INVOKE, EXPR), lambda x: x),
Primitive("expr_ternary", arrow(TERNARY, EXPR), lambda x: x),
Primitive("expr_cast", arrow(CAST, EXPR), lambda x: x)
] + [
Primitive("assign", arrow(TYPE, LHS, EXPR, ASSIGN), _assign)
] + [
# LHS ::= VAR | FIELD | INVOKE
Primitive("lhs_var", arrow(VAR, LHS), lambda x: x),
Primitive("lhs_field", arrow(FIELD, LHS), lambda x: x),
Primitive("lhs_invoke", arrow(INVOKE, LHS), lambda x: x)
] + [
Primitive("if", arrow(TYPE, EXPR, tlist(STMT), tlist(STMT), IF), _if),
Primitive("foreach", arrow(TYPE, VAR, EXPR, tlist(STMT), FOREACH), _foreach),
Primitive("while", arrow(TYPE, EXPR, tlist(STMT), tlist(STMT), WHILE), _while),
Primitive("break", arrow(TYPE, BREAK), lambda tp: ['break', tp]),
Primitive("continue", arrow(TYPE, CONTINUE), lambda tp: ['continue', tp]),
Primitive("return", arrow(TYPE, EXPR, RETURN), _return),
Primitive("noop", NOOP, ['noop']),
Primitive("field", arrow(TYPE, EXPR, field_name, FIELD), _field), # TODO
Primitive("constant", arrow(TYPE, value, CONSTANT), _constant),
Primitive("invoke", arrow(TYPE, function_name, tlist(EXPR), INVOKE), _invoke), # TODO
Primitive("ternary", arrow(TYPE, EXPR, EXPR, EXPR, TERNARY), _ternary),
Primitive("cast", arrow(TYPE, EXPR, CAST), _cast)
] + [
# below are TYPE:
Primitive("bool", TYPE, 'bool'),
Primitive("char", TYPE, 'char'),
Primitive("char*", TYPE, 'char*'),
Primitive("int", TYPE, 'int'),
Primitive("real", TYPE, 'real'),
Primitive("array", arrow(TYPE, TYPE), lambda tp: tp + '*'),
Primitive("set", arrow(TYPE, TYPE), lambda tp: tp + '%'),
Primitive("map", arrow(TYPE, TYPE, TYPE), lambda tp1: lambda tp2: '<'+tp1+'|'+tp2+'>'),
Primitive("record_name", TYPE, 'record_name#') # TODO
] + [
#stuff about lists:
# STMTs, EXPRs, VARs, maybe Funcs and records
Primitive('list_init_stmt', arrow(STMT, tlist(STMT)), lambda stmt: [stmt]),
Primitive('list_add_stmt', arrow(STMT, tlist(STMT), tlist(STMT)), lambda stmt: lambda stmts: stmts + [stmt]),
Primitive('list_init_expr', arrow(EXPR, tlist(EXPR)), lambda expr: [expr]),
Primitive('list_add_expr', arrow(EXPR, tlist(EXPR), tlist(EXPR)), lambda expr: lambda exprs: exprs + [expr]),
Primitive('list_init_var', arrow(VAR, tlist(VAR)), lambda var: [var]),
Primitive('list_add_var', arrow(VAR, tlist(VAR), tlist(VAR)), lambda var: lambda _vars: _vars + [var])
] + [
# value
Primitive('0', value, 0),
Primitive("1", value, "1"),
Primitive("-1", value, "-1")
# ...
] + [
# function_name:
Primitive('+', function_name, '+'),
Primitive('&&', function_name, "&&"),
Primitive("!", function_name, "!"),
Primitive("!=", function_name, "!="),
Primitive("string_find", function_name,"string_find")
# ...
] + [
# field_name:
Primitive('', field_name, '')
# ...
] + [
#
Primitive(f'var{str(i)}', name, f'var{str(i)}') for i in range(12)
]
#for first pass, can just hard code vars and maps n stuff
def ec_prog_to_uast(prog): # TODO
# ideally, just evaluate and then parse
uast = prog.evaluate([])
return uast
def deepcoderProductions():
return [(0.0, prim) for prim in deepcoderPrimitives()]
# def flatten_program(p):
# string = p.show(False)
# num_inputs = string.count('lambda')
# string = string.replace('lambda', '')
# string = string.replace('(', '')
# string = string.replace(')', '')
# #remove '_fn' (optional)
# for i in range(num_inputs):
# string = string.replace('$' + str(num_inputs-i-1),'input_' + str(i))
# string = string.split(' ')
# string = list(filter(lambda x: x is not '', string))
# return string
if __name__ == "__main__":
#g = Grammar.uniform(deepcoderPrimitives())
g = Grammar.fromProductions(deepcoderProductions(), logVariable=.9)
request = arrow(tlist(tint), tint, tint)
p = g.sample(request)
print("request:", request)
print("program:")
print(prettyProgram(p))
print("flattened_program:")
flat = flatten_program(p)
print(flat)
| true |
8993e0499226fed2162532546b19ba566715c6e8 | Python | syahrulhamdani/randomiser | /src/randomiser/__init__.py | UTF-8 | 1,637 | 2.8125 | 3 | [
"MIT"
] | permissive | import requests
from requests.exceptions import RequestException
from randomiser.config import RESOURCE_TO_ENDPOINT
from randomiser.exception import ResourceNotFound, RandomizerReadError
class Randomizer:
"""A random generator class of anything.
For detailed resources see here:
https://random-data-api.com/documentation
"""
def __init__(self, resource="food", size=5, is_xml=True):
self.resource = resource
if resource not in RESOURCE_TO_ENDPOINT.keys():
raise ResourceNotFound(
f"Resource {self.resource} not found. "
f"Available resources:\n{self._list_resources()}"
)
self.size = size
self.is_xml = is_xml
@property
def endpoint(self):
if not hasattr(self, "_endpoint"):
endpoint = RESOURCE_TO_ENDPOINT.get(self.resource)
setattr(self, "_endpoint", endpoint)
return getattr(self, "_endpoint")
def _list_resources(self):
available_resource = ", ".join(list(RESOURCE_TO_ENDPOINT.keys()))
return available_resource
def get(self):
"""Get resources.
Returns:
dict: A dictionary representing resources.
"""
uri = "https://random-data-api.com/api" + self.endpoint
payload = {
"size": self.size,
"is_xml": self.is_xml
}
try:
res = requests.get(uri, params=payload)
res.raise_for_status()
except RequestException as err:
raise RandomizerReadError("Failed to get resources.\n{}".format(err))
return res.json()
| true |
b20990452bf9eba76bd20283fccdb1f0d4671915 | Python | SilviaSanjose/Portal_Anuncios_Flask | /clases/modelo.py | UTF-8 | 371 | 2.578125 | 3 | [] | no_license |
class Anuncio():
def __init__(self, nombre = "", categoria = "", precio = 0.0, descripcion = "", envio = "", contacto = "", num_id= 0 ):
self.nombre = nombre
self.categoria = categoria
self.precio = precio
self.descripcion = descripcion
self.envio = envio
self.contacto = contacto
self.num_id = num_id | true |
463c4eae1ef1a69cf3255480c8af1fbf55fd849d | Python | cragod/CYWidgets | /cy_widgets/exchange/order.py | UTF-8 | 4,535 | 2.96875 | 3 | [
"MIT"
] | permissive | import math
from enum import Enum
from functools import reduce
from cy_components.utils.coin_pair import CoinPair
class OrderSide(Enum):
BUY = 'buy' # 多
SELL = 'sell' # 空
CLOSE = 'close' # 平
class OrderType(Enum):
MARKET = 'market' # 市价
LIMIT = 'limit' # 限价
class Order:
"""订单类,带订单信息,已经最终下单信息
输出订单格式:
{
'info': order,
'id': str(order['id']),
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'lastTradeTimestamp': None,
'symbol': symbol,
'type': orderType,
'side': side,
'price': self.safe_float(order, 'price'),
'average': self.safe_float(order, 'avg_execution_price'),
'amount': self.safe_float(order, 'original_amount'),
'remaining': self.safe_float(order, 'remaining_amount'),
'filled': self.safe_float(order, 'executed_amount'),
'status': status,
'fee': None,
}
"""
# 输出订单
__result_orders = list()
def __init__(self, coin_pair: CoinPair,
base_coin_amount,
trade_coin_amount,
leverage=1,
side=OrderSide.BUY,
type=OrderType.LIMIT,
bid_order_price_coefficient=1.01,
ask_order_price_coefficient=0.99):
super().__init__()
self.coin_pair = coin_pair
self.base_coin_amount = base_coin_amount
self.trade_coin_amount = trade_coin_amount
self.leverage = leverage
self.side = side
self.type = type
self.bid_order_price_coefficient = bid_order_price_coefficient
self.ask_order_price_coefficient = ask_order_price_coefficient
@staticmethod
def fetch_cost_amount(order_info):
"""获取花费的币数量"""
if order_info:
# 没有 cost 字段的,用 filled * price 计算出实际花费
if order_info.get('cost'):
return order_info['cost']
if order_info.get('filled') and order_info.get('price'):
return order_info['filled'] * order_info['price']
return 0
@staticmethod
def all_filled(order_info):
"""检查是否全成交"""
return order_info['remaining'] is not None and math.isclose(order_info['remaining'], 0.0)
@staticmethod
def set_order_side(order_info, side: OrderSide):
"""更新Side"""
if order_info and order_info.get('side'):
order_info['side'] = side.value.lower()
return order_info
def integrate_orders(self, order_infos, fetch_ticker_func):
"""整合一组订单
Parameters
----------
order_infos : [dict]
订单列表,每项一个字典
fetch_ticker_func : func
获取 ticker 方法
Returns
-------
[dict]
一组订单
"""
if not order_infos:
return None
elif len(order_infos) == 1:
return order_infos[0]
def reduce_order_field(key, order_list):
"""同字段累加"""
if len(order_list) == 1:
return order_list[0][key]
return reduce(lambda x, y: x[key] + y[key], order_list)
filled = reduce_order_field('filled', order_infos)
cost = reduce_order_field('cost', order_infos)
amount = reduce_order_field('filled', order_infos[:-1]) + order_infos[-1]['amount']
# 剩余和价格取最后一个订单
remaining = order_infos[-1]['remaining']
price = order_infos[-1]['price']
# 计算成交均价
if cost and filled:
average = cost / filled
else:
# 有的平台没有足够信息,暂定用盘口价格来计算 average/cost
ask_price, bid_price = fetch_ticker_func()
estimated_price = ask_price if self.__order.side == OrderSide.BUY else bid_price
average = estimated_price
cost = average * filled
result_order = order_infos[-1]
result_order['filled'] = filled
result_order['cost'] = cost
result_order['amount'] = amount
result_order['remaining'] = remaining
result_order['price'] = price
result_order['average'] = average
# self._log_procedure('Integrate Orders', result_order)
return result_order
def append_order(self, order_info):
self.__result_orders.append(order_info)
| true |
82b2c38e4a973d306202896aa78feceac3aad82d | Python | jhchiu1/weather_api | /weatherapi.py | UTF-8 | 601 | 2.96875 | 3 | [] | no_license | # Weather API
# Code sample from https://www.wunderground.com/weather/api/d/docs?d=resources/code-samples&MR=1
import urllib.request
import json
# URL where API is called
call = urllib.request.urlopen('http://api.wunderground.com/api/66bc345f90882b9f/geolookup/conditions/q/CA/San_Jose.json')
json_string = call.read()
parsed_json = json.loads(json_string)
# Get key data pairs
location = parsed_json['location']['city']
temp_f = parsed_json['current_observation']['temp_f']
# Print temperature based on city location
print ("Current temperature in %s is: %s" % (location, temp_f))
call.close()
| true |
bed3649da136c17559de9175ea4293d049d665b0 | Python | guymatz/gcf | /gcf.py | UTF-8 | 1,809 | 3.578125 | 4 | [] | no_license | #!/usr/bin/env python
import sys
import math
if len(sys.argv) < 3:
print "Please enter two numbers to find their GCF"
exit(1)
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
def gcf(num1, num2):
# Sadie said to find prime factors
num1_pfs = find_prime_factors(num1)
#print "PFs for num1 = ", num1_pfs
num2_pfs = find_prime_factors(num2)
#print "PFs for num2 = ", num2_pfs
# She then said to find their common factors
cfs = find_common_factors(num1_pfs, num2_pfs)
#print "CFs num2 = ", cfs
# And then finally multiply the common factors
return multiply_common_factors(cfs)
def is_prime(num):
if num in [2,3]:
return True
max_num = int(math.ceil(math.sqrt(num)))
#print "Max of %i for %i" % (max_num, num)
for n in range(2,max_num+1):
#print "Checking if %i divides %i" % (n, num)
if num % n == 0:
#print "returning False"
return False
#print "returning True"
return True
def find_prime_factors(num):
pfs = []
n = 2
while num > 1:
if num % n != 0:
n += 1
continue
if is_prime(n):
#print "%i is prime" % n
pfs.append(n)
num = num / n
n = 2
#print "num = ", num, ", n = ", n
return pfs
def find_common_factors(num1_pfs, num2_pfs):
cfs = []
# Loop trough prime factors of num1. If num_pfs has that
# prime factor, then it's common
for n in num1_pfs:
for i in range(0,len(num2_pfs)):
if n == num2_pfs[i]:
cfs.append(n)
# I need to get rid of this common factor, so i'll just set it to 1
num2_pfs[i] = 1
return cfs
def multiply_common_factors(cfs):
total = 1
for n in cfs:
total = total * n
return total
print gcf(num1, num2)
# vim: ts=2 expandtab sw=2 sts=2
| true |
d16eccf331c14d366e3527538eb00c91bdda600f | Python | Nellrun/VyatSU | /6 Семестр/Параллельное программирование/Лабы/lab_1/main.py | UTF-8 | 163 | 3 | 3 | [] | no_license | import numpy as np
def makeMatrix(h, w):
m = np.arange(1, h*w)
np.random.shuffle(m)
m = np.append(m, 0)
return np.reshape(m, [h, w])
print(makeMatrix(3, 4)) | true |
ce5c7f582e1eed8987abf0ef9e3e27808d378a24 | Python | tjbotfan/tbf7 | /ch11/OLED.py | UTF-8 | 2,747 | 2.6875 | 3 | [] | no_license | # coding: utf-8
import sys
import Adafruit_SSD1306
import time
# import Image
# import ImageDraw
# import ImageFont
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
# argument
args = sys.argv
sel = args[1]
# Raspberry Pi pin configuration
RST = 1
# Initialise Libraly
disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)
disp.begin()
# Misaki Font, awesome 8x8 pixel Japanese font, can be downloaded from the followig site$
# $ wget http://www.geocities.jp/littlimi/arc/misaki/misaki_ttf_2015-04-10.zip
font = ImageFont.truetype('/home/pi/font/misakifont/misaki_gothic.ttf', 8, encoding='unic')
# Clear display.
disp.clear()
disp.display()
# Create blank image for drawing.
# Make sure to create image with mode '1' for 1-bit color.
width = disp.width
height = disp.height
image = Image.new('1', (width, height))
# Get drawing object to draw on image.
draw = ImageDraw.Draw(image)
# Draw a black filled box to clear the image.
draw.rectangle((0,0,width,height), outline=0, fill=0)
if sel == '1':
# Draw LED as an ellipse
draw.ellipse((24, 1,32,10), outline=255, fill=0)
# Draw face as a rectangle
draw.rectangle((1, 6, 56, 46), outline=255, fill=0)
# Draw eyes as ellipses
draw.ellipse((13,34,20,42), outline=255, fill=0)
draw.ellipse((37,34,44,42), outline=255, fill=0)
# Draw Mouth as a polygon
draw.polygon([(1,54), (56,51), (56,60), (1,63)], outline=255, fill=0)
# Write text.
top=10
x=64
draw.text((x, top), u'こんにちは', font=font, fill=255)
draw.text((x, top+15), u'わたしは', font=font, fill=255)
draw.text((x, top+30), u'TJBot zero', font=font, fill=255)
draw.text((x, top+45), u'です', font=font, fill=255)
elif sel == '2':
# Draw LED as an ellipse
draw.ellipse((24, 1,32,10), outline=255, fill=255)
# Draw a rectangle.
# Draw face
draw.rectangle((1, 6, 56, 46), outline=255, fill=255)
# Draw an ellipse.
# Draw eyes
draw.ellipse((13,34,20,42), outline=255, fill=0)
draw.ellipse((37,34,44,42), outline=255, fill=0)
# Draw a polygon.
# Draw Mouth
draw.polygon([(1,54), (56,51), (56,60), (1,63)], outline=255, fill=255)
# Write two lines of text.
top=20
x=64
draw.text((x, top), u'わたしと', font=font, fill=255)
draw.text((x, top+15), u'いっしょに', font=font, fill=255)
draw.text((x, top+30), u'あそびましょう', font=font, fill=255)
elif sel == '3':
image = Image.open('./TJBot_pic.jpg').resize((128, 64), Image.LANCZOS).convert("1")
else:
sys.exit(1)
disp.image(image)
disp.display() | true |
9906a1841420a549ee874f1ccc119b07a15a6087 | Python | chengzi-lizi/CHENGZI | /009.py | UTF-8 | 323 | 3.5 | 4 | [] | no_license | # coding=utf-8
def josephus(n,k):
loop = [number for number in (range(1,n+1))]
a = 0
while True:
b = loop.pop(0)
a += 1
if a == k:
a = 0
continue
loop.append(b)
if len(loop) == int(k-1):
print(loop)
break
josephus(50,3)
| true |
d3367ce3ff03acf83a9e1f9fba552f8227f4514c | Python | iontrapnet/LaF | /Jupyter/mktemp.py | UTF-8 | 85 | 2.53125 | 3 | [] | no_license | import tempfile
f = tempfile.NamedTemporaryFile(delete=False)
f.close()
print(f.name) | true |
3148a6f5701ff59f51059d38649e45ffcc4ea0d2 | Python | 7kbird/learning_notes | /yama/vision/datasets/storage.py | UTF-8 | 1,152 | 2.828125 | 3 | [] | no_license | import os
class Storage(object):
"""An abstract class represent an image storage
All image storage should subclass it. All subclasses should override
``root``, that provide the storage path for the source
"""
def root(self, source_name):
raise NotImplementedError()
class PaperSpaceGradientStorage(Storage):
"""Image storage for Paperespage Gradient Storage
Paperespage Gradient provide a default readonly directory which contains
most popular datasets.
"""
def __init__(self, download_dir='/storage/down', default_dir='/datasets'):
self.download_dir = download_dir
self.default_dir = default_dir
def root(self, source_name):
support_dic = {
'imagenet_full': 'ImageNetFull',
}
if source_name in support_dic:
return os.path.join(self.default_dir, support_dic[source_name])
return os.path.join(self.download_dir, source_name)
class LocalStorage(Storage):
def __init__(self, root_dir):
self.root_dir = root_dir
def root(self, source_name):
return os.path.join(self.root_dir, source_name)
| true |
000054715378a31a14aa80eb1bc2001b226f6979 | Python | alexartwww/python-faq | /classes.py | UTF-8 | 232 | 3.171875 | 3 | [] | no_license | class A(object):
def __init__(self):
self.a = 1
class B(object):
def __init__(self):
self.a = 2
class C(A, B):
def __init__(self):
self.a = 3
super().__init__()
obj = C()
print(obj.a)
| true |
117f69511983ec3daa2fea742ba748f4998f53d0 | Python | Spartabariallali/API_json | /python_json_one.py | UTF-8 | 1,124 | 4.1875 | 4 | [] | no_license | #import json
import json
car_data = {"name": "tesla",
"engine":"electric"}
print(car_data)
print(type(car_data)) # <class dict>
# json.dumps changes python dictionary to json string
car_data_json_string = json.dumps(car_data)
print(type(car_data_json_string)) # returns <class string>
# removes the need to cast data scraped from the web into specific data types
# create a jsonfile with writing permissions
with open("new_json_file.json","w") as jsonfile:
json.dump(car_data, jsonfile) #
# ENCODING and writing into json file
# "w" gives write permissions
# the dump method takes two args : the first = dictionary, second = the jsonfile(fileobject)
#"enter the name of the file", permission type
with open("new_json_file.json") as jsonfile: # Decoding
# Reading from the file we just created
car = json.load(jsonfile) # storing data from file to car variable
print(type(car)) # Checking the type of the data again
print(car['name']) # To get the value stored in key called name
print(car['engine']) # To get the value of second key value pair
| true |
8548afd816222be6dd5c41a0ae87969177aa85a6 | Python | cryptomental/megaphone | /megaphone/post.py | UTF-8 | 4,368 | 2.828125 | 3 | [
"MIT"
] | permissive | import json
import time
from contextlib import suppress
from dateutil import parser
from piston.steem import Post as PistonPost
from megaphone.helpers import parse_payout, time_diff
from megaphone.node import Node
class PostError(RuntimeError):
pass
class Post(PistonPost):
"""
Piston Post enhanced with metadata and a few utility methods.
"""
def __init__(self, post, chaind=None):
if not chaind:
chaind = Node().default()
self.blockchain_name = chaind.rpc.get_config()['BLOCKCHAIN_NAME']
if isinstance(post, PistonPost):
post = post.identifier
super(Post, self).__init__(chaind, post)
@property
def meta(self):
"""
JSON metadata of the post.
:return: post metadata
:rtype: json
"""
with suppress(Exception):
meta_str = self.get("json_metadata", "")
meta = json.loads(meta_str)
return meta
@property
def url(self):
"""
Return post's url.
:return: URL
:rtype: str
"""
url_prefix = {"STEEM": "https://steemit.com",
"GOLOS": "https://golos.io"}
if self.blockchain_name not in url_prefix.keys():
raise PostError("Trying to access post from not supported chain.")
return "%s/%s/%s" % (url_prefix[self.blockchain_name], self.category,
self.identifier)
def is_comment(self):
"""
Return True if post is a comment. Post is a comment if it has an empty
title, its depth is greater than zero or it does have a parent author.
:return: True if post is a comment, false otherwise
:rtype: bool
"""
if len(self["title"]) == 0 or self["depth"] > 0 \
or len(self["parent_author"]) > 0:
return True
else:
return False
def get_votes(self, from_account=None):
"""
Get votes for an account.
:param from_account:
:return:
"""
votes = []
for vote in self['active_votes']:
vote['time_elapsed'] = int(time_diff(self['created'], vote['time']))
if from_account and vote['voter'] == from_account:
return vote
votes.append(vote)
return votes
def get_metadata(self):
"""
Get metadata of the post: number of rshares, sum of weights
and time elapsed since the post was created.
:return: metadata
:rtype: dict
"""
rshares = int(self["vote_rshares"])
weight = int(self["total_vote_weight"])
if int(self["total_vote_weight"]) == 0 and self.time_elapsed() > 3600:
weight = 0
rshares = 0
for vote in self['active_votes']:
weight += int(vote['weight'])
rshares += int(vote['rshares'])
return {
"rshares": rshares,
"weight": weight,
"time_elapsed": self.time_elapsed(),
}
def contains_tags(self, filter_by=('spam', 'test', 'nsfw')):
"""
Check if a post contains certain tags.
Default: spam, test, nsfw (Not Suitable For Work)
:param filter_by: tags to filter the post with
:type filter_by: tuple of str
:return: True if post contains any of the tags, False otherwise
:rtype: bool
"""
for tag in filter_by:
if tag in self['_tags']:
return True
return False
def time_elapsed(self):
"""
Return time elapsed since the post was created.
:return: time elapsed in seconds since post creation
:rtype int
"""
created_at = parser.parse(self['created'] + "UTC").timestamp()
now_adjusted = time.time()
return now_adjusted - created_at
def payout(self):
"""
Return post payout.
:return: post payout
:rtype: float
"""
return parse_payout(self['total_payout_reward'])
def calc_reward_pct(self):
"""
Calculate post reward percentage.
:return: reward percent
:rtype: int
"""
reward = (self.time_elapsed() / 1800) * 100
if reward > 100:
reward = 100
return reward
| true |
3f12c17196541dc6c673bb8197ea24591835244f | Python | malidrsn/OpenCV-Tutorial-w-Basic-Examples | /cizim/cizim.py | UTF-8 | 1,229 | 3.234375 | 3 | [
"MIT"
] | permissive | import cv2
import numpy as np
canvas = np.zeros((512, 512, 3), dtype=np.uint8) + 255 # +255 dersek canvasın rengini beyaza çevirir
# print(canvas)
cv2.line(canvas, (50, 50), (512, 512), (255, 0, 0), thickness=5)
cv2.line(canvas, (100, 50), (200, 250), (0, 0, 255), thickness=1)
cv2.rectangle(canvas, (20, 20), (50, 50), (0, 255, 0),
thickness=-1) # içi dolu diktörtgen çizmek istiyorsak thickness değerini -1 yapıyoruz.
cv2.circle(canvas, (255, 255), 100, (0, 0, 255), thickness=5) # içi dolu yapmak istersek thickness -1 yapıyoruz
# üçgen çizimi için özel bir yol yok fonksiyon yazmalıyız yada kendimize özel bir yöntem belirlemeliyiz.
p1 = (100, 200)
p2 = (50, 50)
p3 = (300, 100)
cv2.line(canvas, p1, p2, (0, 0, 0), 4)
cv2.line(canvas, p2, p3, (0, 0, 0), 4)
cv2.line(canvas, p1, p3, (0, 0, 0), 4)
points = np.array([[100, 200], [330, 200], [290, 220], [100, 100]], np.int32)
cv2.polylines(canvas, [points], True, (0, 0, 100),
thickness=5) # True olan değer birleştirme sağlıyor kapatıyor. false olsa kapamaz
cv2.ellipse(canvas, (300, 300), (80, 20), 0, 90, 360, (255, 255, 0), thickness=-1)
cv2.imshow("Canvas", canvas)
cv2.waitKey(0)
cv2.destroyAllWindows()
| true |
72d7d81e52ef7b8e847a82cc710f2b547df7b4f3 | Python | green0range/IoT-ecosanctuary-web-monitoring-collector | /main.py~ | UTF-8 | 3,130 | 2.953125 | 3 | [] | no_license | #! /usr/bin/python
# Imports
import time
import serialinterface
import server
from threading import Thread
# This system creates 2 threads, 1 to constantly check for new data, and 1 to process already found data.
# Multi-threading is used so that the collector doesn't miss any new data while processing older data.
received_data = []
#Processor thread
class Processor(Thread):
global received_data
def __init__(self):
Thread.__init__(self)
self.daemon = True
self.start()
self.sensors = []
self.get_dat()
self.serv = server.Server()
for i in range(0, len(self.sensors)):
self.sensors[i] = self.sensors[i].split(",")
#NOT USED The data is now formated server side, server will still accept preformatted though.
def get_dat(self):
# This reads in the data file, which contains the data for which sensor is where
# and what attachments they have
try:
f = open('sensors.dat', 'r')
dat = f.read()
f.close()
# Process dat file
sData = dat.split("\n")
for i in range(0, len(sData)):
if list(sData[i])[0] == "#": # Comments
pass
else:
self.sensors.append(sData[i])
except:
print "No sensor config file, if you are using the newer server side formating, ignorge this warning."
def run(self):
global received_data
# Takes the first in queue
if len(received_data) > 0:
self.processing = received_data.pop(0)
print "started processing..." + str(self.processing)
else:
self.processing = "NO_DATA"
# Loops through known sensors to find matching id.
if self.processing != "NO_DATA":
#for i in range(0, len(self.sensors)):
# since we are not using the config id system, this will submit all data with placeholder locations
# If the server gets anything with -1 lat it will use it's own id system, otherwise it will use the
# give value.
self.serv.submit_data("-1", "-1", ord(self.processing[0]), ord(self.processing[1]), time.time())
class Reader(Thread):
global received_data
def __init__(self):
self.conn = serialinterface.Connection()
Thread.__init__(self)
self.daemon = True
self.start()
def run(self):
global received_data
# Appends all data it gets to the received data list.
# This doubles as a processing queue for the processor.
# The Processor MUST remove data once processed, otherwise we have a memory leaks.
data = self.conn.get_input()
if data != -1:
received_data.append(data)
print received_data
# print startup message
print "Running data collection program. Press Ctrl+C to stop"
print "Warning, stopping will stop all data collection, warnings, alerts etc. You have been warned!"
# Create threads
p = Processor()
r = Reader()
# Run the main loop of the processor and reader thread.
while 1:
r.run()
p.run()
| true |
91ca1270f290843e1ed92d22d41c2519d15b0f45 | Python | obround/ppci | /test/graph/test_relooper.py | UTF-8 | 1,239 | 2.71875 | 3 | [
"BSD-2-Clause"
] | permissive | """ Test algorithms which reconstruct structured flow blocks from cfg """
import unittest
import io
from ppci.graph import relooper
from ppci import irutils
class RelooperTestCase(unittest.TestCase):
def test_return_from_loop(self):
""" Check the behavior when we return from within a loop """
mod = """module foo;
global procedure x() {
block1: {
jmp block2;
}
block2: {
i32 a = 2;
i32 b = 5;
cjmp a < b ? block3 : block4;
}
block3: {
exit;
}
block4: {
i32 c = 2;
i32 d = 5;
cjmp c < d ? block5 : block6;
}
block5: {
jmp block2;
}
block6: {
exit;
}
}
"""
ir_module = irutils.read_module(io.StringIO(mod))
ir_function = ir_module['x']
# print(ir_function)
# irutils.print_module(ir_module)
shape, _ = relooper.find_structure(ir_function)
# relooper.print_shape(shape)
# print(shape)
if __name__ == '__main__':
unittest.main()
| true |
ba2ff42e7b24d2fcbd26ac7880f07b567c25b295 | Python | cligmanowski/work-at-olist | /work-at-olist/olistconnect/management/commands/importcategories.py | UTF-8 | 2,685 | 2.796875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import sys
import csv
from django.core.management.base import BaseCommand, CommandError
from django.db.utils import IntegrityError
from olistconnect.models import *
class Command(BaseCommand):
help = ' Import categories from specified CSV file '
channelObj = None
def add_arguments(self, parser):
parser.add_argument('channelName', type=str, help='The channel\'s name that will be stored')
parser.add_argument('csvFile', help='The CSV file that has the categories to be imported')
def handle(self, *args, **options):
channel = options['channelName']
csvFileName = options['csvFile']
try:
self.channelObj = Channel()
self.channelObj.name = channel
self.channelObj.save()
self.readFile(csvFileName)
except CommandError,IntegrityError:
raise CommandError('File "%s" does not exist' % csvFileName)
raise IntegrityError('Already has a channel named "%s"' % channel)
self.stdout.write(self.style.SUCCESS('CSV file "%s" Successfully read' % csvFileName))
def readFile(self, csvFileName):
with open(csvFileName) as csvFile:
read = csv.DictReader(csvFile)
for row in read:
categoryPath = row['Category']
if (categoryPath!=""):
self.saveCategories(categoryPath)
def saveCategories(self,categoryPath):
categories = categoryPath.split("/")
pathLen = len(categories)
ancestor = None
descendant = None
categoryObjList = []
categoryObj = None
categoryTreeObj = None
if (pathLen==1):
category = categories[0].strip()
categoryObj = Category()
categoryTreeObj = CategoryPath()
categoryObj.name = category
categoryObj.categoryChannel = self.channelObj
categoryObj.save()
categoryTreeObj.setDescendant(categoryObj)
categoryTreeObj.setAncestor(ancestor)
categoryTreeObj.save()
else:
for count in range(0,pathLen-1):
category = categories[count].strip()
# print('Buscando "%s" no banco de dados' % category)
categoryObj = Category.objects.get(name=category)
# if categoryObj:
# print('Categoria "%s" encontrada com sucesso' % categoryObj.name)
categoryObjList.append(categoryObj)
categoryObj = Category()
categoryObj.name = categories[pathLen-1].strip()
categoryObj.categoryChannel = self.channelObj
categoryObj.save()
categoryObjList.append(categoryObj)
descendant = categoryObj
objLen = len(categoryObjList)
for ancestor in categoryObjList:
print ancestor.name
categoryTreeObj = CategoryPath()
categoryTreeObj.setAncestor(ancestor)
categoryTreeObj.setDescendant(descendant)
categoryTreeObj.save()
| true |
94852969a654216ec5227cc40ea847743bab3abf | Python | macoto35/Algorithms_Kata | /python/pythonds/8_graphsAndGraphAlgorithms/test_graph_impl_edge_list.py | UTF-8 | 4,558 | 3.234375 | 3 | [] | no_license | import unittest
from graph_impl_edge_list import EdgeListGraph
class TestGraphImplEdgeList(unittest.TestCase):
def setUp(self):
self.g = EdgeListGraph()
def test_undirected_unweighted(self):
arr = [('A', 'D', 1), ('A', 'C', 1), ('B', 'C', 1), ('C', 'D', 1), ('C', 'E', 1)]
for fromKey, toKey, weight in arr:
self.g.add_edge(fromKey, toKey)
self.assertFalse('F' in self.g)
self.assertTrue('A' in self.g)
self.assertTrue('B' in self.g)
self.assertTrue('C' in self.g)
self.assertTrue('D' in self.g)
self.assertTrue('E' in self.g)
nodes = ['A', 'B', 'C', 'D', 'E']
neighbours = [('D', 1), ('C', 1), ('C', 1), ('A', 1), ('B', 1), ('D', 1), ('E', 1), ('A', 1), ('C', 1), ('C', 1)]
i = 0
for node in nodes:
for item in self.g.neighbours(node):
self.assertEqual(neighbours[i], item)
i += 1
tmpNodes = ['A', 'D', 'C', 'B', 'E']
i = 0
for node in self.g.nodes():
self.assertEqual(tmpNodes[i], node)
i += 1
i = 0
for edge in self.g.edges():
self.assertEqual(arr[i], edge)
i += 1
def test_undirected_weighted(self):
arr = [('A', 'D', 5), ('A', 'C', 12), ('B', 'C', 4), ('C', 'D', 7), ('C', 'E', 3)]
for fromKey, toKey, weight in arr:
self.g.add_edge(fromKey, toKey, weight)
self.assertFalse('F' in self.g)
self.assertTrue('A' in self.g)
self.assertTrue('B' in self.g)
self.assertTrue('C' in self.g)
self.assertTrue('D' in self.g)
self.assertTrue('E' in self.g)
nodes = ['A', 'B', 'C', 'D', 'E']
neighbours = [('D', 5), ('C', 12), ('C', 4), ('A', 12), ('B', 4), ('D', 7), ('E', 3), ('A', 5), ('C', 7), ('C', 3)]
i = 0
for node in nodes:
for item in self.g.neighbours(node):
self.assertEqual(neighbours[i], item)
i += 1
tmpNodes = ['A', 'D', 'C', 'B', 'E']
i = 0
for node in self.g.nodes():
self.assertEqual(tmpNodes[i], node)
i += 1
i = 0
for edge in self.g.edges():
self.assertEqual(arr[i], edge)
i += 1
def test_directed_unweighted(self):
arr = [('A', 'D', 1), ('D', 'A', 1), ('C', 'A', 1), ('C', 'B', 1), ('D', 'C', 1), ('E', 'C', 1)]
for fromKey, toKey, weight in arr:
self.g.add_edge(fromKey, toKey)
self.assertFalse('F' in self.g)
self.assertTrue('A' in self.g)
self.assertTrue('B' in self.g)
self.assertTrue('C' in self.g)
self.assertTrue('D' in self.g)
self.assertTrue('E' in self.g)
nodes = ['A', 'B', 'C', 'D', 'E']
neighbours = [('D', 1), ('D', 1), ('C', 1), ('C', 1), ('A', 1), ('B', 1), ('D', 1), ('E', 1), ('A', 1), ('A', 1), ('C', 1), ('C', 1)]
i = 0
for node in nodes:
for item in self.g.neighbours(node):
self.assertEqual(neighbours[i], item)
i += 1
tmpNodes = ['A', 'D', 'C', 'B', 'E']
i = 0
for node in self.g.nodes():
self.assertEqual(tmpNodes[i], node)
i += 1
i = 0
for edge in self.g.edges():
self.assertEqual(arr[i], edge)
i += 1
def test_directed_weighted(self):
arr = [('A', 'D', 2), ('D', 'A', 10), ('C', 'A', 12), ('C', 'B', 4), ('D', 'C', 7), ('E', 'C', 3)]
for fromKey, toKey, weight in arr:
self.g.add_edge(fromKey, toKey, weight)
self.assertFalse('F' in self.g)
self.assertTrue('A' in self.g)
self.assertTrue('B' in self.g)
self.assertTrue('C' in self.g)
self.assertTrue('D' in self.g)
self.assertTrue('E' in self.g)
nodes = ['A', 'B', 'C', 'D', 'E']
neighbours = [('D', 2), ('D', 10), ('C', 12), ('C', 4), ('A', 12), ('B', 4), ('D', 7), ('E', 3), ('A', 2), ('A', 10), ('C', 7), ('C', 3)]
i = 0
for node in nodes:
for item in self.g.neighbours(node):
self.assertEqual(neighbours[i], item)
i += 1
tmpNodes = ['A', 'D', 'C', 'B', 'E']
i = 0
for node in self.g.nodes():
self.assertEqual(tmpNodes[i], node)
i += 1
i = 0
for edge in self.g.edges():
self.assertEqual(arr[i], edge)
i += 1
if __name__ == '__main__':
unittest.main()
| true |
4d42f50f0fff7fdc71bd342396aef5ce186d184d | Python | serfedor/Programm | /python_work/vars/2-6.py | UTF-8 | 115 | 2.890625 | 3 | [] | no_license | #by SerLonic
phrase = "God lead's us"
autor = "Sergey Fedorenko"
message = phrase + " here autor is " + autor
print(message)
| true |
55963ccfa017517a87aeaa5d2006898fe167e382 | Python | Mschikay/leetcode | /526. Beautiful Arrangement.py | UTF-8 | 1,797 | 3.640625 | 4 | [] | no_license | # DFS
# default every number on 1 works
# input: 4
# output:
# [False, True, True, True, False] 0
# [False, True, False, True, True] 1
# [False, True, True, False, True] 2
# [False, True, True, True, False] 3
# [False, False, True, True, True] 4
# [False, True, True, False, True] 5
# [False, True, False, True, True] 6
# [False, False, True, True, True] 7
class Solution:
def countArrangement(self, N: int) -> int:
def dfs(visited, loc, number, res):
if number % loc == 0 or loc % number == 0:
if loc == N:
return res + 1
for newN in range(1, len(visited)):
if visited[newN]:
continue
visited[newN] = True
res = dfs(visited, loc + 1, newN, res)
visited[newN] = False
return res
visited = [False for i in range(N + 1)]
return dfs(visited, 1, 1, 0)
#
class Solution:
def countArrangement(self, N: int) -> int:
def dfs(visited, loc, number, res):
if loc == 0 or number % loc == 0 or loc % number == 0:
if loc == N:
print(visited, res)
return res + 1
for newN in range(1, len(visited)):
if visited[newN]:
continue
visited[newN] = True
res = dfs(visited, loc + 1, newN, res)
visited[newN] = False
return res
visited = [False for i in range(N + 1)]
return dfs(visited, 1, 0, 0)
# 看不懂的一个解
# https://leetcode.com/problems/beautiful-arrangement/discuss/99758/3-liner-DFS-with-%22Trie%22-perspective-(detailed-explanation-with-picture-illustration)
| true |
1b61ea4d2307020f2fa511b862c1dd7c3d813c0a | Python | SpectrePrediction/warrior | /warrior/StaticGraph/Operation/nn/nn.py | UTF-8 | 14,829 | 2.546875 | 3 | [] | no_license | from ..Operation import *
class Conv2d(Operation):
def __init__(self, x, filter_num, kernel_size, padding=0, stride=1, bias=True, data_format='NCHW', name=None):
"""
[n, c, h, w]
:param x: 应当是一个值类型为numpy.array的节点
:param filter_num:
:param kernel_size:
:param padding:
:param stride:
:param bias:
:param data_format:'NCHW' 'NHWC' 可以打乱顺序大小写等,通用 支持3位'CHW'
:param name:
"""
super(self.__class__, self).__init__(x, name=name)
self.filter_num = filter_num
data_format = data_format.upper()
try:
assert data_format.__len__() == 3 or data_format.__len__() == 4, "data_format应当是3位或者4位"
except AssertionError:
Error("data_format : {} 应当是一个4位字母或者3位字母的字符串"
"节点 {} \ndata_format得到 {}".format(data_format, str(self.tensor), data_format.__len__()),
is_raise=True, exc_info=AssertionError)
self.format_num = data_format.__len__()
self.transpose_index = (
data_format.index("N"), data_format.index("C"),
data_format.index("H"), data_format.index("W")
) if self.format_num == 4 else (
data_format.index("C"), data_format.index("H"), data_format.index("W")
)
self.kernel_size = (kernel_size, kernel_size) if isinstance(kernel_size, int) else kernel_size
padding = (padding, padding) if isinstance(padding, int) else padding
self.padding = (
(0, 0), (0, 0),
padding, padding
) if self.format_num == 4 else (
(0, 0), padding, padding
)
self.stride = (stride, stride) if isinstance(stride, int) else stride
self._param = dict()
# 修改权重,以应对没预热无法加载权重
self._param["need_init"] = True
self._param["weight"] = Variable(np.zeros(1), name=self.tensor.name.split("in")[0][:-1] + "_weight")
self._param["weight"].tensor.output_nodes.append(self)
# 选择了没有channel参数的版本,那就在有数据的时候初始化
# self._param["weight"] = Variable(np.random.normal(loc=0.0, scale=1.0, size=(
# input_channel*self.kernel_size[0]*self.kernel_size[1], filter_num)
# ), name=None)
if bias:
self._param["bias"] = Variable(np.random.normal(loc=0.0, scale=0.001, size=(1, filter_num)),
name=self.tensor.name.split("in")[0][:-1] + "_bias")
self._param["bias"].tensor.output_nodes.append(self)
else:
self._param["bias"] = None
self.tensor.input_nodes = (self.tensor.input_nodes[0], self._param["weight"], self._param["bias"]) if \
self._param["bias"] else (self.tensor.input_nodes[0], self._param["weight"])
# 减少内存多次开销
self.out = None
# self.y_matrix_array = None
self.grad = None
self.x_matrix = None
self.inputs_x_shape = None
self.out_h = None
self.out_w = None
self.out_array = None
self.out_count = None
def compute_output(self):
try:
x = self.tensor.input_nodes[0]
inputs_x = x.tensor.output_value
inputs_x = np.transpose(inputs_x, self.transpose_index)
self.inputs_x_shape = inputs_x.shape
padding_x = np.pad(inputs_x, self.padding)
batch_size, kernel_c, image_h, image_w = padding_x.shape if padding_x.shape.__len__() == 4 else \
(1, *padding_x.shape)
if self._param["need_init"]:
self._param["weight"].tensor.output_value = np.random.normal(loc=0.0, scale=0.001, size=(
kernel_c*self.kernel_size[0]*self.kernel_size[1], self.filter_num))
self._param["weight"].auto_output()
if self._param["bias"] is not None:
self._param["bias"].auto_output()
self.out_h = (image_h - self.kernel_size[0]) // self.stride[0] + 1
self.out_w = (image_w - self.kernel_size[1]) // self.stride[1] + 1
self.out = np.zeros((self.out_h * self.out_w, self.kernel_size[0] * self.kernel_size[1] * kernel_c)) if \
self.out is None else self.out
y_matrix_array = np.zeros((batch_size, self.filter_num, self.out_h, self.out_w))
self.x_matrix = []
for batch_index in range(batch_size):
batch_x = padding_x[batch_index]
for idx_h, i in enumerate(range(0, image_h - self.kernel_size[0] + 1, self.stride[0])):
for idx_w, j in enumerate(range(0, image_w - self.kernel_size[1] + 1, self.stride[1])):
self.out[idx_h * self.out_w + idx_w, :] = \
batch_x[:, i:i + self.kernel_size[0], j:j + self.kernel_size[1]].reshape(1, -1)
self.x_matrix.append(self.out.copy())
y_matrix = np.dot(self.out, self._param["weight"].tensor.output_value)
if self._param["bias"]:
y_matrix += self._param["bias"].tensor.output_value
for c in range(y_matrix.shape[1]):
y_matrix_array[batch_index, c] = y_matrix[:, c].reshape(self.out_h, self.out_w)
self.x_matrix = np.asarray(self.x_matrix)
self.tensor.output_value = y_matrix_array
except ValueError as err:
print(err)
Error("节点 {} \n错误信息 {} \n请确保数据输入格式与data_format格式一致".format(str(self.tensor), str(err)),
is_raise=True, exc_info=ValueError)
except TypeError as err:
Error("出现无法获取节点值,可能源于你未启动图会话"
"或者在图会话中没有提供占位符具体的值" + str(self.tensor), is_raise=True, exc_info=err)
return self.tensor.output_value
def auto_output(self):
try:
x = self.tensor.input_nodes[0]
if x.tensor.output_value is None:
x.auto_output()
self.compute_output()
# inputs_x = x.tensor.output_value
# inputs_x = np.transpose(inputs_x, self.transpose_index)
# padding_x = np.pad(inputs_x, self.padding)
#
# batch_size, kernel_c, image_h, image_w = padding_x.shape if padding_x.shape.__len__() == 4 else \
# (1, *padding_x.shape)
#
# if self._param["weight"] is None:
# self._param["weight"] = Variable(np.random.normal(loc=0.0, scale=0.001, size=(
# kernel_c*self.kernel_size[0]*self.kernel_size[1], self.filter_num)
# ), name=self.tensor.name.split("in")[0] + "weight")
# # 测试使用
# # self._param["weight"] = Variable(np.ones((
# # kernel_c * self.kernel_size[0] * self.kernel_size[1], self.filter_num)
# # ), name=self.tensor.name + "weight")
# self._param["weight"].auto_output()
# if self._param["bias"] is not None:
# self._param["bias"].auto_output()
#
# out_h = (image_h - self.kernel_size[0]) // self.stride[0] + 1
# out_w = (image_w - self.kernel_size[1]) // self.stride[1] + 1
# # out = np.zeros((out_h*out_w, kernel_h*kernel_w*kernel_c))
# out = np.empty((out_h * out_w, self.kernel_size[0] * self.kernel_size[1] * kernel_c))
# y_matrix_array = np.empty((batch_size, self.filter_num, out_h, out_w))
#
# # out_array = np.empty((kernel_c, image_h, image_w))
# # y = []
# for batch_index in range(batch_size):
# batch_x = padding_x[batch_index]
# for idx_h, i in enumerate(range(0, image_h - self.kernel_size[0] + 1, self.stride[0])):
# for idx_w, j in enumerate(range(0, image_w - self.kernel_size[1] + 1, self.stride[1])):
#
# out[idx_h * out_w + idx_w, :] = \
# batch_x[:, i:i + self.kernel_size[0], j:j + self.kernel_size[1]].reshape(1, -1)
#
# y_matrix = np.dot(out, self._param["weight"].tensor.output_value)
# if self.bias:
# y_matrix += self._param["bias"].tensor.output_value
#
# # 将out变回原图像
# # for i in range(out_h):
# # for j in range(out_w):
# # out_array[:, i * self.stride[0]:i * self.stride[0] + self.kernel_size[0],
# # j * self.stride[1]:j * self.stride[1] + self.kernel_size[1]] = \
# # out[i * out_w + j].reshape(-1, self.kernel_size[0], self.kernel_size[1])
#
# # 测试中在通道为1的情况下还有问题,感觉是个简单的问题,太晚了,搁置先,启用另一种
# # 简单错误,已修复
# for c in range(y_matrix.shape[1]):
# y_matrix_array[batch_index, c] = y_matrix[:, c].reshape(out_h, out_w)
#
# # 速度上差距不大,保留写法, 稍微不好维护
# # y_i = []
# # for c in range(y_matrix.shape[1]):
# # y_i.append(y_matrix[:, c].reshape(out_h, out_w))
# # y.append(np.asarray(y_i))
# # y = np.asarray(np.asarray(y))
#
# self.tensor.output_value = y_matrix_array
except ValueError as err:
print(err)
Error("节点 {} \n错误信息 {} \n请确保数据输入格式与data_format格式一致".format(str(self.tensor), str(err)),
is_raise=True, exc_info=ValueError)
return self.tensor.output_value
def compute_gradient(self, grad=None):
if grad is None:
grad = np.ones_like(self.tensor.output_value)
d_weight = np.zeros_like(self._param["weight"].tensor.output_value)
d_bias = np.zeros_like(self._param["bias"].tensor.output_value) if self._param["bias"] else None
d_x = np.zeros_like(self.out)
grad_b, grad_c, grad_h, grad_w = grad.shape
grad_matrix = np.zeros((grad_b, grad_h*grad_w, grad_c))
for i in range(grad_b):
for j in range(grad_c):
grad_matrix[i, :, j] = grad[i, j, :, :].reshape((-1))
for idx, x_matrix in enumerate(self.x_matrix):
d_weight += np.dot(x_matrix.T, grad_matrix[idx, :, :])
d_x += np.dot(grad_matrix[idx, :, :], self._param["weight"].tensor.output_value.T)
if self._param["bias"]:
d_bias += np.mean(grad_matrix[idx, :, :], axis=0, keepdims=True)
d_weight /= (grad_b * self.out_h * self.out_w) # *self.__kernel_size[1]**self.__kernel_size[2])
d_x /= grad_b
if self._param["bias"]:
d_bias /= grad_b
shape = self.inputs_x_shape if self.inputs_x_shape.__len__() == 4 else (1, *self.inputs_x_shape)
self.out_array = np.zeros(shape) if self.out_array is None else self.out_array
self.out_count = np.zeros(shape) if self.out_count is None else self.out_count
for batch in range(shape[0]):
for i in range((shape[2]-self.kernel_size[0]) // self.stride[0] + 1):
for j in range((shape[3]-self.kernel_size[1]) // self.stride[1] + 1):
self.out_count[batch, :, i * self.stride[0]:i * self.stride[0] + self.kernel_size[0],
j * self.stride[1]:j * self.stride[1] + self.kernel_size[1]] += 1
self.out_array[batch, :, i * self.stride[0]:i * self.stride[0] + self.kernel_size[0],
j * self.stride[1]:j * self.stride[1] + self.kernel_size[1]] +=\
d_x[i * self.out_w + j].reshape(-1, self.kernel_size[0], self.kernel_size[1])
self.out_count[self.out_count == 0] = 1e10
self.out_array /= self.out_count
# x, weight, bias
return self.out_array, d_weight, d_bias
class Sigmoid(Operation):
def __init__(self, x, name=None):
super(self.__class__, self).__init__(x, name=name)
def compute_output(self):
try:
x, = self.tensor.input_nodes
self.tensor.output_value = 1/(1 + np.exp(-x.tensor.output_value))
# if x.tensor.output_value >= 0:
# self.tensor.output_value = 1 / (1 + np.exp(-x.tensor.output_value))
# else:
# self.tensor.output_value = np.exp(-x.tensor.output_value) / (1 + np.exp(-x.tensor.output_value))
except TypeError as err:
Error("出现无法获取节点值,可能源于你未启动图会话"
"或者在图会话中没有提供占位符具体的值" + str(self.tensor), is_raise=True, exc_info=err)
return self.tensor.output_value
def auto_output(self):
x, = self.tensor.input_nodes
if x.tensor.output_value is None:
x.auto_output()
self.tensor.output_value = 1 / (1 + np.exp(-x.tensor.output_value))
# if x.tensor.output_value >= 0:
# self.tensor.output_value = 1/(1 + np.exp(-x.tensor.output_value))
# else:
# self.tensor.output_value = np.exp(-x.tensor.output_value) / (1 + np.exp(-x.tensor.output_value))
return self.tensor.output_value
def compute_gradient(self, grad=None):
if grad is None:
grad = np.ones_like(self.tensor.output_value)
return grad*self.tensor.output_value*(1 - self.tensor.output_value)
"""
损失函数
"""
def get_loss_form_str(optimizer, *, logits, labels):
return globals()[optimizer](logits, labels)
class SSELoss(object):
"""
和方差损失
"""
def __new__(cls, logits, labels):
"""
构造之前,使用魔术方法
返回和方差的节点,而不是类本身
:param logits: 预测值
:param labels: 标签值
:type logits labels: Operation
:return: Operation
"""
try:
assert isinstance(logits, Operation)
assert isinstance(labels, Operation)
except AssertionError as err:
Error("损失函数应当传入节点. in {}".format(cls), is_raise=True, exc_info=err)
cls.logits = logits
cls.labels = labels
return cls.forward(cls)
def forward(self):
return ReduceSum(Square(self.logits - self.labels))
| true |
8c10688451b7912d7574427f75d7c5714223613b | Python | anaobana/CAPG_DESAFIO | /insira_dados.py | UTF-8 | 516 | 3.328125 | 3 | [] | no_license | #CADASTRO DE ANÚNCIOS
import os
base_geral=[]
def insira_dados():
print ("Insira aqui os dados do seu anúncio:\n")
nome = input ("Nome do anúncio: ")
cliente = input ("Nome do cliente: ")
inicio = input ("Data de início: ")
termino = input ("Data de término: ")
investimento_diario = int(input ("Investimento por dia: "))
base=[nome,cliente,inicio,termino,investimento_diario]
base_geral.append(base)
os.system('cls' if os.name == 'nt' else 'clear')
insira_dados()
insira_dados()
| true |
4a5ca9962fe766d031176ffc497ccb028b3c5a81 | Python | donmajkelo/kurs_Python | /31_2.py | UTF-8 | 500 | 3.734375 | 4 | [] | no_license |
lista = []
x = input (f" podaj liczbe nr 1: ")
lista.append(x)
x = input (f" podaj liczbe nr 2: ")
lista.append(x)
x = input (f" podaj liczbe nr 3: ")
lista.append(x)
x = input (f" podaj liczbe nr 4: ")
lista.append(x)
x = input (f" podaj liczbe nr 5: ")
lista.append(x)
print(f" LISTA TWOICH LICZB: {lista}")
suma = int(lista[0])+int(lista[1])+int(lista[2])+int(lista[3])+int(lista[4])
srednia= int(suma)/len(lista)
print(f" SUMA: {suma}")
print(f" srednia: {srednia}")
| true |
49d9ba3d6bd6d794ca46b84e16ebeb9bdc9039dc | Python | aobo-y/leetcode | /282.expression-add-operators.py | UTF-8 | 1,017 | 2.9375 | 3 | [] | no_license | #
# @lc app=leetcode id=282 lang=python3
#
# [282] Expression Add Operators
#
# @lc code=start
class Solution:
def addOperators(self, num: str, target: int) -> List[str]:
def dfs(i, t, accum=1):
res = []
if i >= len(num):
return res
for j in range(i + 1, len(num) + 1 if num[i] != '0' else i + 2):
token = num[i:j]
v = accum * int(token)
if j == len(num):
if v == t:
res.append(token)
continue
add_res = dfs(j, t - v)
for r in add_res:
res.append(f'{token}+{r}')
min_res = dfs(j, t - v, -1)
for r in min_res:
res.append(f'{token}-' + r)
mul_res = dfs(j, t, v)
for r in mul_res:
res.append(f'{token}*{r}')
return res
return dfs(0, target)
# @lc code=end
| true |
d40586a55e93c0d0c488a14853cd6db547e659d6 | Python | oeg-upm/GEnI | /core/influence_detection.py | UTF-8 | 3,253 | 2.65625 | 3 | [
"MIT"
] | permissive | import numpy as np
import operator
def sig(x, y, type):
if type == 'semantic':
result = -np.dot(x, np.transpose(y))
elif type == 'translation':
result = -(x + y)
return 1 / (1 + np.exp(result))
def point_hess(e_o, nei, embd_e, embd_rel, type):
dim = np.shape(e_o)[0]
H = np.zeros((dim, dim))
for i in nei:
if type == 'semantic':
X = np.multiply(np.reshape(embd_e[i[0]], (1, -1)), embd_rel[i[1]])
elif type == 'translation':
X = np.reshape(embd_e[i[0]] + embd_rel[i[1]], (-1, 1))
sig_tri = sig(e_o, X, type)
Sig = (sig_tri) * (1 - sig_tri)
if type == 'semantic':
H += Sig * np.dot(np.transpose(X), X)
elif type == 'translation':
H += Sig * (X + X)
return H
def point_score(Y, X, e_o, H, type):
sig_tri = sig(e_o, X, type)
try:
M = np.linalg.inv(H + (sig_tri) * (1 - sig_tri) * np.dot(np.transpose(X), X))
except:
return np.inf, []
if type == 'semantic':
Score = - np.dot(Y, np.transpose((1 - sig_tri) * np.dot(X, M)))
elif type == 'translation':
Score = - np.linalg.norm(Y + (np.transpose((1 - sig_tri) * np.dot(np.reshape(X, (-1, 1)).T, M))))
return Score, M
def find_best_attack(h, t, cur_rel, ent_dict, rel_dict, facts, type):
dict_s = {}
triples = []
nei1 = [(i[0], k, i[1]) for k, v in facts.items() for i in v if i[1] == h]
nei2 = [(i[0], k, i[1]) for k, v in facts.items() for i in v if i[1] == t]
e_o = ent_dict[t]
e_s = ent_dict[h]
if type == 'semantic':
Y1 = np.dot(rel_dict[cur_rel], e_o)
Y2 = np.dot(rel_dict[cur_rel], e_s)
elif type == 'translation':
Y1 = rel_dict[cur_rel] + e_o
Y2 = rel_dict[cur_rel] + e_s
if len(nei1) > 0:
H1 = point_hess(e_o, nei1, ent_dict, rel_dict, type)
if len(nei1) > 50:
nei1 = nei1[:50]
for i in nei1:
e1 = i[0]
rel = i[1]
if type == 'semantic':
pred = np.matmul(rel_dict[rel], ent_dict[e1])
elif type == 'translation':
pred = rel_dict[rel] + ent_dict[e1]
score_t, M = point_score(Y1, pred, e_o, H1, type)
dict_s[i] = score_t
if len(nei2) > 0:
H2 = point_hess(e_s, nei2, ent_dict, rel_dict, type)
if len(nei2) > 50:
nei2 = nei2[:50]
for i in nei2:
e1 = i[0]
rel = i[1]
if type == 'semantic':
pred = np.matmul(rel_dict[rel], ent_dict[e1])
elif type == 'translation':
pred = rel_dict[rel] + ent_dict[e1]
score_t, M = point_score(Y2, pred, e_s, H2, type)
dict_s[i] = score_t
if nei1 and nei2:
sorted_score = sorted(dict_s.items(), key=operator.itemgetter(1))
if sorted_score and sorted_score[0][1] < 0:
triples = []
i = 0
while (i <= len(sorted_score) - 2) and len(triples) < 3:
if abs(sorted_score[i][1] - sorted_score[i + 1][1]) >= 100:
triples.append(sorted_score[i][0])
i += 1
else:
break
return triples
| true |
961eae463911aa8a31c79afe209af53958fa67dc | Python | pmoracho/openerm | /tests/test_Config.py | UTF-8 | 2,162 | 2.828125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
# Copyright (c) 2014 Patricio Moracho <pmoracho@gmail.com>
#
# test of Config class
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 3 of the GNU General Public License
# as published by the Free Software Foundation. A copy of this license should
# be included in the file GPL-3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
Software# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
"""
import unittest
import yaml
from openerm.Config import Config, ConfigLoadingException
class ConfigTest(unittest.TestCase):
data = { "A": 'a',
"D": {
"C": 'c',
"D": 'd',
"E": 'e'
},
"L": [1,2,3,4,5]
}
schema = """
A:
type: string
D:
type: dict
allow_unknown: true
schema:
C:
type: string
required: true
allowed:
- x
- z
D:
type: string
E:
type: integer
required: true
L:
type: list
"""
def test_generate_yaml_and_load(self):
"""Genera un archivo yaml y realiza la importación en un diccionario
"""
cfg = Config(self._filename)
self.assertEqual(cfg.dictionary, self.data)
errores_esperados = ["D: schema({'C': {'type': 'string', 'required': True, 'allowed': ['x', 'z']}, 'D': {'type': 'string'}, 'E': {'type': 'integer', 'required': True}}) Valor: {'C': 'c', 'D': 'd', 'E': 'e'}"]
try:
cfg = Config(self._filename,self.schema)
except ConfigLoadingException as ex:
lista = [e for e in ex.args[1]]
self.assertEqual(lista, errores_esperados)
@classmethod
def setUpClass(cls):
cls._filename = "./out/test.yaml"
cls._generate_yaml()
@classmethod
def tearDownClass(cls):
pass
@classmethod
def _generate_yaml(cls):
with open(cls._filename, 'w') as outfile:
yaml.dump(cls.data, outfile, default_flow_style=True)
| true |
7093ddcafc485c29373db7964fc97d3c6e0a7c62 | Python | 2099454967/python_wang | /09day/4.乘法口诀.py | UTF-8 | 116 | 3.171875 | 3 | [] | no_license | a = 1
while a <= 9:
b = 1
while b <= a:
#1*1=1
print("%d*%d=%d"%(a,b,a*b),end='\t')
b+=1
print('')
a+=1
| true |
fb014f34723807d72539311721545dd0022d7d5c | Python | sjdeak/interview-practice | /cp3/ch3/greedy/(caseNum)uva11369/main.py | UTF-8 | 750 | 2.71875 | 3 | [] | no_license | """
AD exchange arguments 例题变体 (轻微变化)
所有任务只要没有开始做,每天都要付罚款
"""
import os, sys
from functools import cmp_to_key
from itertools import count, combinations
from collections import namedtuple, Counter
from operator import itemgetter
from math import sqrt
class CustomException(Exception): pass
if os.getenv('SJDEAK'):
sys.stdin = open(os.path.expanduser('./in.txt'))
# sys.stdout = open(os.path.expanduser('./out.txt'), 'w')
if __name__ == '__main__':
T = int(input())
for caseIndex in range(1, T + 1):
[N] = list(map(int, input().split()))
prices = sorted(list(map(int, input().split())), reverse=True)
ans = sum(prices[i] for i in range(2, len(prices), 3))
print(ans)
| true |
b10420fdef7bc8e8cde6e9aecb84a0cf48dd3069 | Python | karlosos/reinforcement_learning_fundamentals | /lab3/grid_qlearn.py | UTF-8 | 4,996 | 3.359375 | 3 | [] | no_license | import random
import numpy as np
class Grid:
def __init__(self):
self.height = 10
self.width = 10
self.actions = [0, 1, 2, 3]
self.state_count = self.height * self.width
self.action_count = len(self.actions)
self.policy_print_characters = {0: "<", 1: ">", 2: "^", 3: "v"}
self.grid = np.zeros((self.height, self.width))
# end points
self.grid[0, 0] = 10
self.grid[-1, 0] = 50
# obstacles
self.grid[3, 2:8] = -1
self.grid[2:8, 6] = -1
self.grid[2:8, 5] = -1
self.grid[2:8, 4] = -1
self.grid[2:8, 3] = -1
def random_position(self):
"""Find random starting position"""
while True:
h = random.randrange(0, self.height)
w = random.randrange(0, self.width)
if self.grid[h, w] == 0:
return (h, w)
def is_terminal(self, state):
"""Terminal states are those with reward greater than 0"""
if self.grid[state[0], state[1]] > 0:
return True
else:
return False
def to_string(self, state=None, policy=None):
res = "┌" + "─" * self.width + "┐" + "\n"
for i in range(self.height):
res += "│"
for j in range(self.width):
if self.grid[i, j] == -1:
res += "#"
elif self.grid[i, j] > 0:
res += "X"
elif state is not None and state[0] == i and state[1] == j:
res += "¤"
elif policy is not None:
res += self.policy_print_characters[policy[i, j]]
else:
res += " "
res += "│"
res += "\n"
res += "└" + "─" * self.width + "┘"
return res
def __str__(self):
return self.to_string()
def available_actions(self, state):
actions = []
if self.is_terminal(state):
return actions
h, w = state
if h > 0:
if self.grid[h-1, w] >= 0:
actions.append(2) # up
if w > 0:
if self.grid[h, w-1] >= 0:
actions.append(0) # left
if h < self.height-1:
if self.grid[h+1, w] >= 0:
actions.append(3) # down
if w < self.width-1:
if self.grid[h, w+1] >= 0:
actions.append(1) # right
return actions
def take_action(self, state, action):
h, w = state
state_next = [h, w]
if action == 0: # left
state_next[1] = w-1
if action == 1: # right
state_next[1] = w+1
if action == 2: # up
state_next[0] = h-1
if action == 3: # down
state_next[0] = h+1
done = self.is_terminal(state_next) or self.available_actions(state_next) == []
reward = self.grid[state_next[0], state_next[1]]
return state_next, reward, done
def main():
import numpy as np
import time
import os
env = Grid()
# Initialize qtable
qtable = np.random.rand(env.height, env.width, env.action_count)
for i in range(env.height):
for j in range(env.width):
for action in range(4):
# reset unabailable actions
if action not in env.available_actions((i, j)):
qtable[i, j, action] = 0
epochs = 5000
gamma = 0.9
epsilon = 0.2
for i in range(epochs):
state = env.random_position()
reward = 0
done = False
steps = 0
while not done:
h, w = state
# count steps to finish game
steps += 1
# exploration
if np.random.random() < epsilon:
action = np.random.choice(env.available_actions(state))
# best action
else:
action = qtable[h, w].argmax()
available_actions = env.available_actions(state)
if action not in available_actions:
action = np.random.choice(env.available_actions(state))
# take action
state_next, reward, done = env.take_action(state, action)
# update qtable value with Bellman equation
qtable[h, w, action] = reward + gamma * np.max(qtable[state_next])
# update state
# print("Action", action)
# print("Step", steps)
state = state_next
#print(env.to_string(state=state))
print("Epoka: ", i + 1, "kroki:", steps)
if i % 100 == 0:
print("Wyznaczona strategia")
policy = np.argmax(qtable, axis=2)
print(env.to_string(policy=policy))
print("Wyznaczona strategia")
policy = np.argmax(qtable, axis=2)
print(policy)
print(env.to_string(policy=policy))
if __name__ == "__main__":
main()
| true |
40e8310b522da5a56d95ca2acb230604fcaf2cad | Python | bluerwf/bear | /src/queue.py | UTF-8 | 1,460 | 3.703125 | 4 | [] | no_license | #! /usr/bin/env python
# coding=utf-8
class Queue:
def __init__(self, size):
self._lst = []
self.size = size
def enqueue(self, i):
if len(self._lst) < self.size:
self._lst.append(i)
else:
print'full'
def dequeue(self):
try:
self._lst.pop(0)
except IndexError:
print "dequeue from empty queue!"
def __len__(self):
return len(self._lst)
def __str__(self):
return str(self._lst)
@property
def length(self):
return len(self)
class AbsStack:
def push(self, i):
raise NotImplemented
def pop(self):
raise NotImplemented
class Stack(AbsStack):
def __init__(self, size):
self._lst = []
self.size = size
def push(self, i):
if len(self._lst) < self.size:
self._lst.append(i)
else:
print'full'
def pop(self):
try:
v = self._lst.pop()
return v
except IndexError:
print 'this stack is empty'
@property
def top(self):
try:
return self._lst[-1]
except IndexError:
return None
@property
def base(self):
try:
return self._lst[0]
except IndexError:
return None
def __str__(self):
return str(self._lst)
sstack = Stack(10)
sstack.push(1)
sstack.push(2)
| true |
4e9de4299f66dce51b67e28e8fdff69cb144d2cc | Python | ziqingW/python-exercise-flex-Mar06 | /turtle_graphics/exercise3/new.py | UTF-8 | 345 | 2.890625 | 3 | [] | no_license | import shapes
if __name__ == "__main__":
shapes.polygon(3, 80, True, "red", "green")
shapes.polygon(4, 100, False, "black")
shapes.polygon(5, 80, False, "blue")
shapes.polygon(6, 60, True, "yellow", "purple")
shapes.polygon(8, 50, False, "black")
shapes.star(100, False, "red")
shapes.cir(80, True, "black", "white") | true |
6a83efef9e8c9f3ee22302b23904a0dfa751f6eb | Python | limiao06/DSTC4 | /scripts/dstc_thu/preprocessor.py | UTF-8 | 7,017 | 2.734375 | 3 | [] | no_license | #! /usr/bin/python
# -*- coding: utf-8 -*-
'''
preprocessor
'''
import sys
sys.path.append('../')
import nltk
import re
from GlobalConfig import GetConfig
class stemmer(object):
MY_ID = 'STEMMER'
def __init__(self, flag=True):
#self.config = GetConfig()
#from nltk.stem.lancaster import LancasterStemmer as Stemmer
self.flag = flag
if self.flag:
from nltk.stem.porter import PorterStemmer as Stemmer
self.st = Stemmer()
def stem(self, string):
if self.flag and string and string[0] != '$':
return self.st.stem(string)
else:
return string
class tokenizer(object):
MY_ID = 'TOKENIZER'
def __init__(self,mode=None):
self.config = GetConfig()
if mode:
self.mode = mode
else:
if self.config.has_option(self.MY_ID,'mode'):
self.mode = self.config.get(self.MY_ID,'mode')
else:
self.mode = 'NLTK'
if self.mode == 'STANFORD':
from nltk.tokenize.stanford import StanfordTokenizer as Tokenizer
self.tokenizer = Tokenizer()
elif self.mode == 'NLTK':
pass
elif self.mode == 'MINE':
self.spacePunct = re.compile(ur'[`~!@#\$%\^&\*\(\)\[\]{}_\+\-=\|\\:;\"\'<>,\?/]')
self.removePunct = re.compile(ur'\.')
else:
raise Exception('Error: tokenizer, Unknown mode %s!' %(self.mode))
def tokenize(self, sent):
if sent.endswith('-') or sent.endswith('~'):
sent += ' '
sent = sent.replace('~ ', ' ~ ')
sent = sent.replace('- ', ' - ')
if self.mode == 'STANFORD':
tokens = self.tokenizer.tokenize(sent.strip())
elif self.mode == 'NLTK':
tokens = nltk.word_tokenize(sent.strip())
elif self.mode == 'MINE':
new_sent = sent.strip()
new_sent = self.spacePunct.sub(' ', new_sent)
new_sent = self.removePunct.sub('', new_sent)
tokens = new_sent.split()
p_sent = ' '.join(tokens)
p_sent = p_sent.replace('% ', '%')
p_sent = p_sent.replace('``', '\"')
p_sent = p_sent.replace('\'\'', '\"')
p_tokens = p_sent.split(' ')
return p_tokens
class NGRAM_builder(object):
MY_ID='ngram_builder'
def __init__(self, remove_stopwords=True, remove_punctuation=False, replace_num=True):
self.remove_stopwords = remove_stopwords
self.remove_punctuation = remove_punctuation
self.replace_num = replace_num
self.stopwords = set(['okay','yah','yes','alright','oh','uh','i','s','right','see','that','so','it','huh','hm','the','you',
'ah','um','a','to','and','in','sure','of','can','is','but','great','this','correct','have','think','also',
'me','m','be','very','for','ll','now','do','good','let','then','get','no','just','know','sorry','what',
'my','would','two','really','well','welcome','one','are','we','will','on','because','with','not','wow',
'please','understand','if','or','your','ooh','cool','here','want','yeah','re','quay','take','about','o',
'up','nice','all','how','actually','yup','part','need','eight','fine','ve','day','they','t','guess','lot',
'again','kinda','ten','from','give','may','course','bye','mean','eh','got','anyway','going','at','five',
'by','ok','problem','other','exactly','v','along','still','too','r','were','say','any','don','definitely',
'only','him','she','hmm','while','them','bit','d','was','an','as','hello','particular','did','p','k','a',
'about','above','after','again','against','all','an','and','any','are','as','at','be','been','before','being',
'below','between','both','but','by','cannot','could','did','do','does','doing','down','during','each','few',
'for','from','had','has','have','having','he','her','hers','herself','him','himself','his','how','i','if',
'in','into','is','it','its','itself','me','more','most','my','myself','no','nor','not','of','off','on','once',
'only','or','other','ought','our','ours','ourselves','out','over','own','same','she','should','so','some',
'such','than','that','the','their','theirs','them','themselves','then','these','they','this','those','through',
'to','too','under','until','up','very','was','we','were','what','when','where','which','while','who','whom',
'with','would','you','your','yours','yourself','yourselves'])
#self.stopwords = set([])
self.re_puntuation = re.compile("^\W+$")
self.card_numbers = set(['thousand','thousands','hundred','hundreds','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety',
'ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen',
'zero','one','two','three','four','five','six','seven','eight','nine'])
self.ordi_numbers = set(['first','second','third','fourth','fifth','sixth','seventh','eighth','ninth',
'tenth','eleventh','twelfth','thirteenth','fourteenth','fifteenth','sixteenth','seventeenth','eighteenth','nineteenth',
'twentieth','thirtieth','fortieth','fiftieth','sixtieth','seventieth','eightieth','ninetieth'])
self.day_name = set(['monday','tuesday','wednesday','thursday','friday','saturday','sunday'])
self.month_name = set(['january','february','march','april','may','june','july','august','september','october','november','december'])
def RemoveStopWords(self, tokens):
new_tokens = []
for t in tokens:
if t.lower() in self.stopwords:
new_tokens.append('$ST')
else:
new_tokens.append(t)
return new_tokens
def RemovePunct(self, tokens):
new_tokens = []
for t in tokens:
if self.re_puntuation.match(t):
new_tokens.append('$PT')
else:
new_tokens.append(t)
return new_tokens
def ReplaceNum(self, tokens):
new_tokens = []
for t in tokens:
tl = t.lower()
if tl in self.card_numbers:
new_tokens.append('$CNUM')
elif tl in self.ordi_numbers:
new_tokens.append('$ONUM')
elif tl in self.day_name:
new_tokens.append('$DAY')
elif tl in self.month_name:
new_tokens.append('$MONTH')
else:
new_tokens.append(t)
return new_tokens
def PreReplace(self, tokens):
new_tokens = tokens
if self.remove_stopwords:
new_tokens = self.RemoveStopWords(new_tokens)
if self.remove_punctuation:
new_tokens = self.RemovePunct(new_tokens)
if self.replace_num:
new_tokens = self.ReplaceNum(new_tokens)
return new_tokens
def GenerateNGRAM(self, tokens, n):
ngram_list = []
new_tokens = tuple(tokens)
for i in range(len(new_tokens) - (n - 1)):
ngram = new_tokens[i:i+n]
str_ngram = str(ngram)
if self.remove_stopwords and str(ngram).find('$ST') != -1:
continue
if self.remove_punctuation and str(ngram).find('$PT') != -1:
continue
ngram_list.append(ngram)
return ngram_list
if __name__ =="__main__":
preproc = tokenizer('MINE')
sents = ["%uh because this is a East-West Line %um you will have to change %uh the line in City Hall.",
"So you actually get to view %uh you know the- some parts %uh of the island %uh and you know if you feel like stopping you can always stop-",
"You are quite %uh you know what's going on from your airport, you take the subway-"
]
for sent in sents:
tokens = preproc.tokenize(sent)
print ' '.join(tokens)
| true |
1a8457e416d3ffc8b314fd48b5e650420228dc77 | Python | ochaplashkin/cybertonica-client | /CybertonicaAPI/auth.py | UTF-8 | 3,492 | 2.703125 | 3 | [] | no_license | import json
from types import FunctionType, LambdaType
from email.utils import parseaddr
import time
class Auth:
"""Auth class.
Attributes:
root: Object of `CybertonicaAPI.Client`
"""
def __init__(self, root):
self.root = root
def login(self, api_user, api_user_key_hash):
"""Create web session.
Args:
api_user: User login.
api_user_key_hash: User password.
Method:
`POST`
Endpoint:
`/api/v1/login`
Returns:
See CybertonicaAPI.Client.r
"""
assert isinstance(api_user, str), 'The api user must be a string'
assert api_user, 'The api user must not be an empty string'
assert isinstance(api_user_key_hash,
str), 'The api user key hash must be a string'
assert api_user_key_hash, 'The api user key hash must not be an empty string'
url = f'{self.root.url}/api/v1/login'
data = json.dumps({
"apiUser": api_user,
"team": self.root.team,
"apiUserKeyHash": api_user_key_hash
})
headers = {"content-type": "application/json"}
status_code, data = self.root.r(
'POST', url, data, headers, verify=self.root.verify)
if status_code == 200 or status_code == 201:
self.root.token = data['token']
self.root.login_time = time.monotonic()
return (status_code, data)
def logout(self):
"""Drop web session.
Method:
`POST`
Endpoint:
`/api/v1/logout`
Returns:
See CybertonicaAPI.Client.r
"""
url = f'{self.root.url}/api/v1/logout'
headers = {
"content-type": "application/json",
"Authorization": f"Bearer {self.root.token}"}
status_code, data = self.root.r(
'POST', url, None, headers, None, verify=self.root.verify)
if status_code < 400:
self.root.token = ''
self.root.login_time = 0
return (status_code, data)
def recovery_password(self, team, email):
"""Recovery password.
Args:
team: user team.
email: user email.
Method:
`GET`
Endpoint:
`/api/v1/recovery/request?team={team}&email={email}`
Returns:
See CybertonicaAPI.Client.r
"""
assert isinstance(team, str), 'Team must be a string'
assert team, 'Team must not be an empty string'
assert isinstance(email, str), 'Email must be a string'
assert email, 'Email must not be an empty string'
assert '@' in parseaddr(email)[1], 'Email must be valid'
url = f'{self.root.url}/api/v1/recovery/request?team={team}&email={email}'
headers = {"content-type": "application/json"}
return self.root.r('GET', url, None, headers,None, verify=self.root.verify)
def register(self, data):
"""Create a new user in the system.
Args:
data: Dictionary of user data. If the dictionary
does not contain fields `invitedAt` or `updatedAt`,
then they are automatically added with the values `0`.
{
"email":"example@test.com",
"password":"Password12345",
"team":"test",
"firstName":"Test",
"lastName":"Test",
"login":"test",
"invitedAt":0,
"updatedAt":0
}
Method:
`POST`
Endpoint:
`/api/v1/registration`
Returns:
See CybertonicaAPI.Client.r
"""
assert isinstance(data, dict), 'The data type must be a dictionary'
assert data, 'User data must not be an empty dictionary'
url = f'{self.root.url}/api/v1/registration'
headers = {"content-type": "application/json"}
if "invitedAt" not in data:
data["invitedAt"] = 0
if "updatedAt" not in data:
data["updatedAt"] = 0
data = json.dumps(data)
return self.root.r('POST', url, data, headers, verify=self.root.verify)
| true |
b07e4de7fc5fec4b2e14b341740a6fdf7d9a1cf3 | Python | davestroud/Algorithm_Fundamentals | /educative/Lists/List_Of_Products.py | UTF-8 | 406 | 3.890625 | 4 | [] | no_license | def find_product(lst):
# get product to start from left
left = 1
product = []
for ele in lst:
product.append(left)
left = left * ele
# get product starting from right
right = 1
for i in range(len(lst)-1, -1, -1):
product[i] = product[i] * right
right = right * lst[i]
return product
arr = [1,2,3,4]
print(find_product(arr))
| true |
e4d268bd17d495cc4b67f67ddeadecd1dd16112e | Python | slash-segmentation/DP2 | /test_files/test_xml.py | UTF-8 | 684 | 2.9375 | 3 | [] | no_license | # http://www.postneo.com/projects/pyxml/
from xml.dom.minidom import Document
# Create the minidom document
doc = Document()
# Create the <wml> base element
object = doc.createElement("object")
object.setAttribute("identifier", "object1")
object.setAttribute("class", "Vesicle")
doc.appendChild(object)
# Create the main <card> element
maincard = doc.createElement("card")
maincard.setAttribute("id", "main")
# Create a <p> element
paragraph1 = doc.createElement("voxels")
object.appendChild(paragraph1)
# Give the <p> elemenet some text
ptext = doc.createTextNode("0,0,0 0,0,0")
paragraph1.appendChild(ptext)
# Print our newly created XML
print doc.toprettyxml(indent=" ")
| true |
bf71df9e044b4ac5cd32e7e9029230c2f474d6cb | Python | jf115/python-lesson | /Clase 5/listas.py | UTF-8 | 903 | 3.859375 | 4 | [] | no_license | # numeros = [8, 5, 6]
# print(len(numeros))
# print(numeros[2])
# numeros[2]=3 #Así cambio el valor de algo sin tener que tocar toda la lista
# print(numeros)
# numeros.append(25) #Agrego mas elementos
# print(numeros)
# print(sum(numeros)) #Suma toda la cantidad de resultados de numero que se han generado
#Cuál es el promedio mas alto
numeros1 = [59, 58+5, 45-5, 12*2]
numeros2 = [54, 58+5, 45, 12+24]
numeros3 = [54+2, 58+5, 45, 12]
numeros4 = [4, 58+5, 45*2, 12]
n1=((sum(numeros1))/len(numeros1))
n2=((sum(numeros2))/len(numeros2))
n3=((sum(numeros3))/len(numeros3))
n4=((sum(numeros4))/len(numeros4))
#print(max(n1,n2,n3,n4)) #forma corta
#Forma larga
if n1 >= n2 and n1 >= n3 and n1 >= n4:
print('El promedio es ', n1)
elif n2 >= n3 and n2 >= n4:
print('El promedio es ', n2)
elif n3 >= n4:
print('El promedio es ', n3)
else:
print('El promedio es ', n4) | true |
fa1ec0affdf83c64e5cbbfa9bcc36954f5768487 | Python | takedah/hinanbasho | /tests/test_scraper.py | UTF-8 | 3,332 | 2.859375 | 3 | [
"MIT"
] | permissive | import unittest
from unittest.mock import Mock, patch
from requests import ConnectionError, HTTPError, RequestException, Timeout
from hinanbasho.scraper import OpenData, PostOfficeCSV
class TestOpenData(unittest.TestCase):
@patch("hinanbasho.scraper.requests")
def test_lists(self, mock_requests):
csv_content = (
"施設名,郵便番号,住所,電話番号,ファクス番号,地図の緯度,地図の経度"
+ "\r\n"
+ "常磐公園,070-0044,北海道旭川市常磐公園,0166-23-8961,なし,43.7748548,"
+ "142.3578223"
+ "\r\n"
+ "豊西会館,074-1182,北海道旭川市神居町豊里,なし,なし,,"
+ "\r\n"
+ "花咲スポーツ公園,071-0901,北海道旭川市花咲町1~5丁目,0166-52-1934,なし,"
+ "43.78850998,142.3681739"
+ "\r\n"
)
mock_requests.get.return_value = Mock(
status_code=200, content=csv_content.encode("cp932")
)
expect = [
{
"site_id": 1,
"site_name": "常磐公園",
"postal_code": "070-0044",
"address": "北海道旭川市常磐公園",
"phone_number": "0166-23-8961",
"latitude": 43.7748548,
"longitude": 142.3578223,
},
{
"site_id": 2,
"site_name": "豊西会館",
"postal_code": "074-1182",
"address": "北海道旭川市神居町豊里",
"phone_number": "なし",
"latitude": 43.6832208,
"longitude": 142.1762534,
},
{
"site_id": 3,
"site_name": "花咲スポーツ公園",
"postal_code": "070-0901",
"address": "北海道旭川市花咲町1~5丁目",
"phone_number": "0166-52-1934",
"latitude": 43.78850998,
"longitude": 142.3681739,
},
]
open_data = OpenData()
self.assertEqual(open_data.lists, expect)
mock_requests.get.side_effect = Timeout("Dummy Error.")
with self.assertRaises(RequestException):
OpenData()
mock_requests.get.side_effect = HTTPError("Dummy Error.")
with self.assertRaises(RequestException):
OpenData()
mock_requests.get.side_effect = ConnectionError("Dummy Error.")
with self.assertRaises(RequestException):
OpenData()
class TestPostOfficeCSV(unittest.TestCase):
def test_lists(self):
post_office_csv = PostOfficeCSV()
# 先頭行
expect = {
"postal_code": "0600000",
"area_name": "以下に掲載がない場合",
}
self.assertEqual(post_office_csv.lists[0], expect)
# 1382行目
expect = {
"postal_code": "0700055",
"area_name": "5条西",
}
self.assertEqual(post_office_csv.lists[1382], expect)
# 最終行
expect = {
"postal_code": "0861834",
"area_name": "礼文町",
}
self.assertEqual(post_office_csv.lists[-1], expect)
if __name__ == "__main__":
unittest.main()
| true |
c7eae74be8bdd5741cba1bb6e1e570d47fef0671 | Python | guoyc21/finance-cheatsheets | /Variance reduction/antithetic_variates_method.py | UTF-8 | 3,520 | 3.140625 | 3 | [
"MIT"
] | permissive | import matplotlib.pyplot as plt
import numpy as np
from time import time
import pandas as pd
# Underlying informations
S0 = 100
mu = 0.1
sigma = 0.1
# European option informations
T = 1.0
K = 100.0
r = 0.05
# Simulation parameters
nbr_steps = 100
dt = T/nbr_steps
t = np.linspace(0, T, nbr_steps)
min_nbr_sim, max_nbr_sim = 100, 100000
nbr_steps_sims = 100
nbr_sims = np.linspace(min_nbr_sim, max_nbr_sim, nbr_steps_sims)
# Global variables for results storage
prices_standard = []
prices_antithetic = []
# Classic Monte-Carlo simulation
time_begin_classic = time()
for i,nbr_sim in enumerate(nbr_sims):
print(i)
nbr_sim = int(nbr_sim)
price = 0.0
for _ in range(nbr_sim):
W = np.random.standard_normal(size = nbr_steps)
W = np.cumsum(W)*np.sqrt(dt)
X = (mu-0.5*sigma**2)*t + sigma*W
S = S0*np.exp(X)
# Payoff computation of a european call
if(S[-1]>K):
price += S[-1]-K
prices_standard.append((price/nbr_sim)*np.exp(-r*T))
calculation_time_classic = round(time()-time_begin_classic, 1)
# Antithetic variates method
time_begin_antithetic = time()
half_len = int(len(nbr_sims)/2)
for i,nbr_sim in enumerate(nbr_sims[0:half_len]):
print(i)
price = 0.0
nbr_sim = int(nbr_sim)
for _ in range(nbr_sim):
W = np.random.standard_normal(size = nbr_steps)
W_2 = -W
W = np.cumsum(W)*np.sqrt(dt)
W_2 = np.cumsum(W_2)*np.sqrt(dt)
X = (mu-0.5*sigma**2)*t + sigma*W
X_2 = (mu-0.5*sigma**2)*t + sigma*W_2
S = S0*np.exp(X)
S_2 = S0*np.exp(X_2)
# Computation of both payoffs and then the mean
if(S[-1]>K):
price += S[-1]-K
if(S_2[-1]>K):
price += S_2[-1]-K
prices_antithetic.append((price/(2*nbr_sim))*np.exp(-r*T))
calculation_time_antithetic = round(time()-time_begin_antithetic, 1)
# Computing mean and standard deviation
prices = np.array(prices_standard)
mean_val = np.mean(prices)
std_val = round(np.std(prices),4)
# Plotting classical Monte-Carlo simulation
plt.figure(1)
ax1 = plt.subplot(211)
ax1.set_title("Classic method (time of execution : {}s)".format(calculation_time_classic))
ax1.plot(nbr_sims, prices, label='Price')
ax1.plot(nbr_sims, np.linspace(mean_val, mean_val,100), label='Mean')
ax1.plot(nbr_sims, np.linspace(mean_val-std_val, mean_val-std_val,100),'g', label='Mean-std')
ax1.plot(nbr_sims, np.linspace(mean_val+std_val, mean_val+std_val,100),'g', label='Mean+std')
ax1.legend(loc="upper right")
ax1.set_xlabel('number of simulations')
ax1.set_ylabel('price ($)')
# Computing mean and standard deviation
prices = np.array(prices_antithetic)
mean_val = np.mean(prices)
std_val = round(np.std(prices),3)
# Plotting with the antithetic variates method
ax2 = plt.subplot(212, sharex=ax1, sharey=ax1)
ax2.set_title("Antithetic varaites method (time of execution : {}s)".format(calculation_time_antithetic))
ax2.plot(nbr_sims[0:half_len], prices, label='Price')
ax2.plot(nbr_sims[0:half_len], np.linspace(mean_val, mean_val,50), label='Mean')
ax2.plot(nbr_sims[0:half_len], np.linspace(mean_val-std_val, mean_val-std_val,50),'g', label='Mean-std')
ax2.plot(nbr_sims[0:half_len], np.linspace(mean_val+std_val, mean_val+std_val,50),'g', label='Mean+std')
ax2.legend(loc="upper right")
ax2.set_xlabel('number of simulations')
ax2.set_ylabel('price ($)')
plt.tight_layout()
plt.show()
| true |
5b7ed03fdf9f6d0aa4d32fbfaeb5230fec2df0ed | Python | sauravbasak/Codehall-Python | /S1_ Easy.py | UTF-8 | 316 | 3.828125 | 4 | [] | no_license | name = input('input your name name')
age = input('input your age')
height = input('input your heigh in cm')
#because python takes any input as a string. don't need to cast age and height here to concatinate it with the string
print('your name is ' + name + ' you\'r age is ' + age + ' you\'re height is ' + height)
| true |
7a32345d7004d1576e0ee94f21e6c97be6aa733b | Python | uranusjr/packaging-repositories | /src/packaging_repositories/repositories.py | UTF-8 | 2,627 | 2.640625 | 3 | [
"ISC"
] | permissive | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import posixpath
from packaging.utils import canonicalize_name
from six.moves import urllib_parse
from .endpoints import Endpoint
from .entries import list_from_paths, parse_from_html
def _is_filesystem_path(split_result):
if not split_result.scheme:
return True
if len(split_result.scheme) > 1:
return False
# urlparse misidentifies Windows absolute paths. In this situation, the
# scheme would be a single letter (drive name), and netloc would be empty.
if not split_result.netloc:
return True
return False
class _Repository(object):
def __init__(self, endpoint):
self._base_endpoint = endpoint
def __repr__(self):
return "{name}({endpoint!r})".format(
name=type(self).__name__, endpoint=self.base_endpoint.value,
)
@property
def base_endpoint(self):
endpoint = self._base_endpoint
split_result = urllib_parse.urlsplit(endpoint)
if _is_filesystem_path(split_result):
return Endpoint(True, os.path.normpath(os.path.abspath(endpoint)))
return Endpoint.from_url(split_result)
class SimpleRepository(_Repository):
"""A repository compliant to PEP 503 "Simple Repository API".
"""
def iter_endpoints(self, package_name):
name = canonicalize_name(package_name)
base_endpoint = self.base_endpoint
value = posixpath.join(base_endpoint.value, name, "")
yield base_endpoint._replace(value=value)
def get_entries(self, package_name, endpoint, html):
return parse_from_html(html, endpoint.as_url(), package_name)
class FlatHTMLRepository(_Repository):
"""A repository represented by a single HTML file.
This is the non-directory variant of pip's --find-links.
"""
def iter_endpoints(self, package_name):
yield self.base_endpoint
def get_entries(self, package_name, endpoint, html):
return parse_from_html(html, endpoint.as_url(), package_name)
class LocalDirectoryRepository(_Repository):
"""A repository represented by a directory on the local filesystem.
This is the directory variant of pip's --find-links.
"""
def __init__(self, endpoint):
super(LocalDirectoryRepository, self).__init__(endpoint)
if not self.base_endpoint.local:
raise ValueError("endpoint is not local")
def iter_endpoints(self, package_name):
yield self.base_endpoint
def get_entries(self, package_name, endpoint, paths):
return list_from_paths(paths, endpoint.value, package_name)
| true |
c943e9e13526a9cc3986050eeff7d1f4ae3b12b0 | Python | AnnaWillis/MultiplyQuiz1-12 | /1-12multiply.py | UTF-8 | 852 | 4.125 | 4 | [] | no_license | __author__ = 'Anna'
import random
print("Hello, operators!")
print("I will ask you a 1-12 multiplication problem. If you get it right, I will say, 'Correct!'")
while True:
factor1 = random.randint(1, 12)
factor2 = random.randint(1, 12)
guess = ""
while guess=="":
guess = input("What is %d times %d?" % (factor1 , factor2))
if guess=="":
print("That is not a number, silly! Try again and do your best!")
try:
guess = int(guess)
except ValueError:
print("Please enter a number. Otherwise, the Ghost of Unanswered Multiplication Problems will haunt you.")
guess = ""
#print(guess)
product = factor1 * factor2
if guess == product:
print("Correct!")
else:
print("Sorry, the correct answer is %d" % (product))
| true |
493ee6d93d5990e07ff427a9f93a03449c06ee01 | Python | skojaku/hokusai-plot | /scripts/point2net.py | UTF-8 | 1,422 | 2.515625 | 3 | [
"CC0-1.0"
] | permissive | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy import spatial
import networkx as nx
import sys
if __name__ == "__main__":
POINTFILE = sys.argv[1]
OUTPUTFILE = sys.argv[2]
df = pd.read_csv(POINTFILE, sep="\t")
N = df.shape[0]
M = (N - 1) / 2 * 3.2 # number of edges to be placed
D = np.zeros((N, N))
D = spatial.distance.squareform(spatial.distance.pdist(df))
d = np.sqrt(np.sum(D, axis=1))
D = np.diag(1 / d) @ D @ np.diag(1 / d)
S = np.random.power(3, (N,))
dif = 1e30
P_ = []
for l in np.logspace(1, 5):
P = np.outer(S, S) * np.exp(-l * np.power(D, 1))
P[P > 1] = 1
np.fill_diagonal(P, 0)
EM = np.sum(P) / 2
d = np.abs(EM - M)
if d < dif:
dif = d
P_ = P
print(l)
P = P_
Arand = np.array(np.random.random((N, N)) <= P).astype(int)
G = nx.from_numpy_array(Arand)
pos = {}
r, c = np.nonzero(np.triu(Arand))
for i in range(N):
pos[i] = np.array([df.iloc[i, 0], -df.iloc[i, 1]])
for node, (x, y) in pos.items():
G.node[node]["x"] = float(x)
G.node[node]["y"] = float(y)
nx.write_graphml(G, OUTPUTFILE)
#nx.draw_networkx(G, pos=pos, with_labels=False, node_size=S * 10)
#plt.axis("off")
#fig.savefig(OUTPUTFILE, bbox_inches = "tight", dpi = 300)
| true |
4d21da1b4c75b8e289c38d67602db50340cc11a8 | Python | comDennis/model-server | /music_recommender/ml_model/recommender.py | UTF-8 | 1,200 | 2.75 | 3 | [] | no_license | import os
import pickle
from ml_server.settings import BASE_DIR
import pandas as pd
def get_artist_recommendations(artist_name, number=5):
"""
Returns recommendations for a specific artists.
:param artist_name: Input artist.
:param number: Number of recommendations to be made. Max = 20.
:return: List of recommendations.
"""
number = min(20, number)
model_path = os.path.join(BASE_DIR, "music_recommender/ml_model/nn_recommender.sav")
data_path = os.path.join(BASE_DIR, "music_recommender/ml_model/wide_artist.csv")
data = pd.read_csv(data_path).pivot(index='artist_name', columns='user_id',
values='artist_total_plays').fillna(0)
nn_model = pickle.load(open(model_path, 'rb'))
try:
dist, indices = nn_model.kneighbors(data.ix[artist_name].values.reshape(1, -1), n_neighbors=number+1)
results = []
for i in range(1, len(dist.flatten())):
artist_dict = dict()
artist_dict['name'] = data.index[indices[0][i]]
artist_dict['distance'] = dist.flatten()[i]
results += [artist_dict]
except KeyError:
results = []
return results
| true |
2d3df84dcc8235c2204695d721dc70524c2b9ef3 | Python | benleowing29/Savemammy | /savemammy.py | UTF-8 | 29,266 | 2.75 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import random
import time
import getpass
import csv
width = 44
login_tried = 0
endProgram = False
account = {}
job ={}
captcha_list = ['heLL0', 'HoW', "R", "YoU?"]
def update():
with open('mammydata.csv', newline='') as csvfile:
rows = csv.DictReader(csvfile)
for row in rows:
info = {'pw': row['pw'], 'name': row['name'], 'age': row['age'], 'no_of_children': row['no_of_children'], 'child_age': row['child_age'], 'job1': row['job1'], 'job2': row['job2'], 'job3': row['job3'], 'work_mode': row['work_mode'], 'start_time': row['start_time'], 'end_time': row['end_time'], 'experience': row['experience'], 'duration': row['duration']}
account[row['email']] = info
with open('jobdata.csv', newline='') as jobfile:
rows = csv.DictReader(jobfile)
a = 0
for row in rows:
a = a + 1
detail = {'company': row['company'], 'job_name': row['job_name'], 'job_t': row['job_t'], 'job_mode': row['job_mode'], 'start_time': row['start_time'], 'end_time': row['end_time'], 'salary': row['salary'], 'vaccancyno': row['vaccancyno'], 'expectation': row['expectation'], 'details': row['details'], 'contactinfo': row['contactinfo']}
job[str(a)] = detail
def register(account):
email = input("Please input your email for login: ")
while True:
try:
if email == "":
raise Exception("This field cannot be empty!")
except Exception as msg:
print(msg)
break
try:
if '@' not in email:
raise Exception("Please enter an email!!")
except Exception as msg:
print(msg)
break
else:
pw = getpass.getpass(prompt='Please input your password: ')
try:
if pw == "":
raise Exception("This field cannot be empty!")
except Exception as msg:
print(msg)
break
else:
confirm = getpass.getpass(prompt='Please retype the password: ')
try:
if confirm != pw:
raise Exception("Your password and confirmation password do not match!")
except Exception as msg:
print(msg)
break
else:
name = input("Please input your full name: ")
try:
if name == "":
raise Exception("This field cannot be empty!")
except Exception as msg:
print(msg)
break
else:
age_range = ("18-25",'26-30','31-40','41-50','51+')
a = 0
print("## {} ##".format("#"*width))
print("## {} ##".format("".center(width)))
for i in age_range:
a = a + 1
b = str(a) + ". " + i
print("## {} ##".format(b.ljust(width)))
print("## {} ##".format("".center(width)))
print("## {} ##".format("#"*width))
print("\n")
age = input("Please input your age range (input integer): ")
try:
if age == "":
raise Exception("This field cannot be empty!")
except Exception as msg:
print(msg)
break
try:
age = int(age)
except ValueError:
print("Try Again!! Please enter the integer.")
break
try:
if age < 1 or age > a:
raise Exception("Please input integer show in the list!")
except Exception as msg:
print(msg)
break
else:
no_of_children = input("Please input number of children: ")
try:
if no_of_children == "":
raise Exception("This field cannot be empty!")
except Exception as msg:
print(msg)
break
try:
no_of_children = int(no_of_children)
except ValueError:
print("Try Again!! Please enter the integer.")
break
else:
children_age_range = ("0-3","4-6","6+")
c = 0
print("## {} ##".format("#"*width))
print("## {} ##".format("".center(width)))
for i in children_age_range:
c = c + 1
d = str(c) + ". " + i
print("## {} ##".format(d.ljust(width)))
print("## {} ##".format("".center(width)))
print("## {} ##".format("#"*width))
print("\n")
child_age = input("Please input age range of your youngest child (input integer): ")
try:
if child_age == "":
raise Exception("This field cannot be empty")
except Exception as msg:
print(msg)
break
try:
child_age = int(child_age)
except ValueError:
print("Try Again!! Please enter the integer.")
break
try:
if child_age < 1 or child_age > c:
raise Exception("Please input integer show in the list!")
except Exception as msg:
print(msg)
break
else:
job_type = ("Baby Sitting","Nanny","Playgroup Tutor","Postnatal Care/Assist","After-class tutorial","Accounting/Auditing","Baking","Designer","Copywriter","Customized Gift","Promoter")
e=0
print("## {} ##".format("#"*width))
print("## {} ##".format("".center(width)))
for i in job_type:
e = e + 1
f = str(e) + ". " + i
print("## {} ##".format(f.ljust(width)))
print("## {} ##".format("".center(width)))
print("## {} ##".format("#"*width))
print("\n")
job1 = input("Please input first preferred job type (input integer): ")
job2 = input("Please input second preferred job type (input integer): ")
job3 = input("Please input third preferred job type (input integer): ")
try:
if job1 == "" or job2 == "" or job3 =="":
raise Exception("This field cannot be empty")
except Exception as msg:
print(msg)
break
try:
job1 = int(job1)
job2 = int(job2)
job3 = int(job3)
except ValueError:
print("Try Again!! Please enter the integer.")
break
try:
if (job1 < 1 or job1 > e) or (job2 < 1 or job2 > e) or (job3 < 1 or job3 > e):
raise Exception("Please input integer show in the list!")
except Exception as msg:
print(msg)
break
else:
mode = ("Part Time","Full Time","Freelance")
g = 0
print("## {} ##".format("#"*width))
print("## {} ##".format("".center(width)))
for i in mode:
g = g + 1
h = str(g) + ". " + i
print("## {} ##".format(h.ljust(width)))
print("## {} ##".format("".center(width)))
print("## {} ##".format("#"*width))
print("\n")
work_mode = input("Please input your preferred work mode (input integer): ")
try:
if work_mode == "":
raise Exception("This field cannot be empty")
except Exception as msg:
print(msg)
break
try:
work_mode = int(work_mode)
except ValueError:
print("Try Again!! Please enter the integer.")
break
try:
if work_mode < 1 or work_mode > g:
raise Exception("Please input integer show in the list!")
except Exception as msg:
print(msg)
break
else:
print("Please input your available time period in HHMM (e.g.1215)")
start_time = input("From: ")
end_time = input("To: ")
experience = input("Please input number of years of experience in your preferred job field: ")
try:
if experience == "":
raise Exception("This field cannot be empty")
except Exception as msg:
print(msg)
break
try:
experience = int(experience)
except ValueError:
print("Try Again!! Please enter the integer.")
break
else:
j = 0
print("## {} ##".format("#"*width))
print("## {} ##".format("".center(width)))
for i in ("One-off","Weekly","Monthly"):
j = j + 1
k = str(j) + ". " + i
print("## {} ##".format(k.ljust(width)))
print("## {} ##".format("".center(width)))
print("## {} ##".format("#"*width))
print("\n")
duration = input("Please input duration (input integer): ")
try:
if duration == "":
raise Exception("This field cannot be empty")
except Exception as msg:
print(msg)
break
try:
duration = int(duration)
except ValueError:
print("Try Again!! Please enter the integer.")
break
try:
if duration < 1 or duration > j:
raise Exception("Please input integer show in the list!")
except Exception as msg:
print(msg)
break
else:
with open("mammydata.csv", 'a', newline="") as csvfile:
fieldnames = ['email','pw','name','age','no_of_children','child_age','job1','job2','job3','work_mode','start_time','end_time','experience','duration']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'email': email, 'pw': pw, 'name': name, 'age': age, 'no_of_children': no_of_children, 'child_age': child_age, 'job1': job1, 'job2': job2, 'job3': job3, 'work_mode': work_mode, 'start_time': start_time, 'end_time': end_time, 'experience': experience, 'duration': duration})
update()
print("## {} ##".format("#"*width))
print("## {} ##".format("".center(width)))
print("## {} ##".format("Successful Registration!".center(width)))
print("## {} ##".format("".center(width)))
print("## {} ##".format("1. Login".ljust(width)))
print("## {} ##".format("2. Back to Menu".ljust(width)))
print("## {} ##".format("3. Exit".ljust(width)))
print("## {} ##".format("".center(width)))
print("## {} ##".format("#"*width))
option = input("Enter the option: ")
if option == "1":
login(account, login)
return False
elif option == '2':
return False
else:
return True
def login(account, login_tried):
global login
a = ""
ntime=""
# Use while loop to stop the program after user tries login thrice
while login_tried <3:
login = input("Login Email: ")
# Check the existence of a username
if login in account.keys():
pw = getpass.getpass(prompt='Password: ')
# Check password and hide the input
if pw == account[login]["pw"]:
# Draw the captcha from captcha list to verify human
captcha=random.choice(captcha_list)
print("Enter the following captcha to verify you are human: " + captcha)
a=input("Your answer: ")
if a == captcha:
print("Login Success!")
break
else:
# login_tried add up 1 if user inputs data incorrectly
login_tried = login_tried + 1
print("Please try again!! Input captcha wrongly!")
else:
login_tried = login_tried + 1
print("Please try again!! Wrong password")
# Use variable ntime to store the current time if user inputs data incorrectly
ntime = time.localtime()
else:
login_tried = login_tried + 1
print("Please Try Again!! This user does not exist.")
else:
# Shutdown the program if users input the data incorrectly thrice
endProgram = True
def upload():
company = input("Please input company name: ")
while True:
try:
if company == "":
raise Exception("This field cannot be empty!")
except Exception as msg:
print(msg)
break
else:
job_name = input("Please input job name: ")
try:
if job_name == "":
raise Exception("This field cannot be empty!")
except Exception as msg:
print(msg)
break
else:
job_type = ("Baby Sitting","Nanny","Playgroup Tutor","Postnatal Care/Assist","After-class tutorial","Accounting/Auditing","Baking","Designer","Copywriter","Customized Gift","Promoter")
e=0
print("## {} ##".format("#"*width))
print("## {} ##".format("".center(width)))
for i in job_type:
e = e + 1
f = str(e) + ". " + i
print("## {} ##".format(f.ljust(width)))
print("## {} ##".format("".center(width)))
print("## {} ##".format("#"*width))
print("\n")
job_t = input("Please input the related job type (input integer): ")
try:
if job_t == "":
raise Exception("This field cannot be empty")
except Exception as msg:
print(msg)
break
try:
job_t = int(job_t)
except ValueError:
print("Try Again!! Please enter the integer.")
break
try:
if (job_t < 1 or job_t > e):
raise Exception("Please input integer show in the list!")
except Exception as msg:
print(msg)
break
else:
mode = ("Part Time","Full Time","Freelance")
g = 0
print("## {} ##".format("#"*width))
print("## {} ##".format("".center(width)))
for i in mode:
g = g + 1
h = str(g) + ". " + i
print("## {} ##".format(h.ljust(width)))
print("## {} ##".format("".center(width)))
print("## {} ##".format("#"*width))
print("\n")
job_mode = input("Please input the work mode (input integer): ")
try:
if job_mode == "":
raise Exception("This field cannot be empty")
except Exception as msg:
print(msg)
break
try:
job_mode = int(job_mode)
except ValueError:
print("Try Again!! Please enter the integer.")
break
try:
if job_mode < 1 or job_mode > g:
raise Exception("Please input integer show in the list!")
except Exception as msg:
print(msg)
break
else:
print("Please input the work time period in HHMM (e.g.1215)")
start_time = input("From: ")
end_time = input("To: ")
salary = input("Please input salary (in integer): ")
try:
if salary == "":
raise Exception("This field cannot be empty")
except Exception as msg:
print(msg)
break
try:
salary = int(salary)
except ValueError:
print("Try Again!! Please enter the integer.")
break
else:
vaccancyno = input("Please input the number of vaccancy: ")
try:
if vaccancyno == "":
raise Exception("This field cannot be empty")
except Exception as msg:
print(msg)
break
try:
vaccancyno = int(vaccancyno)
except ValueError:
print("Try Again!! Please enter the integer.")
break
else:
expectation = input("Type your expectation (optional): ")
details = input("Type the job details: ")
try:
if details == "":
raise Exception("This field cannot be empty")
except Exception as msg:
print(msg)
break
else:
contactinfo = input("Type the contact info: ")
try:
if contactinfo == "":
raise Exception("This field cannot be empty")
except Exception as msg:
print(msg)
else:
with open("jobdata.csv", 'a', newline="") as jobfile:
fieldnames = ['company','job_name','job_t','job_mode','start_time','end_time','salary','vaccancyno','expectation','details','contactinfo']
writer = csv.DictWriter(jobfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'company': company, 'job_name': job_name, 'job_t': job_t, 'job_mode': job_mode, 'start_time': start_time, 'end_time': end_time, 'salary': salary, 'vaccancyno': vaccancyno, 'expectation': expectation, 'details': details, 'contactinfo': contactinfo})
update()
print("## {} ##".format("#"*width))
print("## {} ##".format("".center(width)))
print("## {} ##".format("Successful Registration!".center(width)))
print("## {} ##".format("".center(width)))
print("## {} ##".format("1. Back to Menu".ljust(width)))
print("## {} ##".format("2. Exit".ljust(width)))
print("## {} ##".format("".center(width)))
print("## {} ##".format("#"*width))
option = input("Enter the option: ")
if option == "1":
return False
else:
return True
def matching(account, job, login):
a = 0
job_type = ("Baby Sitting","Nanny","Playgroup Tutor","Postnatal Care/Assist","After-class tutorial","Accounting/Auditing","Baking","Designer","Copywriter","Customized Gift","Promoter")
mode = ("Part Time","Full Time","Freelance")
for i,j in job.items():
if j['job_t'] == account[login]['job1'] or j['job_t'] == account[login]['job2'] or j['job_t'] == account[login]['job3']:
if j['job_mode'] == account[login]['work_mode']:
if (int(account[login]['start_time'])<= int(j['start_time']) <= int(account[login]['end_time'])) and (int(account[login]['start_time'])<= int(j['end_time']) <= int(account[login]['end_time'])):
a = a + 1
print(str(a)+".")
print("Company:", j['company'], "\n")
print("Job:", j['job_name'], "\n")
print("Job Type:", job_type[int(j['job_t'])-1], "\n")
print("Job Mode:", mode[int(j['job_mode'])-1], "\n")
print("Time:", j["start_time"],"-",j["end_time"],"\n")
print("Salary:", j["salary"],"\n")
print("Number of Vaccancies:", j["vaccancyno"], "\n")
print("Expectation:", j["expectation"], "\n")
print("Details:", j["details"], "\n")
print("Contact Information:", j["contactinfo"],"\n")
if a == 0:
print("Sorry!! We have no jobs which suitable for you.")
else:
print("We have sent your information to the company!")
while not endProgram:
# menu page
menuoption = ""
update()
while not menuoption in ["1", "2", "3", "4","5","view"]:
print("##################################################")
print("## {} ##".format("".center(width)))
print("## {} ##".format("Please select service".center(width)))
print("## {} ##".format("".center(width)))
print("## {} ##".format("1. Register ".ljust(width)))
print("## {} ##".format("2. Login".ljust(width)))
print("## {} ##".format("3. Upload Job".ljust(width)))
print("## {} ##".format("4. Matching".ljust(width)))
print("## {} ##".format("5. Exit".ljust(width)))
print("## {} ##".format("".center(width)))
print("## {} ##".format("#"*width))
menuoption = input("Enter the option: ")
else:
if menuoption == "1":
endProgram = register(account)
input("Press Enter to continue...")
elif menuoption == "2":
endProgram = login(account, login_tried)
input("Press Enter to continue...")
elif menuoption == "3":
endProgram = upload()
input("Press Enter to continue...")
elif menuoption == "4":
endProgram = matching(account, job, login)
input("Press Enter to continue...")
elif menuoption == "5":
endProgram = True
elif menuoption == "view":
endProgram = print(account, "n", job)
input("Press Enter to continue...")
print("Bye!")
input("Press Enter to end the program...") | true |
8ebe59b37983a4a0babe17371ec25ff3af9e7d6b | Python | bulat15g/for_the_trees | /pairs/lib_homo.py | UTF-8 | 3,233 | 2.96875 | 3 | [] | no_license | class Point2d:
x = float
y = float
def __init__(self, x, y):
self.x, self.y = x, y
def get_dxdy(self, point2):
return self.x - point2.x, self.y - point2.y
def get_norm(self, point2):
import math
return math.sqrt((self.x - point2.x) ** 2 + (self.y - point2.y) ** 2)
def __str__(self):
return str((self.x, self.y))
def read_text_file(f, set):
"""
x,y
x1,y1
...
..
.
"""
for line in f.readlines():
local_read = line.replace("\n", "").split(" ")
set.append(Point2d(float(local_read[0]), float(local_read[1])))
f.close()
def print_dict(dictionary):
print("(points in B(n-1))_(points in A(n-1))")
for key in dictionary.keys():
print("k:" + str(key) + " v:" + str(dictionary[key]))
print("\n\n")
def ordered_set(in_list):
out_list = []
added = set()
for val in in_list:
if not val in added:
out_list.append(val)
added.add(val)
return out_list
def export_res_set_mode(name, set_list_not_num, B_set, A_set):
import xlwt
workbook = xlwt.Workbook()
sheet = workbook.add_sheet(name)
set_list_num = ordered_set(set_list_not_num)
sheet.write(0, 0, "set")
sheet.write(0, 1, "POINT IN B(N-1)")
sheet.write(0, 2, "POINT IN A(N-1)")
sheet.write(0, 5, "X IN B")
sheet.write(0, 6, "Y IN B")
sheet.write(0, 8, "X IN A")
sheet.write(0, 9, "Y IN A")
for i in range(len(set_list_num)):
sheet.write(i + set_list_num[i][0] * 2 + 1, 0, str(set_list_num[i][0]))
sheet.write(i + set_list_num[i][0] * 2 + 1, 1, str(set_list_num[i][1]))
sheet.write(i + set_list_num[i][0] * 2 + 1, 2, str(set_list_num[i][2]))
sheet.write(i + set_list_num[i][0] * 2 + 1, 5, str(B_set[set_list_num[i][1]].x))
sheet.write(i + set_list_num[i][0] * 2 + 1, 6, str(B_set[set_list_num[i][1]].y))
sheet.write(i + set_list_num[i][0] * 2 + 1, 8, str(A_set[set_list_num[i][2]].x))
sheet.write(i + set_list_num[i][0] * 2 + 1, 9, str(A_set[set_list_num[i][2]].y))
workbook.save(name + ".xls")
def export_res(name, dictionary, B_set, A_set):
import xlwt
workbook = xlwt.Workbook()
sheet = workbook.add_sheet(name)
sheet.write(0, 0, "POINT IN B(N-1)")
sheet.write(0, 1, "POINT IN A(N-1)")
sheet.write(0, 5, "X IN B")
sheet.write(0, 6, "Y IN B")
sheet.write(0, 8, "X IN A")
sheet.write(0, 9, "Y IN A")
sheet.write(0, 11, "DX")
sheet.write(0, 12, "DY")
counter = 1
for key in dictionary:
sheet.write(counter, 0, str(key))
sheet.write(counter, 1, str(dictionary[key]))
sheet.write(counter, 5, str(B_set[key].x))
sheet.write(counter, 6, str(B_set[key].y))
sheet.write(counter, 8, str(A_set[dictionary[key]].x))
sheet.write(counter, 9, str(A_set[dictionary[key]].y))
sheet.write(counter, 11, str(A_set[dictionary[key]].x - B_set[key].x))
sheet.write(counter, 12, str(A_set[dictionary[key]].y - B_set[key].y))
# print(counter,key," key ",[dictionary[key]]," val ",B_set[key].x,A_set[dictionary[key]].x)
counter += 1
workbook.save(name + ".xls")
| true |
373944866ff8e07763aebea0ace66887f3ba7f7c | Python | JoeyDP/REST-Client | /RESTapi/api.py | UTF-8 | 4,855 | 2.59375 | 3 | [
"MIT"
] | permissive | import sys
from urllib.parse import urljoin
import requests
from .util import decorator
@decorator
def API(cls, base_url):
b = base_url
class A(cls):
base_url = b
suffix = ""
@property
def api(self):
return self
return A
class RequestPage(object):
def __init__(self, response):
self.response = response
@property
def data(self):
return self.response.json()
@property
def items(self):
return self.data.get('data', list())
@property
def itemCount(self):
return None
def getNextUrl(self):
""" Return next url or raise StopIteration if end """
raise NotImplementedError()
class Paginator(object):
def __init__(self, page):
self.page = page
self.itemCount = self.page.itemCount
def fetchNext(self):
response = makeRequest(self.page.getNextUrl())
if not response.ok:
print("Request failed")
print(response.text)
raise StopIteration
self.page = self.page.__class__(response)
def __iter__(self):
while True:
yield self.page
self.fetchNext()
def __len__(self):
return self.itemCount
@decorator
def Entity(cls):
class E(cls):
def __init__(self, api, **data):
self.api = api
# print(data)
for name in dir(cls):
attr = getattr(cls, name)
if isinstance(attr, Property):
try:
value = attr.parse(data.get(name))
except RuntimeError as e:
print("Attribute with name '{}' missing".format(name), file=sys.stderr)
raise e
setattr(self, name, value)
@property
def suffix(self):
return str(self.id) + '/'
@property
def base_url(self):
return self.api.base_url
@property
def token(self):
return self.api.token
return E
def makeRequest(url, *args, **kwargs):
r = requests.get(url, *args, **kwargs)
return r
@decorator
def GET(func, suffix="", paginate=False):
def wrapper(self, *args, **kwargs):
Type = func(self, *args, **kwargs)
the_suffix = suffix
url = urljoin(self.base_url, self.suffix)
url = urljoin(url, the_suffix)
for arg in args:
url = urljoin(url, arg)
params = {key: arg for key, arg in kwargs.items() if arg is not None}
params['access_token'] = self.token
# print(url)
r = makeRequest(url, params=params)
if not r.ok:
print("Request failed")
print("status", str(r.status_code))
print(r.text)
raise RequestException(r)
if paginate:
return self.api.paginate(Type, r)
else:
data = r.json()
entity = Type(self.api, **data)
return entity
return wrapper
def POST(f):
pass
class RequestException(Exception):
def __init__(self, request):
super().__init__()
self.request = request
class Property(object):
def __init__(self, required=True):
self.required = required
def parse(self, value):
if value is None:
if self.required:
raise RuntimeError("Missing required attribute")
else:
return
return self._parse(value)
def _parse(self, value):
raise NotImplementedError("subclasses should implement Property.parse")
class StringProperty(Property):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def _parse(self, value):
return str(value)
class IntProperty(Property):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def _parse(self, value):
return int(value)
# class CompoundProperty(Property):
# def _parse(self, data):
# for name in dir(self.__class__):
# attr = getattr(self.__class__, name)
# if isinstance(attr, Property):
# value = attr.parse(data.get(name))
# setattr(self, name, value)
class ListProperty(Property):
def __init__(self, cls, *args, **kwargs):
super().__init__(*args, **kwargs)
self.cls = cls
def _parse(self, data):
elements = list()
for elem in data:
instance = self.cls()
for name in dir(self.cls):
attr = getattr(self.cls, name)
if isinstance(attr, Property):
value = attr.parse(elem.get(name))
setattr(instance, name, value)
elements.append(instance)
return elements
| true |
1265c876b5f3c800a376716b9e9c519d488d849d | Python | marcoleonmora/algorithms | /8. volumenesFuncionYRepetir.py | UTF-8 | 1,244 | 4.3125 | 4 | [] | no_license | #******************************************
# Algoritmo para calcular y mostrar el área de
# un cubo o de un cilindro, usa funciones
# Programo: MLM
# Version: 3.0
# Fecha: 27/03/2019
#*****************************************/
import math
#Funcion para mostrar menu y capturar la opcion
def mostrarMenu():
print ("--------------------------")
print (" CALCULO DEL VOLUMEN")
print ("")
print (" 1- Volumen del cubo")
print (" 2- Volumen del cilindro")
print (" 3- Salir")
#Obtener opcionión seleccionada
opc = int(input("Seleccione una opcion: "))
print ("")
return opc
#Programa principal -------------------
opcion=0
while opcion != 3:
opcion = mostrarMenu()
volumen = 0
#Según opcion pedir parámetros y Calcular volumen
if opcion == 1:
l = int(input("Ingrese el lado del cubo: "))
volumen = l*l*l
elif opcion == 2:
r = int(input("Ingrese el radio del cilindro: "))
a = int(input("Ingrese la altura del cilindro: "))
volumen = (math.pi * r * r * a)
elif opcion != 3:
print ("La opcionion que ingresó no es válida")
# Mostrar resultado
if volumen > 0:
print ("El volumen es {}".format(volumen))
| true |
c476e79877ec6ed0d42943a92778379bc812a4e6 | Python | danielhasan1/star-wars-api | /starWarsApi/star_wars_data/api/tests.py | UTF-8 | 2,085 | 2.53125 | 3 | [] | no_license | from rest_framework.test import APITestCase
from rest_framework import status
from star_wars_data.models import StarWarsPlanets
MOVIE_DATA_SET = {
"count": 6,
"movie_titles": [
{
"title": "A New Hope",
"created": "2014-12-10T14:23:31.880000Z"
},
{
"title": "The Empire Strikes Back",
"created": "2014-12-12T11:26:24.656000Z"
},
{
"title": "Return of the Jedi",
"created": "2014-12-18T10:39:33.255000Z"
},
{
"title": "The Phantom Menace",
"created": "2014-12-19T16:52:55.740000Z"
},
{
"title": "Attack of the Clones",
"created": "2014-12-20T10:57:57.886000Z"
},
{
"title": "Revenge of the Sith",
"created": "2014-12-20T18:49:38.403000Z"
}
]
}
class SavedTitles(APITestCase):
def test_post_titles(self):
data = {'title': 'new idea'}
response = self.client.post('/api/savedtitles/',data)
data = response.json()
data.pop('timestamp')
# test status code
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
# test posted data
self.assertEqual(data, {'pk': 1, 'title': 'new idea','my_title': None,'favourite': False})
title_count = StarWarsPlanets.objects.all().count()
self.assertEqual(title_count,1)
self.assertNotEqual(title_count,0)
def test_sw_search_planet(self):
data = {
"count": 1,
"planet_names": [
{
"name": "Alderaan",
"created": "2014-12-10T11:35:48.479000Z"
}
]
}
response = self.client.get('/api/planets/?q=Alderaan')
# test planet search result
self.assertEqual(response.json(), data)
def test_sw_fetch_movie(self):
response = self.client.get('/api/movies/')
self.assertEqual(response.json(), MOVIE_DATA_SET) | true |
263cdb588ca7e634b03a0bb9e9dc8ea01ec0b791 | Python | BenLangmead/qtip | /bwamem.py | UTF-8 | 4,092 | 2.5625 | 3 | [
"MIT"
] | permissive | """
Copyright 2016, Ben Langmead <langmea@cs.jhu.edu>
Concrete subclass for BWA-MEM aligner.
"""
import os
import logging
import sys
from subprocess import Popen
from aligner import Aligner
try:
from Queue import Queue
except ImportError:
from queue import Queue # python 3.x
class BwaMem(Aligner):
""" Encapsulates a BWA-MEM process. The input can be a FASTQ
file, or a Queue onto which the caller enqueues reads.
Similarly, output can be a SAM file, or a Queue from which the
caller dequeues SAM records. All records are textual; parsing
is up to the user. """
def __init__(self,
cmd,
aligner_args,
aligner_unpaired_args,
aligner_paired_args,
index,
unpaired=None,
paired=None,
paired_combined=None,
pairs_only=False,
sam=None,
quiet=False,
input_format=None):
""" Create new process.
Inputs:
'unpaired' is an iterable over unpaired input filenames.
'paired' is an iterable over pairs of paired-end input
filenames. If both are None, then input reads will be
taken over the inQ. If either are non-None, then a call
to inQ will raise an exception.
Outputs:
'sam' is a filename where output SAM records will be
stored. If 'sam' is none, SAM records will be added to
the outQ.
"""
if index is None:
raise RuntimeError('Must specify --index when aligner is bwa mem')
options = []
popen_stdin, popen_stdout, popen_stderr = None, None, None
self.inQ, self.outQ = None, None
# Compose input arguments
if unpaired is not None and len(unpaired) > 1:
raise RuntimeError('bwa mem can\'t handle more than one input file at a time')
if paired is not None and len(paired) > 1:
raise RuntimeError('bwa mem can\'t handle more than one input file at a time')
if paired_combined is not None and len(paired_combined) > 1:
raise RuntimeError('bwa mem can\'t handle more than one input file at a time')
if unpaired is not None and (paired is not None or paired_combined is not None):
raise RuntimeError('bwa mem can\'t handle unpaired and paired-end inputs at the same time')
input_args = []
if unpaired is not None:
input_args = [unpaired[0]]
input_args.extend(aligner_unpaired_args)
if paired is not None:
assert len(paired[0]) == 2
input_args = [paired[0][0], paired[0][1]]
input_args.extend(aligner_paired_args)
if paired_combined is not None:
options.append('-p')
input_args = [paired_combined[0]]
input_args.extend(aligner_paired_args)
if unpaired is None and paired is None and paired_combined is None:
raise RuntimeError("Must specify one or more of: unpaired, paired, paired_combined")
# Compose output arguments
output_args = []
if sam is not None:
output_args.extend(['>', sam])
else:
raise RuntimeError("Must specify SAM output")
# Tell bwa mem whether to expected paired-end interleaved input
if pairs_only:
options.append('-p')
# Put all the arguments together
options.extend(aligner_args)
cmd += ' '
cmd += ' '.join(options + [index] + input_args + output_args)
logging.info('bwa mem command: ' + cmd)
if quiet:
popen_stderr = open(os.devnull, 'w')
self.pipe = Popen(cmd, shell=True,
stdin=popen_stdin, stdout=popen_stdout, stderr=popen_stderr,
bufsize=-1, close_fds='posix' in sys.builtin_module_names)
@staticmethod
def supports_mix():
return False
| true |
c032b327e9aac6b14bb1c77cd5eece8eb0ff80e7 | Python | chenxu0602/LeetCode | /1016.binary-string-with-substrings-representing-1-to-n.py | UTF-8 | 1,183 | 3.25 | 3 | [] | no_license | #
# @lc app=leetcode id=1016 lang=python3
#
# [1016] Binary String With Substrings Representing 1 To N
#
# https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/description/
#
# algorithms
# Medium (59.30%)
# Likes: 58
# Dislikes: 212
# Total Accepted: 9.3K
# Total Submissions: 15.8K
# Testcase Example: '"0110"\n3'
#
# Given a binary string S (a string consisting only of '0' and '1's) and a
# positive integer N, return true if and only if for every integer X from 1 to
# N, the binary representation of X is a substring of S.
#
#
#
# Example 1:
#
#
# Input: S = "0110", N = 3
# Output: true
#
#
# Example 2:
#
#
# Input: S = "0110", N = 4
# Output: false
#
#
#
#
# Note:
#
#
# 1 <= S.length <= 1000
# 1 <= N <= 10^9
#
#
#
class Solution:
def queryString(self, S: str, N: int) -> bool:
# suppose that N > 2047 then S must contains substrings of length 11 that represents all 1024 numbers from 1024 to 2047. But it is not possible because S is 1000 long so it can have at most 989 substrings of length 11. So we just need to check if N <= 2047.
return all(bin(i)[2:] in S for i in range(N, N//2, -1))
| true |
1bcdf4cdc4069e27597a48f1b59b00247e96d1e5 | Python | bibhashthakur/data-structures-and-algorithms | /stackarray.py | UTF-8 | 1,242 | 3.828125 | 4 | [] | no_license | import numpy as np
class Stack:
def __init__(self, datatype):
#print("Datatype is ", datatype)
self.arr = np.empty(5, dtype=datatype)
self.top = -1
self.size = self.arr.size
def push(self, val):
if (self.top == self.size - 1):
self.size *= 2
newarr = np.empty(self.size, dtype=int)
for i in range(self.top + 1):
newarr[i] = self.arr[i]
self.arr = newarr
self.top += 1
self.arr[self.top] = val
def pop(self):
if self.top == -1:
print('Stack is empty!')
return
val = self.arr[self.top]
self.top -= 1
return val
def peek(self):
if self.top == -1:
print('Stack is empty!')
return
val = self.arr[self.top]
return val
def driver():
stack = Stack(int)
print(stack.top)
print(stack.size)
stack.push(11)
stack.push(22)
stack.push(33)
stack.push(44)
stack.push(55)
print(stack.top)
print(stack.size)
print(stack.pop())
print(stack.peek())
stack.push(66)
print(stack.top)
print(stack.size)
| true |
37af425025c6b2aa25e849418e6c3915b695f6e6 | Python | P4ll/robotics | /3/src/robot.py | UTF-8 | 7,399 | 2.546875 | 3 | [] | no_license | import vrep
import sys
import math
import time
import numpy as np
import matplotlib.pyplot as plt
import cv2
import array
from PIL import Image
import imutils
class Robot():
"""
Robot class
Consts:
propConst - proportional constant in PID
integralConst - integral constant in PID
diffConst - diff const in PID
integralMaxVal, integralMinVal - lower and upper bounds of integral module
integralSum - inital integral sum
prevDist - previous distance to PID
leftWeelSpeed, rightWeelSpeed - std speed
reqDist - required dist
frontAdd - smoothing const of front detector
lowerGreen, upperGreen - bounds of color detection
"""
propConst = 10.1
integralConst = 1.5
diffConst = 0.5
integralMaxVal = 0.2
integralMinVal = -0.2
integralSum = 0.0
prevDist = -1
leftWeelSpeed = 1
rightWeelSpeed = 1
maxSpeed = 1.5
minSpeed = -1.5
reqDist = 0.55
frontAdd = -0.15
lowerGreen = np.array([0, 180, 0], dtype=np.uint8)
upperGreen = np.array([50, 255, 56], dtype=np.uint8)
def __init__(self):
"""
Constructor
Connection to V-REP and parms init
"""
vrep.simxFinish(-1)
self.clientID = vrep.simxStart('127.0.0.1', 19997, True, True, 5000, 5)
if self.clientID == -1:
print('Connection not successful')
sys.exit('Could not connect')
else:
print("Connected to remote server")
vrep.simxStartSimulation(self.clientID, vrep.simx_opmode_streaming)
# getting handlers of V-REP obj
errorCode, self.sensorFr = vrep.simxGetObjectHandle(self.clientID, 'Prox1', vrep.simx_opmode_oneshot_wait)
self.erCheck(errorCode, 'Prox1')
errorCode, self.sensor = vrep.simxGetObjectHandle(self.clientID, 'Prox2', vrep.simx_opmode_oneshot_wait)
self.erCheck(errorCode, 'Prox2')
errorCode, self.leftMotor = vrep.simxGetObjectHandle(self.clientID, 'Pioneer_p3dx_leftMotor', vrep.simx_opmode_oneshot_wait)
self.erCheck(errorCode, 'leftMotor')
errorCode, self.rightMotor = vrep.simxGetObjectHandle(self.clientID, 'Pioneer_p3dx_rightMotor', vrep.simx_opmode_oneshot_wait)
self.erCheck(errorCode, 'rightMotor')
errorCode, self.visSensor = vrep.simxGetObjectHandle(self.clientID, 'Vision_sensor', vrep.simx_opmode_oneshot_wait)
self.erCheck(errorCode, 'visSensor')
def addLeftSpeed(self, newSpeed):
"""
Control speed of left wheel
"""
ns = self.leftWeelSpeed + newSpeed
ns = min(ns, self.maxSpeed)
ns = max(ns, self.minSpeed)
e = vrep.simxSetJointTargetVelocity(self.clientID, self.leftMotor, ns, vrep.simx_opmode_oneshot_wait)
self.erCheck(e, 'leftMotor')
def addRightSpeed(self, newSpeed):
"""
Control speed of right wheel
"""
ns = self.rightWeelSpeed + newSpeed
ns = min(ns, self.maxSpeed)
ns = max(ns, self.minSpeed)
e = vrep.simxSetJointTargetVelocity(self.clientID, self.rightMotor, ns, vrep.simx_opmode_oneshot_wait)
self.erCheck(e, 'rightMotor')
def calulate(self, state, dist):
#calc of a integral, proportional and diff componets
deltaDist = self.reqDist - dist
propComponent = self.propConst * deltaDist
self.integralSum = self.integralSum + deltaDist
self.integralSum = min(self.integralSum, self.integralMaxVal)
self.integralSum = max(self.integralSum, self.integralMinVal)
integralComponent = self.integralConst * self.integralSum
if self.prevDist == -1:
self.prevDist = dist
diffComponent = self.diffConst * (dist - self.prevDist)
self.prevDist = dist
# getting a PID res
result = propComponent + diffComponent + integralComponent
# speed control
self.addLeftSpeed(-result)
self.addRightSpeed(result)
def erCheck(self, e, str):
if e == -1:
print('Somthing wrong with {0}'.format(str))
sys.exit()
def calcVertByCont(self, c):
# calc vertex by contours
perimetr = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.04 * perimetr, True)
return len(approx)
def isSq(self, c):
# check for square
perimetr = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.04 * perimetr, True)
if (len(approx) == 6):
return True
_, _, w, h = cv2.boundingRect(approx)
ar = w / float(h)
return True if ar >= 0.60 and ar <= 1.4 else False
# return True if ar >= 0.90 and ar <= 1.1 else False
def imageProcessing(self, img):
# getting mask by color
mask = cv2.inRange(img, self.lowerGreen, self.upperGreen)
res = cv2.bitwise_and(img, img, mask=mask)
# getting contours
cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
font = cv2.FONT_HERSHEY_SIMPLEX
# check for cuboid for all cnt
for c in cnts:
if (self.isSq(c)): # or self.calcVertByCont(c) == 4 or self.calcVertByCont(c) == 6
x,y,w,h = cv2.boundingRect(c)
cv2.rectangle(img, (x, y), (x + w, y + h), (250, 0, 0), 2)
return img
def robotControl(self):
# std alg of a Pioneer control
(errorCode, sensorState, sensorDetection, detectedObjectHandle,
detectedSurfaceNormalVectorUp) = vrep.simxReadProximitySensor(self.clientID, self.sensor, vrep.simx_opmode_streaming)
(errorCode, frontState, frontDetection, detectedObjectHandle,
detectedSurfaceNormalVectorFr) = vrep.simxReadProximitySensor(self.clientID, self.sensorFr, vrep.simx_opmode_streaming)
if (frontState and sensorState):
self.calulate(sensorState, min(sensorDetection[2], frontDetection[2] + self.frontAdd))
elif (frontState):
self.calulate(frontState, frontDetection[2] + self.frontAdd)
elif (sensorState):
self.calulate(sensorState, sensorDetection[2])
else:
self.calulate(sensorState, self.reqDist + 0.1)
def simulate(self):
res = vrep.simxGetVisionSensorImage(self.clientID, self.visSensor, 0, vrep.simx_opmode_streaming)
cv2.namedWindow('camera', cv2.WINDOW_NORMAL)
cv2.resizeWindow('camera', 400, 400)
while vrep.simxGetConnectionId(self.clientID) != -1:
self.robotControl()
visionSensorData = vrep.simxGetVisionSensorImage(self.clientID, self.visSensor, 0, vrep.simx_opmode_buffer)
if (len(visionSensorData) == 0 or visionSensorData[0] != vrep.simx_return_ok):
continue
pixelFlow = np.array(visionSensorData[2][::-1], np.uint8)
image = np.reshape(pixelFlow, (visionSensorData[1][0], visionSensorData[1][1], 3), 'C')
image = cv2.flip(image, 1)
image = self.imageProcessing(image)
cv2.imshow('camera', image)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
if __name__ == "__main__":
robot = Robot()
robot.simulate() | true |
a961de5c1d3b4232e20a0cc3956614726f8133b6 | Python | DragonPG2000/GroupNorm | /GroupNorm/groupnorm.py | UTF-8 | 1,836 | 2.703125 | 3 | [] | no_license | import tensorflow as tf
from tensorflow import keras
import numpy as np
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Layer
from tensorflow.keras.backend import image_data_format
class GroupNorm(Layer):
"""
Reimplementation of GroupNorm using the excellent post
https://amaarora.github.io/2020/08/09/groupnorm.html
"""
def __init__(self,groups=32,**kwargs):
"""
Arguments:
groups: The number of groups that the channels are divided into (Default value=32)
eps: The value used in order to prevent zero by division errors
"""
super(GroupNorm,self).__init__(**kwargs)
self.g=groups
self.eps=1e-5
if image_data_format()=='channels_first':
self.axis=1
else:
self.axis=-1
def build(self,input_shape):
"""
Arguments:
input_shape: The shape of the feature maps in the form N*H*W*C
"""
shape=[1,1,1,1]
shape[self.axis]=int(input_shape[self.axis])
self.gamma=self.add_weight('gamma',
shape=shape)
self.beta=self.add_weight('gamma',
shape=shape)
super().build(input_shape)
def call(self,inputs):
"""
Arguments:
inputs: The transformed features from the previous layers
"""
input_shape=K.int_shape(inputs)
n,h,w,c=input_shape
tensor_shape=tf.shape(inputs)
shape=[tensor_shape[i] for i in range(len(input_shape))]
shape[self.axis]=shape[self.axis]//self.g
shape.insert(self.axis,self.g)
shape=tf.stack(shape)
x=tf.reshape(inputs,shape=shape)
mean,variance=tf.nn.moments(x,axes=[1,2,3],keepdims=True)
x_transformed=(x-mean)/tf.sqrt(variance+self.eps)
x_transformed=tf.reshape(x_transformed,shape=tensor_shape)
x_transformed=self.gamma*x_transformed+self.beta
return x_transformed | true |
dfd9007424c657182d931797ac69c4c1a4d80b37 | Python | vovabcps/university_management_service | /university/migrations/0003_insertDataRest.py | UTF-8 | 31,751 | 2.625 | 3 | [] | no_license | from django.db import migrations, transaction
from ..models import *
from django.conf import settings
import math
import random
from django.contrib.auth.models import User
from datetime import datetime, timedelta
from django.shortcuts import get_object_or_404
import collections
import re
import ast
#the @transaction.atomic method decorator ensures the method operations are run in a single transaction.
@transaction.atomic
def makeSchoolYearOBJs(beginYear, endYear):
"""
beginYear -> o primeiro ano em q se começa a guardar dados
endYear -> o ano final(ou seja, este ano)
endYear > beginYear
"""
for i in range(endYear - beginYear):
begin= str((beginYear+i))
end= str((beginYear+i+1))
newYear= SchoolYear(begin=begin, end=end) #ex: (2017, 2018)
newYear.save()
#makeRoomOBJs(70, 0)
@transaction.atomic
def makeRoomOBJs(totalroomsClasses, totalroomsOffices):
"""
totalroomsClasses -> total de salas em q ha aulas (int)
totalroomsOffices -> total de gabinetes (ou salas em q nao ha aulas) (int)
"""
#nota: 1 building has a maximum of 5 floors (75 rooms)
#nota: 1 floor has a maximim of 15 rooms
totalRomms= totalroomsClasses + totalroomsOffices
roomsPlaced= 0
roomsLeftToPlace= totalRomms
numBuilding= 1
while roomsLeftToPlace > 0 :
roomsPlaced += makeBuilding(numBuilding, 5, 15, roomsLeftToPlace, totalroomsOffices)
roomsLeftToPlace= totalRomms - roomsPlaced
numBuilding += 1
def makeBuilding(numBuilding, numFloors, numOfRoomsPerFloor, totalRooms, totalroomsOffices):
"""
numBuilding -> numero do edificio (int)
numFloors -> numero maximo de pisos desse edificio (int)
numOfRoomsPerFloor -> numero maximo de salas de cada piso (int)
totalRooms -> total de salas desse edificio, incluindo gabinetes (int)
totalroomsOffices -> total de gabinetes desse edificio (int)
"""
cont= 0
give_class= True
for f in range(1, numFloors+1):
for r in range(numOfRoomsPerFloor):
if (totalRooms - cont) <= totalroomsOffices :
give_class = False
cont += 1
room= str(numBuilding) + "." + str(f) + "." + str(cont)
newRoom = Room(room_number=room, can_give_class=give_class) #ex: (3.1.15, True)
newRoom.save()
if (cont == totalRooms): return cont
return cont
@transaction.atomic
def makeRoleOBJs():
roles = ["Professor", "Aluno", "Admin"]
for r in roles:
newRole= Role(role=r)
newRole.save()
@transaction.atomic
def makeSystemUserOBJs():
allUsers= User.objects.all() #800 users
gabinetes= Room.objects.filter(can_give_class= False) #42 gabinetes
#roles objs
rProfessor= Role.objects.get(role="Professor")
rAluno= Role.objects.get(role="Aluno")
rAdmin= Role.objects.get(role="Admin")
#[totalusers , roles, tem gabinete?]
totalUserRoles= [[3, rAdmin, True, "@admin.fc.ul.pt"], [110, rProfessor, True, "@professor.fc.ul.pt"], [687, rAluno, False, "@alunos.fc.ul.pt"]]
#3+110=113; 800-113=687 resto
#num professores = num cadeiras (regente)
cont=1
i=0
gab= 0
for user in allUsers :
total= sum([n for (n,l,b,d) in totalUserRoles[:(i+1)]])
if cont > total :
i += 1
newUSER= SystemUser(user=user, role=totalUserRoles[i][1])
newUSER.save() #tem q ser antes do rooms.add
user.email = user.username + totalUserRoles[i][3]
if totalUserRoles[i][2] :
newUSER.rooms.add(gabinetes[gab])
gab = (gab+1) % gabinetes.count() #array circular
user.save()
cont += 1
@transaction.atomic
def makePersonalInfoOBJs():
allSystemUsers= SystemUser.objects.all()
with open(settings.MIGRATIONS_DATA_ROOT + "/NamesGenderNationalityBirthAdressVat800.txt", encoding="utf8") as rfile:
listData = rfile.readlines()
num= 0
m = 0
f = 0
femList = getDicttOfGenderPics()["female"]
maleList = getDicttOfGenderPics()["male"]
for user in allSystemUsers :
name, gender, nationality, date_str, address, vat =listData[num].split("||")
email= name.split()[-1]+str(user.id)+random.choice(["@hotmail.com", "@gmail.com"]) #unique
phone = "9" + str(random.randint(00000000,99999999)) #because they are in portugal so they need a pt phone number xd
random.seed(user.id)
idDocument= str(random.randint(00000000,99999999)) #unique
date = datetime.strptime(date_str, "%d/%m/%Y").date()
newUSER= PersonalInfo(user=user, address=address, birth_date=date, name=name,
phone_number=phone, personal_email=email, gender=gender, nationality=nationality, id_document=idDocument, vat_number=vat)
newUSER.save()
if newUSER.gender == "male":
newUSER.profile_pic = "our/pics/" + maleList[m][:-4]+ ".png"
m+=1
else:
newUSER.profile_pic = "our/pics/" + femList[f][:-4]+ ".png"
f+=1
newUSER.save()
num += 1
def getDicttOfGenderPics():
import os
directory_in_str = settings.STATIC_ROOT + "/our/pics"
directory = os.fsencode(directory_in_str)
maleList = []
femaleList = []
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith(".txt"):
f = open(settings.STATIC_ROOT + "/our/pics/" + filename, "r")
age = f.readline().split(":")[1]
gender = f.readline().split(":")[1]
if gender.__contains__("Female"):
femaleList.append(filename)
else:
maleList.append(filename)
f.close()
continue
else:
continue
return {"male": maleList, "female": femaleList}
@transaction.atomic
def makeCourseOBJs():
allSystemUsers= SystemUser.objects.all()
allSchoolYears= SchoolYear.objects.all()
allTeachers= list(SystemUser.objects.filter(role__role="Professor"))
schoolyearOBJ_17_18= SchoolYear.objects.get(begin=2017)
#----------------- minors -----------------
minors= [(0, "Minor em Biologia"), (1, "Minor em Gestão")]
minorsOBJ= []
for (_, minor) in minors:
newCourse= Course(name=minor, grau="Minor", credits_number=30, credits_numberByYear="", duration=2, timetable="Diurno", coordinator=allTeachers.pop())
newCourse.save()
minorsOBJ.append(newCourse)
#----------------- formaçao e optativas -----------------
newCourseF= Course(name="450_Formação Cultural Social e Ética", grau="Formação", timetable="Diurno")
newCourseF.save()
newCourseOEI= Course(name="462_Lic. em Eng. Informática ", grau="Optativas", timetable="Diurno")
newCourseOEI.save()
newCourseOTI= Course(name="517_Lic. em TIC/TI", grau="Optativas", timetable="Diurno", )
newCourseOTI.save()
#----------------- licenciaturas -----------------
newCourseTI= Course(name="Licenciatura em Tecnologias de Informação", grau="Licenciatura", credits_number=180, credits_numberByYear="1:60|2:60|3:60", duration=6, timetable="Diurno", coordinator=allTeachers.pop())
newCourseTI.save()
newCourseEI= Course(name="Licenciatura em Engenharia Informática", grau="Licenciatura", credits_number=180, credits_numberByYear="1:60|2:60|3:60", duration=6, timetable="Diurno", coordinator=allTeachers.pop())
newCourseEI.save()
#----------------- couso mini_cursos associaçoes -----------------
newCourse_MiniCourse= Course_MiniCourse(course=newCourseEI , miniCourse=newCourseF , credits_number=3, year=2, semestres="2")
newCourse_MiniCourse.save()
newCourse_MiniCourse= Course_MiniCourse(course=newCourseEI , miniCourse=newCourseF , credits_number=3, year=1, semestres="1")
newCourse_MiniCourse.save()
newCourse_MiniCourse= Course_MiniCourse(course=newCourseEI , miniCourse=newCourseOEI , credits_number=6, year=3, semestres="2")
newCourse_MiniCourse.save()
newCourse_MiniCourse= Course_MiniCourse(course=newCourseTI , miniCourse=newCourseF , credits_number=9, year=1, semestres="1")
newCourse_MiniCourse.save()
newCourse_MiniCourse= Course_MiniCourse(course=newCourseTI , miniCourse=minorsOBJ[0] , credits_number=30, year=3, semestres="1,2")
newCourse_MiniCourse.save()
newCourse_MiniCourse= Course_MiniCourse(course=newCourseTI , miniCourse=minorsOBJ[1] , credits_number=30, year=3, semestres="1,2")
newCourse_MiniCourse.save()
newCourse_MiniCourse= Course_MiniCourse(course=newCourseTI , miniCourse=newCourseOTI , credits_number=6, year=3, semestres="1,2")
newCourse_MiniCourse.save()
@transaction.atomic
def makeSubjectAndCourseSubjectOBJs():
with open(settings.MIGRATIONS_DATA_ROOT + "/subjectsData.txt", encoding="utf8") as rfile:
for line in rfile.readlines():
if "#" not in line and "||" in line:
cadeira_curso= line.split("||")
nomeCadeira, cred = cadeira_curso[0].split(",")
#print(nomeCadeira)
newSubject= Subject(name=nomeCadeira, credits_number=int(cred))
newSubject.save()
lstCourses= cadeira_curso[1].split("!!")
for course in lstCourses :
nameCourse, year, semester, type = course.split(",")
cleanType= type.split("\n")[0] #pq ao usar readlines() o line fica com "\n" no final
course= Course.objects.get(name=nameCourse)
newCourseSubject= CourseSubject(course=course, subject=newSubject, year=year, semester=semester, type=cleanType)
newCourseSubject.save()
#print(newCourseSubject)
#print(nameCourse)
#print(nomeCadeira)
#courseSubjectObj= CourseSubject.objects.get(course=course, subject=newSubject)
@transaction.atomic
def makeSystemUserCourseOBJs():
#allSystemUsers= SystemUser.objects.exclude(id__in= table2.objects.filter(roles=["Admin"]).values_list('id', flat=True))
allStudents= SystemUser.objects.filter(role__role="Aluno")
allLicenciaturas= Course.objects.filter(grau="Licenciatura")
casosPossiveis= [["2016/2017", "1"], ["2016/2017", "2"], ["2016/2017", "3"], ["2017/2018", "1"], ["2017/2018", "2"], ["2018/2019", "1"]]
for user in allStudents :
anoInicio, anoAtual= random.choice(casosPossiveis)
course= random.choice(allLicenciaturas)
newSystemUserCourse= SystemUserCourse(user=user, course=course, estadoActual="Matriculado", anoLectivoDeInício=anoInicio, anoActual=int(anoAtual))
if course.name == "Licenciatura em Engenharia Informática":
newSystemUserCourse.minor= "Nao incluido"
newSystemUserCourse.save()
@transaction.atomic
def makeSystemUserSubjectAndLessonSystemUserOBJs():
with open(settings.MIGRATIONS_DATA_ROOT + "/userSubjectsLessonsData.txt", encoding="utf8") as rfile:
for line in rfile.readlines():
if "aprovadas" in line:
tipoDeInscriçaoSubj= "aprovadas"
elif "pending" in line:
tipoDeInscriçaoSubj= "pending"
else:
if "SystemUserCourse" in line:
algoritmo= "SystemUserCourse"
elif "SystemUserSubject" in line :
algoritmo= "SystemUserSubject"
variante= 0
else:
if "#" not in line and "," in line:
line= line[:-1] #remover o '\n' do final
#se nao for um comentario nem uma linha vazia
print(algoritmo)
if algoritmo == "SystemUserCourse":
#Licenciatura em Tecnologias de Informação,Matriculado,2016/2017,1
nameCourse, estado, anoLetivoInicio, ano = line.split(",")
CourseObj= Course.objects.get(name=nameCourse)
lstSystemUserCourseObj= SystemUserCourse.objects.filter(course=CourseObj, estadoActual=estado, anoLectivoDeInício=anoLetivoInicio, anoActual=ano)
else :
if tipoDeInscriçaoSubj == "aprovadas" :
#ex:1sem++Produção de Documentos Técnicos,1,15.0,TP13!!Curso de Competências Sociais e Desenvolvimento Pessoal,1,18.3,TP11!!Programação I (LTI),1,12.2,T11,TP13,PL13| |2sem++Introdução às Tecnologias Web,1,14.1,T21,TP21,PL21!!Programação II (LTI),1,13.7,T21,TP21,PL21
for SystemUserCourseObj in lstSystemUserCourseObj:
sysUser= SystemUserCourseObj.user
somaCredUser= 0
#---------- LessonSystemUser objects ----------
if anoLetivoInicio == "2016/2017" :
opcoes= "2016/2017||2017/2018"
else: # anoLetivoInicio == "2017/2018" :
opcoes= "2017/2018"
#-----------------------------------
for semSubjLessons in line.split("| |") :
#para cada semestre
semestre, subjLessons= semSubjLessons.split("++")
for subjLesson in subjLessons.split("!!"):
#para cada cadeira desse semestre
subjName, state, grade, *lstTypeTurma =subjLesson.split(",")
#print(subjName)
SubjObj= Subject.objects.get(name=subjName)
somaCredUser = somaCredUser + SubjObj.credits_number
turmas_str= " ".join(lstTypeTurma)
#---------- LessonSystemUser objects ----------
anoLetivoAprov= random.choice(opcoes.split("||")) #ano letivo em q foi aprovado a cadeira
schoolYearObj= SchoolYear.objects.get(begin=int(anoLetivoAprov.split("/")[0]))
newSystemUserSubject = SystemUserSubject(user= sysUser, subject=SubjObj, subjSemestre=int(semestre[0]), state=state, grade=grade, turmas=turmas_str, anoLetivo=schoolYearObj)
newSystemUserSubject.save()
#lstTypeTurma: ["T11","TP13","PL13"]
for typeTurma in lstTypeTurma :
type, turma= separateLettersNumb(typeTurma)
lessonObjs= Lesson.objects.filter(subject=SubjObj, type=type, turma=turma)
diasDaSemana= ""
for lessonObj in lessonObjs : #ex: T11 terça, T11 quinta
diasDaSemana = lessonObj.week_day
allCorrectDates= lessonSystemUser(anoLetivoAprov, semestre, diasDaSemana)
presDate_str= presenca_in_date(allCorrectDates)
for presData in presDate_str.split("!!") :
presenca, date_str = presData.split(",")
#print(presData)
dataFormat= datetime.strptime(date_str, "%d/%m/%Y").date()
newLessonSystemUser = LessonSystemUser(systemUser=sysUser, lesson=lessonObj, presente=ast.literal_eval(presenca), date=dataFormat)
newLessonSystemUser.save()
if SystemUserCourseObj.minor != "Nao incluido":
#lti
courseDoUser= SystemUserCourseObj.course
C_miniCursos= Course_MiniCourse.objects.filter(course=courseDoUser)
minors= [] #get todos os minors daquele curso
for C_miniCurso in C_miniCursos:
if C_miniCurso.miniCourse.grau == "Minor" :
minors.append(C_miniCurso.miniCourse)
if somaCredUser >= 108 :
minorEscolhido= random.choice(minors)
SystemUserCourseObj.minor= minorEscolhido.name
SystemUserCourseObj.totalCred= somaCredUser
SystemUserCourseObj.save()
else: #"pending"
#cada turma vai ter 17 alunos aproximadamente exepto teoricas
if variante == 0:
lstSUPartida= lstSystemUserCourseObj[:17]
variante += 1
elif variante == 1:
lstSUPartida= lstSystemUserCourseObj[17:34]
variante += 1
else:
lstSUPartida= lstSystemUserCourseObj[34:]
for SystemUserCourseObj in lstSUPartida:
sysUser= SystemUserCourseObj.user
#-----------------------------------
for semSubjLessons in line.split("| |") :
#para cada semestre
semestre, subjLessons= semSubjLessons.split("++")
for subjLesson in subjLessons.split("!!"):
#para cada cadeira desse semestre
subjName, state, *lstTypeTurma =subjLesson.split(",")
#print(subjName)
SubjObj= Subject.objects.get(name=subjName)
turmas_str= " ".join(lstTypeTurma)
#---------- LessonSystemUser objects ----------
schoolYearObj= SchoolYear.objects.get(begin=2018) #ele esta a increver-se este ano
newSystemUserSubject = SystemUserSubject(user= sysUser, subject=SubjObj, subjSemestre=int(semestre[0]), state=state, grade=None, turmas=turmas_str, anoLetivo=schoolYearObj)
newSystemUserSubject.save()
# -- variaveis --
dic = { "2016/2017": {'1sem': ["20/09/2016", "21/12/2016"], '2sem': ["20/02/2017", "31/05/2017"]},
"2017/2018": {'1sem': ["18/09/2017", "21/12/2017"], '2sem': ["19/02/2018", "30/05/2018"]}}
lstDiasDaSemana= ["SEG", "TER", "QUA", "QUI", "SEX", "SAB", "DOM"]
feriados = ['01/01', '19/04', '21/04', '25/04', '01/05', '10/06', '20/06', '15/08', '05/10', '01/11', '01/12', '08/12', '25/12'] #completo
ferias= [["04/03", "06/03"], #carnaval
["17/04", "23/04"]] #pascoa
def lessonSystemUser(anoLetivoAprov, semestre, diasDaSemana):
dataInicio, dataFinal= dic[anoLetivoAprov][semestre]
ano= dataInicio.split("/")[2] #201*
joinFerias= allFeriasDate(ferias, ano)
formatFeriados= convertFeriados(feriados, ano)
joinFeriasAndFeriados= joinFerias + formatFeriados
return getDatesBetween2Dates(dataInicio, dataFinal, joinFeriasAndFeriados, diasDaSemana)
def getDatesBetween2Dates(dataInicio, dataFinal, lazyDays=None, diasDaSemana=lstDiasDaSemana):
"""
devolve todas as datas que calham em dias de semana especificos
lazyDays != none, retira as datas q sejam feriados ou no periodo de mini ferias
diasDaSemana -> os dias da semana que quero as datas, pode ser uma lista ou uma string(ex: "TER QUI")
recebe: ex: 17/04/2017, 23/04/2017, None, ['SEG', 'TER', 'QUA', 'QUI', 'SEX', 'SAB', 'DOM']
retorna: ex: ['17/04/2017', '18/04/2017', ... , '22/04/2017', '23/04/2017']
recebe: ex: 18/09/2017, 21/12/2017, ['04/03/2017', '05/03/2017', ...], "QUARTA" (ou 'QUA')
retorna: ex: ['20/09/2017', '27/09/2017', '04/10/2017', ..., '20/12/2017']
"""
start_date = datetime.strptime(dataInicio, '%d/%m/%Y')
end_date = datetime.strptime(dataFinal, '%d/%m/%Y')
if lazyDays == None:
lstDates= []
else:
lstWorkDates= []
for i in range(-1, (end_date - start_date).days, 1):
nextDate= start_date + timedelta(days=i+1)
diaDaSemana= lstDiasDaSemana[nextDate.weekday()]
if diaDaSemana in diasDaSemana:
date_str= nextDate.date().strftime('%d/%m/%Y')
#print(date_str)
if lazyDays == None:
lstDates.append(date_str)
else:
if date_str not in lazyDays:
lstWorkDates.append(date_str)
if lazyDays == None:
return lstDates
else:
return lstWorkDates
def convertFerias(ferias, ano):
#recebe ex: ferias= [["04/03", "06/03"], ["17/04", "23/04"]], ano=2018
#retorna ex: [['04/03/201*', '06/03/201*'], ['17/04/201*', '23/04/201*']]
return list(map(lambda lst: list(map(lambda dm: dm + "/" + ano, lst)), ferias))
def convertFeriados(feriados, ano):
#recebe ex: feriados = ['01/01', '19/04', ... ], ano=2018
#retorna ex: feriados = ['01/01/201*', '19/04/201*', '21/04/201*', ...]
return list(map(lambda dm: dm + "/" + ano, feriados))
def allFeriasDate(ferias, ano):
#recebe ex: ferias= [["04/03", "06/03"], ["17/04", "23/04"]], ano=2018
#retorna ex: ['04/03/2018', '05/03/2018', '06/03/2018', '17/04/2018', '18/04/2018', ... , '23/04/2018']
newFerias= convertFerias(ferias, ano)
newFerias_str= []
for f in newFerias:
dataInicio, dataFinal= f
newFerias_str = newFerias_str + getDatesBetween2Dates(dataInicio, dataFinal)
return newFerias_str
def presenca_in_date(allCorrectDates) :
"""
recebe: ex: ['22/09/2017', '29/09/2017', '06/10/2017', ..., '15/12/2017']
retorna: ex: "True,22/09/2017!!True,29/09/2017!!False,06/10/2017!!...!!True,15/12/2017
"""
bool= ["True", "False"]
prob= [0.85,0.15]
prim= True
for date in allCorrectDates:
ispresent= random.choices(bool, prob)[0]
if prim :
output = ispresent + "," + date
prim= False
else:
output = output + "!!" + ispresent + "," + date
return output
def separateLettersNumb(string):
#"TP13" fica ['TP', '13']
return re.split('(\d+)',string)[:-1]
@transaction.atomic
def makeLessonOBJs():
with open(settings.MIGRATIONS_DATA_ROOT + "/lessonsData.txt", encoding="utf8") as rfile:
for line in rfile.readlines():
if "#" not in line and "||" in line:
cadeira_lessons= line.split("||")
nomeCadeira = cadeira_lessons[0]
#print(nomeCadeira)
lstLessons= cadeira_lessons[1].split("!!")
for lesson in lstLessons :
type, turma, weekDay, hour, duration = lesson.split(",")
if len(hour) == 4 :
hour= "0" + hour
if len(turma) == 1 :
turma= "0" + turma
cleanDuration= duration.split("\n")[0] #pq ao usar readlines() o line fica com "\n" no final
subject= Subject.objects.get(name=nomeCadeira)
newLesson= Lesson(subject=subject, type=type, turma=turma, week_day=weekDay, hour=hour, duration=cleanDuration)
newLesson.save()
#put rooms
lessons= Lesson.objects.order_by("week_day", "subject__name", "turma")
rooms= Room.objects.filter(can_give_class= True) #200 rooms that can have class
prim=True
i=0
for lesson in lessons:
if prim :
lesson.room=rooms[i]
prim = False
else :
if lessonAnt.week_day != lesson.week_day :
i= 0
lesson.room=rooms[i]
else: #no mesmo dia de semana
if addMinutes(lessonAnt.hour, lessonAnt.duration) <= hourToMinutes(lesson.hour) :
lesson.room=rooms[i]
else:
i = (i+1) % rooms.count() #array circular
lesson.room=rooms[i]
lesson.save()
lessonAnt = lesson
#atribuir professores
lstLessonsPrim= []
lstLessonsSeg= []
lstLessonsPrimAndSeg= []
#dados
#obter todas as cadeiras ordenadas por curso/mini-curso
dicSubjs= CourseSubject.objects.values('subject').distinct().order_by("course")
allTeachers= SystemUser.objects.filter(role__role="Professor")
#separar cadeiras por semestre e ordena-las
for key in dicSubjs:
subj= Subject.objects.get(id=key['subject'])
lesson= Lesson.objects.filter(subject=subj).order_by("week_day", "hour") #lista de lessons
CRsubjs= CourseSubject.objects.filter(subject=subj)
#se o sem da cadeira e igual independentemente do curso
if is_semestres_all_same(CRsubjs) :
sem= CRsubjs[0].semester
if sem == 1:
lstLessonsPrim.append(lesson)
else:
lstLessonsSeg.append(lesson)
else:
lstLessonsPrimAndSeg.append(lesson)
allLessonsBySem = {"1": lstLessonsPrim, "2":lstLessonsSeg, "1,2": lstLessonsPrimAndSeg}
#ex: lstLessonsPrimAndSeg, a cadeira Empreendedorismo é dada no 1 sem e no 2 sem
# 450_Formação Cultural Social e Ética Empreendedorismo em Ciências 2 ano 2 sem Semestral (Opção)
# 450_Formação Cultural Social e Ética Empreendedorismo em Ciências 1 ano 1 sem Semestral (Opção)
i=0
for semestre, lstLessons in allLessonsBySem.items():
for lessons in lstLessons: #lessons- lista de listas, cada lista tem lessons de uma cadeira de um semestre
subjectProfs= []
for lesson in lessons: #lessons de uma cadeira
while is_lesson_sobreposta(allTeachers[i], lesson, semestre) or isTooMuchLessonsOfSameSubj(allTeachers[i], lesson.subject):
i = (i+1) % allTeachers.count() #array circular
lesson.professor= allTeachers[i]
lesson.save()
subjectProfs.append(lesson.professor)
#todos os professores dessa cadeira
TuplosProfNumOrd = ordenarPorNumOcorrencias(subjectProfs) #sort: professor q da mais aulas dessa cadeira
subj= lesson.subject
tem= False
for prof,n in TuplosProfNumOrd:
if not Subject.objects.filter(regente=prof).first() : #se prof ainda nao for regente
subj.regente = prof
tem= True
break
if not tem :
subj.regente = TuplosProfNumOrd[0][0] #nota: assim um prof pode ser regente de mais uma cadeira!
subj.save()
def isTooMuchLessonsOfSameSubj(professor, subject):
count= Lesson.objects.filter(professor=professor, subject=subject).count()
if count > 5 :
return True
return False
def is_lesson_sobreposta(professor, lesson, semestre):
#verifica se a lesson fica ou nao sobreposta no horario do prof dependendo do semestre
if semestre != "1,2" :
lessonsWeekDay= getLessonsInSpecificWeekDayInSemOfTeacher(professor, int(semestre), lesson.week_day)
if lessonsWeekDay : #se ele ja tiver aulas nesse dia de semana
lastLessonWeekDay= lessonsWeekDay[-1]
return is_lesson1_and_lesson2_sobrepostas(lastLessonWeekDay, lesson)
else:
lastLessonWeekDay= Lesson.objects.filter(professor=professor, week_day=lesson.week_day).order_by("hour").last()
if lastLessonWeekDay :
return is_lesson1_and_lesson2_sobrepostas(lastLessonWeekDay, lesson)
return False
def is_lesson1_and_lesson2_sobrepostas(lesson1, lesson2):
return addMinutes(lesson1.hour, lesson1.duration) > hourToMinutes(lesson2.hour)
def getLessonsInSpecificWeekDayInSemOfTeacher(professor, semestre, week_day):
LessonsSem= []
suLessons = list(Lesson.objects.filter(professor=professor, week_day=week_day).order_by("hour"))
for lesson in suLessons:
subj= lesson.subject
CRsubjs= CourseSubject.objects.filter(subject=subj)
#se o sem da cadeira e igual independentemente do curso
if is_semestres_all_same(CRsubjs) :
sem= CRsubjs[0].semester
if sem == semestre:
LessonsSem.append(lesson)
else:
LessonsSem.append(lesson)
return LessonsSem
def is_semestres_all_same(courseSubjs):
return all(crS.semester == courseSubjs[0].semester for crS in courseSubjs)
def ordenarPorNumOcorrencias(lstObjs):
counts = collections.Counter(lstObjs)
tuploOrd= counts.most_common(len(counts))
return tuploOrd
def hourToMinutes(hour):
#ex: hour-> "9:00" ou "09:00"
lhour= hour.split(":")
return int(lhour[0])*60 + int(lhour[1])
def addMinutes(hour, duration):
return hourToMinutes(hour) + hourToMinutes(duration)
@transaction.atomic
def makeFaculdadeOBJs():
with open(settings.MIGRATIONS_DATA_ROOT + "/faculdadesData.txt", encoding="utf8") as rfile:
for line in rfile.readlines():
if "#" not in line and "," in line:
name, sigla, link= line.split(",")
newFaculdade= Faculdade(name=name, sigla=sigla, link=link)
newFaculdade.save()
def mainInsertData(apps, schema_editor):
#reset (para nao dar duplicado)
Role.objects.all().delete()
SchoolYear.objects.all().delete()
Room.objects.all().delete()
SystemUser.objects.all().delete()
PersonalInfo.objects.all().delete()
Course.objects.all().delete()
Subject.objects.all().delete()
CourseSubject.objects.all().delete()
SystemUserCourse.objects.all().delete()
Lesson.objects.all().delete()
SystemUserSubject.objects.all().delete()
LessonSystemUser.objects.all().delete()
Faculdade.objects.all().delete()
makeRoleOBJs()
makeSchoolYearOBJs(2016,2019)
makeRoomOBJs(200,42)
makeSystemUserOBJs()
makePersonalInfoOBJs()
makeCourseOBJs()
makeSubjectAndCourseSubjectOBJs()
makeSystemUserCourseOBJs() #falta
makeLessonOBJs()
makeSystemUserSubjectAndLessonSystemUserOBJs() #falta
makeFaculdadeOBJs()
class Migration(migrations.Migration):
dependencies = [
('university', '0002_insertDataUsers'),
]
operations = [
migrations.RunPython(mainInsertData)
]
| true |
1e8e0bfa1c2d3bf0d0eaa50f4662ea7c10e032c2 | Python | arvidbt/KattisSolutions | /python/arrangement.py | UTF-8 | 345 | 3.28125 | 3 | [] | no_license | rooms = int(input())
teams = int(input())
if rooms == 1:
print("*" * teams)
exit()
rest = teams % rooms
if rest == 0:
rooms += 1
big_rooms_boys = int((teams - rest)/2)
if rest == 0:
big_rooms_boys = int(big_rooms_boys / 2)
for i in range(rooms-1):
print("*" * int(big_rooms_boys))
print("*" * rest)
| true |
85dae62a9a2a6355276d94017c65e5145bdb7386 | Python | AlexDeimon/Udemy | /Python_sin_fronteras/archivos.py | UTF-8 | 531 | 3.484375 | 3 | [] | no_license | # c = open('chanchito.txt', 'w') #(nombre del archivo, permisos r(read), w(write), a(append), x(create))
# c.write('\nagregaremos una nueva línea a nuestro archivo')
# c.close()
# x = open('chanchito.txt')
# print(x.read()) lee todo el archivo
#print(x.readline()) lee una linea del archivo
import os #libreria para eliminar archivos
if os.path.exists('chanchito.txt'): #si el archivo existe
os.remove('chanchito.txt') #eliminar archivo
else:
print('El archivo no existe')
os.rmdir('micarpeta') #eliminar carpeta
| true |
dec154e893fb399e191ea73c8ba271917d8a4f32 | Python | Gafanhoto742/Python-3 | /Python (3)/Ex_finalizados/ex078.py | UTF-8 | 2,044 | 4.65625 | 5 | [
"MIT"
] | permissive |
'''Faça um programa que leia 5 valores numéricos e guarde-os em uma lista.
No final, mostre qual foi o maior e o menor valor digitado e as suas respectivas posições na lista. '''
''' como eu escrevi'''
maior = menor = 0
val = []
for cont in range (0,5): #5 ler valores para uma lista
val.append(int(input(f'\nDigite o um valor para posição {cont}:')))
if cont == 0 :
maior = menor = val[cont]
else:
if val[cont] > maior:
maior = val[cont]
if val[cont] < menor:
menor = val[cont]
print('-'*30)
print()
print(f'Você digitou os valores: {val}')
print()
for c, v in enumerate(val): #mostra valores que digitou e posição que estão
print(f'\nNa posição {c} encontrei o valor {v}')
print(f'\nO maior valor digitado foi {maior} na(s) posição: ',end='')
for c, v in enumerate(val):
if v == maior:
print(f'{c}...',end='')
print('\n')
print(f'\nO MENOR valor digitado foi {menor} na(s) posição: ',end='')
for c, v in enumerate(val):
if v == menor:
print(f'{c}...',end='')
print('\n')
print('-'*30)
print('\n\nCheguei ao final da lista digitada por você')
''' formato do professor Guanabara
maior = menor = 0
val = []
for cont in range (0,5): #5 ler valores para uma lista
val.append(int(input(f'\nDigite o um valor para posição {cont}:')))
if cont == 0 :
maior = menor = val[cont]
else:
if val[cont] > maior:
maior = val[cont]
if val[cont] < menor:
menor = val[cont]
print('-'*30)
print(f'\nVocê digitou os valores {val}')
print(f'\nO maior valor digitado foi {maior} na(s) posição: ',end='')
for c, v in enumerate(val):
if v == maior:
print(f'{v}...',end='')
print('\n')
print(f'\nO MENOR valor digitado foi {menor} na(s) posição: ',end='')
for c, v in enumerate(val):
if v == menor:
print(f'{v}...',end='')
print('\n')
print('-'*30)
print('\n\nCheguei ao final da lista digitada por você')
''' | true |
3cd83c46f5eee589744a328285454cd5a042545c | Python | CeciFerrari16/Compiti | /es28.py | UTF-8 | 1,282 | 4.15625 | 4 | [] | no_license | '''
I nomi delle città e i corrispondenti Codici di Avviamento Postale (CAP) vengono inseriti da tastiera
e memorizzati in un dizionario, dove il CAP è la chiave. Fornito poi da tastiera il nome di una città,
costruisci un programma che visualizzi il suo CAP oppure un messaggio nel caso la città non sia compresa
nell’ elenco. Analogamente, fornendo il CAP restituisce il nome della città oppure un messaggio di errore.
'''
d = {}
def trova_chiave(dicti, val):
trovate = []
for chiave in dicti:
if d[chiave] == val:
trovate.append(chiave)
return trovate
print("Inserisci STOP quando hai finito")
while True:
CAP = input("Qual è il CAP? ").upper()
citta = input("Qual è la città? ").upper()
if CAP == "STOP" or citta == "STOP":
break
else:
d[CAP] = citta
print(d)
citta = input("Dimmi una città e ti dirò il CAP: ").upper()
if citta in d.values():
print("Il CAP è", trova_chiave(d, citta))
else:
print("Il CAP che hai inserito non è presente")
CAP = input("Dimmi un CAP e ti dirò la città ").upper()
if CAP in d.keys():
for chiave in d.keys():
if CAP == chiave:
print("La città è", d[CAP])
else:
print("La città che hai inserito non è presente")
| true |
464baded20b55c8b287ada48a17eb81d83424a8b | Python | tihonich/otus-python-developer-2020 | /hw_week_1/log_analyzer/test_log_analyzer.py | UTF-8 | 6,677 | 2.765625 | 3 | [] | no_license | import datetime
import os
import unittest
from typing import NoReturn, Tuple, NamedTuple
from log_analyzer import LOG_FILE_PATTERN
from log_analyzer import find_latest_log, parse_log_file, calculate_url_stats
class Config(NamedTuple):
"""
Class with final config parameters such as:
- report_size: size of report
- report_dir: directory where report will be constructed
- log_dir: directory where to take logs from
"""
report_size: int
report_dir: str
log_dir: str
log_file: str
failures_percent_threshold: float
class LatestLogFile(NamedTuple):
"""
Class with latest log file parameters such as:
- path path to latest log file
- create_date creation date
- extension file extension
"""
path: str
date_of_creation: datetime.date
extension: str
class TestLatestLogFileFinder(unittest.TestCase):
"""
Class for testing finder of latest log files
"""
TEST_FOLDER_NAME = "./test_folder"
def setUp(self) -> NoReturn:
"""
Creates test folder
:return:
"""
os.mkdir(TestLatestLogFileFinder.TEST_FOLDER_NAME)
self.test_folder = TestLatestLogFileFinder.TEST_FOLDER_NAME
def tearDown(self) -> NoReturn:
"""
Deletes all files from test folder and folder itself
"""
for file in os.scandir(TestLatestLogFileFinder.TEST_FOLDER_NAME):
os.remove(os.path.join(TestLatestLogFileFinder.TEST_FOLDER_NAME, file.name))
os.rmdir(TestLatestLogFileFinder.TEST_FOLDER_NAME)
def _prepare_test_log_files(self, test_files_names: Tuple[str]) -> NoReturn:
"""
Creates files for testing finding latest log function
:param test_files_names: tuple of files to prepare
"""
test_log_files_path_names = tuple(map(
lambda file_name: os.path.join(self.test_folder, file_name),
test_files_names
))
for test_log_file_name in test_log_files_path_names:
with open(test_log_file_name, "w", encoding="utf-8"):
pass
def test_finding_latest_log_file(self):
"""
Tests finding latest log file (file with latest date in file name
"""
self._prepare_test_log_files(
("nginx-access-ui.log-20170830.gz",
"nginx-access-ui.log-20170701.gz",
"nginx-access-ui.log-19851117.gz",
"nginx-access-ui.log-20180630.gz",
"nginx-access-ui.log-20191104.gz")
)
latest_log_file = find_latest_log(
log_dir=self.test_folder,
log_file_pattern=LOG_FILE_PATTERN
)
right_file_name = os.path.join(self.test_folder, "nginx-access-ui.log-20191104.gz")
right_date = datetime.datetime(year=2019, month=11, day=4)
with self.subTest():
self.assertEqual(right_file_name, latest_log_file.path)
with self.subTest():
self.assertEqual(".gz", latest_log_file.extension)
with self.subTest():
self.assertEqual(right_date, latest_log_file.date_of_creation)
def test_ignoring_wrong_formats(self):
"""
Tests that all file formats except .gz, .txt, .log are ignored
while searching latest log file
"""
# File with right format has earliest date
self._prepare_test_log_files(
("nginx-access-ui.log-20160101.txt",
"nginx-access-ui.log-20190804.zip",
"nginx-access-ui.log-20190904.rtf",
"nginx-access-ui.log-20191004.csv",
"nginx-access-ui.log-20191104.bz2")
)
latest_log_file = find_latest_log(
log_dir=self.test_folder,
log_file_pattern=LOG_FILE_PATTERN
)
right_file_name = os.path.join(self.test_folder, "nginx-access-ui.log-20160101.txt")
right_date = datetime.datetime(year=2016, month=1, day=1)
with self.subTest():
self.assertEqual(right_file_name, latest_log_file.path)
with self.subTest():
self.assertEqual(".txt", latest_log_file.extension)
with self.subTest():
self.assertEqual(right_date, latest_log_file.date_of_creation)
def test_suitable_log_file_not_found(self):
"""
Tests if function returns nothing if suitable log file not found
"""
# No suitable log file
self._prepare_test_log_files(
("nginx-access-ui.log-20190804.zip",
"nginx-access-ui.log-20190904.rtf",
"nginx-access-ui.log-20191004.csv",
"nginx-access-ui.log-20191104.bz2")
)
latest_log_file = find_latest_log(
log_dir=self.test_folder,
log_file_pattern=LOG_FILE_PATTERN
)
self.assertIsNone(latest_log_file)
class TestUrlStatsCalculator(unittest.TestCase):
"""
Class for testing calculator of url stats
"""
TEST_CONFIG = Config(
report_size=50,
report_dir="./reports",
log_dir="./nginx_logs",
log_file="./script_logs/test.log",
failures_percent_threshold=50.0
)
LOG_FILE = LatestLogFile(
path="./nginx_logs/test_sample.txt",
date_of_creation=datetime.date(year=2019, month=11, day=5),
extension=".txt"
)
def test_url_stats_size(self):
"""
Tests if url stats size coincides with report size from config
:return:
"""
parsed_line_gen = parse_log_file(
log_file=TestUrlStatsCalculator.LOG_FILE,
log_file_opener=open
)
url_stats = calculate_url_stats(
parsed_line_gen=parsed_line_gen,
cfg=TestUrlStatsCalculator.TEST_CONFIG
)
with self.subTest():
self.assertEqual(TestUrlStatsCalculator.TEST_CONFIG.report_size, len(url_stats))
urls = set()
for single_url_stat in url_stats:
urls.add(single_url_stat["url"])
with self.subTest():
self.assertEqual(TestUrlStatsCalculator.TEST_CONFIG.report_size, len(urls))
with self.subTest():
for single_url_stat in url_stats:
self.assertIn("url", single_url_stat)
self.assertIn("count", single_url_stat)
self.assertIn("count_perc", single_url_stat)
self.assertIn("time_sum", single_url_stat)
self.assertIn("time_perc", single_url_stat)
self.assertIn("time_avg", single_url_stat)
self.assertIn("time_max", single_url_stat)
self.assertIn("time_med", single_url_stat)
| true |
bd4dfcac7eb0585005b374a35f32e1d46a97bf2d | Python | zhaohui8969/OSX_speak_bot | /speaker_input.py | UTF-8 | 1,469 | 3 | 3 | [] | no_license | #!/usr/bin/env python2
# coding: utf-8
from __future__ import print_function
import subprocess
import sys
import threading
import time
class speaker_and_typeer(object):
def __init__(self, delay, lock):
self.delay = delay
self.lock = lock
def dynamic_char_output(self, msg, delay):
for _char in msg:
print(_char, end='')
sys.stdout.flush()
time.sleep(delay)
def osx_say(self, msg):
subprocess.call(["say", msg])
def speak_and_type(self, msg, delay=None):
if not delay:
delay = self.delay
self.lock.acquire()
t = threading.Thread(target=self.dynamic_char_output, kwargs={'msg': msg, 'delay': delay})
t.start()
self.osx_say(msg)
t.join()
self.lock.release()
def spliter(_string):
split_char = u',.!\n,。!;、'
last_postion = 0
index = 0
_string = unicode(_string, 'utf-8')
for char in _string[last_postion:]:
index += 1
if char in split_char:
yield _string[last_postion:index]
last_postion = index
if __name__ == '__main__':
lock = threading.Lock()
lock.acquire()
ss = speaker_and_typeer(0.05, lock)
fop = sys.stdin
line_str = fop.readline()
while line_str:
for i in spliter(line_str):
lock.release()
ss.speak_and_type(i)
lock.acquire()
line_str = fop.readline()
| true |
304007156b82675872fb846871d10862884e2e50 | Python | nehalrawat/AI-Nutrition-Project | /nutrition_facts.py | UTF-8 | 1,221 | 3.265625 | 3 | [] | no_license | # based on a 2000 calorie diet
# suggested diet = 40 % carbs, 40% protein, 20% fat ,1500 mg of sodium (American Heart Association), 300 mg cholesterol
class Food:
food_facts = {}
def __init__(self, name, calories, fat, cholesterol, sodium, carbohydrates, protein):
self.name = name
self.calories = calories
self.fat = fat
self.cholesterol = cholesterol
self.sodium = sodium
self.carbohydrates = carbohydrates
self.protein = protein
self.food_facts[name] = [self.calories, self.fat, self.cholesterol, self.sodium, self.carbohydrates, self.protein]
def main():
waffles = Food('waffles', 218, 11, 52, 383, 25, 5.9)
sushi = Food('sushi', 349, 19, 17, 537, 38, 7.8)
pizza = Food('pizza', 285, 10, 18, 640, 36, 12)
pho = Food('pho', 638, 14, 86, 3268, 78, 47)
club_sandwich = Food('club_sandwich', 817, 46, 203, 1867, 42, 56)
french_fries= Food('french_fries', 365, 17, 0, 246, 48, 4)
chicken_wings = Food('chicken_wings', 216, 14, 120, 83, 0, 20)
caesar_salad = Food('caesar_salad', 481, 40, 36, 1152, 23, 10)
suggested_diet = Food('suggested', 2000, 400, 300, 1500, 800,800 )
if __name__ == '__main__':
main()
| true |
f6fb793208bc98dcdf60191530e4192ceae06f8a | Python | Aasthaengg/IBMdataset | /Python_codes/p03797/s389824102.py | UTF-8 | 277 | 2.765625 | 3 | [] | no_license | import sys
input = sys.stdin.readline
def main():
N, M = [int(x) for x in input().split()]
if M < N * 2:
print(M // 2)
else:
ans = N
M = M - N * 2
ans += M // 4
print(ans)
if __name__ == '__main__':
main()
| true |
2abff1c15da55329c9e4d2ff35e8e0644375fbfb | Python | abadrinath15/python-leetcode | /problem_118/test_problem_118.py | UTF-8 | 447 | 2.75 | 3 | [] | no_license | import pytest
from problem_118 import Solution
class TestCase:
def test_1(self, get_sln):
assert get_sln.generate(0) == []
def test_2(self, get_sln):
assert get_sln.generate(1) == [[1]]
def test_3(self, get_sln):
assert get_sln.generate(2) == [[1], [1, 1]]
def test_4(self, get_sln):
assert get_sln.generate(3) == [[1], [1, 1], [1, 2, 1]]
@pytest.fixture
def get_sln():
return Solution()
| true |
37d859787f3f3a159b1722a52595b9f27141575f | Python | sriramsv/Mark2 | /utils/state.py | UTF-8 | 877 | 3.4375 | 3 | [] | no_license | import ping
def device_is_present(host, tries=3, timeout=3):
"""
Determines whether a device is present on the network
using its IP address or hostname. If the device can be
pinged successfully, it will return True, and False
otherwise.
Winston needs to run as root to use this function, since
ICMP pings need root to run. That is even true for the
ping command, so there is no way to circumvent this.
See this post for details:
http://stackoverflow.com/questions/1189389/python-non-privileged-icmp
:param host: hostname or IP address
:param tries: number of tries before giving up
:param timeout: timeout in seconds
"""
try:
response = ping.quiet_ping(host, tries, timeout)
# Returns true if more than 0% of packets were returned
return (response[0] > 0)
except:
return False | true |
3cd4f9b5c5f0d9e0b95ddd86a4b36efa849b4152 | Python | xin1314/learngit | /rabbitmq/fanou_send.py | UTF-8 | 685 | 2.78125 | 3 | [] | no_license | import pika
# fanout 广播模式,错过消息就接收不到了,通过exchange绑定
credentials = pika.PlainCredentials('xin', 'xin5655')
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost',
credentials=credentials))
channel = connection.channel() # 建立了rabbit协议的通道
# 声明exchange
channel.exchange_declare(exchange='logs', exchange_type='fanout')
channel.basic_publish(exchange='logs',
routing_key='',
body='Hello World',
) # properties用于消息持久化,确保重启后队列中的数据存在
print("[x] Send 'Hello World!'")
connection.close() | true |
ea7dfbeb32a7499452097cf1fba94b982be92ba2 | Python | uestcljx/pythonBeginner | /digit.py | UTF-8 | 936 | 4.4375 | 4 | [] | no_license | ###Digits output###
###INSTRUCTION:
###本题要求编写程序,分解任意正整数
### 输入格式:
###一个正整数n
###输出格式:
###按照以下格式输出:
###n = 个位数字 + 十位数字*10 + 百位数字*100 +...
###(注意字符之间有空格)
import pdb
def digit(n):
'''
Function to break up an integer
Examples:
>>> digit('152')
152 = 2 + 5*10 + 1*100
>>> digit('1698')
1698 = 8 + 9*10 + 6*100 + 1*1000
'''
# Initialize some useful value
weight = 1
result = ''
for d in n[::-1]: #倒序
temp = f'+ {d}*{str(weight)} ' if weight > 1 else f'{d} '
result = result + temp
weight *=10
result = result.rstrip() #去掉末尾空格
print(f"{n} = {result}")
if __name__ == '__main__':
import doctest
doctest.testmod()
print("Test has passed.\n")
digit(input('Your integer:\n> '))
| true |
08e6fa74a792ffe467c8d5bf3671973499bd48e3 | Python | ashleyrback/utils_cm | /error_utils.py | UTF-8 | 1,959 | 3.671875 | 4 | [] | no_license | #!/usr/bin/env python
#
# error_utils.py
#
# Collection of methods for common error handling constructions
#
# Author A R Back
#
# 18/07/2014 <ab571@sussex.ac.uk> : First revision
# 28/08/2014 <ab571@sussex.ac.uk> : Moved to utils_cm repo
###########################################################################
import sys
def check_exists_in_dict(dict_name, dict, key, location_text):
""" Check the contents of a dict to see if it contains the key supplied
:param dict_name: name of dictionary
:type dict_name: str
:param dict: dict to search
:type dict: dict
:param key: key to search for in dict
:type key: str
:param location_text: text to include in error message to identify location
:type location_text: str
"""
try:
assert (dict.get(key) != None),\
key + " was not found in dictionary " + dict_name
except AssertionError as detail:
print location_text + ": error - ", detail
raise
def almost_equal(value1, value2, precision):
""" Checks that two values are equal to a given precision.
:param value1: first value to check
:type value1: float
:param value2: second value to check
:type value2: float
:param precision: precision to which the two values should be equal.
Specify the last significant figure that should be
equal, e.g. to two decimal places --> 1.0e-2, to the
nearest thousand --> 1.0e3 etc.
:type precision: float
"""
# Convert value 1
value1_rounded = int((value1/precision)+0.5) * precision
value2_rounded = int((value2/precision)+0.5) * precision
precision_rounded = int((precision/precision)+0.5) * precision
assert (value1_rounded == value2_rounded),\
"error_utils.almost_equal: error - supplied values are not equal to a "\
"precision of " + str(precision) + "\n --> " + str(value1_rounded) + \
" != " + str(value2_rounded)
| true |
8b5e5d6815ec9fd40fdc71ce3c4faca4fbcaedc4 | Python | kyungsubbb/Coding-Test | /Programmers/Python/위장.py | UTF-8 | 338 | 3.03125 | 3 | [] | no_license | def solution(clothes):
answer =1
dic = dict()
for i in range(len(clothes)):
if clothes[i][1] not in dic :
dic[clothes[i][1]] = [clothes[i][0]]
else :
dic[clothes[i][1]].append(clothes[i][0])
for k in dic:
answer *= len(dic[k])+1
answer -= 1
return answer | true |
1f60c96524c526419ce6214fa220588877dc085e | Python | Elgava/python-crash-course | /chap06/pg_156 chap6(6-1 to 6-3).py | UTF-8 | 944 | 3.96875 | 4 | [] | no_license | #6-1 person
person = {
'first name' : 'elgin',
'last name' : 'malouw',
'age' : '19',
'city' : 'johanesburg',
}
for key, value in person.items():
print(f'\n{key}: {value}')
for things in person.keys():
print(f'{things.title()}\n')
for names in person.values():
print(names.title())
for names in sorted(person.keys()):
print(f'\n{names.title()} thank you for entering your information')
for user in set(person.values()):
print(f'\n{user.title()}')
#6-2 favourite numbers
fave_numbers ={
'elgin': '17',
'muha': '27',
'ross': '37',
'keoo': '47',
}
for name, num in fave_numbers.items():
print(f"\n{name.title()}'s favorite number are:")
for number in num:
print(f"\t{number.title()}")
#6-3 glossary
glossary = {
'dictionary' : 'used to store a key and a value',
'if statement' : 'used for diferent outcomes',
'lists':'used to store more than one value',
}
for key, value in glossary.items():
print(f'\n{key}: {value}') | true |
03de42c9c639df8ca44f0c7427aa5a6b09de23b8 | Python | SonaliSihra/Guess_a_number | /Main.py | UTF-8 | 537 | 4.125 | 4 | [] | no_license | import random
x = random.randrange(1, 10)
print(x)
print("Let the game begin!! \n guess the number:")
try:
input1 = int(input("Hint=[it is between 0 to 10]: "))
except ValueError:
print("Please enter integer only!!")
exit(0)
if input1 == x:
print("Congratulations!!! this is a correct answer.")
elif input1 > (x/2):
print("You need to lower down the number to reach your goal!")
elif input1 < (x/2):
print("you need to rise above your guess!!")
else:
print("Wrong answer!!! Try again with a new number!") | true |
8bd6f7c9dcbc9512704310bd10dc04554de276ee | Python | PIUphil/project_euler | /001~025/problem17.py | UTF-8 | 1,332 | 3.96875 | 4 | [] | no_license | '''
1부터 5까지의 수를 영어로 쓰면 one, two, three, four, five 이고,
각 단어의 길이를 더하면 3 + 3 + 5 + 4 + 4 = 19 이므로 사용된 글자는 모두 19개입니다.
1부터 1,000까지 영어로 썼을 때는 모두 몇 개의 글자를 사용해야 할까요?
참고: 빈 칸이나 하이픈('-')은 셈에서 제외하며, 단어 사이의 and 는 셈에 넣습니다.
예를 들어 342를 영어로 쓰면 three hundred and forty-two 가 되어서 23 글자,
115 = one hundred and fifteen 의 경우에는 20 글자가 됩니다.
'''
numnum = {
1:3, 2:3, 3:5, 4:4,
5:4, 6:3, 7:5, 8:5, 9:4,
10:3, 11:6, 12:6, 13:8, 14:8,
15:7, 16:7, 17:9, 18:8, 19:8,
20:6, 30:6, 40:5, 50:5, 60:5, 70:7, 80:6, 90:6}
hdrd = len(list("hundred"))
andd = len(list("and"))
for i in range(2,10):
for j in range(1, 10):
numnum[i*10+j] = numnum[i*10]+numnum[j]
li = []
for i in range(1,100):
li.append(numnum[i])
for i in range(100,1001):
num0 = int(str(i)[:-2])
num1 = int(str(i)[-2:])
if i%1000==0:
li.append(len(list("onethousand")))
#numnum[i] = len(list("onethousand"))
elif i%100==0:
li.append(numnum[num0]+hdrd)
#numnum[i] = numnum[num0]+hdrd
else:
li.append(numnum[num0]+numnum[num1]+hdrd+andd)
#numnum[i] = numnum[num0]+numnum[num1]+hdrd+andd
#print(numnum[1000])
print(sum(li))
| true |
834d1609dec01613b7df77e1f53bd591d677bcab | Python | peterpaiter/pastepwn | /util/threadingutils.py | UTF-8 | 718 | 2.8125 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
from threading import Thread, current_thread
import logging
def start_thread(target, name, exception_event, *args, **kwargs):
thread = Thread(target=thread_wrapper, name=name, args=(target, exception_event) + args, kwargs=kwargs)
thread.start()
def thread_wrapper(target, exception_event, *args, **kwargs):
thread_name = current_thread().name
logger = logging.getLogger(__name__)
logger.debug('{0} - thread started'.format(thread_name))
try:
target(*args, **kwargs)
except Exception:
exception_event.set()
logger.exception('unhandled exception in %s', thread_name)
raise
logger.debug('{0} - thread ended'.format(thread_name))
| true |
d85e357eda2fe4a0e1f68a8c8ba402af6deb237f | Python | transcranial/filopod | /resprocess/parser_generic.py | UTF-8 | 2,189 | 2.75 | 3 | [] | no_license | # Parser
# Generic
import re
'''
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Gets metadata information
Returns metadata, which is a list of the following:
0 identifier
1 type
2 language
3 title
4 date
5 publisher
6 author
7 journal
8 volume
9 issue
10 firstpage
11 lastpage
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'''
def get_metadata(url, soup):
meta_tags = soup.find_all('meta')
metadata = ['']*12
for meta_tag in meta_tags:
try:
if 'identifier' in meta_tag['name'].lower():
metadata[0] = meta_tag['content'].encode('utf-8','ignore')
break
except: pass
metadata[3] = soup.title.string.encode('utf-8','ignore')
for meta_tag in meta_tags:
try:
if 'date' in meta_tag['name'].lower():
metadata[4] = meta_tag['content'].encode('utf-8','ignore')
break
except: pass
for meta_tag in meta_tags:
try:
if 'author' in meta_tag['name'].lower():
metadata[6] = meta_tag['content'].encode('utf-8','ignore')
break
except: pass
return metadata
'''
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Returns figures as a list of tuples
Tuple contains:
- figure name
- figure caption
- figure small pic URL
- figure medium pic URL (may return 404)
- figure large pic URL (may return 404)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'''
def get_figures(url, soup):
return []
'''
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Returns content paragraphs
(Discards figure and tables with captions; these are produced by
separate functions)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'''
def get_paragraphs(url, soup):
paragraph_list = []
paragraphs = soup.find_all('p')
for paragraph in paragraphs:
paragraph = paragraph.text.encode('utf-8','ignore')
paragraph = re.compile('([\t\n]+)|(\s\s)+').sub(' ', paragraph)
paragraph = re.compile('(\s\s)+').sub(' ', paragraph)
paragraph = re.compile('(\s\s)+').sub(' ', paragraph)
paragraph_list.append(paragraph)
return paragraph_list | true |
e4a01b754e2e36cc412f43479817c4e7ba0deb0d | Python | n18015/programming-term2 | /src/algo-s2/task20180717_1.py | UTF-8 | 178 | 3 | 3 | [] | no_license | x = 0
x += +1
print("現在位置はx={0}です。".format(x))
x += +1
print("現在位置はx={0}です。".format(x))
x += +1
print("現在位置はx={0}です。".format(x))
| true |
80e5e77476d9747018ecdc991a94a41966f62d01 | Python | acabhishek942/ProjectEuler | /Solutions/pe#36brute-force.py | UTF-8 | 394 | 3.28125 | 3 | [] | no_license | from time import time
t1 = time()
def isPalindrome(number):
if str(number)[::-1] == str(number):
return True
return False
def toBinary(n):
return ''.join(str(1 & int(n) >> i) for i in range(64)[::-1])
total = 0
for i in range(1000000):
binaryRe = '{0:b}'.format(i)
if isPalindrome(i) and isPalindrome(binaryRe):
total += i
print (total)
print(time() - t1)
| true |
2cd06598651d07ac06668e83eaf8a1cdf49c0c0f | Python | francosebastian/python | /variables/variables.py | UTF-8 | 49 | 2.765625 | 3 | [] | no_license | name = "Fazt"
print(name)
name = None
print(name) | true |
d9a8151fef28fd32366745dcd03de819074bbb7d | Python | ShotaHamano/WannaGo | /script/python/01.py | UTF-8 | 307 | 2.6875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
'''
MySQLデータベースを作成する
'''
import sys
import MySQLdb
db_name = sys.argv[1]
db = MySQLdb.connect(host="localhost", user="root", passwd="root")
cursor = db.cursor()
command = 'CREATE DATABASE IF NOT EXISTS %s' % db_name
cursor.execute(command)
cursor.close() | true |
bb863e15e8f9f2ce558bedf8c187cd764589eef0 | Python | whitneygriffith/Introduction-to-Com-Sci-Labs | /find_missing_number.py | UTF-8 | 1,619 | 4.65625 | 5 | [] | no_license | '''
Problem 2: Find missing number
Create a file named find_missing_number.py. In it, write a function named FindMissingNumber that finds the missing number in a list of numbers ranging from A to B. For example, the missing number in the list [45, 51, 47, 46, 50, 49] is 48. FindMissingNumber should take a single parameter, a list of numbers, and it should return a single number.
Below are examples of what should be returned for different calls to FindMissingNumber:
FindMissingNumber([-6, -11, -8, -9, -10]) -> -7
FindMissingNumber([45, 47]) -> 46
Some notes:
You are not allowed to use any Python sort functions.
You are not allowed to import any modules.
The input list will contain all the numbers within an arbitrary range except for one. The input will never be something like: [7, 4, 6, 5], and it will always have at least 2 numbers.
You can assume that the input list only contains whole numbers.
'''
def FindMissingNumber(lists):
#creating dictionary to hold pairs
dict1 = {}
#missing number
missing = -0
#range for missing number
range1 = 0
for i in lists:
var = i
for i in lists:
if var - i == 1 or var - i == -1:
dict1[var] = i
for i in lists:
if i not in dict1:
range1 = i
for i in lists:
if i - range1 == 2 or i - range1 == -2:
range2 = i
missing = range1 + 1
if missing > range1 and missing < range1:
missing = missing
elif missing < range1 and missing > range2:
missing = missing
else:
missing = range1 - 1
print(missing)
FindMissingNumber([45, 47])
FindMissingNumber([-6, -11, -8, -9, -10])
| true |
22bb60f5fcccedd09ea0b217c4300042433a018f | Python | HidoiOokami/Projects-Python | /Lacos/Desafio.py | UTF-8 | 308 | 3.671875 | 4 | [] | no_license | # -*- coding: utf-8 -*-
from random import randint
def given_away():
return randint(1, 6) # o 6 entra
for i in range(1, 7):
if i % 2 == 1:
continue
if i == given_away():
print(f"Acertou!!! seu n° = {i}")
break
else:
print(f"Opss não foi desta vez! seu n° = {i}") | true |
1c449bbbe7a42425c7697fb0d18146cd26497bf0 | Python | Ali-Sahili/Generative_Architectures | /Image_Alignement/FeatureBased.py | UTF-8 | 4,519 | 2.765625 | 3 | [] | no_license | import cv2
import numpy as np
from skimage.transform import AffineTransform
from skimage.measure import ransac
# (ORB,SIFT or SURF) feature based alignment
def featureAlign(im1, im2, detector = 'SIFT', max_features = 5000, feature_retention = 0.15, MIN_MATCH_COUNT = 10):
# Convert images to grayscale
im1Gray = cv2.cvtColor(im1,cv2.COLOR_BGR2GRAY)
im2Gray = cv2.cvtColor(im2,cv2.COLOR_BGR2GRAY)
if detector == 'ORB':
# Detect ORB features and compute descriptors.
orb = cv2.ORB_create(max_features)
keypoints1, descriptors1 = orb.detectAndCompute(im1Gray, None)
keypoints2, descriptors2 = orb.detectAndCompute(im2Gray, None)
# Match features.
matcher = cv2.DescriptorMatcher_create(cv2.DESCRIPTOR_MATCHER_BRUTEFORCE_HAMMING)
matches = matcher.match(descriptors1, descriptors2, None)
# Sort matches by score
matches.sort(key=lambda x: x.distance, reverse=False)
# Remove not so good matches
numGoodMatches = int(len(matches) * feature_retention)
matches = matches[:numGoodMatches]
# Extract location of good matches
points1 = np.zeros((len(matches), 2), dtype=np.float32)
points2 = np.zeros((len(matches), 2), dtype=np.float32)
for i, match in enumerate(matches):
points1[i, :] = keypoints1[match.queryIdx].pt
points2[i, :] = keypoints2[match.trainIdx].pt
else:
if detector == 'SIFT':
# Detect SIFT features and compute descriptors.
sift = cv2.xfeatures2d.SIFT_create()
keypoints1, descriptors1 = sift.detectAndCompute(im1Gray, None)
keypoints2, descriptors2 = sift.detectAndCompute(im2Gray, None)
elif detector == 'SURF':
# Detect SIFT features and compute descriptors.
surf = cv2.xfeatures2d.SURF_create()
keypoints1, descriptors1 = surf.detectAndCompute(im1Gray, None)
keypoints2, descriptors2 = surf.detectAndCompute(im2Gray, None)
FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
search_params = dict(checks = 50)
flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(descriptors1,descriptors2,k=2)
# store all the good matches as per Lowe's ratio test.
good = []
for m,n in matches:
if m.distance < 0.7*n.distance:
good.append(m)
if len(good)>MIN_MATCH_COUNT:
points1 = np.float32([ keypoints1[m.queryIdx].pt for m in good ]).reshape(-1,2)
points2 = np.float32([ keypoints2[m.trainIdx].pt for m in good ]).reshape(-1,2)
return points1, points2
""" First approach """
def homography_based(im1, im2, detector = 'SIFT', max_features = 5000, feature_retention = 0.15, MIN_MATCH_COUNT = 10):
points1, points2 = featureAlign(im1, im2, detector, max_features, feature_retention, MIN_MATCH_COUNT)
# Find homography
homography_matrix, mask = cv2.findHomography(points1, points2, cv2.RANSAC)
# Use homography
height, width, channels = im2.shape
im1Reg = cv2.warpPerspective(im1, homography_matrix, (width, height))
return im1Reg, homography_matrix
""" Second approach """
def AffineTransform_based(im1, im2, detector = 'SIFT', max_features = 5000, feature_retention = 0.15, MIN_MATCH_COUNT = 10):
points1, points2 = featureAlign(im1, im2, detector, max_features, feature_retention, MIN_MATCH_COUNT)
# estimate affine transform model using all coordinates
model = AffineTransform()
model.estimate(points1, points2)
return model
""" Third approach """
def Ransac_based(im1, im2, detector = 'SIFT', max_features = 5000, feature_retention = 0.15, MIN_MATCH_COUNT = 10):
points1, points2 = featureAlign(im1, im2, detector, max_features, feature_retention, MIN_MATCH_COUNT)
# robustly estimate affine transform model with RANSAC
model_robust, inliers = ransac((points1, points2), AffineTransform, min_samples=3,
residual_threshold=2, max_trials=100)
outliers = inliers == False
return model_robust
# Print the parameters of the transformation model
def Print_Result(model):
print("Scale: ", model.scale[0], model.scale[1])
print("Translation: ", model.translation[0], model.translation[1])
print("Rotation: ", model.rotation)
print()
| true |
f4228db54bcca8cea807cf8054823deb1bb354e0 | Python | engsopha/PythonProgram | /HelloWorld/Test_code/List.py | UTF-8 | 220 | 3.03125 | 3 | [] | no_license | pow2 = [2 ** x for x in range(1, 11) if x < 4]
print(pow2)
lang = [x+y for x in ['Python ','C '] for y in ['Language','Programming']]
# ['Python Language', 'Python Programming', 'C Language', 'C Programming']
print(lang) | true |
180732b06b3b722f7128ab6548ee005d866e5915 | Python | Lakshadeep/osm_navigation | /osm_topological_planner/src/osm_topological_planner/compute_orientation.py | UTF-8 | 4,380 | 2.859375 | 3 | [] | no_license | import math
from geometry_msgs.msg import Pose, Point, Quaternion
from tf.transformations import euler_from_quaternion, quaternion_from_euler
from osm_planner_msgs.msg import *
class ComputeOrientation(object):
def __init__(self):
pass
# computes door orientation based on next area
def get_door_orientation(self, door, next_area):
door_points = self._get_door_points(door.geometry.points)
door_center = self._compute_center(door.geometry.points)
next_area_center = self._compute_center(next_area.geometry.points)
door_angle = math.atan2(
door_points[1].y - door_points[0].y, door_points[1].x - door_points[0].x)
door_angle1 = self._wrap_to_pi(door_angle + math.pi / 2)
door_angle2 = self._wrap_to_pi(door_angle - math.pi / 2)
door_area_angle = math.atan2(
(next_area_center.y - door_center.y), (next_area_center.x - door_center.x))
if(math.fabs(self._wrap_to_pi(door_area_angle - door_angle1)) < math.fabs(self._wrap_to_pi(door_area_angle - door_angle2))):
return door_angle1
else:
return door_angle2
def _wrap_to_pi(self, angle):
angle = (angle + math.pi) % (2 * math.pi) - math.pi
return angle
def _get_door_points(self, door_geometry_points):
sides = []
for i, pt in enumerate(door_geometry_points):
if i is not 0:
pt1 = door_geometry_points[i - 1]
pt2 = door_geometry_points[i]
sides.append([pt1, pt2, self._compute_distance(pt1, pt2)])
list.sort(sides, key=lambda l: l[2], reverse=True)
pt1 = Point(x=(sides[0][0].x + sides[1][1].x) / 2.0,
y=(sides[0][0].y + sides[0][0].y) / 2.0)
pt2 = Point(x=(sides[1][0].x + sides[0][1].x) / 2.0,
y=(sides[1][0].y + sides[0][1].y) / 2.0)
return [pt1, pt2]
# computes junction orientation based on next area
def get_junction_orientation(self, junction, next_area):
junction_center = self._compute_center(junction.geometry.points)
next_area_center = self._compute_center(next_area.geometry.points)
angle = self._wrap_to_pi(math.atan2(
(next_area_center.y - junction_center.y), (next_area_center.x - junction_center.x)))
return angle
# computes corridor orientation based on previous and next area
# if previous area is not available then prev_area should equal to either
# 0.0 or desired offset
def get_corridor_orientation(self, prev_area, curr_area, next_area):
exit_pts = self._get_nearest_points(next_area, curr_area)
exit_pt = self._compute_center(exit_pts)
if (isinstance(prev_area, float)):
curr_area_center = self._compute_center(curr_area.geometry.points)
angle = math.atan2(exit_pt.y - curr_area_center.y,
exit_pt.x - curr_area_center.x)
else:
entry_pts = self._get_nearest_points(prev_area, curr_area)
entry_pt = self._compute_center(entry_pts)
angle = math.atan2((exit_pt.y - entry_pt.y),
(exit_pt.x - entry_pt.x))
return angle
# gets points of current area which are closest to specified area
def _get_nearest_points(self, other_area, current_area):
other_area_mid_point = self._compute_center(other_area.geometry.points)
distances = []
current_area_points = current_area.geometry.points
for i, pt in enumerate(current_area_points):
if i is not len(current_area_points) - 1:
pt = current_area_points[i]
distances.append(
[i, self._compute_distance(pt, other_area_mid_point)])
list.sort(distances, key=lambda l: l[1], reverse=False)
return [current_area_points[distances[0][0]], current_area_points[distances[1][0]]]
def _compute_distance(self, pt1, pt2):
return math.sqrt(math.pow(pt1.x - pt2.x, 2) + math.pow(pt1.y - pt2.y, 2))
def _compute_center(self, area_geometry_pts):
x_sum = 0
y_sum = 0
no_of_pts = 0
for pt in area_geometry_pts:
x_sum = x_sum + pt.x
y_sum = y_sum + pt.y
no_of_pts = no_of_pts + 1
return Point(x=x_sum / no_of_pts, y=y_sum / no_of_pts)
| true |
64cbeae4a5074f6a1cb216cf29f8a7f65738f823 | Python | sgrsigma/euler | /problem013.py | UTF-8 | 279 | 3.421875 | 3 | [] | no_license | rangedigits = []
with open('100x50digits.txt') as f:
while True:
c = f.readline()
if not c:
print "End of file"
break
else:
d1 = int(c[:12])
rangedigits.append(d1)
#print firstdigits
total = 0
for n in rangedigits:
total = n + total
print str(total)[:10] | true |
8b6dde32dcafaff3385804c69a15029f94ffe0f9 | Python | gmr/rabbitstew | /rabbitstew.py | UTF-8 | 9,508 | 2.625 | 3 | [] | permissive | """
Rabbit Stew
===========
A CLI application for piping delimited input to RabbitMQ as messages.
Example Use
-----------
.. code:: bash
cat /var/log/messages | rabbitstew -H rabbit-server -r syslog.messages
"""
import argparse
import getpass
import sys
import time
try:
import urllib.parse as urllib
except ImportError:
import urllib
import rabbitpy
from rabbitpy import exceptions
__version__ = '0.1.0'
DESC = "RabbitMQ message publisher"
DEFAULT_HOST = 'localhost'
DEFAULT_PORT = 5672
DEFAULT_VHOST = '/'
DEFAULT_USER = 'guest'
DEFAULT_PASSWORD = 'guest'
class RabbitStew(object):
"""Main Processing Class"""
def __init__(self):
"""Create a new instance of RabbitStew"""
self.channel = None
self.connection = None
self.counter = 0
self.properties = {}
self.parser = self.build_argparser()
self.args = self.parser.parse_args()
self.password = self.get_password()
def build_argparser(self):
"""Build the argument parser, adding the arguments, and return it.
:rtype: argparse.ArgumentParser
"""
formatter = argparse.ArgumentDefaultsHelpFormatter
parser = argparse.ArgumentParser(prog='rabbitstew',
description=DESC,
formatter_class=formatter)
parser.add_argument('-H',
dest='host',
help='Server hostname',
default=DEFAULT_HOST)
parser.add_argument('-p',
dest='port',
type=int,
help='Server port',
default=DEFAULT_PORT)
parser.add_argument('-s',
dest='ssl',
action='store_true',
help='Use SSL to connect')
parser.add_argument('-v',
dest='vhost',
help='Server virtual host',
default=DEFAULT_VHOST)
parser.add_argument('-u',
dest='user',
help='Server username',
default=DEFAULT_USER)
parser.add_argument('-P',
dest='password',
help='Server password',
default=DEFAULT_PASSWORD)
parser.add_argument('-W',
dest='prompt',
action='store_true',
help='Prompt for password')
parser.add_argument('-f',
dest='password_file',
metavar='PATH',
help='Read password from a file')
parser.add_argument('-e',
dest='exchange',
help='Exchange to publish to')
parser.add_argument('-r',
dest='routing_key',
help='Routing Key to use')
parser.add_argument('-c',
dest='confirm',
action='store_true',
help='Confirm delivery of each message, exiting if'
' a message delivery could not be confirmed')
parser.add_argument('--add-user',
action='store_true',
help='Include the user in the message properties')
parser.add_argument('--app-id',
help='Specify the app-id property of the message',
default='rabbitstew')
parser.add_argument('--auto-id',
action='store_true',
help='Create a unique message ID for each message')
parser.add_argument('--content-type',
metavar='VALUE',
help='Specify the content type of the message')
parser.add_argument('--type',
help='Specify the message type')
parser.add_argument('-V',
dest='verbose',
help='Verbose output',
action='store_true')
parser.add_argument('--version',
action='version',
version='%(prog)s ' + __version__)
return parser
def close(self):
"""Close the RabbitMQ connection"""
self.connection.close()
self.log('Closed RabbitMQ connection')
def connect(self):
"""Connect to RabbitMQ and create the channel. Optionally, enable
publisher confirmations based upon cli arguments.
"""
self.log('Connecting to RabbitMQ')
try:
self.connection = rabbitpy.Connection(self.url)
except (exceptions.ConnectionException,
exceptions.AMQPAccessRefused) as err:
self.error('Connection error: {0}'.format(str(err)))
self.channel = self.connection.channel()
if self.args.confirm:
self.channel.enable_publisher_confirms()
self.log('Publisher confirmation enabled')
self.log('Connected')
def default_properties(self):
"""Build the default properties dictionary based upon the CLI options
:rtype: dict
"""
properties = {'app_id': self.args.app_id}
if self.args.content_type:
properties['content_type'] = self.args.content_type
if self.args.type:
properties['message_type'] = self.args.type
if self.args.add_user:
properties['user_id'] = self.args.user
return properties
@staticmethod
def error(message, *args):
"""Log the message to stderr and exit the app
:param str message: The message to log
:param list args: CLI args for the message
"""
sys.stderr.write(message % args + '\n')
sys.exit(1)
def get_password(self):
"""Get the password from either a prompt for the user, a password file,
or the arguments passed in.
:rtype: str
"""
if self.args.prompt:
return getpass.getpass('RabbitMQ password: ')
if self.args.password_file:
return open(self.args.password_file, 'r').read().strip()
return self.args.password
def get_properties(self):
"""Reuse self.properties but set the timestamp to the current value
and remove the message_id if set
:param
"""
self.properties['timestamp'] = int(time.time())
if 'message_id' in self.properties:
del self.properties['message_id']
return self.properties
def log(self, message, *args):
"""Log the message to stdout
:param str message: The message to log
:param list args: CLI args for the message
"""
if self.args.verbose:
sys.stdout.write(message % args + '\n')
def publish(self, line):
"""Publish the line to RabbitMQ
:param str line:
"""
msg = rabbitpy.Message(self.channel,
line.rstrip('\r\n'),
self.get_properties(),
opinionated=self.args.auto_id)
if self.args.confirm:
try:
if not msg.publish(self.args.exchange, self.args.routing_key):
self.error('Could not confirm delivery of last message')
except exceptions.AMQPNotFound as error:
self.error('Error publishing message: %s', error.message)
else:
msg.publish(self.args.exchange, self.args.routing_key)
self.counter += 1
self.log('Message #{0} published'.format(self.counter))
def run(self):
"""Main routine to run, reads in from stdin and publishes out after
connecting and ensuring the exchange and routing key are set properly.
"""
self.connect()
# Is better to show argparser default as None and replace with ''
if not self.args.exchange:
self.args.exchange = ''
if not self.args.routing_key:
self.args.routing_key = ''
# Dict that will get copied for each message
self.properties = self.default_properties()
# Iterate through stdin and publish the message
for line in sys.stdin:
self.publish(line)
self.close()
self.log('Published {0} messages'.format(self.counter))
@property
def url(self):
"""Return the AMQP URI from the parameters
:return str: The PostgreSQL connection URI
"""
scheme = 'amqps' if self.args.ssl else 'amqp'
virtual_host = urllib.quote(self.args.vhost, '')
return '{0}://{1}:{2}@{3}:{4}/{5}'.format(scheme,
self.args.user,
self.password,
self.args.host,
self.args.port,
virtual_host)
def main():
"""Entrypoint for the CLI app"""
stew = RabbitStew()
stew.run()
if __name__ == '__main__':
main()
| true |
25cd9f626526310f08b75bdb1531d8194c104e0d | Python | GlenboLake/DailyProgrammer | /C215I_validating_sorting_networks.py | UTF-8 | 1,262 | 3.65625 | 4 | [] | no_license | '''
http://www.reddit.com/r/dailyprogrammer/comments/36m83a/20150520_challenge_215_intermediate_validating/
'''
def is_sorted(nums):
#print 'checking',nums
for item in range(len(nums)-1):
if nums[item] > nums[item+1]: return False
return True
class SortingNetwork(object):
def __init__(self, wires):
self.n = wires
self.connectors = []
def add_connector(self, wires):
self.connectors.append(wires)
def sort(self, numbers):
#print 'sorting',numbers
for c in self.connectors:
if numbers[c[0]] > numbers[c[1]]:
numbers[c[0]], numbers[c[1]] = numbers[c[1]], numbers[c[0]]
return numbers
def validate(self):
for item in range(2**self.n):
nums = list(map(int, list('{0:0{1}b}'.format(item, self.n))))
if not is_sorted(self.sort(nums)): return False
return True
with open('input/sorting networks challenge2.txt') as f:
params = f.readline().split()
network = SortingNetwork(int(params[0]))
for _ in range(int(params[1])):
t = tuple(map(int, f.readline().split()))
network.add_connector(t)
if network.validate():
print('Valid network')
else:
print('Invalid network') | true |
811a7c896bff8e6356d7d47b61debb665a233824 | Python | callumfrance/brailler | /views/view_braille.py | UTF-8 | 7,862 | 3.109375 | 3 | [
"MIT"
] | permissive | """
This is the ViewBraille class, used to interface this program via a
hardware device such as the Raspberry Pi Zero W or equivalent.
The class seeks to replicate the same functionality as the ViewCLI class,
but instead of displaying on the CLI, it displays on the GPIO pins.
Despite being referred to as a 'view' it also includes support for input.
"""
import gpiozero
from time import sleep
import reader.read as read
import writer.write as write
from writer.braille_cell import BrailleCell
###################################################
## For testing code on a non raspberry pi device ##
# from gpiozero.pins.mock import MockFactory
# gpiozero.Device.pin_factory = MockFactory()
###################################################
class ViewBraille:
def __init__(self, braille_pins=None):
# TODO encapsulate all these variables in another class (BraillePins)
self.br_in_pins = [ 2, 3, 4, 17, 27, 22 ]
self.br_out_pins = [ 18, 23, 24, 25, 12, 16 ]
self.in_enter_pin = 6
self.prev_pin= 13
self.next_pin = 19
self.br_in = [ gpiozero.Button(p, bounce_time=0.1) for p in self.br_in_pins ]
self.br_out = [ gpiozero.LED(p) for p in self.br_out_pins ]
self.in_enter = gpiozero.Button(self.in_enter_pin, bounce_time=0.1)
self.prev = gpiozero.Button(self.prev_pin, bounce_time=0.1)
self.next = gpiozero.Button(self.next_pin, bounce_time=0.1)
# TODO prevent overlapping values for all the above variables
self.disp_speed_delay = 0.5 # "1 second"
if braille_pins:
self.br_in = braille_pins.br_in
self.br_out = braille_pins.br_out
self.br_in_space = braille_pins.br_in_space
self.in_enter = braille_pins.in_enter
self.prev = braille_pins.prev
self.next = braille_pins.next
self.disp_speed_delay = braille_pins.disp_speed_delay
def _whitespace_macro(self, in_ws=None):
"""Modulate a 'whitespace' pause length depending on the type of
whitespace it is supposed to be representing.
"""
if in_ws == ' ':
delay = 1
elif in_ws == '\t':
delay = 1.5
elif in_ws == '\n':
delay = 2
elif in_ws is None:
delay = 0.5
else:
delay = 1
sleep(delay * self.disp_speed_delay * 1.0)
def b_char_print(self, in_b_char):
"""Prints a single braille character through the brailler device
- turn on all keys OR whitespace
- delay
- turn off all keys
"""
isBlank = True
in_b_char = write.Writer.unicode2braille(in_b_char)
for n, i in enumerate(in_b_char.cell):
if i:
self.br_out[n].on()
isBlank = False
if isBlank:
self._whitespace_macro(i)
self._whitespace_macro(None)
for n, j in enumerate(range(6)):
self.br_out[n].off()
self._whitespace_macro(None)
def str_print(self, in_str, ender="\n"):
"""Gets an input alphabetical string, converts to braille, and then
parses through the braille char printer
Callbacks may be triggered whilst this runs.
- Convert incoming string into Grade 2 Braille
- Iteratively print each character
"""
print(in_str)
in_b_str = read.Reader.translate_item(in_str)
for i in in_b_str:
self.b_char_print(i)
def str_input(self, inputter):
cells = list() # The cumulative inputted Braille characters from user
cellString = '' # The string unicode representation of inputted Braille
# b_in = list() # The six button values
b_in = [False, False, False, False, False, False]
notBreakout = True
def reset_button_values():
nonlocal b_in
b_in = [False, False, False, False, False, False]
reset_button_values() # Initialise the buttons to all be False
print("\nBegin writing\n")
# Mini functions to update the button readings when pressed by user
def toggle0():
b_in[0] = not b_in[0]
self.br_out[0].toggle()
print(b_in)
def toggle1():
b_in[1] = not b_in[1]
self.br_out[1].toggle()
print(b_in)
def toggle2():
b_in[2] = not b_in[2]
self.br_out[2].toggle()
print(b_in)
def toggle3():
b_in[3] = not b_in[3]
self.br_out[3].toggle()
print(b_in)
def toggle4():
b_in[4] = not b_in[4]
self.br_out[4].toggle()
print(b_in)
def toggle5():
b_in[5] = not b_in[5]
self.br_out[5].toggle()
print(b_in)
# Function to capture cell information and append to the cell input list
def char_input():
nonlocal notBreakout
"""Note that this may need to be altered because two sequential
spaces can indicate the start of a paragraph.
"""
print("\nEnter pressed")
for i in range(6):
self.br_out[i].off()
# Pump out a flash to indicate enter pressed
for i in range(6):
self.br_out[i].on()
self._whitespace_macro(' ')
for i in range(6):
self.br_out[i].off()
if len(cells) > 1:
print("Last cell isBlank: ", str(cells[-1].isBlank))
if cells[-1].isBlank: # Last entered cell was blank -> check breakout
if BrailleCell(b_in).isBlank: # Two consecutive blanks -> break
print("Two consecutive isBlanks found")
notBreakout = False
return(None)
# Now established that we need to keep writing cells
x = BrailleCell(b_in)
if x.isFull: # Interpret a full cell as a strikethrough - delete prev
print("\nStrikethrough found")
if len(cells) > 1:
cells.pop(-1)
else:
cells.append(x)
# Flush button values
reset_button_values()
# Turn on the button behaviour now that we are reading user input
self.br_in[0].when_pressed = toggle0
self.br_in[1].when_pressed = toggle1
self.br_in[2].when_pressed = toggle2
self.br_in[3].when_pressed = toggle3
self.br_in[4].when_pressed = toggle4
self.br_in[5].when_pressed = toggle5
self.in_enter.when_pressed = char_input
# Loop to capture the user's entire input until they write a breakout
while notBreakout:
pass # This is an intentional pass statement
# Turn off the button behaviour now that reading has completed
for i in range(6):
self.br_in[i].when_pressed = None
self.in_enter.when_pressed = None
# Get unicode of each BrailleCell in cells and squash into one string
for i in cells:
cellString += i.braille2unicode()
# Back_translate captured chars into English
output = read.Reader.back_translate_item(cellString)
# Return back_translated string
return(output)
def option_select(self, in_options):
self.str_print("")
for n, i in enumerate(in_options):
self.str_print(str(n) + " : " + i)
try:
ans = int(self.str_input("\n> "))
except ValueError:
ans = None
if ans < 0 or ans > len(in_options):
ans = None
return(ans)
""" TODO:
- Add callbacks for prev, next, and disp_speed
"""
| true |
49c0e5c023356a7877fe14b27689484e744b6b91 | Python | orwell-int/proxy-robots-python | /orwell/proxy_robots/action.py | UTF-8 | 3,584 | 2.828125 | 3 | [
"BSD-3-Clause"
] | permissive | import logging
from orwell.proxy_robots.status import Status
LOGGER = logging.getLogger(__name__)
class Action(object):
"""
Object functor to wrap a function and possibly the notification associated
to the function (the function sends the message and the notification is
triggered when the reply is received).
"""
def __init__(
self,
doer,
success,
proxy=None,
repeat=False):
"""
`doer`: the function that does something.
`success`: the function to call to check if the action is successful
or not.
`proxy`: the object containing information about the notification to
register to (if needed). If None, there is no registration.
`repeat`: True if and only if the action is to be attempted again on
failure. The function #doer is called again when this happens.
"""
self._doer = doer
self._success = success
self._repeat = repeat
self._proxy = proxy
self._status = Status.created
if self._proxy:
self._proxy.register_listener(self)
def call(self):
"""
Call the wrapped function.
"""
sent = self._doer()
self._update_status(sent)
def reset(self):
"""
To be called on failure to make it possible to repeat the action.
"""
self._update_status()
@property
def status(self):
"""
Status tracking where the action stands.
"""
return self._status
@property
def repeat(self):
return self._repeat
def _update_status(self, sent=False):
"""
Update the status of the action.
"""
updated = False
if Status.created == self._status:
if not sent:
self._status = Status.failed
else:
if self._proxy:
self._status = Status.pending
else:
self._status = Status.waiting
updated = True
if not updated:
if Status.pending == self._status:
self._status = Status.waiting
elif self._status in (Status.successful, Status.failed):
self._status = Status.created
if Status.waiting == self._status:
if not self._proxy:
if self._success():
self._status = Status.successful
else:
self._status = Status.failed
def notify(
self,
message_type,
routing_id,
message):
"""
May only be called if a proxy was provided to the constructor. Called
when the message registered to is read.
"""
LOGGER.debug('Action.notify({0}, {1}, {2})'.format(
message_type,
routing_id,
repr(message)))
if self._proxy.message_type:
if self._proxy.message_type != message_type:
raise Exception("Expected message type {0} but got {1}".format(
self._proxy.message_type, message_type))
if self._proxy.routing_id:
if self._proxy.routing_id != routing_id:
raise Exception("Expected routing id {0} but got {1}".format(
self._proxy.routing_id, routing_id))
self._update_status()
self._proxy.callback(message_type, routing_id, message)
self._update_status()
self._proxy.unregister(self)
| true |
89116340a2f2471effa37426cf44288a309af1de | Python | gardenia-homsi/holbertonschool-python | /0x07-python-test_driven_development/4-print_square.py | UTF-8 | 518 | 3.703125 | 4 | [] | no_license | #!/usr/bin/python3
"""This module does one class that has one private integer attribute with 2 exc
eptions."""
def print_square(size):
"""this function is for printing square"""
if type(size) is int:
if size >= 0:
for iter in range(size):
for iter2 in range(size):
print("#", end="")
print("")
else:
raise ValueError("size must be >= 0")
else:
raise TypeError("size must be an integer")
| true |
7d6f88d5c0c5b9fe139cfd7ee81eb6b9dcbeadf3 | Python | gjq91459/mycourse | /23 Miscellaneous Topics/GUI Frameworks/wxPython/02-menus.py | UTF-8 | 1,359 | 3 | 3 | [] | no_license | ############################################################
#
# menus
#
############################################################
import wx
class MyApp(wx.App):
def OnInit(self):
self.frame = MyFrame("Hello")
self.frame.Show()
self.SetTopWindow(self.frame)
return True;
class MyFrame(wx.Frame):
ID_OPEN = 100
ID_SAVE = 101
ID_EXIT = 102
def __init__(self, title):
wx.Frame.__init__(self,
parent = None,
title = title,
pos = (100, 300),
size = (200, 400))
self.AddMenu()
def AddMenu(self):
self.menubar = wx.MenuBar()
file = wx.Menu()
edit = wx.Menu()
help = wx.Menu()
file.Append(text = '&Open', help = 'Open a new document', id = MyFrame.ID_OPEN)
file.Append(text = '&Save', help = 'Save the document', id = MyFrame.ID_SAVE)
file.AppendSeparator()
file.Append(text = 'E&xit', help = 'Exit', id = MyFrame.ID_EXIT)
self.menubar.Append(file, '&File')
self.menubar.Append(edit, '&Edit')
self.menubar.Append(help, '&Help')
self.SetMenuBar(self.menubar)
app = MyApp()
app.MainLoop()
| true |
464810a7d8aa697b4de3747a26cf62eeaaa11ac1 | Python | idabayev/extracting-data-from-emails | /writing_hits_into_table.py | UTF-8 | 3,379 | 3.015625 | 3 | [] | no_license | import pandas
# For writing to excel file
import openpyxl
# For writing to google spreadsheet
import gspread
from oauth2client.service_account import ServiceAccountCredentials
COL_OF_TZ = 2
COL_OF_HIT = 8
COL_OF_TREATS = 9
COL_OF_FILENAME = 10
GOOGLE_SHEET_NAME = "Copy of Leumit For Ida"
SHEET_PAGE_NAME = "New Hithayvuyot"
def find_tz_name(cell_value):
"""
return the t_z, and name in Hebrew
:param cell_value: the string value
"""
parts = cell_value.split(" - ")
name, tz = parts[0], parts[1]
tz = int(tz.replace("/", ""))
return tz, name
def register_monthly_ids(file_name):
"""
Will register this month t_z in dictionary and on computer
:param file_name: excel file name
:return:
"""
# To open the workbook, workbook object is created
wb_obj = openpyxl.load_workbook(file_name)
t_z_dict = {}
for i in ("RONIT", "AVIVA"):
sheet_obj = wb_obj.get_sheet_by_name(i)
row, col = 2, COL_OF_TZ
cell_value = sheet_obj.cell(row, col).value
while cell_value:
row += 1
t_z, name = find_tz_name(cell_value)
t_z_dict[t_z] = name
cell_value = sheet_obj.cell(row, col).value
return t_z_dict
def write_df_to_gspread(data):
# use creds to create a client to interact with the Google Drive API
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)
# Find a workbook by name and open the first sheet
# Make sure you use the right name here.
sheet = client.open(GOOGLE_SHEET_NAME).worksheet(SHEET_PAGE_NAME)
list_of_data = [data.columns.values.tolist()] + data.values.tolist()
for i in range(len(list_of_data)):
for j in range(len(list_of_data[0])):
sheet.update_cell(i+1, j+1, list_of_data[i][j])
print("Done")
def write_data_to_excel(file_name, hit_info):
wb_obj = openpyxl.load_workbook(file_name)
for i in ("RONIT", "AVIVA"):
sheet_obj = wb_obj.get_sheet_by_name(i)
row, col = sheet_obj.max_row, 1
cell_value = sheet_obj.cell(row, col).value
while cell_value > 1:
row -= 1
cell_value = sheet_obj.cell(row, col).value
col = COL_OF_TZ
cell_value = sheet_obj.cell(row, col).value
while cell_value:
t_z, name = find_tz_name(cell_value)
if t_z in hit_info['t_z']:
data_row = hit_info[(hit_info['t_z'] == t_z)]
hits = data_row['hithaybut'].tolist()
treats = data_row['num_treats'].tolist()
f_names = data_row['file_name'].tolist()
# if len(hits) >= 1:
hit = hits[0]
num_treats = treats[0]
f_name = f_names[0]
sheet_obj.cell(row, COL_OF_HIT).value = hit
sheet_obj.cell(row, COL_OF_TREATS).value = num_treats
sheet_obj.cell(row, COL_OF_FILENAME).value = f_name
row += 1
cell_value = sheet_obj.cell(row, col).value
wb_obj.save(file_name)
hit_info = pandas.DataFrame.from_csv("Hithayvuyot_06012020.xlsx")
write_data_to_excel("MayHit.xlsx", hit_info)
write_df_to_gspread(hit_info)
| true |