Example #1
0
def main():
    import sys
    if len(sys.argv) == 5:
        _, p_rom, p_patch, p_asmfile, p_ldscript = sys.argv
    else:
        print("Usage: <this> rom.gba patch.json out.s out.ldscript")
        return

    with open("info.json") as infofile:
        info = json.load(infofile)

    unknowns = []
    funcs = {}
    for fj in info["functions"]:
        addr = leval(fj["range"][0])
        size = leval(fj["range"][1])
        name = fj.get("name", "sub_{:08x}".format(addr))
        funcs[name] = Function(name, addr, size)

    del addr, size, name

    with open(p_patch) as patchfile:
        patch = json.load(patchfile)

    patches = []
    for section in patch["sections"]:
        if section["name"].startswith(".text."):
            funcname = section["name"][6:]
            if funcname not in funcs:
                # allow all unknowns
                func = Function(funcname, None, None)
                unknowns.append(func)
            else:
                func = funcs[funcname]
            patches.append(Patch(func, section["size"]))

    leval_sym_addr = lambda ts: [(leval(addr_expr), name)
                                 for addr_expr, name in ts]
    symbols_thumb = leval_sym_addr(info["symbols-thumb"])
    symbols_ram = leval_sym_addr(info["symbols-ram"])

    for func in funcs.values():
        if not hasattr(func, "use"):
            symbols_thumb.append((func.addr + 1, func.name))

    with open(p_asmfile, "w") as asmfile:
        with open(p_ldscript, "w") as ldscript:
            write(info, patches, symbols_thumb, symbols_ram, p_rom, asmfile,
                  ldscript)

    if not unknowns: return
    print("Unknowns (put into pool)")
    for f in unknowns:
        print(" ", f.name)
Example #2
0
def main():
	import sys
	if len(sys.argv) == 5:
		_, p_rom, p_patch, p_asmfile, p_ldscript = sys.argv
	else:
		print("Usage: <this> rom.gba patch.json out.s out.ldscript")
		return

	with open("info.json") as infofile:
		info = json.load(infofile)

	unknowns = []
	funcs = {}
	for fj in info["functions"]:
		addr = leval(fj["range"][0])
		size = leval(fj["range"][1])
		name = fj.get("name", "sub_{:08x}".format(addr))
		funcs[name] = Function(name, addr, size)

	del addr, size, name

	with open(p_patch) as patchfile:
		patch = json.load(patchfile)

	patches = []
	for section in patch["sections"]:
		if section["name"].startswith(".text."):
			funcname = section["name"][6:]
			if funcname not in funcs:
				# allow all unknowns
				func = Function(funcname, None, None)
				unknowns.append(func)
			else:
				func = funcs[funcname]
			patches.append(Patch(func, section["size"]))

	leval_sym_addr = lambda ts: [(leval(addr_expr), name) for addr_expr, name in ts]
	symbols_thumb = leval_sym_addr(info["symbols-thumb"])
	symbols_ram = leval_sym_addr(info["symbols-ram"])

	for func in funcs.values():
		if not hasattr(func, "use"):
			symbols_thumb.append((func.addr+1, func.name))

	with open(p_asmfile, "w") as asmfile:
		with open(p_ldscript, "w") as ldscript:
			write(info, patches, symbols_thumb, symbols_ram, p_rom, asmfile, ldscript)

	if not unknowns: return
	print("Unknowns (put into pool)")
	for f in unknowns:
		print(" ", f.name)
Example #3
0
def test_datagen_getitem_val():
    datagen = DataGen(conf=default_conf, split='val', do_augmentation=False)
    item = datagen[0]
    load_dict = leval(item['load_dict'])

    assert (item['label'] == load_dict['class'])
    assert (load_dict['pos'] == 0)
	def parse_repeat_str (self, s):
		"""
		Parse out the 'repeat' field in each record.
		"""
		if not s:
			return {'form': [], 'section': [], 'subsection': [], 'row': []}
		else:
			md_dict = self.parse_metadata_qual (s)
			for k, v in list (md_dict.items()):
				if not v:
					continue
				elif ',' in v:
					# must be a explicit sequence
					# hideous but I eval the string to get a list
					try:
						rpt_list = leval ("[%s]" % v)
					except Exception as err:
						print ("eval string")
						print (v)
						raise
				else:
					assert '-' in v, "can't interpret '%s' as range" % v
					start, stop = [int (x) for x in v.split ('-', 1)]
					rpt_list = list (range (start, stop+1))

				md_dict[k] = rpt_list

			assert len (md_dict) == 4, "bad dict %s" % md_dict
			return md_dict
 def onchange_partner_id(
     self, cr, uid, ids, partner_id, context_saved, context=None
 ):
     context_saved = leval(context_saved)
     domain = deepcopy(move_line_domain)
     if (
         context_saved['state_line_ids'] == 'entering_wizard' or
         not partner_id
     ):
         return {
             'value': {},
             'domain': {'line_ids': domain}
         }
     domain.append(('partner_id', '=', partner_id))
     list_ids = context_saved['lines_by_partner'][partner_id]
     context_saved['state_line_ids'] = 'partner_changed'
     res = {
         'value': {
             'line_ids': [(6, 0, list_ids)],
             'context_saved': str(context_saved),
         },
         'domain': {'line_ids': domain},
     }
     conflicts = self._get_account_conflicts(
         cr, uid, list_ids, context=context
     )
     if conflicts:
         res['warning'] = {
             'title': _('Warning'),
             'message': self._print_conflicts(
                 cr, uid, conflicts, context=context
             )
         }
     return res
Example #6
0
def test_datagen_getitem_train():

    datagen = DataGen(conf=default_conf, split='train')
    item = datagen[0]
    load_dict = leval(item['load_dict'])

    assert (item['label'] == load_dict['class'])
    assert (load_dict['pos'] == 0)
