def __init__(self, radius, name, time_step, n_bodies):
     self._radius = radius
     self._name = name
     self._body_list = []
     self._f_matrix = np.zeros(shape=(3, n_bodies))
     self.a_matrix = np.zeros(shape=(3, n_bodies))
     self.dt = time_step
     self._n_bodies = n_bodies
     self._analytics = Analytics()
     self._acceleration_analytics = Analytics()
     self._velocity_analytics = Analytics()
     self._t = 0
Exemplo n.º 2
0
class TestAnalytics(unittest.TestCase):
    ''' Test Class to test Class Analytics '''
    test_data = Analytics("2019-08-01")
    test_data.get_analytics()

    # test the customer count for "2019-08-01"
    def testCustomers(self):
        self.assertEqual(TestAnalytics.test_data.output['customers'], 9)

    # test the total_discount_amount for "2019-08-01"
    def test_total_discount_amount(self):
        self.assertAlmostEqual(
            TestAnalytics.test_data.output['total_discount_amount'],
            130429980.24)

    # test the total items sold for "2019-08-01"
    def test_items(self):
        self.assertEqual(TestAnalytics.test_data.output['items'], 2895)

    # The average order total for "2019-08-01"
    def test_order_total_average(self):
        self.assertAlmostEqual(
            TestAnalytics.test_data.output['order_total_average'], 15895179.73)

    # The average discount rate applied to the items sold for "2019-08-01"
    def test_discount_rate_avg(self):
        self.assertAlmostEqual(
            TestAnalytics.test_data.output['discount_rate_avg'], 0.13)

    # The total amount of commissions generated for "2019-08-01"
    def test_commissions_total(self):
        self.assertAlmostEqual(TestAnalytics.test_data.commissions['total'],
                               20833236.94)
Exemplo n.º 3
0
 def __init__(self):
     '''  The __init__ access tokens and credentials are being imported from the config.py module.
     This file must be included in the root for the script to function'''
     self.SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
     self.KEY_FILE_LOCATION = './auth.json'
     self.VIEW_ID = config.view_id
     self.analytics = Analytics()
Exemplo n.º 4
0
    def __init__(self, collection, api_class=OdiloAPI, **kwargs):
        """Constructor.

        :param collection: Provide bibliographic coverage to all
            Odilo books in the given Collection.
        :param api_class: Instantiate this class with the given Collection,
            rather than instantiating OdiloAPI.
        """
        super(OdiloBibliographicCoverageProvider,
              self).__init__(collection, **kwargs)
        if isinstance(api_class, OdiloAPI):
            # Use a previously instantiated OdiloAPI instance
            # rather than creating a new one.
            self.api = api_class
        else:
            # A web application should not use this option because it
            # will put a non-scoped session in the mix.
            _db = Session.object_session(collection)
            self.api = api_class(_db, collection)

        self.replacement_policy = ReplacementPolicy(
            identifiers=True,
            subjects=True,
            contributions=True,
            links=True,
            formats=True,
            rights=True,
            link_content=True,
            # even_if_not_apparently_updated=False,
            analytics=Analytics(self._db))
Exemplo n.º 5
0
    def __init__(self, _db, collection):
        if collection.protocol != ExternalIntegration.ODILO:
            raise ValueError(
                "Collection protocol is %s, but passed into OdiloAPI!" %
                collection.protocol)

        self._db = _db
        self.analytics = Analytics(self._db)

        self.collection_id = collection.id
        self.token = None
        self.client_key = collection.external_integration.username
        self.client_secret = collection.external_integration.password
        self.library_api_base_url = collection.external_integration.setting(
            self.LIBRARY_API_BASE_URL).value

        if not self.client_key or not self.client_secret or not self.library_api_base_url:
            raise CannotLoadConfiguration("Odilo configuration is incomplete.")

        # Use utf8 instead of unicode encoding
        settings = [
            self.client_key, self.client_secret, self.library_api_base_url
        ]
        self.client_key, self.client_secret, self.library_api_base_url = (
            setting.encode('utf8') for setting in settings)

        # Get set up with up-to-date credentials from the API.
        self.check_creds()
        if not self.token:
            raise CannotLoadConfiguration(
                "Invalid credentials for %s, cannot intialize API %s" %
                (self.client_key, self.library_api_base_url))
