def main():
    # content = read_strings()
    # charges =[]
    # for line in content:
    #     values = re.split('\s+', line)
    #     if len(values) == 3:
    #         values = [float(x) for x in values]
    #         coord = tuple(values[0:2])
    #         q = values[2]
    #         charges += [Charge(coord,q)]
    n = 5
    charges = [random_Charge(10, 10) for i in range(n)]
    for c in charges:
        print(c)
    create_image(charges, 'potentials.png')
    charges = [random_Charge(20, 1) for i in range(2)]
    for c in charges:
        print(c)
    print(minimum_potential_point(charges))
    print(total_vector_potential((0, 0), charges))
    print(unit_vector_potential((0, 0), charges))
    assert 1 == 2

    # mutable charges exercise
    n = 10
    a = [None] * 3
    a[0] = Charge((.4, .6), 50)
    a[1] = Charge((.5, .5), -5)
    a[2] = Charge((.6, .6), 50)
    for i in range(100):
        create_image(a, 'mutab_charge' + str(i) + '.png')
        a[1] += (-2.0)
Beispiel #2
0
class Tank:
    def __init__(self, the_world_I_live_in, my_initial_position_x,
                 my_initial_position_y):
        print "Hi, I am an instance of the Tank class"
        self.w = the_world_I_live_in
        self.x = my_initial_position_x
        self.y = my_initial_position_y
        self.s = 40  # This is my size
        self.blength = 50  # lenght of my barrel
        self.b = None  # This will be my barrel
        self.charge_velocity = 20  # [m/s] initial velocity of a charge (power) ! will be a tuple
        self.c = None  # no charge yet

    def draw(self):
        # Drawing a tank
        d = self.s / 2
        x1 = self.x - d
        y1 = self.y - d
        x2 = self.x + d
        y2 = self.y + d
        self.w.canvas.create_rectangle(x1, y1, x2, y2, fill="red")

        # Drawing a barrel
        self.bx1 = x1 + (x2 - x1) / 2
        self.by1 = y1 + (y2 - y1) / 2
        self.bx2 = self.bx1 + self.blength
        self.by2 = self.by1 + 0
        self.__drawBarrel()

        # We will need this to draw the charge
        self.end_of_barrel = [self.bx2,
                              self.by2]  # The type of this is 'array'

        # Drawing a charge
        self.c = Charge(self)

    def __drawBarrel(self):
        self.b = self.w.canvas.create_line(self.bx1,
                                           self.by1,
                                           self.bx2,
                                           self.by2,
                                           fill="grey",
                                           width=3)

    def recalc(self):
        if self.c:
            self.c.recalc()

    def update(self):
        if self.c:
            self.c.update()
Beispiel #3
0
    def add_charge(self):
        """ Обработчик нажатия на кнопку add_charge, добавляет заряд на graphicsView """
        charge_value = randint(MIN_CHARGE_VALUE, MAX_CHARGE_VALUE)
        color = self.identify_color(charge_value)

        charge = Charge(randint(self.min_width, self.max_width),
                        randint(self.min_height, self.max_height), self.radius,
                        self.radius, charge_value, color, self.events)
        charge.setFlags(QGraphicsItem.ItemIsMovable
                        | QGraphicsItem.ItemIsSelectable
                        | QGraphicsItem.ItemIsFocusable)

        # Снимаем выделение со всех зарядов и выделяем только вновь добавленный
        for selected_charge in self.scene.selectedItems():
            if type(selected_charge) == Charge:
                selected_charge.setSelected(False)
        charge.setSelected(True)

        # Добавляем сам новый заряд и его значение
        self.scene.addItem(charge)
        charge.setFocus()

        # Добавляем связи со всеми существующими на данный момент зарядами
        self.selected_charges = self.scene.selectedItems()
        self.add_connections()
Beispiel #4
0
 def node_damage(self, position=None):
     if self.power < 0.2 or random.random() > 0.1:
         self.behaviour = None
         self.behaviour_type = None
         return
     if not position:
         node = self.matrix.node_check(self)
         if node and not node.offline and node.id[1] != 1:
             charge = Charge(self.matrix, self.x, self.y, 90)
             self.matrix.charges.add(charge)
     else:
         charge = Charge(self.matrix, position[0], position[1], 90)
         self.matrix.charges.add(charge)
     self.behaviour = self.behaviours['roam']
     self.behaviour_type = 'roam'
Beispiel #5
0
    def add_charge(self, x_pos, y_pos, x_vel, y_vel, mass, charge):
        """ Adds a point charge with the given position,
            velocity, mass, and charge to the environment.

            Allows the users to add charges that are not
            just protons and electrons!
        """
        if self._any_overlap(x_pos, y_pos):
            sys.exit('There is already a charge at ({0}, {1}). '.format(x_pos, y_pos) + \
                     'No two points can overlap in space!')
        charge = Charge(x_pos, y_pos, x_vel, y_vel, mass, charge)
        self._charges.append(charge)