Example #7
0
def read_scanners():
    scanners = []
    for line in sys.stdin.read().strip().splitlines():
        if ',' in line:
            sc.beacons.append(Point(*leval(line)))
        elif 'scanner' in line:
            sc = Scanner()
            scanners.append(sc)
    return scanners
Example #8
0
def readAfdFromFile(filename):
	f=open(filename)
	states=list(leval(f.readline().strip()))
	sigma=list(f.readline().strip())
	delta=[]
	for i in range(len(states)):
		temp=leval(f.readline().strip())
		if len(temp)!=len(sigma):raise RuntimeError("invalid delta on "+filename)
		for t in temp:
			if t not in states:
				raise RuntimeError("invalid delta on "+filename)
		delta.append(list(temp))
	initial=leval(f.readline().strip())
	if initial not in states:raise RuntimeError("invalid initial on "+filename)
	final=leval(f.readline().strip())
	final=list(final)if type(final)==tuple else [final]
	for temp in final:
		if temp not in states:raise RuntimeError("invalid final on "+filename)
	f.close()
	return AFD(states,sigma,delta,initial,final)
def get_label(exp, src):
    settings = None
    with open(
            os.path.join(REP_PATH, src + '_rep',
                         src + '_' + str(exp) + '_log.txt'), 'r') as f:
        fl = f.readlines()
        algorithm = fl[4][:-1]
        shape = fl[8][:-1]
        settings = leval(fl[12])
        if 'random_state' in settings:
            del settings['random_state']

    return algorithm + ' trained on (' + shape + ') with: ' + str(settings)
Example #10
0
 def loads(cls, input_str: str):
     null = None
     pcre.enable_re_template_mode()
     json = pcre.match(cls.__pattern, input_str)
     if input_str.isdigit() or (input_str.startswith('-') and input_str[1:].isdigit()):
         return input_str
     if json is None:
         if input_str.startswith('"') and input_str.endswith('"'):
             return leval(input_str)
         raise SyntaxError('Invalid json format')
     else:
         json = json.group(0)
         res: dict = eval(json, {}, {'null': null})
     return res
Example #11
0
  def __init__(self,assets_file):
    self.assets_file = assets_file
    with open(assets_file,'r') as f:
      main_dict = leval(f.read())
    stocks = array([ Stock(**s) for s in main_dict['stocks'] ])
    moneys = array([ Money(**m) for m in main_dict['moneys'] ])

    self.tickers,self.stocks = self.reduce_assets(stocks)
    self.exticks,self.moneys = self.reduce_assets(moneys)
    #self.moneys[where(self.exticks=='ETHBTC')[0]] *= 650

    self.update_asset(self.stocks)
    self.update_asset(self.moneys)

    self.assets = [ self.stocks, self.moneys ]
    self.update()
    def onchange_line_ids(
        self, cr, uid, ids, selector, partner_id,
        line_ids, context_saved, context=None
    ):
        """ print the line selected or the line filtered by state
            4 states : 'entering_wizard'
                       'view_changed'
                       'partner_changed
                       'add_del_element' = None
        """

        context_saved = leval(context_saved)

        # We cut the ids from the magic tuple [(6, False, [ids])]
        list_ids = line_ids[0][2]

        res = {}

        # and we store the ids in the many2many
        # depending on the state we are.
        if context_saved['state_line_ids'] == 'entering_wizard':
            res = self.__entering_wizard(cr, uid, ids, list_ids, context_saved)
        elif not context_saved['state_line_ids']:
            res = self.__add_del_element(
                cr, uid, ids, selector, partner_id, list_ids, context_saved
            )
        elif context_saved['state_line_ids'] == 'partner_changed':
            res = self.__partner_changed(cr, uid, ids, list_ids, context_saved)
        elif context_saved['state_line_ids'] == 'view_changed':
            res = self.__view_changed(cr, uid, ids, list_ids, context_saved)
        if context_saved['lines_by_partner']:
            res['value'].update(
                self.__compute_sum_and_nb_lines(cr, uid, context_saved)
            )
        else:
            res['value'].update(
                {'nb_lines': 0, 'total_amount': 0.0}
            )

        res['value']['context_saved'] = str(
            res.get('context_saved', context_saved)
        )

        return res
Example #13
0
    def onchange_line_ids(self,
                          cr,
                          uid,
                          ids,
                          selector,
                          partner_id,
                          line_ids,
                          context_saved,
                          context=None):
        """ print the line selected or the line filtered by state
            4 states : 'entering_wizard'
                       'view_changed'
                       'partner_changed
                       'add_del_element' = None
        """

        context_saved = leval(context_saved)

        # We cut the ids from the magic tuple [(6, False, [ids])]
        list_ids = line_ids[0][2]

        res = {}

        # and we store the ids in the many2many
        # depending on the state we are.
        if context_saved['state_line_ids'] == 'entering_wizard':
            res = self.__entering_wizard(cr, uid, ids, list_ids, context_saved)
        elif not context_saved['state_line_ids']:
            res = self.__add_del_element(cr, uid, ids, selector, partner_id,
                                         list_ids, context_saved)
        elif context_saved['state_line_ids'] == 'partner_changed':
            res = self.__partner_changed(cr, uid, ids, list_ids, context_saved)
        elif context_saved['state_line_ids'] == 'view_changed':
            res = self.__view_changed(cr, uid, ids, list_ids, context_saved)
        if context_saved['lines_by_partner']:
            res['value'].update(
                self.__compute_sum_and_nb_lines(cr, uid, context_saved))
        else:
            res['value'].update({'nb_lines': 0, 'total_amount': 0.0})

        res['value']['context_saved'] = str(
            res.get('context_saved', context_saved))

        return res
