Esempio n. 1
0
 def __init__(self, input_variable=Variable, name=str, alpha = 0.25):
     self.input_variables = input_variable
     self.output_variables = Variable(self.input_variables.shape, name='out', scope=name)
     self.alpha = alpha
     self.momentum  = 0.9
     self.eta = 1e-4
     Operator.__init__(self, name, self.input_variables, self.output_variables)
Esempio n. 2
0
def main():
    firstQueueGroup = [[], [], []]
    secondQueueGroup = [[], []]

    clientGenerator = Generator(UniformDistribution(1, 5), firstQueueGroup)

    operators = [
        Operator(firstQueueGroup[0], secondQueueGroup, UniformDistribution(2, 5)),    
        Operator(firstQueueGroup[1], secondQueueGroup, UniformDistribution(4, 8)),
        Operator(firstQueueGroup[2], secondQueueGroup, UniformDistribution(10, 15))    
    ]

    Attractions = [
        Attraction(secondQueueGroup[0], UniformDistribution(5, 9)),   
        Attraction(secondQueueGroup[1], UniformDistribution(10, 25))   
    ]

    totalVisitors = 300

    tStart = time()
    res = modeling(clientGenerator, operators, Attractions, totalVisitors)

    print('time (secs)', time() - tStart)
    for key in res.keys():
        print(key, res[key])

    print('lost', res['lost'] / totalVisitors)
Esempio n. 3
0
    def __init__(self, phone_number, phone_passwd):
        self.phone_number = phone_number
        self.phone_passwd = phone_passwd

        Operator.__init__(self, phone_number, phone_passwd)
        Operator.get_task_no(self, phone_number=phone_number)

        self.homepage = 'http://www.10010.com'
        self.login_url = 'https://uac.10010.com/portal/homeLogin'
        self.driver = None

        ua = ("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 " +
              "(KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36")
        self.header = {
            "HOST": "iservice.10010.com",
            "Origin": "http://iservice.10010.com",
            "X-Requested-With": "XMLHttpRequest",
            "Referer": r"https://uac.10010.com/portal/homeLogin",
            "Accept": r"application/json, text/javascript, */*; q=0.01",
            "User-Agent": ua,
            "Accept-Encoding": r"deflate",
            "Accept-Language": r"zh-CN,zh;q=0.8",
            "Upgrade-Insecure-Requests": "1",
            "Content-Type": r"application/x-www-form-urlencoded;charset=UTF-8"
        }

        # 2.2 创建带上述头信息的会话
        self.ses = requests.Session()
        self.ses.headers = self.header
Esempio n. 4
0
def plot_time(iterations):
    iteration = []
    time = []
    timer = Timer()
    mean_time = 0
    for i in range(iterations):
        individuals = 10
        first_operation = Operator(lambda x, y: x + y, '+')
        second_operation = Operator(lambda x, y: x * y, '*')
        operations = [first_operation, second_operation]
        values = [25, 7, 8, 100, 4, 2]
        constants = []
        for value in values:
            constants.append(Constant(value))
        depth = 3
        goal = 459
        timer.start()
        build_programs(individuals, operations, constants, depth, goal, 1000)
        value = timer.stop()
        time.append(value)
        mean_time += value
        iteration.append(i + 1)
    mean_time = mean_time / iterations
    plt.figure()
    plt.title("Tiempo Tomado en 1000 Generaciones", fontsize=20)
    plt.xlabel('Iteración')
    plt.ylabel('Tiempo (segundos)')
    plt.scatter(iteration, time, color='blue')
    plt.axhline(y=mean_time, color='r', linestyle='-')
    plt.show()
Esempio n. 5
0
def main():
    client_generator = Generator(EvenDistribution(8, 12))

    first_queue = []
    second_queue = []

    operators = [
        Operator(first_queue, EvenDistribution(15,
                                               25)),  # самый производительный
        Operator(first_queue, EvenDistribution(30, 50)),
        Operator(second_queue,
                 EvenDistribution(20, 60))  # наименее производительный
    ]

    processors = [
        Processor(first_queue, EvenDistribution(15, 15)),  # ровно 15 минут
        Processor(second_queue, EvenDistribution(30, 30))  # ровно 30 минут
    ]

    total_requests = 300

    t_start = time()
    res = modeling(client_generator, operators, processors, total_requests)

    print('time seconds', time() - t_start)
    for key in res.keys():
        print(key, res[key])

    print('lost', res['lost'] / total_requests)
Esempio n. 6
0
def main():
    clientGenerator = Generator(UniformDistribution(8, 12))

    firstQueue = []
    secondQueue = []

    operators = [
        Operator(firstQueue, UniformDistribution(15, 25)),
        Operator(firstQueue, UniformDistribution(30, 50)),
        Operator(secondQueue, UniformDistribution(20, 60))
    ]

    processors = [
        Processor(firstQueue, UniformDistribution(15, 15)),
        Processor(secondQueue, UniformDistribution(30, 30))
    ]

    totalRequests = 3000

    tStart = time()
    res = modeling(clientGenerator, operators, processors, totalRequests)

    print('time (secs)', time() - tStart)
    for key in res.keys():
        print(key, res[key])

    print('lost', res['lost'] / totalRequests)
Esempio n. 7
0
def fitness_vs_population():
    x = []
    y = []
    population = numpy.arange(10, 1010, 10)
    for pop in population:
        individuals = 10
        first_operation = Operator(lambda x, y: x + y, '+')
        second_operation = Operator(lambda x, y: x * y, '*')
        operations = [first_operation, second_operation]
        values = [25, 7, 8, 100, 4, 2]
        constants = []
        for value in values:
            constants.append(Constant(value))
        depth = 3
        goal = 459
        program = Number(individuals, operations, constants, depth, goal)
        program.run(100)
        x.append(pop)
        y.append(program.get_fitness(program.best_individual))
    plt.figure()
    plt.title("Mejor fitness según población inicial", fontsize=20)
    plt.xlabel('Población inicial')
    plt.ylabel('Fitness')
    plt.plot(x, y)
    plt.show()
    def __init__(self, kernel: Callable, lower: float, upper: float, grid_size: int,
                 observations: np.ndarray, sample_size: int, order: int = 1, adjoint: bool = False,
                 quadrature: str = 'rectangle', **kwargs):
        """
        Instance of iterated Tikhonov solver for inverse problem in Poisson noise with integral operator.
        :param kernel: Kernel of the integral operator.
        :type kernel: Callable
        :param lower: Lower end of the interval on which the operator is defined.
        :type lower: float
        :param upper: Upper end of the interval on which the operator is defined.
        :type upper: float
        :param grid_size: Size pf grid used to approximate the operator.
        :type grid_size: int
        :param observations: Observations used for the estimation.
        :type observations: numpy.ndarray
        :param sample_size: Theoretical sample size (n).
        :type sample_size: int
        :param order: Order of the iterated algorithm. Estimator for each regularization parameter is obtained after
        order iterations. Ordinary Tikhonov estimator is obtained for order = 1.
        :type order: int (default: 1)
        :param adjoint: Whether the operator is adjoint (True) or not (False).
        :type adjoint: boolean (default: False)
        :param quadrature: Type of quadrature used to approximate integrals.
        :type quadrature: str (default: recatngle)
        :param kwargs: Possible arguments:
            - tau: Parameter used to rescale the obtained values of estimated noise level (float or int, default: 1).
            - parameter_space_size: Number of possible values of regularization parameter calculated as values between
            10^(-15) and 1 with step dictated by the parameter_space_size (int, default: 100).
             - grid_max_iter: Maximum number of iterations of routine looking for the reasonable starting point for grid
             search. In each iteration, parameter grid is shifted by 1. In case no reasonable starting point has been found,
             RuntimeWarning is raised (int, default: 50).

        """
        Operator.__init__(self, kernel, lower, upper, grid_size, adjoint, quadrature)
        EstimatorDiscretize.__init__(self, kernel, lower, upper, grid_size, observations, sample_size, quadrature)
        assert isinstance(order, int), 'Please specify the order as an integer'
        self.__order: int = order
        self.grid_max_iter: int = kwargs.get('grid_max_iter', 50)
        assert isinstance(self.grid_max_iter, int)
        self.__tau: float = kwargs.get('tau', 1.)
        assert isinstance(self.__tau, (int, float)), 'tau must be a number'
        self.__parameter_space_size: int = kwargs.get('parameter_space_size', 100)
        try:
            assert isinstance(self.__parameter_space_size, int)
        except AssertionError:
            warn('Parameter space size is not an integer, falling back to default value')
            self.__parameter_space_size = 100
        self.__parameter_grid: np.ndarray = np.flip(np.power(10, np.linspace(-15, 0, self.__parameter_space_size)))
        self.initial: cp.ndarray = cp.empty(self.grid_size, dtype=cp.float64)
        self.previous: cp.ndarray = cp.empty(self.grid_size, dtype=cp.float64)
        self.current: cp.ndarray = cp.empty(self.grid_size, dtype=cp.float64)
        self.__solution: cp.ndarray = cp.empty(self.initial.shape, dtype=cp.float64)
        Operator.approximate(self)
        self.__KHK: cp.ndarray = self.__premultiplication(self.KH, self.K)
        self.identity: cp.ndarray = cp.identity(self.grid_size, dtype=cp.float64)
        EstimatorDiscretize.estimate_q(self)
        EstimatorDiscretize.estimate_delta(self)
        self.__grid: np.ndarray = getattr(super(), quadrature + '_grid')()
        self.__define_grid()
