Exemplo n.º 1
0
def math(arith_str):
    #替换空格、--、++、-+、+-、/+、*+为去空格、+、+、-、-、/、*,还有去掉行首的 + 号
    arith_str = equl_tihuan(arith_str)
    # 如果发现括号,则先算括号里面的
    if re.findall('[()]+', arith_str):
       arith_sub = re.findall('[(][^()]+[)]', arith_str)  #取所有最内部括号
       n = 0
       for i in arith_sub:
          # 取括号内的表达式
          j = re.search('[^()]+',i).group()
          # 算括号内的值
          i = calculate(j)
          # 将原来的括号替换为算出来的值
          arith_str = arith_str.replace(arith_sub[n], i, 1)
          n = n + 1
       # print("去最外层括号:", arith_str)
    # 如果没有括号,则再算加减乘除
    elif re.findall('[+*/-]+', arith_str):
        # print(arith_str)
        if re.search('e-',arith_str) == None:
            arith_str = calculate(arith_str)
        return arith_str
    # 如果就一个字符串,不包含括号和加减乘除则,直接返回
    else:
        return arith_str
    # arith_str = equl_tihuan(arith_str)
    # print("asadsad")
    return math(arith_str)
def test_whitespaces():
    assert calculate('5 + 5') == 10
    assert calculate('5+5 -3') == 7
    assert calculate('5     +  9') == 14

    assert calculate('5\t+6') == 11
    assert calculate('8\n+5+  7') == 20
Exemplo n.º 3
0
def main():
    args = parse_args()
    csv_filename = args.data
    result_csv = args.outfile
    data_dict = load_data(csv_filename)
    calculate(data_dict)
    write_csv(data_dict, result_csv)
    write_sql(result_csv, args=args)
Exemplo n.º 4
0
def train(model, sess, saver, epochs, batch_size, data_train, id2word, id2tag):
    """
  模型训练
  :param model: model的一些信息
  :param sess: TensorFlow会话内容
  :param saver: TensorFlow保存器
  :param epochs: 所有训练数据forwward+bachword后更新参数的次数
  :param batch_size: 一次iteration选取的样本数量
  :param data_train: 输入样本
  :param id2word:    给每个word映射了一个id, 通过id 查找word
  :param id2tag:     给每个word映射了一个tag, 通过id 查找tag
  :return:
  """
    batch_num = int(data_train.y.shape[0] / batch_size)  # 计算一次iteration需要多少轮
    for epoch in range(epochs):
        for batch in range(batch_num):
            x_batch, y_batch = data_train.next_batch(batch_size)
            feed_dict = {model.input_data: x_batch, model.labels: y_batch}
            predict_train, _ = sess.run(
                [model.viterbi_sequence, model.train_op], feed_dict=feed_dict)
            acc = 0  # 累计
            if batch % 100 == 0:
                for i, j in product(range(len(y_batch)),
                                    range(len(y_batch[0]))):
                    if y_batch[i][j] == predict_train[i][j]:
                        acc += 1
                recall_result = acc * 1.0 / (len(y_batch) * len(y_batch[0]))
                print("召回率:", recall_result)
        # 保存结果
        save_path_name = os.path.join(os.getcwd(), "model",
                                      "model" + str(epoch) + ".ckpt")
        print(save_path_name)
        if epoch % 5 == 0:
            saver.save(sess, save_path_name)
            print("in epoch %d" % epoch, "model is saved")
            entity_result = []  # 应该是实体结果
            entity_all = []  # 和上面一样, 功能未知
            for batch in range(batch_num):
                x_batch, y_batch = data_train.next_batch(batch_size)
                feed_dict = {model.input_data: x_batch, model.labels: y_batch}
                predict_train = sess.run([model.viterbi_sequence], feed_dict)
                predict_train = predict_train[0]  # 未知
                entity_result = calculate(x_batch, predict_train, id2word,
                                          id2tag, entity_result)
                entity_all = calculate(x_batch, y_train, id2word, id2tag,
                                       entity_all)
            and_set = set(entity_result) & set(entity_all)
            if len(and_set) > 0:
                precision_ratio = len(and_set) / len(entity_result)
                recall_ratio = len(and_set) / len(entity_all)
                f_value = 2 * precision_ratio * recall_ratio / (
                    precision_ratio + recall_ratio)
                print("precision_ratio is :", precision_ratio)
                print("recall_ratio is : ", recall_ratio)
                print("f value is :", f_value)
            else:
                print("something wrong! no and set!!")
Exemplo n.º 5
0
def calc_everything(tup):
    """"Designed to be run in other tread. Calculates everything"""
    global progress
    filename = tup[0]
    q = tup[1]
    filename = filename.rstrip('.png')
    _time = time.time()
    extracted = c.extract(filename, IMAGES_FOLDER, stepDEGR)
    #print('Extract time: ', time.time()-_time, '  File:  ', filename)
    if extracted is not None:
        _time = time.time()
        output = []
        if filename.startswith('3'):
            #pass
            for point in extracted:
                output.append(c.calculateTOP(point[0], point[1], point[2]))
        else:
            for point in extracted:
                output.append(c.calculate(point[0], point[1], point[2]))
        #print('Calculate time: ', time.time()-_time)

        q.put(output)
        mutex.lock()
        progress = progress + 1
        print('DONE!!!', filename, "progress: ", progress, '\n')
        mutex.unlock()
    else:
        progress = progress + 1
        print("Corrupted PNG file: ", filename, "progress: ", progress, '\n')