Example #14
0
	def update(self):
		"Call this regularly."
		while True:
			e = self.host.service()
			
			if not e:
				break
			
			if e.type() == 'receive':
				try:
					self.message(leval(e.data().decode()))
				except:
					traceback.print_exc()
			elif e.type() == 'connect':
				self.connected = True
				while self.queue:
					self.send(self.queue.pop(0))
			elif e.type() == 'disconnect':
				self.connected = False
			else:
				break
Example #15
0
    def onchange_view_selector(self,
                               cr,
                               uid,
                               ids,
                               selector,
                               partner_id,
                               context_saved,
                               context=None):
        context_saved = leval(context_saved)
        if context_saved['state_line_ids'] == 'entering_wizard':
            context_saved['state_line_ids'] = None
            return {'value': {'context_saved': str(context_saved)}}
        domain = {}
        value = {}
        if not selector:
            selector = 'complete'
            value['view_selection'] = 'complete'
        list_ids = []
        if selector == 'complete':
            list_ids = list(
                itertools.chain.from_iterable(
                    context_saved['lines_by_partner'].values()))
            partner_id = None
        else:
            if (context_saved['lines_by_partner'] and
                    partner_id != context_saved['lines_by_partner'].keys()[0]):
                partner_id = context_saved['lines_by_partner'].keys()[0]
            else:
                domain['line_ids'] = [('partner_id', '=', -1)]

        if list_ids:
            value['line_ids'] = [(6, 0, list_ids)]
        value['partner_id'] = partner_id

        context_saved['state_line_ids'] = 'view_changed'
        value['context_saved'] = str(context_saved)
        return {
            'value': value,
            'domain': domain,
        }
    def onchange_view_selector(
        self, cr, uid, ids, selector, partner_id, context_saved, context=None
    ):
        context_saved = leval(context_saved)
        if context_saved['state_line_ids'] == 'entering_wizard':
            context_saved['state_line_ids'] = None
            return {'value': {'context_saved': str(context_saved)}}
        domain = {}
        value = {}
        if not selector:
            selector = 'complete'
            value['view_selection'] = 'complete'
        list_ids = []
        if selector == 'complete':
            list_ids = list(
                itertools.chain.from_iterable(
                    context_saved['lines_by_partner'].values()
                )
            )
            partner_id = None
        else:
            if (
                context_saved['lines_by_partner'] and
                partner_id != context_saved['lines_by_partner'].keys()[0]
            ):
                partner_id = context_saved['lines_by_partner'].keys()[0]
            else:
                domain['line_ids'] = [('partner_id', '=', -1)]

        if list_ids:
            value['line_ids'] = [(6, 0, list_ids)]
        value['partner_id'] = partner_id

        context_saved['state_line_ids'] = 'view_changed'
        value['context_saved'] = str(context_saved)
        return {
            'value': value,
            'domain': domain,
        }
Example #17
0
    def __init__(self, input_file=None):
        self.Documentation = OrderedDict()
        self.UserOptions = OrderedDict()
        self.ActiveOptions = OrderedDict()
        self.ForcedOptions = OrderedDict()
        self.ForcedWarnings = OrderedDict()
        self.InactiveOptions = OrderedDict()
        self.InactiveWarnings = OrderedDict()

        # still need to read the file to build the dictionary
        if input_file != None:
            for line in open(input_file).readlines():
                line = sub('#.*$', '', line.strip())
                s = line.split()
                if len(s) > 0:
                    # Options are case insensitive
                    key = s[0].lower()
                    try:
                        val = leval(line.replace(s[0], '', 1).strip())
                    except:
                        val = str(line.replace(s[0], '', 1).strip())
                    self.UserOptions[key] = val
def io_proxy_wado(
    api_key, api_key_prefix, project_id, study=None, series=None, instance=None
):
    """
    Request wrapper for io-proxy api (https://{instance}/io-proxy/docs#/)

    Args:
        api_key (str): Full instance api-key
        api_key_prefix (str): Type of user (e.g. 'scitran-user')
        project_id (str): Project ID to inquire
        study (str, optional): DICOM StudyUID. Defaults to None.
        series (str, optional): DICOM SeriesUID. Defaults to None.
        instance (str, optional): DICOM InstanceUID. Defaults to None.

    Returns:
        dict/list: A dictionary for dicom tags or a list of dictionaries with dicom tags
    """
    base_url = Path(api_key.split(":")[0])
    base_url /= "io-proxy/wado"
    base_url /= "projects/" + project_id
    if study:
        base_url /= "studies/" + study
    if series:
        base_url /= "series/" + series
        base_url /= "instances"
    if instance:
        base_url /= instance
        base_url /= "tags"
    base_url = "https://" + str(base_url)

    headers = {
        "Authorization": api_key_prefix + " " + api_key,
        "accept": "application/json",
    }

    req = requests.get(base_url, headers=headers)

    return leval(req.text)
Example #19
0
	def update(self):
		"Call this regularly."
		while True:
			e = self.host.service()
			
			if not e:
				break
			
			if e.type() == 'receive':
				try:
					self.clients[e.who().id].message(leval(e.data().decode()))
				except:
					traceback.print_exc()
			elif e.type() == 'connect':
				c = self.peerFactory(self, e.who())
				self.clients[e.who().id] = c
				self.connected(c)
			elif e.type() == 'disconnect':
				if e.who().id in self.clients:
					self.disconnected(self.clients[e.who().id])
					del self.clients[e.who().id]
			else:
				break