Exemplo n.º 6
0
def get_analytics():
    try:
        args = json.dumps(request.json)
        args = json.loads(args)
        arg = args[0]
        analytic_object = Analytics(es_instance)
        result = []
        if (arg == "category"):
            result = analytic_object.get_category_analytics()
        elif (arg == "entity"):
            result = analytic_object.get_entities_analytics()
        elif (arg == "reporter"):
            result = analytic_object.get_reporter_analytics()
        elif (arg == "avg_leads_cat"):
            result = analytic_object.get_avg_category_analytics()
        elif (arg == "avg_leads_ent"):
            result = analytic_object.get_avg_entity_analytics()
        else:
            result = ["Invalid choice"]
            logging.error("Invalid Choice")
        return jsonify({"success": True, "data": result})

    except Exception as e:
        logging.error("In fetching analytics" + str(e))
        return jsonify({"success": False})
Exemplo n.º 7
0
def main():
    a = Analytics()
    a.start_timer()
    img = cv2.imread('lvision/assets/images/locations/basing.png')
    points = numpy.where(numpy.all(img == [0, 255, 0], axis=-1))
    points = list(zip(*points[::-1]))
    print(points)
    a.end_timer()
Exemplo n.º 8
0
def _rand_event(instant):
    component = choice([
        _rand_first_button, _rand_success_button, _rand_range,
        _rand_first_name, _rand_last_name
    ])()
    component['timestamp'] = time_ns()
    component['session'] = choice(list(_sessions))
    component['instant'] = instant
    return Analytics(component)
Exemplo n.º 9
0
    def find(self, df, mode, param):
        self.available_columns = available_columns = list(df.columns)
        original_variables = [col for col in df.columns if '_impact' in col]
        self.impact_variables = [
            col for col in original_variables if not '_rescaled' in col
        ]
        self.y_variable = param["y_variable"]
        self.y_variable_predict = param["y_variable_predict"]
        self.param = param
        self.instance_id = self.random_string_generator()
        self.create_dir("data_storage")
        self.create_dir("data_storage/user")
        self.user_id = None
        self.df = df

        self.analytics = Analytics()
        self.analytics['ip'] = self.analytics.finding_ip()
        self.analytics['mac'] = self.analytics.finding_address()
        self.analytics['instance_id'] = self.instance_id
        self.analytics['time'] = str(datetime.datetime.now())
        self.analytics['total_columns'] = len(self.available_columns)
        self.analytics['total_rows'] = len(self.df)
        self.analytics['os'] = self.analytics.finding_system()
        self.analytics['model_name'] = self.param["model_name"]
        self.analytics["function"] = 'explainx.ai'
        self.analytics["query"] = "all"
        self.analytics['finish_time'] = ''

        self.callback_input = [
            Input(f + '_slider', 'value') for f in self.param["columns"]
        ]
        self.callback_input.append(Input('submit-button-state', 'n_clicks'))

        # self.callback_input_prototype = [Input(f + '-slider', 'value') for f in self.param["columns"]]
        # self.callback_input_prototype.append(Input('btn-nclicks-1', 'n_clicks'))

        self.prototype_array = []
        for f in self.param["columns"]:
            self.prototype_array.append([f + '_slider', 'value'])
        self.prototype_array.append(['btn-nclicks-1', 'n_clicks'])
        try:
            user_id = pd.read_csv("data_storage/user/user_id.csv")
            user_id.drop_duplicates(['id'], keep='first', inplace=True)
            user_id = user_id['id'].iloc[0]
            self.user_id = user_id
        except Exception as e:
            # print("inside user track" )
            user_id_val = self.random_string_generator()
            user_id_csv = pd.DataFrame(data={"id": [user_id_val]})
            user_id_csv.to_csv("data_storage/user/user_id.csv", index=False)
            self.user_id = user_id_val

        self.analytics['user_id'] = self.user_id
        self.analytics.insert_data()
        self.insights = insights(self.param)
        d = self.dash(df, mode)
        return True
