def marathon_data(): TFT0=request.values.get('Target Finish Time') Age=request.values.get('Age') Experience=request.values.get('Experience') Gender=request.values.get('Gender') TFTHH,_,TFTMM = TFT0.partition(':') TFTHH = int(TFTHH) TFTMM = int(TFTMM) TFT = TFTHH*60 + TFTMM y_pace, y_predict = generate_series(TFT, Age, Experience, Gender) with open('./Elite_runners.txt') as elite_runners_txt: with generate_personal_txt_file(y_pace, y_predict) as personal_txt: rows = list(parser.read(elite_runners_txt)) rows += list(parser.read(personal_txt)) data = parser.parse(rows) placed_data, ranks = parser.place_at_splits(data) impute_placed_data = parser.impute(placed_data, ranks) marathon_data = json.dumps(impute_placed_data, indent=4) return Response(marathon_data, mimetype='text/json')
def marathon_data(): TFT0 = request.values.get('Target Finish Time') Age = request.values.get('Age') Experience = request.values.get('Experience') Gender = request.values.get('Gender') TFTHH, _, TFTMM = TFT0.partition(':') TFTHH = int(TFTHH) TFTMM = int(TFTMM) TFT = TFTHH * 60 + TFTMM y_pace, y_predict = generate_series(TFT, Age, Experience, Gender) with open('./Elite_runners.txt') as elite_runners_txt: with generate_personal_txt_file(y_pace, y_predict) as personal_txt: rows = list(parser.read(elite_runners_txt)) rows += list(parser.read(personal_txt)) data = parser.parse(rows) placed_data, ranks = parser.place_at_splits(data) impute_placed_data = parser.impute(placed_data, ranks) marathon_data = json.dumps(impute_placed_data, indent=4) return Response(marathon_data, mimetype='text/json')
def saveOverzicht(self): filename = 'settings.ini' parser = configparser.ConfigParser() parser.read(filename) parser.set('COMMON', 'TRESHOLD', self.tresholdTxt.text()) parser.set('COMMON', 'BOXPERCENT', self.percentageTxt.text()) parser.set('COMMON', 'MOEILIJKTRESHOLD', self.moeilijkTxt.text()) with open(filename, 'w') as configfile: parser.write(configfile)
def set_env(): logger.info("Setting environment variables from config file") parser = SafeConfigParser() parser.read('config.txt') os.environ["OS_PROJECT_DOMAIN_NAME"] = parser.get('environment', 'OS_PROJECT_DOMAIN_NAME') os.environ["OS_USER_DOMAIN_NAME"] = parser.get('environment', 'OS_USER_DOMAIN_NAME') os.environ["OS_PROJECT_NAME"] = parser.get('environment', 'OS_PROJECT_NAME') os.environ["OS_USERNAME"] = parser.get('environment', 'OS_USERNAME') os.environ["OS_PASSWORD"] = parser.get('environment', 'OS_PASSWORD') os.environ["OS_AUTH_URL"] = parser.get('environment', 'OS_AUTH_URL') os.environ["OS_IDENTITY_API_VERSION"] = parser.get('environment', 'OS_IDENTITY_API_VERSION') os.environ["OS_IMAGE_API_VERSION"] = parser.get('environment', 'OS_IMAGE_API_VERSION')
def command_line_runner(): parser = get_parser() args = vars(parser.parse_args()) if args['version']: print(__version__) return if not args['input']: parser.print_help() return else: welcome() enable_cache() print 'Preparing the input file for NWChem ............' name = nwchem(args) print 'NWChem is running...............................' os.system('nwchem '+ name +'.nw' + '>' + name +'.nwo') print 'Getting following infomation from NWChem output:' print 'Number of total electrons' print 'Nuclear replusion energy' print 'Kinetic integral' print 'Potential integral' print 'Overlap integral' print 'two electrons integral' print '\n' p = read(name+'.nwo') mol = rhf(p.Nelec,'enuc.dat','s.dat','t.dat','v.dat','e2.dat') print '=====> Begin SCF Iterations <====\n\n' ens = mol.converge(SCFIterator) print "* Total SCF energy = " +str(mol.energy)
def command_line_runner(): parser = get_parser() args = vars(parser.parse_args()) if args['version']: print(__version__) return if not args['input']: parser.print_help() return else: welcome() enable_cache() print 'Preparing the input file for NWChem ............' name = nwchem(args) print 'NWChem is running...............................' os.system('nwchem ' + name + '.nw' + '>' + name + '.nwo') print 'Getting following infomation from NWChem output:' print 'Number of total electrons' print 'Nuclear replusion energy' print 'Kinetic integral' print 'Potential integral' print 'Overlap integral' print 'two electrons integral' print '\n' p = read(name + '.nwo') mol = rhf(p.Nelec, 'enuc.dat', 's.dat', 't.dat', 'v.dat', 'e2.dat') print '=====> Begin SCF Iterations <====\n\n' ens = mol.converge(SCFIterator) print "* Total SCF energy = " + str(mol.energy)
def employees_idemnity_nov19(file_path, employees): data = parser.read(file_path) #Ajustando dataframe para simplificar interação data = data[data['Unnamed: 4'].notna()] data = data[data['Ministério Público do Estado do Espírito Santo'].notna()] data = data[1:] parser.clean_currency(data, 4, 7) #Parsing Data rows = data.to_numpy() for row in rows: reg = str(row[0]) # Matrícula aux_ali = row[4] #CARTÃO ALIMENTAÇÃO ferias_indenizadas = row[5] ferias_premio = row[6] aux_saude = row[7] #AUXÍLIO SAÚDE plantao = row[8] #Plantao #Há funcionários não listados na lista de remunerações mas listados na lista de indenizações try: emp = employees[reg] exists = True except: exists = False if exists: emp = employees[reg] emp['income'].update({ 'total': round(emp['income']['total'] + plantao, 2), }) emp['income']['perks'].update({ 'total': round(aux_ali + aux_saude + ferias_indenizadas + ferias_premio, 2), 'vacation': round(ferias_indenizadas + ferias_premio, 2), 'food': round(aux_ali, 2), 'health': round(aux_saude, 2), }) emp['income']['other']['others'].update({ 'Plantão': plantao, }) emp['income']['other'].update({ 'total': round(emp['income']['other']['total'] + plantao, 2), 'others_total': round(emp['income']['other']['others_total'] + plantao, 2), }) employees[reg] = emp return employees
def set_env(): logger.info("Setting environment variables from config file") parser = SafeConfigParser() parser.read('config.txt') os.environ["OS_PROJECT_DOMAIN_NAME"] = parser.get( 'environment', 'OS_PROJECT_DOMAIN_NAME') os.environ["OS_USER_DOMAIN_NAME"] = parser.get('environment', 'OS_USER_DOMAIN_NAME') os.environ["OS_PROJECT_NAME"] = parser.get('environment', 'OS_PROJECT_NAME') os.environ["OS_USERNAME"] = parser.get('environment', 'OS_USERNAME') os.environ["OS_PASSWORD"] = parser.get('environment', 'OS_PASSWORD') os.environ["OS_AUTH_URL"] = parser.get('environment', 'OS_AUTH_URL') os.environ["OS_IDENTITY_API_VERSION"] = parser.get( 'environment', 'OS_IDENTITY_API_VERSION') os.environ["OS_IMAGE_API_VERSION"] = parser.get('environment', 'OS_IMAGE_API_VERSION')
def add_coverage(coverage_ID, new_name, measurement_unit, other_info): installation_dir = os.path.abspath(os.path.dirname(sys.argv[0])) #LOAD CONFIGURATION try: parser = SafeConfigParser() parser.read("%s/../etc/pep_lib.ini" % installation_dir) except: logging.error("I am unable to load configuration") loging.debug(str(e)) return try: new_dict = dict(e.split('=') for e in other_info.split(';')) new_dict['function'] new_dict['label'] except: logging.error("other_info param is not a string in a valid format") conn = psycopg2.connect( "dbname='%s' user='******' host='%s' password='******'" % (parser.get("db", "name"), parser.get( "db", "user"), parser.get("db", "host"), parser.get("db", "pass"))) cur = conn.cursor() query = "SELECT * from data_ingestion_collectiontable where \"coverageID\" like '%s'" % ( coverage_ID) logging.debug("add_coverage select query: %s" % (query)) cur.execute(query) data = cur.fetchall() try: val = ['' if v is None else v for v in data[0]] query = "INSERT INTO data_ingestion_collectiontable(name, source, max_lat, max_lon, min_lat, min_lon, start_date,end_date,application,"+\ "\"group\", location,other_info,uploaded_by_id,status, \"IO\", \"coverageID\",measurement_unit,access,ipr,max_value,min_value) VALUES " query = "%s ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s',%s,'%s','%s','%s','%s','%s','%s','%s','%s')" % ( query, new_name, val[2], val[3], val[4], val[5], val[6], val[7], val[8], val[9], val[10], val[11], other_info, val[13], 'reprocess', 'O', val[16], measurement_unit, val[18], val[19], val[20], val[21]) logging.debug("add_coverage insert query: %s" % (query)) cur.execute(query) conn.commit() except Exception as e: raise logging.error( "Error to insert coverage on data_ingestion_collectiontable") logging.debug(str(e)) cur.close() conn.close()
def selectDir(self): filename = 'settings.ini' parser = configparser.ConfigParser() parser.read(filename) global WACHTWOORD WACHTWOORD = parser.get('COMMON', 'wachtwoord') if debug: dialog = QtWidgets.QFileDialog() dialog.setFileMode(QtWidgets.QFileDialog.DirectoryOnly) dialog.setViewMode(QtWidgets.QFileDialog.Detail) if (dialog.exec()): a = dialog.selectedFiles() directory = a[0] + '/' else: directory = default else: directory = default try: open(directory + parser.get('PATHS', 'SHEETINFO')) gelukt = True except: gelukt = False if not gelukt: directory = default parser.set('PATHS', 'QUIZFOLDER', directory) with open(filename, 'w') as configfile: parser.write(configfile) if 'Test' in directory: pal = QPalette() pal.setColor(QPalette.Background, Qt.red) self.setAutoFillBackground(True) self.setPalette(pal) lijstje = directory.split('/') titel = lijstje[len(lijstje) - 2] self.setWindowTitle(self.windowTitle() + ' ' + titel) return gelukt
def employees_idemnity(file_path, employees): data = parser.read(file_path) #Ajustando dataframe para simplificar interação data = data[data['Unnamed: 4'].notna()] data = data[data['Ministério Público do Estado do Espírito Santo'].notna()] parser.clean_currency(data,1,5) #Parsing data rows = data.to_numpy() for row in rows: reg = str(row[0]) # Matrícula verba1 = row[1] #VERBAS INDENIZATÓRIAS 1 verba2 = row[2] #VERBAS INDENIZATÓRIAS 2 other1 = row[3] #REMUNERAÇÃO TEMPORÁRIA 1 other2 = row[4] #REMUNERAÇÃO TEMPORÁRIA 2 #Há funcionários não listados na lista de remunerações mas listados na lista de indenizações try: emp = employees[reg] exists = True except: exists = False if exists : emp = employees[reg] emp['income']['perks'].update({ 'total': 0.0, }) emp['income']['other']['others'].update({ 'VERBAS INDENIZATÓRIAS 1': verba1, 'VERBAS INDENIZATÓRIAS 2': verba2, 'REMUNERAÇÃO TEMPORÁRIA 1': other1, 'REMUNERAÇÃO TEMPORÁRIA 2': other2, }) emp['income']['other'].update({ 'others_total': round( emp['income']['other']['others_total'] + verba1 + verba2 + other1 + other2, 2), }) emp['income']['other'].update({ 'total': round(emp['income']['other']['total'] + emp['income']['other']['others_total'], 2) }) emp['income'].update({ 'total': round( emp['income']['perks']['total'] + emp['income']['other']['total'] + emp['income']['wage'], 2), }) employees[reg] = emp return employees
def index(resource, reindex=False): segments = parser.read(resource) ix = get_index() writer = ix.writer() if not check_for_presence(ix, segments) or reindex: for title in segments: for segment in segments[title]: if segment.get("content") and segment.get("url"): add_to_index(writer, segment, title, resource) writer.commit() return(ix)
def test_eval_simple_let(self): exp = Evaluator().eval(read('(let ((x 4)) x)')) self.assertEqual(exp, 4)
def test_lamda_expression(self): exp = Evaluator().eval(read('(lambda (x) (+ x 2))')) self.assertIsInstance(exp, type(lambda: None))
def test_read_number_list(self): self.assertEqual(read('(1 2 3.14 22.22)'), [1, 2, 3.14, 22.22])
def test_complex_eqv_special_form(self): e = Evaluator() exp = e.eval(read('(let ((p (lambda (x) x))) (eqv? p p)')) self.assertEqual(exp, True)
def test_define_func(self): e = Evaluator() exp = e.eval(read('(define (square a) (* a a))')) self.assertIsInstance(exp, type(lambda: None))
def test_define_var(self): e = Evaluator() exp = e.eval(read('(define x 4)')) self.assertEqual(e.env.get('x'), 4)
def test_eqv_special_form(self): e = Evaluator() exp = e.eval(read('(eqv? 1 1)')) self.assertEqual(exp, True)
def test_define_lambda(self): e = Evaluator() exp = e.eval(read('(define square (lambda (x) (* x x)))')) next_exp = e.eval(read('(square 5)')) self.assertEqual(next_exp, 25)
def test_eval_let_with_two_vals_in_last_sexp(self): exp = Evaluator().eval(read('(let ((x 4)) (let ((x 3)) "foo" x))')) self.assertEqual(exp, 3)
def test_eval_nested_let(self): exp = Evaluator().eval(read('(let ((x 4)) (let ((x 3)) x))')) self.assertEqual(exp, 3)
def test_falsy_eqv_special_form(self): e = Evaluator() exp = e.eval(read('(eqv? 1 2)')) self.assertEqual(exp, False)
def parse(inport): "Parse a program: read and expand/error-check it." # Backwards compatibility: given a str, convert it to an InPort if isinstance(inport, str): inport = InPort(StringIO.StringIO(inport)) return expand(read(inport), toplevel=True)
def test_read_simple_lambda(self): self.assertEqual(read(self.line), [['lambda', ['x'], 'x'], '"Lisp"'])
ride_list.index(r)) do(r, c, t) elif (b > 1): c_index = random.randint(0, len(bonus_cars) - 1) c = bonus_cars[c_index] print "picked car " + str( car_list.index(c)) + " to get bonus on ride " + str( ride_list.index(r)) do(r, c, t) return True filename = sys.argv[1] f = open(filename) passed_list = [] passed_list = parser.read(f) f.close() I = int(passed_list[0]) J = int(passed_list[1]) F = int(passed_list[2]) R = int(passed_list[3]) B = int(passed_list[4]) T = int(passed_list[5]) car_list = passed_list[6] ride_list = passed_list[7] t = 0 while t <= T: #for all rides #if !isDone #if ride_is_possible at t
def test_eval_lambda_expression(self): exp = Evaluator().eval(read('((lambda(x) (+ x 2)) 42)')) self.assertEqual(exp, 44)
def REPL(line, evaluator): try: return evaluator.eval(read(line)) except IndexError: return ''
def employees_parser(file_path): data = parser.read(file_path) #Ajustando dataframe para simplificar interação data = data[data['Unnamed: 0'].notna()] del data['Unnamed: 18'] data = data.dropna() parser.clean_currency(data, 4, 15) #Parsing data rows = data.to_numpy() employees = {} for row in rows: reg = str(row[0]) #Matrícula name = row[1] #Nome role = row[2] #Cargo workplace = row[3] #Lotação remuneration = format_value(row[4]) #Remuneração do cargo efetivo other_verbs = format_value( row[5]) #Outras Verbas Remuneratórias, Legais ou Judiciais trust_pos = format_value( row[6]) #Função de Confiança ou Cargo em Comissão christmas_grati = format_value(row[7]) #Gratificação Natalina terco_ferias = format_value(row[8]) #Férias (1/3 constitucional) abono_permanencia = format_value(row[9]) #Abono de Permanência temp_remu = format_value(row[10]) #Outras Remunerações Temporárias idemnity = format_value(row[11]) #Verbas Indenizatórias prev_contrib = format_value(row[13]) #Contribuição Previdenciária imposto_renda = format_value(row[14]) #Imposto de Renda ceil_ret = format_value(row[15]) #Retenção do Teto total_desconto = prev_contrib + imposto_renda + ceil_ret total_gratificacoes = trust_pos + christmas_grati + terco_ferias + abono_permanencia + temp_remu total = total_gratificacoes + idemnity + remuneration + other_verbs employees[reg] = { 'reg': reg, 'name': name, 'role': role, 'type': 'membro', 'workplace': workplace, 'active': True, "income": { 'total': round(total, 2), 'wage': round(remuneration + other_verbs, 2), 'perks': { 'total': idemnity, }, 'other': { 'total': round(total_gratificacoes, 2), 'trust_position': trust_pos, 'eventual_benefits': temp_remu, 'others_total': round(christmas_grati + terco_ferias + abono_permanencia, 2), 'others': { 'Gratificação Natalina': christmas_grati, 'Férias (1/3 constitucional)': terco_ferias, 'Abono de permanência': abono_permanencia, } }, }, 'discounts': { 'total': round(total_desconto, 2), 'prev_contribution': prev_contrib, 'ceil_retention': ceil_ret, 'income_tax': imposto_renda } } return employees
import sys import parser import matplotlib.pyplot as plt import testing as test import instance as inst import solution as sol import constructives as cons import lpSolution as lp import graphing as graph import VNS as VNS if __name__ == "__main__": for arg in sys.argv[1:]: nodes = parser.read(arg) alpha = [0.25,0.5,0.75,1] m = [3,4,5] it = 100 tests = test.testCases(nodes, alpha, m, 0.9) #sol = map(lambda x: map(lp.solve, x), tests) #sol = map(lambda x: map(lambda y:cons.naive(y,1,0), x), tests) #sol = map(lambda x: map(VNS.localSearchZ3, x), sol) sol = map(lambda x: map(lambda y: VNS.VNS(y, it), x), tests) sol = list(map(list, sol)) # print(sol) #sol[0][0] = VNS.changeNeighbourhood(sol[0][0]) graph.graphSolutions(sol) graph.toLaTeX(sol)
# Helper class to convert a DynamoDB item to JSON. class DecimalEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, decimal.Decimal): if o % 1 > 0: return float(o) else: return int(o) return super(DecimalEncoder, self).default(o) ## Datos credenciales twitter from configparser import ConfigParser parser = ConfigParser() parser.read('api_auth.cfg') access_token = parser.get('api_tracker', 'access_token') access_token_secret = parser.get('api_tracker', 'access_token_secret') consumer_key = parser.get('api_tracker', 'consumer_key') consumer_secret = parser.get('api_tracker', 'consumer_secret') def get_tweet_list(twapi, idlist): tweets = twapi.statuses_lookup(id_=idlist, include_entities=False, trim_user=True) if len(idlist) != len(tweets): #Logger.warn('get_tweet_list: unexpected response size %d, expected %d', len(tweets), len(idlist)) print("error, algunos tweet ids no se pudieron consultar") # for tweet in tweets: # print('%s,%s' % (tweet.id, tweet.retweet_count ))
import parser import codegen import sys if len(sys.argv) == 1: sys.stderr.write("No input files given.\n") sys.exit(1) else: if sys.argv[1] == "--read-ast": sys.argv = sys.argv[1:] for fname in sys.argv[1:]: codegen.generate(parser.read(fname)) else: for fname in sys.argv[1:]: codegen.generate(parser.parse(fname))
#processing if dict_args['function'] == 'verticalIntegration': twodize(matches, outputdir, label) elif dict_args['function'] == 'convert': convert(matches, outputdir, label, float(dict_args['gain']), float(dict_args['offset'])) else: logging.error("Reprocessing: Unrecognized function") raise Exception('Error', 'Unrecognized function') if __name__ == "__main__": #LOAD CONFIGURATION try: parser = SafeConfigParser() parser.read("%s/../etc/pep_lib.ini" % installation_dir) #set logger logging.basicConfig( #stream= sys.stdout, filename=installation_dir + "/../log/FilesystemData.log", level=int(parser.get("Logger", "loglevel")), format='%(levelname)s\t| %(asctime)s | %(message)s') except Exception as e: print "I am unable to load configuration" print str(e) parser = argparse.ArgumentParser( prog=sys.argv[0], description= 'Utility used to reprocess entire collections on filesystem', epilog='SISTEMA GmbH <http://sistema.at>')
import multiprocessing import parser import socket import threading from config_file import ConfigParser parser = ConfigParser() parser.read('conf.ini') sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server_name = (socket.gethostbyname(socket.gethostname()), 4096) IPAddr = socket.gethostbyname(socket.gethostname()) counter = 0 count = 0 pac_cap = parser.getboolean('Maximum', 'Start') connection_hs = True heartbeat_ = True # Heartbeat funktionen def heartbeat(): if heartbeat_: threading.Timer(parser.getint('Heartbeat', 'time'), heartbeat).start() heartbeat_msg = 'con-h 0x00' heartbeat_msg_sent = sock.sendto(heartbeat_msg.encode(), server_name) print('test HB') else: print("No Heartbeat Action") sock.close()
import pymysql from parser import read import administration_db, for_html incoming_file = 'eFw3Cefj.json' db = 'test' table = read(incoming_file) adm_db = administration_db.AdminDB(table, incoming_file) try: adm_db.connect_db(db) except pymysql.err.InternalError: try: adm_db.create_db(db) except: raise ConnectionError finally: adm_db.use_db(db) try: adm_db.create_table(adm_db.name_table_data) except: adm_db.drop_table(adm_db.name_table_data) adm_db.create_table(adm_db.name_table_data) finally: adm_db.write_into(adm_db.name_table_data, adm_db.table) table_from_db = adm_db.read_from(adm_db.name_table_data) adm_db.close_connection()