Example #1
0
def mkdir(path):
    """Create a directory"""
    cl = Client()
    res = cl.create_dir(path)
    stat = res['status']
    if stat != Status.ok:
        print(Status.description(stat))
Example #2
0
def rm(path):
    """Delete a file or directory"""
    cl = Client()
    res = cl.delete(path)
    stat = res['status']
    if stat != Status.ok:
        print(Status.description(stat))
Example #3
0
def run():
    config = ConfigParser.ConfigParser()
    with open(CONFIG_PATH) as config_fp:
        config.readfp(config_fp)
    logging.config.dictConfig(LOGGING_CONFIG)
    client = Client(config)
    client.start()
Example #4
0
def places(request):
	context_dict = {}
	if request.method == 'POST':
		from_station = request.POST.get('from_station')
		to_station = request.POST.get('to_station')
		date = request.POST.get('departure_date')
		time = request.POST.get('departure_time')
		train_number = request.POST.get('train_number')
		departure_date = datetime.strptime(date, "%Y-%m-%d")
		client = Client(api_usernumber = conf.USER_NUMBER, api_passmd5 = conf.USER_PASSMD5, id_terminal = conf.ID_TERMINAL, id_service = conf.ID_SERVICE, request_url = conf.API_URL)
		df = DateFormat(departure_date)
		places = client.get_train_places(from_station, to_station, df.format('d.m.Y'), time, train_number)
		data = json.dumps(places, ensure_ascii=False)
		response_dict = json.loads(data)
		if 'status' in response_dict:
			context_dict['error'] = response_dict['message']
		else:
			context_dict = place_handler(response_dict)
		context_dict['data'] = data
		context_dict['from_station'] = Station.objects.get(code=from_station)
		context_dict['to_station'] = Station.objects.get(code=to_station)
		context_dict['departure_date'] = date
		context_dict['departure_time'] = time
		context_dict['train_number'] = train_number
		context_dict['stations'] = Station.objects.all()
	return render(request, 'search/places.html', context_dict)
Example #5
0
def download(path_from, path_to):
    """Download a file"""
    cl = Client()
    res = cl.download_file(path_from, path_to)
    # print(res)
    stat = res['status']
    if stat != Status.ok:
        print(Status.description(stat))
Example #6
0
    def create(self, callback=None, connectionType=None, vhost=None):
        from client.client import Client

        client = Client(self.room)
        client.callback = callback
        client.type = connectionType
        if vhost:
            client.vhost = vhost
        self.clientList[client.unique_key] = client
        return client.unique_key
Example #7
0
def upload(local_path, remote_path):
    """Create a file"""
    cl = Client()

    if os.path.isdir(local_path):
        print("You can't upload directory as a file")
    else:
        res = cl.create_file(local_path, remote_path)
        stat = res['status']
        if stat != Status.ok:
            print(Status.description(stat))