Exemplo n.º 10
0
    def run_abstract_service(self, service_name, persist=False):
        #print "run run_abstract_service(Events, persist) from run_events_service(self, persist=False)"
        i = 1
        service_instance = None
        while True:
            try:
                if isinstance(self.__connection,
                              ONVIFCamera) and self.__connect_state:
                    #print 'Run ' + str(service_name) + ' service'
                    support = self.loop_check_status_abstract_service(
                        'support', service_name)
                    init = self.loop_check_status_abstract_service(
                        'init', service_name)
                    #run = self.loop_check_status_abstract_service('run', service_name)
                    if self.__loop_mode:
                        if support and init:
                            #print 'change state run True ' + str(service_name) + ' service'
                            #print "Call loop_edit_status_abstract_service(run, Events) from run_abstract_service(Events, persist)"
                            self.loop_edit_status_abstract_service(
                                'run', service_name)
                    else:
                        print 'Start ' + str(service_name) + ' service'
                        # self.__services['Event'] = EventService(self.__connection, persist)
                        self.loop_edit_status_abstract_service(
                            'run', service_name)
                        if service_name == 'Analytics':
                            service_instance = Analytics(self, persist)
                        if service_name == 'Device':
                            service_instance = Device(self, persist)
                        if service_name == 'Events':
                            service_instance = Events(self, persist)
                        if service_name == 'Imaging':
                            service_instance = Imaging(self, persist)
                        if service_name == 'Media':
                            service_instance = Media(self, persist)
                        if service_name == 'PTZ':
                            service_instance = PTZ(self, 0, 0, 0, 20, persist,
                                                   None)
                        if service_instance is not None:
                            self.loop_edit_status_abstract_service(
                                'instance', service_name, service_instance)
                            break
                        else:
                            print 'service_instance of ' + str(
                                service_name) + ' is None'

                else:
                    if not isinstance(self.__connection,
                                      ONVIFCamera) or not self.__connect_state:
                        # print 'The connection has not yet been established or connection has been lost'
                        self.try_connect(i)
            except ONVIFError as e:
                self.__connect_state = False
                print 'Exception inside get_support_device: ' + str(e.reason)
                self.try_connect(i)
                continue
            i += 1
Exemplo n.º 11
0
def main():
    '''Main function of the script'''
    parser = argparse.ArgumentParser()
    parser.add_argument('--all', '-a', action='store_true')
    parser.add_argument('--interactive', '-i', action='store_true')

    args = parser.parse_args()

    logger = CliLogger()
    screen = Screen()

    analytics = Analytics(logger)
    resources = Resources()
    analytics.ignore = ANALYTICS_IGNORE
    resources.load(analytics)

    if args.interactive:
        handle = wait_league_window(logger, (0, 0, 1024, 768))
        screen.d3d.capture(target_fps=10, region=find_rect(handle))
        while True:
            if keyboard.is_pressed('x'):
                cv2.destroyAllWindows()
                screen.d3d.stop()
                break
            img = screen.d3d.get_latest_frame()
            if img is None:
                continue
            try:
                img_bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
                objs = tick(logger, analytics, resources, img)
                draw_objects(img_bgr,
                             objs,
                             wait=False,
                             title='League Vision - Interactive')
                logger.log('Press and hold x to exit bot.')
            except NoCharacterInMinimap:
                pass
            logger.log('-' * 50)
            time.sleep(1)
        return

    if args.all:
        files = glob.glob('screenshots/*.png')
    else:
        files = glob.glob('screenshots/*.png')[:1]

    for file in files:
        img_bgr = cv2.imread(file)
        img = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
        try:
            objs = tick(logger, analytics, resources, img)
            logger.log('Press x to exit.')
        except NoCharacterInMinimap:
            pass
        logger.log('-' * 50)
        if draw_objects(img_bgr, objs, title=f'League Vision - {file}') == 120:
            break
