コード例 #1
0
    def __init__(self) -> None:
        """Initialization"""
        self.return_code = -1
        self.state = self.State(self.State.START.value + 1)

        self.new_user = dict(
            username="******",
            password="******",
            full_name="John Doe",
            role=AuthenticationMessages.Role.OPERATOR.value,
            updated_full_name="John J. Doe",
            updated_password="******",
            updated_role=AuthenticationMessages.Role.ADMIN.value,
        )

        self.settings = get_settings()

        self.logger = setup_log("AuthenticationExample",
                                self.settings.log_level)

        self.client = Connections(
            hostname=self.settings.hostname,
            logger=self.logger,
            authentication_on_open=self.authentication_on_open,
            authentication_on_message=self.authentication_on_message,
            authentication_on_error=self.authentication_on_error,
            authentication_on_close=self.authentication_on_close,
        )

        self.authentication = AuthenticationMessages(
            self.logger, self.settings.protocol_version)
コード例 #2
0
def lambda_handler(event, context, **kwargs):
    print(
        'Starting function\n-------------------------------------------------')
    start_time = time()
    print('Loading account credentials')
    accounts = Connections()

    print('Gathering Usage and Limit Data')
    comparisons = {}
    for count, account in enumerate(accounts.env_names):
        comparisons[account] = AccountUsage(accounts.env_names[count],
                                            accounts.connection_list[count])
        comparisons[account].get_limits()
        comparisons[account].compare()

    print('Generationg Email')
    email = EmailGenerator(comparisons)
    email.create_html
    email.send_email

    print('Creating Report')
    report = ReportGenerator(email.utilization)
    json = report.write_json()
    csv = report.write_csv

    print('Uplaoding Report to S3')
    push_json = report.push_to_s3(report.metadata)
    push_csv = report.push_to_s3(report.report)

    end_time = time() - start_time
    print('Time required: {0:.2f} s'.format(end_time))
コード例 #3
0
ファイル: games.py プロジェクト: bpaff/123-p
 def __init__(self):
     self._connections = Connections()
     self._connections_need_game = []
     self._number_of_wait_ticks = 0
     self._game_number = 0
     self._games = {}
     self._games_to_kill = []
コード例 #4
0
    def __init__(self):
        builder = Gtk.Builder()
        builder.add_objects_from_file('app.glade', ('winConnections', ))

        self.window = builder.get_object('winConnections')

        self.connection_list = builder.get_object('listConnections')

        self.ent_host = builder.get_object('entHost')
        self.ent_port = builder.get_object('entPort')
        self.ent_user = builder.get_object('entUser')
        self.ent_password = builder.get_object('entPassword')
        self.ent_database = builder.get_object('entDatabase')
        self.ent_remote_host = builder.get_object('entRemoteHost')
        self.ent_remote_user = builder.get_object('entRemoteUser')
        self.file_remote_key = builder.get_object('fileRemoteKey')

        self.connections = Connections()

        for connection in self.connections.get_connections():
            self.connection_list.add(ListBoxRowWithData(connection))

        if self.connections.count() == 0:
            self.on_add_connection(None)

        builder.connect_signals({
            'onAddConnection': self.on_add_connection,
            'onListSelected': self.on_list_selected,
            'onRemoveConnection': self.on_remove_connection,
            'onSaveConnection': self.on_save_connection,
            'onConnect': self.on_connect
        })

        WindowManager.add_window(self.window)
        self.window.show_all()
コード例 #5
0
    def __init__(self) -> None:
        """Initialization"""
        self.return_code = -1
        self.state = self.State(self.State.START.value + 1)

        self.authentication_thread = None
        self.metadata_thread = None

        self.settings = get_settings()

        self.logger = setup_log("BuildingExample", self.settings.log_level)

        self.client = Connections(
            hostname=self.settings.hostname,
            logger=self.logger,
            authentication_on_open=self.authentication_on_open,
            authentication_on_message=self.authentication_on_message,
            authentication_on_error=self.authentication_on_error,
            authentication_on_close=self.authentication_on_close,
            metadata_on_open=self.metadata_on_open,
            metadata_on_message=self.metadata_on_message,
            metadata_on_error=self.metadata_on_error,
            metadata_on_close=self.metadata_on_close,
        )

        self.messages = BuildingMessages(self.logger,
                                         self.settings.protocol_version)