Exemplo n.º 6
0
def pipeline(args):
    pd.options.mode.chained_assignment = None

    # Sanity check args
    if not parent_dir_exists(args.out):
        raise ValueError('--out flag points to an invalid path.')

    print('Preparing files for analysis...')
    gwas_snps, bed, N1, N2 = prep(args.bfile, args.partition, args.sumstats1,
                                  args.sumstats2, args.N1, args.N2)
    print('Calculating LD scores...')
    ld_scores = ldscore(args.bfile, gwas_snps)
    gwas_snps = gwas_snps[gwas_snps['SNP'].isin(ld_scores['SNP'])]
    print('{} SNPs included in our analysis...'.format(len(gwas_snps)))
    print('Calculating heritability...')
    h_1, h_2 = heritability(gwas_snps, ld_scores, N1, N2)
    print(
        'The genome-wide heritability of the first trait is {}.\nThe genome-wide heritability of the second trait is {}.'
        .format(h_1, h_2))
    print('Calculating phenotypic correlation...')
    pheno_corr, pheno_corr_var = pheno(gwas_snps, ld_scores, N1, N2, h_1, h_2)
    print('Calculating local genetic covariance...')
    out = calculate(args.bfile, bed, args.thread, gwas_snps, ld_scores, N1, N2,
                    pheno_corr, pheno_corr_var)
    out.to_csv(args.out, sep=' ', na_rep='NA', index=False)
Exemplo n.º 7
0
def pipeline(args):
    pd.options.mode.chained_assignment = None

    # Sanity check args
    if args.save_ld is not None and args.use_ld is not None:
        raise ValueError('Both the --save-ld and --use-ld flags were set. '
                         'Please use only one of them.')
    if args.save_ld is not None:
        if not parent_dir_exists(args.save_ld):
            raise ValueError('--save-ld flag points to an invalid path.')
    if args.use_ld is not None:
        if not os.path.exists(args.use_ld + '.csv.gz'):
            raise ValueError('--use-ld flag points to an invalid path.')
    if not parent_dir_exists(args.out):
        raise ValueError('--out flag points to an invalid path.')

    print('Preparing files for analysis...')
    gwas_snps, N1, N2, annots = prep(args.bfile, args.annot, args.sumstats1,
                                     args.sumstats2)
    if args.N1 is not None:
        N1 = args.N1
    if args.N2 is not None:
        N2 = args.N2
    if args.use_ld is not None:
        print('Loading LD scores from {}'.format(args.use_ld))
        ld_scores = pd.read_csv(args.use_ld + '.csv.gz', sep=' ')
    else:
        print('Calculating LD scores...')
        ld_scores = ldscore(args.bfile, annots, gwas_snps, args.save_ld)
    print('Calculating correlation...')
    out = calculate(gwas_snps, ld_scores, annots, N1, N2)
    print('\nFinal results:\n{}\n'.format(out))
    print('\nView ldsc.log for verbose output.')
    out.insert(0, 'annot_name', out.index)
    out.to_csv(args.out, sep=' ', na_rep='NA', index=False)
Exemplo n.º 8
0
Arquivo: celeb.py Projeto: chyojn/kod
 def get(self):
   d = self.request.get('astro')
   celebbday = datetime.datetime.strptime(d, '%d/%m/%Y').date().strftime('%Y%m%d')
   [cellewis, celspiller, celchinese, celmillman] = calculate.calculate(celebbday)
   res = []
   infile = open("celebs")   
   for line in infile.readlines():
     resline = []
     tokens = line.split("|")
     name = tokens[0]
     resline.append(name)
     occup = tokens[1]
     resline.append(occup)
     tokens = tokens[2].split(":")
     if celspiller in tokens: resline.append(celspiller)
     if celchinese in tokens: resline.append(celchinese)
     for lewi in cellewis:
       if lewi in tokens: resline.append(lewi)
     if len(resline) > 5: # to avoid unnecessary sorting later
       res.append(resline)
     
   # sort according to list size, negative is taken
   # so that the sorting is descending
   #res.sort(lambda x, y: cmp(-len(x), -len(y))) 
   res = res[0:100]    
   self.response.out.write(simplejson.dumps(res))
Exemplo n.º 9
0
def text_calculate(string):
    numbers = {
        'один': '1',
        'два': '2',
        'три': '3',
        'четыре': '4',
        'пять': '5',
        'шесть': '6',
        'семь': '7',
        'восемь': '8',
        'девять': '9',
        'ноль': '0'
    }
    operators = {'плюс': '+', 'минус': '-', 'умножить': '*', 'делить': '/'}
    string = string.split()
    word_ind = 0
    num_string = ''
    while word_ind < len(string):
        if string[word_ind] in numbers:
            num_string = num_string + numbers[string[word_ind]]
        elif string[word_ind] in operators:
            num_string = num_string + operators[string[word_ind]]
        elif string[
                word_ind] == 'и' and word_ind - 1 >= 0 and word_ind + 1 < len(
                    string) and string[word_ind -
                                       1] in numbers and string[word_ind +
                                                                1] in numbers:
            num_string = num_string + '.'

        word_ind += 1
    return calculate(num_string)
Exemplo n.º 10
0
    def get(self):
        d = self.request.get('astro')
        celebbday = datetime.datetime.strptime(
            d, '%d/%m/%Y').date().strftime('%Y%m%d')
        [cellewis, celspiller, celchinese,
         celmillman] = calculate.calculate(celebbday)
        res = []
        infile = open("celebs")
        for line in infile.readlines():
            resline = []
            tokens = line.split("|")
            name = tokens[0]
            resline.append(name)
            occup = tokens[1]
            resline.append(occup)
            tokens = tokens[2].split(":")
            if celspiller in tokens: resline.append(celspiller)
            if celchinese in tokens: resline.append(celchinese)
            for lewi in cellewis:
                if lewi in tokens: resline.append(lewi)
            if len(resline) > 5:  # to avoid unnecessary sorting later
                res.append(resline)

        # sort according to list size, negative is taken
        # so that the sorting is descending
        #res.sort(lambda x, y: cmp(-len(x), -len(y)))
        res = res[0:100]
        self.response.out.write(simplejson.dumps(res))