Exemplo n.º 12
0
    def test_initialize(self):
        # supports multiple analytics providers, site-wide or with libraries

        # Two site-wide integrations
        mock_integration, ignore = create(
            self._db,
            ExternalIntegration,
            goal=ExternalIntegration.ANALYTICS_GOAL,
            protocol="mock_analytics_provider")
        mock_integration.url = self._str
        local_integration, ignore = create(
            self._db,
            ExternalIntegration,
            goal=ExternalIntegration.ANALYTICS_GOAL,
            protocol="local_analytics_provider")

        # A broken integration
        missing_integration, ignore = create(
            self._db,
            ExternalIntegration,
            goal=ExternalIntegration.ANALYTICS_GOAL,
            protocol="missing_provider")

        # Two library-specific integrations
        l1, ignore = create(self._db, Library, short_name="L1")
        l2, ignore = create(self._db, Library, short_name="L2")

        library_integration1, ignore = create(
            self._db,
            ExternalIntegration,
            goal=ExternalIntegration.ANALYTICS_GOAL,
            protocol="mock_analytics_provider")
        library_integration1.libraries += [l1, l2]

        library_integration2, ignore = create(
            self._db,
            ExternalIntegration,
            goal=ExternalIntegration.ANALYTICS_GOAL,
            protocol="mock_analytics_provider")
        library_integration2.libraries += [l2]

        analytics = Analytics(self._db)
        eq_(2, len(analytics.sitewide_providers))
        assert isinstance(analytics.sitewide_providers[0],
                          MockAnalyticsProvider)
        eq_(mock_integration.url, analytics.sitewide_providers[0].url)
        assert isinstance(analytics.sitewide_providers[1],
                          LocalAnalyticsProvider)
        assert missing_integration.id in analytics.initialization_exceptions

        eq_(1, len(analytics.library_providers[l1.id]))
        assert isinstance(analytics.library_providers[l1.id][0],
                          MockAnalyticsProvider)

        eq_(2, len(analytics.library_providers[l2.id]))
        for provider in analytics.library_providers[l2.id]:
            assert isinstance(provider, MockAnalyticsProvider)
Exemplo n.º 13
0
def click():
    if 'id' not in session:
        session['id'] = uuid.uuid4()
    session_id = session['id']
    data = request.get_json()
    app.logger.info('Event received: %s', data)
    data['session'] = session_id.hex
    app.logger.info('Event enriched: %s', data)
    analytics.set(uuid.uuid4(), Analytics(data)).result()
    return Response(status=202)
Exemplo n.º 14
0
def main():
    global start_of_event
    global last_window
    global last_event
    global html_update_time

    analytic = Analytics()

    print("""
---------------------------------------
TRACK YOUR TIME - DON'T WASTE IT!
---------------------------------------

  TIME           CATEGORY""")

    while True:
        mouse_idle = is_mouse_idle()
        keyboard_idle = is_keyboard_idle(0.01)

        current_window = get_window_name()
        idle = mouse_idle and keyboard_idle

        if idle:
            current_event = 'idle'
        else:
            current_event = current_window

        if current_event != last_event:
            if last_event == 'idle':
                category = 'idle'
            else:
                category = analytic.get_cat(last_window)

            duration = time.time() - start_of_event
            if duration > 2:

                save_data([time.time(), category, int(duration)])
                try:
                    if sys.version_info.major > 2:
                        mins = int(np.floor(duration / 60))
                        secs = int(np.floor(duration - mins * 60))
                        print("{0: 3}:{1:02} min\t".format(mins, secs),
                              "{}\t".format(category),
                              "({})".format(last_event[:30]))
                except UnicodeDecodeError:
                    print("{0: 5.0f} s\t".format(duration),
                          "UNICODE DECODE ERROR")

            last_window = current_window
            start_of_event = time.time()
            last_event = current_event

        if time.time() > html_update_time:
            analytic.create_html()
            html_update_time = time.time() + 60
Exemplo n.º 15
0
 def initialize(self):
     self._uuid = self._get_setting([
         ["plugins", "discovery", "upnpUuid"],
     ], ["public", "uuid"]) or self._generate_uuid()
     self._search_id = self._settings.get(["public", "search_id"
                                           ]) or self._generate_search_id()
     self._analytics = Analytics(self)
     self._url = self._settings.get(["url"])
     self._logger.info("FindMyMrBeam enabled: %s", self.is_enabled())
     self._analytics.log_enabled(self.is_enabled())
     self.update_frontend()
Exemplo n.º 16
0
def request_analytics_by_date(analytics_date):

    #redirect to date_error page is invalid date format
    if not isValidDate(analytics_date):
        return render_template('date_error.html')

    # create Analytics object and populate with analytics data.
    data = Analytics(analytics_date)
    data.get_analytics()

    # return the output dictionary in json format to the browser
    return jsonify(data.output)