コード例 #6
0
    def __init__(self) -> None:
        """Initialization"""
        self.return_code = -1
        self.state = self.State(self.State.START.value + 1)

        self.authentication_thread = None
        self.metadata_thread = None
        self.realtime_situation_thread = None

        self.total_node_count = 0
        self.loaded_node_count = 0

        self.settings = get_settings()

        self.logger = setup_log("ComponentsInformationExample",
                                self.settings.log_level)

        self.client = Connections(
            hostname=self.settings.hostname,
            logger=self.logger,
            authentication_on_open=self.authentication_on_open,
            authentication_on_message=self.authentication_on_message,
            authentication_on_error=self.authentication_on_error,
            authentication_on_close=self.authentication_on_close,
            metadata_on_open=self.metadata_on_open,
            metadata_on_message=self.metadata_on_message,
            metadata_on_error=self.metadata_on_error,
            metadata_on_close=self.metadata_on_close,
            realtime_situation_on_open=self.realtime_situation_on_open,
            realtime_situation_on_message=self.realtime_situation_on_message,
            realtime_situation_on_error=self.realtime_situation_on_error,
            realtime_situation_on_close=self.realtime_situation_on_close,
        )

        self.messages = Messages(self.logger, self.settings.protocol_version)
コード例 #7
0
 def tearDownClass(cls) -> None:
     db = Connections(table_name=None)
     with db.connect() as conn:
         company_email = '*****@*****.**'
         email = '*****@*****.**'
         conn.execute(
             f"delete from provider where email = '{company_email}'")
         conn.execute(f"delete from client where email = '{email}'")
コード例 #8
0
    def __init__(self) -> None:
        """Initialization"""
        self.return_code = -1
        self.state = self.State(self.State.START.value + 1)

        # Network id needs to point to a valid network with at least one sink
        # online
        self.network_id = 777555

        self.sink_ids = None
        # Uncomment the line below for setting appconfig for specific sinks only
        # self.sink_ids = [1, 101]

        # When running more than once for the same network, the diagnostics interval
        # or application data needs to changed as WNT server will not try to set the
        # application configuration if it is already the same.
        self.diagnostics_interval = 60
        self.application_data = "00112233445566778899AABBCCDDEEFF"

        self.is_override_on = False

        self.authentication_thread = None
        self.metadata_thread = None
        self.realtime_situation_thread = None

        self.total_node_count = 0
        self.loaded_node_count = 0

        self.settings = get_settings()

        self.logger = setup_log(
            "ApplicationConfigurationExample", self.settings.log_level
        )

        self.client = Connections(
            hostname=self.settings.hostname,
            logger=self.logger,
            authentication_on_open=self.authentication_on_open,
            authentication_on_message=self.authentication_on_message,
            authentication_on_error=self.authentication_on_error,
            authentication_on_close=self.authentication_on_close,
            metadata_on_open=self.metadata_on_open,
            metadata_on_message=self.metadata_on_message,
            metadata_on_error=self.metadata_on_error,
            metadata_on_close=self.metadata_on_close,
            realtime_situation_on_open=self.realtime_situation_on_open,
            realtime_situation_on_message=self.realtime_situation_on_message,
            realtime_situation_on_error=self.realtime_situation_on_error,
            realtime_situation_on_close=self.realtime_situation_on_close,
        )

        self.messages = Messages(self.logger, self.settings.protocol_version)
コード例 #9
0
    def __init__(self):
        """Return a Customer object whose name is *name*."""

        self.exchangeRate = ExchangeRate()
        self.weather = Weather()
        self.myconnection = Connections()
        self.myppointments = Appointments()

        #place holder for other option
        if (SHOW_DATA_AT == "spread_sheet"):
            self.data_visualizer = SreadSheet()

        self.reset()
コード例 #10
0
    def connectionsFactory(*args, **kwargs):
        """
    Create a :class:`~nupic.algorithms.connections.Connections` instance.  
    :class:`TemporalMemory` subclasses may override this method to choose a 
    different :class:`~nupic.algorithms.connections.Connections` implementation, 
    or to augment the instance otherwise returned by the default 
    :class:`~nupic.algorithms.connections.Connections` implementation.

    See :class:`~nupic.algorithms.connections.Connections` for constructor 
    signature and usage.

    :returns: :class:`~nupic.algorithms.connections.Connections` instance
    """
        return Connections(*args, **kwargs)