Example #8
0
class Ui_Form(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        self.setupUi(self)
        self.client = Client('localhost')
        
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(8, 600)        
        self.horizontalLayout = QHBoxLayout(Form)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.horizontalLayout.setGeometry(QRect(0, 0, 600, 600))
        self.horizontalLayout.setSizeConstraint(QLayout.SetFixedSize)
        self.gridLayout = QGridLayout()        
#         self.gridLayout.setSizeConstraint(QLayout.SetMaximumSize)
        self.gridLayout.setObjectName("gridLayout")        
        self.horizontalLayout.addLayout(self.gridLayout)
        
        self.row = 0;
        self.col = 0;
        self.width = 3;                        
        self.entries = []

        self.retranslateUi(Form)
        QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        
    def addImageLabel(self, pic):          
        print (pic)      
        pixmap = QPixmap(pic).scaled(200, 200, Qt.KeepAspectRatio)
        label = QLabel(self)
        
        label.setPixmap(pixmap)
        self.entries.append(label)                        
        self.gridLayout.addWidget(label, *(self.row, self.col))
        self.col += 1
        if self.col % self.width == 0:
            self.col = 0
            self.row += 1              
        
    def removeImageLabel(self, position):
        item = position[0] * self.width + position[1]  
        label = self.gridLayout.takeAt(item)
        widget = label.widget();
        widget.deleteLater();
        
    def run(self):
        self.client.getAllPhoto()
        jpgList = glob.glob1("temp", "*.jpg")        
        for each in jpgList:
            self.addImageLabel("temp/" + each)                
Example #9
0
File: main.py Project: jchmura/PiE
def main():
    parser = argparse.ArgumentParser(description='Tic Tac Toe')
    subparsers = parser.add_subparsers(title='module', dest='module')
    subparsers.required = True
    subparsers.add_parser('server', help='start the server')
    subparsers.add_parser('client', help='start a client')

    args = parser.parse_args()

    if args.module == 'server':
        server = Server()
        try:
            server.start()
        except BaseException as e:
            logger.error('Process interrupted, stopping the server', exc_info=e)
        finally:
            server.stop()
    elif args.module == 'client':
        client = Client()
        try:
            client.connect()
            client.run()
        except BaseException as e:
            logger.error('Process interrupted, disconnecting the client', exc_info=e)
        finally:
            client.disconnect()
    else:
        print('unknown module {}'.format(args.module), file=sys.stderr)
Example #10
0
def ls(path):
    """List directory contents"""
    cl = Client()
    dir_ls = cl.list_dir(path)
    stat = dir_ls['status']
    if stat == Status.ok:
        for item, info in dir_ls['items'].items():
            fr = "-rw-r--r--"
            if info['type'] == NodeType.directory:
                fr = "drwxr-xr-x"
            date = datetime.datetime.fromtimestamp(info['date'])
            date_format = '%b %d %H:%M' if date.year == datetime.datetime.today().year else '%b %d %Y'
            print('%.11s   %.10s   %6sB   %.15s    %s' % (fr,
                                                       getpass.getuser(),
                                                       info['size'],
                                                       datetime.datetime.fromtimestamp(info['date']).strftime(date_format),
                                                       item))
    else:
        print(Status.description(stat))
Example #11
0
def buy_ticket(request):
	context_dict = {}
	if request.method == 'POST':
		from_station = request.POST.get('from_station')
		to_station = request.POST.get('to_station')
		date = request.POST.get('departure_date')
		time = request.POST.get('departure_time')
		train_number = request.POST.get('train_number')
		car_number = request.POST.get('car_number')
		car_type = request.POST.get('car_type')
		doc_type = request.POST.get('doc_type')
		doc_number = request.POST.get('doc_number')
		first_name = request.POST.get('first_name')
		last_name = request.POST.get('last_name')
		middle_name = request.POST.get('middle_name')
		full_name = last_name+"="+first_name+"="+middle_name
		departure_date = datetime.strptime(date+" "+time, "%Y-%m-%d %H:%M")
		df = DateFormat(departure_date)
		client = Client(api_usernumber = conf.USER_NUMBER, api_passmd5 = conf.USER_PASSMD5, id_terminal = conf.ID_TERMINAL, id_service = conf.ID_SERVICE, request_url = conf.API_URL)
		class_service = ""
		if car_type==u"Люкс":
			class_service = u'1Л'
		elif car_type == u"Купе":
			class_service = u'2К'
		elif car_type == u"Плацкартный":
			class_service = u'3П'
		print car_type
		print class_service
		booking = client.buy_ticket(from_station, to_station, df.format('d.m.Y H:i'),  train_number, car_type, car_number, class_service, '0', '0', 'null', '1', 'null', 'null', doc_type, doc_number, full_name, car_type[0], '1')
		data = json.dumps(booking, ensure_ascii=False)
		response_dict = json.loads(data)
		if "GtETicket_Response" in response_dict:
			context_dict = handle_ticket(response_dict)
		else:
			context_dict['error'] = data
		context_dict['from_station'] = Station.objects.get(code=from_station)
		context_dict['to_station'] = Station.objects.get(code=to_station)
		context_dict['departure_date'] = date
		context_dict['stations'] = Station.objects.all()
	return render(request, 'search/ticket.html', context_dict)
Example #12
0
 def test_duplicate_alias(self, client: Client):
     client.add_address("baz", "foo", force=True)
     show_foo = client.show_address("foo", show_secret=True)
     assert show_foo.secret_key is not None
Example #13
0
 def test_transfer_to_noop(self, client: Client):
     client.transfer(10, 'bootstrap1', 'noop', ['--arg', 'Unit'])
     utils.bake(client)
Example #14
0
 def test_balances_foo_bar(self, client: Client, session):
     # 999.95 = 1000 - transfer fees
     assert client.get_balance(session['keys'][0]) == 999.95
     assert client.get_balance(session['keys'][1]) == 2000
Example #15
0
def test_context_suffix_no_rpc(proxy_client: Client, path: str):
    """
    This test checks that the proxy client never does a useless RPC.

    I.e. it checks that if the proxy client requested
    `/chains/<main>/blocks/<head>/context/raw/bytes/some_path`
    it doesn't later request
    `/chains/<main>/blocks/<head>/context/raw/bytes/some_other_path`

    with `some_other_path` being a suffix of `some_path`. In this
    scenario, the proxy client should look for the tail of
    `some_other_path` that is a suffix of `some_path` and use this
    suffix to get the data within the tree received by the first request.

    For this, this test inspects the debug output produced by
    setting TEZOS_LOG to alphas.proxy_rpc->debug. This causes the client
    to print the RPCs done to get pieces of the context:

    alpha.proxy_rpc: P/v1/constants
    alpha.proxy_rpc: Received tree of size 1
    alpha.proxy_rpc: P/v1/first_level
    alpha.proxy_rpc: Received tree of size 1
    alpha.proxy_rpc: P/cycle/0/random_seed
    alpha.proxy_rpc: Received tree of size 1
    alpha.proxy_rpc: P/cycle/0/roll_snapshot
    alpha.proxy_rpc: Received tree of size 1
    alpha.proxy_rpc: P/cycle/0/last_roll/0

    where P is /chains/<main>/blocks/<head>/context/raw/bytes

    In the client, this behavior is implemented by putting the result
    of RPC calls in a trie.
    """
    cmd = ["rpc", "get", path]
    (_, stderr, _) = proxy_client.run_generic(cmd, env_change=_PROXY_RPC_LOG)

    prefix = "/chains/<main>/blocks/<head>/context/raw/bytes"
    search_re = f".proxy_rpc: {prefix}/(.*)"

    # The suffix of RPCs querying data, such as "v1/constants",
    # "v1/first_level", "cycle/0/random_seed", etc. (see method doc)
    context_queries = []
    for line in stderr.splitlines():
        match = re.search(search_re, line)
        if match:
            suffix = match.group(1)
            context_queries.append(suffix)

    assert len(context_queries) >= 2, "There should be at least two queries"

    def gen_msg(query_before, query):
        return (f"Query {query_before} should not be followed by query" +
                f" {query} because the latter is a suffix of the former." +
                " Hence the proxy should reuse the data of the first query.")

    i = len(context_queries) - 1
    while i >= 0:
        query = context_queries[i]
        j = i - 1
        while j >= 0:
            query_before = context_queries[j]
            assert not query_before.startswith(query), gen_msg(
                query_before, query)
            j -= 1
        i -= 1
Example #16
0
 def __init__(self, *args, **kwargs):
     QWidget.__init__(self, *args, **kwargs)
     self.setupUi(self)
     self.client = Client('localhost')
Example #17
0
def connect(stdscr, server_ip):
    global connection
    connection = Client()
    connection.connect(server_ip)
    return connected(stdscr)
Example #18
0
def status(path):
    """Check if path refers to file or directory"""
    cl = Client()
    res = cl.path_status(path)
    print('%s is a %s' % (path, NodeType.description(res['type'])))
Example #19
0
 def setUp(self):
     self.app = MagicMock()
     self.client = Client(self.app, 'localhost', 5000)
Example #20
0
class TestClient(unittest.TestCase):

    def setUp(self):
        self.app = MagicMock()
        self.client = Client(self.app, 'localhost', 5000)

    def test_send(self):
        message = "test"
        with patch("socket.socket.send") as mock:
            self.client.send(message)
            self.assertEqual(mock.call_count, 1)
            self.assertEqual(mock.call_args[0][0], message)

    def test_connect(self):
        self.client._host = "localhost"
        self.client._port = 5000
        with patch("socket.socket.connect") as mock:
            self.client.connect()
            self.assertEqual(mock.call_count, 1)
            self.assertEqual(mock.call_args[0][0], (self.client._host, self.client._port))

    def test_process_users_list(self):
        user1 = "user1"
        user2 = "user2"
        history = "history"
        data = "<users>" + user1 + "," + user2 + "<history>" + history
        self.client.process_users_list(data)
        self.assertEqual(self.client.user_list, [user1, user2])
        self.assertEqual(self.app.show_users.call_count, 1)
        self.assertEqual(self.app.display.call_count, 2)
        self.assertEqual(self.app.display.call_args_list[0][0], (history,))

    def test_process_add_user(self):
        user = "******"
        data = "<users-add>" + user
        self.client.process_add_user(data)
        self.assertTrue(user in self.client.user_list)
        self.assertEqual(self.app.show_users.call_count, 1)
        self.assertEqual(self.app.show_users.call_args[0][0], self.client.user_list)
        self.assertEqual(self.app.display.call_count, 1)
        self.assertTrue(user in self.app.display.call_args[0][0])

    def test_process_remove_user(self):
        user = "******"
        self.client.user_list.append(user)
        data = "<users-remove>" + user
        self.client.process_remove_user(data)
        self.assertTrue(user not in self.client.user_list)
        self.assertEqual(self.app.show_users.call_count, 1)
        self.assertEqual(self.app.show_users.call_args[0][0], self.client.user_list)
        self.assertEqual(self.app.display.call_count, 1)
        self.assertTrue(user in self.app.display.call_args[0][0])

    def test_process_data_users_list(self):
        data = "<users>users<history>history"
        with patch("client.client.Client.process_users_list") as mock:
            self.client.process_data(data)
            self.assertEqual(mock.call_count, 1)
            self.assertEqual(mock.call_args[0][0], data)

    def test_process_data_new_user(self):
        data = "<users-add>user"
        with patch("client.client.Client.process_add_user") as mock:
            self.client.process_data(data)
            self.assertEqual(mock.call_count, 1)
            self.assertEqual(mock.call_args[0][0], data)

    def test_process_data_remove_user(self):
        data = "<users-remove>user"
        with patch("client.client.Client.process_remove_user") as mock:
            self.client.process_data(data)
            self.assertEqual(mock.call_count, 1)
            self.assertEqual(mock.call_args[0][0], data)

    def test_process_data_message(self):
        data = "message"
        self.client.process_data(data)
        self.assertEqual(self.app.display.call_count, 1)
        self.assertEqual(self.app.display.call_args[0][0], data)
Example #21
0
    def test_operation_size_medium(self, client: Client):
        bytes_arg = "0x" + ("00" * 24 * 1024)  # 24 KB of data.

        client.transfer(10, 'bootstrap1', 'bytes', ['--arg', bytes_arg])
        utils.bake(client)
Example #22
0
 def test_no_service_3(self, client: Client):
     path = '/chains/main/blocks/head/context/raw/bytes/non-existent?depth=0'
     with assert_run_failure('No service found at this URL'):
         client.rpc('get', path)
Example #23
0
 def test_proto_known(self, client: Client):
     res = client.list_protocols()
     assert PROTO in res
def run():
    # Parse configuration to constants
    logging.config.dictConfig(LOGGING_CONFIG)
    client = Client()
    client.start()
Example #25
0
 def test_level1(self, client: Client):
     assert client.get_level(params=PARAMS) == 1
Example #26
0
 def test_split_large_file(self):
     chunks = Client.split_file('test_large.txt')
     self.assertEqual(chunks[1], self.content[1024:])
     self.assertEqual(chunks[0]+chunks[1], self.content)
Example #27
0
 def test_level2(self, client: Client):
     head = client.rpc('get', '/chains/main/blocks/head/', params=PARAMS)
     assert head['header']['level'] == 2
Example #28
0
 def test_balances_bar_foo(self, client: Client, session):
     assert client.get_balance(session['keys'][0]) == 2000
     assert client.get_balance(session['keys'][1]) == 1000
Example #29
0
def cat(path):
    """Print a file"""
    cl = Client()
    res = cl.get_file_content(path)
    print(res)
Example #30
0
 def test_first_protocol(self, client: Client):
     proto = 'PrihK96nBAFSxVL1GLJTVhu9YnzkMFiBeuJRPA8NwuZVZCE1L6i'
     assert client.get_protocol() == proto
Example #31
0
 def test_proto_client_known(self, client: Client):
     res = client.list_understood_protocols()
     assert 'ProtoDemoCou' in res
Example #32
0
 def test_protocol_genesis(self, client: Client):
     assert client.get_protocol(params=PARAMS) == PROTO_GENESIS
Example #33
0
 def test_level1(self, client: Client):
     assert client.get_level() == 1
Example #34
0
 def test_gen_keys(self, client: Client, session):
     session['keys'] = ['foo', 'bar', 'boo']
     sigs = [None, 'secp256k1', 'ed25519']
     for key, sig in zip(session['keys'], sigs):
         args = [] if sig is None else ['--sig', sig]
         client.gen_key(key, args)
Example #35
0
 def test_inject_operations(self, client: Client):
     client.run(['increment', 'a'])
     client.run(['increment', 'b'])
     client.run(['transfer', '10'])
Example #36
0
 def test_transfer_foo_bar(self, client: Client, session):
     client.reveal(session['keys'][0], ['--fee', '0', '--force-low-fee'])
     utils.bake(client)
     client.transfer(1000, session['keys'][0], session['keys'][1],
                     ['--fee', '0.05'])
     utils.bake(client)
Example #37
0
 def test_mempool(self, client: Client):
     ops = client.get_mempool()
     assert len(ops['applied']) == 3
Example #38
0
 def test_transfer_failure(self, client: Client, session):
     with pytest.raises(Exception):
         client.transfer(999.95, session['keys'][0], session['keys'][1])
Example #39
0
 def test_bake_command_2(self, client: Client):
     time.sleep(1)
     client.run(['bake', 'This is block 3'])
Example #40
0
 def test_transfer_king_queen(self, client: Client, session):
     keys = session['keys']
     client.transfer(10, keys[3], keys[4], TRANSFER_ARGS)
     utils.bake(client)
Example #41
0
 def test_level3(self, client: Client):
     head = client.rpc('get', '/chains/main/blocks/head/')
     assert head['header']['level'] == 3
Example #42
0
 def test_no_service_2(self, client: Client):
     path = ('/chains/main/blocks/head/context/raw/bytes/'
             'non-existent?depth=-1')
     expected = r'Failed to parse argument \'depth\' \("-1"\)'
     with assert_run_failure(expected):
         client.rpc('get', path)
Example #43
0
 def test_rpc_counter_b(self, client: Client):
     head = client.rpc('get', '/chains/main/blocks/head/counter/b')
     assert head == 111
Example #44
0
    def test_operation_size_oversized(self, client: Client):
        bytes_arg = "0x" + ("00" * 36 * 1024)  # 36 KB of data.

        expected_error = "Oversized operation"
        with assert_run_failure(expected_error):
            client.transfer(10, 'bootstrap1', 'bytes', ['--arg', bytes_arg])
Example #45
0
 def test_get_counter_commands(self, client: Client):
     message_a = client.run(['get', 'a'])
     assert message_a == "The counter value is 91\n"
     message_b = client.run(['get', 'b'])
     assert message_b == "The counter value is 111\n"
Example #46
0
def check_level_greater_than(
    client: Client, level, chain: str = 'main'
) -> bool:
    return client.get_level(chain=chain) >= level
Example #47
0
from client.client import Client
from flask import Blueprint, render_template, session, request
from authentication.authenticator import login_required, group_access_level

api = Client()
page = 'members'

members_page = Blueprint('members_page', __name__)


@members_page.before_request
@login_required
def client_auth(**kwargs):
    api.set_auth_header('Bearer %s' % session['jwt'])


@members_page.route("/groups/<groupId>/members")
@login_required
@group_access_level('member')
def MembersPage(**kwargs):
    subtab = request.args.get('subtab', 'members')
    user_role = kwargs.get('user_role')
    username = kwargs.get('username', None)
    groupId = kwargs.get('groupId', None)
    group = api.groups.get(groupId=groupId).json()
    members = api.groups.members.list(groupId=groupId).json()

    requests = []
    if user_role == 'admin':
        requests = api.groups.requests.list(groupId=groupId).json()
from client.client import Client
import asyncore
import socket
from time import sleep
import sys
from inputOutput.filehandling import get_client_config
from inputOutput.output import show_info_dialog, show_input_dialog, show_option_dialog


if __name__ == '__main__':

    choice = show_option_dialog("Do you want to use config file?",
                                ["yes", "no"])
    if choice == "yes":
        address, port, programId, username = get_client_config()
        client = Client((address, int(port)), programId,
                        username)
        asyncore.loop()
    else:
        show_info_dialog("This client is intended to run on one processor core "
                         "and calculates results from clustering documents given "
                         "a set of parameters (received from server). If you want"
                         " to use more cores, run additional clients. You can "
                         "exit the client at any time by pressing ctrl + c.\n")

        hostAddress = show_input_dialog("Please type in the ip address or domain "
                                        "name of the host on the form '0.0.0.0' "
                                        "or 'domain.com': ")

        port = show_input_dialog("Please input the port the server listens to: ")

        programId = show_input_dialog("Please specify programId: ")
Example #49
0
                    help='port of the server this client will connect to')