Exemplo n.º 17
0
    def loop_check_edit_instance_service(self, name_service):
        run = self.loop_check_status_abstract_service('run', name_service)
        instance = self.loop_check_status_abstract_service(
            'instance', name_service)
        #print 'NAME PTZ SERVICE BEFORE IF:' + str(name_service)
        #print 'NAME PTZ SERVICE RUN:' + str(run)
        #print 'NAME PTZ SERVICE INSTANCE:' + str(instance)

        #instance_service = None
        #instance_flag = False
        if run and not instance:
            if name_service == 'Analytics':
                instance_service = Analytics(self, True)
                self.loop_edit_status_abstract_service('instance',
                                                       name_service,
                                                       instance_service)
                instance_flag = True
            if name_service == 'Device':
                instance_service = Device(self, True)
                self.loop_edit_status_abstract_service('instance',
                                                       name_service,
                                                       instance_service)
                instance_flag = True
            if name_service == 'Events':
                instance_service = Events(self, True)
                self.loop_edit_status_abstract_service('instance',
                                                       name_service,
                                                       instance_service)
                instance_flag = True
            if name_service == 'Imaging':
                instance_service = Imaging(self, True)
                self.loop_edit_status_abstract_service('instance',
                                                       name_service,
                                                       instance_service)
                instance_flag = True
            if name_service == 'Media':
                instance_service = Media(self, True)
                self.loop_edit_status_abstract_service('instance',
                                                       name_service,
                                                       instance_service)
                instance_flag = True
            if name_service == 'PTZ':
                #print 'MY<>NAME<>PTZ'
                instance_service = PTZ(self, 0, 0, 0, 20, True, None)
                #print 'Vse NORM'
                self.loop_edit_status_abstract_service('instance',
                                                       name_service,
                                                       instance_service)
                instance_flag = True
Exemplo n.º 18
0
 def __init__(self, root):
     builder = pygubu.Builder()
     builder.add_from_file('ldesigner/gui.ui')
     builder.get_object('main_frame', root)
     builder.connect_callbacks(self)
     root.title('League of Legends Tile Designer')
     root.geometry('640x480+0+480')
     logger = CliLogger('%H:%M:%S')
     keyboard.add_hotkey('a', self.set_true)
     keyboard.add_hotkey('s', self.set_false)
     self.analytics = Analytics(logger)
     self.builder = Builder(builder)
     self.tiles = numpy.zeros((183, 183, 3), numpy.uint8)
     self.coor = None
     threading.Thread(target=self.monitor_league, daemon=True).start()
Exemplo n.º 19
0
    def test_collect_event(self):
        sitewide_integration, ignore = create(
            self._db,
            ExternalIntegration,
            goal=ExternalIntegration.ANALYTICS_GOAL,
            protocol="mock_analytics_provider")

        library, ignore = create(self._db, Library, short_name="library")
        library_integration, ignore = create(
            self._db,
            ExternalIntegration,
            goal=ExternalIntegration.ANALYTICS_GOAL,
            protocol="mock_analytics_provider",
        )
        library_integration.libraries += [library]

        work = self._work(title="title", with_license_pool=True)
        [lp] = work.license_pools
        analytics = Analytics(self._db)
        sitewide_provider = analytics.sitewide_providers[0]
        library_provider = analytics.library_providers[library.id][0]

        analytics.collect_event(self._default_library, lp,
                                CirculationEvent.DISTRIBUTOR_CHECKIN, None)

        # The sitewide provider was called.
        eq_(1, sitewide_provider.count)
        eq_(CirculationEvent.DISTRIBUTOR_CHECKIN, sitewide_provider.event_type)

        # The library provider wasn't called, since the event was for a different library.
        eq_(0, library_provider.count)

        analytics.collect_event(library, lp,
                                CirculationEvent.DISTRIBUTOR_CHECKIN, None)

        # Now both providers were called, since the event was for the library provider's library.
        eq_(2, sitewide_provider.count)
        eq_(1, library_provider.count)
        eq_(CirculationEvent.DISTRIBUTOR_CHECKIN, library_provider.event_type)

        # Here's an event that we couldn't associate with any
        # particular library.
        analytics.collect_event(None, lp,
                                CirculationEvent.DISTRIBUTOR_CHECKOUT, None)

        # It's counted as a sitewide event, but not as a library event.
        eq_(3, sitewide_provider.count)
        eq_(1, library_provider.count)