Example #20
0
 def onchange_partner_id(self,
                         cr,
                         uid,
                         ids,
                         partner_id,
                         context_saved,
                         context=None):
     context_saved = leval(context_saved)
     domain = deepcopy(move_line_domain)
     if (context_saved['state_line_ids'] == 'entering_wizard'
             or not partner_id):
         return {'value': {}, 'domain': {'line_ids': domain}}
     domain.append(('partner_id', '=', partner_id))
     list_ids = context_saved['lines_by_partner'][partner_id]
     context_saved['state_line_ids'] = 'partner_changed'
     res = {
         'value': {
             'line_ids': [(6, 0, list_ids)],
             'context_saved': str(context_saved),
         },
         'domain': {
             'line_ids': domain
         },
     }
     conflicts = self._get_account_conflicts(cr,
                                             uid,
                                             list_ids,
                                             context=context)
     if conflicts:
         res['warning'] = {
             'title':
             _('Warning'),
             'message':
             self._print_conflicts(cr, uid, conflicts, context=context)
         }
     return res
Example #21
0
def write(info, patches, symbols_thumb, symbols_ram, rom_path, out_s, out_ld):

	rombegin = leval(info["rom"][0])
	romend   = leval(info["rom"][1])

	events = []
	free_placement = []

	for patch in patches:
		original = patch.original

		if original.size is not None and patch.size > original.size:
			trampoline = Trampoline(original)

			if trampoline.size > original.size:
				print("Patch {} and trampoline are too big for gap at {:08x} ({} > {} > {}).".format(
					patch, original.addr, patch.size, trampoline.size, original.size))
				raise Exception("No space for trampoline")

			events.append(trampoline)
			original.addr = None

		if original.addr is None:
			free_placement.append(patch)

		else:
			events.append(patch)

	for addr, name in symbols_thumb:
		events.append(EntrypointThumb(name, addr))

	gapstart = leval(info["gap"][0])
	gapend   = leval(info["gap"][1])

	regions = [
		Region(addr=rombegin, size=gapstart-rombegin),
		Region(addr=gapstart, size=gapend  -gapstart, gap=True),
		Region(addr=gapend,   size=romend  -gapend)
	]

	print("MEMORY {", file=out_ld)
	print("\tROM (rx) : ORIGIN = 0x{:08x}, LENGTH = 0x{:x}".format(rombegin, romend-rombegin), file=out_ld)
	print("}", file=out_ld)

	events.extend(regions)

	events.sort(key=lambda thing: (thing.addr, 1-isinstance(thing, Region)))

	section = object()
	in_region = None

	print('.thumb', file=out_s)

	def incbin(begin, end):
		nonlocal section
		assert begin <= end, "[{:08x}:{:08x}]".format(begin, end)

		if section is None:
			section = "s{:08x}".format(begin)
			print('.section', section, ', "ax"', file=out_s)
			# print("\t\t. = 0x{:08x};".format(begin), file=out_ld)
			print("\t\t*({})".format(section), file=out_ld)

		if end-begin > 0:
			print('\t.incbin "{}",{},{}'.format(rom_path, begin-rombegin, end-begin), file=out_s)

	def close_region():
		nonlocal in_region
		print("\t}", file=out_ld)
		in_region = None

	def do_gap(event):
		nonlocal addr
		addr = event.addr
		for p in free_placement:
			p.addr = addr
			addr += p.size
			print(p.write_ld(), file=out_ld)

		print("""
		*(.text .stub .text.* .gnu.linkonce.t.*)
		*(.data .data.* .gnu.linkonce.d.*)
		SORT(CONSTRUCTORS)
		*(.bss .bss.* .gnu.linkonce.b.*)
		*(.rodata*) /* this should be empty */
		*(COMMON)""", file=out_ld)


	#	. = 0x08000000;
	#	* (s08000000)
	#	. = 0x08000111;
	#	* (.text.npc_coords_shift)
	#	. = 0x08000121;
	#	* (s08000121)

	rnum = 0
	print("SECTIONS {", file=out_ld)

	for addr, name in symbols_ram:
		print("\t{} = 0x{:08x};".format(name, addr), file=out_ld)
	print("", file=out_ld)

	addr = rombegin
	in_gap = False
	for event in events:
		evaddr = event.addr
		#print("{:08x}/{:08x}/{}/{}".format(addr, evaddr, type(event), vars(event)))

		if in_gap:
			print("\t\t/* remaining functions here */", file=out_ld)
			do_gap(event)
			in_gap = False
			pass
		else:
			incbin(addr, evaddr)

			print(event.write(), file=out_s)
			if hasattr(event, "write_ld"):
				print(event.write_ld(), file=out_ld)

			if isinstance(event, SectionBreaker):
				section = None

		if isinstance(event, Region):
			if "new_region":
				if not in_region:
					in_region = event
					print("\t.text.{} 0x{:08x} : {{".format(rnum, evaddr), file=out_ld)
					rnum += 1

				print("\t\t. = 0x{:08x};".format(evaddr-in_region.addr), file=out_ld)

				if event.gap:
					in_gap = True

			else:
				if in_region and not in_region.gap:
					close_region()

				in_region = event

				if not in_region.gap:
					print("\t.text.{} 0x{:08x} : {{".format(rnum, evaddr), file=out_ld)
					rnum += 1

		if isinstance(event, Region) and event.gap is False:
			addr = evaddr
		else:
			addr = evaddr + event.size

	incbin(addr, romend)
	close_region()


	print("""
	/* DWARF debug sections.
	 Symbols in the DWARF debugging sections are relative to the beginning
	 of the section so we begin them at 0.  */
	/* DWARF 1 */
	.debug          0 : { *(.debug) }
	.line           0 : { *(.line) }
	/* GNU DWARF 1 extensions */
	.debug_srcinfo  0 : { *(.debug_srcinfo) }
	.debug_sfnames  0 : { *(.debug_sfnames) }
	/* DWARF 1.1 and DWARF 2 */
	.debug_aranges  0 : { *(.debug_aranges) }
	.debug_pubnames 0 : { *(.debug_pubnames) }
	/* DWARF 2 */
	.debug_info     0 : { *(.debug_info .gnu.linkonce.wi.*) }
	.debug_abbrev   0 : { *(.debug_abbrev) }
	.debug_line     0 : { *(.debug_line) }
	.debug_frame    0 : { *(.debug_frame) }
	.debug_str      0 : { *(.debug_str) }
	.debug_loc      0 : { *(.debug_loc) }
	.debug_macinfo  0 : { *(.debug_macinfo) }
	""", file=out_ld)

	print("}", file=out_ld)