parser.add_argument('-l',
                    '--logging',
                    type=int,
                    default=30,
                    help='set the logging level')

args = parser.parse_args()
port = args.port

pub_key_location = 'client/public.key'
private_key_location = 'client/private.key'

logging.getLogger().setLevel(args.logging)

a = Client(f'http://localhost:{port}', pub_key_location, private_key_location)

# resp = a.send_transaction("what what what asdfasdfasdfasdfasdf;lkj asdf adsf asdf asdf asdf aaaaaaaaaadg asdg asd gas dgas dga sdgWhat a horrible candle-snuffing word. That's like saying, He can't climb that mountain, he's just a man, or That's not a diamond, it's just a rock. Just.")
# b = resp.json()
# print(b)

inp = ''
while not inp is 'exit' and not inp is 'x':
    print(
        "s: send\ng: get transaction by id\na: get all of your transactions\nx: exit"
    )
    inp = input('>')
    if inp == 's':
        notes = input('patient notes: ')
        resp = a.send_transaction(notes)
        print(resp.json())
Example #50
0
class Ui_Form(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        self.setupUi(self)
        self.client = Client('localhost')
        
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(1000, 688)
        
        contents = QWidget(self)
        contents.setGeometry(QtCore.QRect(800, 40, 100, 30))
        self.getPhotoBtn = QtWidgets.QPushButton(contents)                
        self.getPhotoBtn.setObjectName("getPhotoBtn")
        self.getPhotoBtn.clicked.connect(self.getPhotoBtnEvent)
        
        contents = QWidget(self)
        contents.setGeometry(QtCore.QRect(800, 80, 100, 30))
        self.synchBtn = QtWidgets.QPushButton(contents)                
        self.synchBtn.setObjectName("synchBtn")
        self.synchBtn.clicked.connect(self.synchBtnEvent)
        
        self.horizontalLayoutContents = QtWidgets.QWidget(self)
        self.horizontalLayoutContents.setGeometry(QRect(40, 40, 700, 600))       
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutContents)
        
        
        self.scrollAreaWidgetContents = QtWidgets.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 600, 600))
        
        self.gridLayout = QtWidgets.QGridLayout()
        
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.scrollAreaWidgetContents)                
        self.horizontalLayout_2.addLayout(self.gridLayout)        
        
        self.scrollArea = QtWidgets.QScrollArea(self)
        self.scrollArea.setWidgetResizable(True)        
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        
        self.horizontalLayout.addWidget(self.scrollArea)
        
        self.row = 0;
        self.col = 0;
        self.width = 3;                        
        self.entries = []

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)
        
    def getPhotoBtnEvent(self):
        self.client.getAllPhoto()
        jpgList = glob.glob1("temp", "*.jpg")        
        for each in jpgList:
            self.addImageLabel(each)
    
    def synchBtnEvent(self):
        self.client.synchrinize()

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.getPhotoBtn.setText(_translate("Form", "getphoto"))
        self.synchBtn.setText(_translate("Form", "synchronize"))
    
    def addImageLabel(self, pic):        
        pixmap = QPixmap('temp/' + pic).scaled(200, 200, Qt.KeepAspectRatio)
        label = MyQLabel(self)
        label.setName(pic)
        
        label.setPixmap(pixmap)
        self.entries.append(label)                        
        self.gridLayout.addWidget(label, *(self.row, self.col))
        self.col += 1
        if self.col % self.width == 0:
            self.col = 0
            self.row += 1              
        
    def removeImageLabel(self, position):
        item = position[0] * self.width + position[1]  
        label = self.gridLayout.takeAt(item)
        widget = label.widget();
        widget.deleteLater();