Exemplo n.º 11
0
 def test_speed_increase_calculate_valid(self):
     calc = calculate()
     car_speed_in = 10.4673
     road_speed_in = 15
     result = calc.speed_increase(car_speed_in, road_speed_in)  #valid speed
     answer = -4.5327  #10.4673 - 15 = -4.5327
     self.assertEqual(answer, result)
Exemplo n.º 12
0
 def test_average_speed_calculate_invalid2(self):
   calc = calculate()
   time_1_in = 170
   time_2_in = 120
   dist_in = 4
   result = calc.average_speed(time_1_in, time_2_in, dist_in)#invalid speed
   self.assertFalse(result)
Exemplo n.º 13
0
 def test_speed_increase_calculate_valid(self):
   calc = calculate()
   car_speed_in = 10.4673
   road_speed_in = 15
   result = calc.speed_increase(car_speed_in, road_speed_in)#valid speed
   answer = -4.5327 #10.4673 - 15 = -4.5327
   self.assertEqual(answer, result)
Exemplo n.º 14
0
def pipeline(args):
    pd.options.mode.chained_assignment = None

    # Sanity check args
    if not parent_dir_exists(args.out):
        raise ValueError('--out flag points to an invalid path.')

    print('Preparing files for analysis...')
    gwas_snps, reversed_alleles_ref, bed, N1, N2 = prep(args.bfile1, args.bfile2, args.partition, args.sumstats1, args.sumstats2, args.N1, args.N2)
    print('Calculating LD scores for the first population...')
    ld_scores1 = ldscore(args.bfile1, gwas_snps)
    print('Calculating LD scores for the second population...')
    ld_scores2 = ldscore(args.bfile2, gwas_snps)
    ld_scores1 = ld_scores1[ld_scores1['SNP'].isin(ld_scores2['SNP'])]
    ld_scores2 = ld_scores2[ld_scores2['SNP'].isin(ld_scores1['SNP'])]
    subset_index = gwas_snps['SNP'].isin(ld_scores1['SNP'])
    gwas_snps = gwas_snps[subset_index]
    reversed_alleles_ref = reversed_alleles_ref[subset_index]
    print('{} SNPs included in our analysis...'.format(len(gwas_snps)))
    #print('Calculating heritability...')
    #h_1, h_2 = heritability(gwas_snps, ld_scores1, ld_scores2, N1, N2)
    #print('The genome-wide heritability of the first trait is {}.\nThe genome-wide heritability of the second trait is {}.'.format(h_1, h_2))
    print('Calculating local genetic covariance...')
    out = calculate(args.bfile1, args.bfile2, bed, args.thread, gwas_snps, reversed_alleles_ref, N1, N2, args.genome_wide, ld_scores1, ld_scores2)
    out.to_csv(args.out, sep=' ', na_rep='NA', index=False)
Exemplo n.º 15
0
 def update_text(self):
     """Called whenever the text is updated"""
     # Blank value for answer
     answer = ''
     # Get the text
     # Get the variable (and start value if applicable)
     # Get the answer
     # Give the text the extra d/dx, int, or sum
     if self.mode == 'Derivative':
         text = self.ui.text_entry_d.text()
         if len(text) > 0:
             variable = self.ui.variable_d.currentText()
             answer = calculate(self.mode, text, variable)
             text = f'd/d{variable} ({text})'
     elif self.mode == 'Integral':
         text = self.ui.text_entry_i.text()
         if len(text) > 0:
             variable = self.ui.variable_i.currentText()
             answer = calculate(self.mode,
                                text,
                                variable,
                                start=self.ui.lower_bound.text(),
                                end=self.ui.upper_bound.text())
             text = f'int {text}d{variable}'
     else:
         text = self.ui.text_entry_s.text()
         if len(text) > 0:
             variable = self.ui.variable_s.currentText()
             value = self.ui.value_s.text()
             answer = calculate(self.mode,
                                text,
                                variable,
                                value=value,
                                do_it=self.ui.button_value.isChecked())
             text = fr'sum_({variable}={value})^infty {text}'
     try:
         # Blank input
         if len(text) == 0:
             load_svg(self.ui.input, to_svg(BLANK))
             load_svg(self.ui.output, to_svg(BLANK))
         # Not blank input
         else:
             load_svg(self.ui.input, to_svg(to_latex(text)))
             load_svg(self.ui.output, to_svg(to_latex(answer)))
     except ValueError:
         # If there's an input error
         pass
Exemplo n.º 16
0
 def test_average_speed_calculate_valid(self):
   calc = calculate()
   time_1_in = 120
   time_2_in = 160
   dist_in = 56
   result = calc.average_speed(time_1_in, time_2_in, dist_in)#valid speed
   answer = 1.4
   self.assertEqual(answer, result)
Exemplo n.º 17
0
 def test_average_speed_calculate_invalid2(self):
     calc = calculate()
     time_1_in = 170
     time_2_in = 120
     dist_in = 4
     result = calc.average_speed(time_1_in, time_2_in,
                                 dist_in)  #invalid speed
     self.assertFalse(result)
Exemplo n.º 18
0
 def test_average_speed_calculate_valid(self):
     calc = calculate()
     time_1_in = 120
     time_2_in = 160
     dist_in = 56
     result = calc.average_speed(time_1_in, time_2_in,
                                 dist_in)  #valid speed
     answer = 1.4
     self.assertEqual(answer, result)
def test_basic_operators():
    assert calculate('5+5') == 10
    assert calculate('5*5') == 25
    assert calculate('10/2') == 5
    assert calculate('10-4') == 6
    assert calculate('10%4') == 2

    assert calculate('6/3') == 2
    assert calculate('5-10') == -5

    assert calculate('55+20') == 75