Beispiel #6
0
    def draw(self):
        # Drawing a tank
        d = self.s / 2
        x1 = self.x - d
        y1 = self.y - d
        x2 = self.x + d
        y2 = self.y + d
        self.w.canvas.create_rectangle(x1, y1, x2, y2, fill="red")

        # Drawing a barrel
        self.bx1 = x1 + (x2 - x1) / 2
        self.by1 = y1 + (y2 - y1) / 2
        self.bx2 = self.bx1 + self.blength
        self.by2 = self.by1 + 0
        self.__drawBarrel()

        # We will need this to draw the charge
        self.end_of_barrel = [self.bx2,
                              self.by2]  # The type of this is 'array'

        # Drawing a charge
        self.c = Charge(self)
def minimum_potential_point(charges):
    NB_SPLIT = 100
    values = np.linspace(0, 1, NB_SPLIT + 1)
    coords = product(values, values)
    minim = None
    res = None
    for coord in coords:
        pot = total_potential(coord, charges)
        if minim is None:
            minim = pot
        elif pot < minim:
            minim = pot
            res = Charge(coord, pot)
    return res
Beispiel #8
0
import argparse
from geomutils import neighbours
from charge import Charge
from potential import total_potential

def get_neighs(coord, width):
    POINTS=((0,width),(0,-width),(width,0),(-width,0))
    return neighbours(coord, POINTS)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Four charges in the cardinal direction')
    parser.add_argument('w', type=float, help='distance from center')
    args = parser.parse_args()
    w  = args.w 
    CENTER = (0.5,0.5)
    CHARGE = 1.0
    charges =[]
    for coord in get_neighs(CENTER, w):
        charges += [Charge(coord, CHARGE)]

    point_of_interest = (.25,.5)
    print('%.2e' % total_potential(point_of_interest, charges))
    print( total_potential(point_of_interest, charges))




Beispiel #9
0
from charge import Charge
import stddraw
import stdarray
from picture import Picture
from color import Color

a = stdarray.create1D(3)
a[0] = Charge(.4, .6, 50)
a[1] = Charge(.5, .5, -5)
a[2] = Charge(.6, .6, 50)

MAX_GRAY_SCALE = 255
p = Picture()
stddraw.setCanvasSize(p.width(),p.height())
for t in range(100):
    # Compute the picture p.
    for col in range(p.width()):
        for row in range(p.height()):
            # Compute pixel color.
            x = 1.0 * col / p.width()
            y = 1.0 * row / p.height()
            v = 0.0

            for i in range(3):
                v += a[i].potentialAt(x, y)    
            v = (MAX_GRAY_SCALE / 2.0)  + (v / 2.0e10)
            if v < 0:
                grayScale = 0
            elif v > MAX_GRAY_SCALE:
                grayScale = MAX_GRAY_SCALE
            else:
Beispiel #10
0
#-----------------------------------------------------------------------
# chargeclient.py
#-----------------------------------------------------------------------

import sys
import stdio
from charge import Charge

# Accept floats x and y as command-line arguments. Create two Charge
# objects with fixed position and electrical charge, and write to
# standard output the potential at (x, y) due to the two charges.

x = float(sys.argv[1])
y = float(sys.argv[2])
c1 = Charge(.51, .63, 21.3)
c2 = Charge(.13, .94, 81.9)
v1 = c1.potentialAt(x, y)
v2 = c2.potentialAt(x, y)
stdio.writef('potential at (%.2f, %.2f) due to\n', x, y)
stdio.writeln('  ' + str(c1) + ' and')
stdio.writeln('  ' + str(c2))
stdio.writef('is %.2e\n', v1+v2)

#-----------------------------------------------------------------------

# python chargeclient.py .2 .5
# potential at (0.20, 0.50) due to
#   21.3 at (0.51, 0.63) and
#   81.9 at (0.13, 0.94)
# is 2.22e+12
Beispiel #11
0
from charge import Charge
from potential import total_potential
import sys

if __name__ == "__main__":
    x = float(sys.argv[1])
    y = float(sys.argv[2])
    c1 = Charge((.51,.63), 21.3)
    c2 = Charge((.13,.94), 81.9)
    v1 = c1.potential_at((x,y))
    v2 = c2.potential_at((x,y))
    print('potential at', (x,y))
    print('due to', c1)
    print('and', c2)
    print('is %.2e' % (v1 + v2))
    print('%.2e' %total_potential((x,y),[c1,c2]))
Beispiel #12
0
    def bark(self):
        return "woof"

ponyo = Dog("ponyo")
print ponyo.get_type()
print ponyo.bark()
# print ponyo.meow()

from charge import Charge

class Proton(Charge):
    def __init__(self, str):
        self.str = str
        self.t = "+"

c = Charge("+")
print c.get_type(), c.get_str()