Example #51
0
from tornado.ioloop import IOLoop

from rx import Observable
from rx.subjects import Subject
from rx.concurrency import QtScheduler, AsyncIOScheduler

from client.client import Client
from client.client_window import ClientWindow

import utils

if __name__ == '__main__':
    app = QApplication(sys.argv)
    scheduler = QtScheduler(QtCore)
    stock_prices = Subject()
    client = Client(port='9999')

    loop = asyncio.new_event_loop()
    asyncio_scheduler = AsyncIOScheduler(loop)

    def run_client():
        asyncio.set_event_loop(loop)
        asyncio.get_event_loop().call_soon(utils.run_client_websocket, client,
                                           stock_prices)
        asyncio.get_event_loop().run_forever()

    thread = Thread(target=run_client, daemon=True)
    thread.start()

    client_window = ClientWindow(stock_prices_stream=stock_prices)
    client_window.get_orders() \
Example #52
0
#!/usr/bin/python

from sys import argv

from client.client import Client

client = Client()

try:
  if "-s" in argv:
    try:
        client.run()
    except Exception, ex:
        print ex
  else:
    client.run()
except KeyboardInterrupt:
  print "KeyboardInterrupt"
  if client.run:
      client.run = False

Example #53
0
 def test_split_small_file(self):
     chunks = Client.split_file('test_small.txt')
     self.assertEqual(chunks[0], self.content[:12])
     self.assertEqual(len(chunks), 1)