Exemplo n.º 20
0
 def __init__(self, label, params={}, **kwargs):
     self.label = label
     self.setup = Setup()
     self.ana = Analytics()
     if 'analysis_type' in kwargs:
         self.analysis_type = kwargs['analysis_type']
     else:
         self.analysis_type = 'dynamical'
     # set default analysis and circuit parameter
     self._set_up_circuit(params, kwargs)
     # set parameter derived from analysis and circuit parameter
     new_vars = self.setup.get_params_for_analysis(self)
     new_vars['label'] = self.label
     self._set_class_variables(new_vars)
     # set variables which require calculation in analytics class
     self._calc_variables()
Exemplo n.º 21
0
def collection_and_analysis(data, is_analytic):
    entrants = []
    for fio in data:
        entrant = EntrantApplications(fio)
        entrants.append(entrant)
    result = []
    for entrant in entrants:
        result.append(entrant.fname)
        result.append('Согласие о зачислении подано на направление: ' +
                      entrant.priority[1])
        for direction in entrant.apps:
            result.append(direction[1])
        result.append('')
    if is_analytic:
        analysis = Analytics(entrants)
        result.extend(analysis.get_analytics())
    return result
Exemplo n.º 22
0
def main():
    '''Main function of the script'''
    logger = CliLogger()
    analytics = Analytics(logger)
    analytics.ignore = [
        'screenshot', 'get_minimap_coor', 'get_minimap_areas', 'get_objects'
    ]
    screen = Screen()
    hwnd = wait_league_window(logger, (0, 0, 1024, 768))
    time.sleep(1)

    logger.log('Press and hold x to exit bot.')
    while True:
        if keyboard.is_pressed('x'):
            break
        img = screen.screenshot(find_rect(hwnd))
        time.sleep(1)
Exemplo n.º 23
0
def main():
    '''Main function of the script'''
    paused = False

    logger = CliLogger()
    screen = Screen()
    resources = Resources()
    analytics = Analytics(logger)
    cooldown = Cooldown(COOLDOWNS)
    analytics.ignore = ANALYTICS_IGNORE
    resources.load(analytics)
    utility = Utility(logger, screen, resources, analytics, cooldown)
    logic = Logic(utility)
    try:
        handle = wait_league_window(logger, (0, 0, 1024, 768))
    except CantForgroundWindowError:
        pass
    logger.log('Press and hold x to exit bot.')
    screen.d3d.capture(target_fps=10, region=find_rect(handle))
    while True:
        try:
            if keyboard.is_pressed('x'):
                raise BotExitException
            if keyboard.is_pressed('ctrl+u'):
                paused = False
            if paused:
                time.sleep(0.1)
                continue
            if keyboard.is_pressed('ctrl+p'):
                paused = True
                logger.log(
                    'Bot paused. Press ctrl+u to unpause. Press x to exit.')
                continue
            logic.tick()
            time.sleep(random.randint(*TICK_INTERVAL) / 1000)
        except BotContinueException as exp:
            time.sleep(random.randint(*exp.tick_interval) / 1000)
        except NoCharacterInMinimap:
            time.sleep(1)
        except BotExitException:
            screen.d3d.stop()
            break
        except Exception:  # pylint:disable=broad-except
            traceback.print_exc()
            screen.d3d.stop()
            break
Exemplo n.º 24
0
    def __init__(self):
        self.connection = psql_connection()
        self.analytics = Analytics(token=MIXPANEL_TOKEN)
        self.payment_processor = Payment(token=STRIPE_TOKEN)

        try:
            cpus = cpu_count()
        except NotImplementedError:
            cpus = 2

        self.queue = Queue()
        self.processes = list()

        for i in xrange(cpus):
            print "Worker Process #{} Initialized".format(i)

            p = Process(target=work_queue, args=(self.queue,))
            p.start()
            self.processes.append(p)
Exemplo n.º 25
0
def main():

    print("Imports data into InfluxDB. Use --help for parameters")

    use_importers = read_parameters()

    importers = [Catalanitzador(), Programs(), AdSense(), Analytics(),
                 TTS(), TM(), DictMutilingual(), Criteo(), Traductor(), STT(), NeuralTranslator()]

    for importer in importers:
        try:
            if use_importers and type(importer).__name__.lower() not in use_importers:
                continue

            importer.do()

        except Exception as e:
            msg = "Error at importer '{0}': {1}"
            print(msg.format(type(importer).__name__, e))
            exc_type, exc_value, exc_traceback = sys.exc_info()
            traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
