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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
155a982259d92158c49e4960fd467efe1222f00e | Python | saka0045/create_bed_file | /parseAlamut.py | UTF-8 | 2,876 | 3.046875 | 3 | [] | no_license | ####
## Purpose:
##
## Usage:
##
## @author JRWalsh 12/13/2018
####
import sys
import argparse
"""
Main
"""
def main(args):
excludedList = parseExcluded(args["exclude"])
allowedList = parseAllowed(args["allow"])
parseAlamut(args["inputAlamutFile"], excludedList, allowedList)
####
## Parse a 1 column file of transcript or gene names
####
def parseExcluded(excludeFile):
if excludeFile == None:
return None
with open(excludeFile) as f:
excludedList = f.readlines()
excludedList = [x.strip() for x in excludedList]
return excludedList
####
## Parse a 1 column file of transcript or gene names
###
def parseAllowed(allowFile):
if allowFile == None:
return None
with open(allowFile) as f:
allowedList = f.readlines()
allowedList = [x.strip() for x in allowedList]
return allowedList
####
## Main loop
####
def parseAlamut(alamutFile, excludedList, allowedList):
with open(alamutFile) as f:
lines = f.readlines()
f.close()
for line in lines:
try:
items = line.rstrip().split()
gene = items[1]
transcriptID = items[7]
if allowedList is not None:
if transcriptID in allowedList or gene in allowedList:
print(line.rstrip())
elif excludedList is not None:
if transcriptID not in excludedList and gene not in excludedList:
print(line.rstrip())
else:
print(line.rstrip())
except:
if len(line) > 1:
print("Error in line: ", line)
########################################
# Parse arguments and kick off program #
########################################
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--inputAlamutFile", required=True, help="Alamut gene/transcript/exon file to parse")
#ap.add_argument("-o", "--output", required=True, help="output location")
ap.add_argument("-x", "--exclude", required=False, default=None, help="list of genes or transcripts to exclude from output")
ap.add_argument("-a", "--allow", required=False, default=None, help="list of genes or transcripts to allow in the output")
args = vars(ap.parse_args())
# Expects txv format with the following columns:
#['Assembly', 'Symbol', 'HGNC_Id', 'Chromosome', 'Gene_Start', 'Gene_End', 'Strand', 'Transcript', 'Transcript_Start', 'Transcript_End', 'Transcript_CDS_Start', 'Transcript_CDS_End', 'Exon', 'Exon_Start', 'Exon_End', 'Exon_CDS_Start', 'Exon_CDS_End']
# Cannot set both -x and -a, complain if user tries
if args["exclude"] and args["allow"]:
print("Usage: cannot specify both an include and exclude list at the same time")
sys.exit()
# Call main code
main(args)
| true |
9bc72b4688e8c0a35b1d154e72b8f8a601b14412 | Python | vinaycheruku123/My_Python_Practice | /Local_Global_Varibles.py | UTF-8 | 254 | 3.875 | 4 | [] | no_license | print('Learning Local and Global Variables ')
print('=====================================')
a = 0
x = input('Enter a number')
if int(x) == 10:
print ('Inside if condition ', end = '')
print(a)
a = 1
print(a)
print(a)
| true |
c26d1aeaf3bd97d128ce52e26c42471caa0a89ac | Python | rrtucci/Entanglish | /entanglish/SymNupState.py | UTF-8 | 3,941 | 3.546875 | 4 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | import itertools as it
import numpy as np
import entanglish.utilities as ut
class SymNupState:
"""
This class is designed to perform tasks related to a SymNupState.
SymNupState is an abbreviation for Symmetrized N-qubits-up State,
which is a special, very convenient for testing purposes, type of
quantum state vector. Note, this is a pure state of qubits only. No
qudits with d != 2 in this state. The state contains a total of
num_qbits qubits. num_up of them are up (in state ``|1>``) and num_qbits
- num_up are down (in state ``|0>``). To build such a state, we first
create any ( normalized) initial state vector with the required number
of up and down qubits, and then we apply a total symmetrizer to that
initial state vector.
It turns out that SymNupState's have a (bipartite) entanglement that is
known and has a simple analytical expression given by the classical
entropy of a hyper-geometric distribution.
See Ref.1 for a more detailed explanation of the algos used in this class.
References
----------
1. R.R. Tucci, "A New Algorithm for Calculating Squashed Entanglement
and a Python Implementation Thereof"
Attributes
----------
num_qbits : int
total number of qubits in the state
num_up : int
should be <= num_qbits. The number of qubits that is up (in state
``|1>``). The other num_qbits - n_up are down (in state ``|0>``)
"""
def __init__(self, num_up, num_qbits):
"""
Constructor
Parameters
----------
num_up : int
num_qbits : int
Returns
-------
"""
assert 0 <= num_up <= num_qbits
self.num_qbits = num_qbits
self.num_up = num_up
def get_st_vec(self):
"""
This method outputs the (pure) state vector for the SymNupState
object.
Returns
-------
np.ndarray
shape=(2^self.num_qbits, )
"""
st_vec = np.zeros(tuple([2]*self.num_qbits), dtype=complex)
all_axes = list(range(0, self.num_qbits))
comb_len = self.num_up
for up_axes in it.combinations(all_axes, comb_len):
index = tuple([1 if k in up_axes else 0
for k in range(self.num_qbits)])
st_vec[index] = 1
mag = np.linalg.norm(st_vec)
st_vec /= mag
return st_vec.reshape((1 << self.num_qbits,))
def get_known_entang(self, num_x_axes):
"""
This method calculates the (bipartite) entanglement analytically,
from a known formula, not numerically.
E(x_axes, y_axes)=E(y_axes, x_axes) (order of x_axes and y_axes
arguments doesn't matter)
len(x_axes)= num_x_axes, and len(y_axes)= num_row_axes - num_x_axes.
After the symmetrization of the state, E(x_axes, y_axes) only
depends of the numbers of x_axes and y_axes.
One can prove that E(x_axes, y_axes) is given by the hyper-geometric
distribution (see Ref.1)
References
----------
1. `<https://en.wikipedia.org/wiki/Hypergeometric_distribution)>`_
Parameters
----------
num_x_axes : int
Returns
-------
float
"""
assert 0 <= num_x_axes <= self.num_qbits
nn = self.num_qbits
n = num_x_axes
xx = self.num_up
probs = [ut.prob_hypergeometric(x, xx, n, nn)
for x in range(xx + 1)]
return ut.get_entropy_from_probs(np.array(probs))
if __name__ == "__main__":
def main():
num_up = 4
num_qbits = 5
st = SymNupState(num_up, num_qbits)
print('st_vec=\n', st.get_st_vec())
for num_x_axes in range(0, num_qbits+1):
print('known entang for ' + str(num_x_axes) + ' x axes=',
st.get_known_entang(num_x_axes))
main()
| true |
28dfda698884f126ef9eddbfa2d69e191425ad24 | Python | asc3ndr/zoom-meetings | /eksamen/eksamen2019/oppg_8.py | UTF-8 | 157 | 3.296875 | 3 | [] | no_license | def find_number(string):
number = [int(symbol) for symbol in string if symbol.isnumeric()]
return sum(number)
print(find_number("Ab23s249ttu21"))
| true |
bff226b4f086f88c9dfb361f030cba2444d6aedb | Python | awwilliams/tconfig | /tconfig/tests/core/algorithms/recursive/test_field.py | UTF-8 | 2,347 | 2.890625 | 3 | [
"MIT"
] | permissive | """
Created on Sep 20, 2017
@author: Alan Williams
"""
import pytest
from tconfig.core.algorithms.recursive.intmod import IntMod
from tconfig.core.algorithms.recursive.rem_poly import RemainderPoly
from tconfig.core.algorithms.recursive.field import Field
# pylint: disable=invalid-name
def test_field_2():
f = Field(2)
assert f.elements == [RemainderPoly.constant(0), RemainderPoly.constant(1)]
def test_field_3():
f = Field(3)
assert f.elements == [
RemainderPoly.constant(0),
RemainderPoly.constant(1),
RemainderPoly.constant(2),
]
def test_field_4():
f = Field(4)
assert [str(e) for e in f.elements] == ["0", "1", "x", "x + 1"]
assert f.elements == [
RemainderPoly(coef_list=[IntMod(0)]),
RemainderPoly(coef_list=[IntMod(1)]),
RemainderPoly(coef_list=[IntMod(0), IntMod(1)]),
RemainderPoly(coef_list=[IntMod(1), IntMod(1)]),
]
def test_field_5():
f = Field(5)
assert f.elements == [
RemainderPoly.constant(0),
RemainderPoly.constant(1),
RemainderPoly.constant(2),
RemainderPoly.constant(3),
RemainderPoly.constant(4),
]
def test_field_6():
with pytest.raises(ArithmeticError, match="Field order 6 is not a prime power"):
Field(6)
def test_field_7():
f = Field(7)
assert f.elements == [
RemainderPoly.constant(0),
RemainderPoly.constant(1),
RemainderPoly.constant(2),
RemainderPoly.constant(3),
RemainderPoly.constant(4),
RemainderPoly.constant(5),
RemainderPoly.constant(6),
]
def test_field_8():
f = Field(8)
assert [str(e) for e in f.elements] == [
"0",
"1",
"x",
"x + 1",
"x^2",
"x^2 + 1",
"x^2 + x",
"x^2 + x + 1",
]
assert f.elements == [
RemainderPoly(coef_list=[IntMod(0)]),
RemainderPoly(coef_list=[IntMod(1)]),
RemainderPoly(coef_list=[IntMod(0), IntMod(1)]),
RemainderPoly(coef_list=[IntMod(1), IntMod(1)]),
RemainderPoly(coef_list=[IntMod(0), IntMod(0), IntMod(1)]),
RemainderPoly(coef_list=[IntMod(1), IntMod(0), IntMod(1)]),
RemainderPoly(coef_list=[IntMod(0), IntMod(1), IntMod(1)]),
RemainderPoly(coef_list=[IntMod(1), IntMod(1), IntMod(1)]),
]
| true |
d6591dc34fcf6f4fd9457e34acf7ad9a63381c42 | Python | aeciovc/sda_python_ee4 | /SDAPythonIntermediateGeneratorsAndIterators/iterating_sample.py | UTF-8 | 174 | 3.703125 | 4 | [] | no_license | a = [1, 2, 3, 4]
for item in a:
print(item)
a = "Alice has a cat"
for item in a:
print(item)
a = {'name': "Adam", 'surname': "Smith"}
for item in a:
print(item) | true |
ae9cd6c493344926048dea7f400f10ba1e005b28 | Python | Cardmonitor/card-scanner | /compare_images.py | UTF-8 | 3,657 | 2.890625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
from glob import glob
from cv_utils import compare_images
from scipy.misc import imread, imresize, imshow
import cv2
import numpy as np
import scipy
import timeit
import json
import os.path
def dhash(image, hashSize=8):
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# resize the input image, adding a single column (width) so we
# can compute the horizontal gradient
resized = cv2.resize(image, (hashSize + 1, hashSize))
# compute the (relative) horizontal gradient between adjacent
# column pixels
diff = resized[:, 1:] > resized[:, :-1]
# convert the difference image to a hash
return sum([2 ** i for (i, v) in enumerate(diff.flatten()) if v])
def img_gray(image):
return np.average(image, weights=[0.299, 0.587, 0.114], axis=2)
def resize(image, height=30, width=30):
row_res = cv2.resize(image,(height, width), interpolation = cv2.INTER_AREA).flatten()
col_res = cv2.resize(image,(height, width), interpolation = cv2.INTER_AREA).flatten('F')
return row_res, col_res
def intensity_diff(row_res, col_res):
difference_row = np.diff(row_res)
difference_col = np.diff(col_res)
difference_row = difference_row > 0
difference_col = difference_col > 0
return np.vstack((difference_row, difference_col)).flatten()
def difference_score(image, height = 30, width = 30):
gray = img_gray(image)
row_res, col_res = resize(gray, height, width)
difference = intensity_diff(row_res, col_res)
return difference.tolist()
def hamming_dist(h1,h2):
return scipy.spatial.distance.hamming(h1, h2)
def save_orig_image_hashs_to_json(orig_image_hashs):
data = json.dumps(orig_image_hashs)
f = open("orig_image_hashs.json","w")
f.write(data)
f.close()
def load_orig_image_hashs_from_json():
print 'Lade Hashes'
with open("orig_image_hashs.json") as f:
cards = json.load(f)
return cards
def hash_original_images():
print 'Creating Hashes'
orig_image_hashs = {}
i = 0
start = timeit.default_timer()
for orig in glob("original/*.jpg"):
if (i > 10000000):
break
orig_image = imread(orig)
orig_image_hash = difference_score(orig_image, 32, 32)
orig_image_hashs[orig] = orig_image_hash
i += 1
stop = timeit.default_timer()
print('{} Hashes created'.format(i))
print 'Dauer: ' + str(round((stop - start), 2)) + ' Sekunden'
save_orig_image_hashs_to_json(orig_image_hashs)
return orig_image_hashs
if (os.path.isfile("orig_image_hashs.json")):
orig_image_hashs = load_orig_image_hashs_from_json()
else:
orig_image_hashs = hash_original_images()
# hash our warped image
#hash = imagehash.phash_simple(Image.open("source_images/test.jpg"))
image = imread("source_images/test.jpg")
# image = cv2.resize(image, (672, 936))
# image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# image_dst = cv2.dct(np.float32(image)/255.0)
image_hash = difference_score(image, 32, 32)
scores = {}
start = timeit.default_timer()
print 'Comparing Hashes'
# loop over all official images
for (filename) in orig_image_hashs:
# score = compare_images(orig_image, image)
print(filename)
scores[filename] = hamming_dist(image_hash, orig_image_hashs[filename])
# print('Comparing image to {}, score {}'.format(
# orig, score
# ))
stop = timeit.default_timer()
print 'Hashes compared'
print 'Dauer: ' + str(round((stop - start), 2)) + ' Sekunden'
print('-' * 50)
for (filename, score) in sorted(scores.items(), key=lambda item: item[1]):
print('Comparing image to {}, score {}'.format(
filename, score
))
| true |
bc0f747fd19ce1da90a4fe6afcbe7ca1c9cabafa | Python | kaustubsinha/Python-Fundamentals-For-Machine-Learning- | /6. Using Rest Api/Rest Api Get and Post method.py | UTF-8 | 534 | 2.578125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 24 23:08:47 2018
@author: Kaustub Sinha
"""
import requests as rq
data = {
"Phone_Number":"9983654545",
"Name":"Kaustub Sinha",
"College_Name":"Manipal University Jaipur",
"Branch":"Jaipur"
}
Req_send_url="http://13.127.155.43/api_v0.1/sending"
resp = rq.post(Req_send_url,json=data)
print(resp.text)
Req_Recv_url = "http://13.127.155.43/api_v0.1/receiving?Phone_Number=9983654545"
resp_Recv = rq.get(Req_Recv_url)
print(resp_Recv.text)
| true |
523cb3a37707d0e03bd033708ba1899b51dfd5b6 | Python | euctrl-pru/rt-python | /tests/test_HorizontalPath.py | UTF-8 | 1,702 | 2.6875 | 3 | [
"MIT",
"LicenseRef-scancode-other-permissive"
] | permissive | #!/usr/bin/env python
#
# Copyright (c) 2018 Via Technology Ltd. All Rights Reserved.
# Consult your license regarding permissions and restrictions.
import unittest
import numpy as np
import json
from numpy.testing import assert_array_almost_equal
from pru.HorizontalPath import HorizontalPath
GOLDEN_ANGLE = np.rad2deg(np.arctan(2.0))
LATITUDE = 90.0 - GOLDEN_ANGLE
NM = np.deg2rad(1.0 / 60.0)
ROUTE_LATS = np.array([90.0, LATITUDE, LATITUDE,
LATITUDE, LATITUDE, LATITUDE,
-LATITUDE, -LATITUDE, -LATITUDE,
-LATITUDE, -LATITUDE, -90.0])
ROUTE_LONS = np.array([0.0, 180.0, -1.5 * 72.0,
-0.5 * 72.0, 0.5 * 72.0, 1.5 * 72.0,
2.0 * 72.0, -2.0 * 72.0, -1.0 * 72.0,
0.0, 1.0 * 72.0, 0.0])
""" An Icosahedron with vertices at the North and South poles. """
TURN_DISTANCES = np.array([0., 0., 10 * NM,
20 * NM, 20 * NM, 20 * NM,
20 * NM, 20 * NM, 20 * NM,
20 * NM, 0., 0.])
class TestHorizontalPath(unittest.TestCase):
def test_HorizontalPath(self):
traj_0 = HorizontalPath(ROUTE_LATS, ROUTE_LONS, TURN_DISTANCES)
s = traj_0.dumps()
# print(s)
json_1 = json.loads(s)
traj_1 = HorizontalPath.loads(json_1)
assert_array_almost_equal(traj_1.lats, traj_0.lats)
assert_array_almost_equal(traj_1.lons, traj_0.lons)
assert_array_almost_equal(traj_1.tids, traj_0.tids)
ecef_path_1 = traj_1.ecef_path()
self.assertEqual(len(ecef_path_1), len(ROUTE_LATS))
if __name__ == '__main__':
unittest.main()
| true |
1defbcbd0378f9e8c913ed7c1d4c7b8b60aee5e5 | Python | cescara/aoc2019 | /day12.py | UTF-8 | 3,551 | 3.140625 | 3 | [] | no_license | from util import get_input
from itertools import count
from math import gcd
import re
def read_input(file):
return [Vector.from_string(x.strip()) for x in file]
def cmp(i, j):
return (i < j) - (i > j)
def lcm(x, y, z):
gcd_yz = gcd(y, z)
lcm_yz = y * z // gcd_yz
lcm_xyz = x * lcm_yz // gcd(x, lcm_yz)
return lcm_xyz
class Vector:
__slots__ = ("x", "y", "z")
pattern = re.compile(r".*<x=(?P<x> *-?\d+), y=(?P<y> *-?\d+), z=(?P<z> *-?\d+)>")
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
def __add__(self, other):
return Vector(
self.x + other.x,
self.y + other.y,
self.z + other.z)
def __iadd__(self, other):
self.x += other.x
self.y += other.y
self.z += other.z
return self
def __repr__(self):
return f"Vector <x={self.x}, y={self.y}, z={self.z}>"
def state_code(self):
return hash((self.x, self.y, self.z))
def gravitate(self, others):
result = Vector()
for other in others:
if other == self:
continue
result += Vector(cmp(self.x, other.x), cmp(self.y, other.y), cmp(self.z, other.z))
return result
def abs_sum(self):
return sum(map(abs, (self.x, self.y, self.z)))
@classmethod
def from_string(cls, s):
match = cls.pattern.match(s)
if match is None:
raise ValueError
return cls(int(match.group("x")), int(match.group("y")), int(match.group("z")))
def get_states(moons):
return {attr: tuple(getattr(moon, attr) for moon in moons) for attr in "xyz"}
def part1(moons: list, steps):
velocities, energy = {moon: Vector() for moon in moons}, []
for step in range(steps + 1):
energy = []
print(f"After {step} steps:")
for moon, vel in velocities.items():
moon += vel
moon_energy = moon.abs_sum() * vel.abs_sum()
energy.append(moon_energy)
print(f"pos={moon}, vel={vel}, total_energy={moon_energy}")
for moon in moons:
velocities[moon] += moon.gravitate(moons)
print(f"Sum of total energy: {energy} => {sum(energy)}\n")
return sum(energy)
def part2(moons: list):
velocities = {moon: Vector() for moon in moons}
first_loops = dict.fromkeys("xyz")
initial_states = get_states(moons)
for steps in count():
for moon, vel in velocities.items():
moon += vel
for attr, state in get_states(moons).items():
if steps and not first_loops[attr] and state == initial_states[attr]:
first_loops[attr] = steps + 1
for moon in moons:
velocities[moon] += moon.gravitate(moons)
if all(first_loops.values()):
break
return lcm(*first_loops.values())
test_1_0 = """<x=-1, y=0, z=2>
<x=2, y=-10, z=-7>
<x=4, y=-8, z=8>
<x=3, y=5, z=-1>"""
test_1_1 = """<x=-8, y=-10, z=0>
<x=5, y=5, z=10>
<x=2, y=-7, z=3>
<x=9, y=-8, z=-3>"""
def test_part1():
assert part1(read_input(test_1_0.split("\n")), 10) == 179
assert part1(read_input(test_1_1.split("\n")), 100) == 1940
def test_part2():
assert part2(read_input(test_1_0.split("\n"))) == 2772
assert part2(read_input(test_1_1.split("\n"))) == 4686774924
def main():
with open(get_input(__file__)) as file:
moons = read_input(file)
print(part1(moons.copy(), 1000))
print(part2(moons))
if __name__ == '__main__':
main()
| true |
a9b1d2762cf09d71584c48094888a5096c372115 | Python | yugov/tceh_homeworks | /homework2/homework2_6.py | UTF-8 | 254 | 4 | 4 | [] | no_license | # Функция принимает матрицу ( список списков ) и выводит в консоль построчно
matrix = [ [1,2,3], [4,5,6], [7,8,9]]
def matrix_out(m):
for row in m:
print(row)
matrix_out(matrix)
| true |
08a2f4835304ec7600be31a69f1600847e0752dc | Python | Wallacexwav/camiseta | /camiseta/utils.py | UTF-8 | 1,706 | 2.765625 | 3 | [
"MIT"
] | permissive | from camiseta.tempfile import *
import pathlib, os
from http.server import HTTPServer, BaseHTTPRequestHandler
import webbrowser
class Save:
def __init__(self, path='', file_name = ''):
self.path = path
self.name = file_name
if not os.path.isdir(self.path) and self.path != '':
return print('Invalid output path {}'.format(self.path))
else:
if self.path == '': self.path = pathlib.Path().resolve()
# Validating file name
if self.name == '': self.name = 'index.html'
if not self.name.endswith('.html'): self.name += '.html'
temp_file.seek(0)
with open('{}/{}'.format(self.path, self.name), 'w') as html:
html.write(temp_file.read())
temp_file.close()
print('Finished. {} saved in {}/{}'.format(self.name, self.path, self.name))
class File:
def __init__(self, path = ''):
try:
self.path = os.path.join(pathlib.Path().resolve(), path)
with open(self.path, 'r') as file:
temp_file.write(file.read())
except:
print('Error loading file {}. Ignoring.'.format(self.path))
class Server:
def __init__(self, port = 3500):
temp_file.seek(0)
self.port = port
server = HTTPServer(('', self.port), HelloHandler)
print('Running')
webbrowser.open_new_tab('http://127.0.0.1:{}/'.format(self.port))
server.serve_forever()
class HelloHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('content-type', 'text/html')
self.end_headers()
self.wfile.write(temp_file.read().encode()) | true |
bcd83510c9e7203c3bd99e0c18498aabf5170913 | Python | francico4293/Kuba | /kuba_game.py | UTF-8 | 50,544 | 3.28125 | 3 | [] | no_license | # Author: Colin Francis
# Description: This file contains all logic used to play the game of Kuba. This file also contains all logic used
# to configure and update the game board using Pygame.
import pygame
from settings import *
import copy
class KubaGame(object):
"""Represents the board game Kuba"""
def __init__(self) -> None:
"""Initializes pygame modules and creates a KubaGame object with board, running, and selected attributes. The
board attribute initializes the game Board. The running attribute is True while the game is running and False
when the user exits. The selected attribute is set to True if the user selects a cell on the game board,
otherwise this is False."""
pygame.init()
pygame.mixer.init()
self._board = Board()
self._running = True
self._selected = False
self._turn = None
self._winner = None
self._player_1 = Player(WHITE, "White")
self._player_2 = Player(BLACK, "Black")
def play(self) -> None:
"""Start playing Kuba."""
while self._running:
self._board.update_board()
for event in pygame.event.get():
if event.type == pygame.QUIT:
self._running = False
if event.type == pygame.MOUSEBUTTONDOWN:
# row 1
if (BOARD_POSITIONS[0][0][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][1][0]) and \
(BOARD_POSITIONS[0][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[1][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][0][0])
self._board.set_top(BOARD_POSITIONS[0][0][1])
elif (BOARD_POSITIONS[0][1][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][2][0]) and \
(BOARD_POSITIONS[0][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[1][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][1][0])
self._board.set_top(BOARD_POSITIONS[0][0][1])
elif (BOARD_POSITIONS[0][2][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][3][0]) and \
(BOARD_POSITIONS[0][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[1][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][2][0])
self._board.set_top(BOARD_POSITIONS[0][0][1])
elif (BOARD_POSITIONS[0][3][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][4][0]) and \
(BOARD_POSITIONS[0][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[1][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][3][0])
self._board.set_top(BOARD_POSITIONS[0][0][1])
elif (BOARD_POSITIONS[0][4][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][5][0]) and \
(BOARD_POSITIONS[0][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[1][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][4][0])
self._board.set_top(BOARD_POSITIONS[0][0][1])
elif (BOARD_POSITIONS[0][5][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][6][0]) and \
(BOARD_POSITIONS[0][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[1][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][5][0])
self._board.set_top(BOARD_POSITIONS[0][0][1])
elif (BOARD_POSITIONS[0][6][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][6][0] + 100) and \
(BOARD_POSITIONS[0][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[1][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][6][0])
self._board.set_top(BOARD_POSITIONS[0][0][1])
# row 2
elif (BOARD_POSITIONS[0][0][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][1][0]) and \
(BOARD_POSITIONS[1][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[2][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][0][0])
self._board.set_top(BOARD_POSITIONS[1][0][1])
elif (BOARD_POSITIONS[0][1][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][2][0]) and \
(BOARD_POSITIONS[1][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[2][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][1][0])
self._board.set_top(BOARD_POSITIONS[1][0][1])
elif (BOARD_POSITIONS[0][2][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][3][0]) and \
(BOARD_POSITIONS[1][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[2][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][2][0])
self._board.set_top(BOARD_POSITIONS[1][0][1])
elif (BOARD_POSITIONS[0][3][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][4][0]) and \
(BOARD_POSITIONS[1][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[2][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][3][0])
self._board.set_top(BOARD_POSITIONS[1][0][1])
elif (BOARD_POSITIONS[0][4][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][5][0]) and \
(BOARD_POSITIONS[1][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[2][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][4][0])
self._board.set_top(BOARD_POSITIONS[1][0][1])
elif (BOARD_POSITIONS[0][5][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][6][0]) and \
(BOARD_POSITIONS[1][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[2][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][5][0])
self._board.set_top(BOARD_POSITIONS[1][0][1])
elif (BOARD_POSITIONS[0][6][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][6][0]) + 100 and \
(BOARD_POSITIONS[1][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[2][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][6][0])
self._board.set_top(BOARD_POSITIONS[1][0][1])
# row 3
elif (BOARD_POSITIONS[0][0][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][1][0]) and \
(BOARD_POSITIONS[2][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[3][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][0][0])
self._board.set_top(BOARD_POSITIONS[2][0][1])
elif (BOARD_POSITIONS[0][1][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][2][0]) and \
(BOARD_POSITIONS[2][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[3][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][1][0])
self._board.set_top(BOARD_POSITIONS[2][0][1])
elif (BOARD_POSITIONS[0][2][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][3][0]) and \
(BOARD_POSITIONS[2][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[3][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][2][0])
self._board.set_top(BOARD_POSITIONS[2][0][1])
elif (BOARD_POSITIONS[0][3][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][4][0]) and \
(BOARD_POSITIONS[2][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[3][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][3][0])
self._board.set_top(BOARD_POSITIONS[2][0][1])
elif (BOARD_POSITIONS[0][4][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][5][0]) and \
(BOARD_POSITIONS[2][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[3][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][4][0])
self._board.set_top(BOARD_POSITIONS[2][0][1])
elif (BOARD_POSITIONS[0][5][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][6][0]) and \
(BOARD_POSITIONS[2][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[3][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][5][0])
self._board.set_top(BOARD_POSITIONS[2][0][1])
elif (BOARD_POSITIONS[0][6][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][6][0]) + 100 and \
(BOARD_POSITIONS[2][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[3][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][6][0])
self._board.set_top(BOARD_POSITIONS[2][0][1])
# row 4
elif (BOARD_POSITIONS[0][0][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][1][0]) and \
(BOARD_POSITIONS[3][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[4][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][0][0])
self._board.set_top(BOARD_POSITIONS[3][0][1])
elif (BOARD_POSITIONS[0][1][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][2][0]) and \
(BOARD_POSITIONS[3][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[4][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][1][0])
self._board.set_top(BOARD_POSITIONS[3][0][1])
elif (BOARD_POSITIONS[0][2][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][3][0]) and \
(BOARD_POSITIONS[3][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[4][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][2][0])
self._board.set_top(BOARD_POSITIONS[3][0][1])
elif (BOARD_POSITIONS[0][3][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][4][0]) and \
(BOARD_POSITIONS[3][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[4][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][3][0])
self._board.set_top(BOARD_POSITIONS[3][0][1])
elif (BOARD_POSITIONS[0][4][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][5][0]) and \
(BOARD_POSITIONS[3][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[4][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][4][0])
self._board.set_top(BOARD_POSITIONS[3][0][1])
elif (BOARD_POSITIONS[0][5][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][6][0]) and \
(BOARD_POSITIONS[3][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[4][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][5][0])
self._board.set_top(BOARD_POSITIONS[3][0][1])
elif (BOARD_POSITIONS[0][6][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][6][0]) + 100 and \
(BOARD_POSITIONS[3][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[4][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][6][0])
self._board.set_top(BOARD_POSITIONS[3][0][1])
# row 3
elif (BOARD_POSITIONS[0][0][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][1][0]) and \
(BOARD_POSITIONS[2][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[3][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][0][0])
self._board.set_top(BOARD_POSITIONS[2][0][1])
elif (BOARD_POSITIONS[0][1][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][2][0]) and \
(BOARD_POSITIONS[2][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[3][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][1][0])
self._board.set_top(BOARD_POSITIONS[2][0][1])
elif (BOARD_POSITIONS[0][2][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][3][0]) and \
(BOARD_POSITIONS[2][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[3][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][2][0])
self._board.set_top(BOARD_POSITIONS[2][0][1])
elif (BOARD_POSITIONS[0][3][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][4][0]) and \
(BOARD_POSITIONS[2][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[3][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][3][0])
self._board.set_top(BOARD_POSITIONS[2][0][1])
elif (BOARD_POSITIONS[0][4][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][5][0]) and \
(BOARD_POSITIONS[2][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[3][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][4][0])
self._board.set_top(BOARD_POSITIONS[2][0][1])
elif (BOARD_POSITIONS[0][5][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][6][0]) and \
(BOARD_POSITIONS[2][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[3][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][5][0])
self._board.set_top(BOARD_POSITIONS[2][0][1])
elif (BOARD_POSITIONS[0][6][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][6][0]) + 100 and \
(BOARD_POSITIONS[2][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[3][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][6][0])
self._board.set_top(BOARD_POSITIONS[2][0][1])
# row 5
elif (BOARD_POSITIONS[0][0][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][1][0]) and \
(BOARD_POSITIONS[4][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[5][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][0][0])
self._board.set_top(BOARD_POSITIONS[4][0][1])
elif (BOARD_POSITIONS[0][1][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][2][0]) and \
(BOARD_POSITIONS[4][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[5][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][1][0])
self._board.set_top(BOARD_POSITIONS[4][0][1])
elif (BOARD_POSITIONS[0][2][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][3][0]) and \
(BOARD_POSITIONS[4][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[5][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][2][0])
self._board.set_top(BOARD_POSITIONS[4][0][1])
elif (BOARD_POSITIONS[0][3][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][4][0]) and \
(BOARD_POSITIONS[4][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[5][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][3][0])
self._board.set_top(BOARD_POSITIONS[4][0][1])
elif (BOARD_POSITIONS[0][4][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][5][0]) and \
(BOARD_POSITIONS[4][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[5][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][4][0])
self._board.set_top(BOARD_POSITIONS[4][0][1])
elif (BOARD_POSITIONS[0][5][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][6][0]) and \
(BOARD_POSITIONS[4][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[5][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][5][0])
self._board.set_top(BOARD_POSITIONS[4][0][1])
elif (BOARD_POSITIONS[0][6][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][6][0]) + 100 and \
(BOARD_POSITIONS[4][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[5][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][6][0])
self._board.set_top(BOARD_POSITIONS[4][0][1])
# row 6
elif (BOARD_POSITIONS[0][0][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][1][0]) and \
(BOARD_POSITIONS[5][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[6][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][0][0])
self._board.set_top(BOARD_POSITIONS[5][0][1])
elif (BOARD_POSITIONS[0][1][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][2][0]) and \
(BOARD_POSITIONS[5][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[6][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][1][0])
self._board.set_top(BOARD_POSITIONS[5][0][1])
elif (BOARD_POSITIONS[0][2][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][3][0]) and \
(BOARD_POSITIONS[5][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[6][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][2][0])
self._board.set_top(BOARD_POSITIONS[5][0][1])
elif (BOARD_POSITIONS[0][3][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][4][0]) and \
(BOARD_POSITIONS[5][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[6][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][3][0])
self._board.set_top(BOARD_POSITIONS[5][0][1])
elif (BOARD_POSITIONS[0][4][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][5][0]) and \
(BOARD_POSITIONS[5][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[6][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][4][0])
self._board.set_top(BOARD_POSITIONS[5][0][1])
elif (BOARD_POSITIONS[0][5][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][6][0]) and \
(BOARD_POSITIONS[5][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[6][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][5][0])
self._board.set_top(BOARD_POSITIONS[5][0][1])
elif (BOARD_POSITIONS[0][6][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][6][0]) + 100 and \
(BOARD_POSITIONS[5][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[6][0][1]):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][6][0])
self._board.set_top(BOARD_POSITIONS[5][0][1])
# row 7
elif (BOARD_POSITIONS[0][0][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][1][0]) and \
(BOARD_POSITIONS[6][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[6][0][1] + 100):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][0][0])
self._board.set_top(BOARD_POSITIONS[6][0][1])
elif (BOARD_POSITIONS[0][1][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][2][0]) and \
(BOARD_POSITIONS[6][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[6][0][1]) + 100:
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][1][0])
self._board.set_top(BOARD_POSITIONS[6][0][1])
elif (BOARD_POSITIONS[0][2][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][3][0]) and \
(BOARD_POSITIONS[6][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[6][0][1] + 100):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][2][0])
self._board.set_top(BOARD_POSITIONS[6][0][1])
elif (BOARD_POSITIONS[0][3][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][4][0]) and \
(BOARD_POSITIONS[6][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[6][0][1] + 100):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][3][0])
self._board.set_top(BOARD_POSITIONS[6][0][1])
elif (BOARD_POSITIONS[0][4][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][5][0]) and \
(BOARD_POSITIONS[6][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[6][0][1] + 100):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][4][0])
self._board.set_top(BOARD_POSITIONS[6][0][1])
elif (BOARD_POSITIONS[0][5][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][6][0]) and \
(BOARD_POSITIONS[6][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[6][0][1] + 100):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][5][0])
self._board.set_top(BOARD_POSITIONS[6][0][1])
elif (BOARD_POSITIONS[0][6][0] <= pygame.mouse.get_pos()[0] < BOARD_POSITIONS[0][6][0]) + 100 and \
(BOARD_POSITIONS[6][0][1] <= pygame.mouse.get_pos()[1] < BOARD_POSITIONS[6][0][1] + 100):
self._selected = True
self._board.set_cell_selected(True)
self._board.set_left(BOARD_POSITIONS[0][6][0])
self._board.set_top(BOARD_POSITIONS[6][0][1])
else:
self._board.set_cell_selected(False)
if self._selected is True:
if self._marble_in_cell() and self._board.get_marble().get_color() != RED:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
self._make_move('L')
elif event.key == pygame.K_RIGHT:
self._make_move('R')
elif event.key == pygame.K_UP:
self._make_move('F')
elif event.key == pygame.K_DOWN:
self._make_move('B')
self._board.get_screen().blit(self._display_white_captures(), (25, 60))
self._board.get_screen().blit(self._display_black_captures(), (510, 60))
if self._turn is not None and self._winner is None:
self._board.get_screen().blit(self._display_turn(), (295, 10))
if self._winner is not None:
self._board.get_screen().blit(self._display_winner(), (295, 10))
pygame.display.update()
def set_turn(self, player: object) -> None:
"""Sets turn to the Player whose turn it is."""
self._turn = player
def _make_move(self, direction: str) -> None:
"""Makes a move on the Board by shifting marble positions based on the selected Marble and the specified push
direction."""
if self._board.get_marble().get_color() == self._player_1.get_color():
player = self._player_1
other_player = self._player_2
else:
player = self._player_2
other_player = self._player_1
if (self._turn is None or self._turn.get_color() == self._board.get_marble().get_color()) and \
self._winner is None:
if self._is_valid(direction):
if self._is_valid_push(direction, self._board.get_marble().get_color()):
# get marble counts before move:
white_count_before, black_count_before, red_count_before = self._marble_count()
# make move:
self._push_marbles(direction)
# get marble counts after move:
white_count_after, black_count_after, red_count_after = self._marble_count()
# make sure move isn't undoing a previous move leading to exact same board state:
if player.get_previous_configuration() is not None and self._undone(player):
self._board.restore_previous_configuration()
else:
self.play_slide_sound()
self._board.set_cell_selected(False)
# check for red marble captures and set winner if 7 red marbles have been captured:
if red_count_after < red_count_before:
player.capture()
if player.get_captures() == 7:
self._winner = player.get_color_text()
# check if all of one player's marbles have been removed and set winner accordingly:
if white_count_after == 0:
self._winner = self._player_2.get_color_text()
elif black_count_after == 0:
self._winner = self._player_1.get_color_text()
self.set_turn(other_player)
self._board.set_previous_configuration(player)
self._board.set_previous_configuration()
def _undone(self, player) -> bool:
"""Returns True if the move being made is going to undo the other Player's previous move and return the Board
back to the exact same state."""
for marble_index, marble in enumerate(self._board.get_marbles_on_board()):
if marble.get_center() != player.get_previous_configuration()[marble_index].get_center():
return False
else:
return True
def _is_valid(self, direction: str) -> bool:
"""Returns True if the attempted move is valid, otherwise returns False. In order for an attempted move to
be valid, there must be an empty space or edge on the side the push is occurring from."""
if direction == 'L':
if self._board.get_selected_left() + 100 >= 725 or \
not self._marble_in_cell(left=self._board.get_selected_left() + 100,
top=self._board.get_selected_top()):
return True
else:
return False
elif direction == 'R':
if self._board.get_selected_left() - 100 < 25 or \
not self._marble_in_cell(left=self._board.get_selected_left() - 100,
top=self._board.get_selected_top()):
return True
else:
return False
elif direction == 'F':
if self._board.get_selected_top() + 100 > 800 or \
not self._marble_in_cell(left=self._board.get_selected_left(),
top=self._board.get_selected_top() + 100):
return True
else:
return False
else: # direction == 'B'
if self._board.get_selected_top() - 100 < 100 or \
not self._marble_in_cell(left=self._board.get_selected_left(),
top=self._board.get_selected_top() - 100):
return True
else:
return False
def _is_valid_push(self, direction: str, color: tuple, left=None, top=None, curr_marble=None) -> bool:
"""Recursively searches for the last marble in the chain of marbles being pushed to confirm that the Player is
not pushing their own Marble of the Board."""
if left is None:
left = self._board.get_selected_left()
top = self._board.get_selected_top()
curr_marble = self._board.get_marble()
if direction == 'R':
if not self._marble_in_cell(left=left + 100, top=top):
if left + 100 >= 725 and curr_marble.get_color() == color:
return False
else:
return True
else:
next_marble = self._board.get_marble(left=left + 100, top=top)
return self._is_valid_push(direction, color, left=left + 100, top=top, curr_marble=next_marble)
elif direction == 'L':
if not self._marble_in_cell(left=left - 100, top=top):
if left - 100 < 25 and curr_marble.get_color() == color:
return False
else:
return True
else:
next_marble = self._board.get_marble(left=left - 100, top=top)
return self._is_valid_push(direction, color, left=left - 100, top=top, curr_marble=next_marble)
elif direction == 'F':
if not self._marble_in_cell(left=left, top=top - 100):
if top - 100 < 100 and curr_marble.get_color() == color:
return False
else:
return True
else:
next_marble = self._board.get_marble(left=left, top=top - 100)
return self._is_valid_push(direction, color, left=left, top=top - 100, curr_marble=next_marble)
else:
if not self._marble_in_cell(left=left, top=top + 100):
if top + 100 >= 800 and curr_marble.get_color() == color:
return False
else:
return True
else:
next_marble = self._board.get_marble(left=left, top=top + 100)
return self._is_valid_push(direction, color, left=left, top=top + 100, curr_marble=next_marble)
def _marble_in_cell(self, left=None, top=None) -> bool:
"""Returns true if the selected cell has a marble in it, otherwise False is returned. By default, this method
will use the current selected cell to define left and top. Default arguments `left` and `top` can be changed
to specify a different left or top position."""
if left is None:
left = self._board.get_selected_left()
top = self._board.get_selected_top()
for marble in self._board.get_marbles_on_board():
if (left <= marble.get_center()[0] < left + 100) and (top <= marble.get_center()[1] < top + 100):
return True
return False
def _push_marbles(self, direction: str, left=None, top=None, curr_marble=None) -> None:
"""Recursively moves each Marble in the chain of Marbles being pushed one square over in the direction of the
push. If a valid Marble is knocked off the Board, it will be removed from play."""
if left is None:
left = self._board.get_selected_left()
top = self._board.get_selected_top()
curr_marble = self._board.get_marble()
if direction == 'R':
if not self._marble_in_cell(left=left + 100, top=top):
curr_marble.push_right()
if curr_marble.get_center()[0] > 725:
self.play_capture_sound()
del self._board.get_marbles_on_board()[self._board.get_marbles_on_board().index(curr_marble)]
return
else:
next_marble = self._board.get_marble(left=left + 100, top=top)
curr_marble.push_right()
return self._push_marbles(direction, left=left + 100, top=top, curr_marble=next_marble)
elif direction == 'L':
if not self._marble_in_cell(left=left - 100, top=top):
curr_marble.push_left()
if curr_marble.get_center()[0] < 25:
self.play_capture_sound()
del self._board.get_marbles_on_board()[self._board.get_marbles_on_board().index(curr_marble)]
return
else:
next_marble = self._board.get_marble(left=left - 100, top=top)
curr_marble.push_left()
return self._push_marbles(direction, left=left - 100, top=top, curr_marble=next_marble)
elif direction == 'F':
if not self._marble_in_cell(left=left, top=top - 100):
curr_marble.push_up()
if curr_marble.get_center()[1] < 100:
self.play_capture_sound()
del self._board.get_marbles_on_board()[self._board.get_marbles_on_board().index(curr_marble)]
return
else:
next_marble = self._board.get_marble(left=left, top=top - 100)
curr_marble.push_up()
return self._push_marbles(direction, left=left, top=top - 100, curr_marble=next_marble)
else:
if not self._marble_in_cell(left=left, top=top + 100):
curr_marble.push_down()
if curr_marble.get_center()[1] > 800:
self.play_capture_sound()
del self._board.get_marbles_on_board()[self._board.get_marbles_on_board().index(curr_marble)]
return
else:
next_marble = self._board.get_marble(left=left, top=top + 100)
curr_marble.push_down()
return self._push_marbles(direction, left=left, top=top + 100, curr_marble=next_marble)
def _marble_count(self) -> tuple:
"""Counts the number of white, black, and red Marbles that remain in play and returns a tuple containing the
counts of the Marbles in that order."""
white_count = 0
black_count = 0
red_count = 0
for marble in self._board.get_marbles_on_board():
if marble.get_color() == WHITE:
white_count += 1
elif marble.get_color() == BLACK:
black_count += 1
else:
red_count += 1
return white_count, black_count, red_count
def _display_white_captures(self):
"""Displays the number of red marbles captured by the Player using the white marbles."""
font = pygame.font.SysFont("Times New Roman", 30)
return font.render("White Captures: {}".format(self._player_1.get_captures()), True, WHITE)
def _display_black_captures(self):
"""Displays the number of red marbles captured by the Player using the Black marbles."""
font = pygame.font.SysFont("Times New Roman", 30)
return font.render("Black Captures: {}".format(self._player_2.get_captures()), True, WHITE)
def _display_turn(self):
"""Displays the color of the Player whose turn it is."""
font = pygame.font.SysFont("Times New Roman", 30)
return font.render("{}'s Turn".format(self._turn.get_color_text()), True, WHITE)
def _display_winner(self):
"""Displays the color of the winning Player"""
font = pygame.font.SysFont("Times New Roman", 30)
return font.render("{} Wins!".format(self._winner), True, WHITE)
@staticmethod
def play_capture_sound():
"""A sound used when a Marble is knocked off the board."""
pygame.mixer.Sound('marble_capture.mp3').play()
@staticmethod
def play_slide_sound():
"""A sound used when Marbles are pushed on the game Board."""
pygame.mixer.Sound('marble_slide.mp3').play().set_volume(0.15)
class Board(object):
"""Represents a Board to play the game Kuba on."""
def __init__(self) -> None:
"""Creates a Board object."""
pygame.display.set_caption("Kuba")
self._screen = pygame.display.set_mode(GAME_SCREEN)
self._marbles_on_board = [Marble(WHITE, MARBLE_POSITIONS[0][0]), Marble(WHITE, MARBLE_POSITIONS[0][1]),
Marble(BLACK, MARBLE_POSITIONS[0][5]), Marble(BLACK, MARBLE_POSITIONS[0][6]),
Marble(WHITE, MARBLE_POSITIONS[1][0]), Marble(WHITE, MARBLE_POSITIONS[1][1]),
Marble(BLACK, MARBLE_POSITIONS[1][5]), Marble(BLACK, MARBLE_POSITIONS[1][6]),
Marble(RED, MARBLE_POSITIONS[1][3]), Marble(RED, MARBLE_POSITIONS[2][2]),
Marble(RED, MARBLE_POSITIONS[2][3]), Marble(RED, MARBLE_POSITIONS[2][4]),
Marble(RED, MARBLE_POSITIONS[3][1]), Marble(RED, MARBLE_POSITIONS[3][2]),
Marble(RED, MARBLE_POSITIONS[3][3]), Marble(RED, MARBLE_POSITIONS[3][4]),
Marble(RED, MARBLE_POSITIONS[3][5]), Marble(RED, MARBLE_POSITIONS[4][2]),
Marble(RED, MARBLE_POSITIONS[4][3]), Marble(RED, MARBLE_POSITIONS[4][4]),
Marble(RED, MARBLE_POSITIONS[5][3]), Marble(BLACK, MARBLE_POSITIONS[5][0]),
Marble(BLACK, MARBLE_POSITIONS[5][1]), Marble(WHITE, MARBLE_POSITIONS[5][5]),
Marble(WHITE, MARBLE_POSITIONS[5][6]), Marble(BLACK, MARBLE_POSITIONS[6][0]),
Marble(BLACK, MARBLE_POSITIONS[6][1]), Marble(WHITE, MARBLE_POSITIONS[6][5]),
Marble(WHITE, MARBLE_POSITIONS[6][6])]
self._previous_configuration = copy.deepcopy(self._marbles_on_board)
self._selected_top = None
self._selected_left = None
self._cell_selected = False
def get_screen(self):
"""Returns the screen that Kuba is being played on."""
return self._screen
def get_selected_top(self) -> float:
"""Returns the top position of the current selected cell."""
return self._selected_top
def get_selected_left(self) -> float:
"""Returns the left position of the current selected cell."""
return self._selected_left
def get_marbles_on_board(self) -> list:
"""Returns a list of Marble objects that are current on the Board."""
return self._marbles_on_board
def get_marble(self, left=None, top=None):
"""Returns the Marble object contained in the currently selected cell. Default arguments 'left' and 'top' can
be used in order to get a Marble in a different cell than the one currently selected."""
if left is None:
left = self._selected_left
top = self._selected_top
for marble in self._marbles_on_board:
if (left <= marble.get_center()[0] < left + 100) and (top <= marble.get_center()[1] < top + 100):
return marble
def set_previous_configuration(self, player=None):
"""Sets the previous board configuration prior to the player's most recent move."""
previous_configuration = []
if player is None:
for marble in self._marbles_on_board:
previous_configuration.append(marble)
self._previous_configuration = copy.deepcopy(previous_configuration)
else:
for marble in self._marbles_on_board:
previous_configuration.append(marble)
player.set_previous_configuration(copy.deepcopy(previous_configuration))
def set_cell_selected(self, state: bool) -> None:
"""Set the _shade_cell attribute to True if a cell is selected and should be shaded. Otherwise, this attribute
should be set to False."""
self._cell_selected = state
def set_top(self, top: float) -> None:
"""Sets the top position corresponding to the current selected cell."""
self._selected_top = top
def set_left(self, left: float) -> None:
"""Sets the left position corresponding to the current selected cell."""
self._selected_left = left
def update_board(self):
"""Responsible for updating thew board."""
self._draw_board()
if self._cell_selected is True:
self._shade_cell(self._selected_left + 4, self._selected_top + 4)
self._draw_grid()
self._place_marbles()
def restore_previous_configuration(self):
"""Restores the previous configuration of the board."""
self._marbles_on_board = copy.deepcopy(self._previous_configuration)
def _draw_board(self):
"""Draws the rectangle that will act as the game Board."""
self._screen.fill(SCREEN_COLOR)
pygame.draw.rect(self._screen, GREY, pygame.Rect(25, 100, 700, 700))
pygame.draw.rect(self._screen, BLACK, pygame.Rect(25, 100, 700, 700), width=5)
def _draw_grid(self):
"""Draws the grid lines on the game Board that the Marbles will moved into."""
x_pos, y_pos = 25 + 100, 100 + 100
for loop_count in range(7):
pygame.draw.line(self._screen, BLACK, (x_pos, 100), (x_pos, 800), width=5)
pygame.draw.line(self._screen, BLACK, (25, y_pos), (725, y_pos), width=5)
x_pos += 100
y_pos += 100
def _shade_cell(self, left, top):
"""Shades a cell that has been selected."""
pygame.draw.rect(self._screen, LIGHT_GREY, pygame.Rect(left, top, 95, 95))
def _place_marbles(self):
"""Places Marble objects on the game board."""
for marble in self._marbles_on_board:
pygame.draw.circle(self._screen, marble.get_color(), marble.get_center(), MARBLE_RADIUS)
class Marble(object):
"""Represents a Marble used to play Kuba with."""
def __init__(self, color: tuple, center: tuple) -> None:
"""Creates a Marble object with color and center attributes. The center represents the position on the Board
where the center of the Marble will be placed."""
self._color = color
self._center = center
def get_center(self) -> tuple:
"""Returns the coordinates where the center of the Marble currently is on the Board. The first coordinate is the
x-coordinate, the second coordinate is the y-coordinate."""
return self._center
def get_color(self) -> tuple:
"""Returns the RGB tuple representing the Marble's color."""
return self._color
def set_center(self, center: tuple) -> None:
"""Repositions the center of the Marble on the Board."""
self._center = center
def push_right(self) -> None:
"""Pushes a Marble one square in the right-hand direction."""
self._center = (self._center[0] + 100, self._center[1])
def push_left(self) -> None:
"""Pushes a Marble one square in the left-hand direction."""
self._center = (self._center[0] - 100, self._center[1])
def push_up(self) -> None:
"""Pushes a Marble one square in the upwards direction."""
self._center = (self._center[0], self._center[1] - 100)
def push_down(self) -> None:
"""Pushes a Marble one square in the downwards direction."""
self._center = (self._center[0], self._center[1] + 100)
class Player(object):
"""Represents a Player in a game of Kuba."""
def __init__(self, color: tuple, color_text: str) -> None:
"Creates a Player object."
self._color = color
self._color_text = color_text
self._captures = 0
self._previous_configuration = None
def get_color(self):
"""Returns the Marble color that the Player is using."""
return self._color
def get_color_text(self):
"""Returns the string with the name of the Marble color that the Player is using."""
return self._color_text
def get_captures(self):
"""Returns the number of red marbles captures by the Player."""
return self._captures
def get_previous_configuration(self):
"""Returns the previous configuration of the game board."""
return self._previous_configuration
def set_previous_configuration(self, previous_configuration):
"""Sets the previous configuration of the game board."""
self._previous_configuration = previous_configuration
def capture(self):
"""Increments the number of red marbles captured by the Player by 1."""
self._captures += 1
| true |
8ef6e90a599738d1c899f040403d1808cdab35b5 | Python | DFTF-PConsole/AED-Labs-Algoritmos-LEI-2020 | /Arvore AVL (TP3 A1)/mainA1AVL-v3.py | UTF-8 | 12,940 | 3.15625 | 3 | [
"MIT"
] | permissive | # v3 - Melhoramentos: Retirei "in" em "x in array"; implementei pesquisa binaria; print_array; etc.
# v3 Abordagem Ate as folhas, depois de Baixo-para-Cima, Recursiva
# pai.direcao = return no filho da recursividade
# #### BIBLIOTECAS ####
import sys
# #### CONSTANTES ####
CMD_IN_LINHAS = "LINHAS"
CMD_OUT_NULO = "-1"
CMD_IN_ASSOC = "ASSOC"
CMD_OUT_NAOENCONTRADA = "NAO ENCONTRADA."
CMD_OUT_ENCONTRADA = "ENCONTRADA."
CMD_IN_TERMINADO = "TCHAU\n"
CMD_IN_TERMINADO2 = "TCHAU"
CMD_IN_TEXTO = "TEXTO\n"
CMD_IN_FIM = "FIM.\n"
CMD_OUT_GUARDADO = "GUARDADO."
# #### FUNCOES ####
class Elemento:
def __init__(self, input_palavra, input_ocorrencias):
self.palavra = input_palavra
self.ocorrencias = []
self.ocorrencias.append(input_ocorrencias)
def add_ocorrencia(self, count):
if not count == self.ocorrencias[-1]:
self.ocorrencias.append(count)
class No:
def __init__(self, input_elemento=None, input_esquerda=None, input_direita=None):
self.elemento = input_elemento
self.esquerda = input_esquerda
self.direita = input_direita
self.altura = 1
class ArvoreAVL:
def __init__(self, input_raiz=None):
self.raiz = input_raiz
def rotacao_esq(self, input_no_k1): # Faz rotacao simples com filho k2 a direita, E <- D
# ### FUNCAO ### Rotacao Simples Esquerda (Direcao <-)
no_k2 = input_no_k1.direita
no_k3 = no_k2.esquerda
no_k2.esquerda = input_no_k1
input_no_k1.direita = no_k3
input_no_k1.altura = 1 + max(self.get_altura(input_no_k1.esquerda), self.get_altura(input_no_k1.direita)) # Cumprir ordem para obter altura coerente
no_k2.altura = 1 + max(self.get_altura(no_k2.esquerda), self.get_altura(no_k2.direita)) # Altura anterior + 1 (para incluir o no atual)
return no_k2 # Nova raiz da sub-arvore
def rotacao_dir(self, input_no_k1): # Faz rotacao simples com filho k2 a esquerda, E -> D
# ### FUNCAO ### Rotacao Simples Direita ( Direcao ->)
no_k2 = input_no_k1.esquerda
no_k3 = no_k2.direita
no_k2.direita = input_no_k1
input_no_k1.esquerda = no_k3
input_no_k1.altura = 1 + max(self.get_altura(input_no_k1.esquerda), self.get_altura(input_no_k1.direita))
no_k2.altura = 1 + max(self.get_altura(no_k2.esquerda), self.get_altura(no_k2.direita))
return no_k2
def rotacao_esq_dir(self, input_no_k1): # Faz rotacao com filho k2 a direita | Faz rotacao com filho k2 a esquerda ?
# ### FUNCAO ### Rotacao Dupla Esquerda-Direita ( Direcao <- e ->)
input_no_k1.esquerda = self.rotacao_esq(input_no_k1.esquerda)
return self.rotacao_dir(input_no_k1)
def rotacao_dir_esq(self, input_no_k1): # Faz rotacao com filho k2 a esquerda | Faz rotacao com filho k2 a direita ?
# ### FUNCAO ### Rotacao Dupla Direita-Esquerda ( Direcao -> e <-)
input_no_k1.direita = self.rotacao_dir(input_no_k1.direita)
return self.rotacao_esq(input_no_k1)
def procura_palavra(self, input_palavra):
# ### FUNCAO ### Procura Palavra na Arvore e return esse elemento, se nao existe retorna: None
no = self.raiz
while no is not None:
if compara_str(input_palavra, no.elemento.palavra) == 0:
return no.elemento
elif compara_str(input_palavra, no.elemento.palavra) == 1:
no = no.direita
else:
no = no.esquerda
return None
def inserir_elemento(self, input_raiz, input_elemento): # input_raiz -> raiz ou no da sub-arvore
# ### FUNCAO ### Inserir Elementos na Arvore AVP, recursivamente, ate chegar as folhas nulas, inserindo-o
if input_raiz is None: # Insere o elemento
novo_no = No(input_elemento)
return novo_no
elif compara_str(input_raiz.elemento.palavra, input_elemento.palavra) == 1: # Se a str 1 (no da arvore) e maior
input_raiz.esquerda = self.inserir_elemento(input_raiz.esquerda, input_elemento)
else: # Se a str 2 (novo no) e maior
input_raiz.direita = self.inserir_elemento(input_raiz.direita, input_elemento)
input_raiz.altura = 1 + max(self.get_altura(input_raiz.esquerda), self.get_altura(input_raiz.direita)) # Altura anterior + 1 (para incluir o no atual)
# ----------------------- Verificar Equilibrio, fazer rotacoes para corrigir ----------------------
equilibrio = self.get_equilibrio(input_raiz)
if equilibrio > 1: # Lado Esquerdo MAIOR que o Direito (na sub-arvore do no atual: input_raiz)
if compara_str(input_raiz.esquerda.elemento.palavra, input_elemento.palavra) == 1: # str 1 (Palavra no->esquerdo) MAIOR que str 2 (Palavra nova inserida)
# Se Caminho entre Avo-Pai-Filho -> Esq-Esq
return self.rotacao_dir(input_raiz)
else: # str 2 (Palavra nova inserida) MAIOR que str 1 (Palavra no->esquerdo)
# Se Caminho entre Avo-Pai-Filho -> Esq-Dir
return self.rotacao_esq_dir(input_raiz)
if equilibrio < -1: # Lado Direito MAIOR que o Esquerdo (na sub-arvore do no atual: input_raiz)
if compara_str(input_raiz.direita.elemento.palavra, input_elemento.palavra) == 2: # str 1 (Palavra no->esquerdo) MAIOR que str 2 (Palavra nova inserida)
# Se Caminho entre Avo-Pai-Filho -> Dir-Dir
return self.rotacao_esq(input_raiz)
else: # str 2 (Palavra nova inserida) MAIOR que str 1 (Palavra no->esquerdo)
# Se Caminho entre Avo-Pai-Filho -> Dir-Esq
return self.rotacao_dir_esq(input_raiz)
return input_raiz # Sem rotacoes
def get_altura(self, input_no):
# ### FUNCAO ### Get Altura guardado no atributo do no, ou 0 se o no e nulo
if input_no is None:
return 0
return input_no.altura
def get_equilibrio(self, input_no):
# ### FUNCAO ### Get Equilibrio atraves da altura guardado no atributo do no, ou 0 se o no e nulo
if input_no is None:
return 0
return self.get_altura(input_no.esquerda) - self.get_altura(input_no.direita) # Equilibrio da sub-arvore
def compara_str(str1, str2):
# ### FUNCAO ### str1 maior: return 1, str2 maior: return 2, iguais: return 0
if str1 > str2: # Str1 Maior
return 1
elif str1 < str2: # Str2 Maior
return 2
else: # Iguais
return 0
def input_texto(arvore_avl):
# ### FUNCAO ### Le e manipula o texto do stdin ate CMD_IN_FIM
count = 0
for linha in sys.stdin:
if count == 0 and linha == "":
sys.exit("Erro - Sem Texto para input")
if linha == CMD_IN_FIM:
break
palavra = ""
for ch in linha:
if ch == '\n':
if len(palavra) > 0:
palavra = palavra.lower()
elemento = arvore_avl.procura_palavra(palavra)
if elemento is not None:
elemento.add_ocorrencia(count)
else:
elemento = Elemento(palavra, count)
arvore_avl.raiz = arvore_avl.inserir_elemento(arvore_avl.raiz, elemento)
palavra = ""
elif ch == ' ' or ch == '.' or ch == ',' or ch == ';' or ch == '(' or ch == ')':
if len(palavra) > 0:
palavra = palavra.lower()
elemento = arvore_avl.procura_palavra(palavra)
if elemento is not None:
elemento.add_ocorrencia(count)
else:
elemento = Elemento(palavra, count)
arvore_avl.raiz = arvore_avl.inserir_elemento(arvore_avl.raiz, elemento)
elemento = arvore_avl.procura_palavra(ch)
if elemento is not None:
elemento.add_ocorrencia(count)
else:
elemento = Elemento(ch, count)
arvore_avl.raiz = arvore_avl.inserir_elemento(arvore_avl.raiz, elemento)
palavra = ""
else:
palavra = palavra + ch
count += 1
print(CMD_OUT_GUARDADO)
return 0
def input_cmd(arvore_avl):
# ### FUNCAO ### Le, executa e escreve no stdout os comandos no stdin, ate CMD_IN_TERMINADO
for linha in sys.stdin:
if linha == CMD_IN_TERMINADO2:
break
elif linha == CMD_IN_TERMINADO:
break
elif linha == "":
break
elif (CMD_IN_LINHAS in linha) and (linha.index(CMD_IN_LINHAS) == 0):
palavra = linha[len(CMD_IN_LINHAS)+1:len(linha)-1]
palavra = palavra.lower()
elemento = arvore_avl.procura_palavra(palavra)
if elemento is not None:
print(print_array(elemento.ocorrencias))
else:
print(CMD_OUT_NULO)
elif (CMD_IN_ASSOC in linha) and (linha.index(CMD_IN_ASSOC) == 0):
palavras = linha.split(' ')
palavras[2] = (palavras[2])[:len(palavras[2])-1]
palavras[1] = palavras[1].lower()
elemento = arvore_avl.procura_palavra(palavras[1])
if elemento is not None:
if not (pesquisa_binaria(elemento.ocorrencias, int(palavras[2])) == -1):
print(CMD_OUT_ENCONTRADA)
else:
print(CMD_OUT_NAOENCONTRADA)
else:
print(CMD_OUT_NAOENCONTRADA)
else:
sys.exit("Erro - Interpretacao dos comandos pos-texto")
return 0
def pesquisa_binaria(array, valor):
# ### FUNCAO ### Pesquisa Binaria Classica num Array/Lista, input array e valor, return indice ou -1 se nao existir
inicio = 0
fim = len(array)-1
if fim == -1:
return -1
while inicio <= fim:
meio = inicio + (fim - inicio) // 2 # Divisao Real, Arredonda para baixo
if array[meio] == valor: # Valor esta no meio
return meio
elif array[meio] < valor: # Se valor e maior que o meio, ignora metade inferior
inicio = meio + 1
else: # Se for menor que o meio, ignora metade superior
fim = meio - 1
return -1 # Nao existe
def print_array(array):
# ### FUNCAO ### Transforma os dados num array numa string com espacos
string = ""
for num in array:
string = string + " " + str(num)
return string[1:]
def main():
# ### FUNCAO ### Funcao Principal
arvore_avl = ArvoreAVL()
if sys.stdin.readline() == CMD_IN_TEXTO:
input_texto(arvore_avl)
else:
sys.exit("Erro - Sem Comando Incial: " + CMD_IN_TEXTO)
input_cmd(arvore_avl)
return 0
if __name__ == '__main__':
# ### START ###
main()
| true |
b969069ac299f0e6b3058a2361e9230d0026b20a | Python | DAI-Lab/SteganoGAN | /steganogan/critics.py | UTF-8 | 1,578 | 2.84375 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
import torch
from torch import nn
class BasicCritic(nn.Module):
"""
The BasicCritic module takes an image and predicts whether it is a cover
image or a steganographic image (N, 1).
Input: (N, 3, H, W)
Output: (N, 1)
"""
def _conv2d(self, in_channels, out_channels):
return nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3
)
def _build_models(self):
return nn.Sequential(
self._conv2d(3, self.hidden_size),
nn.LeakyReLU(inplace=True),
nn.BatchNorm2d(self.hidden_size),
self._conv2d(self.hidden_size, self.hidden_size),
nn.LeakyReLU(inplace=True),
nn.BatchNorm2d(self.hidden_size),
self._conv2d(self.hidden_size, self.hidden_size),
nn.LeakyReLU(inplace=True),
nn.BatchNorm2d(self.hidden_size),
self._conv2d(self.hidden_size, 1)
)
def __init__(self, hidden_size):
super().__init__()
self.version = '1'
self.hidden_size = hidden_size
self._models = self._build_models()
def upgrade_legacy(self):
"""Transform legacy pretrained models to make them usable with new code versions."""
# Transform to version 1
if not hasattr(self, 'version'):
self._models = self.layers
self.version = '1'
def forward(self, x):
x = self._models(x)
x = torch.mean(x.view(x.size(0), -1), dim=1)
return x
| true |
cbfe581d394cd6d7fd543ddab38741aeb4441aa3 | Python | simonpf/llrte | /test/surface/plot_results_reflecting.py | UTF-8 | 1,177 | 2.8125 | 3 | [] | no_license | import numpy as np
import matplotlib.pyplot as plt
import xarray
#
# Lambertian surface
#
data = xarray.open_dataset("surface_lambertian.nc")
out = np.array(data.outgoing_directions)
outp = np.array(data.outgoing_positions)
inc = np.array(data.incoming_directions)
incp = np.array(data.incoming_positions)
thetas = np.arccos(-out[:, 0])
phis = np.arctan2(out[:, 1], out[:, 2])
f, axs = plt.subplots(1, 2)
ax = axs[0]
ax.hist(thetas, normed=True)
ax.set_ylabel("Frequency")
ax.set_xlabel(r"$\theta$")
ax = axs[1]
ax.hist(phis, normed=True)
ax.set_xlabel(r"$\phi$")
plt.tight_layout()
plt.savefig("lambertian_angles.png")
#
# Specular surface
#
data = xarray.open_dataset("surface_specular.nc")
out = np.array(data.outgoing_directions)
outp = np.array(data.outgoing_positions)
inc = np.array(data.incoming_directions)
incp = np.array(data.incoming_positions)
thetas = np.arccos(-out[:, 0])
phis = np.arctan2(out[:, 1], out[:, 2])
f, axs = plt.subplots(1, 2)
ax = axs[0]
ax.hist(thetas, normed=True)
ax.set_ylabel("Frequency")
ax.set_xlabel(r"$\theta$")
ax = axs[1]
ax.hist(phis, normed=True)
ax.set_xlabel(r"$\phi$")
plt.tight_layout()
plt.savefig("specular_angles.png")
| true |
2d684b367956a8f20b9cd89f20c219c4aad2c76d | Python | rst-workbench/rst-converter-service | /src/rstconverter/dis/codra.py | UTF-8 | 1,231 | 2.671875 | 3 | [
"BSD-3-Clause"
] | permissive |
import argparse
import os
import re
import sys
from rstconverter.dis.distree import DisRSTTree
EDU_START_RE = re.compile("^_!")
EDU_END_RE = re.compile("_!$")
TRIPLE_ESCAPE_RE = re.compile(r'\\\\\\"') # string contains a " char
class CodraRSTTree(DisRSTTree):
"""A CodraRSTTree is basically just a DisRSTTree with some added clean-up code.
The CODRA RST parser uses the same *.dis format that was used by the RST-DT corpus
and early versions of RSTTool, but it's string escaping is different.
"""
def __init__(self, dis_filepath, word_wrap=0, debug=False):
super(CodraRSTTree, self).__init__(dis_filepath, word_wrap=word_wrap, debug=debug)
self.cleanup_codra_edus()
def cleanup_codra_edus(self):
"""Remove leading/trailing '_!' from CODRA EDUs and unescape its double quotes."""
for leafpos in self.tree.treepositions('leaves'):
edu_str = self.tree[leafpos]
edu_str = EDU_START_RE.sub("", edu_str)
edu_str = TRIPLE_ESCAPE_RE.sub('"', edu_str)
edu_str = EDU_END_RE.sub("", edu_str)
self.tree[leafpos] = edu_str
# pseudo-function to create a document tree from a RST (.codra) file
read_codra = CodraRSTTree
| true |
0314a0e54cbaa7e2f90de2f2e7aec4418ac48403 | Python | shige-horiuchi/auto | /Python自動処理sample/chapter07/show_many_columns.py | UTF-8 | 257 | 2.90625 | 3 | [] | no_license | import pandas as pd
pat = 'display.expand_frame_repr'
pd.set_option(pat, False) #←1行に含まれる列を改行せずに表示
df = pd.read_csv('e-stat-10102.csv', encoding='utf-8', header=0)
print(df[:3]) #←先頭から3行だけ表示 | true |
e4eec6d7f73c275ff143f234847522ffbe65acfd | Python | EnochEronmwonsuyiOPHS/Y11Python | /Selection006.py | UTF-8 | 264 | 3.671875 | 4 | [] | no_license | #Selection006.py
#Enoch
age = int(input("Enter your age"))
if age >= 18:
print("You can vote")
if age == 17:
print("You can learn how to drive")
if age == 16:
print("You can buy a lottery ticket")
if age < 16:
print("You can go trick or treating")
| true |
c6bae881b4333fdb533a4da6f1126328b9ec0ebf | Python | AdamZhouSE/pythonHomework | /Code/CodeRecords/2341/60896/293160.py | UTF-8 | 298 | 2.734375 | 3 | [] | no_license | a=eval(input())
for i in range(0,a):
n=input()
temp=input().split(' ')
b=map(eval,temp)
list1=list(b)
temp=input().split(' ')
b=map(eval,temp)
list2=list(b)
list1+=list2
list1.sort()
for t in range(0,len(list1)):
print(list1[t],end=' ')
print('') | true |
4fb751a31bb0f3ae966bf859f3175d372f9e4a6e | Python | parasthiti/AI | /MachineLearning/Regression_Stock.py | UTF-8 | 1,753 | 2.59375 | 3 | [] | no_license | import pandas as pd
import quandl
import math, datetime
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
import pickle
from sklearn import preprocessing, svm
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
style.use('ggplot')
quandl.ApiConfig.api_key = 'vdYKgJkojqWAif1PwBYC'
df = quandl.get_table('WIKI/PRICES', ticker='GOOGL')
df = df[['date','adj_close', 'adj_volume']]
df = df.set_index('date')
#print(df.tail())
forecast_col = 'adj_close'
df.fillna(-99999, inplace=True)
forecast_out = int(math.ceil(0.01*len(df)))
df['label'] = df[forecast_col].shift(-forecast_out)
# print(df.head())
X = np.array(df.drop(['label'],axis=1))
X = preprocessing.scale(X)
X_predict = X[-forecast_out:]
X = X[:-forecast_out]
df.dropna(inplace=True)
y = np.array(df['label'])
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4)
# clf = LinearRegression()
# clf.fit(X_train, y_train)
# with open('stock_lregression.pickle','wb') as fh:
# pickle.dump(clf, fh)
pickle_in = open('stock_lregression.pickle', 'rb')
clf = pickle.load(pickle_in)
accuracy = clf.score(X_test, y_test)
forecast_set = clf.predict(X_predict)
print(forecast_set, accuracy, forecast_out)
df['Forecast'] = np.nan
df['adj_close'].plot()
df['Forecast'].plot()
last_date = df.iloc[-1].name
last_unix = last_date.timestamp()
one_day = 86400
next_unix = last_unix + one_day
for i in forecast_set:
next_date = datetime.datetime.fromtimestamp(next_unix)
next_unix += one_day
df.loc[next_date] = [np.nan for _ in range(len(df.columns)-1)] + [i]
plt.clf()
df['adj_close'].plot()
df['Forecast'].plot()
plt.legend(loc=4)
plt.xlabel('Date')
plt.ylabel('Price')
plt.show()
| true |
f6f8caa68425d0f006a7176766eeb2c1325d6257 | Python | log2timeline/plaso | /plaso/parsers/fish_history.py | UTF-8 | 3,556 | 2.6875 | 3 | [
"Apache-2.0"
] | permissive | # -*- coding: utf-8 -*-
"""Parser for fish history files."""
import os
import re
import yaml
from dfdatetime import posix_time as dfdatetime_posix_time
from dfvfs.helpers import text_file
from plaso.containers import events
from plaso.lib import errors
from plaso.parsers import manager
from plaso.parsers import interface
class FishHistoryEventData(events.EventData):
"""Fish history log event data.
Attributes:
command (str): command that was executed.
written_time (dfdatetime.DateTimeValues): date and time the entry was
written.
"""
DATA_TYPE = 'fish:history:entry'
def __init__(self):
"""Initializes event data."""
super(FishHistoryEventData, self).__init__(data_type=self.DATA_TYPE)
self.command = None
self.written_time = None
class FishHistoryParser(interface.FileObjectParser):
"""Parses events from Fish history files."""
NAME = 'fish_history'
DATA_FORMAT = 'Fish history file'
_ENCODING = 'utf-8'
# 50 MiB is the maximum supported fish history file size.
_MAXIMUM_FISH_HISTORY_FILE_SIZE = 50 * 1024 * 1024
_FILENAME = 'fish_history'
_YAML_FORMAT_RE_1 = re.compile(r'^- cmd: \S+')
_YAML_FORMAT_RE_2 = re.compile(r' when: [0-9]{9}')
def ParseFileObject(self, parser_mediator, file_object):
"""Parses a fish history file from a file-like object
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): a file-like object.
Raises:
WrongParser: when the file cannot be parsed.
"""
filename = parser_mediator.GetFilename()
if filename != self._FILENAME:
raise errors.WrongParser('Not a Fish history file.')
text_file_object = text_file.TextFile(file_object, encoding='utf-8')
header_line_1 = text_file_object.readline()
header_line_2 = text_file_object.readline()
if (not self._YAML_FORMAT_RE_1.match(header_line_1) or
not self._YAML_FORMAT_RE_2.match(header_line_2)):
raise errors.WrongParser('Not a valid fish history file.')
file_size = file_object.get_size()
if file_size > self._MAXIMUM_FISH_HISTORY_FILE_SIZE:
parser_mediator.ProduceExtractionWarning(
'Fish history file size: {0:d} exceeds maxmimum'.format(file_size))
return
file_object.seek(0, os.SEEK_SET)
try:
fish_history = yaml.safe_load(file_object)
except yaml.YAMLError as exception:
parser_mediator.ProduceExtractionWarning(
'Error reading YAML with error: {0:s}'.format(exception))
return
for entry_index, history_entry in enumerate(fish_history):
command = history_entry.get('cmd', None)
timestamp = history_entry.get('when', None)
if None in (command, timestamp):
parser_mediator.ProduceExtractionWarning(
'Unsupported history entry: {0:d}'.format(entry_index))
continue
if not isinstance(timestamp, int):
try:
timestamp = int(timestamp, 10)
except (TypeError, ValueError):
parser_mediator.ProduceExtractionWarning(
'Unsupported timestamp: {0!s} in history entry: {1:s}'.format(
timestamp, entry_index))
continue
event_data = FishHistoryEventData()
event_data.command = command
event_data.written_time = dfdatetime_posix_time.PosixTime(
timestamp=timestamp)
parser_mediator.ProduceEventData(event_data)
manager.ParsersManager.RegisterParser(FishHistoryParser)
| true |
8ae6581b6921f02ef5fc0f049b5f6814d19d3532 | Python | sensiTelemetria/telegram | /ruuvi/specified_tags.py | UTF-8 | 915 | 3.015625 | 3 | [] | no_license | from ruuvitag_sensor.ruuvi import RuuviTagSensor
import os
import datetime
# List of macs of sensors which data will be collected
# If list is empty, data will be collected for all found sensors
macs = ['D7:05:12:28:73:D9',]
# get_data_for_sensors will look data for the duration of timeout_in_sec
timeout_in_sec = 4
while 1:
datas = RuuviTagSensor.get_data_for_sensors(macs, timeout_in_sec)
# Dictionary will have lates data for each sensor
tags = datas['D7:05:12:28:73:D9']
#print(datas['D7:05:12:28:73:D9'])
for var in tags:
print(var +" : " +str( tags[var]) )
date = datetime.datetime.now()
print("Ano : " + str(date.year))
print("Mês : " + str(date.month))
print("dia : " + str(date.day))
print("hora : " + str(date.hour))
print("minuto : " + str(date.minute))
print("segundo : " + str(date.second))
print("\n\n--------------------------\n\n") | true |
cfd4ec2fd6b4051f0947c8dc3f82b005c746a70b | Python | AadeshSalecha/HackerRank---Python-Domain | /Strings/What'sYourName.py | UTF-8 | 249 | 3.53125 | 4 | [] | no_license | '''
Title : What's Your Name
Subdomain : Strings
Domain : Python
Author : Aadesh Salecha
Created : August 2016
'''
first = str(raw_input())
last = str(raw_input())
print "Hello " + first + " " + last + "! You just delved into python." | true |
07f76f4f6c59841f11b463d44ca565ed9988a67b | Python | zcgu/leetcode | /codes/31. Next Permutation.py | UTF-8 | 871 | 2.875 | 3 | [] | no_license | class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
pos = -1
for i in reversed(range(1, len(nums))):
if nums[i] > nums[i-1]:
pos = i
break
print pos
if pos == -1:
nums.sort()
return
minpos = -1
minnum = 2 ** 31 - 1
for i in range(pos, len(nums)):
if nums[i] > nums[pos-1] and nums[i] < minnum:
minnum = nums[i]
minpos = i
nums[pos-1], nums[minpos] = nums[minpos], nums[pos-1]
nums2 = nums[pos:]
nums2.sort()
for i in range(len(nums2)):
nums[i+pos] = nums2[i]
| true |
1471c6cca03a4ebe67ac6215d98fa87ee50d4322 | Python | Nox7atra/SimpleBuildsServer | /data_structures.py | UTF-8 | 1,357 | 2.828125 | 3 | [
"MIT"
] | permissive | import os
from datetime import datetime
time_pattern = "%H:%M:%S %d/%m/%Y"
default_iconsPath = "/icons/"
def format_bytes(size):
# 2**10 = 1024
power = 2**10
n = 0
power_labels = {0 : 'B', 1: 'KB', 2: 'MB', 3: 'GB', 4: 'TB'}
while size > power:
size /= power
n += 1
return "%.0f" % size, power_labels[n]
def isImage(extension):
return extension == ".png" or extension == ".jpg" or extension == ".svg"
class FileData:
def __init__(self, filename, abs_path):
self.href = filename
self.creationTime = datetime.fromtimestamp(os.path.getctime(abs_path)).strftime(time_pattern)
self.modificationTime = datetime.fromtimestamp(os.path.getmtime(abs_path)).strftime(time_pattern)
size = format_bytes(os.path.getsize(abs_path))
self.fileSize = size[0] + " " + size[1]
self.caption = os.path.basename(filename)
extension = os.path.splitext(filename)[1]
if extension == ".apk":
self.iconPath = os.path.join(default_iconsPath, "apk.png")
else:
if isImage(extension):
self.iconPath = filename
else:
self.iconPath = os.path.join(default_iconsPath, "file.png")
class DirectoryData:
def __init__(self, path):
self.href = path
self.caption = os.path.basename(path) | true |
fbee51ecd723559225a59ac2a9c2560bed06bc2b | Python | apurvTri123/pythonCardGame | /pythonCardGame.py | UTF-8 | 13,167 | 3.234375 | 3 | [] | no_license | import random
count = 1
discardedDeck = []
class Game:
def __init__(self):
self.Name = "" # make it cpu for computer
self.playerNumber = 0
self.score = 0
self.cardDeck = []
self.spellGod = True
self.spellRes = True
self.chance = False
def playerName(self):
global count
print("Enter a name for player : ", count)
self.Name = raw_input()
if(count == 1):
self.playerNumber = 1
count = 2
else:
self.playerNumber = 2
count = 1
def deal(self):
if(self.playerNumber == 2):
for i, v in enumerate(list1):
if(i % 2 == 0):
self.cardDeck.append(list1[i])
else:
for i, v in enumerate(list1):
if(i % 2 != 0):
self.cardDeck.append(list1[i])
# method playing and comparing cards
def playCard(self): # Called by method inside class with refference to object
# print("Debugger>>>>>1",player1.cardDeck,player2.cardDeck)
print(self.Name, "Your Card Is:")
# print("Debug>>>>2",self.cardDeck)
card = self.cardDeck.pop(0)
# print("Debug>>>3",self.cardDeck)
if(self.playerNumber == 1):
card2 = getCard(2)
else:
card2 = getCard(1)
# print("Debugger>>>>>4",player1.cardDeck,player2.cardDeck)
print("Name : ", card['Name'])
print("Rank : ", card['Rank'])
print("Weight : ", card['Weight'])
print("Height : ", card['Height'])
# print("Check",p1Deck)
ch = input(
"Choose power to play with [Press : 1->Rank 2->Weight 3->Height]")
global discardedDeck
# print("GlobalDiscard",discardedDeck)
discardedDeck.append(card)
discardedDeck.append(card2)
print("Rank check", card['Rank'] >
card2['Rank'], card['Rank'], card2['Rank'])
if(ch == 1):
if(card['Rank'] < card2['Rank']):
self.score = self.score+1
print (self.Name, " _Wins!! Score : ", self.score)
if(len(player2.cardDeck) > 0 and len(player1.cardDeck) > 0):
self.play()
else:
gameEnds()
elif(card['Rank'] > card2['Rank']):
if(self.playerNumber == 1):
obj = player2
else:
obj = player1
obj.score = obj.score+1
print(obj.Name, " Wins!! Score : ", obj.score)
if(len(player2.cardDeck) > 0 and len(player1.cardDeck) > 0):
obj.play()
else:
gameEnds()
if(ch == 2):
if(card['Weight'] > card2['Weight']):
self.score = self.score+1
print (player1.Name + " Wins!! Score : ", self.score)
if(len(player2.cardDeck) > 0 and len(player1.cardDeck) > 0):
self.play()
else:
gameEnds()
elif(card['Weight'] < card2['Weight']):
if(self.playerNumber == 1):
obj = player2
else:
obj = player1
obj.score = obj.score+1
print (obj.Name + " Wins!! Score : ", obj.score)
if(len(player2.cardDeck) > 0 and len(player1.cardDeck) > 0):
obj.play()
else:
gameEnds()
if(ch == 3):
# print("asc",card,card2,card['Height'] > card2['Height'],card['Height'] ,card2['Height'],type(card2['Height']),type(card['Height']))
if(card['Height'] > card2['Height']):
self.score = self.score+1
print (player1.Name + " Wins!! Score : ", self.score)
if(len(player2.cardDeck) > 0 and len(player1.cardDeck) > 0):
self.play()
else:
gameEnds()
elif(card['Height'] < card2['Height']):
if(self.playerNumber == 1):
obj = player2
else:
obj = player1
obj.score = obj.score+1
print (obj.Name + " Wins!! Score : ", obj.score)
if(len(player2.cardDeck) > 0 and len(player1.cardDeck) > 0):
obj.play()
else:
gameEnds()
else:
print("<---Invalid choice--->")
self.playCard()
def play(self):
print(self.Name + " please choose")
print("Press 1---->For playing your card")
print("Press 2---->For using God Spell")
print("Press 3---->For using Resurrection Spell")
choice = input("Your choice :")
if(choice == 1):
self.playCard()
elif(choice == 2):
if(self.spellGod):
self.spellGod = False
self.godSpell()
else:
print("God spell can only be used once in an entire game")
self.play()
elif(choice == 3):
if(self.spellRes == False):
print("You can only play a spell once")
self.play()
return
self.resurrectionSpell()
else:
print("Invalid choice")
self.play()
def godSpell(self):
# global discardedDeck
deck = []
if(self.playerNumber == 1):
deck = player2.cardDeck
else:
deck = player1.cardDeck
# print("Inside gods spell",deck)
if(len(discardedDeck) >= 0):
print(self.Name + " Please choose a card for 2nd player")
print("choose number between " + " 1 "+" and " + str(len(deck)))
ch = int(input("Enter : "))-1
if(ch < 0 or ch >= len(deck)):
print("Invalid Choice")
self.godSpell()
else:
self.afterGod(ch)
else:
print("No card in the discarde cards..Try later")
self.spellGod = True
self.play()
def afterGod(self, ch):
# name=""
obj = player1
if(self.playerNumber == 1):
card = player2.cardDeck[ch]
# name=player2.playerName
obj = player2
player2.cardDeck.remove(card)
player2.cardDeck.insert(0, card)
elif(self.playerNumber == 2):
card = player1.cardDeck[ch]
# name=player1.Name
obj = player1
player1.cardDeck.remove(card)
player1.cardDeck.insert(0, card)
print(obj.Name, " Please choose between continue play or resurrection spell")
print("Press 1-->for continue play and Press 2-->for resurrection spell")
# if(name=="CPU"):
# print("Check for cpu")
gameMode = input()
if(gameMode == 1):
self.play()
elif(gameMode == 2):
obj.resAfterGod()
else:
print("Pllease enter a valid choice-->")
self.afterGod(ch)
def resurrectionSpell(self):
global discardedDeck
random.shuffle(discardedDeck)
# print("Res---Spell discarded card-->",discardedDeck)
if len(discardedDeck) > 0:
self.spellRes = False
# print("Please choose card number for reserection--->",)
ch = random.randrange(0, len(discardedDeck)-1)
# print("Random card choosen for ",self.Name, " is ",discardedDeck[ch])
print("Card choosen for->", self.Name)
self.cardDeck.insert(0, discardedDeck[ch])
discardedDeck.remove(discardedDeck[ch])
else:
print("Empty discarded card deck please choose the spell later")
self.spellRes = True
self.play()
def resAfterGod(self):
global discardedDeck
random.shuffle(discardedDeck)
ch = random.randrange(0, len(discardedDeck)-1)
# name=""
obj = player1
# code repeat
if(self.playerNumber == 1):
# name=player2.playerName
obj = player2
else:
# name=player1.playerName
obj = player1
if(self.spellRes == False):
print("Reserection spell can only be used once by a player")
print(obj.Name, " please make next move")
obj.play()
print(obj.Name, " Please press 1 to allow the other player to play with new card and 2 to not allow")
action = input("Please provide Input ")
if(action == 1):
if(self.playerNumber == 1):
player2.cardDeck.insert(0, discardedDeck[ch])
else:
player1.cardDeck.insert(0, discardedDeck[ch])
obj.play()
elif(action == 2):
if(self.playerNumber == 1):
player2.cardDeck.insert(1, discarderdDeck[ch])
else:
player1.cardDeck.insert(1, discardedDeck[ch])
discardedDeck.remove(discardedDeck[ch])
obj.play()
else:
print("Invalid choice")
obj.play() # check for invalid entry
def gameEnds():
name = player1
global discardedDeck
discardedDeck = []
score = 0
if(player1.score > player2.score):
name = player1
score = player1.score
elif(player1.score == player2.score):
print("<---Its a Draw--->")
pageLoad()
else:
name = player2
# score = player2.score
print(name.Name, " wins !!!")
print("Score : ", name.score)
pageLoad()
def getCard(player):
# print("DEbufgger>>>",player)
if(player == 2):
# print("Removed from player 2....>>1",player2.cardDeck)
a = player2.cardDeck.pop(0)
# print("Removed from player 2",player2.cardDeck)
return(a)
else:
# print("Removed from player 1....>>1",player1.cardDeck)
a = player1.cardDeck.pop(0)
# print("Removed from player 1....>>2",player1.cardDeck)
return(a)
# print()
#toss winner starts the game
def chance():
# print("player1")
# print("player1>>>>>>>",player1.chance,player2.chance )
if(player1.chance):
player1.chance = False
player2.chance = True
player1.play()
elif(player2.chance):
player2.chance = False
player1.chance = True
player2.play()
def shuffelCards():
random.shuffle(list1)
#toss gamestart
def gamePlay():
while(True):
choice = input("Enter 1 to begin: ")
if(choice != 1):
print("Invalid choice")
else:
print("Game begins.....rolling dice for player one")
break
while(True):
rand1 = random.randrange(1, 6)
print("Dice roll---->", rand1)
rand2 = random.randrange(1, 6)
print("Player2 Dice Roll---->", rand2)
if(rand1 > rand2):
print("Player One wins...!!")
player2.chance = False
player1.chance = True
break
elif(rand2 > rand1):
print("Player Two wins...!!")
player2.chance = True
player1.chance = False
break
else:
print("Its a draw")
def cardCreation():
c1 = {'Name': 'Kane', 'Rank': 7,
'Height': '6.10', 'Weight': '410 pounds'}
c2 = {'Name': 'BigShow', 'Rank': 3,
'Height': '7.0', 'Weight': '500 pounds'}
c3 = {'Name': 'Lita', 'Rank': 8,
'Height': '5.11', 'Weight': '250 pounds'}
c4 = {'Name': 'Tori', 'Rank': 6, 'Height': '5.9', 'Weight': '230 pounds'}
c5 = {'Name': 'Stephni', 'Rank': 5,
'Height': '5.4', 'Weight': '210 pounds'}
c6 = {'Name': 'Stone Cold', 'Rank': 4,
'Height': '6.10', 'Weight': '350 pounds'}
c7 = {'Name': 'Rock', 'Rank': 1, 'Height': '6.2', 'Weight': '360 pounds'}
c8 = {'Name': 'Mike', 'Rank': 2, 'Height': '6.4', 'Weight': '365 pounds'}
# print("Sample test 1", c1)
# Inserting card in a list
global list1
list1 = [c1, c2, c3, c4, c5, c6, c7, c8]
# list1 = [c7, c8]
def pageLoad():
global player1
global player2
player1 = Game() # object of class
player2 = Game()
cardCreation() # Creating deck of card
shuffelCards() # Shuffelling card
player1.playerName() # Screen to take player name
player2.playerName() # same as above
player1.deal() # deal cards for player 1
player2.deal() # deal cards for player 2
gamePlay() # toss
chance() # Toss winner starts the game
pageLoad()
| true |
6948d1b12cdca304d36d358405a8ae99d1903cd7 | Python | DesertBot/DesertBot | /desertbot/modules/commands/RSS.py | UTF-8 | 9,879 | 2.546875 | 3 | [
"MIT",
"BSD-3-Clause"
] | permissive | import datetime
import dateutil.parser as dparser
import feedparser
from twisted.plugin import IPlugin
from zope.interface import implementer
from desertbot.message import IRCMessage
from desertbot.moduleinterface import IModule
from desertbot.modules.commandinterface import admin, BotCommand
from desertbot.response import IRCResponse
@implementer(IPlugin, IModule)
class RSS(BotCommand):
def triggers(self):
return ["rss"]
def actions(self):
return super(RSS, self).actions() + [("ping", 1, self.checkFeeds)]
def onLoad(self) -> None:
if "rss_feeds" not in self.storage:
self.storage["rss_feeds"] = {}
self.feeds = self.storage["rss_feeds"]
if "rss_channels" not in self.storage:
self.storage["rss_channels"] = []
self.channels = self.storage["rss_channels"]
def help(self, query):
"""
RSS command syntax:
.rss <feed_name> - fetch latest for feed name
.rss channels <channel_name> [<channel_name>]- send notifications to <channel_name> whenever a feed is updated
.rss follow <url> <feed_name> - start following <url> as <feed_name>
.rss unfollow <feed_name> - stop following <feed_name>
.rss toggle <feed_name> - toggle automatic posting of new RSS posts to channels
.rss list - list followed feeds
"""
helpDict = {
"channels": "{}rss channels <channel_name> [<channel_name>]- send notifications to <channel_name> whenever a feed is updated",
"follow": "{}rss follow <url> <feed_name> - Start following the RSS feed at <url> as <feed_name>",
"unfollow": "{}rss unfollow <feed_name> - Stop following the RSS feed at <url>",
"toggle": "{}rss toggle <feed_name> - Toggle displaying of new posts of the given RSS feed as chat messages",
"list": "{}rss list - List currently followed RSS feeds",
"": "{}rss <feed_name> - Display the latest post in the given RSS feed."
}
if len(query) == 1:
return ("{0}rss <feed_name>/channels/follow/unfollow/toggle/list - Manages RSS feeds and automatic updates of them"
" Use {0}help rss <subcommand> for more help.".format(self.bot.commandChar))
else:
if query[1].lower() in helpDict:
return helpDict[query[1].lower()].format(self.bot.commandChar)
else:
return ("{!r} is not a valid subcommand, use {}help rss for a list of subcommands"
.format(query[1], self.bot.commandChar))
def execute(self, message: IRCMessage):
if len(message.parameterList) == 0:
return IRCResponse(self.help(["rss"]), message.replyTo)
if message.parameterList[0].lower() == "channels":
return self._setChannels(message)
elif message.parameterList[0].lower() == "follow":
return self._followFeed(message)
elif message.parameterList[0].lower() == "unfollow":
return self._unfollowFeed(message)
elif message.parameterList[0].lower() == "toggle":
return self._toggleFeedSuppress(message)
elif message.parameterList[0].lower() == "list":
return self._listFeeds(message)
else:
feed = message.parameters.strip()
latest = self._getLatest(feed)
if latest is not None:
response = 'Latest {}: {} | {}'.format(latest["name"], latest["title"], latest["link"])
return IRCResponse(response, message.replyTo)
else:
return IRCResponse("{} is not an RSS feed I monitor, leave a tell if you'd like it added!".format(
message.parameters.strip()), message.replyTo)
def checkFeeds(self):
responses = []
for feedName, feedDeets in self.feeds.items():
newPost = self._updateFeed(feedName)
if newPost and not feedDeets["suppress"]:
for channel in self.channels:
response = "New {}! Title: {} | {}".format(feedName, feedDeets["lastTitle"], feedDeets["lastLink"])
responses.append(IRCResponse(response, channel))
return responses
def _updateFeed(self, feedName: str) -> bool:
"""
Returns True if feed has a new post, otherwise False
"""
feedDeets = self.feeds[feedName]
if feedDeets["lastCheck"] > (datetime.datetime.utcnow() - datetime.timedelta(minutes=10)).isoformat():
return False
self.feeds[feedName]["lastCheck"] = datetime.datetime.utcnow().isoformat()
response = self.bot.moduleHandler.runActionUntilValue("fetch-url", feedDeets["url"])
if not response:
self.logger.warning("Failed to fetch {!r}, either a server hiccuped "
"or the feed no longer exists".format(feedDeets["url"]))
return False
feed = feedparser.parse(response.content)
if len(feed["entries"]) > 0:
def datesort(item):
return dparser.parse(item["published"], fuzzy=True, ignoretz=True).isoformat()
entries = sorted(feed["entries"], key=datesort, reverse=True)
item = entries[0]
else:
self.logger.warning("The feed at {!r} doesn't have any entries, has it shut down?".format(feedDeets["url"]))
return False
itemDate = item["published"]
newestDate = dparser.parse(itemDate, fuzzy=True, ignoretz=True).isoformat()
if newestDate > feedDeets["lastUpdate"]:
self.feeds[feedName]["lastUpdate"] = newestDate
title = item["title"]
link = item["link"]
try:
shortLink = self.bot.moduleHandler.runActionUntilValue("shorten-url", link)
if shortLink is None:
self.logger.error("Failed to shorten {}".format(link))
except Exception:
self.logger.exception("Exception when trying to shorten URL {}".format(link))
else:
link = shortLink
if link == "":
link = "Failed to find link for latest entry in feed!"
self.feeds[feedName]["lastTitle"] = title
self.feeds[feedName]["lastLink"] = link
self.storage["rss_feeds"] = self.feeds
return True
return False
def _getLatest(self, feedName):
lowerMap = {name.lower(): name for name in self.feeds}
if feedName.lower() in lowerMap:
name = lowerMap[feedName.lower()]
self._updateFeed(name)
title = self.feeds[name]["lastTitle"]
link = self.feeds[name]["lastLink"]
return {
"name": name,
"title": title,
"link": link
}
else:
return None
@admin("[RSS] Only my admins may tell me what channels to send notifications to!")
def _setChannels(self, message: IRCMessage):
self.channels = message.parameterList[1:]
self.storage["rss_channels"] = self.channels
return IRCResponse("RSS notifications will now be sent to: {}".format(self.channels), message.replyTo)
@admin("[RSS] Only my admins may follow new RSS feeds!")
def _followFeed(self, message: IRCMessage):
try:
url = message.parameterList[1]
name = " ".join(message.parameterList[2:])
feed_object = {
"url": url,
"lastUpdate": (datetime.datetime.utcnow() - datetime.timedelta(days=365)).isoformat(),
"lastTitle": "",
"lastLink": "",
"lastCheck": (datetime.datetime.utcnow() - datetime.timedelta(minutes=10)).isoformat(),
"suppress": False
}
self.feeds[name] = feed_object
self.storage["rss_feeds"] = self.feeds
self._updateFeed(name)
return IRCResponse("Successfully followed {} at URL {}".format(name, url), message.replyTo)
except Exception:
self.logger.exception("Failed to follow RSS feed - {}".format(message.messageString))
# clean up if it already got saved, and the error was in _updateFeed
if name in self.feeds:
del self.feeds[name]
self.storage["rss_feeds"] = self.feeds
return IRCResponse("I couldn't quite parse that RSS follow, are you sure you did it right?",
message.replyTo)
@admin("[RSS] Only my admins may unfollow RSS feeds!")
def _unfollowFeed(self, message: IRCMessage):
name = " ".join(message.parameterList[1:])
if name in self.feeds:
del self.feeds[name]
self.storage["rss_feeds"] = self.feeds
return IRCResponse("Sucessfully unfollowed {}".format(name), message.replyTo)
else:
return IRCResponse("I am not following any feed named {}".format(name), message.replyTo)
@admin("[RSS] Only my admins may turn RSS feeds on and off!")
def _toggleFeedSuppress(self, message: IRCMessage):
name = " ".join(message.parameterList[1:])
if name in self.feeds:
self.feeds[name]["suppress"] = not self.feeds[name]["suppress"]
self.storage["rss_feeds"] = self.feeds
return IRCResponse(
"Successfully {}ed {}".format("suppress" if self.feeds[name]["suppress"] else "unsupress", name),
message.replyTo)
else:
return IRCResponse("I am not following any feed named {}".format(name), message.replyTo)
def _listFeeds(self, message: IRCMessage):
return IRCResponse("Currently followed feeds are: {}".format(", ".join(self.feeds.keys())), message.replyTo)
rss = RSS()
| true |
c08522fb490170ebd41a314640c0242585d532ab | Python | zihuaweng/leetcode-solutions | /leetcode_python/360.Sort_Transformed_Array.py | UTF-8 | 824 | 3.65625 | 4 | [] | no_license | # https://leetcode.com/problems/sort-transformed-array/
class Solution:
def sortTransformedArray(self, nums: List[int], a: int, b: int,
c: int) -> List[int]:
nums = [a * x * x + b * x + c for x in nums]
p1 = 0
p2 = len(nums) - 1
# decide which side to start filling res.
# if a < 0, value in two sides will be smaller, so we fill res from beginning
# if a > 0, value in two sides will be larger, so we fill res from the end
i, d = (p1, 1) if a < 0 else(p2, -1)
res = [0] * len(nums)
while p1 <= p2:
if nums[p1] * -d > nums[p2] * -d:
res[i] = nums[p1]
p1 += 1
else:
res[i] = nums[p2]
p2 -= 1
i += d
return res | true |
956196898857f0c27106b98806d49843d7542545 | Python | NonBorn/TensorFlow | /Logistic_Regression.py | UTF-8 | 3,497 | 3.140625 | 3 | [] | no_license | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
learning_rate = 0.01
training_epochs = 10
batch_size = 100
display_step = 1
def categorical_cross_entropy_loss(y,pred):
# # Minimize error using cross entropy
# # tf.reduce_mean(input_tensor, axis=None, keep_dims=False, name=None, reduction_indices=None) # Computes the mean of elements across dimensions of a tensor.
# # tf.reduce_sum(input_tensor, axis=None, keep_dims=False, name=None, reduction_indices=None) # Computes the sum of elements across dimensions of a tensor.
# # tf.log(x, name=None) # Computes natural logarithm of x element-wise.
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=1))
# # For brevity, let x = logits, z = labels. The logistic loss is z * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x))
# cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(targets=y, logits=tf.log(pred)))
return cost
# tf Graph Input
x = tf.placeholder(tf.float32, [None, 784]) # mnist data image of shape 28*28=784
y = tf.placeholder(tf.float32, [None, 10]) # 0-9 digits recognition => 10 classes
# Set model weights
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
# Construct model
pred = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax
# print(pred.get_shape())
cost = categorical_cross_entropy_loss(y,pred)
# Gradient Descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
# Test model
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
# Calculate accuracy
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# Initializing the variables
#init = tf.initialize_all_variables() # tf version < 1.0.0
init = tf.global_variables_initializer() # tf version == 1.0.0
with tf.Session() as sess:
sess.run(init)
epochs = []
tr_acc = []
test_acc = []
costs = []
for epoch in range(training_epochs):
avg_cost = 0.
avg_acc = 0.
total_batch = int(mnist.train.num_examples/batch_size)
for i in range(total_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
# Run optimization op (backprop) and cost op (to get loss value)
_, c, acc = sess.run(
[
optimizer,
cost,
accuracy
],
feed_dict={
x: batch_xs,
y: batch_ys
}
)
avg_cost += c / total_batch
avg_acc += acc / total_batch
# print(avg_cost)
if (epoch+1) % display_step == 0:
# cmpute test acc
tes_acc = sess.run( accuracy, feed_dict={
x: mnist.test.images,
y: mnist.test.labels
} )
print(
"Epoch: "+str('%04d' % (epoch+1))+
" cost="+"{:.9f}".format(avg_cost)+
" train accuracy="+"{:.9f}".format(avg_acc)+
" test accuracy="+"{:.9f}".format(tes_acc)
)
# add results to matrices
epochs.append(epoch+1)
tr_acc.append(avg_acc)
test_acc.append(tes_acc)
costs.append(avg_cost)
#
print("Optimization Finished!") | true |
67fd5fcd6e55e23d8c79ff7b868cefd526783486 | Python | SteveDoyle2/cpylog | /cpylog/html_utils.py | UTF-8 | 1,971 | 3.375 | 3 | [
"BSD-3-Clause"
] | permissive | """
defines:
- str_to_html(log_type, filename, lineno, msg)
"""
import datetime
import html
#message colors
DARK_ORANGE = '#EB9100'
COLORS = {
'COMMAND' : 'blue',
'ERROR' : 'Crimson',
'DEBUG' : DARK_ORANGE,
'WARNING' : 'purple',
'INFO' : 'green',
'EXCEPTION' : 'Crimson',
'CRITICAL' : 'Crimson',
}
def str_to_html(log_type, filename, lineno, msg):
"""
Converts the message to html
Parameters
----------
color : str
the HTML color
log_type : str
the message type
filename : str
the filename the message came from
lineno : int
the line number the message came from
message : str
the message
Returns
-------
html_msg : str
the HTML message
"""
tim = datetime.datetime.now().strftime('[%Y-%m-%d %H:%M:%S]')
#print('log_type = %s' % log_type)
#print('filename = %s' % filename)
#print('lineno = %s' % lineno)
#print('msg = %s' % msg)
#assert isinstance(msg, str), msg
msg = html.escape(msg)
#message colors
color = COLORS[log_type]
if filename.endswith('.pyc'):
filename = filename[:-1]
html_msg = get_html_msg(color, tim, log_type, filename, lineno, msg)
return html_msg
def get_html_msg(color, tim, log_type, filename, lineno, msg):
"""
converts the message to html
Parameters
----------
color : str
the HTML color
time : str
the time for the message
log_type : str
the message type
filename : str
the filename the message came from
lineno : int
the line number the message came from
message : str
the message
Returns
-------
html_msg : str
the HTML message
"""
# log_type, filename, lineno, msg
html_msg = r'<font color="%s"> %s %s : %s:%i</font> %s <br>' % (
color, tim, log_type, filename, lineno, msg.replace('\n', '<br>'))
return html_msg
| true |
786f6950521560b1af4d31646176724adb1f4321 | Python | simonesenechal/python-codes-2 | /Exerc.48.py | UTF-8 | 316 | 4.03125 | 4 | [] | no_license | # Exercicio 48
# 048: Faça um programa que calcule a soma entre
# todos os números que são múltiplos de três e que se encontram no intervalo de 1 até 500.
soma = 0
count = 0
for c in range(1, 501, 2):
if c % 3 == 0:
soma += c
count += 1
print(f'A soma total é de {count, soma}')
| true |
b2907c85bde903868e0f1d53ece858e3cbeb58e4 | Python | UelitonFreitas/TDD-BECK-KENT | /Python/test_framework.py | UTF-8 | 535 | 3.28125 | 3 | [] | no_license | class CasoDeTeste:
def __init__(self, nome):
self.nome = nome
def executa(self):
metodo = getattr(self, self.nome)
metodo()
class FoiTestado(CasoDeTeste):
def __init__(self, nome):
self.foiTestado = None
CasoDeTeste.__init__(self, nome)
def metodoDeTeste(self):
self.foiTestado = 1
class TesteDoCasoDeTeste(CasoDeTeste):
def testeExecutando(self):
teste = FoiTestado("metodoDeTeste")
assert(not teste.foiTestado)
teste.executa()
assert(teste.foiTestado)
TesteDoCasoDeTeste("testeExecutando").executa() | true |
0f11fe14d836b243af56f3dbf2fb4e9ab226547b | Python | zinking/acmcatchups | /leetcode/remove-duplicate-letter.py | UTF-8 | 1,069 | 3.21875 | 3 | [] | no_license | __author__ = 'awang'
class Solution(object):
def removeDuplicateLetters(self, s):
"""
:type s: str
:rtype: str
"""
d={}
n=len(s)
if n==0:return ""
for i in range(n):
c = s[i]
if d.has_key(c):
d[c].append(i)
else:
d[c]=[i]
self.found = False
self.items = sorted(d.items())
self.itemsn = len(d)
def dfs(row, r, tpos ):
if self.found:return
if len(r)==self.itemsn:
self.found = True
self.r = r
return
pos = self.items[row][1]
for p in pos:
if p>tpos:
oldr = r
r+=s[p]
dfs(row+1,r,p)
r=oldr
dfs(0,"",-1)
return self.r
s = Solution()
print s.removeDuplicateLetters("cbacdcbc")
print s.removeDuplicateLetters("bcabc")
print s.removeDuplicateLetters("")
print s.removeDuplicateLetters("abacb")
| true |
2f73a01e51a34936b5e955e1b81f775e55127b08 | Python | khodwe56/kaggle-birdsong-recognition | /src/loss/noisy_controlled_loss.py | UTF-8 | 1,874 | 2.609375 | 3 | [
"MIT"
] | permissive | import torch
from torch import nn
import torch.nn.functional as F
EPSILON_FP16 = 1e-5
class LSoftLoss(nn.Module):
def __init__(self):
super().__init__()
def forward(self, y_pred, y_true, beta):
with torch.no_grad():
y_true_updated = (beta*y_true+(1-beta)*y_pred) * y_true
return F.binary_cross_entropy(y_pred, y_true_updated, reduction='none')
class NoisyControlledLoss(nn.Module):
def __init__(self):
super().__init__()
self.noisy_loss_fn = LSoftLoss()
self.sigmoid = nn.Sigmoid()
self.loss_keys = ["zeros_loss", "ones_loss", "primary_loss", "overall_target_loss"]
def forward(self, output, target, beta, primary_beta):
target_all, target_primary = target
bs, s, o = target_all.shape
output = self.sigmoid(output)
output = torch.clamp(output, min=EPSILON_FP16, max=1.0-EPSILON_FP16)
output = output.reshape(bs*s,o)
target_all = target_all.reshape(bs*s,o)
noisy_loss = self.noisy_loss_fn(output, target_all, beta)
ones_loss = (((noisy_loss*target_all).sum()/(target_all.sum()+EPSILON_FP16)))*4/5
zeros_loss = (((noisy_loss*(1-target_all)).sum()/((1-target_all).sum()+EPSILON_FP16))) # * 5.0
if target_primary is not None:
primary_preds = output.view(-1)[[i*o+ix[0] for i, ix in enumerate(target_primary)]]
primary_loss = self.noisy_loss_fn(primary_preds, torch.ones_like(primary_preds), primary_beta)
primary_loss = primary_loss.mean()*1/5
else:
primary_loss = 0.0
overall_target_loss = (ones_loss + primary_loss)
loss = (zeros_loss + overall_target_loss)/2
return loss, {"zeros_loss": zeros_loss, "ones_loss":ones_loss, "primary_loss": primary_loss, "overall_target_loss": overall_target_loss} | true |
a72fa101eca7aa98b781a599cfbc04daca16f20d | Python | augmentedfabricationlab/afab_course | /02_python_basics/examples/02_lists_tuples_dictionaries/ex1_lists.py | UTF-8 | 385 | 3.40625 | 3 | [] | no_license | number_list = [1, 3, 4, 6, 8, 11, 13]
string_list = ["hello", "goodbye", "no more ideas", "etc."]
mixed_list = ["strings", 5, 6, 6.7, True, "etc."]
a = range(1,10)
print(list(a))
print(list(range(1,100,5)))
print(list(range(100, -10, -20)))
print(len(string_list))
print(string_list + number_list)
print(string_list*3)
print("hello" in string_list)
print("houdini" in string_list)
| true |
0ebba8dded479336373a14a97796454df9bfd905 | Python | Alexan101/oop | /calling_methods.py | UTF-8 | 1,982 | 3 | 3 | [] | no_license | import student as st
import mentor as mr
def separator():
print('=' * 60)
student1 = st.Student('Vasya', 'Pupkin', 'male')
student2 = st.Student('Pupka', 'Vasina', 'female')
lecturer1 = mr.Lecturer('Mr', 'Prepod')
lecturer2 = mr.Lecturer('Mrs', 'Uchilka')
reviewer1 = mr.Reviewer('Mr', 'Review1')
reviewer2 = mr.Reviewer('Mrs', 'Review2')
student1.courses_in_progress += ['Python'] + ['GIT']
student2.courses_in_progress += ['Python']
student1.finished_courses += ['English']
student2.finished_courses += ['GIT']
lecturer1.courses_attached += ['Python'] + ['GIT']
lecturer2.courses_attached += ['Python']
reviewer1.rate_hw(student1, 'Python', 7)
reviewer2.rate_hw(student1, 'Python', 6)
reviewer1.rate_hw(student1, 'GIT', 10)
reviewer2.rate_hw(student1, 'GIT', 10)
reviewer1.rate_hw(student2, 'Python', 9)
reviewer2.rate_hw(student2, 'Python', 8)
student1.rate_lecture(lecturer1, 'Python', 10)
student2.rate_lecture(lecturer1, 'Python', 10)
student1.rate_lecture(lecturer2, 'Python', 7)
student2.rate_lecture(lecturer2, 'Python', 5)
student1.rate_lecture(lecturer1, 'GIT', 8)
student2.rate_lecture(lecturer1, 'GIT', 9)
print(student1.return_grades())
print(student2.return_grades())
separator()
print(student1.average_rate('Python'))
print(student1.average_rate('GIT'))
print(student2.average_rate('Python'))
separator()
print(student1.average_rate_hw())
print(student2.average_rate_hw())
separator()
print(lecturer1.average_rate('Python'))
print(lecturer1.average_rate('GIT'))
print(lecturer2.average_rate('Python'))
separator()
print(lecturer1.average_rate_all())
print(lecturer2.average_rate_all())
separator()
print(student1 < student2)
separator()
print(lecturer1 < lecturer2)
separator()
print(st.average_rate_students('Python', student1, student2))
separator()
print(mr.average_rate_lecturers('Python', lecturer1, lecturer2))
separator()
print(reviewer1)
print(reviewer2)
separator()
print(student1)
print(student2)
separator()
print(lecturer1)
print(lecturer2) | true |
68750313474a6bdfc74bf1df70b029fa3c56eac6 | Python | sgriffith3/2020-12-07-PyNDE | /learning_dictionaries.py | UTF-8 | 651 | 3.890625 | 4 | [
"MIT"
] | permissive | #!/usr/bin/env python3
# key: value
# basic_dictionary = {"key": "value"}
# random_word = {"aglet": "the tip of a shoelace"}
# print(random_word)
# print(random_word["aglet"])
# myform = {"name": "Sam", "State": "PA"}
# print(myform)
# print(f"My name is {myform['name']} and I live in {myform['State']}")
my_car = {"year": 2011, "color": "white", "style": "minivan"}
print(type(my_car))
print(my_car)
print(f"I drive a {my_car['year']} {my_car['color']} {my_car['style']}")
print(my_car.get('year'))
print(my_car.get("drivetrain"))
print(my_car.keys())
print(my_car.values())
print(my_car.items())
#mystr = "This is a pretty 'cool' string"
| true |
a791bec6fadb29bf62dd6a7544800791ad93e7ce | Python | KoffieNu/slimmemeter-rpi | /rspiWebServer-1/appWebserver.py | UTF-8 | 1,201 | 2.546875 | 3 | [] | no_license | import datetime
import re
from flask import Flask, render_template, request
import sqlite3
import json
app = Flask(__name__)
numSamples = 100
def getDatetimeObject(iso_string):
timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', iso_string)
dt = datetime.datetime.strptime(timestamp, "%Y%m%dT%H%M%S.%f%z")
return dt
@app.route("/data.json")
def data():
global numSamples
conn = sqlite3.connect('../dsmr50.sqlite')
curs = conn.cursor()
if numSamples == 0:
curs.execute("select COUNT(id) from telegrams")
numSamples = curs.fetchall()[0][0]
curs.execute("SELECT `1-0:1.7.0`, `timestamp` FROM telegrams ORDER BY timestamp DESC LIMIT " + str(numSamples))
data = curs.fetchall()
#datalist = [(float(v.split('*')[0]), str(getDatetimeObject(ts).time())) for v, ts in data if '*' in v]
datalist = [(str(getDatetimeObject(ts)), float(v.split('*')[0])) for v, ts in data if '*' in v]
print(datalist)
return json.dumps(datalist)
@app.route("/graph")
def graph():
return render_template('graph.html')
if __name__ == '__main__':
app.run(
debug=True,
threaded=True,
host='127.0.0.1'
)
| true |
8ae659e405e6e426bf3832af780d600c48005c43 | Python | tnakaicode/jburkardt-python | /disk/disk_sample.py | UTF-8 | 3,455 | 2.921875 | 3 | [] | no_license | #! /usr/bin/env python3
#
def disk_sample ( center, r, n, seed ):
#*****************************************************************************80
#
## DISK_SAMPLE uniformly samples the unit disk.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 05 July 2018
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, real CENTER(2), the center of the disk.
#
# Input, real R, the radius of the disk.
#
# Input, integer N, the number of points.
#
# Input/output, integer SEED, a seed for the random
# number generator.
#
# Output, real X(2,N), the points.
#
import numpy as np
from r8_uniform_01 import r8_uniform_01
from r8vec_normal_01 import r8vec_normal_01
x = np.zeros ( [ 2, n ] )
for j in range ( 0, n ):
#
# Fill a vector with normally distributed values.
#
v, seed = r8vec_normal_01 ( 2, seed )
#
# Compute the length of the vector.
#
norm = np.sqrt ( v[0] ** 2 + v[1] ** 2 )
#
# Normalize the vector.
#
v[0] = v[0] / norm
v[1] = v[1] / norm
#
# Now compute a value to map the point ON the disk INTO the disk.
#
r2, seed = r8_uniform_01 ( seed )
x[0,j] = center[0] + r * np.sqrt ( r2 ) * v[0]
x[1,j] = center[1] + r * np.sqrt ( r2 ) * v[1]
return x, seed
def disk_sample_test ( center, r ):
#*****************************************************************************80
#
## DISK_SAMPLE_TEST tests DISK_SAMPLE.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 05 July 2018
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, real CENTER(2), the center of the disk.
#
# Input, real R, the radius of the disk.
#
import platform
import numpy as np
from disk_area import disk_area
from disk01_monomial_integral import disk01_monomial_integral
from monomial_value import monomial_value
print ( '' )
print ( 'DISK_SAMPLE_TEST' )
print ( ' Python version: %s' % ( platform.python_version ( ) ) )
print ( ' Use DISK_SAMPLE to estimate integrals in the disk' )
print ( ' with center (%g,%g) and radius %g' \
% ( center[0], center[1], r ) )
e_test = np.array ( [ \
[ 0, 0 ], \
[ 2, 0 ], \
[ 0, 2 ], \
[ 4, 0 ], \
[ 2, 2 ], \
[ 0, 4 ], \
[ 6, 0 ] ] )
seed = 123456789
print ( '' )
print ( ' N 1 X^2 Y^2 X^4 X^2Y^2 Y^4 X^6' )
print ( '' )
n = 1
while ( n <= 65536 ):
x, seed = disk_sample ( center, r, n, seed )
print ( ' %8d' % ( n ), end = '' )
for i in range ( 0, 7 ):
e = e_test[i,:]
value = monomial_value ( 2, n, e, x )
result = disk_area ( center, r ) * np.sum ( value[:] ) / n
print ( ' %14.6g' % ( result ), end = '' )
print ( '' )
n = 2 * n
if ( \
center[0] == 0.0 and \
center[1] == 0.0 and \
r == 1.0 ):
print ( '' )
print ( ' Exact', end = '' )
for i in range ( 0, 7 ):
e = e_test[i,:]
result = disk01_monomial_integral ( e )
print ( ' %14.6g' % ( result ), end = '' )
print ( '' )
#
# Terminate.
#
print ( '' )
print ( 'DISK01_SAMPLE_TEST' )
print ( ' Normal end of execution.' )
return
if ( __name__ == '__main__' ):
from timestamp import timestamp
import numpy as np
timestamp ( )
center = np.array ( [ 1.0, 2.0 ] )
r = 3.0
disk_sample_test ( center, r )
timestamp ( )
| true |
4da9e865d9043b4582214f77d71a79c69f37da66 | Python | sgosline/SAMNet | /src/parseinput_samnet.py | UTF-8 | 9,644 | 2.6875 | 3 | [
"MIT"
] | permissive | '''
parseinput_samnet.py
SAMNet module handles pre-processing of SAMNet files
Copyright (c) 2012 Sara JC Gosline
sgosline@mit.edu
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''
import re,math,networkx,collections,pickle
def get_weights_phen_source(phendatadict):
weights_source = collections.defaultdict(dict)
for treatment in phendatadict.keys(): #changed for multi-source
phendatalist=phendatadict[treatment]
for item in phendatalist:
#weight associated with the protein(from phenotypic data) and the source
#this weight is given in somephenfile (in the column following the protein)
fields = item.strip('\r\n').split('\t')
protein = fields[0].strip()
weight =math.fabs(float(fields[1].strip()))
if weight==0.0:
weight=0.000001
if weight==1.0:
weight=0.999999
weights_source[treatment][protein] = weight
#keys of this dictionary will be all proteins from the genes of the phenotypic dataset
return weights_source
def by_comm_into_one_dict(argument_file_containing_comm,doUpper=False):
'''
Takes multiple file arguments but parses them into separate elements of a dictionary
New function for multi-source
'''
argument = argument_file_containing_comm
lines=[line.strip() for line in open(argument)]
alldata=dict()
treats=set()
mrna=set()
for l in lines:
arr=l.strip().split()
m=arr[1].strip()
if doUpper:
m=m.upper()
treats.add(arr[0])
if arr[0]+'_treatment' not in alldata:
alldata[arr[0]+'_treatment']=[]
alldata[arr[0]+'_treatment'].append(m+'\t'+arr[2])
mrna.add(m)
#print ','.join(mrna)
return alldata,[a for a in treats],[a for a in mrna]
def get_direct_target_weights(targ_dict):
'''
Takes as input a dictionary of tab-delimited files (opened as list) with mRNA targets and weights
for a single miRNA
'''
targ_dict=collections.defaultdict(dict)#changed for multi source
for treatment in targ_dict.keys():
targs=targ_dict[treatment]
for line in targs:
[mrna,weight]=re.split('\t',line.strip())
w=float(weight)
if(w==0.0):
w=0.000001
if w==1.0:
w=0.999999
targ_dict[treatment][mrna+'mrna']=math.fabs(w)
return targ_dict
def multiple_args_into_one_list(arguments_separated_by_comma):
arguments = arguments_separated_by_comma
#make a list of all the arguments given
list_of_datasets = arguments.split(",")
#initialize the list that will hold data from all datasets
alldata = []
if len(list_of_datasets)==0 or list_of_datasets=='':
return alldata
#go through the list of datasets
for dataset in list_of_datasets:
if dataset=='':
continue
onedataset = open (dataset, 'r')
#put each line of the dataset into a list that will contain data from all datasets
lines = onedataset.readlines()
for line in lines:
if '@' not in line:
alldata.append(line)
return alldata
def multiple_args_into_one_dict(arguments_separated_by_comma,treatmentNames=''):
'''
Takes multiple file arguments but parses them into separate elements of a dictionary
New function for multi-source
'''
arguments = arguments_separated_by_comma
#make a list of all the arguments given
list_of_datasets = arguments.split(",")
alldata = collections.defaultdict(list)
if len(list_of_datasets)==0 or list_of_datasets=='':
return alldata
#initialize the list that will hold data from all datasets
if(len(list_of_datasets)>1):
treatlist=['treatment'+str(count) for count in range(len(list_of_datasets))]
else:
treatlist=['treatment']
allt=treatmentNames.split(',')
if(len(allt)!=len(list_of_datasets)):
print "List of treatments does not equal list of files, using default naming"
elif len(allt[0])>0:
for i in range(len(allt)):
treatlist[i]=allt[i]+'_treatment'
#go through the list of datasets
for dataset in range(len(list_of_datasets)):
if list_of_datasets[dataset]=='':
continue
onedataset = open (list_of_datasets[dataset], 'r')
#put each line of the dataset into a list that will contain data from all datasets
lines = onedataset.readlines()
for line in lines:
if '@' not in line:
alldata[treatlist[dataset]].append(line)
return alldata
def filter_ppi(ppi_network,list_of_prots,updateIds=''):
'''
Filters protein interaction network by list of proteins for tissue-specific analysis
'''
prots=[i.strip() for i in list_of_prots.readlines()]
# print prots[1:10]
print "Filtering network of with",str(ppi_network.number_of_nodes()),"nodes and",str(ppi_network.number_of_edges()),"edges with list of",str(len(prots)),"proteins"
for p in ppi_network.nodes():
if(p not in prots):
#ppi_network.delete_node(p)
ppi_network.remove_node(p)
print "Network now has",str(ppi_network.number_of_nodes()),'nodes and',str(ppi_network.number_of_edges()),'edges'
return ppi_network
'''
These two functions normalize responseNet dictionaries or networks
'''
def renormalizeNetworkweights(ppi,type='ecdf'):
'''
Takes networkx encoded graph and replaces edge weights with those that are normalized to fall between
0 and 1
'''
all_weights=[ppi.get_edge_data(x[0],x[1])['weight'] for x in ppi.edges()]
#for each unique weight create a dictionary lookup to replace weight with normalized weight
wdict={}
for w in all_weights:
if w not in wdict.keys():
wdict[w]=float(len([y for y in all_weights if y<=w]))/float(len(all_weights))
#iterate through and replace edgeweights
for x in ppi.edges():
ppi.get_edge_data(x[0],x[1])['weight']=wdict[ppi.get_edge_data(x[0],x[1])['weight']]
return ppi
def renormalizeDictionaryweights(ppi,type='ecdf'):
'''
Takes networkx encoded graph and replaces edge weights with those that are normalized to fall between
0 and 1
'''
all_weights=ppi.values()
# print all_weights[0:5]
#for each unique weight create a dictionary lookup to replace weight with normalized weight
wdict={}
for w in all_weights:
sw=str(w)
if sw not in wdict.keys():
if type=='ecdf':
wdict[sw]=float(len([y for y in all_weights if y<=w]))/float(len(all_weights))
elif type=='probability': ##this assumes they sum to 1
wdict[sw]=float(w)/float(sum(all_weights))
elif type=='fraction': ##fraction of max
wdict[sw]=float(w)/float(max(all_weights))
# print wdict
#iterate through and replace edgeweights
for x in ppi.keys():
if str(ppi[x]) in wdict.keys():
ppi[x]=wdict[str(ppi[x])]
return ppi
def get_ppi_network(networkfile,doUpper=False):
'''
First figure out if the file is a pickle or a text file, then make into network if text
networkfile: text or pickle file
doupper: make uppercase if try and in text file
'''
#figure out file format
ext=networkfile.split('.')[-1]
# print 'Determined '+networkfile+' is PKL, loading...'
try:
ppinet=pickle.load(open(networkfile,'rU'))
##now test for object type
if type(ppinet) is networkx.Graph or type(ppinet) is networkx.DiGraph:
print 'Unpickled is networkX, returning'
else:
print 'Pickled object unknown, returning empty digraph'
ppinet=networkx.DiGraph()
except:
print networkfile+' is Not pickle, assuming text'
ppinet=networkx.DiGraph()
for row in open(networkfile,'rU').readlines():
arr=row.strip().split()
if len(arr)!=3:
continue
prot1=arr[0]
prot2=arr[1]
if doUpper:
prot1=prot1.upper()
prot2=prot2.upper()
weight=float(arr[2])
if weight==1.0:
weight=0.999999
ppinet.add_edge(prot1,prot2,{'weight':weight})
ppinet.add_edge(prot2,prot1,{'weight':weight})
print "Returning "+str(ppinet.number_of_edges())+' PPI interaction scores'
return ppinet
| true |
55d288204671710dc6d8ec17a7b905f9ce1cfb6d | Python | loganyu/leetcode | /problems/2491_divide_players_into_teams_of_equal_skill.py | UTF-8 | 1,515 | 4.125 | 4 | [] | no_license | '''
You are given a positive integer array skill of even length n where skill[i] denotes the skill of the ith player. Divide the players into n / 2 teams of size 2 such that the total skill of each team is equal.
The chemistry of a team is equal to the product of the skills of the players on that team.
Return the sum of the chemistry of all the teams, or return -1 if there is no way to divide the players into teams such that the total skill of each team is equal.
Example 1:
Input: skill = [3,2,5,1,3,4]
Output: 22
Explanation:
Divide the players into the following teams: (1, 5), (2, 4), (3, 3), where each team has a total skill of 6.
The sum of the chemistry of all the teams is: 1 * 5 + 2 * 4 + 3 * 3 = 5 + 8 + 9 = 22.
Example 2:
Input: skill = [3,4]
Output: 12
Explanation:
The two players form a team with a total skill of 7.
The chemistry of the team is 3 * 4 = 12.
Example 3:
Input: skill = [1,1,2,3]
Output: -1
Explanation:
There is no way to divide the players into teams such that the total skill of each team is equal.
Constraints:
2 <= skill.length <= 105
skill.length is even.
1 <= skill[i] <= 1000
'''
class Solution:
def dividePlayers(self, skill: List[int]) -> int:
team_skill = 2 * sum(skill) // len(skill)
chemistry = 0
count = Counter(skill)
for v, c in count.items():
if c != count[team_skill - v]:
return -1
chemistry += c * v * (team_skill-v)
return chemistry // 2
| true |
606b7466b96e57536079fe159dfe6c74a8744133 | Python | shen-huang/selfteaching-python-camp | /exercises/1901040018/1001S02E05_array.py | UTF-8 | 102 | 2.671875 | 3 | [] | no_license | l=list(range(10))
l.reverse()
l1=(str(i) for i in l)
l2=''.join(l1)
l3=l2[1:8]
l4=l3[::,-1]
print(l4)
| true |
66d2d5858a8b30c5beee56f1f64147e19e2b05d6 | Python | Sree-Vandana/AI-final-project | /Expectimax/main_2048game.py | UTF-8 | 3,955 | 3.40625 | 3 | [] | no_license | from game_board import GameBoard
from ai import AI
from random import randint, seed
import numpy as np
dirs = {
0: "UP",
1: "DOWN",
2: "LEFT",
3: "RIGHT"
}
# python main_cli > output.txt
stepCount_256Arr = []
stepCount_512Arr = []
stepCount_1024Arr = []
stepCount_2048Arr = []
stepCount_4096Arr = []
gameMaxValues = []
totalGames = 50
class CLIRunner:
def __init__(self):
self.board = GameBoard()
self.ai = AI()
self.init_game()
# self.print_board()
self.run_game()
self.over = False
def init_game(self):
self.insert_random_tile()
self.insert_random_tile()
def checkValue(self, param):
elem_to_find = param
return any(elem_to_find in sublist for sublist in self.board.grid)
"""
Player tries to solve the game by merging the tiles together by choosing best move
computer tries to insert random tiles at random location
"""
def run_game(self):
turn_count = 0
step_count_256 = 0
step_count_512 = 0
step_count_1024 = 0
step_count_2048 = 0
step_count_4096 = 0
while True:
turn_count += 1
move = self.ai.get_move(self.board)
self.board.move(move)
self.insert_random_tile()
if step_count_256 == 0 and self.checkValue(256):
step_count_256 = turn_count
if step_count_512 == 0 and self.checkValue(512):
step_count_512 = turn_count
if step_count_1024 == 0 and self.checkValue(1024):
step_count_1024 = turn_count
if step_count_2048 == 0 and self.checkValue(2048):
step_count_2048 = turn_count
if step_count_4096 == 0 and self.checkValue(4096):
step_count_4096 = turn_count
if len(self.board.get_available_moves()) == 0:
print("- Game Over (max tile / max score): " + str(self.board.get_max_tile()))
gameMaxValues.append(self.board.get_max_tile())
self.print_board()
break
stepCount_256Arr.append(step_count_256)
stepCount_512Arr.append(step_count_512)
stepCount_1024Arr.append(step_count_1024)
stepCount_2048Arr.append(step_count_2048)
stepCount_4096Arr.append(step_count_4096)
if step_count_2048 != 0:
print("- GAME WON -")
print("- Step at which 1st 2048 occurred: ", step_count_2048)
print("")
else:
print("- GAME LOST -")
print("- NO 2048 -")
print("")
"""
Print the 4 X 4 board / grid
"""
def print_board(self):
for i in range(4):
for j in range(4):
print("%6d " % self.board.grid[i][j], end="")
print("")
print("")
"""
This function helps us to insert random 2 tiles at different locattions
Initially value can be 2 or 4
"""
def insert_random_tile(self):
if randint(0,99) < 100 * 0.9:
value = 2
else:
value = 4
cells = self.board.get_available_cells()
pos = cells[randint(0, len(cells) - 1)] if cells else None
if pos is None:
return None
else:
self.board.insert_tile(pos, value)
return pos
def saveToFile(fileName, arrayValue):
a_file = open(fileName, "w")
np.savetxt(a_file, arrayValue, delimiter=',')
a_file.close()
if __name__ == '__main__':
for i in range(totalGames):
print("------ Game Number: ",i+1,"------")
CLIRunner()
saveToFile("step256.txt", stepCount_256Arr)
saveToFile("step512.txt", stepCount_512Arr)
saveToFile("step1024.txt", stepCount_1024Arr)
saveToFile("step2048.txt", stepCount_2048Arr)
# saveToFile("step4096.txt", stepCount_4096Arr)
saveToFile("maxValuesList.txt", gameMaxValues)
| true |
2c6d859adb5cfdf64e7abd8ff608ece3210a9308 | Python | seekever/VideoSummary | /video_summary/models/model_interface.py | UTF-8 | 4,151 | 2.890625 | 3 | [
"MIT"
] | permissive | """ The module for the model's interface."""
import logging
from PyQt5 import QtCore
# Logger
LOGGER_NAME = 'App.Models.Interface'
LOG = logging.getLogger(LOGGER_NAME)
class ModelInterface:
"""
The model's interface.
...
Attributes
----------
next : signal
the signal to change to the next window
previous : signal
the signal to change to the previous window
Methods
-------
load_context()
load the windows' context
save_context()
save the window's context
reload_conditional_format()
reload the format of the conditional widgets
check_data()
check if all context data is correct
update_scenes_analysis_progress_bar(value)
update the progress bar of the scenes analysis
update_objects_analysis_progress_bar(value)
update the progress bar of the objects analysis
update_subtitles_analysis_progress_bar(value)
update the progress bar of the subtitles analysis
update_resume_progress_bar(value)
update the progress bar of the resume
previous_window()
save context and pass to the previous window
next_window()
save context and pass to the next window
"""
# Signals
next = QtCore.pyqtSignal()
previous = QtCore.pyqtSignal()
def __init__(self, *args, **kwargs):
super().__init__(*args, *kwargs)
self.hide()
def load_context(self):
""" The method to load the windows' context."""
def save_context(self):
""" The method to save the windows' context."""
def reload_conditional_format(self):
""" The method to reload the format of the conditional widgets."""
def check_data(self):
""" The method to check if all context data is correct."""
def update_scenes_analysis_progress_bar(self, value):
"""
Method that update the progress bar of the scenes analysis.
Parameters
----------
value : int
the progress bar value (0 - 100)
"""
LOG.debug('updating scenes analysis progress bar')
self.sceneAnalysisBar.setValue(value)
LOG.debug('scenes analysis progress bar updated: %s / 100', value)
def update_objects_analysis_progress_bar(self, value):
"""
Method that update the progress bar of the objects analysis.
Parameters
----------
value : int
the progress bar value (0 - 100)
"""
LOG.debug('updating objects analysis progress bar')
self.objectAnalysisBar.setValue(value)
LOG.debug('objects analysis progress bar updated: %s / 100', value)
def update_subtitles_analysis_progress_bar(self, value):
"""
Method that update the progress bar of the subtitles analysis.
Parameters
----------
value : int
the progress bar value (0 - 100)
"""
LOG.debug('updating subtitles analysis progress bar')
self.subtitleAnalysisBar.setValue(value)
LOG.debug('subtitles analysis progress bar updated: %s / 100', value)
def update_resume_progress_bar(self, value):
"""
Method that update the progress bar of the resume.
Parameters
----------
value : int
the progress bar value (0 - 100)
"""
LOG.debug('updating resume progress bar')
self.resumeBar.setValue(value)
LOG.debug('resume progress bar updated: %s / 100', value)
def previous_window(self):
""" Method that save context and pass to the previous window."""
LOG.debug('previousButton clicked')
self.save_context()
LOG.debug('changing to previous window')
self.hide()
self.previous.emit()
LOG.info('window changed to the previous')
def next_window(self):
""" Method that save context and pass to the next window."""
LOG.debug('nextButton clicked')
self.save_context()
LOG.debug('changing to next window')
self.hide()
self.next.emit()
LOG.info('window changed to the next')
| true |
cb2829fc637598496730137cc7ebffda93865dd8 | Python | SuyashVerma2311/micromouse_maze_solver | /pkg_tf_micromouse/scripts/obstacle.py | UTF-8 | 1,664 | 2.71875 | 3 | [
"MIT"
] | permissive | import rospy
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry
from tf import transformations
import numpy as np
class Obstacle(object):
def __init__(self, delta_err=3):
self.sub = rospy.Subscriber('/my_mm_robot/laser/scan', LaserScan, self.clbk_laser)
self.sub_odom = rospy.Subscriber('/odom', Odometry, self.clbk_odom)
self.dist2wall = None
self.lcr = None # left-center-right
self.position = None
self.yaw = None
def clbk_laser(self, msg):
# print("size: ", len(msg.ranges))
self.dist2wall = [
round(100*min(min(msg.ranges[0:71]), 100)),
round(100*min(min(msg.ranges[72:143]), 100)),
round(100*min(min(msg.ranges[144:215]), 100)),
round(100*min(min(msg.ranges[216:287]), 100)),
round(100*min(min(msg.ranges[288:359]), 100)),
]
self.lcr = [self.dist2wall[4], self.dist2wall[2], self.dist2wall[0]]
def clbk_odom(self, msg):
# position
self.position = msg.pose.pose.position
# yaw
quaternion = (
msg.pose.pose.orientation.x,
msg.pose.pose.orientation.y,
msg.pose.pose.orientation.z,
msg.pose.pose.orientation.w)
euler = transformations.euler_from_quaternion(quaternion)
self.yaw = (euler[2]* 180.0) / np.pi
def get_state(self):
return {"pos": self.position, "yaw": self.yaw }
def display(self):
print("d2w: ", self.dist2wall)
print("lcr: ", self.lcr)
print("pos: ", self.position)
print("yaw: ", self.yaw) | true |
5fc72ff4256225dfaa0e0aca91ad58b5deaba226 | Python | stonecoldhughes/dare | /data_analysis/analyze.py | UTF-8 | 6,950 | 2.625 | 3 | [] | no_license | #The purpose of this file is to obtain data runs and then call
#another script to run a simple statistical analysis
import xml.etree.ElementTree as xml
import subprocess
import argparse
import sys
import os
#Use autogen.py to build an executable
def make_test_executable(config, mode):
if(mode == 'trace'):
config_xml = config.trace_config_xml
elif(mode == 'autotune'):
config_xml = config.autotune_config_xml
cmd = [config.python_ex, config.autogen_script, '-c', config_xml]
p = subprocess.Popen(cmd, cwd = config.dare_dir)
p.communicate()
#Build the test executable
cmd = ['make']
p = subprocess.Popen(cmd, cwd = config.test_dir)
p.communicate()
return
def run_trace_executable(cmd, src, destination, iterations, config):
for i in range(iterations):
p = subprocess.Popen(cmd, cwd = config.test_dir)
p.communicate()
#Save output to this directory
os.rename(config.test_dir + '/' + src,\
this_dir + '/' + destination)
return
def run_autotune_executable(args, stdin_args, iterations, config):
for i in range(iterations):
p = subprocess.Popen(
args.params,\
cwd = config.test_dir,\
stdin = subprocess.PIPE,\
stdout = subprocess.PIPE)
out = p.communicate(stdin_args)
os.rename(config.test_dir + '/' + config.autotune_test_output,\
this_dir + '/' + config.autotune_test_output)
return
def analyze_data(args, config):
#Output files are now ready for analysis
p = subprocess.Popen([config.python_ex,\
config.compare_script,\
'-t',\
config.trace_test_output,\
'-c',\
config.control_test_output,\
'-a',\
config.autotune_test_output])
out = p.communicate()
return
class config_class:
def __init__(self):
self.python_ex = ''
self.dar_dir = ''
self.test_dir = ''
self.test_ex = ''
self.autogen_script = ''
self.trace_config_xml = ''
self.autotune_config_xml = ''
self.autotune_test_output = ''
self.trace_test_output = ''
self.control_test_output = ''
self.control_script = ''
def parse_xml_config():
tree = xml.parse(args.xml)
root = tree.getroot()
tag = root.find('python_ex')
config = config_class()
if(tag != None):
config.python_ex = tag.text.strip()
else:
print('python_ex tag not present. Location of python executable')
sys.exit()
tag = root.find('dare_dir')
if(tag != None):
config.dare_dir = tag.text.strip()
else:
print('dare_dir tag not present. Location of DARE directory')
sys.exit()
tag = root.find('test_dir')
if(tag != None):
config.test_dir = tag.text.strip()
else:
print('test_dir tag not present. Location of autotune and trace testing'\
+ ' directory.')
sys.exit()
tag = root.find('test_ex')
if(tag != None):
config.test_ex = tag.text.strip()
else:
print('test_ex tag not present. Name of executable under test.')
sys.exit()
tag = root.find('autogen_script')
if(tag != None):
config.autogen_script = tag.text.strip()
else:
print('autogen_script tag not present. Name of DARE autogenerator script')
sys.exit()
tag = root.find('trace_config_xml')
if(tag != None):
config.trace_config_xml = tag.text.strip()
else:
print('trace_config_xml tag not present. XML config file for DARE tracer')
sys.exit()
tag = root.find('autotune_config_xml')
if(tag != None):
config.autotune_config_xml = tag.text.strip()
else:
print('autotune_config_xml not present. XML config file for DARE autotuner')
sys.exit()
tag = root.find('trace_test_output')
if(tag != None):
config.trace_test_output = tag.text.strip()
else:
print('trace_test_output tag not present. DARE output file for trace run')
sys.exit()
tag = root.find('control_test_output')
if(tag != None):
config.control_test_output = tag.text.strip()
else:
print('control_test_output tag not present. DARE output file for control')
sys.exit()
tag = root.find('autotune_test_output')
if(tag != None):
config.autotune_test_output = tag.text.strip()
else:
print('autotune_test_output tag not present. DARE output file for autotune')
sys.exit()
tag = root.find('compare_script')
if(tag != None):
config.compare_script = tag.text.strip()
else:
print('compare_script tag not present. Python script to compare runs.')
sys.exit()
this_dir = os.getcwd()
return config
#Main code
#Get command line arguments
parser = argparse.ArgumentParser()
parser.add_argument('--params', nargs = 8,\
help = 'function, m, m_add, n, n_add, iterations, seed, '\
+ ' tile_size',\
required = True)
parser.add_argument('-e', '--execution_ratio',\
help = 'specify an execution_ratio for the autotuner',\
default = '2:2')
parser.add_argument('-x', '--xml',\
help = 'XML config file for settings',\
required = True)
args = parser.parse_args()
#Read the XML config file
config = parse_xml_config()
#Build the tracing library.
make_test_executable(config, 'trace')
#Insert the executable before the params
args.params.insert(0, config.test_ex)
#Run a control test
run_trace_executable(args.params,\
config.trace_test_output,\
config.control_test_output,\
2,\
config)
#Run the trace test
run_trace_executable(args.params,\
config.trace_test_output,\
config.trace_test_output,\
2,
config)
#Build the autotune library
make_test_executable(config, 'autotune')
tile_size = args.params[-1]
args.params[-1] = '-1'
stdin_args = '2 execution_ratio {execution_ratio} tile_size {tile_size}'\
.format(tile_size = tile_size,\
execution_ratio = args.execution_ratio).encode('utf-8')
#Run the autotune pass
run_autotune_executable(args, stdin_args, 2, config)
analyze_data(args, config)
| true |
c771c6d7cb1e614227672e92a4cd696d113e4654 | Python | won-hyw/CodingTest | /문제05.py | UTF-8 | 704 | 3.828125 | 4 | [] | no_license | # 1부터 number까지 몇 번 박수를 쳐야 하는지 반환
def solution(number):
count = 0
for i in range(1, number + 1): # for(int i=1; i<number+1)
current = i
temp = count
while current != 0:
if current % 10 % 3 == 0 and current % 10 != 0:
count += 1
current = current // 10
return count
# 카운터 = 0
#
# for num in range(1, a+1):
# # 해당하는 숫자가 박수를 몇 번 치는지
# while num:
# if num % 10 == 3 or num % 10 == 6 or num % 10 == 9:
# 카운터 += 1
# num = num // 10
# The following is code to output testcase.
number = 40
ret = solution(number)
print(ret)
| true |
660f8eb80cab70da9fd2b49ef7b98952508f84d0 | Python | Labbeti/MLU | /mlu/utils/typing_/classes.py | UTF-8 | 1,118 | 3 | 3 | [
"MIT"
] | permissive |
from abc import ABC
from torch.utils.data.dataset import Dataset
from typing import Iterable, Protocol, Sized, Union, runtime_checkable
class SizedIterable(Sized, Iterable, Protocol):
"""
Class that inherit from Sized and Iterable protocols classes.
Subclasses must implements '__iter__' and '__len__' methods.
"""
pass
@runtime_checkable
class SizedDatasetLike(Protocol):
"""
Class that inherit from Sized and add the '__getitem__' method of a dataset.
Subclasses must implements '__getitem__' and '__len__' methods.
"""
def __getitem__(self, idx):
raise NotImplemented('Abstract method')
def __len__(self) -> int:
raise NotImplemented('Abstract method')
class SizedDatasetSubclass(Dataset, ABC):
def __len__(self) -> int:
raise NotImplemented('Abstract method')
@staticmethod
def __instancecheck__(obj) -> bool:
return SizedDatasetLike.__subclasscheck__(type(obj))
@staticmethod
def __subclasscheck__(cls) -> bool:
if issubclass(cls, Dataset) and hasattr(cls, '__len__'):
return True
else:
return False
SizedDataset = Union[SizedDatasetLike, SizedDatasetSubclass]
| true |
6e23a1e76ce536e3d085ac58025565da14d15a05 | Python | mnot/tarawa | /http/lib/header/registry.py | UTF-8 | 3,211 | 2.65625 | 3 | [] | no_license | """
http.header.registry - HTTP Header Field Registry
This module provides a metaclass and functions that together implement a
centralised registry of HTTP header field names and the implementations
for their values.
"""
__license__ = """
Copyright (c) 1999-2006 Mark Nottingham <mnot@pobox.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
__revision__ = "$Id: filelist.py,v 1.15 2002/11/19 13:12:27 akuchling Exp $"
field_map = {}
header_name_map = {}
def get_field_name(instr):
"""
Given a header field name in any case, return its properly
capitalised version.
@param instr: token
@type instr: string
@return: HTTP header field-name
@rtype: string
"""
return header_name_map.get(instr.lower(), instr.capitalize())
def new_field(name, error_handler=None, **keywords): #TODO: make into a factory to manage error handler and registration state?
"""
Return an appropriate FieldValue instance for the given
(case-insensitive) field-name.
@param name: field-name
@type name: string
@param error_handler: handler for header parsing errors
@type error_handler: L{ErrorHandler} instance
@param keywords: Extra options for the field
@return: empty instance
@rtype: L{FieldValue}
"""
field = field_map.get(get_field_name(name), None)
if field is not None:
return field(error_handler=error_handler, **keywords)
else:
from .field_types import UnknownHeader
return UnknownHeader(error_handler=error_handler, **keywords)
class FieldValueType(type):
"""
Type for FieldValues that populates field_map and header_name_map, to keep track
of field names and their mapping to FieldValue-derived classes.
"""
def __new__(mcs, name, bases, dict_):
cls = super(FieldValueType, mcs).__new__(mcs, name, bases, dict_)
if dict_.has_key('field_name'):
field_map[dict_['field_name']] = cls
header_name_map[dict_['field_name'].lower()] = dict_['field_name']
if dict_.has_key('_parse'):
cls._parse = classmethod(dict_['_parse'])
if dict_.has_key('_asString'):
cls._asString = classmethod(dict_['_asString'])
return cls
| true |
1c1a31e99cdd455bdee709276e7c4ab1bb0211ef | Python | AxelSiliezar/ME021-Python | /Me021-Python/HW02/HW02_01.py | UTF-8 | 477 | 4.28125 | 4 | [] | no_license | import math
Ang_1 = input ("Enter value for first angle: ") #value in degrees
Ang_1 = float (Ang_1)
Ang_2 = input ("Enter value for second angle: ") #value in degrees
Ang_2 = float (Ang_2)
ang_1 = Ang_1*(math.pi/180) #convert to radians
ang_2 = Ang_2*(math.pi/180) #convert to radians
cos1 = math.cos(ang_1)
cos2 = math.cos(ang_2)
if (cos1 > cos2):
print (cos1,Ang_1)
elif (cos1 < cos2):
print (cos2,Ang_2)
else:
print ("Both angles are the same")
| true |
15ad768be6c1fc726c275642673b7329365646be | Python | jg1141/nzpug20210721 | /setup.py | UTF-8 | 4,765 | 2.828125 | 3 | [
"MIT"
] | permissive | # setup.py
# Created 20210524 1537
# Invoke with %run "C:\\setup.py"
# Modified (see version)
VERSION = "20210720 2217 "
import datetime
import humanize
import numpy as np
import os
import pandas as pd
import plotly.express as px
import pyperclip
import re
import sidetable
import snowflake.connector
import time
from snowflake.connector.pandas_tools import write_pandas
from dotenv import load_dotenv
_ = load_dotenv()
# Get non-null counts
pd.options.display.max_info_rows = 16907850
# Connection string
conn = snowflake.connector.connect(
user=os.getenv('user'),
password=os.getenv('password'),
account=os.getenv('account'),
warehouse=os.getenv('warehouse'),
database=os.getenv('database'),
schema=os.getenv('schema')
)
# Execute a statement that will generate a result set.
cur = conn.cursor()
def compare_sets(list1, list2):
"""Make a count of the intersections of two sets, A and B"""
set1 = set(list1)
set2 = set(list2)
set2_intersection_set1 = set2.intersection(set1)
result = {'IN A':[len(set1), len(set2_intersection_set1), round(len(set1)/len(set1)*100,1), round(len(set2_intersection_set1)/len(set2)*100,1)]}
result['IN B'] = [len(set2_intersection_set1), len(set2), round(len(set2_intersection_set1)/len(set1)*100,1), round(len(set2)/len(set2)*100,1)]
result['NOT IN A'] = [0, len(set2 - set1), 0, round(len(set2 - set1)/len(set2)*100,1)]
result['NOT IN B'] = [len(set1 - set2), 0, round(len(set1 - set2)/len(set1)*100,1), 0]
df = pd.DataFrame.from_dict(result, orient='index', columns=['A', 'B', '% of A', '% of B'])
return df
def d(vars):
"""List of variables starting with string "df" in reverse order. Usage: d(dir())
@vars list of variables output by dir() command
"""
list_of_dfs = [item for item in vars if (item.find('df') == 0 and item.find('_') == -1 and item != 'dfs')]
list_of_dfs.sort(key=lambda x:int(re.sub("[^0-9]", "", x.replace('df',''))) if len(x) > 2 else 0, reverse=True)
return list_of_dfs
def e(start_time):
"""Return human readable time delta
@start_time time to compare to current time
"""
print(f'Time now: {datetime.datetime.now().strftime("%Y-%m-%d %H:%M")}')
print(f"Time since start: {humanize.naturaldelta(time.monotonic() - start_time)}")
def execute(sql):
"""Execute a SQL command"""
start_time = time.monotonic()
_ = cur.execute(sql)
end_time = time.monotonic()
elapsed = end_time - start_time
print(f"Elapsed time {elapsed:.2f}")
return
def find_col_with(df, char_to_find):
"""Return column index of first column containing char_to_find
@char_to_find character to search for in column name
"""
first_column_with_char_to_find = [col for col in df.columns if col.find(char_to_find) > -1][0]
return list(df.columns).index(first_column_with_char_to_find)
def find_max_order(df, start_col=1):
"""Find the max value in each column and use it to put columns in rank order
@start_col Index of starting column (typically 1 as first column -- column 0 -- is a date or label)
"""
return list(df[df.columns[start_col:]].max().sort_values(ascending=False).keys())
def find_percentage_total(df, start_col=1):
"""Find total and percent of total for columns of Pandas dataframe
@start_col Index of starting column (typically 1 as first column -- column 0 -- is a date or label)
"""
# Get values for col1,col2 and col3
total = pd.Series(data=np.zeros(len(df)))
col_count = len(df.columns)
for i in range(start_col, col_count):
total += df.iloc[:,i]
df.insert(len(df.columns), 'total', total)
for i in range(start_col, col_count + 1):
pct_of_total = round((df.iloc[:,i]/total)*100, 2)
# Create Pandas DF with new column of pct_of_total
df.insert(len(df.columns),f"{df.columns[i]} %", pct_of_total)
# Pull original dataframe to show total and %
return df
def query(sql):
"""Run a SQL query and fetch result into Pandas DataFrame"""
start_time = time.monotonic()
_ = cur.execute(sql)
df = cur.fetch_pandas_all()
end_time = time.monotonic()
elapsed = end_time - start_time
print(f"Elapsed time {elapsed:.2f}")
return df
def t(title_string):
"""Add "as at {today}" to title. Usage: t(title_sting)
@title_string text to preceed the "as at" part
"""
today = datetime.datetime.today().strftime('%d %b %Y')
title = f"{title_string} as at {today}"
print(title)
pyperclip.copy(title)
print("(now on clipboard)")
return title
start_time = time.monotonic()
print(f"Setup Complete v {VERSION}")
| true |
789d9cfad51ba0bda57a449592832b86c40dfef1 | Python | psnakhwa/Python-Exercises | /Python Coding Exercises/zeromatrix.py | UTF-8 | 622 | 3.75 | 4 | [] | no_license | #Zero Matrix in python
#ctci 1.8
def nullifyRow(matrix,row):
for j in range(len(matrix[0])):
matrix[row][j]=0
def nullifyCol(matrix,col):
for i in range(len(matrix)):
matrix[i][col]=0
def setZeros(matrix):
row = [None]*len(matrix)
col = [None]*len(matrix[0])
for i in range(len(row)):
for j in range(len(col)):
if matrix[i][j]==0:
row[i]=True
col[j]=True
#Nullify Row
for i in range(len(row)):
if row[i]:
nullifyRow(matrix,i)
#Nullify Col
for j in range(len(col)):
if col[j]:
nullifyCol(matrix,j)
return matrix
matrix = [[1,2,3],[1,0,3],[1,1,1],[0,1,1]]
print setZeros(matrix) | true |
6b0c2d402071557bddbf0375a5b517dd3e363575 | Python | sevenreek/mysterious-complete | /TimerServer/roomController.py | UTF-8 | 6,529 | 2.71875 | 3 | [] | no_license | from CONFIGURATION import CFG_DEFAULT_TIME
from logger import Logger
import datetime
STATE_READY = 0
STATE_RUNNING = 1
STATE_PAUSED = 2
STATE_STOPPED = 3
# All events(RoomEvent) are passed to the roomcontroller which handles them calling appropriate public functions in gpio, display and timer.
# The room controller holds the current GameState
class RoomEventListener():
def raiseEvent(self, event):
pass
class RoomEvent():
EVT_SERVER_PLAY = 0xA000
EVT_SERVER_PAUSE = 0xA001
EVT_SERVER_SETTIME = 0xA002
EVT_SERVER_ADDTIME = 0xA003
EVT_SERVER_STOP = 0xA004
EVT_SERVER_RESET = 0xA005
EVT_TIMER_HITZERO = 0xB000
EVT_GPIO_FINISHED = 0xC000
EVT_GPIO_PLAY = 0xC001
EVT_GPIO_PAUSE = 0xC002
EVT_GPIO_STOPRESET = 0xC003
EVT_GPIO_ADDTIME = 0xC004
namedict = {
0xA000 : 'EVT_SERVER_PLAY' ,
0xA001 : 'EVT_SERVER_PAUSE' ,
0xA002 : 'EVT_SERVER_SETTIME' ,
0xA003 : 'EVT_SERVER_ADDTIME' ,
0xA004 : 'EVT_SERVER_STOP' ,
0xA005 : 'EVT_SERVER_RESET' ,
0xB000 : 'EVT_TIMER_HITZERO' ,
0xC000 : 'EVT_GPIO_FINISHED' ,
0xC001 : 'EVT_GPIO_PLAY' ,
0xC002 : 'EVT_GPIO_PAUSE' ,
0xC003 : 'EVT_GPIO_STOPRESET' ,
0xC004 : 'EVT_GPIO_ADDTIME'
}
def __init__(self, value, data=None):
self.value = value
self.data = data
class GameState():
def __init__(self, state, active, timeLeft, timeStarted = None):
self.state = state
self.active = active
self.seconds = timeLeft
self.startedon = timeStarted
enddate = datetime.datetime.now() + datetime.timedelta(0,timeLeft)
self.expecetedend = "{:02d}:{:02d}".format(enddate.hour,enddate.minute)
class MainRoomController(RoomEventListener):
def __init__(self, server = None, timer = None, gpio = None):
self.server = server
self.timer = timer
self.gpio = gpio
self.roomState = STATE_READY
self.gameActive = False
self.timeStarted = None
def initialize(self, server = None, timer = None, gpio = None): # due to the circular dependency this function must be called after creating all other controllers
if(server is not None):
self.server = server
if(timer is not None):
self.timer = timer
if(gpio is not None):
self.gpio = gpio
def _onEvent(self, roomEvent):
try:
Logger.glog("Received event: {0}; data: {1}".format(RoomEvent.namedict[roomEvent.value], str(roomEvent.data)))
except Exception as e:
print("Logging failed")
print(str(e))
# BEGIN SERVER EVENTS
if(roomEvent.value == RoomEvent.EVT_SERVER_PLAY):
if(self.roomState == STATE_READY): # start game
self.roomState = STATE_RUNNING
self.gpio.triggerStart()
self.timer.resume()
self.setActive()
elif(self.roomState == STATE_PAUSED): # resume game
self.timer.resume()
self.roomState = STATE_RUNNING
elif(roomEvent.value == RoomEvent.EVT_SERVER_PAUSE):
if(self.roomState == STATE_RUNNING): # pause game
self.roomState = STATE_PAUSED
self.timer.pause()
elif(roomEvent.value == RoomEvent.EVT_SERVER_SETTIME): # set time to
self.timer.setSeconds(roomEvent.data)
elif(roomEvent.value == RoomEvent.EVT_SERVER_ADDTIME): # add time
self.timer.addSeconds(roomEvent.data)
elif(roomEvent.value == RoomEvent.EVT_SERVER_STOP): # stop game
if(self.roomState == STATE_RUNNING or self.roomState == STATE_PAUSED):
self.roomState = STATE_STOPPED
self.timer.pause()
self.gpio.unlockEntrance()
self.setUnactive()
elif(roomEvent.value == RoomEvent.EVT_SERVER_RESET): # reset game from stopped
if(self.roomState == STATE_STOPPED):
self.roomState = STATE_READY
self.timer.setSeconds(roomEvent.data)
# BEGIN TIMER EVENTS
elif(roomEvent.value == RoomEvent.EVT_TIMER_HITZERO): # when timer runs out
self.roomState = STATE_STOPPED
self.timer.pause()
self.gpio.unlockEntrance()
self.setUnactive()
# BEGIN GPIO EVENTS
elif(roomEvent.value == RoomEvent.EVT_GPIO_FINISHED): # when finished signal is received, i.e. last puzzle solved
self.roomState = STATE_STOPPED
self.timer.pause()
self.gpio.unlockExit()
self.setUnactive()
elif(roomEvent.value == RoomEvent.EVT_GPIO_PLAY):
if(self.roomState == STATE_READY): # start game
self.roomState = STATE_RUNNING
self.timer.setSeconds(CFG_DEFAULT_TIME)
self.gpio.triggerStart()
self.timer.resume()
elif(self.roomState == STATE_PAUSED): # resume game
self.timer.resume()
self.roomState = STATE_RUNNING
elif(roomEvent.value == RoomEvent.EVT_GPIO_PAUSE):
if(self.roomState == STATE_RUNNING): # pause game
self.timer.pause()
self.roomState = STATE_PAUSED
elif(roomEvent.value == RoomEvent.EVT_GPIO_STOPRESET):
self.roomState = STATE_READY
self.timer.setSeconds(roomEvent.data)
self.timer.pause()
self.gpio.unlockEntrance()
self.setUnactive()
elif(roomEvent.value == RoomEvent.EVT_GPIO_ADDTIME):
self.timer.addSeconds(roomEvent.data)
return GameState(self.roomState, self.gameActive, self.timer.secondsRemaining, self.timeStarted)
def raiseEvent(self, roomEvent):
return self._onEvent(roomEvent)
def getState(self):
return GameState(self.roomState, self.gameActive, self.timer.secondsRemaining, self.timeStarted)
def setActive(self): # the room state can be stopped or ready which means the a game in the room is not in progress and the room is not "active"
self.gameActive = True
self.timeStarted = "{:02d}:{:02d}".format(datetime.datetime.now().hour, datetime.datetime.now().minute)
# could probably use datetime.datetime.now().strftime("%R") but this thing works too
def setUnactive(self):
self.gameActive = False | true |
1368279a837198f403b0e7724ceb6a0c86e0afe9 | Python | anastas-ananas/itstep | /lesson6/prime42.py | UTF-8 | 256 | 3.59375 | 4 | [] | no_license | result = []
for number in range(2, 300):
for i in range(2, number):
if number % i == 0:
break
else:
result.append(number)
if len(result) == 42:
break
print(result)
print(f"Number of digits: {len(result)}")
| true |
b6b1a120a10fc378ba6e1c94694394c068a7e221 | Python | bobbecooper/congenial-engine | /main.py | UTF-8 | 265 | 2.921875 | 3 | [] | no_license | from Cycle import Cycle
my_cycle = Cycle()
# main input loop
my_cycle.print_options()
user_input = int(input())
while user_input != 0:
my_cycle.update_cycle(user_input)
my_cycle.print_new_idea()
my_cycle.print_options()
user_input = int(input())
| true |
fe36a0fd14e0479356d2261a86c2cad02bbdd8f8 | Python | Aasthaengg/IBMdataset | /Python_codes/p03576/s816034475.py | UTF-8 | 709 | 3.09375 | 3 | [] | no_license | n, k = map(int, input().split())
x_y = []
x = []
y = []
for i in range(n):
a,b = map(int, input().split())
x.append(a)
y.append(b)
x_y.append([a,b])
ans = 10**19
def check(a,b,c,d):
count = 0
for i in range(n):
s,t = x_y[i]
if a <= s <= b and c <= t <= d:
count += 1
if count >= k:
return True
else:
return False
x.sort()
y.sort()
for x_1 in range(n):
for x_2 in range(x_1+1,n):
for y_1 in range(n):
for y_2 in range(y_1+1,n):
if check(x[x_1],x[x_2],y[y_1],y[y_2]):
rect_area = (x[x_2] - x[x_1]) * (y[y_2] - y[y_1])
ans = min(ans, rect_area)
print(ans)
| true |
e0e53cdbe1da00a5936c23f9c132ed916c3682fe | Python | ifrit98/tf_dataset | /tf_dataset/metadata.py | UTF-8 | 4,615 | 2.71875 | 3 | [] | no_license | import os
import numpy as np
import pandas as pd
from .dataset_sql import signal_dataset
from .dataset_prepare_signal import dataset_prepare_signal_for_ml
from .dataset_slice_windows import dataset_signal_slice_windows
from .dataset_complex import dataset_signal_apply_analytic
from .dataset_normalize import dataset_signal_normalize
from .tf_utils import dataset_batch, dataset_set_shapes, is_empty
from pathlib import Path
def construct_metadata(data_dir, labels=None, label_colname='class', targets=None,
metadata=None, ext='.wav', create_targets=True):
r"""Construct a metadata pandas dataframe for use with `signal_dataset`
Args:
data_dir: string filepath to top-level data directory.
(Nested dir support coming soon)
labels: may be either a `np.ndarray` of sequential labels to associate with
lexicographically sorted filepaths in `data_dir`, OR a python `dict`,
mapping filepaths to labels.
E.g.
np.ndarray
labels = np.asarray(['label123', 'label456'])
OR
dict
labels = {
'filepath123.wav': 'label123',
'filepath456.wav': 'label456',
...,
}
If none supplied, `construct_metadata()` will use regex to extract
labels between the final underscore `_` to file extension `.wav'.
If your file naming scheme does not follow this convention,
parsed `labels` will be meaningless.
E.g. 'data/signal_123_cargo.wav'. -> 'cargo'
Where
'cargo' is extracted and added to the labels column of the dataframe
for every example in `data_dir`.
label_colname: string label to use as key for dataframe labels. Default: 'class'
metadata: (optional) pandas dataframe of relavant information to add to the sql db.
ext: string representation of file extension starting with '.'. Default: '.wav'.
This is how `construct_metadata()` will find data files from the `data_dir`.
Can be arbitrary, so long as passing `process_db_entry()` along with subsequent
calls to `training_dataset()` or `signal_dataset()`
create_targets: boolean. Default: True.
Returns:
pd.DataFrame object containing metadata for creating a tf.data.Dataset object
"""
if targets is not None and create_targets is True:
import warnings
warnings.warn(
"Setting `create_targets` to False since `targets` is supplied.")
create_targets = False
data_dir = os.path.abspath(data_dir)
data_files = list(Path(data_dir).rglob("*" + ext))
if data_files == []:
raise ValueError("No files found with ext {} at {}".format(ext, data_dir))
df = pd.DataFrame.from_dict({'filepath': data_files})
# Extract from `data_files`
if isinstance(labels, list) or isinstance(labels, np.ndarray):
df.loc[:, (label_colname)] = np.asarray(labels).astype(str)
elif isinstance(labels, dict):
labels2 = {
'filepath': list(),
label_colname: list()
}
for k,v in labels.items():
labels2['filepath'].append(os.path.abspath(k))
labels2[label_colname].append(v)
df[label_colname] = pd.DataFrame(labels2)[label_colname]
elif labels is None:
import re
extract = lambda s: re.search("\\D*{}".format(ext), str(s)).group(0)
extract = np.vectorize(extract)
classes = extract(df['filepath'])
extract = lambda s: re.search("(?<=_)\\w*[^{}]".format(ext), s).group(0)
extract = np.vectorize(extract)
labels = np.asarray(extract(classes)).astype(str)
df[label_colname] = labels
else:
raise ValueError("`labels` must be one of [`list`, `np.ndarray`, `dict`]")
if label_colname in df.columns.values:
df.loc[:, ('num_classes')] = [len(df[label_colname].unique())] * len(df[label_colname])
if create_targets:
CLASSES = df[label_colname].unique().astype(str)
classes_dict = dict(zip(CLASSES, range(len(CLASSES))))
targets = list(map(lambda x: classes_dict[x], df[label_colname]))
if targets is not None:
if len(df['filepath']) != len(targets):
raise ValueError("Passed `targets` with different length than `df`.")
df.loc[:, ('target')] = np.asarray(targets)
return df
| true |
a312a2275cbc178d68918bced66b68f3d191495c | Python | EsriJapan/gcf2018-arcpy-demo | /source/forum_ArcPy_arcgispro.py | UTF-8 | 2,884 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | # coding:utf-8
###############################################################
# CSVファイルを読込み、フィーチャ クラスを作成するスクリプト #
###############################################################
"""
data フォルダをCドライブ直下に配置すればそのまま動作します。
任意の場所に配置する場合はデータの配置場所に合わせて変数の値を変更してください。
"""
import arcpy
import os
import datetime
######################################
# ワークスペースの設定
######################################
workPath = r"C:\data"
arcpy.env.workspace = workPath + r"\ArcGIS Pro\arcpy.gdb"
######################################
# PDF 出力先フォルダの作成
######################################
date = datetime.datetime.now()
dateStr = '{0:%Y%m%d}'.format(date)
# 現在の日時でフォルダを作成
os.makedirs(workPath + r"\output\{0}".format(dateStr))
######################################
# CSV ファイルを読込む
# ポイント フィーチャ クラスを作る
######################################
# ジオプロセシングツールに必要なパラメータの作成
csv_table = workPath + r"\current.csv"
out_csv_feature_class = "csv{0}".format(dateStr)
x_field = "X"
y_field = "Y"
current_csv_feature_class = "current"
# ジオプロセシングツールの実行
arcpy.XYTableToPoint_management(csv_table, out_csv_feature_class, x_field, y_field)
arcpy.DeleteFeatures_management(current_csv_feature_class)
arcpy.Append_management(out_csv_feature_class, current_csv_feature_class, "NO_TEST")
######################################
# 各駅ごとの放置車両数を集計する
######################################
# フィーチャクラス (curent) に対してカーソルを定義
cursor = arcpy.UpdateCursor("current")
# 23 区ごとに放置車両の合計値を算出
for row in cursor:
row.setValue("放置車両_合計",row.getValue("放置台数_自転車") + row.getValue("放置台数_原付") + row.getValue("放置台数_自二"))
cursor.updateRow(row)
del cursor, row
######################################
# 23 区ごとに地図を PDF 出力する
######################################
project = arcpy.mp.ArcGISProject(workPath + r"\ArcGIS Pro\arcpy.aprx")
layout = project.listLayouts()[0]
if layout.mapSeries is not None:
ms = layout.mapSeries
if ms.enabled:
# マップシリーズで指定した図郭ごとに出力
for pageNum in range(1, ms.pageCount + 1):
ms.currentPageNumber = pageNum
print("{0}/{1}ページを出力中".format(str(ms.currentPageNumber), str(ms.pageCount)))
layout.exportToPDF(workPath + r"\output\{0}\report_{1}".format(dateStr, str(ms.currentPageNumber)) + ".pdf") | true |
b30e054ecff2299dd39a31a1682bf22953ce1437 | Python | sourav-coder/Python-Code-Challanges | /Python Code Challenges/100-plus-Python-programming-exercises-extended-master/solutions/Day-16/64.py | UTF-8 | 157 | 3.375 | 3 | [] | no_license | def gen(n):
for i in range(0,n+1):
if i%5==0 and i%7==0:
yield str(i)
a=list(gen(int(input())))
print(','.join(a))
| true |
fffcd0fbd6bd234bc8e22a572734c85ef9a28d03 | Python | mickwar/leetcode | /medium/minimum_path_sum.py | UTF-8 | 2,062 | 3.90625 | 4 | [] | no_license | # https://leetcode.com/problems/minimum-path-sum/
# At time of submission
# performed 78% faster
# used less than 17% memory
# than other solutions
# Thanks to this article for help: https://www.geeksforgeeks.org/min-cost-path-dp-6/
# Using dynamic programming (DP), allocating memory so we don't do unnecessary
# computations. There is no recursion, we've optimized it out using DP.
# But, what is that path? Start from the end of the total cost array, and do a
# greedy search, always picking the branch which is smaller. If there is a tie,
# it doesn't matter which you choose
class Solution:
def minPathSum(self, grid):
n = len(grid) # rows
m = len(grid[0]) # columns
# We use a total cost array "tc" where tc[i][j] is the total (minimum)
# cost to go from [0][0] up until [i][j]. Thus, the last element,
# tc[n-1][m-1] is the minimum across all possible paths.
### Initialize total cost array
# Initial space
tc = [[0] * m for _ in range(n)]
tc[0][0] = grid[0][0]
# First column
for i in range(1, n):
tc[i][0] = tc[i-1][0] + grid[i][0]
# First row
for j in range(1, m):
tc[0][j] = tc[0][j-1] + grid[0][j]
# Fill in the remaining
for i in range(1, n):
for j in range(1, m):
tc[i][j] = grid[i][j] + min(tc[i-1][j],
tc[i][j-1])
print("")
print("Original")
for line in grid:
print(line)
print("Minimum")
for line in tc:
print(line)
print("")
return tc[n-1][m-1]
### Examples
obj = Solution()
grid = [
[1,3,1,0],
[1,5,1,0],
[4,2,1,1]
]
print(obj.minPathSum(grid))
grid = [
[1,3,1,0],
[1,5,1,0],
[0,0,1,1]
]
print(obj.minPathSum(grid))
grid = [
[1,3,1,5,0],
[1,5,2,0,3],
[2,6,1,1,4],
[3,0,2,3,1]
]
print(obj.minPathSum(grid))
grid = [
[1,0,0,1],
[1,1,1,1],
[1,0,0,1]
]
print(obj.minPathSum(grid))
| true |
11043f399a2f35456aacd9ca2cc12576610d4e5a | Python | whitepaper2/data_beauty | /leetcode/100_is_sametree.py | UTF-8 | 1,832 | 3.546875 | 4 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/11/18 下午5:32
# @Author : pengyuan.li
# @Site :
# @File : 100_is_sametree.py
# @Software: PyCharm
from common import timeit
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
@timeit
def is_same_tree(p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
def is_same_subtree(p0, q0):
if p0 is None and q0 is None:
return True
elif p0 is not None and q0 is not None:
out = True if p0.val == q0.val else False
left = is_same_subtree(p0.left, q0.left)
right = is_same_subtree(p0.right, q0.right)
return out and left and right
else:
return False
return is_same_subtree(p, q)
@timeit
def is_same_tree2(p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
def is_same_subtree(p0, q0):
if p0 is None and q0 is None:
return True
elif p0 is not None and q0 is not None:
out = True if p0.val == q0.val else False
if out:
left = is_same_subtree(p0.left, q0.left)
right = is_same_subtree(p0.right, q0.right)
return left and right
else:
return False
else:
return False
return is_same_subtree(p, q)
if __name__ == "__main__":
root = TreeNode(1)
left = TreeNode(2)
right = TreeNode(3)
root.left = left
root.right = right
root2 = TreeNode(4)
left = TreeNode(2)
right = TreeNode(3)
root2.left = left
root2.right = right
print(is_same_tree2(root, root2))
# print(is_same_tree(root, root2))
| true |
10cf88102f04a2393c230257135c9a83e850fa87 | Python | Yash-Dabhade/Automatic-File-Handler | /FileCleaner.py | UTF-8 | 1,839 | 2.671875 | 3 | [] | no_license | import os
files = os.listdir()
files.remove("FileCleaner.py")
def createfolder(foldername):
if not os.path.exists(foldername):
os.makedirs(foldername)
def sortfiles(fileslist, ext):
for file in files:
if os.path.splitext(file)[1].lower() in ext:
fileslist.append(file)
def move(foldername, files):
for file in files:
os.replace(file, f"{foldername}/{file}")
imgext = [".png", ".jpg", ".jpeg", ".gif"]
medext = [".mpg", ".mp4", ".mpeg", ".mp3", ".mkv", ".avi"]
rarext = [".rar", ".zip", ".7z"]
codext = [".py", ".js", ".css", ".html", ".c", ".cpp", ".java", ".r"]
docsext = [".docs", ".ppt", ".pdf", ".md", ".doc", ".docx", ".txt"]
softext = [".exe", ".msi"]
for file in files:
e = os.path.splitext(file)[1]
if(e in imgext):
createfolder("Images")
elif(e in medext):
createfolder("Media")
elif(e in rarext):
createfolder("RAR/ZIP")
elif(e in codext):
createfolder("Code")
elif(e in docsext):
createfolder("Docs")
elif(e in softext):
createfolder("Softwares")
else:
createfolder("Others")
image = []
media = []
rar = []
code = []
docs = []
soft = []
other = []
sortfiles(image, imgext)
sortfiles(media, medext)
sortfiles(rar, rarext)
sortfiles(docs, docsext)
sortfiles(code, codext)
sortfiles(soft, softext)
for file in files:
ext = os.path.splitext(file)[1].lower()
if(ext not in imgext) and (ext not in medext) and (ext not in rarext) and (ext not in codext) and (ext not in docsext) and (ext not in softext) and (os.path.isfile(file)):
other.append(file)
move("Images", image)
move("Media", media)
move("RAR/ZIP", rar)
move("Softwares", soft)
move("Code", code)
move("Docs", docs)
move("Others", other)
| true |
80bde3b43be525795f6feba464e3aa0302386488 | Python | MinSu-Kim/python_tutorial | /mysql_tutorial/coffee_sale/connection_pool_test.py | UTF-8 | 354 | 2.734375 | 3 | [] | no_license | from mysql_tutorial.coffee_sale.connection_pool import DatabaseConnectionPool
connection = DatabaseConnectionPool.get_instance().get_connection()
cursor = connection.cursor()
cursor.execute("select * from product")
rows = cursor.fetchall()
print('Total Row(s):', cursor.rowcount)
for row in rows:
print(type(row), " => ", row)
connection.close() | true |
75094d0082644d028368f28fdc4e81a7bf9adbcd | Python | Savirman/Python_lesson01 | /example05.py | UTF-8 | 1,563 | 4.28125 | 4 | [] | no_license | # Программа расчета основных показателей деятельности фирмы
# Запрос основных показателей фирмы: выручки (proceeds) и издержек (costs)
# с целью определения прибыли (profit)
proceeds = float(input("Какова выручка Вашей компании?: "))
costs = float(input("Каковы издержки Вашей компании?: "))
profit = proceeds - costs
# Проверка рентабельности деятельности фирмы
if profit < 0:
print("Ваша фирма работаетв убыток")
elif profit == 0:
print('Ваша фирма работает в "ноль"')
# Если фирма работает с прибылью, то рассчитаем рентабельность (profitability)
# и прибыль на одного сотрудника (profit_per_emp)
else:
print("Ваша фирма работает с прибылью. Прибыль компании составляет {}".format(profit))
profitability = profit / proceeds
print("Рентабельность выручки составляет: {}".format(profitability))
num_of_emp = int(input("Введите численность сотрудников Вашей фирмы: "))
profit_per_emp = profit / num_of_emp
print("Прибыль фирмы в расчете на одного сотрудника составляет: {}".format(profit_per_emp))
| true |
0e38c2901d7673db20a4660daa6134e7dd7f6e7a | Python | shashi278/DataCommunication | /codes/ssb_sc.py | UTF-8 | 1,528 | 3.109375 | 3 | [
"MIT"
] | permissive | import numpy as np
from numpy import *
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from ampMod import AmplitudeModulation
class SSBSC(AmplitudeModulation):
def createSignals(self):
'''
Note:
==========
creates 'carrier', 'message', 'lower band
modulated' and 'upper band modulated'
signals
#upper side band modulated signal
usb= m(t).cos(2.π.fc.t) - m'(t).sin(2.π.fc.t)
#upper side band modulated signal
lsb= m(t).cos(2.π.fc.t) + m'(t).sin(2.π.fc.t)
m'(t) ---> Hilbert Transform of m(t)
i.e. m'(t)= m(t)/π.t
'''
#carrier signal
c= lambda t: self.Ac*sin(2*pi*self.fc*t)
#message signal
m= lambda t: self.Am*sin(2*pi*self.fm*t)
#hilbert transform, m'(t)
mh= lambda t: m(t)/(pi*t)
#upper side band
usb= lambda t: m(t)*cos(2*pi*self.fc*t) - mh(t)*sin(2*pi*self.fc*t)
#lower side band
lsb= lambda t: m(t)*cos(2*pi*self.fc*t) + mh(t)*sin(2*pi*self.fc*t)
return c, m, usb, lsb
if __name__=='__main__':
labels= {
'title': '====SSB-SC Modulation====',
'xlabel': 'Time(Sec)',
'ylabel': 'Amplitude',
'subtitle1': 'Carrier Signal: Ac.sin(Wc*t)',
'subtitle2': 'Message Signal: Am.sin(Wm*t)',
'subtitle3': 'SSB-SC Modulated Signal(USB)\nm(t)*cos(Wc*t) - m\'(t)*sin(Wc*t)',
'subtitle4': 'SSB-SC Modulated Signal(LSB)\nm(t)*cos(Wc*t) + m\'(t)*sin(Wc*t)'
}
ssb= SSBSC(Ac= 3, Am= 2, fc= 5, fm= 1)
ssb.plot(*ssb.createSignals()[0:3], labels, ssb.createSignals()[3]) | true |
a9e039ea4d34ef0b8cb46f79f4fe59755833b7f3 | Python | kimberlybone/python-course | /conditional.py | UTF-8 | 434 | 4.1875 | 4 | [] | no_license | x = 20
# CONDITIONAL 1 (Basic)
# if x > 2 :
# print('Bigger')
# else :
# print('Smaller')
# print('All done')
# CONDITIONAL 2 (Multi-way)
# if x < 2 :
# print('small')
# elif x < 10 :
# print('Medium')
# else :
# print('LARGE')
# print('All done')
# CONDITIONAL 3 (Used to catch errors)
astr = 'Hello'
# if
try:
istr = int(astr)
# else
except:
istr = "Your code didn't work"
print('Done.', istr)
| true |
c13fc5fb06c18048eb1a6e3952e6d088f27c9e9c | Python | AsaneZeto/Image-Process | /hw2.py | UTF-8 | 7,848 | 2.953125 | 3 | [] | no_license | import sys
sys.path.append("../hw1")
import hw1
import numpy as np
import cv2
import queue
def processImage(path, color='gray'):
img = cv2.imread(path,1)
if color == 'gray':
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
elif color == 'rgb':
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
return img
def logFilter(kernel_size=5, sigma=1):
def logValue(x,y,sigma):
rs = x**2 + y**2
hr = np.exp(-rs/(2.*sigma**2))
w = ((rs-(2.0*sigma**2))/sigma**4)
normal = 1 / (2.0 * np.pi * sigma**2)
kernel = (hr*w)/ normal
return kernel
half = int(kernel_size/2)
filter = np.zeros((kernel_size,kernel_size))
for i in range(half+1):
for j in range(half+1):
value = logValue(i,j,sigma)
filter[i+half,j+half] = value
filter[-i+half,j+half] = value
filter[i+half,-j+half] = value
filter[-i+half, -j+half] = value
# filter = filter - np.mean(filter)
# filter /= sigma
return filter
def sobel(degree):
if degree == 0:
sobel = [[-1,-2,-1],[0,0,0],[1,2,1]]
elif degree == 45:
sobel = [[-2,-1,0],[-1,0,1],[0,1,2]]
elif degree == 90:
sobel = [[-1,0,1],[-2,0,2],[-1,0,1]]
elif degree == 135:
sobel = [[0,1,2],[-1,0,1],[-2,-1,0]]
return sobel
def prewitt(degree):
if degree == 0:
prewitt = [[-1,-1,-1],[0,0,0],[1,1,1]]
elif degree == 45:
prewitt = [[-1,-1,0],[-1,0,1],[0,1,1]]
elif degree == 90:
prewitt = [[-1,0,1],[-1,0,1],[-1,0,1]]
elif degree == 135:
prewitt = [[0,1,1],[-1,0,1],[-1,-1,0]]
return prewitt
def gradient(image, filter='sobel', degree=0):
if filter == 'sobel':
sobel_filter = np.array(sobel(degree))
new_image = convolve2D(image, sobel_filter)
return new_image
elif filter == 'prewitt':
prewitt_filter = np.array(prewitt(degree))
new_image = convolve2D(image, prewitt_filter)
return new_image
def Gaussian(s, t, variance):
r2 = s**2 + t**2
return np.exp(-1*(r2/2*variance))
# correlation
def getGaussian(filter_size, variance):
Gfilter = np.empty((filter_size,filter_size))
offset = int(filter_size/2)
# generate filter
for i in range(filter_size):
for j in range(filter_size):
Gfilter[i][j] = Gaussian(i-offset, j-offset, variance)
Gfilter = np.divide(Gfilter, np.sum(Gfilter))
return Gfilter
def GBlur(image, kernel_size=5, sigma=1.4):
"""
args:
image : The input image
kernel_size : kernel size
sigma : The width parameter of the Gaussian filter
"""
g_filter = getGaussian(kernel_size, sigma)
new_image = convolve2D(image, g_filter)
new_image = transferType(new_image)
return new_image
def LoG(image, kernel_size=5, sigma=1.4):
"""
args:
image : The input image
kernel_size : kernel size
sigma : The width parameter of the Gaussian filter
"""
log_filter = logFilter(kernel_size, sigma)
new_image = convolve2D(image, log_filter)
new_image = transferType(new_image)
return new_image
def convolve2D(image, kernel, padding=0, pad_method='0'):
kernel = np.flipud(np.fliplr(kernel))
kernel_size = kernel.shape[0]
img_height = image.shape[0]
img_width = image.shape[1]
new_image_height = int((img_height-kernel_size+2*padding)+1)
new_image_width = int((img_width-kernel_size+2*padding)+1)
new_image = np.zeros((new_image_height,new_image_width))
if padding != 0:
if pad_method == '0':
pad_img = np.pad(image, padding, constant_value=0)
else:
pad_img = np.pad(image, padding, mode=pad_method)
else:
pad_img = image
for row in range(img_height):
if row > img_height - kernel_size:
break
for col in range(img_width):
if col > img_width - kernel_size:
break
local = pad_img[row:row+kernel_size, col:col+kernel_size]
new_image[row , col] = (local*kernel).sum()
return new_image
def transferType(image):
mn = image.min()
mx = image.max()
mx -= mn
image = ((image - mn)/mx) * 255
return image.astype(np.uint8)
def normalize(image):
max = np.max(image)
image /= max
return image
def threshold(image, threshold=0):
new_image = image.copy()
if threshold == 0:
new_image[new_image>0] = 255
return new_image
else:
new_image[new_image>=threshold] = 255
new_image[new_image<threshold] = 0
return new_image
def canny(image, threshold1, threshold2):
# 1.gaussian smooth
image = GBlur(image)
#image = transferType(image)
# 2.gradient
Gx = gradient(image, filter='sobel', degree=0)
Gy = gradient(image, filter='sobel', degree=90)
#magnitude = np.sqrt(Gx**2+Gy**2)
magnitude = transferType(np.abs(Gx) + np.abs(Gy))
# gradient direction
theta = ((np.arctan(Gy/Gx))/np.pi) * 180
theta[theta < 0] += 180
# 3.non-maximum suppresion
nms = magnitude.copy()
for i in range(theta.shape[0]):
if i == 0 or i == (theta.shape[0]-1) : continue
for j in range(theta.shape[1]):
if j == 0 or j == (theta.shape[1]-1) : continue
# degree 0
if (theta[i, j] <= 22.5 or theta[i, j] > 157.5):
if(magnitude[i, j] <= magnitude[i, j-1]) and (magnitude[i, j] <= magnitude[i, j+1]):
nms[i, j] = 0
# degree 45
elif (theta[i, j] > 22.5 and theta[i, j] <= 67.5):
if(magnitude[i, j] <= magnitude[i+1, j+1]) and (magnitude[i, j] <= magnitude[i-1, j-1]):
nms[i, j] = 0
# degree 90
elif (theta[i, j] > 67.5 and theta[i, j] <= 112.5):
if(magnitude[i, j] <= magnitude[i+1, j]) and (magnitude[i, j] <= magnitude[i-1, j]):
nms[i, j] = 0
# degree 135
elif (theta[i, j] > 112.5 and theta[i, j] <= 157.5):
if(magnitude[i, j] <= magnitude[i+1, j-1]) and (magnitude[i, j] <= magnitude[i-1, j+1]):
nms[i, j] = 0
# 4.double threshold
strong = nms.copy()
weak = nms.copy()
# strong edge
strong[strong>threshold2] = 255
strong[strong<threshold1] = 0
# weak edge
weak[weak<threshold1] = 0
weak[weak>threshold2] = 0
# 5. Hystersis
edgeImage = strong.copy()
for i in range(edgeImage.shape[0]):
if i == 0 or i == (edgeImage.shape[0]-1): continue
for j in range(theta.shape[1]):
if j == 0 or j == (edgeImage.shape[1]-1): continue
if(edgeImage[i,j]!=0):
# degree 0
if (theta[i, j] <= 22.5 or theta[i, j] > 157.5):
if(weak[i,j-1]!=0):
edgeImage[i,j-1] = 255
if(weak[i,j+1]!=0):
edgeImage[i,j+1] = 255
# degree 45
elif (theta[i, j] > 22.5 and theta[i, j] <= 67.5):
if(weak[i-1,j-1]!=0):
edgeImage[i-1,j-1] = 255
if(weak[i+1,j+1]!=0):
edgeImage[i+1,j+1] = 255
# degree 90
elif (theta[i, j] > 67.5 and theta[i, j] <= 112.5):
if(weak[i-1,j]!=0):
edgeImage[i-1,j] = 255
if(weak[i+1,j]!=0):
edgeImage[i+1,j] = 255
# degree 135
elif (theta[i, j] > 112.5 and theta[i, j] <= 157.5):
if(weak[i+1,j+1]!=0):
edgeImage[i+1,j+1] = 255
if(weak[i-1,j-1]!=0):
edgeImage[i-1,j-1] = 255
return nms, edgeImage
| true |
9918ee3844c1f33d9a1e8a89b30ec4a45530651c | Python | hub4mani/ProjectEuler | /016.py | UTF-8 | 132 | 3.046875 | 3 | [] | no_license | num_str = str(2**1000)
print num_str
sum = 0
length = len(num_str)
for i in range(length):
sum = sum + int(num_str[i])
print sum
| true |
2baee35c5fcd1523e6a2ef9683be61e0000925e2 | Python | MayhemMark/project-mayhem | /tests/die_rolls.py | UTF-8 | 548 | 4.21875 | 4 | [] | no_license | import random
def roll_dice():
list1 = []
sides = int(input("how many sides does the die have?: "))
times = int(input("how many times do you want to roll? "))
print(f"\nRolling a {sides} sided die, rolling it {times} times")
print("These are the results:\n")
for i in range(0, times):
list1.append(random.randint(1, sides))
print(list1)
print(f"the total of your rolls: {sum(list1)}")
pick = input("\nroll again? y/n: ")
if pick == "y":
roll_dice()
else:
return
roll_dice()
| true |
a170be88d09386d33e40e62f5029c215ffffaf8f | Python | lyft/salt | /salt/modules/win_servermanager.py | UTF-8 | 4,100 | 2.59375 | 3 | [
"Apache-2.0",
"MIT",
"BSD-2-Clause"
] | permissive | # -*- coding: utf-8 -*-
'''
Manage Windows features via the ServerManager powershell module
'''
from __future__ import absolute_import
import logging
# Import python libs
try:
from shlex import quote as _cmd_quote # pylint: disable=E0611
except ImportError:
from pipes import quote as _cmd_quote
# Import salt libs
import salt.utils
log = logging.getLogger(__name__)
def __virtual__():
'''
Load only on windows
'''
if salt.utils.is_windows():
return 'win_servermanager'
return False
def _srvmgr(func):
'''
Execute a function from the ServerManager PS module and return the STDOUT
'''
return __salt__['cmd.run'](
'Import-Module ServerManager ; {0}'.format(func),
shell='powershell',
python_shell=True)
def _parse_powershell_list(lst):
'''
Parse command output when piped to format-list
Need to look at splitting with ':' so you can get the full value
Need to check for error codes and return false if it's trying to parse
'''
ret = {}
for line in lst.splitlines():
if line:
splt = line.split()
# Ensure it's not a malformed line, e.g.:
# FeatureResult : {foo, bar,
# baz}
if len(splt) > 2:
ret[splt[0]] = splt[2]
ret['message'] = lst
return ret
def list_available():
'''
List available features to install
CLI Example:
.. code-block:: bash
salt '*' win_servermanager.list_available
'''
return _srvmgr('Get-WindowsFeature -erroraction silentlycontinue -warningaction silentlycontinue')
def list_installed():
'''
List installed features. Supported on Windows Server 2008 and Windows 8 and
newer.
CLI Example:
.. code-block:: bash
salt '*' win_servermanager.list_installed
'''
ret = {}
names = _srvmgr('Get-WindowsFeature -erroraction silentlycontinue -warningaction silentlycontinue | Select DisplayName,Name')
for line in names.splitlines()[2:]:
splt = line.split()
name = splt.pop(-1)
display_name = ' '.join(splt)
ret[name] = display_name
state = _srvmgr('Get-WindowsFeature -erroraction silentlycontinue -warningaction silentlycontinue | Select Installed,Name')
for line in state.splitlines()[2:]:
splt = line.split()
if splt[0] == 'False' and splt[1] in ret:
del ret[splt[1]]
if '----' in splt[0]:
del ret[splt[1]]
return ret
def install(feature, recurse=False):
'''
Install a feature
Note:
Some features requires reboot after un/installation, if so until the server is restarted
Other features can not be installed !
Note:
Some features takes a long time to complete un/installation, set -t with a long timeout
CLI Example:
.. code-block:: bash
salt '*' win_servermanager.install Telnet-Client
salt '*' win_servermanager.install SNMP-Service True
'''
sub = ''
if recurse:
sub = '-IncludeAllSubFeature'
out = _srvmgr('Add-WindowsFeature -Name {0} {1} -erroraction silentlycontinue -warningaction silentlycontinue | format-list'.format(
_cmd_quote(feature), sub))
return _parse_powershell_list(out)
def remove(feature):
'''
Remove an installed feature
.. note::
Some features require a reboot after installation/uninstallation. If
one of these features are modified, then other features cannot be
installed until the server is restarted. Additionally, some features
take a while to complete installation/uninstallation, so it is a good
idea to use the ``-t`` option to set a longer timeout.
CLI Example:
.. code-block:: bash
salt -t 600 '*' win_servermanager.remove Telnet-Client
'''
out = _srvmgr('Remove-WindowsFeature -Name {0} -erroraction silentlycontinue -warningaction silentlycontinue | format-list'.format(
_cmd_quote(feature)))
return _parse_powershell_list(out)
| true |
9520bf2d1900bb8188141cd0b1539d046f8f0856 | Python | zhangqizky/LearnOpenCV_Chinese | /HighDynamicRange/HDR.py | UTF-8 | 2,056 | 2.765625 | 3 | [] | no_license | import os
import cv2
import numpy as np
def readImagesAndTimes():
"""[读取时间和图像]
Returns:
[list of images] -- [图像]
[list of times] -- [时间]
"""
times = np.array([1/30,0.25,2.5,15],dtype=np.float32)
filenames = ["img_0.033.jpg","img_0.25.jpg","img_2.5.jpg","img_15.jpg"]
images = []
for filename in filenames:
im = cv2.imread(filename)
images.append(im)
return images,times
def main():
#读取多张曝光的图像
images,times = readImagesAndTimes()
#对齐图像
alignMTB = cv2.createAlignMTB()
alignMTB.process(images, images)
#恢复相机响应函数
calibrateDebevec = cv2.createCalibrateDebevec()
responseDebevec = calibrateDebevec.process(images, times)
# 将多张图像融合成hdr
mergeDebevec = cv2.createMergeDebevec()
hdrDebevec = mergeDebevec.process(images, times, responseDebevec)
# 保存融合结果,可用ps打开
cv2.imwrite("hdrDebevec.hdr", hdrDebevec)
# Tonemap using Drago's method to obtain 24-bit color image
tonemapDrago = cv2.createTonemapDrago(1.0, 0.7)
ldrDrago = tonemapDrago.process(hdrDebevec)
ldrDrago = 3 * ldrDrago
cv2.imwrite("ldr-Drago.jpg", ldrDrago * 255)
# Tonemap using Durand's method obtain 24-bit color image
tonemapDurand = cv2.createTonemapDurand(1.5,4,1.0,1,1)
ldrDurand = tonemapDurand.process(hdrDebevec)
ldrDurand = 3 * ldrDurand
cv2.imwrite("ldr-Durand.jpg", ldrDurand * 255)
# Tonemap using Reinhard's method to obtain 24-bit color image
tonemapReinhard = cv2.createTonemapReinhard(1.5, 0,0,0)
ldrReinhard = tonemapReinhard.process(hdrDebevec)
cv2.imwrite("ldr-Reinhard.jpg", ldrReinhard * 255)
# Tonemap using Mantiuk's method to obtain 24-bit color image
tonemapMantiuk = cv2.createTonemapMantiuk(2.2,0.85, 1.2)
ldrMantiuk = tonemapMantiuk.process(hdrDebevec)
ldrMantiuk = 3 * ldrMantiuk
cv2.imwrite("ldr-Mantiuk.jpg", ldrMantiuk * 255)
if __name__=="__main__":
main()
| true |
4e4ab7d6fd76ab5364cf9595c7c4e5a390ecdc0a | Python | vladstulov/SFact | /Krest-nol_4x4.py | UTF-8 | 1,845 | 3.703125 | 4 | [] | no_license |
def show_field(f):
num =' 0 1 2 3'
print(num)
#zip
for row,i in zip(f,num.split()):
print (f"{i} {' '.join(str(j) for j in row)}")
def users_input(f,user):
while True:
place=input(f"Ходит {user} Введите координаты строка столбец:").split()
if len(place)!=2:
print('Введите две координаты')
continue
#is digit str
if not(place[0].isdigit() and place[1].isdigit()):
print('Введите числа')
continue
x, y = map(int, place)
if not(x>=0 and x<4 and y>=0 and y<4):
print('Вышли из диапазона')
continue
if f[x][y]!='-':
print('Клетка занята')
continue
break
return x,y
def win_position(f,user):
f_list=[]
print(f)
for l in f:
f_list+=l
print(f_list)
positions=[[0,1,2,3],[4,5,6,7],[8,9,10,11],[12,13,14,15],[0,4,8,12],[1,5,9,13],[2,6,10,14],[3,7,11,15],[0,5,10,15],[3,6,9,12]]
indices = set([i for i, x in enumerate(f_list) if x == user])
for p in positions:
if len(indices.intersection(set(p)))==4:
return True
return False
def start(field):
count=0
while True:
show_field(field)
if count%2==0:
user='x'
else:
user = 'o'
if count<16:
x, y = users_input(field,user)
field[x][y] = user
elif count==16:
print ('Ничья')
break
if win_position(field,user):
print(f"Выиграл {user}")
break
count+=1
field = [['-'] * 4 for _ in range(4)]
start(field) | true |
f08be0440ad50529c44157826fb19b9ab6055d7e | Python | gerrymandr/graphmaker | /graphmaker/reports/splitting.py | UTF-8 | 3,337 | 2.984375 | 3 | [
"MIT"
] | permissive | import numpy
from graphmaker.constants import fips_to_state_name
from graphmaker.resources import BlockAssignmentFile, BlockPopulationShapefile
def splitting_report_for_fips(fips, unit, part, function_for_splitting_energy=numpy.log):
df = load_matching_dataframe(fips, unit, part)
return splitting_report(df, unit, part, function_for_splitting_energy)
def splitting_report(df, unit, part, function_for_splitting_energy=numpy.log):
matrix, indices = splitting_matrix(df, unit, part, 'population')
information_distance = float(
splitting_energy(matrix, function=function_for_splitting_energy))
splitting_confidence_vector = splitting_confidence(
matrix).flatten().tolist()
unit_indices = {u: i for (u, p), (i, j) in indices.items()}
confidences = {
u: splitting_confidence_vector[i] for u, i in unit_indices.items()}
return {'unit': unit, 'partitioned_by': part,
'splitting_energy': information_distance,
'splitting_confidences': confidences}
def load_matching_dataframe(fips, unit, part, part_name='DISTRICT'):
blocks_to_parts = BlockAssignmentFile(fips).as_df(part)
blocks_to_parts = blocks_to_parts.set_index('BLOCKID')
blocks_to_units = BlockAssignmentFile(fips).as_df(unit)
blocks_to_units = blocks_to_units.set_index('BLOCKID')
blocks_to_units[part] = blocks_to_parts[part_name]
block_pops = BlockPopulationShapefile(fips).as_df()
blocks_to_units['population'] = block_pops['POP10']
return blocks_to_units
def splitting_matrix(df, unit, part, weight_column):
units = df[unit].unique()
parts = df[part].unique()
indices = {(u, p): (i, j) for (i, u) in enumerate(units)
for (j, p) in enumerate(parts)}
matrix = numpy.zeros((len(units), len(parts)))
grouped = df.groupby([unit, part])
for label, group in grouped:
matrix[indices[label]] = numpy.sum(group[weight_column].values)
return matrix, indices
def splitting_energy(matrix, function=numpy.log):
"""
Computes the conditional entropy splitting energy for the given
:matrix:, whose ij-th entry is expected to be the intersection
(in terms of population, area, or whatever the user wants)
of unit i with part j.
Uses :function: in place of `log` (default is`numpy.log`).
"""
total = numpy.sum(matrix)
unit_totals = numpy.sum(matrix, axis=1)
def prob_i_and_j(i, j):
return matrix[i, j] / total
def prob_j_given_i(i, j):
if unit_totals[i] == 0:
return 0
return matrix[i, j] / unit_totals[i]
def ijth_term(i, j):
inside = prob_j_given_i(i, j)
if inside == 0:
return 0
return prob_i_and_j(i, j) * function(inside)
return - numpy.sum(ijth_term(i, j) for (i, j) in numpy.ndindex(*matrix.shape))
def splitting_confidence(matrix):
"""
Index the units by i and the parts by j.
The splitting confidence vector is the vector whose ith coordinate is
the maximum over all j of the probability of being in part j, given
that you are in unit i. (The maximum over j of prob_j_given_i).
"""
vector = (numpy.amax(matrix, axis=1) / numpy.sum(matrix, axis=1)).flatten()
vector[vector == numpy.inf] = 0
vector = numpy.nan_to_num(vector)
return vector
| true |
861c40b22fe484eb33d51933f54f871d987219df | Python | cleancoindev/Qurry | /qurry/libraries/standard_library/constructs/bernoulli.py | UTF-8 | 276 | 2.609375 | 3 | [
"MIT"
] | permissive | from ..library.controlled import bernoulli as _bern
def bernoulli(p, q, rot='RX', kernel=None):
'''
Exploit an RX gate to create a simple bernoulli trial
(bernoulli 0.5 0) # Create the 0.5 state on qubit 0
'''
p = float(p)
return _bern(p, q, rot=rot)
| true |
c3f5693ba33bf1565e5ce9ca43f4ee0554dfe4b3 | Python | NeqroMa/DiceRollTest | /random_example.py | UTF-8 | 421 | 3.65625 | 4 | [] | no_license | import random
# pick a random number from 0 to n-1
n = 10
my_rand = random.randrange(n)
print(my_rand)
a = 2
b = 5
my_rand2 = random.randint(a,b)
my_rand3 = random.randrange(a,b)
print( f'{my_rand2} vs {my_rand3}')
my_rand4 = random.randrange(10) + 1
print(my_rand4)
"""
randint enables a result to be the biggest value while randrange can output only max-1 biggest value
"""
print(random.randrange(0,2)+1)
| true |
926492d26e22064e078a07f45221036f24f85168 | Python | atseng202/flask-blogly | /app.py | UTF-8 | 8,804 | 2.546875 | 3 | [] | no_license | """Blogly application."""
from flask import Flask, request, redirect, render_template, flash
from models import db, connect_db, User, Post, Tag, PostTag
from form_validation import is_form_invalid
from flask_debugtoolbar import DebugToolbarExtension
app = Flask(__name__)
app.config["SECRET_KEY"] = "SECRET!"
debug = DebugToolbarExtension(app)
app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql:///blogly"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["SQLALCHEMY_ECHO"] = True
connect_db(app)
db.create_all()
###### ROUTES FOR USERS ######
@app.route("/")
def redirect_to_users():
""" Redirects to /users path """
return redirect("/users")
@app.route("/users")
def show_all_users():
""" Show all users of app """
users = User.query.order_by(User.last_name, User.first_name).all()
return render_template("users.html", users=users)
@app.route("/users/new")
def show_new_user_form():
""" Show form to create a new user """
return render_template("user-new.html")
@app.route("/users/new", methods=["POST"])
def process_new_user_form():
"""Get the new user form data and flash error messages
if form input invalid or add the new user in the database
"""
first_name = request.form["first_name"] or None
last_name = request.form["last_name"] or None
image_url = request.form["image_url"] or None
form_input_labels = [("first_name", "First Name"), ("last_name", "Last Name")]
if is_form_invalid(request.form, form_input_labels):
return redirect("/users/new")
new_user = User(first_name=first_name, last_name=last_name, image_url=image_url)
db.session.add(new_user)
db.session.commit()
return redirect("/users")
@app.route("/users/<int:user_id>")
def show_user_page(user_id):
""" Shows the page of the user by the user ID """
user = User.query.get_or_404(user_id)
return render_template("user.html", user=user)
@app.route("/users/<int:user_id>/edit")
def show_edit_user_form(user_id):
""" Shows the edit page for the user """
user = User.query.get_or_404(user_id)
return render_template("user-edit.html", user=user)
@app.route("/users/<int:user_id>/edit", methods=["POST"])
def process_edit_user_form(user_id):
"""Get the edit user form data and flash error messages
if form input invalid or update user data in the database
"""
form_input_labels = [("first_name", "First Name"), ("last_name", "Last Name")]
if is_form_invalid(request.form, form_input_labels):
return redirect(f"/users/{user_id}/edit")
user = User.query.get(user_id)
user.first_name = request.form["first_name"] or None
user.last_name = request.form["last_name"] or None
user.image_url = request.form["image_url"] or None
db.session.commit()
return redirect("/users")
@app.route("/users/<int:user_id>/delete", methods=["POST"])
def delete_user(user_id):
""" Get the user from user_id and delete from database """
user = User.query.get(user_id)
db.session.delete(user)
db.session.commit()
return redirect("/users")
###### ROUTES FOR POSTS ######
@app.route("/users/<int:user_id>/posts/new")
def show_new_post_form(user_id):
""" Displays the page for adding a post """
user = User.query.get_or_404(user_id)
tags = Tag.query.all()
return render_template("post-new.html", user=user, tags=tags)
@app.route("/users/<int:user_id>/posts/new", methods=["POST"])
def process_new_post_form(user_id):
"""Get the new post form data and flash error messages
if form input invalid or add the new post in the database
"""
form_input_labels = [("post_title", "Title"), ("post_content", "Content")]
if is_form_invalid(request.form, form_input_labels):
return redirect(f"/users/{user_id}/posts/new")
User.query.get_or_404(user_id)
new_post = Post(
title=request.form["post_title"],
content=request.form["post_content"],
user_id=user_id,
)
tag_names = request.form.getlist("tag_name")
tags = Tag.query.filter(Tag.name.in_(tag_names)).all()
new_post.tags = tags
# May be inefficient to query this many times
# for tag_name in tag_names:
# new_tag = Tag.query.filter_by(name=tag_name).one()
# new_post.tags.append(new_tag)
db.session.add(new_post)
db.session.commit()
return redirect(f"/users/{user_id}")
@app.route("/posts/<int:post_id>")
def show_post_page(post_id):
""" Shows the post page by the post ID """
post = Post.query.get_or_404(post_id)
return render_template("post.html", post=post)
@app.route("/posts/<int:post_id>/edit")
def show_edit_post_form(post_id):
""" Shows the page to edit a post by the post ID """
post = Post.query.get_or_404(post_id)
tags = Tag.query.all()
return render_template("post-edit.html", post=post, all_tags=tags, initial_tags=post.tags)
@app.route("/posts/<int:post_id>/edit", methods=["POST"])
def process_edit_post_form(post_id):
"""Get the edit post form data and flash error messages
if form input invalid or edit the post in the database
"""
form_input_labels = [("post_title", "Title"), ("post_content", "Content")]
if is_form_invalid(request.form, form_input_labels):
return redirect(f"/posts/{post_id}/edit")
post = Post.query.get_or_404(post_id)
post.title = request.form["post_title"]
post.content = request.form["post_content"]
tag_names = request.form.getlist("tag_name")
# Use filter to grab updated tags, did not figure this out ourselves, tried to grab tags one by one
# see below
tags = Tag.query.filter(Tag.name.in_(tag_names)).all()
post.tags = tags
# PostTag.filter_by(tag_id=new_tag.id).delete()
# May be inefficient to query this many times
# for tag_name in tag_names:
# new_tag = Tag.query.filter_by(name=tag_name).one()
# post.tags.append(new_tag)
db.session.add(post)
db.session.commit()
return redirect(f"/posts/{post_id}")
@app.route("/posts/<int:post_id>/delete", methods=["POST"])
def delete_post(post_id):
""" Deletes the post with associated post id """
post = Post.query.get_or_404(post_id)
# db.session.delete(post)
# db.session.commit()
Post.query.filter_by(id=post_id).delete()
db.session.commit()
return redirect(f"/users/{post.user_id}")
###### ROUTES FOR TAGS ######
@app.route("/tags")
def show_tags():
""" Shows page with all tags """
tags = Tag.query.order_by(Tag.name).all()
return render_template("tags.html", tags=tags)
@app.route("/tags/<int:tag_id>")
def show_tag_page(tag_id):
""" Shows the page for tag details by tag_id """
tag = Tag.query.get_or_404(tag_id)
return render_template("tag.html", tag=tag)
@app.route("/tags/new")
def show_new_tag_form():
"""" Displays the page for adding a tag """
return render_template("tag-new.html")
@app.route("/tags/new", methods=["POST"])
def process_new_tag_form():
"""Get the new tag form data and flash error messages
if form input invalid or add the new tag in the database
"""
tag_name = request.form["tag_name"] or None
form_input_labels = [("tag_name", "Tag Name")]
if is_form_invalid(request.form, form_input_labels):
return redirect("/tags/new")
new_tag = Tag(name=tag_name)
db.session.add(new_tag)
db.session.commit()
return redirect("/tags")
@app.route("/tags/<int:tag_id>/edit")
def show_edit_tag_form(tag_id):
""" Shows the page to edit a tag by the tag ID """
tag = Tag.query.get_or_404(tag_id)
return render_template("tag-edit.html", tag=tag)
@app.route("/tags/<int:tag_id>/edit", methods=["POST"])
def process_edit_tag_form(tag_id):
"""Get the edit tag form data and flash error messages
if form input invalid or edit the tag in the database
"""
Tag.query.get_or_404(tag_id)
tag_name = request.form["tag_name"] or None
form_input_labels = [("tag_name", "Tag Name")]
if is_form_invalid(request.form, form_input_labels):
return redirect(f"/tags/{tag_id}/edit")
tag = Tag.query.get(tag_id)
tag.name = tag_name
db.session.add(tag)
db.session.commit()
return redirect("/tags")
@app.route("/tags/<int:tag_id>/delete", methods=["POST"])
def delete_tag(tag_id):
""" Deletes the tag with associated tag id """
Tag.query.get_or_404(tag_id)
PostTag.query.filter_by(tag_id=tag_id).delete()
Tag.query.filter_by(id=tag_id).delete()
db.session.commit()
return redirect("/tags")
### ERROR ROUTE ###
@app.errorhandler(404)
def page_not_found(e):
""" Shows the error page when user browses a page that does not exist """
return render_template("404_error.html"), 404
| true |
c89e7b321275288b358d0c23c1015cde8febbfb8 | Python | Kamala16/python-fais | /zestaw_03/poprawnoscKodu1.py | UTF-8 | 304 | 4.1875 | 4 | [] | no_license | # I Część - jest poprawny
x = 2 ; y = 3;
if (x > y):
result = x;
else:
result = y;
#II Część - nie jest poprawny
#for i in "qwerty": if ord(i) < 100: print (i)
#III Część - nie jest poprawny w python 3 (trzeba dodać nawiasy)
#for i in "axby": print ord(i) if ord(i) < 100 else i
| true |
adc3d2e74a9fec4f31fd1816320ee6128b78d7af | Python | lychengrex/Image-Denoising-with-Deep-CNNs | /src/nntools.py | UTF-8 | 12,684 | 3.15625 | 3 | [
"MIT"
] | permissive | """
Neural Network tools developed for UCSD ECE285 MLIP.
Copyright 2019. Charles Deledalle, Sneha Gupta, Anurag Paul, Inderjot Saggu.
"""
import os
import time
import torch
from torch import nn
import torch.utils.data as td
from abc import ABC, abstractmethod
class NeuralNetwork(nn.Module, ABC):
"""An abstract class representing a neural network.
All other neural network should subclass it. All subclasses should override
``forward``, that makes a prediction for its input argument, and
``criterion``, that evaluates the fit between a prediction and a desired
output. This class inherits from ``nn.Module`` and overloads the method
``named_parameters`` such that only parameters that require gradient
computation are returned. Unlike ``nn.Module``, it also provides a property
``device`` that returns the current device in which the network is stored
(assuming all network parameters are stored on the same device).
"""
def __init__(self):
super(NeuralNetwork, self).__init__()
@property
def device(self):
# This is important that this is a property and not an attribute as the
# device may change anytime if the user do ``net.to(newdevice)``.
return next(self.parameters()).device
def named_parameters(self, recurse=True):
nps = nn.Module.named_parameters(self)
for name, param in nps:
if not param.requires_grad:
continue
yield name, param
@abstractmethod
def forward(self, x):
pass
@abstractmethod
def criterion(self, y, d):
pass
class StatsManager(object):
"""
A class meant to track the loss during a neural network learning experiment.
Though not abstract, this class is meant to be overloaded to compute and
track statistics relevant for a given task. For instance, you may want to
overload its methods to keep track of the accuracy, top-5 accuracy,
intersection over union, PSNR, etc, when training a classifier, an object
detector, a denoiser, etc.
"""
def __init__(self):
self.init()
def __repr__(self):
"""Pretty printer showing the class name of the stats manager. This is
what is displayed when doing ``print(stats_manager)``.
"""
return self.__class__.__name__
def init(self):
"""Initialize/Reset all the statistics"""
self.running_loss = 0
self.number_update = 0
def accumulate(self, loss, x=None, y=None, d=None):
"""Accumulate statistics
Though the arguments x, y, d are not used in this implementation, they
are meant to be used by any subclasses. For instance they can be used
to compute and track top-5 accuracy when training a classifier.
Arguments:
loss (float): the loss obtained during the last update.
x (Tensor): the input of the network during the last update.
y (Tensor): the prediction of by the network during the last update.
d (Tensor): the desired output for the last update.
"""
self.running_loss += loss
self.number_update += 1
def summarize(self):
"""Compute statistics based on accumulated ones"""
return self.running_loss / self.number_update
class Experiment(object):
"""
A class meant to run a neural network learning experiment.
After being instantiated, the experiment can be run using the method
``run``. At each epoch, a checkpoint file will be created in the directory
``output_dir``. Two files will be present: ``checkpoint.pth.tar`` a binary
file containing the state of the experiment, and ``config.txt`` an ASCII
file describing the setting of the experiment. If ``output_dir`` does not
exist, it will be created. Otherwise, the last checkpoint will be loaded,
except if the setting does not match (in that case an exception will be
raised). The loaded experiment will be continued from where it stopped when
calling the method ``run``. The experiment can be evaluated using the method
``evaluate``.
Attributes/Properties:
epoch (integer): the number of performed epochs.
history (list): a list of statistics for each epoch.
If ``perform_validation_during_training``=False, each element of the
list is a statistic returned by the stats manager on training data.
If ``perform_validation_during_training``=True, each element of the
list is a pair. The first element of the pair is a statistic
returned by the stats manager evaluated on the training set. The
second element of the pair is a statistic returned by the stats
manager evaluated on the validation set.
Arguments:
net (NeuralNetork): a neural network.
train_set (Dataset): a training data set.
val_set (Dataset): a validation data set.
stats_manager (StatsManager): a stats manager.
output_dir (string, optional): path where to load/save checkpoints. If
None, ``output_dir`` is set to "experiment_TIMESTAMP" where
TIMESTAMP is the current time stamp as returned by ``time.time()``.
(default: None)
batch_size (integer, optional): the size of the mini batches.
(default: 16)
perform_validation_during_training (boolean, optional): if False,
statistics at each epoch are computed on the training set only.
If True, statistics at each epoch are computed on both the training
set and the validation set. (default: False)
"""
def __init__(self, net, train_set, val_set, optimizer, stats_manager,
output_dir=None, batch_size=16, perform_validation_during_training=False):
# Define data loaders
train_loader = td.DataLoader(train_set, batch_size=batch_size, shuffle=True,
drop_last=True, pin_memory=True)
val_loader = td.DataLoader(val_set, batch_size=batch_size, shuffle=False,
drop_last=True, pin_memory=True)
# Initialize history
history = []
# Define checkpoint paths
if output_dir is None:
output_dir = 'experiment_{}'.format(time.time())
os.makedirs(output_dir, exist_ok=True)
checkpoint_path = os.path.join(output_dir, "checkpoint.pth.tar")
config_path = os.path.join(output_dir, "config.txt")
# Transfer all local arguments/variables into attributes
locs = {k: v for k, v in locals().items() if k is not 'self'}
self.__dict__.update(locs)
# Load checkpoint and check compatibility
if os.path.isfile(config_path):
with open(config_path, 'r') as f:
if f.read()[:-1] != repr(self):
raise ValueError(
"Cannot create this experiment: "
"I found a checkpoint conflicting with the current setting.")
self.load()
else:
self.save()
@property
def epoch(self):
"""Returns the number of epochs already performed."""
return len(self.history)
def setting(self):
"""Returns the setting of the experiment."""
return {'Net': self.net,
'TrainSet': self.train_set,
'ValSet': self.val_set,
'Optimizer': self.optimizer,
'StatsManager': self.stats_manager,
'BatchSize': self.batch_size,
'PerformValidationDuringTraining': self.perform_validation_during_training}
def __repr__(self):
"""Pretty printer showing the setting of the experiment. This is what
is displayed when doing ``print(experiment)``. This is also what is
saved in the ``config.txt`` file.
"""
string = ''
for key, val in self.setting().items():
string += '{}({})\n'.format(key, val)
return string
def state_dict(self):
"""Returns the current state of the experiment."""
return {'Net': self.net.state_dict(),
'Optimizer': self.optimizer.state_dict(),
'History': self.history}
def load_state_dict(self, checkpoint):
"""Loads the experiment from the input checkpoint."""
self.net.load_state_dict(checkpoint['Net'])
self.optimizer.load_state_dict(checkpoint['Optimizer'])
self.history = checkpoint['History']
# The following loops are used to fix a bug that was
# discussed here: https://github.com/pytorch/pytorch/issues/2830
# (it is supposed to be fixed in recent PyTorch version)
for state in self.optimizer.state.values():
for k, v in state.items():
if isinstance(v, torch.Tensor):
state[k] = v.to(self.net.device)
def save(self):
"""Saves the experiment on disk, i.e, create/update the last checkpoint."""
torch.save(self.state_dict(), self.checkpoint_path)
with open(self.config_path, 'w') as f:
print(self, file=f)
def load(self):
"""Loads the experiment from the last checkpoint saved on disk."""
checkpoint = torch.load(self.checkpoint_path,
map_location=self.net.device)
self.load_state_dict(checkpoint)
del checkpoint
def run(self, num_epochs, plot=None):
"""Runs the experiment, i.e., trains the network using backpropagation
based on the optimizer and the training set. Also performs statistics at
each epoch using the stats manager.
Arguments:
num_epoch (integer): the number of epoch to perform.
plot (func, optional): if not None, should be a function taking a
single argument being an experiment (meant to be ``self``).
Similar to a visitor pattern, this function is meant to inspect
the current state of the experiment and display/plot/save
statistics. For example, if the experiment is run from a
Jupyter notebook, ``plot`` can be used to display the evolution
of the loss with ``matplotlib``. If the experiment is run on a
server without display, ``plot`` can be used to show statistics
on ``stdout`` or save statistics in a log file. (default: None)
"""
self.net.train()
self.stats_manager.init()
start_epoch = self.epoch
print("Start/Continue training from epoch {}".format(start_epoch))
if plot is not None:
plot(self)
for epoch in range(start_epoch, num_epochs):
s = time.time()
self.stats_manager.init()
for x, d in self.train_loader:
x, d = x.to(self.net.device), d.to(self.net.device)
self.optimizer.zero_grad()
y = self.net.forward(x)
loss = self.net.criterion(y, d)
loss.backward()
self.optimizer.step()
with torch.no_grad():
self.stats_manager.accumulate(loss.item(), x, y, d)
if not self.perform_validation_during_training:
self.history.append(self.stats_manager.summarize())
print("Epoch {} | Time: {:.2f}s | Training Loss: {:.6f}".format(
self.epoch, time.time() - s, self.history[-1][0]['loss']))
else:
self.history.append(
(self.stats_manager.summarize(), self.evaluate()))
print("Epoch {} | Time: {:.2f}s | Training Loss: {:.6f} | Evaluation Loss: {:.6f}".format(
self.epoch, time.time() - s, self.history[-1][0]['loss'], self.history[-1][1]['loss']))
self.save()
if plot is not None:
plot(self)
print("Finish training for {} epochs".format(num_epochs))
def evaluate(self):
"""Evaluates the experiment, i.e., forward propagates the validation set
through the network and returns the statistics computed by the stats
manager.
"""
self.stats_manager.init()
self.net.eval()
with torch.no_grad():
for x, d in self.val_loader:
x, d = x.to(self.net.device), d.to(self.net.device)
y = self.net.forward(x)
loss = self.net.criterion(y, d)
self.stats_manager.accumulate(loss.item(), x, y, d)
self.net.train()
return self.stats_manager.summarize()
| true |
1a710ac65bb0e17b3d95b8f7a62bde205077ec1f | Python | Mundhey/Code-Monk-Hacker-Earth | /Basic Programming/Product.py | UTF-8 | 153 | 2.765625 | 3 | [] | no_license | N=int(raw_input())
numArray = map(int, raw_input().split())
prod=1
for i in range(0,N):
prod=prod*numArray[i]
prod=prod % (pow(10,9)+7)
print prod | true |
9bd3128d732ff27d680306a05cad5db621fd03e4 | Python | lpr014/omega | /Divide.py | UTF-8 | 636 | 3.421875 | 3 | [] | no_license | # Created by Lorantz on 9/28/17 6:15 PM
# Last edit by Lorantz on 9/29/17 5:20 PM
def divide(num1, num2):
# divide by zero error check
if num2 == 0:
print("CANNOT DIVIDE BY ZERO")
return
else:
ans=num1/num2
return ans
# remainder using the % symbol
def mod(num1, num2):
if num2==0:
print("CANNOT DIVIDE BY ZERO")
return
else:
ans=num1%num2
return ans
# used for integer division with the "//" symbol
def whole(num1, num2):
if num2==0:
print("CANNOT DIVIDE BY ZERO")
return
else:
ans=num1//num2
return ans
| true |
27fbc6e39f543885d4d2e07e8d91546d7bc8e4bd | Python | luggroo/224u_dating_classical_chinese | /crawl.py | UTF-8 | 458 | 2.796875 | 3 | [] | no_license | import codecs
import re
f = codecs.open('Chinese Text Project.html', encoding='utf-8')
lines = []
file = open("booktitles.txt","wb")
for line in f:
if ("class=\"sprite-expand\" title=\"+\">+<div style=\"display: inline;\"></div></a></div><a" in line):
a = re.findall(r'href=\"([^\"]*?)\">([^<]*?)</a>', line)
print(a)
uni = (a[0][0]+" , "+a[0][1]+"\n").encode('utf-8')
print(uni)
file.write(uni)
| true |
f04c2d56ef665c621770043d0ae9fb1df65ab746 | Python | nabetama/gimei | /tests/test_name.py | UTF-8 | 1,224 | 3.53125 | 4 | [
"MIT"
] | permissive | # coding: utf-8
from gimei import Gimei
from gimei import Name
class TestName(object):
def test_kanji_name_in_data(self):
name = Gimei().name
assert Name.find_name_by_kanji(name.kanji)
def test_hiragana_name_in_data(self):
name = Gimei().name
assert Name.find_name_by_hiragana(name.hiragana)
def test_katakana_name_in_data(self):
name = Gimei().name
assert Name.find_name_by_katakana(name.katakana)
def test_str(self):
name = Gimei().name
name.first.all = ['糸央', 'いお', 'イオ']
name.last.all = ['大木', 'おおき', 'オオキ']
assert str(name) == '大木 糸央'
def test_repr(self):
name = Gimei().name
name.gender = 'female'
name.first.all = ['七祐', 'なゆ', 'ナユ']
name.last.all = ['佐野', 'さの', 'サノ']
assert repr(name) == "Name(gender='female', first=['七祐', 'なゆ', 'ナユ'], last=['佐野', 'さの', 'サノ'])"
def test_create_name_from_gender(self):
name = Gimei('male').name
assert name.is_male
def test_create_name_from_gender(self):
name = Gimei('female').name
assert name.is_female
| true |
81956b102ab0fca330fa7d1f8945afef81b6b6ce | Python | Brunochavesg/Guanabara | /ex009.py | UTF-8 | 423 | 3.75 | 4 | [
"MIT"
] | permissive | n1 = int(input ("Digite um numero: "))
print ("=" * 15)
print (f"{n1} x {1:2} = {n1 * 1}")
print (f"{n1} x {2:2} = {n1 * 2}")
print (f"{n1} x {3:2} = {n1 * 3}")
print (f"{n1} x {4:2} = {n1 * 4}")
print (f"{n1} x {5:2} = {n1 * 5}")
print (f"{n1} x {6:2} = {n1 * 6}")
print (f"{n1} x {7:2} = {n1 * 7}")
print (f"{n1} x {8:2} = {n1 * 8}")
print (f"{n1} x {9:2} = {n1 * 9}")
print (f"{n1} x {10} = {n1 * 10}")
print ("=" * 15)
| true |
49a596c4cd34e0437ded60748d9a51726f83837b | Python | mdukat/anonupload | /config.py | UTF-8 | 1,175 | 2.78125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/python3
import os
home = os.environ['HOME']
config_file = open(home + '/.config/anonupload', 'w')
print("Hi! I will ask you some questions, read carefully!")
print("What server do you want to use? [anonfile, megaupload, bayfiles, none]")
server = input()
if(server not in ('anonfile', 'megaupload', 'bayfiles')):
print("I dont know what you typed, using anonfile.")
server = 'anonfile'
print("Please enter your API key for this server, or if you dont have one, press enter:")
api = input()
if(api == ''):
api = None
print("Okay, now please enter your public GPG key name (it's case sensitive!), or if you don't have one, press enter")
gpg = input()
if(gpg == ''):
gpg = None
#print("Cool, do you want to save links to file so later you can download them fast? (y/n)")
#files = input()
#if(files == 'y'):
# files = True
#else:
# files = False
print("Fine, now i will write new config...")
config_file.write('SERVER:' + server + '\n')
if(api != None):
config_file.write('API:' + api + '\n')
if(gpg != None):
config_file.write('GPG:' + gpg + '\n')
#if(files != False):
# config_file.write('FILES_LIST:true\n')
print("Done everything! Have a nice day :)")
| true |
43ec17d54890a8190a0b5d1eb8b5e669823633d7 | Python | uyth/pu | /test_environment.py | UTF-8 | 1,866 | 3.5 | 4 | [] | no_license | from course_schedule.course_details import *
def stars():
print("*" * 69)
def print_stuff(code, program):
print()
print()
stars()
print("*" * 20 + " PARRY'S METHOD TESTER " + "*" * 20)
stars()
print("Current course: " + code.upper())
print("Current program: " + program.upper())
print()
print("get_course_ ...")
print("1. Name")
print("2. Code")
print("3. Description")
print("4. Exam date")
print("5. Days until exam")
print("6. Schedule")
print("7. Credits")
print()
print("\'C\' to change code")
print("\'P\' to change program")
print("\'Q\' to quit")
print("\'M\' for menu")
stars()
print()
def main():
code = "tdt4145"
program = "MTDT"
print_stuff(code, program)
while True:
ans = input("Action:\n>> ")
if ans == '1':
stars()
print(get_name(code))
stars()
elif ans == '2':
stars()
print(code.upper())
stars()
elif ans == '3':
stars()
print(get_description(code))
stars()
elif ans == '4':
stars()
print(get_exam_date_readable(code))
stars()
elif ans == '5':
stars()
print(get_days_until(code))
stars()
elif ans == '6':
stars()
print(get_schedule(code, program))
stars()
elif ans == '7':
stars()
print(get_credits(code))
stars()
elif ans == "P":
program = input("New program:\n>> ")
elif ans == "C":
code = input("New course:\n>> ")
elif ans == 'M':
print_stuff(code, program)
elif ans == "Q":
break
if __name__ == '__main__':
main()
| true |
2a224b1e9320afebe4fb1a783b4cba7ab57387f7 | Python | undugy/2017182020_2Dproject | /final project/game/CPlayer.py | UTF-8 | 4,699 | 2.578125 | 3 | [] | no_license | from pico2d import *
import gfw
import win32api
from gobj import *
import CBullet
import CHyperion
class Player():
playertype=0
def __init__(self):
self.x, self.y = 0, 90
self.image = load_image('Resource/Player_T.png')
self.image2 = load_image('Resource/Player_T2.png')
self.image3 = load_image('Resource/Player_T3.png')
self.image4 = load_image('Resource/Player_T4.png')
self.image5 = load_image('Resource/Player_T5.png')
self.Frame=3##speed
self.Time=0
self.Interval=0
self.PlayerState=0
self.Life = 3
self.PreLife=self.Life
self.Gage=0
self.LagerTime=0
self.Power=0#플레이어 파워
self.BombNumber=2 #필살기개수
self.IsShield=False
self.ShieldTime=0
self.SuperMode =False
def Player_LifeSystem(self):
#0x44 D
if win32api.GetAsyncKeyState(0x44) & 0x1001:
if self.SuperMode is True:
self.SuperMode=False
elif self.SuperMode is False:
self.SuperMode=True
if self.PreLife !=self.Life:
self.IsShield=True
self.PreLife=self.Life
if self.IsShield is True:
#self.Life-=1
self.ShieldTime +=gfw.delta_time
if self.ShieldTime > 3:
self.ShieldTime=0
self.IsShield=False
def fire(self):
if win32api.GetAsyncKeyState(0x20) & 0x8000 and self.Interval>=1: # space
self.Interval=0
bullet=CBullet.Bullet(self.x,self.y+20)
gfw.world.add(gfw.layer.CBullet,bullet)
def Make_Hyperion(self):
if win32api.GetAsyncKeyState(0x53) & 0x1001 and self.BombNumber >= 1 : # s:
self.BombNumber -= 1
Ch=CHyperion.Hyperion(360, 0)
gfw.world.add(gfw.layer.CHyperion,Ch)
Lh=CHyperion.Hyperion(200, -100)
gfw.world.add(gfw.layer.CHyperion,Lh)
Rh=CHyperion.Hyperion(520, -100)
gfw.world.add(gfw.layer.CHyperion,Rh)
def Make_Lager(self):
if gfw.world.count_at(gfw.layer.CLazer) >0:
self.LagerTime+=gfw.delta_time*2
if win32api.GetAsyncKeyState(0x41) & 0x1001:
if gfw.world.count_at(gfw.layer.CLazer) == 0 and self.Gage>20:# a
LayL=CBullet.Player_Lager(14)
gfw.world.add(gfw.layer.CLazer,LayL)
LayR=CBullet.Player_Lager(-25)
gfw.world.add(gfw.layer.CLazer,LayR)
elif self.LagerTime> 3 and gfw.world.count_at(gfw.layer.CLazer) >0:
self.LagerTime=0
for Lager in gfw.world.objects_at(gfw.layer.CLazer):
Lager.isDead=True
pass
def update(self):
self.Player_LifeSystem()
self.Make_Lager()
self.Make_Hyperion()
self.fire()
self.Interval += (20 * gfw.delta_time)
self.x = clamp(40, self.x, 720)
self.Gage=clamp(0, self.Gage,100)
self.y=clamp(40,self.y,960)
if(win32api.GetAsyncKeyState(0x25) & 0x8000 or win32api.GetAsyncKeyState(0x26) & 0x8000
or win32api.GetAsyncKeyState(0x27) & 0x8000 or win32api.GetAsyncKeyState(0x28) & 0x8000):
if win32api.GetAsyncKeyState(0x25) & 0x8000:
self.x-= 400 * gfw.delta_time
if win32api.GetAsyncKeyState(0x27) & 0x8000:
self.x += 400 * gfw.delta_time
if win32api.GetAsyncKeyState(0x26) & 0x8000: # UP
self.y +=400 * gfw.delta_time
if win32api.GetAsyncKeyState(0x28) & 0x8000: #DOWN
self.y -= 400 * gfw.delta_time
else:
PlayerState=0
self.Time=(self.Time+1)%50
if win32api.GetAsyncKeyState(0x25) & 0x8000 and self.Time>=48:
self.Frame -=1
if win32api.GetAsyncKeyState(0x27) & 0x8000 and self.Time>=48:
self.Frame +=1
if self.Frame<=0:
self.Frame=0
if self.Frame>=6:
self.Frame=6
def draw(self):
if Player.playertype==1:
self.image5.clip_draw(3*33, 0, 33, 33, self.x, self.y,80,80)
elif Player.playertype==2:
self.image3.clip_draw(3*33, 0, 33, 33, self.x, self.y,80,80)
elif Player.playertype==3:
self.image4.clip_draw(3*32, 0, 33, 33, self.x, self.y,80,80)
elif Player.playertype==4:
self.image.clip_draw(3*33, 0, 33, 33, self.x, self.y,80,80)
elif Player.playertype==5:
self.image2.clip_draw(3*33, 0, 33, 33, self.x, self.y,80,80)
| true |
0fec682b8002a70fc1ed644337dafcbcf46f7b88 | Python | victortd/GeometricMethods_CS | /code_mapreduce/job1_mapper.py | UTF-8 | 349 | 3.359375 | 3 | [] | no_license | #!/usr/bin/env python
#job 1
#mapper_1
import os
import sys
value=[0,0]
for line in sys.stdin:
"""
the input line is "key x y z"
the output is (key, "x y z")
"""
#we get the key
value[0] = line.split(' ')[0]
#we get the three coordinates
value[1] = line[line.find(' '):-1]
#we print the output
print '{},{}'.format(value[0],value[1])
| true |
ffd046de296ab75cf6eaca0581cbc51c68772cfd | Python | g573179240/spider | /scrapy/Douyu/Douyu/spiders/douyu.py | UTF-8 | 1,383 | 2.75 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import scrapy
import json
from Douyu.items import DouyuItem
class DouyuSpider(scrapy.Spider):
name = 'douyu'
allowed_domains = ['capi.douyucdn.cn']
baseUrl = "http://capi.douyucdn.cn/api/v1/getVerticalRoom?limit=20&offset="
offset = 0
start_urls = [ baseUrl + str(offset) ]
def parse(self, response):
# response为json格式的数据
# 先把响应转成python数据类型
nickList = json.loads(response.text)["data"]
# nickList : [{},{},{}]
# 如果nickList为空,说明爬取完毕
if len(nickList) == 0:
return
for nick in nickList:
# nick : {1个主播的详细信息}
item = DouyuItem()
item["imgLink"] = nick["vertical_src"]
item["nickName"] = nick["nickname"]
item["nickCity"] = nick["anchor_city"]
yield item
# 实现翻页功能
self.offset += 20
yield scrapy.Request(
self.baseUrl+str(self.offset),
callback = self.parse
)
# {
# "errorcode":0,
# "data":[
# {
# vertical_src: "https://rpic.douyucdn.cn/live-cover/roomCover/2018/10/31/8edeac935f91eafb7aa90a24a8932598_small.jpg",
# nickname: "一坨柠檬酱",
# anchor_city: "成都市"
# },
# ]
# }
| true |
0f3d4662274f5bf16eff984ad7128d0ebd06c995 | Python | mgorgei/codeeval | /Easy/c93 Capitalize Words.py | UTF-8 | 543 | 4.21875 | 4 | [] | no_license | '''CAPITALIZE WORDS
Write a program which capitalizes the first letter of each word in a sentence.
INPUT SAMPLE:
Your program should accept as its first argument a path to a filename. Input
example is the following
Hello world
javaScript language
a letter
1st thing
OUTPUT SAMPLE:
Print capitalized words in the following way.
Hello World
JavaScript Language
A Letter
1st Thing
'''
def f(test='Hello world'):
test = test.rstrip().split()
result = [word[0].upper() + word[1:] for word in test]
print(' '.join(result))
| true |
4ca937367afe64a053529d837edd527a940ab19b | Python | ZwangaMukwevho/Design | /APIcode/driver.py | UTF-8 | 4,335 | 2.8125 | 3 | [
"MIT"
] | permissive | import os
import subprocess
import fileManager
import time
import fileTransfer
import admin
FM = fileManager.fileManager()
FT = fileTransfer.fileTransfer()
AD = admin.admin()
class runner:
def welcome():
os.system('clear')
print(" _________ _____ ")
print("| | | | | / \ ")
print("| | | | | / \ ")
print("|--------| | -------- | | | | ")
print("| | | | | \ / ")
print("| | |_________ |_________ |_________ \ _____ / ")
print("")
print("-------------------------------------------------------------")
print("")
#https://my.eng.utah.edu/~cs5480/homeworks/hw4_soln.pdf
def mainMenu():
option = input("Select an option: D - Download | S - Search | E - delete | T - Transfer file | Q - Quit\n")
option = option.upper()
if option == "D":
option2 = input("Press 1 the link is from a website that requires logging in, press 2 if the website does not require user logging in - Quit\n\n")
if option2 == "2":
downloadLink = input("Please enter download link: \n")
# Downloading the file using fileManager class
uList =FM.splitUrl(downloadLink)
if uList == 'invalid URL given':
print("invalid download link given\n")
else:
name = FM.obtainName(uList)
typ = FM.obtainType(uList)
output = FM.donwloadFile(downloadLink,name,typ )
print("download successful :-) \n")
print("")
time.sleep(1)
elif option2 == "1":
name = input("Enter your username: \n")
password = input("Enter your password: \n")
downloadLink = input("Enter the link to the file to be downloaded: \n")
# Downloading the file using fileManager class
uList =FM.splitUrl(downloadLink)
fileName = FM.obtainName(uList)
typ = FM.obtainType(uList)
outName = fileName + "." + typ
if uList == 'invalid URL given':
print("invalid download link given\n")
else:
FM.authDownload(downloadLink,name,password,outName )
print("download successful :-) \n")
else:
print("Invalid option chosen")
print()
elif option == "S":
searchName = input("Please enter the name of the file: \n")
output = FM.searchFile(searchName)
outLength = len(output)
if outLength == 0:
time.sleep(1)
print("Unfortunately the file was not found :(")
else:
time.sleep(1)
print("The file "+searchName+" exists")
print("")
elif option == "E":
deleteName = input("Please enter the name of the file to be deleted: \n")
output = FM.deleteFile(deleteName)
print("")
time.sleep(1)
elif option == "Q":
time.sleep(1)
print("Come back soon to get more files")
exit()
elif option == "T":
print("connect to server below to get your file, Make sure you are connected to eduroam")
FT.getIP()
time.sleep(1)
else:
print("Invalid option, please choose one from the ones given below")
time.sleep(1)
def login():
login = input("Welcome, select an option below\n1 - sign in: | 2 - sign up \n")
if login == "1":
name = input("Enter your username \n")
password = input("Enter your password\n")
checkBool = AD.check(name,password)
if (checkBool):
time.sleep(0.3)
os.system('clear')
print("welcome "+name)
return False
else:
time.sleep(0.3)
print("Sorry, wrong username or password was entered , please recheck your cridentials and sign in again")
return True
elif login == "2":
print("welcome new user \n")
name = input("Enter your username that you will use in log in \n")
password = input("Enter your password that you will use to log in\n")
checkBool = AD.createUser(name,password)
time.sleep(0.3)
print("Congratulations, you have been successfully reqistered, now choose option 1 to sign in with your current details\n")
return True
else:
print("Oops, you entered an unknown option, please choose between 1 and 2")
time.sleep(0.3)
if __name__ == "__main__":
try:
welcome()
checkLogin = login()
while(checkLogin):
checkLogin = login()
while True:
mainMenu()
pass
except Exception as e:
print(e)
| true |
56ff946586cb43995aafbdf4eebc9fa1a23a8725 | Python | VladBaryliuk/my_start_tasks | /new/src/06.02.2021/to letter i.py | UTF-8 | 347 | 3.328125 | 3 | [
"Apache-2.0"
] | permissive | alfabet ="абвгдеёжзийклмнопрстуфхцчшщъыьэюя"
human_string = str(input("enter your string in the russian language"))
def before_letter_i():
global human_string
for i in human_string:
if i < "и":
human_string = human_string.replace(i, "")
return human_string
print(before_letter_i()) | true |
f797f8730edfe2335659c4e0cc2e6477848e3206 | Python | rbyrne08/QuantCreation | /APIPull.py | UTF-8 | 1,562 | 2.890625 | 3 | [] | no_license | import requests
import time
import pandas as pd
from config import client_id
import plotly.graph_objects as go
#The daily prices endpoints
def pricehistory():
#Define endpoint
endpoint = r"https://api.tdameritrade.com/v1/marketdata/{}/pricehistory".format('AMD')
#Define payload
payload = {'apikey':client_id,
'periodType': 'day',
'frequencyType':'minute',
'frequency':'1',
'period':'2',
'endDate':int(time.time()*1000),
'startDate':int(time.mktime((2020,1,1,0,0,0,0,0,0))*1000),
'needExtendedHours':'true'
}
#make a request
content = requests.get(url=endpoint,params=payload)
data = content.json()
dataframe = pd.DataFrame.from_dict(data.get("candles"))
dataframe['date'] = pd.to_datetime(dataframe['datetime'],unit='ms')
print(dataframe)
fig = go.Figure(data=[go.Candlestick(x=dataframe['date'],
open=dataframe['open'],
high=dataframe['high'],
low=dataframe['low'],
close=dataframe['close'])])
fig.show()
def getQuote():
#Define endpoint
endpoint = r"https://api.tdameritrade.com/v1/marketdata/{}/quotes".format('AMD')
#Define payload
payload = {'apikey':client_id}
#make a request
content = requests.get(url=endpoint,params=payload)
data = content.json()
print(data)
pricehistory() | true |
fa74fbccddc048dda2f1d625e0835ba8fbee90e5 | Python | hmbtl/ejob_parser | /ejob/spiders/bossFull.py | UTF-8 | 5,278 | 2.65625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import scrapy, dateparser
class BossFullSpider(scrapy.Spider):
name = 'bossFull'
allowed_domains = ['boss.az']
start_urls = ['http://boss.az']
def parse(self, response):
# create empty dict
categories = [];
sub_categories = [];
# for each option in categories
for cat in response.xpath('//select[@id="search_category_id"]/option[contains(@value, "")]'):
# get category name
cat_name = cat.xpath('.//text()').get();
# get category id
cat_id = cat.xpath('.//@value').get();
# create category dict
cat_dict = {
"id":cat_id,
"cat_name": cat_name.strip("— ")
}
# if option is main category
if "— " not in cat_name:
# if already have sub_categories then add to category array
if len(sub_categories) != 0:
# create new key for dict to add sub_categories
cat_main_dict['sub_categories'] = sub_categories;
# add new dictionary to categories array
categories.append(cat_main_dict);
# remove all elements of sub_categories
sub_categories = [];
cat_main_dict = cat_dict
else:
sub_categories.append(cat_dict);
# create new key for dict to add sub_categories
cat_main_dict['sub_categories'] = sub_categories;
# add new dictionary to categories array
categories.append(cat_main_dict);
for cat in categories:
sub_cats = []
for sub_cat in cat['sub_categories']:
yield sub_cat
yield cat
def parseJobs(self, response):
for jobs in response.xpath('//div[@class="results-i"]'):
url = jobs.xpath(".//div[@class='results-i-salary-and-link']/a[@class='results-i-link']/@href").get()
yield scrapy.Request(response.urljoin(url), callback=self.parse_detail)
next_page = response.xpath('//span[@class="next"]/a/@href').get()
if next_page is not None:
yield scrapy.Request(response.urljoin(next_page))
def decode_email(self, e):
de = ""
k = int(e[:2], 16)
for i in range(2, len(e)-1, 2):
de += chr(int(e[i:i+2], 16)^k)
return de
def parse_detail(self, response):
# get start date and parse to correct string
start_date_str = response.xpath('//div[@class="bumped_on params-i-val"]/text()').get()
start_date = dateparser.parse(start_date_str).strftime('%d/%m/%Y')
# get end date and parse to correct string
end_date_str = response.xpath('//div[@class="expires_on params-i-val"]/text()').get()
end_date = dateparser.parse(end_date_str).strftime('%d/%m/%Y')
# get candidate ages
age = response.xpath('//div[@class="age params-i-val"]/text()').re("\d+")
# get candidate work experience
experience = response.xpath('//div[@class="experience params-i-val"]/text()').re("\d+")
# get salary
salary = response.xpath('//span[@class="post-salary salary"]/text()').re("\d+");
# get encoded email
encoded_email = response.xpath('//div[@class="email params-i-val"]/a/@href').get().split("#")[-1]
email = self.decode_email(encoded_email)
# yield values
yield {
'id': response.xpath('//div[@class="post-header-secondary"]/text()').re("\d+")[1],
'url': response.url,
'title': response.xpath('//h1[@class="post-title"]/text()').get(),
'city': response.xpath('//div[@class="region params-i-val"]/text()').get(),
'salary': {
'min': (salary[0] if len(salary) > 0 else None), # if has atleast 1 item then get first as min
'max': (salary[1] if len(salary) > 1 else None) # if has atleast 2 items then get second as max
},
'age': {
'min': (age[0] if len(age) > 0 else None), # if has atleast 1 item then get first as min
'max': (age[1] if len(age) > 1 else None) # if has atleast 2 items then get second as max
},
'experience': {
"min": (experience[0] if len(experience) > 0 else None), # if has atleast 1 item then get first as min
"max": (experience[1] if len(experience) > 1 else None) # if has atleast 2 items then get second as max
},
'start_date': start_date,
'end_date': end_date,
'contact_person': response.xpath('//div[@class="contact params-i-val"]/text()').get(),
'company': {
'id': response.xpath('//a[@class="post-company"]/@href').get().split("=")[-1],
'url': response.xpath('//a[@class="post-company"]/@href').get(),
'title': response.xpath('//a[@class="post-company"]/text()').get()
},
'phones': response.xpath('//a[@class="phone"]/text()').extract(),
'email': email,
'description': "".join(response.xpath('//dd[@class="job_description params-i-val"]/p/text()').extract()),
'requirements': "".join(response.xpath('//dd[@class="requirements params-i-val"]/p/text()').extract()),
'category': {
'id': response.xpath('//div[@class="breadcrumbs"]/a/@href').get().split('=')[-1],
'name':response.xpath('//div[@class="breadcrumbs"]/a/text()').get(),
'sub_category': {
'id': response.xpath('//div[@class="breadcrumbs"]/a[2]/@href').get().split('=')[-1],
'name':response.xpath('//div[@class="breadcrumbs"]/a[2]/text()').get(),
}
}
}
| true |
26b57d020f887da5f240723961e123b0244394fa | Python | El-anqiao/program-diary | /Python/keyword/t2.py | UTF-8 | 896 | 2.671875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from snownlp import normal
from snownlp import seg
from snownlp.summary import textrank
import re
from html.parser import HTMLParser
import html
text='''
Children Kids Rain Proof Wear-resisting Anti-Slip Shoe Cover S(Blue Sports)
'''
text=html.unescape(text)
dr = re.compile(r'<[^>]+>',re.S)
text = dr.sub('',text)
if __name__ == '__main__':
t = normal.zh2hans(text)
sents = normal.get_sentences(t)
doc = []
for sent in sents:
words = seg.seg(sent)
words = normal.filter_stop(words)
doc.append(words)
rank = textrank.TextRank(doc)
rank.solve()
for index in rank.top_index(10):
print(sents[index])
keyword_rank = textrank.KeywordTextRank(doc)
keyword_rank.solve()
for w in keyword_rank.top_index(10):
print(w) | true |
123a9ee7376f106bf0a70c2dbda59365e7c8225b | Python | benjyar123/Developers-Institute | /Week 4 - Python/Day 3 - Dictionaries/Dictionaries/W4D3DC.py | UTF-8 | 619 | 4.0625 | 4 | [] | no_license | def encrypt(string):
message = ""
for letters in string:
new = chr(ord(letters) + 14)
message += str(new)
print(message)
def decrypt(string):
message = ""
for letters in string:
new = chr(ord(letters) - 14)
message += str(new)
print(message)
quit = False
while quit == False:
function = input("Select function 'encrypt'/'decrypt'/'quit': ")
if function == "quit":
break
text = input("Type the message you would like to encrypt: ")
if function == "encrypt":
encrypt(text)
elif function == "decrypt":
decrypt(text)
| true |
6ee561658e3a7370439679228a6db6ec362019c3 | Python | mtleis/Bioinformatics-Specialisation-UC | /01_Replication/02_SkewArrayAndHammingDistance/03_MinimumSkew.py | UTF-8 | 877 | 3.765625 | 4 | [] | no_license | # Input: A DNA string Genome
# Output: A list containing all integers i minimizing Skew(Prefix_i(Text)) over all values of i (from 0 to |Genome|)
def MinimumSkew(Genome):
positions = [] # output variable
array = SkewArray(Genome)
print('array, ', array)
minimum = min(array)
print('minimum', minimum)
for i in range(len(array)):
if array[i] == minimum:
print('i: ', i)
positions.append(i)
return positions
# Input: A String Genome
# Output: SkewArray(Genome)
# simple implementation, you can also use the separate function that accounts for new lines
def SkewArray(Genome):
skew = [0]
score = {"A":0, "T":0, "C":-1, "G":1}
for i in range(len(Genome)):
skew.append(score[Genome[i]] + skew[i])
return skew
Sequence = "ATGCATGGCCTACGTACTA"
m = MinimumSkew(Sequence)
print('minimum skew ', m) | true |
d650a206d5e06601c71e354017dbf6ace03706cd | Python | Sushanta-Ghosh/Smart-Cross | /matcode/traffic_control.py | UTF-8 | 7,749 | 2.671875 | 3 | [] | no_license | import time
import scipy.io as sio
import sys
def main():
data_list = ['self_distance', 'v2_distance', 'v2_cmd', 'self_cmd', 'offset_theta', 'sensor_distance']
local_data = {'self_distance': 0.0, 'v2_distance':0.0, 'v2_cmd': 3.0, 'self_cmd': 3.0}
#initialize mat file values to begin
sio.savemat('py_data.mat',local_data)
decision_flag = False
print("python main function")
while True:
try:
try:
#Each cycle of the control system, load in the .mat data file to make decisions
py_data = sio.loadmat('py_data.mat')
local_data = {data_list[0]: float(py_data[data_list[0]][0,0]),
data_list[1]: float(py_data[data_list[1]][0,0]),
data_list[2]: float(py_data[data_list[2]][0,0]),
data_list[3]: float(py_data[data_list[3]][0,0])}
print("self_distance = ", local_data['self_distance'])
print("v2_distance = ", local_data['v2_distance'])
if (local_data['self_cmd'] == 1.0 and local_data['v2_cmd'] == 0.0): #Go to Leader Mode
print("Leader!")
#py_data = sio.loadmat('py_data.mat')
#calculate command and drive mode based on vehicle distances
self_cmd, Drive_Mode = Leader(local_data['self_distance'], local_data['v2_cmd'])
#add code to send necessary information to the other vehicle
##
## data_stripped = {data_list[0]: float(py_data[data_list[1]][0,0]),
## data_list[1]: float(py_data[data_list[1]][0,0]),
## data_list[2]: float(py_data[data_list[2]][0,0]),
## data_list[3]: self_cmd}
local_data['self_cmd'] = self_cmd
try:
#save the updated information so it can be sent over network to the other vehicle
sio.savemat('py_data.mat',local_data)
#local_data = data_stripped #update local files
print(local_data)
except Exception:
time.sleep(0.035)
elif (local_data['self_cmd'] == 0.0 and local_data['v2_cmd'] == 1.0) or local_data['v2_cmd'] == 2.0: #Go to Follower Mode
print("Follower Mode!")
#py_data = sio.loadmat('py_data.mat')
#calculate command and drive mode based on vehicle distances
self_cmd, Drive_Mode = Follower(local_data['self_distance'])
local_data['self_cmd'] = self_cmd
#add code to send necessary information to the other vehicle
##
## data_stripped = {data_list[0]: float(py_data[data_list[1]][0,0]),
## data_list[1]: float(py_data[data_list[1]][0,0]),
## data_list[2]: float(py_data[data_list[2]][0,0]),
## data_list[3]: self_cmd}
#save the updated information so it can be sent over network to the other vehicle
try:
sio.savemat('py_data.mat', local_data)
#local_data = data_stripped #update local files
print(local_data)
except Exception:
time.sleep(0.035)
elif local_data['self_cmd'] == 2.0: #Go to Idle Mode
print("Path Complete, Idling...")
self_cmd = 2.0
Drive_Mode = 0
local_data['self_cmd'] = self_cmd
try:
sio.savemat('py_data.mat',local_data)
#local_data = data_stripped #update local files
print(local_data)
except Exception:
time.sleep(0.035)
#Otherwise Default to Decision mode until the above conditions are satisfied.
else:
print("Decision Mode!")
#py_data = sio.loadmat('py_data.mat')
#calculate command and drive mode based on vehicle distances
self_cmd, Drive_Mode = make_decision(local_data['self_distance'], local_data['v2_distance'],decision_flag)
print("Command = ", self_cmd)
print("Drive_Mode = ", Drive_Mode)
if (self_cmd or self_cmd == 0.0): #if we made a command decision, if not keep the same local_data values
local_data['self_cmd'] = self_cmd
try:
#save the updated information so it can be sent over network to the other vehicle
sio.savemat('py_data.mat',local_data)
#local_data = data_stripped #update local files
print(local_data)
except Exception:
time.sleep(0.035)
time.sleep(1) #pause before re-scanning the control system
except Exception:
time.sleep(0.035)
except (KeyboardInterrupt, EOFError):
print("Shutting down Traffic Control Script ...")
sys.exit(1)
#takes self_distance and v2_cmd as inputs, stops at intersection, waits until Follower is safe
def Leader(self_distance, v2_cmd):
print("Self_distance = ", self_distance)
if self_distance > 1: #stop the car if the camera has picked up the intersection
Drive_Mode = 0
else: #keep moving forward towards the intersection otherwise
Drive_Mode = 1
if v2_cmd > 1: #if Follower vehicle is safe, become the new Follower
self_cmd = 0.0
else: #stay in Leader mode otherwise
self_cmd = 1.0
print("Leader Command is ", self_cmd)
return self_cmd, Drive_Mode
#takes self_distance and v2_cmd as inputs, stops at intersection, waits until Follower is safe
def Follower(self_distance):
print("Self_distance = ", self_distance)
if self_distance > 3: #stop the Follower car if it has reached the end of its path, send safe signal
Drive_Mode = 0
self_cmd = 2.0
else: #keep moving in the forward path, stay in Follower Mode
Drive_Mode = 1
self_cmd = 0.0
return self_cmd, Drive_Mode
def make_decision(self_distance, v2_distance,decision_flag):
if (self_distance == v2_distance) and not(decision_flag): #if decision has not yet taken place
self_cmd = 3.0
Drive_Mode = 1
elif self_distance > v2_distance: #self is Leader, indicate a decision has been made by self
self_cmd = 1.0
Drive_Mode = 1
decision_flag = True
elif self_distance < v2_distance: #self is Follower, indicate a decision has been made by self
self_cmd = 0.0
Drive_Mode = 1
decision_flag = True
else: #keep the command and drive mode the same
self_cmd = False
Drive_Mode = False
return self_cmd, Drive_Mode
if __name__ == '__main__':
main()
| true |
116519e71b1e8c91c498496dbb6b096f4208c838 | Python | alrusdi/bg.alrusdi.ru | /chooser/tests/test_helpers.py | UTF-8 | 712 | 2.640625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import fudge
from django.test import TestCase
from chooser import helpers
class BaseTestCase(TestCase):
pass
class ChooseNewGameToPlayTest(BaseTestCase):
@fudge.patch('chooser.helpers._choose_random')
def test_chooses_random_game_from_lowest_by_play(self, choose_random_stub):
stored_cands = []
def choose_random_repl(cands):
stored_cands = [g["id"] for g in cands]
choose_random_stub.expects_call().calls(choose_random_repl)
game = helpers.choose_new_game_to_play(
{
'is_real': True,
'is_digital': False
}
)
self.assertIn(stored_cands, game['id'])
| true |
1bbdcc4790dcd5e62fe44ffbe13da095f64bf9f3 | Python | PlumpMath/jafp3dd | /tests/recurseTest.py | UTF-8 | 1,693 | 3.140625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 21 09:47:48 2011
@author: shawn
"""
import random
from panda3d.core import Vec3, Quat
class BranchNode():
def __init__(self,l=1,rad=1,Q=Quat(),pos=Vec3(0,0,0)):
self.length = l # MOVE TO GENERATION ROUTINE. DON'T NEED LENGTHS, ONLY POSITIONS
self.radius = rad # radius of child end (parent end will obvious have it's radius)
self.quat = Q # orientation quaternion; which way am I pointing?
self.pos = pos # center point of this branch node
self.children = [] # list of children from THIS branch's end
self.gen = 0 # generation ID
#
def getChildren(numSib=2,gen=1):
print gen
children = []
if gen < 4:
for i in range(numSib):
sib = BranchNode()
sib.children = getChildren(numSib,gen+1)
sib.gen = gen
children.append(sib)
return children
else:
return []
# parent is a list of N generations
# each generation will split into numSibdren
# children of generation n+1
def selectGen(gen,Tree):
for child in Tree:
if child.gen == gen: print child.length
if __name__ == '__main__':
numGens = 3
# T = BranchNode() #1st gen (trunk)
# T.children = getChildren() #2nd gen
thisBranch = [BranchNode()] # make a starting node flat at 0,0,0
for i in range(numGens):
newNode = BranchNode()
newNode.pos += newNode.quat.getUp() * (1/(i+1))
newNode.quat.setHpr((0,0,15))
newNode.radius = 1/(i+1)
thisBranch.append(newNode)
| true |