コード例 #11
0
    def __init__(self, layer_num):  # 初始化一个全联接网络,所以不需要指定connections,layer_num是一个list,元素代表每层node数
        self.layers = []
        layer_count = len(layer_num)
        for i in range(layer_count):
            self.layers.append(Layer(i, layer_num[i]))  # 初始化layer,给各layer填充节点

        self.connections = Connections()
        for i in range(layer_count - 1):  # 初始化connections,全连接网络
            connections = [Connection(up_node, down_node) for up_node in self.layers[i].nodes
                           for down_node in self.layers[i + 1].nodes]
            for conn in connections:
                self.connections.add_conn(conn)
                conn.up_node.add_downconns(conn)
                conn.down_node.add_upconns(conn)
コード例 #12
0
    def __init__(self) -> None:
        """Initialization"""
        self.floor_plan_image_id = None
        self.floor_plan_image_thumbnail_id = None

        self.return_code = -1
        self.state = self.State(self.State.START.value + 1)

        self.authentication_thread = None
        self.metadata_thread = None

        self.settings = get_settings()

        self.logger = setup_log("FloorPlanAreaExample", self.settings.log_level)

        self.client = Connections(
            hostname=self.settings.hostname,
            logger=self.logger,
            authentication_on_open=self.authentication_on_open,
            authentication_on_message=self.authentication_on_message,
            authentication_on_error=self.authentication_on_error,
            authentication_on_close=self.authentication_on_close,
            metadata_on_open=self.metadata_on_open,
            metadata_on_message=self.metadata_on_message,
            metadata_on_error=self.metadata_on_error,
            metadata_on_close=self.metadata_on_close,
        )

        self.messages = Messages(self.logger, self.settings.protocol_version)

        script_path = os.path.dirname(os.path.realpath(__file__))

        self.floor_plan_image_file_path = os.path.join(
            script_path, "assets/floor_plan.png"
        )

        self.floor_plan_image_thumbnail_file_path = os.path.join(
            script_path, "assets/floor_plan_thumbnail.png"
        )

        self.floor_plan_image_width = 8989
        self.floor_plan_image_height = 4432

        self.temp_floor_plan_image_file_path = (
            self.floor_plan_image_file_path + ".tmp.png"
        )
        self.temp_floor_plan_image_thumbnail_file_path = (
            self.floor_plan_image_thumbnail_file_path + ".tmp.png"
        )
コード例 #13
0
ファイル: network.py プロジェクト: BourbonShi/my_learn_dl
 def __init__(self, layers):
     self.connections = Connections()
     self.layers = []
     layer_count = len(layers)
     node_count = 0
     for i in range(layer_count):
         self.layer.append(Layer(i, layers[i]))
     for layer in range(layer_count - 1):
         connections = [
             Connection(upstream_node, downstream_node)
             for upstream_node in self.layers[layer].nodex
             for downstream_node in self.layers[layer + 1].nodes[:-1]
         ]
         for conn in connections:
             self.connections.add_connection(conn)
             conn.downstream_node.append_upstream_connection(conn)
             conn.upstream_node.append_downstream_connection(conn)
コード例 #14
0
def main():
    """ Gathers all data from yaml config file and places it into variables """
    with open('bot_config.yaml') as server_info:
        config = yaml.load(server_info, Loader=yaml.FullLoader)
        server = config['Server'][0]
        channel = config['Channel'][0]
        bot_name = config['Bot_Name'][0]
        port_number = config['Port_Number'][0]
    """ Initializes the connection and joins the channels listed and sets all other variables"""
    irc = Connections(server, channel, bot_name, port_number)
    irc.connect()
    irc.joinchan()
    while 1:
        """Prints all IRC data to console"""  #TODO Make this optional and split out different data to customize what is shown
        ircmsg = irc.irc.recv(2048).decode("UTF-8")
        ircmsg = ircmsg.strip('\n\r')
        print(ircmsg)
        """Looks for user text and splits it up into all the major parts to be used elsewhere"""
        if ircmsg.find("PRIVMSG") != -1:
            name = ircmsg.split('!', 1)[0][1:]
            message = ircmsg.split('PRIVMSG', 1)[1].split(':', 1)[1]
            channel = ircmsg.split("PRIVMSG")[1].split(":")[0].strip()

            #TODO Events needs a major re-work so this will be getting a major change and will be split into a seperate class and file
            """Looks through the Event class to determine if there is an event to trigger"""
            event = Events(name, message, channel, ircmsg, "mech")
            event.event_check()
            if event.event_check() == False:
                pass
            else:
                """Determines if the bot is trying to print to IRC or complete a bot specific command QUIT/JOIN etc."""
                try:
                    irc.sendmsg(event.event_output, channel)
                except (TypeError):
                    if event.event_output == bytes("QUIT \n", "UTF-8"):
                        irc.sendmsg(random.choice(event.quit_message), channel)
                        irc.irc.send(event.event_output)
                        break
                    else:
                        pass
        else:  #TODO Will also need to be set as an optional debug parameter
            """Pings back to IRC to let it know I am still listening"""
            if ircmsg.find("PING :") != -1:
                irc.ping_pong(ircmsg)
コード例 #15
0
def _approximations(df, relations=[]):
    t1 = ut.out('approximating relational with mean, max, median...')
    df = df.copy()

    con_obj = Connections()

    g, sgs = con_obj.find_subgraphs(df, relations, verbose=False)
    approx_dict = {}

    sg_list = []
    for i, sg in enumerate(sgs):
        if sg[3] > 0:  # num edges > 0
            sg_list.extend([(x, i) for x in sg[0]])  # give sg_id

    if len(sg_list) == 0:
        return approx_dict

    sg_df = pd.DataFrame(sg_list, columns=['com_id', 'sg_id'])
    df = df.merge(sg_df, how='left')
    df['sg_id'] = df['sg_id'].fillna(-1).apply(int)

    sg_mean = df.groupby('sg_id')['ind_pred'].mean().reset_index()\
        .rename(columns={'ind_pred': 'sg_mean_pred'})
    sg_median = df.groupby('sg_id')['ind_pred'].median().reset_index()\
        .rename(columns={'ind_pred': 'sg_median_pred'})
    sg_max = df.groupby('sg_id')['ind_pred'].max().reset_index()\
        .rename(columns={'ind_pred': 'sg_max_pred'})
    df = df.merge(sg_mean).merge(sg_median).merge(sg_max)

    filler = lambda x, c: x['ind_pred'] if x['sg_id'] == -1 else x[c]
    for col in ['sg_mean_pred', 'sg_median_pred', 'sg_max_pred']:
        cols = ['ind_pred', col, 'sg_id']
        df[col] = df[cols].apply(filler, axis=1, args=(col,))

    ut.time(t1)

    return df
コード例 #16
0
ファイル: app.py プロジェクト: dushmis/analytics-quarry-web
def setup_context():
    g.conn = Connections(app.config)
コード例 #17
0
ファイル: main.py プロジェクト: user234683/osr
from arguments import Arguments
from connections import Connections
'''
This code runs the JPL Open Source Rover. It accepts a few command line arguments for different functionality
   -t : Testing mode - allows you to test commands to send to the rover emulating a signals from a controller
   -s : Attempts to connect to a Unix socket for controlling the LED screen. The screen.py script must be running
   			previous to this in order to work. It lives at ../led/screen.py
   -c : Controller flag, letting this program know what type of controller you wish to run with
   		b : Bluetooth app (default)
   		x : XBox controller (requires USB reciever)

An example line running this script to run the LED screen and with an Xbox controller
	sudo python main.py -s -c x
'''
args = Arguments()
conn = Connections()
rover = Rover()


def listener():
    '''
	Based on command line args decides which controller and sockets to open
	'''

    if args.socket:
        print "starting LED socket client"
        conn.unixSockConnect()
    elif args.connect == 'x' or args.connect == 'b':
        conn.connect(args.connect)
    else:
        conn.connect('b')
コード例 #18
0
def _spread(df, col='ind_pred', relations=[]):
    """This'll give some post-hoc test-set analysis, when running this,
    keep track of the test sets that improved using relational modeling,
    then average those test set statistics together to compare to the test
    sets that did not improve."""
    t1 = ut.out('computing subgraph statistics...')
    con_obj = Connections()

    gids = [r[2] for r in relations]
    g, sgs = con_obj.find_subgraphs(df, relations, verbose=False)
    spread_dict = {}

    sg_list = []
    for i, sg in enumerate(sgs):
        if sg[3] > 0:  # num edges > 0
            sg_list.extend([(x, i) for x in sg[0]])  # give sg_id

    if len(sg_list) == 0:
        return spread_dict

    sg_df = pd.DataFrame(sg_list, columns=['com_id', 'sg_id'])
    df = df.merge(sg_df, how='left')
    df['sg_id'] = df['sg_id'].fillna(-1).apply(int)

    p, r, ts = precision_recall_curve(df['label'], df[col])
    aupr = average_precision_score(df['label'], df[col])
    mp = 1.0 - aupr

    corrects = []
    step = int(len(ts) / 100) if len(ts) > 100 else 1
    for i in range(0, len(ts), step):
        t = ts[i]
        df['pred'] = np.where(df[col] > t, 1, 0)
        correct = df['pred'] == df['label']
        corrects.append(correct.apply(int))

    total_corrects = [sum(x) for x in zip(*corrects)]
    df['correct'] = total_corrects

    # extract bottom x% data
    df = df.sort_values('correct', ascending=False)
    ndx = len(df) - int(len(df) * mp)
    qfs = df[df['label'] == 1]
    qfo = df[df['label'] == 0]
    qf1, qf2 = df[ndx:], df[:ndx]
    qf1s = qf1[qf1['label'] == 1]  # low performers
    qf1o = qf1[qf1['label'] == 0]  # low performers
    qf2s = qf2[qf2['label'] == 1]  # high performers
    qf2o = qf2[qf2['label'] == 0]  # high performers

    spread_dict['spam_mean'] = round(qfs['ind_pred'].mean(), 4)
    spread_dict['spam_median'] = round(qfs['ind_pred'].median(), 4)
    spread_dict['ham_mean'] = round(qfo['ind_pred'].mean(), 4)
    spread_dict['ham_median'] = round(qfo['ind_pred'].median(), 4)

    for nm, temp_df in [('bot_spam', qf1s), ('bot_ham', qf1o),
                        ('top_spam', qf2s), ('top_ham', qf2o)]:
        wf = temp_df[(temp_df[gids] != -1).any(axis=1)]
        sg_mean = wf.groupby('sg_id')['ind_pred'].mean().reset_index()\
            .rename(columns={'ind_pred': 'sg_mean'})
        sg_std = wf.groupby('sg_id')['ind_pred'].std().reset_index()\
            .rename(columns={'ind_pred': 'sg_std'})
        sg_median = wf.groupby('sg_id')['ind_pred'].median().reset_index()\
            .rename(columns={'ind_pred': 'sg_median'})
        sg_min = wf.groupby('sg_id')['ind_pred'].min().reset_index()\
            .rename(columns={'ind_pred': 'sg_min'})
        sg_max = wf.groupby('sg_id')['ind_pred'].max().reset_index()\
            .rename(columns={'ind_pred': 'sg_max'})
        wf = wf.merge(sg_mean).merge(sg_std).merge(sg_median)\
            .merge(sg_min).merge(sg_max)
        wf['sg_spread'] = wf['sg_max'] - wf['sg_min']

        spread_dict[nm + '_sg_mean'] = round(np.mean(wf['sg_mean']), 4)
        spread_dict[nm + '_sg_std'] = round(np.mean(wf['sg_std']), 4)
        spread_dict[nm + '_sg_median'] = round(np.mean(wf['sg_median']), 4)
        spread_dict[nm + '_sg_min'] = round(np.mean(wf['sg_min']), 4)
        spread_dict[nm + '_sg_max'] = round(np.mean(wf['sg_max']), 4)
        spread_dict[nm + '_sg_spread'] = round(np.mean(wf['sg_spread']), 4)

    ut.time(t1)
    return spread_dict
コード例 #19
0
 def __init__(self, wt):
   Layers.conn = Connections(wt)
コード例 #20
0
def init(sender, signal):
    global conn

    conn = Connections(celery.conf)
    celery_log.info("Initialized lazy loaded connections")
コード例 #21
0
from connections import Connections

__dir__ = os.path.dirname(__file__)
config = yaml.load(open(os.path.join(__dir__, "../default_config.yaml")))
try:
    config.update(yaml.load(open(os.path.join(__dir__, "../config.yaml"))))
except IOError:
    # is ok if we do not have config.yaml
    pass

logging.basicConfig(filename=config['KILLER_LOG_PATH'],
                    level=logging.INFO,
                    format='%(asctime)s pid:%(process)d %(message)s')
logging.info("Started killer process, with limit %s",
             config['QUERY_TIME_LIMIT'])
conn = Connections(config)

cur = conn.replica.cursor()
try:
    cur.execute('SHOW PROCESSLIST')
    queries = cur.fetchall()
    logging.info("Found %s queries running", len(queries))
    to_kill = [
        q for q in queries
        if q[5] > config['QUERY_TIME_LIMIT'] and q[4] != 'Sleep'
    ]
    logging.info("Found %s queries to kill", len(to_kill))
    for q in to_kill:
        try:
            cur.execute('KILL QUERY %s', q[0])
            logging.info("Killed query with thread_id:%s" % q[0])
コード例 #22
0
 def tearDown(self) -> None:
     db = Connections(table_name='provider')
     with db.connect() as conn:
         conn.execute(
              db.table.update().where(db.table.c.id == self._id).values(active=None)
         )