Exemplo n.º 26
0
    def post(self, opt):
        params = tornado.escape.json_decode(self.request.body)
        logging.info('load data', opt, params)
        res = {}
        if opt == 'upload':
            AnalyticsHandler.data = Dataset(
                pd.DataFrame.from_dict(params['data']))
        else:
            AnalyticsHandler.data = Dataset(pd.read_csv(params['url']))

        if '$select' in params:
            AnalyticsHandler.data.select(**params['$select'])
        if '$preprocess' in params:
            AnalyticsHandler.data.preprocess(**params['$preprocess'])
        if '$transform' in params:
            AnalyticsHandler.data.transform(**params['$transform'])

        AnalyticsHandler.program = Analytics(AnalyticsHandler.data,
                                             AnalyticsHandler.models)
        res = AnalyticsHandler.program.metadata()
        self.write(res)
Exemplo n.º 27
0
    def __init__(self, opt, from_file=False):
        self.opt = opt
        self.max_size_lim = opt.max_size_lim
        self.prolif_lim = self.opt.prolif_lim

        if not from_file:
            self.tumoursize = opt.init_size
            self.clonecount = 1
            self.all_mutations = {'b': [], 'n': [], 'd': [], 'r': []}
            self.subpop = Subpopulation(opt=opt,
                                        prolif=opt.pro,
                                        mut_rate=opt.mut,
                                        depth=0,
                                        t_curr=0,
                                        col='n',
                                        prev_time=0)
            if opt.init_diversity:
                self.subpop.size = 0
                self.subpop.new_subpop_from_file(self.opt, self.opt.sub_file)
            else:
                self.subpop.size = opt.init_size
            self.avg_pro_rate = self.opt.pro
            self.avg_mut_rate = self.opt.mut
            self.analytics_base = Analytics()
        else:
            # these attributes will be initialised from file
            self.tumoursize = self.clonecount = None
            self.all_mutations = self.subpop = None
            self.avg_pro_rate = self.avg_mut_rate = None
            self.analytics_base = None

        self.select_pressure = 0.0
        self.mutagenic_pressure = 0.0
        self.selective_pressure_applied = False
        # these lists will be populated at crash time
        self.mid_proliferation = []
        self.mid_mutation = []
Exemplo n.º 28
0
def main():
    '''Main function of the script'''
    root = tkinter.Tk()
    root.title('Training Data Generator')
    canvas = tkinter.Canvas(root, width=300, height=300)
    canvas.pack()
    canvas_img = canvas.create_image(20, 20, anchor="nw")
    root.mainloop(n=1)

    parser = argparse.ArgumentParser()
    parser.add_argument('--all', '-a', action='store_true')
    parser.add_argument('--interactive', '-i', action='store_true')

    args = parser.parse_args()

    logger = CliLogger()
    screen = Screen()
    analytics = Analytics(logger)

    def tick_gui(img):
        tick(lambda: askstring('Enter label. Type exit to stop.', root, parent=root),
             lambda i: canvas.itemconfig(canvas_img, image=i), img)

    if args.interactive:
        hwnd = wait_league_window(logger, (0, 0, 1024, 768))
        img = screen.screenshot(analytics, find_rect(hwnd))
        img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
        tick_gui(img)
        return
    if args.all:
        files = glob.glob('screenshots/*.png')
    else:
        files = [glob.glob('screenshots/*.png')[0]]
    for file in files:
        img = cv2.imread(file)
        tick_gui(img)
Exemplo n.º 29
0
app.config.from_object('config')
db = SQLAlchemy(app)

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

from models import User, WaitingListUser, ActiveChatsUser
from templates import TextTemplate
from DB_Wrappers import *

usersdb = UsersDB(db=db)
waitlistdb = WaitingListDB(db=db)
activechatsdb = ActiveChatsDB(db=db)

from modules import *
setup_all()
metrics = Analytics()
Int = Interrupts()
game = Game(db=db)


# --------------------------------------------------------------- #
@app.route('/webview/', methods=['POST'])
def getProfile():
    try:
        print("FORM SUBMITTED", dict(request.form))
        bio = request.form['bio']
        interests = request.form['interests']
        id = request.form['psid']
        print("USER ID", id)
        user = usersdb.get(id)
        user.interests = interests
Exemplo n.º 30
0
 def processTransactions(self):
     transactions = self.getAllTransactions()
     transactions.reverse()
     self.analysis = Analytics(transactions)
     self.analysis.process()