def demo_sort_by_last_let(): util.banner('multiple calls to sort_by_last_letter redefine innner func') strparam = ['def', 'abc', 'ghi'] r1 = sort_by_last_letter(strparam) r2 = sort_by_last_letter(strparam) print('intput param: {} sort by last letter resilt {}'.format( strparam, r2))
def demo_decorator_on_class_method(): util.banner( 'IslandMakers method make_island is decorated with tracer global variable' ) im = IslandMaker('øy') isl1 = im.make_island('Python') pp('made island {}'.format(isl1))
def demo_counts_of_hello_calls(): util.banner('shows the counts of a func call through class decorator') hello('Micha') hello('Sveta') hello('Petya') hello('Grisha') print('hello was called {} times '.format(hello.count))
def demo_sorted(): util.banner('demo how to sort on 2nd family name using lamba' + \ 'func as a key param of built-int sorted') scientist = [ 'Marie Curie', 'Albert Einsterin', 'Niels Bohr', 'Isaac Newton', 'Charles Darwin' ] pp(sorted(scientist, key=lambda name: name.split()[-1]))
def demo_extened_call_syntax(): util.banner('prepare a list of args in a tuple before passing it to a func') def print_args(arg1, arg2, *args): pp(arg1) pp(arg2) pp(args) t=(11,12,13,14,15) print_args(*t) # NB! observe *t
def demo_func_with_arg_validation_via_deco(): util.banner('calling a function with 2nd arg validated through deco') l = create_list(0, 5) # ok pp('called create_list ok with result {}'.format(l)) util.starprint( 'next call fails with an !!expected!! exception message from a decorator' ) #ll = create_list(0,-5) # nok pp('ll = create_list(0,-5)')
def demo_distinct_timers(): util.banner('t1() and t2() are independent timers') t1 = make_timer() print('t1 elapsed first call {}'.format(t1())) t2 = make_timer() print('t2 elapsed 1st call {}'.format(t2())) print('t1 elapsed 2nd call {}'.format(t1())) time.sleep(1) print('t1 elapsed 3nd call {}'.format(t1())) time.sleep(2) print('t2 elapsed 2st call {}'.format(t2()))
def demo_trace(): util.banner('trace func demo. trace does not know about signature of traced function') def trace(f, *args, **kwargs): print('args =', args) print('kwargs = ', kwargs) result = f(*args, **kwargs) #this covers a signature of any func print("result = ", result) return result trace(int, "ff", base=16)
def demo_named_extended_args(): util.banner('tag func is called with a arbitrary number of attributes in signature') def tag(name, **kargs): result = '<' + name for key, value in kargs.items(): result += ' {k}="{v}"'.format(k=key, v=value) result += '>' return result pp(tag('img',src="monet.jpg", alt="Sunrise by C. Monet", border=1))
def demo_position_extended_args(): util.banner("hypervolume signature with 1 required an 2nd optional positional params") def hypervolume(length, *lengths): v = length for item in lengths: v *= item return v pp('line {}'.format(hypervolume(2))) pp('cube {}'.format(hypervolume(2,2,2))) pp('hupercube {}'.format(hypervolume(2,2,2,2))) pp('expected exception if hypervolume is called with no args: hypervolume()')
def demo_method_attributes(): util.banner('decorators can change __name__ and __doc__') print('non-decorated hello func dunder name: {}'.format(hello.__name__)) print('hello-decorated func dunder doc: {}'.format(hello.__doc__)) util.starprint('hello2 with noop deco,') print('hello2 func dunder name: {}'.format(hello2.__name__)) print('hello2 func dunder doc: {}'.format(hello2.__doc__)) util.starprint('hello3 with noopfixed deco,') print('hello3 func dunder name: {}'.format(hello3.__name__)) print('hello3 func dunder doc: {}'.format(hello3.__doc__))
def demo_factory_squares_cubes(): util.banner('raise_to closure returning more specialized functions') square = raise_to(2) cube = raise_to(3) divisor = raise_to(-1) util.starprint('different calls of raise_to produce different functions') pp(square) pp(cube) pp('square of 3: {}'.format(square(3))) pp('cube of 3: {}'.format(cube(3))) pp('divisor of 3: {}'.format(divisor(3)))
def demo_chain_decorator(): util.banner( 'decorators can be applied in chain (here tracer + escape_unicode') @tracer @escape_unicode def norwegian_island_maker(name): return name + 'øy' isl1 = norwegian_island_maker('Llama') isl2 = norwegian_island_maker('Troll') isl3 = norwegian_island_maker('Python') print("islands {} {} {}".format(isl1, isl2, isl3))
def main(): banner() if not platform.system() == 'Windows': error("Only Windows is supported") sys.exit(2) if len(sys.argv) <= 1: error("Usage: kira.py -img <img>") else: parser = argparse.ArgumentParser(description='Hide a Powershell Payload in an Image') parser.add_argument('-img', metavar='image_name', type=str, help='Image to inject payload in') args = parser.parse_args() requirementsCheck(args.img) cleanUp()
def demo_decor_with_instance(): util.banner('2 calls with tracing via an instance decorator') tracer = Trace() @tracer # observe the use of tracer name tracer is instance of Trace def rotate_list(l): return l[1:] + [l[0]] l = [1, 2, 3] lr = rotate_list(l) print('{} rotated {}'.format(l, lr)) tracer.enabled = False util.starprint('switched off tracing before next call') lrr = rotate_list(lr) print('{} rotated {}'.format(lr, lrr))
def demo_zip_transposed(): util.banner('zip transposing') util.starprint('zip initially') sunday = [12,14,15,15] monday = [13,14,14,14] tuesday = [10,11,11,10] for item in zip(sunday,monday,tuesday): pp(item) daily = [sunday,monday,tuesday] #list of list util.starprint('daily is a list of lists') pp(daily) util.starprint('zipping all sublists in daily') for item in zip(*daily): pp(item) util.starprint('now transposed compare it to daily') transposed = list(zip(*daily)) pp(transposed)
def make_dipo(dipole, dipole_types, coords): dip_type = dipole[0] dip_s = np.sqrt(dipole_types[dip_type][0]) dip_ori = dipole[1:] # Orient dipole along an interatomic axis if len(dip_ori) == 2: # -1 to adapt to Python numeration a = coords[dip_ori[0] - 1] b = coords[dip_ori[1] - 1] direction = (b - a) / np.linalg.norm(b - a) # dip = dip_s * direction dip = direction if u.verbosity >= 2: print(" Dipole oriented along %s." % ', '.join(u.compact_extended_list(dip_ori))) # Orient dipole along an interatomic axis and forming and angle # theta with the plane defined by 3 atoms elif len(dip_ori) == 4: # -1 to adapt to Python numeration a = coords[dip_ori[0] - 1] b = coords[dip_ori[1] - 1] c = coords[dip_ori[2] - 1] theta = dip_ori[3] # Generate a reference frame from point a, b, c # Our desired direction is b - a, i.e. the x axis # of this new ref frame. (see refframe function in # util.py ref = u.refframe(a, b, c) cartesian = np.eye(3) # Define transformation matrices T = np.dot(cartesian, ref.T) Ry = u.rot_mat_y(theta) # Ry is 4x4, reduce it to 3x3 Ry = Ry[:3,:3] x = cartesian[0] direction = np.dot(x, Ry) direction = np.dot(direction, T.T) # dip = dip_s * direction dip = direction if u.verbosity >= 2: print(" Dipole oriented out of the plane defined by %s by %5.2f degrees." % \ (', '.join(u.compact_extended_list(dip_ori[:-1])), theta)) else: print(u.banner(text='ERROR', ch='#', length=80)) print("Unrecognized number of parameters for dipole orientation.") print sys.exit() return dip
def parse_input(infile): '''Returns a Dictionary with dipole types, and a list of tuples for points of application of the dipoles. The keys of dipole types dictionary are the flags set ny the user in the input. Each value is a tuple. The first element of the tuple is a list containing the Dipolar Strength, the Excitation energy and the damping. The second element of the tuple is a flag defining the type of polarizability to calculate (electric or magnetic). The third element of the tuple if present only for magnetic polarizabilities and it is the bj coefficient. For application points, the data are tuples of 3 elements. Each tuple contains, as first element, the center expressed in terms of atom indexes and, as second element, the weight to be applied on the first element of the list. As third element, we have a list of dipoles to be applied in that point. The dipole is described through a list containing the dipole type and its orientation, in terms of atomic indexes.''' u.checkfile(infile) type_counter = 0 center_counter = 0 dipole_types = {} centers = [] with open(infile) as f: while True: line = f.readline() if not line: break if line.strip(): if line.startswith('#'): continue # Create Dipole Types Dictionary elif line.split()[0].lower() == 'type': type_counter += 1 type_flag = line.split()[1] # Try to read TYPE definition without optional keyword try: dipole = map(float, line.split()[2:]) pol_type = 'ele' dipole_types[type_flag] = (map(float, line.split()[2:]), pol_type) # Read TYPE definition with optional keyword except ValueError: pol_type = line.split()[-2] bj = float(line.split()[-1]) dipole_types[type_flag] = (map(float, line.split()[2:-2]), pol_type, bj) type_counter += 1 # Centers elif line.split()[0].lower() == 'center': center_counter += 1 weight = float(line.split()[1]) atom_idx = u.extend_compact_list(line.split()[2:]) # Adjust indices to Python's numeration atom_idx = map(lambda x: x - 1, atom_idx) data = f.readline().strip() # Retrieve dipoles applied in this center dipoles = [] while True: if not data or data.split()[0].lower() != 'dipole': break data = data.split() dip_type = [data[1]] dip_ori = data[2:] if len(dip_ori) == 2: dip_ori = u.extend_compact_list(dip_ori) elif len(dip_ori) > 2: theta = float(dip_ori[-1]) dip_ori = u.extend_compact_list(dip_ori[:-1]) dip_ori = dip_ori + [theta] dipole = dip_type + dip_ori dipoles.append(dipole) data = f.readline().strip() centers.append((atom_idx, weight, dipoles)) # Dipoles elif line.split()[0].lower() == 'dipole': if center_counter == 0: print(u.banner(text='ERROR', ch='#', length=80)) print print(" You defined a DIPOLE before assigning it a CENTER in %s" % infile) print sys.exit() # dipole_counter += 1 if type_counter == 0: print(u.banner(text='ERROR', ch='#', length=80)) print print(" No dipole TYPE has been defined in %s" % infile) print sys.exit() return dipole_types, centers
u.verbosity = args.verbosity nsteps = args.nsteps if nsteps: step = (args.max - args.min) / nsteps SpecRange = np.arange(args.min, args.max + 1, step) else: step = args.step SpecRange = np.arange(args.min, args.max + 1, step) nsteps = len(SpecRange) if u.verbosity >= 1: print print(u.banner(ch='#', length=80)) print(title) print(u.banner(ch='#', length=80)) print # # Recapitulation of input files # if u.verbosity >= 1: print(" > READING INPUT FILES...") print # if u.verbosity >= 2: print(" Dipole orientation file : %s" % infile) print(" Structure file : %s" % structure) print
def demo_accessing_scopes_from_local_funcs(): util.banner( 'scoping global params and local are accessible in local funcs') outer()
def demo_arg_valid_on_several_params(): util.banner('multple args validation via chained decoratos') #dummy_func(-1,0) # expected raised exception #dummy_func(-1,-2) # expected raised exception #dummy_func(0,-2) # expected raised exception dummy_func(0, 0) # expected no exception