Esempio n. 9
0
 def __init__(self, id, name, capacity=1, schedulingRule="FIFO", **kw):
     Operator.__init__(self,
                       id=id,
                       name=name,
                       capacity=capacity,
                       schedulingRule=schedulingRule)
     from Globals import G
     G.OperatorManagedJobsList.append(self)
Esempio n. 10
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("CardBord AI Demo ver0.10")
        self.operator = Operator()

        self.setupUi()

        self.operator.speach.connect(self.speak_ai)

        self.init()
Esempio n. 11
0
    def test(self, cyc, HN, tst, tsExpt, ftest):
        
        tsPerCyc = self.pm.get("tsPerCyc")
        cls = self.pm.get("cls")
        dvol = self.pm.get("dvol")
        tag = self.pm.get("tag")
        rTime = self.pm.get("rTime")
        sepY = self.pm.get("sepY")
        dThres = self.pm.get("dThres")
        isRecordReact = self.pm.get("isRecordReact")
        isDNATube = self.pm.get("isDNATube")
        clsNum = len(cls)
        
        # Prepare test Tubes
#         print("\t\t\t\tPreparing test tubes...")
        tsTubes = list()
        for i in range(clsNum) :
            c = self.testData[i][1][0][0]
            lblPrf = "ts_cyc" + str(cyc)
            if isDNATube :
                tsTubes.extend(self.makeDNATubesFromData(lblPrf, "B", self.testData[i][0], c, tsPerCyc/2, tst, tsExpt))
            else :
                tsTubes.extend(self.makeTubesFromData(lblPrf, "B", self.testData[i][0], c, tsPerCyc/2, tst, tsExpt))
        random.shuffle(tsTubes)
        
        # Run Test
#         print("\t\t\t\tRunning test reaction...")
        testSummary = np.zeros((clsNum,clsNum))
        for i in range(tsPerCyc) :
            print("\t\t\t\t%dth test" % (i+1))
            subHN = [None]*clsNum
            DList = [None]*clsNum
            
            for j in range(clsNum) :
                ts = tsTubes[i]
                subHN[j] = HN[j].copyTube(dvol)
                subHN[j].setLabel("HN" + str(cls[j]) + "_Cycle" + str(cyc+1) + "_test" + str(i+1))
#                 print "\t\t\t\tPour test tube..."
                subHN[j].addTube(ts)
#                 print "\t\t\t\tReacting..."
                Operator.reactionSSA(subHN[j], rTime, tag, isRecordReact)
#                 print "\t\t\t\tElectrophoresis..."
                DList[j] = Operator.separation(subHN[j], sepY)
                
            csf = Classifier()
            if isDNATube :
                score, predict = csf.thresholdClassifyOnDNATube(DList, cls, dThres)
            else :
                score, predict = csf.thresholdClassifyOnTube(DList, cls, dThres)

            testSummary[cls.index(predict)][cls.index(ts.cls)] += 1
            tsTubes[i] = None
            
        # Save Result
        dm.saveTestSummaryLine(ftest, cyc, testSummary)
Esempio n. 12
0
def first_example():
    individuals = 10
    first_operation = Operator(lambda x, y: x + y, '+')
    second_operation = Operator(lambda x, y: x * y, '*')
    operations = [first_operation, second_operation]
    values = [25, 7, 8, 100, 4, 2]
    constants = []
    for value in values:
        constants.append(Constant(value))
    depth = 3
    goal = 459
    show_results(individuals, operations, constants, depth, goal, 2000)
Esempio n. 13
0
 def Operators(self, j):
     o = flatbuffers.number_types.UOffsetTFlags.py_type(
         self._tab.Offset(10))
     if o != 0:
         x = self._tab.Vector(o)
         x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
         x = self._tab.Indirect(x)
         from Operator import Operator
         obj = Operator()
         obj.Init(self._tab.Bytes, x)
         return obj
     return None
Esempio n. 14
0
    def spider(self):

        #个人信息
        personal_info = self.get_personal_info()

        #账单
        bill_info = self.get_bill_info()

        #通话
        call_info = self.get_call_info()

        #短信
        smss_info = self.get_smss_info()

        #存数据到数据库中\
        self.write_log(u'保存用户的信息到数据库,开始' + self.phone_number)
        if len(personal_info) > 0:
            Operator.save_basic(self, self.task_id, self.phone_number, [personal_info])
        if len(bill_info) > 0:
            Operator.save_bill(self, self.task_id, self.phone_number, bill_info)
        if len(call_info) > 0:
            Operator.save_calls(self, self.task_id, self.phone_number, call_info)
        if len(smss_info) > 0:
            Operator.save_sms(self, self.task_id, self.phone_number, smss_info)

        self.write_log(u'保存用户的信息到数据库,完成。 ' + self.phone_number)

        self.exit()
Esempio n. 15
0
 def __init__(self, kernel: Callable, lower: float, upper: float, grid_size: int,
              observations: np.ndarray, sample_size: int, adjoint: bool = False, quadrature: str = 'rectangle',
              **kwargs):
     """
     Instance of Landweber solver for inverse problem in Poisson noise with integral operator.
     :param kernel: Kernel of the integral operator.
     :type kernel: Callable
     :param lower: Lower end of the interval on which the operator is defined.
     :type lower: float
     :param upper: Upper end of the interval on which the operator is defined.
     :type upper: float
     :param grid_size: Size pf grid used to approximate the operator.
     :type grid_size: int
     :param observations: Observations used for the estimation.
     :type observations: numpy.ndarray
     :param sample_size: Theoretical sample size (n).
     :type sample_size: int
     :param adjoint: Whether the operator is adjoint (True) or not (False).
     :type adjoint: boolean (default: False)
     :param quadrature: Type of quadrature used to approximate integrals.
     :type quadrature: str (default: recatngle)
     :param kwargs: Possible arguments:
         - max_iter: The maximum number of iterations of the algorithm (int, default: 1000).
         - tau: Parameter used to rescale the obtained values of estimated noise level (float or int, default: 1).
         - initial: Initial guess for the solution (numpy.ndarray, default: 0).
         - relaxation: Parameter used in the iteration of the algorithm (step size, omega). This approximate square norm
          of an operator is divide by the value of relaxation parameter (float or int, default: 2).
     """
     Operator.__init__(self, kernel, lower, upper, grid_size, adjoint, quadrature)
     EstimatorDiscretize.__init__(self, kernel, lower, upper, grid_size, observations, sample_size, quadrature)
     self.max_iter: int = kwargs.get('max_iter', 100)
     self.__tau: float = kwargs.get('tau', 1.)
     assert isinstance(self.__tau, (int, float)), 'tau must be a number'
     self.initial: cp.ndarray = kwargs.get('initial_guess',
                                           cp.repeat(cp.array([0]), self.grid_size).astype(cp.float64))
     try:
         assert isinstance(self.initial, cp.ndarray)
     except AssertionError:
         warn('Initial guess is not a cupy array, falling back to default value', RuntimeWarning)
         self.initial: cp.ndarray = cp.repeat(cp.array([0]), self.grid_size).astype(cp.float64)
     self.previous: cp.ndarray = cp.empty(self.grid_size, dtype=cp.float64)
     self.current: cp.ndarray = cp.empty(self.grid_size, dtype=cp.float64)
     Operator.approximate(self)
     self.__KHK: cp.ndarray = self.__premultiplication(self.KH, self.K)
     self.__relaxation: float = kwargs.get('relaxation', 0.5)
     assert isinstance(self.__relaxation, (int, float)), 'Relaxation parameter must be a number'
     self.__relaxation = self.__relaxation / (np.max(np.linalg.svd(cp.asnumpy(self.KHK), compute_uv=False, hermitian=True)))
     EstimatorDiscretize.estimate_q(self)
     EstimatorDiscretize.estimate_delta(self)
     self.__grid: np.ndarray = getattr(super(), quadrature + '_grid')()
Esempio n. 16
0
 def __init__(self,
              kernel: Callable,
              lower: Union[float, int],
              upper: Union[float, int],
              grid_size: int,
              observations: np.ndarray,
              sample_size: int,
              adjoint: bool = False,
              quadrature: str = 'rectangle',
              **kwargs):
     """
     Instance of TSVD solver for inverse problem in Poisson noise with integral operator.
     :param kernel: Kernel of the integral operator.
     :type kernel: Callable
     :param lower: Lower end of the interval on which the operator is defined.
     :type lower: float
     :param upper: Upper end of the interval on which the operator is defined.
     :type upper: float
     :param grid_size: Size pf grid used to approximate the operator.
     :type grid_size: int
     :param observations: Observations used for the estimation.
     :type observations: numpy.ndarray
     :param sample_size: Theoretical sample size (n).
     :type sample_size: int
     :param adjoint: Whether the operator is adjoint (True) or not (False).
     :type adjoint: boolean (default: False)
     :param quadrature: Type of quadrature used to approximate integrals.
     :type quadrature: str (default: recatngle)
     :param kwargs: Possible arguments:
         - tau: Parameter used to rescale the obtained values of estimated noise level (float or int, default: 1).
     """
     Operator.__init__(self, kernel, lower, upper, grid_size, adjoint,
                       quadrature)
     EstimatorDiscretize.__init__(self, kernel, lower, upper, grid_size,
                                  observations, sample_size, quadrature)
     self.__tau: Union[float, int] = kwargs.get('tau', 1.)
     assert isinstance(self.__tau, (int, float)), 'tau must be a number'
     self.previous: cp.ndarray = cp.empty(self.grid_size, dtype=cp.float64)
     self.current: cp.ndarray = cp.empty(self.grid_size, dtype=cp.float64)
     Operator.approximate(self)
     self.__KHK: cp.ndarray = self.__premultiplication(self.KH, self.K)
     EstimatorDiscretize.estimate_q(self)
     EstimatorDiscretize.estimate_delta(self)
     self.__U: cp.ndarray = cp.zeros((self.grid_size, self.grid_size))
     self.__V: cp.ndarray = cp.zeros((self.grid_size, self.grid_size))
     self.__D: cp.ndarray = cp.zeros((self.grid_size, ))
     self.__U, self.__D, self.__V = self.decomposition(
         self.KHK, self.grid_size)
     self.__grid: np.ndarray = getattr(super(), quadrature + '_grid')()