Example #22
0
    def good_to_pay(self, cr, uid, ids, context=None):

        aml_osv = self.pool['account.move.line']
        avl_osv = self.pool['account.voucher.line']
        voucher_osv = self.pool['account.voucher']
        journal_osv = self.pool['account.journal']

        supplier_to_voucher_map = dict()
        voucher_amounts = dict()

        action = {'type': 'ir.actions.act_window_close'}

        for form in self.read(cr, uid, ids, context=context):

            conflicts = self._get_account_conflicts(cr,
                                                    uid,
                                                    form['line_ids'],
                                                    context=context)
            if conflicts:
                raise osv.except_osv(
                    _('Error'),
                    self._print_conflicts(cr, uid, conflicts, context=context))

            context_saved = leval(form['context_saved'])
            # Both debit and credit are allowed, no checks anymore
            auto = form['generate_report']
            active_ids = list(
                itertools.chain.from_iterable(
                    context_saved['lines_by_partner'].values()))
            for aml in aml_osv.browse(cr, uid, active_ids, context=context):

                # first we need to make sure the line is acceptable to be
                # used in a voucher (ie: account is marked as payable

                if aml.account_id.type not in ('payable', 'receivable'):
                    msg = msg_invalid_line_type % aml.account_id.type
                    raise osv.except_osv(_('Error!'), msg)

                if (aml.account_id.type == 'payable' and
                    (not aml.partner_id or not aml.partner_id.supplier)):
                    msg = msg_invalid_partner_type_supplier % aml.partner_id.name
                    raise osv.except_osv(_('Error!'), msg)
                if (aml.account_id.type == 'receivable' and
                    (not aml.partner_id or not aml.partner_id.customer)):
                    msg = msg_invalid_partner_type_customer % aml.partner_id.name
                    raise osv.except_osv(_('Error!'), msg)

                if aml.reconcile_id:
                    msg = msg_already_reconciled % aml.name
                    raise osv.except_osv(_('Error!'), msg)

                partner_id = aml.partner_id.id

                if partner_id not in supplier_to_voucher_map:
                    # we don't have a voucher for this supplier yet...
                    # just create a new one for our own use
                    vals = dict()
                    vals['partner_id'] = partner_id
                    # id is stored in fist column, name in second column
                    vals['journal_id'] = form['journal_id'][0]
                    if aml.account_id.type in ('payable'):
                        vals['type'] = 'payment'
                    if aml.account_id.type in ('receivable'):
                        vals['type'] = 'receipt'
                    journal = journal_osv.browse(cr, uid, vals['journal_id'])
                    vals['amount'] = 0.0
                    vals['payment_option'] = 'without_writeoff'
                    # Define "pre_line" to ensure the voucher is aware of the
                    # lines we are going to add; otherwise it doesn't show all
                    # of them.
                    vals['pre_line'] = True

                    if not journal.default_credit_account_id or \
                            not journal.default_debit_account_id:
                        raise osv.except_osv(
                            _('Error!'),
                            msg_define_dc_on_journal % journal.name)

                    account_id = journal.default_credit_account_id.id or \
                        journal.default_debit_account_id.id

                    vals['account_id'] = account_id

                    bank_osv = self.pool['res.partner.bank']
                    bank_id = bank_osv.search(
                        cr,
                        uid, [('partner_id', '=', partner_id)],
                        context=context)

                    if bank_id:
                        vals['partner_bank_id'] = bank_id[0]

                    voucher_id = voucher_osv.create(cr,
                                                    uid,
                                                    vals,
                                                    context=context)

                    supplier_to_voucher_map[partner_id] = voucher_id
                    voucher_amounts[voucher_id] = 0.0

                else:
                    voucher_id = supplier_to_voucher_map[partner_id]

                # now that we have a voucher id we'll add our line to it
                line_vals = dict()
                line_vals['name'] = aml.name
                line_vals['voucher_id'] = voucher_id
                # Voucher lines must use the same account as the move lines,
                # in order to be able to reconcile them with the move lines
                # created during the validation of the voucher.
                line_vals['account_id'] = aml.account_id.id
                line_vals['type'] = 'dr' if aml.credit else 'cr'
                line_vals['move_line_id'] = aml.id

                avl_id = avl_osv.create(cr, uid, line_vals, context=context)
                avl = avl_osv.browse(cr, uid, avl_id, context=context)

                line_vals2 = dict()
                line_vals2['reconcile'] = True
                line_vals2['amount'] = avl.amount_unreconciled

                avl_osv.write(cr, uid, [avl_id], line_vals2)

                # Add credits, substract debits.
                voucher_amounts[voucher_id] += avl.amount_unreconciled * (
                    1 if aml.credit else -1) * (1 if aml.account_id.type
                                                == 'payable' else -1)

            # once every voucher is finished we recompute the voucher totals
            # and write them back to the vouchers
            for voucher_id in voucher_amounts.keys():
                voucher_osv.write(cr, uid, [voucher_id],
                                  {'amount': voucher_amounts[voucher_id]})

            if auto:
                action = self._generate_report(cr, uid, voucher_amounts.keys(),
                                               context)

        return action
Example #23
0
File: show.py Project: jrmyp/zeno
def rline(l):
    return leval(l[:-1])