Exemplo n.º 20
0
 def __init__(self):
     super().__init__()
     self.setupUi(self)
     self.pushButton.clicked.connect(self.compute)
     self.comboBox.addItem('xgboost')
     self.comboBox.addItem('naive_bayes')
     self.comboBox.addItem('kmeans')
     self.calc = calculate.calculate()
     self.graphicsView = QGraphicsView()
     self.graphicsView_2 = QGraphicsView()
Exemplo n.º 21
0
 def get(self):    
   bday = self.request.get('bday')     
   btype = self.request.get('btype')    
   [lewis, spiller, chinese, millman] = calculate.calculate(bday)
   logging.debug(lewis)
   lewis_int = [int(x) for x in lewis]
   mb = calculate.calculate_mbti_full([lewis, spiller, chinese, millman]) 
   cycle, now_year, str_d = calculate.calculate_cycle(bday)
   res = {"lewis": lewis_int, "spiller": spiller, "chinese": chinese, "millman": millman, "mb": mb, "cycle": cycle}
   self.response.out.write(simplejson.dumps(res))
Exemplo n.º 22
0
 def run(self):
     while True:
         future_ticks = getFuturesTick(self.future_codes['IF'] +
                                       self.future_codes['IH'] +
                                       self.future_codes['IC'])
         index_ticks = getIndexTick(self.index_codes)
         result = calculate(future_ticks, index_ticks)
         self.update_date.emit(result)
         # print(result)
         time.sleep(1)
Exemplo n.º 23
0
def analyze(recalculate=False):
    basename = os.path.basename(os.path.normpath(data_folder))
    all_trajectories_filepath = basename + "_" + all_trajectories_file

    if (not recalculate) and os.path.exists(all_trajectories_filepath):
        df_all = pd.read_csv(all_trajectories_filepath, sep='\t')
        # print('A1', ~recalculate)
    else:
        data_files_list = [
            f for f in glob.iglob(os.path.join(data_folder, r"*" + extension),
                                  recursive=False)
        ]

        file = data_files_list[0]
        df_all = pd.read_csv(file, sep='\t')

        for i in trange(1,
                        np.min([max_N, len(data_files_list)]),
                        desc='Loading data files'):
            # for file in data_files_list[1:]:  # , desc='Loading data files'):
            file = data_files_list[i]
            df = pd.read_csv(file, sep='\t')
            df_all = df_all.append(df, ignore_index=True)
        df_all.to_csv(all_trajectories_filepath, sep='\t')  # ,  na_rep='nan')

    # folder, _ = os.path.split(file_list[0])
    results_path = results_folder
    reinit_folder(results_path)

    # Process
    from calculate import calculate
    calculate(csv_file=all_trajectories_filepath,
              results_folder=results_path,
              bl_produce_maps=True,
              snr_label=snr_label,
              sigma=sigma,
              recalculate=recalculate,
              ticks=True,
              txt_extension=extension,
              pdf=True,
              png=True,
              **kwargs)
Exemplo n.º 24
0
def call_calculate(bot, update):
    equation = update.message.text.replace('/calculate', '').strip()
    if equation == "":
        q_equation = ""
        custom_keyboard = [['7', '8', '9', '*'], ['4', '5', '6', '-'],
                           ['1', '2', '3', '+'], [',', '0', '=', '/']]
        reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard)
        bot.send_message(chat_id=update.message.chat_id,
                         text="Калькулятор",
                         reply_markup=reply_markup)
        return

    update.message.reply_text(calculate(equation))
Exemplo n.º 25
0
def pipeline(args):
    pd.options.mode.chained_assignment = None

    # Sanity check args
    if not parent_dir_exists(args.out):
        raise ValueError('--out flag points to an invalid path.')

    print('Preparing files for analysis...')
    gwas_snps, N1, N2 = prep(args.bfile, args.chr, args.start, args.end,
                             args.sumstats1, args.sumstats2, args.N1, args.N2)
    print('Calculating local TWAS...')
    out = calculate(args.bfile, gwas_snps, N1, N2, args.h1, args.h2,
                    args.shrinkage)
    out.to_csv(args.out, sep=' ', na_rep='NA', index=False)
Exemplo n.º 26
0
 def __init__(self, request_data):
   self.request_data = request_data
   self.valid = validate()
   site_id = self.valid.site(request_data['site_id'])
   self.site_cam_id = self.valid.cam(request_data['camera_id'])
   self.uuid = self.valid.uuid(request_data['uuid'])
   self.time_2 = self.valid.time(request_data['epoch_time'])
   self.sqlite = database()
   self.calc = calculate()
   self.s_id, self.s_limit = self.sqlite.find_site(site_id)
   self.cam_id = self.sqlite.get_cam_id(self.site_cam_id, self.s_id)
   self.curr_cam_m = self.sqlite.get_cam_m(self.cam_id, self.s_id)
   for plate_no in range(0,len(self.request_data['results'])):
     self.plate(plate_no)
Exemplo n.º 27
0
  def get(self):    
    res = []
    bdays = self.request.get('bdays')
    for bday in bdays.split(","): 
      bday_date = datetime.datetime.strptime(bday, '%B %d %Y').date()
      bday_pb_date = bday_date.strftime('%Y%m%d')
      [lewis, spiller, chinese, millman] = calculate.calculate(bday_pb_date)
      logging.debug(lewis)
      lewis_int = [int(x) for x in lewis]
      mb_astro_res = calculate.calculate_mb([lewis, spiller, chinese, millman]) 
      cycle, now_year, str_d = calculate.calculate_cycle(bday_pb_date)
      res.append({"lewis": lewis_int, "spiller": spiller, "chinese": chinese, "millman": millman, "mb": mb_astro_res, "cycle": cycle, "bday": bday_pb_date})

    self.response.out.write(simplejson.dumps(res))