Esempio n. 17
0
def second_example():
    individuals = 10
    first_operation = Operator(lambda x, y: x + y, '+')
    second_operation = Operator(lambda x, y: x - y, '-')
    third_operation = Operator(lambda x, y: x / y, '/')
    fourth_operation = Operator(lambda x, y: x * y, '*')
    operations = [
        first_operation, second_operation, third_operation, fourth_operation
    ]
    values = [25, 7, 8, 100, 4, 2]
    constants = []
    for value in values:
        constants.append(Constant(value))
    depth = 4
    goal = 595
    show_results(individuals, operations, constants, depth, goal, 2000)
Esempio n. 18
0
    def check_if_login(self):
        """
        检查是否成功登录(同时也是获取各个页面的中间必要通信环节)
        :return: True for success; False for not.
        """
        self.logger.info(u"验证是否是登录状态...")

        checkin_url = "http://iservice.10010.com/e3/static/check/checklogin?_="
        try:
            res = self.ses.post(checkin_url + Operator.get_timestamp())
        except Exception as e:
            self.logger.error(u"[1001] 无法发送获取登录状态的请求" + str(checkin_url))
            self.logger.error(str(e))
            return False, "0003"

        try:
            result = res.json().get("isLogin")
        except Exception as e:
            self.logger.error(u"[1002] check_login登录状态返回内容异常")
            self.logger.error(str(e))
            return False, "0001"

        if result is None:
            self.logger.error(u"[1002] check_login登录状态返回内容异常")
            return False, "0001"

        if result:
            self.logger.info(u"成功登录联通官网")
            return True, "0000"
        else:
            self.logger.warning(u"登录联通官网失败")
            return False, "0003"
Esempio n. 19
0
def test_separation():

    tube = Tube()
    chemComp = {"a/D": 3, "b/T": 2, "c/B": 1, "d/D": 5}
    tube.chemComp = chemComp
    r = Operator.separation(tube, 0.5)
    print r
Esempio n. 20
0
    def OnInputChanged(self, *args): #args just catches tkinter arguments. I don't need them
        self.operand1 = (self.input_operand1.get(), Base.stringToBase(self.input_base1.get()))
        self.operand2 = (self.input_operand2.get(), Base.stringToBase(self.input_base2.get()))
        operator = Operator.stringToOperator(self.operator.get())

        if self.canCalculate(operator):
            operand1 = convert(self.operand1[0], self.operand1[1], Base.decimal)

            # edge case not operation, operand2 could be invalid
            if operator != Operator.NOT:
                operand2 = convert(self.operand2[0], self.operand2[1], Base.decimal)
            else:
                operand2 = None

            # edge case div by zero
            if operator == Operator.DIV and float(operand2) == 0:
                self.outputError('2', "Can't divide by 0")
                self.outputResults('result', clear=True)
                return

            try:
                self.result = (result(operand1, operand2, operator), Base.decimal)
                self.outputResults('result')
            except Exception as e:
                print("Calculation: ", e)
        else:
            self.outputResults('result', clear=True)
Esempio n. 21
0
 def operatorButtonClicked(self):
     username = self.username.get()
     password = self.password.get()
     if not username:
         messagebox.showwarning("Username input is empty",
                                "Please enter username.")
         return False
     if not password:
         messagebox.showwarning("Password input is empty",
                                "Please enter password")
         return False
     isAnOperatorUsername = self.cursor.execute(
         "SELECT * FROM operatorowner WHERE username = %s", username)
     if not isAnOperatorUsername:
         messagebox.showwarning(
             "Username is not an operator\'s username",
             "The username you entered is not an operator\'s username.")
         return False
     usernameAndPasswordMatch = self.cursor.execute(
         "SELECT * FROM registereduser WHERE (username = %s AND password = %s)",
         (username, password))
     if not usernameAndPasswordMatch:
         messagebox.showwarning(
             "Username and password don\'t match",
             "Sorry, the username and password you entered" +
             " do not match.")
         return False
     self.loginWindow.withdraw()
     operator = Operator(username)
     return True
Esempio n. 22
0
    def compile_expression(self):
        """
        many examples..i,e., x = 4
        """
        # ops get compiled at end in reverse order in which they were added
        ops = []

        while self._not_terminal_token_for('expression'):
            if self._subroutine_call():
                self.compile_subroutine_call()
            elif self._array_expression():
                self.compile_array_expression()
            elif self.tokenizer.current_token.text.isdigit():
                self.vm_writer.write_push(
                    segment='constant',
                    index=self.tokenizer.current_token.text)
            elif self.tokenizer.identifier():
                self.compile_symbol_push()
            elif self.tokenizer.current_token.is_operator(
            ) and not self._part_of_expression_list():
                ops.insert(
                    0,
                    Operator(token=self.tokenizer.current_token.text,
                             category='bi'))
            elif self.tokenizer.current_token.is_unary_operator():
                ops.insert(
                    0,
                    Operator(token=self.tokenizer.current_token.text,
                             category='unary'))
            elif self.tokenizer.string_const():
                self.compile_string_const()
            elif self.tokenizer.boolean():  # boolean case
                self.compile_boolean()
            elif self._starting_token_for('expression'):  # nested expression
                # skip starting (
                self.tokenizer.advance()
                self.compile_expression()
            elif self.tokenizer.null():
                self.vm_writer.write_push(segment='constant', index=0)

            self.tokenizer.advance()

        # compile_ops
        for op in ops:
            self.compile_op(op)
    def __init__(self, input_queue=Queue()):
        self.functions = {
            "EXP": Function(numpy.exp),
            "LOG": Function(numpy.log),
            "SIN": Function(numpy.sin),
            "COS": Function(numpy.cos),
            "SQRT": Function(numpy.sqrt),
        }

        self.operators = {
            "ADD": Operator(numpy.add, 0),
            "MULTIPLY": Operator(numpy.multiply, 1),
            "DIVIDE": Operator(numpy.divide, 1),
            "SUBTRACT": Operator(numpy.subtract, 0),
        }

        self.output_queue = Queue()
        self.input_queue = input_queue
        self.operator_stack = Stack()
Esempio n. 24
0
    def parse(self) -> RecordList:
        record_list = RecordList()

        with open(self.src) as fd:
            for line in fd.readlines():
                line = line.replace('=>', ' ')
                line = line.replace(',', ' ')

                operator, *operand = line.split()
                if operator.startswith("//"):
                    # this is comment line
                    continue

                # remove inline comment
                i = 0
                for i, _ in enumerate(operand):
                    op = operand[i]
                    if op == '//':
                        break
                operand = operand[:i + 1]

                if operator in Operator.NOP_OPERATOR:
                    record_list.append(Record(Operator(operator)))
                elif operator in Operator.UNARY_OPERATOR:
                    record_list.append(
                        Record(Operator(operator), Operand(operand[0])))
                elif operator in Operator.BINARY_OPERATOR:
                    if len(operand) != 2:
                        raise ValueError("invalid operand: {}".format(operand))

                    record_list.append(
                        Record(Operator(operator),
                               operand_one=Operand(operand[0]),
                               operand_three=Operand(operand[1])))
                elif operator in Operator.TRIPLE_OPERATOR:
                    record_list.append(
                        Record(Operator(operator), Operand(operand[0]),
                               Operand(operand[1]), Operand(operand[2])))
                else:
                    raise ValueError("invalid operator: {}".format(operator))

        return record_list
Esempio n. 25
0
class CreateOperatorCommand(CreateContextCommand):
    def __init__(self, id, server, login, password):
        CreateContextCommand.__init__(self)
        self.server = server
        self.login = login
        self.password = password
        self.id = id

    def process(self):
        self.operator = Operator(self.server, self.login, self.password)
        ok, error = self.operator.connect()
        return ok, self.operator if ok else error
Esempio n. 26
0
def process_sample(file_path):
    print file_path
    config=Config()
    load_sucess=config.load_config()
    if load_sucess:
        dis=Dissector()
        parser=Parser()
        extrator=Extractor()
        operator=Operator(config)
        r_generator=Report_Generator()
        sample=Sample(file_path)        
        rlt=dis.extract_file(sample,config.get_output_dir())   
        bin_time_list=list()     
        if rlt:                     
            parser.parse(sample)
            extrator.extract(sample)
            # config.print_info()      
            operator.operate(sample,config)
            r_generator.write_report(sample)  

    return sample        
Esempio n. 27
0
def process_sample(file_path):
    print file_path
    config = Config()
    load_sucess = config.load_config()
    if load_sucess:
        dis = Dissector()
        parser = Parser()
        extrator = Extractor()
        operator = Operator(config)
        r_generator = Report_Generator()
        sample = Sample(file_path)
        rlt = dis.extract_file(sample, config.get_output_dir())
        bin_time_list = list()
        if rlt:
            parser.parse(sample)
            extrator.extract(sample)
            # config.print_info()
            operator.operate(sample, config)
            r_generator.write_report(sample)

    return sample
Esempio n. 28
0
    def compile_expression(self):
        """
        many examples..i,e., x = 4
        """
        # las operaciones se compilan al final en orden inverso al que fueron agregadas
        ops = []

        while self._not_terminal_token_for('expression'):
            if self._subroutine_call():
                self.compile_subroutine_call()
            elif self._array_expression():
                self.compile_array_expression()
            elif self.tokenizer.current_token.text.isdigit():
                self.vm_writer.write_push(
                    segment='constant',
                    index=self.tokenizer.current_token.text
                )
            elif self.tokenizer.identifier():
                self.compile_symbol_push()
            elif self.tokenizer.current_token.is_operator() and not self._part_of_expression_list():
                ops.insert(0, Operator(token=self.tokenizer.current_token.text, category='bi'))
            elif self.tokenizer.current_token.is_unary_operator():
                ops.insert(0, Operator(token=self.tokenizer.current_token.text, category='unary'))
            elif self.tokenizer.string_const():
                self.compile_string_const()
            elif self.tokenizer.boolean():  # caso booleano
                self.compile_boolean()
            elif self._starting_token_for('expression'):  # expresión anidada
                # saltamos el inicial (
                self.tokenizer.advance()
                self.compile_expression()
            elif self.tokenizer.null():
                self.vm_writer.write_push(segment='constant', index=0)

            self.tokenizer.advance()

        for op in ops:
            self.compile_op(op)
Esempio n. 29
0
    def __init__(self, id, name, capacity=1, operatorsList='None', **kw):

        capacity = int(capacity or 1)

        self.id = id
        self.objName = name

        self.type = "OperatorPool"
        # list with the coreObjects IDs that the Operators operate
        self.coreObjectIds = []
        # list with the coreObjects that the Operators operate
        self.coreObjects = []
        # holds the object/Machine that currently handles the operator pool
        self.currentObject = 'None'
        # if operatorsList is of type list and of length 0
        #     then no operators will be created, they may be
        #     populated earlier on by the logic of the Stations
        if operatorsList != 'None' and len(operatorsList) == 0:
            # list of operators that the OperatorPool holds
            self.operators = []
            # the capacity of the OperatorPool in Operators
            self.capacity = capacity
        # check if an operatorsList is 'None'
        elif operatorsList == 'None':
            # list of operators that the OperatorPool holds
            self.operators = []
            # the capacity of the OperatorPool in Operators
            self.capacity = capacity
            # populate the the operators list and initiate the operators
            for index in range(self.capacity):
                id = self.id + '_O_' + str(index)
                name = self.objName + '_Operator_' + str(index)
                self.operators.append(Operator(id, name))
        # if a list of operators is given then update accordingly the self.operators variable
        else:
            assert type(operatorsList) is list, "operatorsList is not a List"
            self.operators = operatorsList
            self.capacity = len(self.operators)
Esempio n. 30
0
 def __init__(self):
     # Definiton of the variables
     self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
     self.path_selected = None
     self.navi = Navigator(self.window)
     self.info = Infor(self.window)
     self.oper = Operator(self.window)
     self.gwydata = GwyData()
     self.img_1 = Imager(self.window,400)
     self.img_2 = Imager(self.window,400)
     self.channel_img_1 = None
     self.channel_img_2 = None
     # Definition of the widget
     self.window.connect("destroy", lambda w: gtk.main_quit())
     self.window.set_title("SPMBrowser")
     # vbox_main
     self.vbox_main = gtk.VBox(False,0)
     # hbox_main
     self.hbox_main = gtk.HBox(False,0)
     self.vbox_2 = gtk.VBox(False,0)
     self.hbox_main.pack_start(self.img_1.vbox_main,1,1,0)
     self.hbox_main.pack_start(self.img_2.vbox_main,1,1,0)
     self.vbox_2.pack_start(self.info.table_info,0,1,0)
     self.vbox_2.pack_end(self.oper.vbox_main,0,1,0)
     self.hbox_main.pack_end(self.vbox_2,0,1,0)
     # pack
     self.vbox_main.pack_start(self.navi.vbox_main,0,1,0)
     self.vbox_main.pack_start(self.hbox_main,0,1,0)
     self.window.add(self.vbox_main)
     self.window.show_all()
     # Signal handling
     self.navi.combobox_files.connect('changed',self.update_all,None)
     self.img_1.combobox_channels.connect('changed',self.record_channels,None)
     self.img_2.combobox_channels.connect('changed',self.record_channels,None)
     #self.info.entry_ratio.connect('changed',self.update_info,None)
     self.window.connect('key_press_event',self._key_press_event)
Esempio n. 31
0
    def get_personal_info(self):
        """
        获取账号基本信息
        :return:
        """
        # 1. 获取个人基本信息
        checkin_url = "http://iservice.10010.com/e3/static/check/checklogin?_="
        try:
            res = self.ses.post(checkin_url + Operator.get_timestamp())
        except Exception as e:
            self.write_log(u"[3002] 无法发送获取登录状态的请求" + str(checkin_url))
            self.write_log(traceback.format_exc())
            return False

        try:
            res_json = res.json().get("userInfo")
        except Exception as e:
            self.write_log(u"[3003] 用户基本信息(userInfo)返回内容异常")
            self.write_log(traceback.format_exc())
            return False

        # 2. 获取余额以及最近更新时间
        try:
            self.ses.get(self.user_info)
            res2 = self.ses.post(self.user_json)
        except Exception as e:
            self.write_log(u"[3002] 无法打开账户信息页面" + str(self.user_json))
            self.write_log(traceback.format_exc())
            return False

        try:
            res2_json = res2.json().get("defBindnumInfo").get("costInfo")
        except Exception as e:
            self.write_log(u"[3003] 账户信息页面(costInfo)返回内容异常")
            self.write_log(traceback.format_exc())
            res2_json = None

        # 3. 整理结果
        open_time = res_json.get("opendate")
        if open_time is None:
            try:
                open_time = res2.json().get("defBindnumInfo").get("mydetailinfo").get("opendate")
            except Exception as e:
                self.write_log(u"[3003] 账户信息页面返回内容异常")
                self.write_log(traceback.format_exc())
                open_time = ""
            else:
                open_time = open_time.replace(u"年", "-").replace(u"月", "-").replace(u"日", "").strip()
        else:
            open_time = open_time[:4] + '-' + open_time[4:6] + '-' + open_time[6:8]

        result = dict()
        result["real_name"] = res_json.get("custName")
        result["id_card"] = res_json.get("certnum")
        result["addr"] = res_json.get("certaddr")
        result["user_source"] = "CHINA_UNICOM"
        result["level"] = res_json.get("vip_level")
        # result["state"] = -1
        result["open_time"] = open_time
        result["package_name"] = res_json.get("packageName")

        if result["level"] is None:
            try:
                res = self.ses.post("https://uac.10010.com/cust/userinfo/userInfo")
                level_json = res.json()
            except Exception as e:
                self.write_log(u"[3002] 无法获取用户VIP等级")
                result["level"] = ""
                self.write_log(traceback.format_exc())
            else:
                result["level"] = level_json.get("vipLevel")

        if result["level"] is None:
            result["level"] = ""

        if res2_json is not None:
            try:
                result["phone_remain"] = int(float(res2_json.get("balance")) * 100)
            except Exception as e:
                self.write_log(u"[3003] 获取的账户余额数值异常: " + str(res2_json.get("balance")))
                self.write_log(traceback.format_exc())
                result["phone_remain"] = None
        else:
            result["phone_remain"] = None
        result["last_modify_time"] = ""

        if result["phone_remain"] is None:
            result["phone_remain"] = ''

        # 获取归属地
        try:
            result["province"], result["city"] = location_scrape(self.phone_number)
        except Exception as e:
            self.write_log(u"[3004] 获取号码归属地的程序出现异常")
            self.write_log(traceback.format_exc())
            result["province"], result["city"] = ["", ""]

        return result
Esempio n. 32
0
class CardBordAIApp(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("CardBord AI Demo ver0.10")
        self.operator = Operator()

        self.setupUi()

        self.operator.speach.connect(self.speak_ai)

        self.init()

    def setupUi(self):
        self.mainlayout = QVBoxLayout(self)

        self.title = QLabel("CardBord Operator", self)
        self.mainlayout.addWidget(self.title)

        self.user_txtarea = QTextEdit(self)
        self.ai_txtarea = QTextEdit(self)

        self.users_edit_title = QLabel("質問に答えてください")
        self.users_edit = QLineEdit("", self)

        self.txtarea_layout = QHBoxLayout()

        self.txtarea_layout.addWidget(self.user_txtarea)
        self.txtarea_layout.addWidget(self.ai_txtarea)

        self.mainlayout.addLayout(self.txtarea_layout)
        self.mainlayout.addWidget(self.users_edit_title)
        self.mainlayout.addWidget(self.users_edit)

        self.send_btn = QPushButton("send", self)
        self.send_btn.setObjectName("send_btn")
        self.mainlayout.addWidget(self.send_btn)

        QMetaObject.connectSlotsByName(self)

    def init(self):
        # Talkエリアの初期化
        self.user_txtarea.clear()
        self.ai_txtarea.clear()
        # オペレータ初期化、初期ワード取得
        self.operator.init()

    @Slot()
    def on_send_btn_clicked(self):
        # UI処理
        user_word = self.users_edit.text()
        if user_word == "":
            return None
        self.users_edit.clear()
        self.user_txtarea.append(user_word)

        # サーバー(エンジン)へユーザワードを送信
        self.operator.send(user_word)

    @Slot()
    def speak_ai(self, word):
        # AIのトークを表示
        # ディレイを使ってテンポを整える
        def wrapper():
            self.ai_txtarea.append(word)

        QTimer.singleShot(TALK_DELAY, wrapper)
Esempio n. 33
0
 def __init__(self, id, name, capacity=1,schedulingRule="FIFO"):
     Operator.__init__(self,id=id,name=name,capacity=capacity,schedulingRule=schedulingRule)
     self.operatorAssignedTo=None
Esempio n. 34
0
 def __init__(self):
     Operator.__init__(self)
     self.symbol = '^'
     self.precedence = 4
     self.associative = 'R'
Esempio n. 35
0
class SPMBrowser():
    def __init__(self):
        # Definiton of the variables
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.path_selected = None
        self.navi = Navigator(self.window)
        self.info = Infor(self.window)
        self.oper = Operator(self.window)
        self.gwydata = GwyData()
        self.img_1 = Imager(self.window,400)
        self.img_2 = Imager(self.window,400)
        self.channel_img_1 = None
        self.channel_img_2 = None
        # Definition of the widget
        self.window.connect("destroy", lambda w: gtk.main_quit())
        self.window.set_title("SPMBrowser")
        # vbox_main
        self.vbox_main = gtk.VBox(False,0)
        # hbox_main
        self.hbox_main = gtk.HBox(False,0)
        self.vbox_2 = gtk.VBox(False,0)
        self.hbox_main.pack_start(self.img_1.vbox_main,1,1,0)
        self.hbox_main.pack_start(self.img_2.vbox_main,1,1,0)
        self.vbox_2.pack_start(self.info.table_info,0,1,0)
        self.vbox_2.pack_end(self.oper.vbox_main,0,1,0)
        self.hbox_main.pack_end(self.vbox_2,0,1,0)
        # pack
        self.vbox_main.pack_start(self.navi.vbox_main,0,1,0)
        self.vbox_main.pack_start(self.hbox_main,0,1,0)
        self.window.add(self.vbox_main)
        self.window.show_all()
        # Signal handling
        self.navi.combobox_files.connect('changed',self.update_all,None)
        self.img_1.combobox_channels.connect('changed',self.record_channels,None)
        self.img_2.combobox_channels.connect('changed',self.record_channels,None)
        #self.info.entry_ratio.connect('changed',self.update_info,None)
        self.window.connect('key_press_event',self._key_press_event)

    def update_all(self,widget,data):
        self.current_data = self.navi.get_full_path()
        if self.current_data:
            self.gwydata.load_data(self.current_data)
            self.info.initialize(widget,self.gwydata.param)
            #print self.gwydata.param['channels']
            self.img_1.initialize(self.gwydata,self.channel_img_1)
            self.img_2.initialize(self.gwydata,self.channel_img_2)
            self.oper.get_current_data(self.gwydata.get_container(),self.gwydata.get_param(),self.navi.get_path2save(),'Z')

    def record_channels(self,widget,data):
        self.gwydata.param['im_1_channel'] = self.img_1.channel_id
        self.gwydata.param['im_2_channel'] = self.img_2.channel_id
        self.channel_img_1 = self.img_1.get_active_channel()
        self.channel_img_2 = self.img_2.get_active_channel()
        self.oper.get_current_data(self.gwydata.get_container(),self.gwydata.get_param(),self.navi.path2save,'Z')
        #print self.navi.path2save

    def update_info(self,widget,data):
        self.info.update()

    def _key_press_event(self,widget,data):
        keyval = data.keyval
        #print keyval
        if keyval == 110:
            active = self.navi.combobox_files.get_active()
            if active >= 0:
                self.navi.go_forward(widget,data)
        if keyval == 98:
            active = self.navi.combobox_files.get_active()
            if active >= 0:
                self.navi.go_backward(widget,data)
Esempio n. 36
0
@app.route("/apps/<appid>.apk")
def apps(appid):
    global config, market, operator

    request = AssetRequest(appid, market.token, config['device'], operator,
                           config['devname'], config['sdklevel'])
    url, market_da = market.get_asset(request.encode())

    generator, size = Util.download_apk_stream(appid, url, market_da)
    return Response(response=generator, headers={'Content-Length': size})


@app.route("/reload")
def reload():
    global config

    config = json.loads(open('config.json', 'rb').read().decode('utf-8'))

    return json.dumps(config)


if __name__ == "__main__":
    reload()

    market = Market(config['email'], config['password'])
    market.login()

    operator = Operator(config['country'], config['operator'])

    app.run(host='0.0.0.0', debug=True, use_reloader=False)
Esempio n. 37
0
    def set_date(self, url, url2, bill_date, keyword):
        """
        设置查询账单的日期(不同类型的信息,传输的内容存在不同)
        :param url: 信息首页
        :param url2:设置查询时间信息首页
        :param bill_date:查询时间
        :param keyword:查询那种信息
                        'call': 通话记录
                        'sms': 短信记录
                        'net': 上网记录
                        'bill': 历史账单
        :return: None: 获取信息失败
                 False: 该月不存在要查询的信息
                 True: 获取信息成功
        """
        set_date_success = None

        current_infos = self.keyword_infos.get(keyword)
        if current_infos is None:
            self.write_log(keyword + u" -- 还不能提供该类信息的查询!")
            self.write_log(u"设置查询日期失败(查询信息类型不支持): " + str(keyword) + "!")
            return set_date_success
        else:
            self.write_log(u"尝试设置查询日期:" + str(current_infos) + "...")

        # 依次进行如下操作:
        # 1. 打开信息首页,并检验是否登录状态
        try:
            self.ses.get(url)
        except Exception as e:
            self.write_log(u"[3002] 无法打开查询网页(设置查询日期): " + str(current_infos) + " : " + url)
            self.write_log(traceback.format_exc())
            return set_date_success

        if not self.check_if_login():
            self.write_log(u"在查询" + str(current_infos) + "掉出登录")
            return set_date_success

        # 2. 根据不同类型的信息,设置不同的post data
        date_list = Operator.get_begin_end_date(bill_date)
        post_data = {
            "querytype": "0001",
            "querycode": "0001",
            "billdate": bill_date.replace("-", "")
        }

        # 3. 传送post data到指定信息页面
        try:
            strtsmp = self.get_timestamp()
            res = self.ses.post(url2.format(strtsmp=strtsmp), data=post_data)
        except Exception as e:
            self.write_log(u"[3002] 无法打开查询网页(设置查询日期): " + str(url2))
            self.write_log(traceback.format_exc())
            return set_date_success

        # 4. 检查是否成功获取指定信息:
        try:
            json_res = res.json()
        except Exception as e:
            self.write_log(u"[3003] 获得的结果不匹配!" + str(current_infos))
            self.write_log(traceback.format_exc())
            return set_date_success

        # 5. 根据查询信息的类别,提取关键词信息
        if keyword == "bill":
            set_date_success = json_res.get("issuccess")
            if set_date_success is True:
                result_json = res.json().get("historyResultList")
                if result_json is None:
                    res_json = res.json().get("result")
                    if res_json is not None:
                        result_json = res_json.get("billinfo")
                        return self.get_bill_by_month_detail(result_json, bill_date)
Esempio n. 38
0
 def __init__(self, id, name, capacity=1,schedulingRule="FIFO",**kw):
     Operator.__init__(self,id=id,name=name,capacity=capacity,schedulingRule=schedulingRule)
     from Globals import G
     G.OperatorManagedJobsList.append(self) 
Esempio n. 39
0
from Operator import Operator
from Model import Model
import pandas as pd
import numpy as np

if __name__ == '__main__':
    '''
    define class:
    Operator: structure and others
    import rawData and every class contains rawData
    '''
    op = Operator()
    rawData = pd.read_csv('Total_Data5.csv', header=0, index_col=0)

    # get russel 3000 information
    russRet, russInfoR, russMDD = op.russel3000()

    startDate = '12/01/2004'
    endDate = '03/01/2005'
    dateList = op.dateList(startDate, endDate, russRet)

    setStockAmount = 10
    optRet = []
    for date in dateList:
        print(date)
        currentYr = date.year
        currentMon = date.month
        # select trading stocks
        selectStocksDic = op.selectStocks(currentMon, currentYr,
                                          setStockAmount, rawData, russRet)
        # calculate expected return/ var/ cov for current date
Esempio n. 40
0
    def run(self, trTubes, cyc, tst, tsExpt):

        cls = self.pm.get("cls")
        dim = self.pm.get("dim")
        conc = self.pm.get("conc")
        vol = self.pm.get("vol")
        dvol = self.pm.get("dvol")
        dThres = self.pm.get("dThres")
        tag = self.pm.get("tag")
        sepY = self.pm.get("sepY")
        rThres = self.pm.get("rThres")
        rTime = self.pm.get("rTime")
        isDNATube = self.pm.get("isDNATube")
        isRecordReact = self.pm.get("isRecordReact")
        clsNum = len(cls)

        dm = DataModule()
        ftrain = dm.makeTrainSummaryFile(tag)
        ftest = dm.makeTestSummaryFile(tag)
        
        HN = [None] * clsNum
        print("\t\tMaking Initial Random Hypernetworks...")
        for i in range(clsNum) :
            if isDNATube :
                HN[i] = Operator.makeRandomLibraryOnDNATube(dim, conc, vol, rThres, "T")
            else :
                HN[i] = Operator.makeRandomLibraryOnTube(dim, conc, vol, rThres)
            HN[i].setLabel("Hypernetworks" + str(cls[i]))
        
        
        print("\t\tStart Learning Cycle...")
        for i in range(cyc) :
            
            start = timer()
            
            summaryCycle = list()
            summaryCycle.append(i+1)
            for j in range(clsNum) :
                if isDNATube :
                    summaryCycle.append(HN[j].getSpcNum("T"))
                    summaryCycle.append(HN[j].getConcSum("T"))
                else :
                    summaryCycle.append(HN[j].getSpcNum())
                    summaryCycle.append(HN[j].getConcSum())
                
            print("\t\t%dth Cycle" % (i+1))
            subHN = [None] * clsNum
            DList = [None] * clsNum
            
            for j in range(clsNum) :
                print("\t\t\tFor Class %d Hypernetwork" % cls[j])
                tr = trTubes[i]
                
                subHN[j] = HN[j].divideTube(dvol)
                subHN[j].setLabel("HN" + str(cls[j]) + "_learningcycle" + str(i+1))
                print "\t\t\tPour training tube..."
                subHN[j].addTube(tr)
                print "\t\t\tReacting..."
                rTimeEnd = Operator.reactionSSA(subHN[j], rTime, tag, isRecordReact)
                summaryCycle.append(rTimeEnd)
                print "\t\t\tElectrophoresis..."
                DList[j] = Operator.separation(subHN[j], sepY)
                
            csf = Classifier()
            if isDNATube :
                score, predict = csf.thresholdClassifyOnDNATube(DList, cls, dThres)
            else :
                score, predict = csf.thresholdClassifyOnTube(DList, cls, dThres)
                
            for j in range(clsNum) :
                summaryCycle.append(score[j])
            summaryCycle.append(predict)
            summaryCycle.append(tr.cls)
            
            print("\t\t\tFeedback...")
            update = [None] * clsNum
            for j in range(clsNum) :
                if isDNATube :
                    DList[j] = Operator.PCR_DNA(DList[j])
                    update[j] = Operator.denaturationOnDNATube(DList[j], "T", dvol)
                else :
                    DList[j] = Operator.PCR(DList[j])
                    update[j] = Operator.denaturationOnTube(DList[j], "T", dvol)
                
             
            if predict == tr.cls :
                for j in range(clsNum) :
                    if cls[j] == predict :
                        Operator.amplification(update[j], 8) #TODO: Tune multiply number
                        HN[j].addTube(update[j]) 
                    else :
                        Operator.amplification(update[j], 1)
                        HN[j].addTube(update[j])
            else :
                for j in range(clsNum) :
                    if cls[j] == predict :
                        Operator.amplification(update[j], 0)
                        HN[j].addTube(update[j])
                    else :
                        Operator.amplification(update[j], 1)
                        HN[j].addTube(update[j])
            
            # Test with test data
            # don't update Hypernetwork
            print("\t\t\tTesting...")
            self.test(i, HN, tst, tsExpt, ftest)
            
            trTubes[i] = None   # Discard used tube
            end = timer()
            dt = end-start
            print("\t\t\ttime elapsed %f s" % dt)
            summaryCycle.append(dt)
            
            dm.saveTrainSummaryLine(ftrain, summaryCycle)
            
        ftrain.close()
        ftest.close()
Esempio n. 41
0
 def __init__(self, regex, *args):
     """
     Constructor.
     """
     Operator.__init__(self, *args)
     self.regex = re.compile(regex)
def main():
    print(
        "\n\tGooglePlay Downloader - Directly download apks from GooglePlay to your PC.\n"
        + "\tCopyleft Simone Margaritelli <*****@*****.**>\n" +
        "\thttp://www.evilsocket.net\n\n")

    defaults = {
        'email': None,
        'password': None,
        'package': None,
        'country': None,
        'operator': None,
        'device': None,
        'sdklevel': 19,
        'devname': 'passion'
    }

    usage = """usage: %prog [options]

EXAMPLE:
    %prog --email [email protected] --password your-password --name com.arttech.xbugsfree --country "Italy" --operator "3" --device your-device-id
"""
    parser = ExtendedOptionParser(defaults=defaults, usage=usage)

    parser.add_option_with_default("-e",
                                   "--email",
                                   action="store",
                                   dest="email",
                                   help="Your android account email.")
    parser.add_option_with_default("-p",
                                   "--password",
                                   action="store",
                                   dest="password",
                                   help="Your android account password.")
    parser.add_option_with_default(
        "-n",
        "--name",
        action="store",
        dest="package",
        help="Package identifier ( com.something.name ).")
    parser.add_option_with_default("-c",
                                   "--country",
                                   action="store",
                                   dest="country",
                                   help="Your country.")
    parser.add_option_with_default("-o",
                                   "--operator",
                                   action="store",
                                   dest="operator",
                                   help="Your phone operator.")
    parser.add_option_with_default(
        "-d",
        "--device",
        action="store",
        dest="device",
        help=
        "Your device ID ( can be obtained with this app https://play.google.com/store/apps/details?id=com.redphx.deviceid ) ."
    )
    parser.add_option_with_default(
        "-s",
        "--sdklevel",
        action="store",
        type="int",
        dest="sdklevel",
        help="Android SDK API level (default is 19 like Android 4.4).")
    parser.add_option_with_default(
        "-m",
        "--devname",
        action="store",
        dest="devname",
        help=
        "Device name (default 'passion' like HTC Passion aka Google Nexus One."
    )
    parser.add_option(
        "-f",
        "--config",
        action="store",
        dest="config",
        default=None,
        help="Load additional settings from the specified config file.")

    (o, args) = parser.parse_args()

    option_pool = {}

    for key in defaults:
        option_pool[key] = getattr(o, key)

    if o.config is not None:
        config = json.loads(open(o.config, 'rb').read().decode('utf-8'))
        for key in config:
            if key not in option_pool or option_pool[key] is None:
                # in Python 2.x, json results are unicode
                option_pool[key] = str(config[key])

    if option_pool['email'] is None:
        print("No email specified.")

    elif option_pool['password'] is None:
        print("No password specified.")

    elif option_pool['package'] is None:
        print("No package specified.")

    elif option_pool['country'] is None or option_pool[
            'country'] not in Operator.OPERATORS:
        print("Empty or invalid country specified, choose from : \n\n" +
              ", ".join(Operator.OPERATORS.keys()))

    elif option_pool['operator'] is None or option_pool[
            'operator'] not in Operator.OPERATORS[option_pool['country']]:
        print("Empty or invalid operator specified, choose from : \n\n" +
              ", ".join(Operator.OPERATORS[option_pool['country']].keys()))

    elif option_pool['device'] is None:
        print("No device id specified.")

    elif option_pool['sdklevel'] < 2:
        print("The SDK API level cannot be less than 2.")

    else:
        print("@ Logging in ...")

        market = Market(option_pool['email'], option_pool['password'])
        market.login()

        print("@ Requesting package ...")

        operator = Operator(option_pool['country'], option_pool['operator'])

        request = AssetRequest(option_pool['package'], market.token,
                               option_pool['device'], operator,
                               option_pool['devname'], option_pool['sdklevel'])
        (url, market_da) = market.get_asset(request.encode())

        print("@ Downloading...\n")

        Util.download_apk(option_pool['package'], url, market_da)
Esempio n. 43
0
def main(a, queue):
    try:

        import multiprocessing
        import threading
        from Webserver import WebSocketHandler
        from Webserver import MainHandler
        from Participant import Participant
        from Bulletin import Bulletin
        from Operator import Operator
        from Service import Service
        from Manufacturer import Manufacturer
        import Pump
        import time
        import json
        import datetime
        import RPi.GPIO as GPIO
        from PIL import Image
        import pygame
        from multiprocessing import Process, Queue
        import signal
        from random import randint
        import RFID
        GPIO.setmode(GPIO.BOARD)

        # CONSTANTS
        PIMP_GPIO = 13 #gpio 27
        OUT_MANUFACTURER = 11 #gpio 17
        OUT_SERVICE = 33 #gpio 13
        ALARM_MANUFACTURER = 16 # gpio 23
        ALARM_OPERATOR = 7 #gpio 4
        ALARM_SERVICE = 38 #gpio 20
        REPAIR_ASSET_GPIO = 40 # gpio 21
        BREAK_ASSET_MANUALY_GPIO = 18 #gpio 24
        SERVICE_BULLETIN_MANUFACTURER = 31 #gpio 6v
        SERVICE_BULLETIN_MANUFACTURER_MEASURE = 35 #gpio 19
        SERVICE_BULLETIN_OPERATOR = 12 #gpio 18
        SERVICE_BULLETIN_OPERATOR_MEASURRE = 15 #gpio 22
        GPIO_to_repair_for_demo=40 # gpio 21

        # CATALOG OF RFID CHIPS' IDs THAT ARE ASSIGNED TO THE ASSETS IN THE FRONEND
        CATALOG = {
            215: {'id': 215, 'repairGPIO': REPAIR_ASSET_GPIO},
            216: {'id': 215, 'repairGPIO': REPAIR_ASSET_GPIO},
            98: {'id': 215, 'repairGPIO': REPAIR_ASSET_GPIO},
            209: {'id': 209, 'repairGPIO': REPAIR_ASSET_GPIO},
            133: {'id': 133, 'repairGPIO': REPAIR_ASSET_GPIO}
        }
        GPIO.setup(GPIO_to_repair_for_demo, GPIO.IN)
        # CREATING PARTICIPANTS OBJECTS
        Manufacturer = Manufacturer(OUT_MANUFACTURER, service_bulletin_out=SERVICE_BULLETIN_MANUFACTURER,
                                    service_bullete_measure=SERVICE_BULLETIN_MANUFACTURER_MEASURE,
                                    alarm_out=ALARM_MANUFACTURER, bulletin=Bulletin(), catalog=CATALOG)
        Service = Service(OUT_SERVICE, alarm_out=ALARM_SERVICE)
        Operator = Operator(service_bulletin_out=SERVICE_BULLETIN_OPERATOR,
                            service_bullete_measure=SERVICE_BULLETIN_OPERATOR_MEASURRE, alarm_out=ALARM_OPERATOR,
                            pimp_gpio=PIMP_GPIO)

        # SETTING ALL OUTPUTS TO LOW
        GPIO.output(Operator.Service_Bulletin_GPIO_out, GPIO.LOW)
        GPIO.output(Manufacturer.Service_Bulletin_GPIO_out, GPIO.LOW)
        GPIO.output(Manufacturer.ALARM_out, GPIO.LOW)
        GPIO.output(Operator.ALARM_out, GPIO.LOW)
        GPIO.output(Service.ALARM_out, GPIO.LOW)

        global ASSET_INSTALLED
        ASSET_INSTALLED = True
        #variable for the emergency handling, if the pump is not discovered
        #global EMERGENCY


        ############################

        ##SERVICE CAR HANDLING HELP-VARIABLES##
        #informed_to_remove_the_service_car = False

        ##################################

        GPIO.setup(BREAK_ASSET_MANUALY_GPIO, GPIO.IN)
        get_alife(Manufacturer.GPIO_out, Service.GPIO_out, Operator.Service_Bulletin_GPIO_out, BREAK_ASSET_MANUALY_GPIO)
        Participant.update_event(0)
        GPIO.output(Operator.Service_Bulletin_GPIO_out, GPIO.HIGH)
        Operator.buy_asset(Manufacturer, queue, BREAK_ASSET_MANUALY_GPIO, Service, GPIO_to_repair_for_demo)

        while queue.empty():

            # CHECKING IF THE ASSET IS ON THE RFID READER
            if not __builtin__.EMERGENCY:
               Operator.check_asset()
            #for the emergency case
            if __builtin__.EMERGENCY and not __builtin__.operator_connected:
                Participant.update_event(15)

            # IF NO ASSET ON THE RFID READER00
            if not Operator.Has_asset and ASSET_INSTALLED:
                print "No Asset"
                if not Operator.User_informed_about_recent_update:
                    Manufacturer.Bulletin.Agreement_loaded_on_bulletin_by_the_manufacturer = False
                Manufacturer.bulletin_stop_blinking()
                GPIO.output(SERVICE_BULLETIN_MANUFACTURER, GPIO.LOW)
                Manufacturer.Next_asset_update = 0
                GPIO.output(Manufacturer.GPIO_out, GPIO.LOW)
                GPIO.output(Service.GPIO_out, GPIO.LOW)
                # ASSET_INSTALLED=False
                #Operator.Asset.Next_Pimp = 0
                Operator.Asset.Next_Break = 0
                GPIO.output(Manufacturer.GPIO_out, GPIO.HIGH)
                Participant.update_event(1)
                Operator.buy_asset(Manufacturer, queue, BREAK_ASSET_MANUALY_GPIO, Service, GPIO_to_repair_for_demo)

             ##BULLETIN HANDLING###
             #Manufacturer.Bulletin.Agreement_loaded_on_bulletin_by_the_manufacturer=True when the bulletin has been activated by the manufacturer (first blinking after start)
             #Manufacturer.Bulletin.Activated_for_the_communication=True when the bulletin is installed on the operator's side for the first time
            if Operator.Has_asset and ASSET_INSTALLED and not Operator.Asset.Broken:
                #Next_asset_update is 0 only after the start of the demo
                if not Manufacturer.Next_asset_update == 0:
                    #one time bulletin activation at the manufacturer's site for the furthere communication
                    if datetime.datetime.now() > Manufacturer.Next_asset_update and not Manufacturer.Bulletin.Agreement_loaded_on_bulletin_by_the_manufacturer and __builtin__.operator_connected:
                        GPIO.output(Manufacturer.GPIO_out, GPIO.HIGH)
                        if GPIO.input(Manufacturer.Service_Bulletin_GPIO_Measure) == 0:
                            Participant.update_event(9)
                            print "setting blletin true"
                            Manufacturer.Bulletin.Agreement_loaded_on_bulletin_by_the_manufacturer = True
                            Manufacturer.Bulletin_at_manufacturers_campus = True
                            Manufacturer.bulletin_start_blinking(queue)
                        else:
                            #inform user to put the service bulletin to the manufacturer's site first to load the agreements
                            Participant.update_event(14)

                else:
                    #first update over the service bulletin after the demo has started
                    Manufacturer.set_next_asset_update_time(22)

                #returning the activated bulletin to the manufacturer's site only causes the bulletin to blink signaling that it should be brought back to the operator's
                #if Manufacturer.Bulletin.Agreement_loaded_on_bulletin_by_the_manufacturer and GPIO.input(Manufacturer.Service_Bulletin_GPIO_Measure) == 0 and not Manufacturer.Bulletin_at_manufacturers_campus:
                 #   Manufacturer.bulletin_start_blinking(queue)
                  #  Manufacturer.Bulletin_at_manufacturers_campus = True
                    #Stoping blinking of the blue lamp at operator's site
                   # Operator.bulletin_stop_blinking()
                if Manufacturer.Bulletin.Agreement_loaded_on_bulletin_by_the_manufacturer and GPIO.input(Manufacturer.Service_Bulletin_GPIO_Measure) == 0 and __builtin__.operator_connected:
                    if not Manufacturer.Blinker_queue_bulletin.empty() or Manufacturer.Blinker_queue_bulletin==None:
                        Manufacturer.bulletin_start_blinking(queue)
                        Manufacturer.Bulletin_at_manufacturers_campus = True
                        if not Operator.Blinker_queue_bulletin==None and Operator.Blinker_queue_bulletin.empty:
                            Operator.bulletin_stop_blinking()
                            GPIO.output(SERVICE_BULLETIN_OPERATOR, GPIO.LOW)

                #The moment the bulleting is plugged of the manufacturer's site
                if Manufacturer.Bulletin.Agreement_loaded_on_bulletin_by_the_manufacturer  and GPIO.input(Manufacturer.Service_Bulletin_GPIO_Measure) == 1 and Manufacturer.Bulletin_at_manufacturers_campus and __builtin__.operator_connected:
                    Manufacturer.bulletin_stop_blinking()
                    GPIO.output(SERVICE_BULLETIN_MANUFACTURER, GPIO.LOW)
                    GPIO.output(Manufacturer.GPIO_out, GPIO.LOW)
                    Manufacturer.Bulletin_at_manufacturers_campus = False
                    #start blinking operator
                    Operator.bulletin_start_blinking(queue)

                if not Manufacturer.Next_asset_update == 0:
                    if Manufacturer.Bulletin.Agreement_loaded_on_bulletin_by_the_manufacturer and GPIO.input(
                            Manufacturer.Service_Bulletin_GPIO_Measure) == 1 and GPIO.input(Operator.Service_Bulletin_GPIO_Measure)==0 and not Manufacturer.Bulletin_at_manufacturers_campus and __builtin__.operator_connected:
                      Manufacturer.Bulletin.Activated_for_the_communication=True
                      if Operator.Blinker_queue_bulletin.empty() and not Operator.Blinker_queue_bulletin is None:
                        #Stoping blinking of the blue lamp at operator's site
                        Operator.bulletin_stop_blinking()
                        GPIO.output(SERVICE_BULLETIN_OPERATOR, GPIO.LOW)
                      #when the service bulletin is intalled on the operator's site the updates are intalled periodically
                      if datetime.datetime.now() > Manufacturer.Next_asset_update:
                                print "Informing"
                                if not Operator.User_informed_about_recent_update:
                                    # Informing user about the service bulletin functionality only once at the beggining of the demo
                                    Participant.update_event(4)
                                    Operator.User_informed_about_recent_update = True
                                    # install bulletin first time
                                    Operator.bulletin_stop_blinking()
                                    GPIO.output(Manufacturer.GPIO_out, GPIO.HIGH)
                                    GPIO.output(Operator.Service_Bulletin_GPIO_out, GPIO.HIGH)
                                    time.sleep(4)
                                    GPIO.output(Manufacturer.GPIO_out, GPIO.LOW)
                                    GPIO.output(Operator.Service_Bulletin_GPIO_out, GPIO.LOW)
                                    Manufacturer.set_next_asset_update_time()
                                    #Operator.install_bulletin(Manufacturer)
                                    #Operator.Asset.set_next_break()
                                else:
                                    Manufacturer.inform_operator_about_Update(Operator)

            ##END BULLETIN HANDLING###


            # ASSET BREAK
              #MANUAL BREAK
                # can be issued by the presenter any time after the serice bulletin is installed by pressing the dedicated button
            if not Operator.Asset.Broken and __builtin__.operator_connected:
              #print Operator.Asset.broken_asset_security
              if GPIO.input(BREAK_ASSET_MANUALY_GPIO) == 0:
                     Operator.Asset.broken_asset_security = Operator.Asset.broken_asset_security + 1
              if GPIO.input(BREAK_ASSET_MANUALY_GPIO) == 1:
                     Operator.Asset.broken_asset_security = 0
              if Operator.Asset.broken_asset_security > 3:
                    Operator.Asset.broken_asset_security = 0
                    Operator.Asset_is_working = False
            #RANDOM BREAK - happens once when the power pack and pump are installed, bulletin is activated
            if Operator.Asset.Pimped and Operator.Has_asset and ASSET_INSTALLED and not Operator.Asset.Broken and Manufacturer.Bulletin.Activated_for_the_communication and __builtin__.operator_connected:
                # can happen only after the standard scenario is completed - after the booting part is installed
                if Operator.Asset.First_time_random_break:
                 if Operator.Asset.Next_Break == 0:
                    Operator.Asset.set_next_break()
                 if not Operator.Asset.Next_Break == 0:
                    if datetime.datetime.now() > Operator.Asset.Next_Break and Operator.Asset_is_working and not Operator.Asset.Broken and Operator.Has_asset:
                        print "not working"
                        Operator.Asset.First_time_random_break=False
                        Operator.Asset_is_working = False

            if not Operator.Asset_is_working and not Operator.Asset.Broken and __builtin__.operator_connected:
                    Participant.handle_break(Service, Manufacturer, Operator, queue)
                    # END ASSET BREAK

            ##HANDLING THE SERVICE CAR AND REPAIRING THE ASSET#

            Participant.handle_reparing(Operator, Service, Manufacturer,GPIO_to_repair_for_demo)
            ### END HANDLING THE SERVICE CAR AND REPAIRING THE ASSET##

            ####HANDLING ASSET BOOSTING
            if ASSET_INSTALLED and not Operator.Asset.Broken and Operator.Has_asset and __builtin__.operator_connected:
                print Operator.Asset.pimping
                if GPIO.input(Operator.Pimp_GPIO) == 0 and Operator.Asset.pimping < 5:
                    Operator.Asset.pimping += 1
                if GPIO.input(Operator.Pimp_GPIO) == 1 and Operator.Asset.pimping > 0:
                    Operator.Asset.pimping -= 1

                # remind to pimp the asset
                if not Manufacturer.Bulletin_at_manufacturers_campus and GPIO.input(
                        Operator.Service_Bulletin_GPIO_Measure) == 0 and not Operator.Asset.Pimped and Manufacturer.Bulletin.Activated_for_the_communication and Manufacturer.Bulletin.Agreement_loaded_on_bulletin_by_the_manufacturer:
                    if Operator.Asset.Next_Pimp == 0 and Manufacturer.Bulletin.Activated_for_the_communication:
                        # FIRST REMINDER
                        print "setting next pimp"
                        print str(Manufacturer.Bulletin.Activated_for_the_communication)
                        Operator.Asset.set_next_pimp_reminder(seconds_=8)
                    else:
                        if datetime.datetime.now() > Operator.Asset.Next_Pimp:
                            # REMINDER EVENT
                            print ("updating event 10")
                            Participant.update_event(10)
                            GPIO.output(Service.GPIO_out, GPIO.HIGH)
                            Operator.Asset.set_next_pimp_reminder()

                ##BOOSTING THE ASSET
                # if pimping>4 and not Operator.Asset.Pimped and not INFORMED_BULLETIN:
                if Operator.Asset.pimping == 5 and not Operator.Asset.Pimped:
                    Operator.pimp_the_pump()
                    GPIO.output(Operator.Service_Bulletin_GPIO_out, GPIO.HIGH)
                    GPIO.output(Manufacturer.GPIO_out, GPIO.HIGH)
                    GPIO.output(Service.GPIO_out, GPIO.HIGH)
                    time.sleep(10)
                    GPIO.output(Operator.Service_Bulletin_GPIO_out, GPIO.LOW)
                    GPIO.output(Manufacturer.GPIO_out, GPIO.LOW)
                    GPIO.output(Service.GPIO_out, GPIO.LOW)

                if Operator.Asset.pimping ==0 and Operator.Asset.Pimped and not Operator.Asset.Broken and Operator.Has_asset:
                    Operator.unpimp_the_pump(Service)
                    Operator.Asset.Next_Break = 0
                    Operator.Asset.set_next_pimp_reminder()

                    ##END BOOSTING THE ASSET
        print "stoped"

    except KeyboardInterrupt:
        # here you put any code you want to run before the program
        # exits when pressing CTRL+C
        GPIO.cleanup()
        http_server.stop()
Esempio n. 44
0
    def get_smss_by_month_detail(self, check_url, url, bill_date):
        self.write_log(u"开始请求短信记录, 查询月份: " + str(bill_date))
        self.write_log(u"尝试设置查询日期:短信记录...")

        smss_list = []
        # 依次进行如下操作:
        # 1. 打开信息首页,并检验是否登录状态
        try:
            self.ses.get(check_url)
        except Exception as e:
            self.write_log(u"[3002] 无法打开查询网页(设置查询日期): " + url)
            self.write_log(traceback.format_exc())

        if not self.check_if_login():
            self.write_log(u"在查询 短信记录 掉出登录")

        # 2. 根据不同类型的信息,设置不同的post data
        date_list = Operator.get_begin_end_date(bill_date)

        page_no = 1
        post_data = {
            "pageNo": "1",
            "pageSize": "20",
            "begindate": date_list[0].replace("-", ""),
            "enddate": date_list[1].replace("-", "")
        }


        try:
            strtsmp = self.get_timestamp()
            res = self.post(url.format(strtsmp=strtsmp), post_data=post_data)
            smss_list.extend(self.get_smss_by_page_detail(res.json()))
            self.write_log(u"查询数据" + str(bill_date) + "月, 查询第1页...")
        except Exception as e:
            self.write_log(u"[3002] 无法打开查询网页(设置查询日期): " + str(url))
            self.write_log(traceback.format_exc())

        # 4. 检查是否成功获取指定信息:
        try:
            json_res = res.json()
            page_map = json_res.get('pageMap')
            if page_map != None:
                total_pages = page_map.get('totalPages')
                page_no = int(page_map.get('pageNo'))

                for page in range(2, total_pages):
                    try:
                        post_data['pageNo'] = str(page)
                        strtsmp = self.get_timestamp()
                        res = self.post(url.format(strtsmp=strtsmp), post_data=post_data)
                        smss_list.extend(self.get_smss_by_page_detail(res.json()))
                        self.write_log(u"查询数据" + str(bill_date) + "月, 查询第" + str(page) + "页..., 总数据页数: " + str(total_pages))
                    except Exception as e:
                        self.write_log(u"[3002] 无法打开查询网页(设置查询日期): " + str(url))
                        self.write_log(
                            u"查询数据失败, " + str(bill_date) + "月, 查询第" + str(page) + "页..., 总数据页数: " + str(total_pages))
                        self.write_log(traceback.format_exc())

            self.write_log(u"请求短信记录成功, 查询月份: " + str(bill_date))
        except Exception as e:
            self.write_log(u"[3003] 获得的结果不匹配!短信记录 ")
            self.write_log(traceback.format_exc())

        return smss_list
Esempio n. 45
0
 def __init__(self, id, name, capacity=1,**kw):
     Operator.__init__(self,id=id, name=name, capacity=capacity)
     self.type="Repairman"
     from Globals import G
     G.RepairmanList.append(self) 
Esempio n. 46
0
 def __init__(self, left, right):
     """
     Constructor.
     """
     Operator.__init__(self, left, right)
Esempio n. 47
0
 def __init__(self):
     Operator.__init__(self)
     self.symbol = '/'
     self.precedence = 2
     self.associative = 'L'
Esempio n. 48
0
 def process(self):
     self.operator = Operator(self.server, self.login, self.password)
     ok, error = self.operator.connect()
     return ok, self.operator if ok else error