Example #24
0
def write(info, patches, symbols_thumb, symbols_ram, rom_path, out_s, out_ld):

    rombegin = leval(info["rom"][0])
    romend = leval(info["rom"][1])

    events = []
    free_placement = []

    for patch in patches:
        original = patch.original

        if original.size is not None and patch.size > original.size:
            trampoline = Trampoline(original)

            if trampoline.size > original.size:
                print(
                    "Patch {} and trampoline are too big for gap at {:08x} ({} > {} > {})."
                    .format(patch, original.addr, patch.size, trampoline.size,
                            original.size))
                raise Exception("No space for trampoline")

            events.append(trampoline)
            original.addr = None

        if original.addr is None:
            free_placement.append(patch)

        else:
            events.append(patch)

    for addr, name in symbols_thumb:
        events.append(EntrypointThumb(name, addr))

    gapstart = leval(info["gap"][0])
    gapend = leval(info["gap"][1])

    regions = [
        Region(addr=rombegin, size=gapstart - rombegin),
        Region(addr=gapstart, size=gapend - gapstart, gap=True),
        Region(addr=gapend, size=romend - gapend)
    ]

    print("MEMORY {", file=out_ld)
    print("\tROM (rx) : ORIGIN = 0x{:08x}, LENGTH = 0x{:x}".format(
        rombegin, romend - rombegin),
          file=out_ld)
    print("}", file=out_ld)

    events.extend(regions)

    events.sort(key=lambda thing: (thing.addr, 1 - isinstance(thing, Region)))

    section = object()
    in_region = None

    print('.thumb', file=out_s)

    def incbin(begin, end):
        nonlocal section
        assert begin <= end, "[{:08x}:{:08x}]".format(begin, end)

        if section is None:
            section = ".rom.{:08x}".format(begin)
            print('.section', section, ', "ax"', file=out_s)
            if confirm:
                print("\t\t. = 0x{:08x};".format(begin), file=out_ld)
            print("\t\t*({})".format(section), file=out_ld)

        if end - begin > 0:
            print('\t.incbin "{}",{},{}'.format(rom_path, begin - rombegin,
                                                end - begin),
                  file=out_s)

    def close_region():
        nonlocal in_region
        print("\t}", file=out_ld)
        in_region = None

    def do_gap(event):
        nonlocal addr
        addr = event.addr
        for p in free_placement:
            p.addr = addr
            addr += p.size
            print(p.write_ld(), file=out_ld)

        print("""
		*(.text .stub .text.* .gnu.linkonce.t.*)
		*(.data .data.* .gnu.linkonce.d.*)
		SORT(CONSTRUCTORS)
		*(.bss .bss.* .gnu.linkonce.b.*)
		*(.rodata*) /* this should be empty */
		*(COMMON)""",
              file=out_ld)

    #	. = 0x08000000;
    #	* (s08000000)
    #	. = 0x08000111;
    #	* (.text.npc_coords_shift)
    #	. = 0x08000121;
    #	* (s08000121)

    rnum = 0
    print("SECTIONS {", file=out_ld)

    for addr, name in symbols_ram:
        print("\t{} = 0x{:08x};".format(name, addr), file=out_ld)
    print("", file=out_ld)

    addr = rombegin
    in_gap = False
    for event in events:
        evaddr = event.addr
        #print("{:08x}/{:08x}/{}/{}".format(addr, evaddr, type(event), vars(event)))

        if in_gap:
            print("\t\t/* remaining functions here */", file=out_ld)
            do_gap(event)
            in_gap = False
            pass
        else:
            incbin(addr, evaddr)

            print(event.write(), file=out_s)
            if hasattr(event, "write_ld"):
                print(event.write_ld(), file=out_ld)

            if isinstance(event, SectionBreaker):
                section = None

        if isinstance(event, Region):
            if "new_region":
                if not in_region:
                    in_region = event
                    print("\t.text.{} 0x{:08x} : {{".format(rnum, evaddr),
                          file=out_ld)
                    rnum += 1

                print("\t\t. = 0x{:08x};".format(evaddr - in_region.addr),
                      file=out_ld)

                if event.gap:
                    in_gap = True

            else:
                if in_region and not in_region.gap:
                    close_region()

                in_region = event

                if not in_region.gap:
                    print("\t.text.{} 0x{:08x} : {{".format(rnum, evaddr),
                          file=out_ld)
                    rnum += 1

        if isinstance(event, Region) and event.gap is False:
            addr = evaddr
        else:
            addr = evaddr + event.size

    incbin(addr, romend)
    close_region()

    print("""
	/* DWARF debug sections.
	 Symbols in the DWARF debugging sections are relative to the beginning
	 of the section so we begin them at 0.  */
	/* DWARF 1 */
	.debug          0 : { *(.debug) }
	.line           0 : { *(.line) }
	/* GNU DWARF 1 extensions */
	.debug_srcinfo  0 : { *(.debug_srcinfo) }
	.debug_sfnames  0 : { *(.debug_sfnames) }
	/* DWARF 1.1 and DWARF 2 */
	.debug_aranges  0 : { *(.debug_aranges) }
	.debug_pubnames 0 : { *(.debug_pubnames) }
	/* DWARF 2 */
	.debug_info     0 : { *(.debug_info .gnu.linkonce.wi.*) }
	.debug_abbrev   0 : { *(.debug_abbrev) }
	.debug_line     0 : { *(.debug_line) }
	.debug_frame    0 : { *(.debug_frame) }
	.debug_str      0 : { *(.debug_str) }
	.debug_loc      0 : { *(.debug_loc) }
	.debug_macinfo  0 : { *(.debug_macinfo) }
	""",
          file=out_ld)

    print("}", file=out_ld)