p = Proton(100)
print p.get_type(), p.get_str()

def print_point(p):
    """Print a Point object in human-readable format."""
    print '(%g, %g)' % (p.x, p.y)

def distance_between_points(p1, p2):
    """Finds the distance between two points, p1 and p2."""
    x1, y1 = p1.get_coordinates()
    x2, y2 = p2.get_coordinates()
    return ((x1-x2)**2 + (y1-y2)**2)**0.5
from charge import Charge
import sys

w = eval(sys.argv[1])

c1 = Charge(0.5 - w, 0.5, 1)
c2 = Charge(0.5 + w, 0.5, 1)
c3 = Charge(0.5, 0.5 - w, 1)
c4 = Charge(0.5, 0.5 + w, 1)

v1 = c1.potentialAt(.25, .5)
v2 = c2.potentialAt(.25, .5)
v3 = c3.potentialAt(.25, .5)
v4 = c4.potentialAt(.25, .5)

print('{0:.2e}'.format(v1 + v2 + v3 + v4))
Beispiel #14
0
# Read values from standard input to create an array of charged
# particles. Set each pixel color in an image to a grayscale value
# proportional to the total of the potentials due to the particles at
# corresponding points. Draw the resulting image to standard draw.

MAX_GRAY_SCALE = 255

# Read charges from standard input into an array.
#n = stdio.readInt()
n = eval(sys.argv[1])
charges = stdarray.create1D(n)
for i in range(n):
    x0 = round(stdrandom.uniformFloat(0, 1), 2)
    y0 = round(stdrandom.uniformFloat(0, 1), 2)
    q0 = stdrandom.gaussian(50, 150)
    charges[i] = Charge(x0, y0, q0)
    print(str(charges[i]))

# Create a Picture depicting potential values.
pic = Picture()
for col in range(pic.width()):
    for row in range(pic.height()):
        # Compute pixel color.
        x = 1.0 * col / pic.width()
        y = 1.0 * row / pic.height()
        v = 0.0

        for i in range(n):
            v += charges[i].potentialAt(x, y)
        v = (MAX_GRAY_SCALE / 2.0) + (v / 2.0e10)
        if v < 0:
def random_Charge(mean, sd):
    x, y = random.random(), random.random()
    charge = np.random.normal(mean, sd)

    return Charge((x, y), charge)
import sys
import stdio
from charge import Charge

# Accept a float w as a command-line argument. Create four Charge
# objects that are each distance w in each of the four cardinal
# directions from (.5, .5), and write the potential at (.25, .5).

w = float(sys.argv[1])

# Center of standard drawing window.
cx = 0.5
cy = 0.5

# Construct four charges.
c1 = Charge(cx + w, cy, 1.0)
# east
c2 = Charge(cx, cy - w, 1.0)
# south
c3 = Charge(cx - w, cy, 1.0)
# west
c4 = Charge(cx, cy + w, 1.0)
# north

# Compute potentials at (.25, .5).
px = 0.25
py = 0.5
v1 = c1.potentialAt(px, py)
v2 = c2.potentialAt(px, py)
v3 = c3.potentialAt(px, py)
v4 = c4.potentialAt(px, py)
Beispiel #17
0
 def __init__(self, two_wheeler_price, four_wheeler_price, time):
     self.charge = Charge(two_wheeler_price, four_wheeler_price)
     self.time = time
Beispiel #18
0
import sys
import stdio
from charge import Charge

x = float(sys.argv[1])
y = float(sys.argv[2])

c1 = Charge(.51, .63, 21.3)
c2 = Charge(.13, .84, 81.9)

v1 = c1.potentialAt(x, y)
v2 = c2.potentialAt(x, y)

stdio.writef('potential at (%.2f, %.2f) due to \n', x, y)
stdio.writeln(' ' + str(c1) + ' and')
stdio.writeln(' ' + str(c2))
stdio.writef('is %.2e\n', v1 + v2)
Beispiel #19
0
        self.charges = []

    def addCharge(self, charge):
        self.charges.append(charge)
        self.sum += charge.price


if __name__ == "__main__":
    if not os.path.exists("node_modules"):
        os.system("npm install")

    try:
        # get user, pass, bank
        user, password, bank = sys.argv[1:4]
        print("financial report start")
    except ValueError:
        print("Usage: python fincRep.py [user] [password] [bank]")
        print(
            "bank could be one of: 'hapoalim', 'leumi', 'discount', 'otsarHahayal', 'visaCal', 'leumiCard', 'isracard', 'amex'"
        )
        sys.exit(1)

    run_scrapper_cmd = "node index.js {} {} {}".format(user, password, bank)
    subprocess.check_call(run_scrapper_cmd, shell=True)
    # read expenses
    with open("accounts.json") as file:
        expenses = json.load(file)["accounts"][0]["txns"]
    for expense in expenses:
        pr = Charge(expense)
        print(pr)