def main(arg_str):
    """
    Main analysis file that uses TRamWAy
    """

    # Define arguments
    arg_parser = argparse.ArgumentParser(
        description='TRamWAy wrapper for analysis of a random walk trajectory')
    arg_parser.add_argument('-v',
                            '--version',
                            action='version',
                            version='%(prog)s ' + str(version))
    arg_parser.add_argument('-f',
                            '--file',
                            required=True,
                            action='store',
                            type=str,
                            help='Path to a trajectory')

    # Analyze arguments
    input_args = arg_parser.parse_args(arg_str.split())

    # Use the analyzed arguments
    file = input_args.file

    print(file)
    # Tesselate and perform inference

    # Calculate Bayes factors and output results
    _, output_folder = folders()
    calculate(file,
              output_folder,
              bl_produce_maps=False,
              snr_label=snr_label,
              sigma=sigma,
              extension=extension,
              **kwargs)
Exemplo n.º 29
0
 def get(self):
     bday = self.request.get('bday')
     btype = self.request.get('btype')
     [lewis, spiller, chinese, millman] = calculate.calculate(bday)
     logging.debug(lewis)
     lewis_int = [int(x) for x in lewis]
     mb = calculate.calculate_mbti_full([lewis, spiller, chinese, millman])
     cycle, now_year, str_d = calculate.calculate_cycle(bday)
     res = {
         "lewis": lewis_int,
         "spiller": spiller,
         "chinese": chinese,
         "millman": millman,
         "mb": mb,
         "cycle": cycle
     }
     self.response.out.write(simplejson.dumps(res))
Exemplo n.º 30
0
    def get(self):
        d = self.request.get('d')
        btype = self.request.get('btype')

        try:
            lewis, spiller, chinese, millman = calculate.calculate(d)

            lewi_summary = self.get_lewi(lewis[0])
            spiller_summary = self.get_spiller(spiller)
            chinese_summary = self.get_chinese(chinese)
            millman_summary = self.get_millman(millman[0])
            mbti_summary = self.get_mbti()

            cycle, now_year, str_d = calculate.calculate_cycle(d)

            mb_astro_res = calculate.calculate_mbti_full(
                [lewis, spiller, chinese, millman])
            logging.debug(mb_astro_res)

            path = os.path.join(os.path.dirname(__file__), 'reading.html')
            template_values = {
                'code_date': d,
                'date': str_d,
                'lewi_main': lewis[0],
                'lewis': lewis,
                'spiller': spiller,
                'spiller_converted': convertSpiller(spiller),
                'chinese': chinese,
                'btype': btype,
                'millman': millman,
                'millman_main': millman[0],
                'mb': mb_astro_res,
                'lewi_summary': lewi_summary,
                'spiller_summary': spiller_summary,
                'chinese_summary': chinese_summary,
                'millman_summary': millman_summary,
                'mbti_summary': mbti_summary,
                'cycle': cycle,
                'now_year': now_year
            }
        except Exception, e:
            logging.debug(e)
            path = os.path.join(os.path.dirname(__file__), 'explore.html')
            template_values = {
                'error': 'Wrong date',
            }
Exemplo n.º 31
0
  def get(self):
    d = self.request.get('d')     
    btype = self.request.get('btype') 

    try:
      lewis, spiller, chinese, millman = calculate.calculate(d)
      
      lewi_summary = self.get_lewi(lewis[0])
      spiller_summary = self.get_spiller(spiller)
      chinese_summary = self.get_chinese(chinese)
      millman_summary = self.get_millman(millman[0])
      mbti_summary = self.get_mbti()

      cycle, now_year, str_d = calculate.calculate_cycle(d)

      mb_astro_res = calculate.calculate_mbti_full([lewis, spiller, chinese, millman])
      logging.debug(mb_astro_res)
      
      path = os.path.join(os.path.dirname(__file__), 'reading.html')
      template_values = {
        'code_date': d,
        'date': str_d,
        'lewi_main': lewis[0],
        'lewis': lewis,
        'spiller': spiller,
        'spiller_converted': convertSpiller(spiller),
        'chinese': chinese,
        'btype': btype,
        'millman': millman,
        'millman_main': millman[0],
        'mb': mb_astro_res,
        'lewi_summary': lewi_summary,
        'spiller_summary': spiller_summary,
        'chinese_summary': chinese_summary,
        'millman_summary': millman_summary,
        'mbti_summary': mbti_summary,
        'cycle': cycle,
        'now_year': now_year
        }  
    except Exception, e:
      logging.debug(e)
      path = os.path.join(os.path.dirname(__file__), 'explore.html')
      template_values = {
        'error': 'Wrong date',
        }        
Exemplo n.º 32
0
    def result(self,master):
        try:
            # calculate
            rate = evaluate(self.rateEntry.get())
            distance = evaluate(self.distanceEntry.get())
            price = evaluate(self.priceEntry.get())

            rate = c.rate(rate,self.rateUnit.type)
            distance = c.distance(distance,self.distanceUnit.type)
            price = c.price(price,self.priceUnit.type)

            calculated = c.calculate(rate,distance,price)

            self.showRes(f"Total Cost: ${calculated:.2f}")

        except ZeroDivisionError:
            print ("Error: Dividing by Zero")
            self.showRes("Error: Dividing by Zero")
Exemplo n.º 33
0
def GetMoodIndex(N, day):
    AA4_LIST = []  #存放AA4数据的列表
    AA5_LIST = []  #存放AA5数据的列表
    AA6_LIST = []
    c = calculate(N, day)
    highlist = c.GetHighpxList()
    lowlist = c.GetLowhpxList()
    HHV = c.HHV(highlist)
    LLV = c.LLV(lowlist)
    for i in range(12, -1, -1):
        AA4_LIST.append(c.RSV(c.GetClosepx(i), LLV, HHV))
    #计算最近心情指数
    i = 0
    j = 0
    SMA(AA4_LIST, i, 13, 8, AA5_LIST)
    SMA(AA5_LIST, j, 13, 8, AA6_LIST)
    INDEX = math.ceil(AA6_LIST[-1])
    return INDEX
Exemplo n.º 34
0
def GetMoodIndex(N,day):
    AA4_LIST = [] #存放AA4数据的列表
    AA5_LIST = [] #存放AA5数据的列表
    AA6_LIST = []
    c = calculate(N,day)
    highlist = c.GetHighpxList()
    lowlist = c.GetLowhpxList()
    HHV = c.HHV(highlist)
    LLV = c.LLV(lowlist)
    for i in range(12,-1,-1):
        AA4_LIST.append(c.RSV(c.GetClosepx(i), LLV, HHV))
    #计算最近心情指数
    i = 0
    j = 0
    SMA(AA4_LIST,i,13,8,AA5_LIST)
    SMA(AA5_LIST,j,13,8,AA6_LIST)
    INDEX = math.ceil(AA6_LIST[-1])
    return INDEX
Exemplo n.º 35
0
def handleImageProcessing(msg):
    nmsg = msg[22:]
    cb = (base64.urlsafe_b64decode(nmsg + '=' * (4 - len(nmsg) % 4)))
    imgarr = idc.bytes_to_np_array(cb)
    imgarr = imgarr[:, :, 0:3]
    imgarr = np.stack([imgarr[:, :, 2], imgarr[:, :, 1], imgarr[:, :, 0]],
                      axis=2)
    imgarr = np.transpose(imgarr, (2, 0, 1)) / 255
    #bb: 416*416 dm:
    detections, classes, depthmap = calculate.calculate(imgarr)

    dist = np.sum(depthmap[64 - 10:64 + 10, 80 - 40:80 + 40])
    print(dist)
    if dist < 1800:
        emit('vibrate', '6')
    elif dist < 2000:
        emit('vibrate', '5')
    elif dist < 2100:
        emit('vibrate', '4')
    elif dist < 2300:
        emit('vibrate', '2')
    elif dist < 2700:
        emit('vibrate', '1')

    print(detections, '\n')
    for x1, y1, x2, y2, _, _, c in detections:
        cl = classes[int(c)]
        object_width = int(x2 - x1)
        object_length = int(y2 - y1)
        if object_width <= 0 or object_length <= 0:
            break
        x1, x2 = x1 / 416 * 128, x2 / 416 * 160
        # depthmap = depthmap[int(x1):int(x2), int(y1):int(y2)]
        # dist = numpy.sum(depthmap)/(x2-x1)/(y2-y1)
        print(dist)
        left, right = x1, 416 - x2
        if abs(left - right) > 20:
            if left > right and dist < 2100:
                emit('playsound',
                     cl + ' is on your right side. And it\'s pretty close')
            if left < right and dist < 2100:
                emit('playsound',
                     cl + ' is on your right side. And it\'s pretty close')
Exemplo n.º 36
0
def auto_calculate(bot, update):
    if update.message.text.startswith('Когда ближайшее полнолуние после'):
        date_pol = re.search('\d{4}-\d{2}-\d{2}', update.message.text)
        if date_pol is None:
            update.message.reply_text('Введите дату формата гггг-мм-дд')
        else:
            date_pol = date_pol.group(0)
            date_pol = ephem.next_full_moon(date_pol)
            update.message.reply_text("{}".format(date_pol))
        return

    global q_equation
    if update.message.text != '=':
        q_equation = q_equation + update.message.text
    else:
        reply_markup = telegram.ReplyKeyboardRemove()
        bot.send_message(chat_id=update.message.chat_id,
                         text=calculate(q_equation),
                         reply_markup=reply_markup)
Exemplo n.º 37
0
Arquivo: celeb.py Projeto: chyojn/kod
 def get(self):
   d = self.request.get('astro')
   filter = self.request.get('filter')
   celebbday = datetime.datetime.strptime(d, '%d/%m/%Y').date().strftime('%Y%m%d')
   [cellewis, celspiller, celchinese, celmillman] = calculate.calculate(celebbday)
   res = []
   infile = open("celeb_life_goal.txt")   
   for line in infile.readlines():
     try:
       tokens = line.split(":")
       if filter == '':
         if celmillman[0] == tokens[2].replace("\n",""):
           res.append([tokens[0], tokens[1]])
       else:
         #logging.debug(tokens[1])
         if (filter.lower() in tokens[1].lower()) and (celmillman[0] == tokens[2].replace("\n","")):
           res.append([tokens[0], tokens[1]])
     except Exception, e:
       pass
Exemplo n.º 38
0
def GetJValue(N, day):
    KLIST = []  #存放K值的列表
    RSV_LIST = []  #存放RSV值的列表
    DLIST = []  #存放D值的列表
    c = calculate(N, day)
    highlist = c.GetHighpxList()
    lowlist = c.GetLowhpxList()
    HHV = c.HHV(highlist)
    LLV = c.LLV(lowlist)
    #计算最近5天内的RSV值
    for i in range(4, -1, -1):
        #print i
        RSV_LIST.append(c.RSV(c.GetClosepx(i), LLV, HHV))
    #计算K值
    i = 0
    j = 0
    SMA(RSV_LIST, i, 5, 1, KLIST)
    SMA(KLIST[2:], j, 3, 1, DLIST)
    K = KLIST[-1]
    D = DLIST[-1]
    J = 3 * K - 2 * D
    return J
Exemplo n.º 39
0
 def get(self):
     d = self.request.get('astro')
     filter = self.request.get('filter')
     celebbday = datetime.datetime.strptime(
         d, '%d/%m/%Y').date().strftime('%Y%m%d')
     [cellewis, celspiller, celchinese,
      celmillman] = calculate.calculate(celebbday)
     res = []
     infile = open("celeb_life_goal.txt")
     for line in infile.readlines():
         try:
             tokens = line.split(":")
             if filter == '':
                 if celmillman[0] == tokens[2].replace("\n", ""):
                     res.append([tokens[0], tokens[1]])
             else:
                 #logging.debug(tokens[1])
                 if (filter.lower() in tokens[1].lower()) and (
                         celmillman[0] == tokens[2].replace("\n", "")):
                     res.append([tokens[0], tokens[1]])
         except Exception, e:
             pass
Exemplo n.º 40
0
def GetJValue(N,day):
    KLIST = [] #存放K值的列表
    RSV_LIST = []  #存放RSV值的列表
    DLIST = []  #存放D值的列表
    c = calculate(N,day)  
    highlist = c.GetHighpxList()
    lowlist = c.GetLowhpxList()
    HHV = c.HHV(highlist)
    LLV = c.LLV(lowlist)
    #计算最近5天内的RSV值 
    for i in range(4,-1,-1):
        #print i
        RSV_LIST.append(c.RSV(c.GetClosepx(i),LLV,HHV))
    #计算K值
    i = 0
    j = 0
    SMA(RSV_LIST,i,5,1,KLIST)
    SMA(KLIST[2:],j,3,1,DLIST)    
    K = KLIST[-1]
    D = DLIST[-1]
    J = 3*K-2*D
    return J     
Exemplo n.º 41
0
def answer(text):
    try:
        dni, date, cp = _check_input_data(text)
    except OnVotarError as e:
        res = str(e)
        logger.info('%s', e.__class__.__name__)
    else:
        result = calculate(dni, date, cp)
        if result:
            res = ('{}\n{}\n{}\n\n'
                   'Districte: {}\n'
                   'Secció: {}\n'
                   'Mesa: {}').format(*result)
            logger.info('OK - %s %s', date[:4], cp)
        else:
            res = ('Les dades introduides no han retornat cap resultat.\n\n'
                   'Si has canviat recentment de domicili, prova el '
                   'codi postal anterior.\n'
                   'Si tens més dubtes, contacta amb el correu electrònic '
                   'oficial de la Generalitat:\n'
                   '*****@*****.**')
            logger.info('DADES_INCORRECTES')
    return res
Exemplo n.º 42
0
    def run(self):
        """
        Opens file based on filename given by the user on the start screen.
        Calls the calculate function from the calculate.py file to compute the normalised value for tastes/emotions.
        Sends this data in an array to the main thread.
        If the value for taste/emotion is above 60, it is classified as predominant.
        """

        name = getName()
        with open('../GUI/files/' + str(name) + '.csv', 'r') as f:
            self.rows = sum(1 for line in f)

        time.sleep(0.8)

        while self.row < self.rows:

            values = calculate(self.row, name)

            # Thresholds for predominancy
            for i in range(0, 5):
                if values[i] > 55:
                    External.pred.append(i)

            for i in range(5, 11):
                if values[i] > 60:
                    External.pred.append(i)

            self.row += 1

            if self.row == self.rows:
                values.clear()
                values.append(1)

            self.countChanged.emit(values)
            # OpenFace reads the frames of the video every 0.33 seconds therefore, sleep time = 0.33
            time.sleep(0.033)
            values.clear()
Exemplo n.º 43
0
import sys
from datetime import datetime
sys.path.append('..')
import calculate

file = open ("../famousbday.txt")
for f in file.readlines():
  s = f.split(":")[2].replace("\n","")
  name = f.split(":")[0].replace("\n","")
  occup = f.split(":")[1].replace("\n","")    
  try:
    d = datetime.strptime(s, '%d/%m/%Y').date()
    res =  calculate.calculate(d.strftime('%Y%m%d'))
    if "mathematician" in occup: 
      if "194" in res[0]:
        print name, res, occup, d
      #if res[0][0] == '22' and res[3][0] == '303':
      #  print name, res, occup, d
  except Exception, e:
    pass

Exemplo n.º 44
0
# some experimental code to determine to full type based on 
# the celeb database. 
import sys; sys.path.append('..')
import calculate
import math

if __name__ == '__main__':    
    res =  calculate.calculate('19730424')
    print calculate.calculate_mbti_full(res)
    print res

    #res =  calculate.calculate('19451005')    
    #res =  calculate.calculate('19490222')
    #res =  calculate.calculate('19820108')

    #res =  calculate.calculate('19100422') # Norman Steenrod, 
    #res =  calculate.calculate('19160430') # Claude Shannon
    #res =  calculate.calculate('19230521') # Armand Borel
    #res =  calculate.calculate('19170617') # Atle Selberg
    #res =  calculate.calculate('19090821') # Nikolay Bogolyubov
    #res =  calculate.calculate('19640825') # Maxim Kontsevich
    #res =  calculate.calculate('19341012') # Albert Shiryaev
    #res =  calculate.calculate('19061024') # Alexander Gelfond
    #res =  calculate.calculate('19381103') # Martin Dunwoody    
    
    #res =  calculate.calculate('19610804') # barack obama
    #res =  calculate.calculate('19730326') # larry page
    #res =  calculate.calculate('19730821') # sergey brin
    #res =  calculate.calculate('19540226') # tayyip erdogan
    #res =  calculate.calculate('19590226') # ahmet davutoglu
    #res =  calculate.calculate('19501029') # abdullah gul
Exemplo n.º 45
0
 def test_speed_increase_calculate_invalid(self):
   calc = calculate()
   car_speed_in = '10.4673'
   road_speed_in = 'a0hbv'
   result = calc.speed_increase(car_speed_in, road_speed_in)#valid speed
   self.assertFalse(result)
def test_floating_point():
    assert calculate('10/4') == 2.5
    assert calculate('5.5*2') == 11
    assert calculate('100/3') - 33.33 < 0.1
    assert calculate('5.5+3.5') == 9
    assert calculate('3.4-1.4') == 2
Exemplo n.º 47
0
import pickle
import sys
sys.path.append('..')
import calculate

lewis, spiller, chinese, millman =  calculate.calculate('19730424')
#res =  calculate.calculate('19451005')
#res =  calculate.calculate('19820108')
#res =  calculate.calculate('19490222')
#res =  calculate.calculate('19730326') #larry page
#res =  calculate.calculate('19730821') #brin
#res =  calculate.calculate('19540226') 
#res =  calculate.calculate('19730423')
#res =  calculate.calculate('19480331') # al gore
#res =  calculate.calculate('19420108') # hawking
#res =  calculate.calculate('19610804') # obama

print lewis, spiller, chinese, millman 

Exemplo n.º 48
0
def GetTradeDate(i):
    c = calculate()
    return c.tradedate[i]
    
Exemplo n.º 49
0
# some experimental code to determine to full type based on 
# the celeb database. 
import sys
import calculate
import math

if __name__ == '__main__':    
    res =  calculate.calculate('19730424')
    print calculate.calculate_mbti_full(res)
    print res

    #res =  calculate.calculate('19451005')    
    #res =  calculate.calculate('19490222')
    #res =  calculate.calculate('19820108')
    
    #res =  calculate.calculate('19610804') # barack obama
    #res =  calculate.calculate('19730326') # larry page
    #res =  calculate.calculate('19730821') # sergey brin
    #res =  calculate.calculate('19540226') # tayyip erdogan
    #res =  calculate.calculate('19590226') # ahmet davutoglu
    #res =  calculate.calculate('19501029') # abdullah gul
    #res =  calculate.calculate('19560120') # bill maher
    #res =  calculate.calculate('19700921') # jen
    #res =  calculate.calculate('19180511') # richard feynman
    #res =  calculate.calculate('19691228') # linus torvalds
    #res =  calculate.calculate('19200102') # isaac asimov
    #res =  calculate.calculate('19690312') # acun
    #res =  calculate.calculate('19270622') # cetin altan
    #res =  calculate.calculate('19560101') # mumtaz turkone
    #res =  calculate.calculate('19550224') # steve jobs
    #res =  calculate.calculate('19370611') # mumford
def test_operator_precedence():
    # Test Precedence of operators
    assert calculate('2+7*2') == 16
    assert calculate('4-6/3') == 2
    assert calculate('4+5%3') == 6
def test_parentheses():
    assert calculate('7+(5*2)') == 17
    assert calculate('7*(5+2)') == 49
    assert calculate('(7*3)+(9/3)') == 24
    assert calculate('7+(7*(6+10/(1*2)))') == 84
Exemplo n.º 52
0
__author__ = 'srtoosnye'
# -*- coding: utf-8 -*-
from Expr import Expr
from calculate import calculate
import data
import sys

conn = data.link_to_mysql()
cursor = conn.cursor()
data.create_table(cursor)
expr = raw_input('请输入表达式:')
if data.is_used_data(cursor, expr):
    sys.exit()

s = Expr(expr)
s.check_value()
s.opt_value()

data.store_result(cursor, calculate(s.get_postfix()), expr)
conn.commit()
conn.close()
Exemplo n.º 53
0
# some experimental code to determine to full type based on 
# the celeb database. 
import sys
import calculate
import math

if __name__ == '__main__':    
    res =  calculate.calculate('19730424')
    print calculate.calculate_mbti_full(res); print res

    #res =  calculate.calculate('19451005')    
    #res =  calculate.calculate('19490222')
    #res =  calculate.calculate('19820108')
    
    #res =  calculate.calculate('19610804') # barack obama
    #res =  calculate.calculate('19730326') # larry page
    #res =  calculate.calculate('19730821') # sergey brin
    #res =  calculate.calculate('19540226') # tayyip erdogan
    #res =  calculate.calculate('19590226') # ahmet davutoglu
    #res =  calculate.calculate('19501029') # abdullah gul
    #res =  calculate.calculate('19560120') # bill maher
    #res =  calculate.calculate('19700921') # jen
    #res =  calculate.calculate('19180511') # richard feynman
    #res =  calculate.calculate('19691228') # linus torvalds
    #res =  calculate.calculate('19200102') # isaac asimov died 19920406
    #res =  calculate.calculate('19690312') # acun
    #res =  calculate.calculate('19270622') # cetin altan
    #res =  calculate.calculate('19560101') # mumtaz turkone
    #res =  calculate.calculate('19550224') # steve jobs
    #res =  calculate.calculate('19370611') # mumford
    #res =  calculate.calculate('19470412') # tom clancy
Exemplo n.º 54
0
records=[]
insertQuery='insert into __table_name__(type,property,native_type,native_property,hit,total) VALUES(%s,%s,%s,%s,%s,%s);'
insertQuery = insertQuery.replace('__table_name__',tableName)
if lang !="FA":
    #print insertQuery
    filepath = 't.xml'
    tree = xml.parse(filepath)
    xmlRoot = tree.getroot()
    for c in xmlRoot.findall('.//Type'):
        typeName = c.attrib['name']
        #typeName = 'http://dbpedia.org/ontology/University'
        native_type = findLabel(originTree,typeName,slang,0)
        if native_type == None:
            native_type = 'None'
        properties = calculate.calculate(typeName,lang)
        #print properties
        total = properties['__total__']
        for property in properties:
            native_property = ''
            if property == '__total__':
                native_property = '__total__'
            else:
                native_property = findLabel(originTree,property[1:-1],slang,1)
                if native_property == None:
                    native_property = findLabel(originTree,property[1:-1],slang,2)
                if native_property == None:
                    native_property = 'None'

            hit = properties[property]
            record = (typeName,property,native_type,native_property,hit,total)