Example #25
0
        m.setObjective(s)
        m.optimize()

        assert m.getStatus() == "optimal"
        if verbose:
            for v in m.getVars():
                print("%s %d" % (v,m.getVal(v)))
            print("%d%%2 == %d?" % (m.getVal(x), m.getVal(s)))
            print(m.getVal(s) == m.getVal(x)%2)

        xval = m.getVal(x)
        sval = m.getVal(s)
        sstr = sdic[sval]
        print("%d is %s" % (xval, sstr))
    except (AssertionError, TypeError):
        print("%s is neither even nor odd!" % number.__repr__())

if __name__ == "__main__":
    import sys
    from ast import literal_eval as leval
    example_values = [0, 1, 1.5, "hallo welt", 20, 25, -101, -15., -10, -int(2**31), int(2**31-1), int(2**63)-1]
    try:
        try:
            n = leval(sys.argv[1])
        except ValueError:
            n = sys.argv[1]
        parity(n)
    except IndexError:
        for n in example_values:
            parity(n)
Example #26
0
    finally:
        if verbose:
            print(80*"*")
            print("")
    return sval

if __name__ == "__main__":
    """
    If positional arguments are given:
        the parity check is performed on each of them
    Else:
        the parity check is performed on each of the default example values
    """
    import sys
    from ast import literal_eval as leval
    try:
        # check parity for each positional arguments
        sys.argv[1]
        values = sys.argv[1:]
    except IndexError:
        # check parity for each default example value
        values = example_values
    # format lenght, cosmetics
    fmtlen = max([len(fmt) for fmt in pfmt(values,width=1).split('\n')])
    for value in values:
        try:
            n = leval(value)
        except (ValueError, SyntaxError): # for numbers or str w/ spaces
            n = value
        parity(n)
Example #27
0
            for v in m.getVars():
                print("%s %d" % (v, m.getVal(v)))
            print("%d%%2 == %d?" % (m.getVal(x), m.getVal(s)))
            print(m.getVal(s) == m.getVal(x) % 2)

        xval = m.getVal(x)
        sval = m.getVal(s)
        sstr = sdic[sval]
        print("%d is %s" % (xval, sstr))
    except (AssertionError, TypeError):
        print("%s is neither even nor odd!" % number.__repr__())


if __name__ == "__main__":
    import sys
    from ast import literal_eval as leval
    example_values = [
        0, 1, 1.5, "hallo welt", 20, 25, -101, -15., -10, -int(2**31),
        int(2**31 - 1),
        int(2**63) - 1
    ]
    try:
        try:
            n = leval(sys.argv[1])
        except ValueError:
            n = sys.argv[1]
        parity(n)
    except IndexError:
        for n in example_values:
            parity(n)
Example #28
0
        # import model settings
        settings = {}

        if exp != -1:
            with open(EXP_FILE) as f:
                fl = f.readlines()

                for i in range(len(fl)):
                    l = fl[i]
                    if l == ('{}:\n'.format(str(exp))):
                        algorithm = fl[i + 1][:-1]
                        if algorithm not in alg_list:
                            raise ValueError(
                                'Please enter valid algorithm for experiment {}'
                                .format(exp))
                        settings = leval(fl[i + 2])
                        if type(settings) != dict:
                            raise ValueError(
                                'Please enter valid dict for experiment {}'.
                                format(exp))

        if len(settings) == 0:
            print(
                'continue using default model settings (adds random_state=2364)'
            )

        # initialize model
        if algorithm == 'umap':
            from umap import UMAP
            settings['random_state'] = 2364
            embedding = UMAP(**settings)
Example #29
0
    # terminal interface
    if len(args) > 0 or options.configfile:
        from os import listdir
        from os.path import isfile, abspath, join, splitext

        extraparams = {}

        # parse configuration file
        if options.configfile:
            import ConfigParser
            from ast import literal_eval as leval

            config = ConfigParser.RawConfigParser()
            config.read(options.configfile)

            getcfg = lambda x: leval(config.get('params', x))

            args = [config.get('paths', 'inputdir')]
            options.filename = config.get('paths', 'geojsonfile')
            options.nfiles = getcfg('filenumber')
            options.toLines = getcfg('points')
            options.toPoints = getcfg('lines')

            if config.has_option('paths', 'geojsonmeans'):
                options.fmeans = config.get('paths', 'geojsonmeans')
            if config.has_option('paths', 'geojsonmedians'):
                options.fmedians = config.get('paths', 'geojsonmedians')

            present = set(['size', 'newest', 'random']) \
                .intersection(config.options('params'))
            for opt in present:
    def good_to_pay(self, cr, uid, ids, context=None):

        aml_osv = self.pool['account.move.line']
        avl_osv = self.pool['account.voucher.line']
        voucher_osv = self.pool['account.voucher']
        journal_osv = self.pool['account.journal']

        supplier_to_voucher_map = dict()
        voucher_amounts = dict()

        action = {'type': 'ir.actions.act_window_close'}

        for form in self.read(cr, uid, ids, context=context):

            conflicts = self._get_account_conflicts(
                cr, uid, form['line_ids'], context=context
            )
            if conflicts:
                raise osv.except_osv(
                    _('Error'),
                    self._print_conflicts(cr, uid, conflicts, context=context)
                )

            context_saved = leval(form['context_saved'])
            # Both debit and credit are allowed, no checks anymore
            auto = form['generate_report']
            active_ids = list(
                itertools.chain.from_iterable(
                    context_saved['lines_by_partner'].values()
                )
            )
            for aml in aml_osv.browse(
                    cr, uid, active_ids, context=context):

                # first we need to make sure the line is acceptable to be
                # used in a voucher (ie: account is marked as payable

                if aml.account_id.type not in ('payable', 'receivable'):
                    msg = msg_invalid_line_type % aml.account_id.type
                    raise osv.except_osv(_('Error!'), msg)

                if (
                    aml.account_id.type == 'payable'
                    and (not aml.partner_id or not aml.partner_id.supplier)
                ):
                    msg = msg_invalid_partner_type_supplier % aml.partner_id.name
                    raise osv.except_osv(_('Error!'), msg)
                if (
                    aml.account_id.type == 'receivable'
                    and (not aml.partner_id or not aml.partner_id.customer)
                ):
                    msg = msg_invalid_partner_type_customer % aml.partner_id.name
                    raise osv.except_osv(_('Error!'), msg)

                if aml.reconcile_id:
                    msg = msg_already_reconciled % aml.name
                    raise osv.except_osv(_('Error!'), msg)

                partner_id = aml.partner_id.id

                if partner_id not in supplier_to_voucher_map:
                    # we don't have a voucher for this supplier yet...
                    # just create a new one for our own use
                    vals = dict()
                    vals['partner_id'] = partner_id
                    # id is stored in fist column, name in second column
                    vals['journal_id'] = form['journal_id'][0]
                    if aml.account_id.type in ('payable'):
                        vals['type'] = 'payment'
                    if aml.account_id.type in ('receivable'):
                        vals['type'] = 'receipt'
                    journal = journal_osv.browse(
                        cr, uid, vals['journal_id'])
                    vals['amount'] = 0.0
                    vals['payment_option'] = 'without_writeoff'
                    # Define "pre_line" to ensure the voucher is aware of the
                    # lines we are going to add; otherwise it doesn't show all
                    # of them.
                    vals['pre_line'] = True

                    if not journal.default_credit_account_id or \
                            not journal.default_debit_account_id:
                        raise osv.except_osv(
                            _('Error!'),
                            msg_define_dc_on_journal % journal.name)

                    account_id = journal.default_credit_account_id.id or \
                        journal.default_debit_account_id.id

                    vals['account_id'] = account_id

                    bank_osv = self.pool['res.partner.bank']
                    bank_id = bank_osv.search(
                        cr, uid, [('partner_id', '=', partner_id)],
                        context=context
                    )

                    if bank_id:
                        vals['partner_bank_id'] = bank_id[0]

                    voucher_id = voucher_osv.create(cr, uid, vals,
                                                    context=context)

                    supplier_to_voucher_map[partner_id] = voucher_id
                    voucher_amounts[voucher_id] = 0.0

                else:
                    voucher_id = supplier_to_voucher_map[partner_id]

                # now that we have a voucher id we'll add our line to it
                line_vals = dict()
                line_vals['name'] = aml.name
                line_vals['voucher_id'] = voucher_id
                # Voucher lines must use the same account as the move lines,
                # in order to be able to reconcile them with the move lines
                # created during the validation of the voucher.
                line_vals['account_id'] = aml.account_id.id
                line_vals['type'] = 'dr' if aml.credit else 'cr'
                line_vals['move_line_id'] = aml.id

                avl_id = avl_osv.create(cr, uid, line_vals, context=context)
                avl = avl_osv.browse(cr, uid, avl_id, context=context)

                line_vals2 = dict()
                line_vals2['reconcile'] = True
                line_vals2['amount'] = avl.amount_unreconciled

                avl_osv.write(cr, uid, [avl_id], line_vals2)

                # Add credits, substract debits.
                voucher_amounts[voucher_id] += avl.amount_unreconciled * (
                    1 if aml.credit else -1
                ) * (
                    1 if aml.account_id.type == 'payable' else -1
                )

            # once every voucher is finished we recompute the voucher totals
            # and write them back to the vouchers
            for voucher_id in voucher_amounts.keys():
                voucher_osv.write(
                    cr, uid, [voucher_id],
                    {'amount': voucher_amounts[voucher_id]})

            if auto:
                action = self._generate_report(
                    cr, uid, voucher_amounts.keys(), context
                )

        return action
Example #31
0
        if verbose:
            print(80 * "*")
            print("")
    return sval


if __name__ == "__main__":
    """
    If positional arguments are given:
        the parity check is performed on each of them
    Else:
        the parity check is performed on each of the default example values
    """
    import sys
    from ast import literal_eval as leval
    try:
        # check parity for each positional arguments
        sys.argv[1]
        values = sys.argv[1:]
    except IndexError:
        # check parity for each default example value
        values = example_values
    # format lenght, cosmetics
    fmtlen = max([len(fmt) for fmt in pfmt(values, width=1).split('\n')])
    for value in values:
        try:
            n = leval(value)
        except (ValueError, SyntaxError):  # for numbers or str w/ spaces
            n = value
        parity(n)
Example #32
0
    # Get all input into one list
    for inFileName in filelist:
        sys.stderr.write("Processing file %s\n" % inFileName)
        inFile = open(inFileName, 'r')
        for sublist in inFile.readlines():
            flat_input.append(sublist)
        inFile.close()

    if args.task:
        # Read each element in the list as a dict and merge by "task"
        for tmpline in flat_input:
            line = tmpline.replace("\\n",
                                   "").replace("u\'",
                                               "\"").replace("\'", "\"")
            workflow = leval(line)  # Read as a dict
            tasks[workflow["task"]].append(workflow["steps"])

    if args.workflow:
        # Read each element in the list as a dict and merge by "task"
        for tmpline in flat_input:
            line = tmpline.replace("\\n",
                                   "").replace("u\'",
                                               "\"").replace("\'", "\"")
            workflow = leval(line)  # Read as a dict
            wf_name = re.findall('\/(.*?)\/', workflow["task"])[0]  #
            tasks[wf_name].append(workflow["steps"])

    else:
        # Read each element in the list as a dict and merge by "PrepID"
        for tmpline in flat_input: