code
stringlengths
75
104k
code_sememe
stringlengths
47
309k
token_type
stringlengths
215
214k
code_dependency
stringlengths
75
155k
def get_all_related_companies(self, include_self=False): """ Return all parents and subsidiaries of the company Include the company if include_self = True """ parents = self.get_all_parents() subsidiaries = self.get_all_children() related_companies = parents | subsidiaries if include_self is True: company_qs = Company.objects.filter(id=self.id) related_companies = related_companies | company_qs related_companies_ids = [company.id for company in list(set(related_companies))] related_companies = Company.objects.filter(id__in=related_companies_ids) return related_companies
def function[get_all_related_companies, parameter[self, include_self]]: constant[ Return all parents and subsidiaries of the company Include the company if include_self = True ] variable[parents] assign[=] call[name[self].get_all_parents, parameter[]] variable[subsidiaries] assign[=] call[name[self].get_all_children, parameter[]] variable[related_companies] assign[=] binary_operation[name[parents] <ast.BitOr object at 0x7da2590d6aa0> name[subsidiaries]] if compare[name[include_self] is constant[True]] begin[:] variable[company_qs] assign[=] call[name[Company].objects.filter, parameter[]] variable[related_companies] assign[=] binary_operation[name[related_companies] <ast.BitOr object at 0x7da2590d6aa0> name[company_qs]] variable[related_companies_ids] assign[=] <ast.ListComp object at 0x7da18f09c550> variable[related_companies] assign[=] call[name[Company].objects.filter, parameter[]] return[name[related_companies]]
keyword[def] identifier[get_all_related_companies] ( identifier[self] , identifier[include_self] = keyword[False] ): literal[string] identifier[parents] = identifier[self] . identifier[get_all_parents] () identifier[subsidiaries] = identifier[self] . identifier[get_all_children] () identifier[related_companies] = identifier[parents] | identifier[subsidiaries] keyword[if] identifier[include_self] keyword[is] keyword[True] : identifier[company_qs] = identifier[Company] . identifier[objects] . identifier[filter] ( identifier[id] = identifier[self] . identifier[id] ) identifier[related_companies] = identifier[related_companies] | identifier[company_qs] identifier[related_companies_ids] =[ identifier[company] . identifier[id] keyword[for] identifier[company] keyword[in] identifier[list] ( identifier[set] ( identifier[related_companies] ))] identifier[related_companies] = identifier[Company] . identifier[objects] . identifier[filter] ( identifier[id__in] = identifier[related_companies_ids] ) keyword[return] identifier[related_companies]
def get_all_related_companies(self, include_self=False): """ Return all parents and subsidiaries of the company Include the company if include_self = True """ parents = self.get_all_parents() subsidiaries = self.get_all_children() related_companies = parents | subsidiaries if include_self is True: company_qs = Company.objects.filter(id=self.id) related_companies = related_companies | company_qs # depends on [control=['if'], data=[]] related_companies_ids = [company.id for company in list(set(related_companies))] related_companies = Company.objects.filter(id__in=related_companies_ids) return related_companies
def mock_stream(hamiltonian, prog_orbit, prog_mass, k_mean, k_disp, release_every=1, Integrator=DOPRI853Integrator, Integrator_kwargs=dict(), snapshot_filename=None, output_every=1, seed=None): """ Generate a mock stellar stream in the specified potential with a progenitor system that ends up at the specified position. Parameters ---------- hamiltonian : `~gala.potential.Hamiltonian` The system Hamiltonian. prog_orbit : `~gala.dynamics.Orbit` The orbit of the progenitor system. prog_mass : numeric, array_like A single mass or an array of masses if the progenitor mass evolves with time. k_mean : `numpy.ndarray` Array of mean :math:`k` values (see Fardal et al. 2015). These are used to determine the exact prescription for generating the mock stream. The components are for: :math:`(R,\phi,z,v_R,v_\phi,v_z)`. If 1D, assumed constant in time. If 2D, time axis is axis 0. k_disp : `numpy.ndarray` Array of :math:`k` value dispersions (see Fardal et al. 2015). These are used to determine the exact prescription for generating the mock stream. The components are for: :math:`(R,\phi,z,v_R,v_\phi,v_z)`. If 1D, assumed constant in time. If 2D, time axis is axis 0. release_every : int (optional) Release particles at the Lagrange points every X timesteps. Integrator : `~gala.integrate.Integrator` (optional) Integrator to use. Integrator_kwargs : dict (optional) Any extra keyword argumets to pass to the integrator function. snapshot_filename : str (optional) Filename to save all incremental snapshots of particle positions and velocities. Warning: this can make very large files if you are not careful! output_every : int (optional) If outputing snapshots (i.e., if snapshot_filename is specified), this controls how often to output a snapshot. seed : int (optional) A random number seed for initializing the particle positions. Returns ------- stream : `~gala.dynamics.PhaseSpacePosition` """ if isinstance(hamiltonian, CPotentialBase): warnings.warn("This function now expects a `Hamiltonian` instance " "instead of a `PotentialBase` subclass instance. If you " "are using a static reference frame, you just need to " "pass your potential object in to the Hamiltonian " "constructor to use, e.g., Hamiltonian(potential).", DeprecationWarning) hamiltonian = Hamiltonian(hamiltonian) # ------------------------------------------------------------------------ # Some initial checks to short-circuit if input is bad if Integrator not in [LeapfrogIntegrator, DOPRI853Integrator]: raise ValueError("Only Leapfrog and dop853 integration is supported for" " generating mock streams.") if not isinstance(hamiltonian, Hamiltonian) or not hamiltonian.c_enabled: raise TypeError("Input potential must be a CPotentialBase subclass.") if not isinstance(prog_orbit, Orbit): raise TypeError("Progenitor orbit must be an Orbit subclass.") if snapshot_filename is not None and Integrator != DOPRI853Integrator: raise ValueError("If saving snapshots, must use the DOP853Integrator.") k_mean = np.atleast_1d(k_mean) k_disp = np.atleast_1d(k_disp) if k_mean.ndim > 1: assert k_mean.shape[0] == prog_orbit.t.size assert k_disp.shape[0] == prog_orbit.t.size # ------------------------------------------------------------------------ if prog_orbit.t[1] < prog_orbit.t[0]: raise ValueError("Progenitor orbit goes backwards in time. Streams can " "only be generated on orbits that run forwards. Hint: " "you can reverse the orbit with prog_orbit[::-1], but " "make sure the array of k_mean values is ordered " "correctly.") c_w = np.squeeze(prog_orbit.w(hamiltonian.units)).T # transpose for Cython funcs prog_w = np.ascontiguousarray(c_w) prog_t = np.ascontiguousarray(prog_orbit.t.decompose(hamiltonian.units).value) if not hasattr(prog_mass, 'unit'): prog_mass = prog_mass * hamiltonian.units['mass'] if not prog_mass.isscalar: if len(prog_mass) != prog_orbit.ntimes: raise ValueError("If passing in an array of progenitor masses, it " "must have the same length as the number of " "timesteps in the input orbit.") prog_mass = prog_mass.decompose(hamiltonian.units).value if Integrator == LeapfrogIntegrator: stream_w = _mock_stream_leapfrog(hamiltonian, t=prog_t, prog_w=prog_w, release_every=release_every, _k_mean=k_mean, _k_disp=k_disp, G=hamiltonian.potential.G, _prog_mass=prog_mass, seed=seed, **Integrator_kwargs) elif Integrator == DOPRI853Integrator: if snapshot_filename is not None: if os.path.exists(snapshot_filename): raise IOError("Mockstream save file '{}' already exists.") import h5py _mock_stream_animate(snapshot_filename, hamiltonian, t=prog_t, prog_w=prog_w, release_every=release_every, output_every=output_every, _k_mean=k_mean, _k_disp=k_disp, G=hamiltonian.potential.G, _prog_mass=prog_mass, seed=seed, **Integrator_kwargs) with h5py.File(str(snapshot_filename), 'a') as h5f: h5f['pos'].attrs['unit'] = str(hamiltonian.units['length']) h5f['vel'].attrs['unit'] = str(hamiltonian.units['length']/hamiltonian.units['time']) h5f['t'].attrs['unit'] = str(hamiltonian.units['time']) return None else: stream_w = _mock_stream_dop853(hamiltonian, t=prog_t, prog_w=prog_w, release_every=release_every, _k_mean=k_mean, _k_disp=k_disp, G=hamiltonian.potential.G, _prog_mass=prog_mass, seed=seed, **Integrator_kwargs) else: raise RuntimeError("Should never get here...") return PhaseSpacePosition.from_w(w=stream_w.T, units=hamiltonian.units)
def function[mock_stream, parameter[hamiltonian, prog_orbit, prog_mass, k_mean, k_disp, release_every, Integrator, Integrator_kwargs, snapshot_filename, output_every, seed]]: constant[ Generate a mock stellar stream in the specified potential with a progenitor system that ends up at the specified position. Parameters ---------- hamiltonian : `~gala.potential.Hamiltonian` The system Hamiltonian. prog_orbit : `~gala.dynamics.Orbit` The orbit of the progenitor system. prog_mass : numeric, array_like A single mass or an array of masses if the progenitor mass evolves with time. k_mean : `numpy.ndarray` Array of mean :math:`k` values (see Fardal et al. 2015). These are used to determine the exact prescription for generating the mock stream. The components are for: :math:`(R,\phi,z,v_R,v_\phi,v_z)`. If 1D, assumed constant in time. If 2D, time axis is axis 0. k_disp : `numpy.ndarray` Array of :math:`k` value dispersions (see Fardal et al. 2015). These are used to determine the exact prescription for generating the mock stream. The components are for: :math:`(R,\phi,z,v_R,v_\phi,v_z)`. If 1D, assumed constant in time. If 2D, time axis is axis 0. release_every : int (optional) Release particles at the Lagrange points every X timesteps. Integrator : `~gala.integrate.Integrator` (optional) Integrator to use. Integrator_kwargs : dict (optional) Any extra keyword argumets to pass to the integrator function. snapshot_filename : str (optional) Filename to save all incremental snapshots of particle positions and velocities. Warning: this can make very large files if you are not careful! output_every : int (optional) If outputing snapshots (i.e., if snapshot_filename is specified), this controls how often to output a snapshot. seed : int (optional) A random number seed for initializing the particle positions. Returns ------- stream : `~gala.dynamics.PhaseSpacePosition` ] if call[name[isinstance], parameter[name[hamiltonian], name[CPotentialBase]]] begin[:] call[name[warnings].warn, parameter[constant[This function now expects a `Hamiltonian` instance instead of a `PotentialBase` subclass instance. If you are using a static reference frame, you just need to pass your potential object in to the Hamiltonian constructor to use, e.g., Hamiltonian(potential).], name[DeprecationWarning]]] variable[hamiltonian] assign[=] call[name[Hamiltonian], parameter[name[hamiltonian]]] if compare[name[Integrator] <ast.NotIn object at 0x7da2590d7190> list[[<ast.Name object at 0x7da1b0d56a70>, <ast.Name object at 0x7da1b0d550f0>]]] begin[:] <ast.Raise object at 0x7da1b0d57280> if <ast.BoolOp object at 0x7da1b0d54d90> begin[:] <ast.Raise object at 0x7da1b0d56620> if <ast.UnaryOp object at 0x7da1b0d56710> begin[:] <ast.Raise object at 0x7da1b0d550c0> if <ast.BoolOp object at 0x7da1b0d54f70> begin[:] <ast.Raise object at 0x7da1b0d55b40> variable[k_mean] assign[=] call[name[np].atleast_1d, parameter[name[k_mean]]] variable[k_disp] assign[=] call[name[np].atleast_1d, parameter[name[k_disp]]] if compare[name[k_mean].ndim greater[>] constant[1]] begin[:] assert[compare[call[name[k_mean].shape][constant[0]] equal[==] name[prog_orbit].t.size]] assert[compare[call[name[k_disp].shape][constant[0]] equal[==] name[prog_orbit].t.size]] if compare[call[name[prog_orbit].t][constant[1]] less[<] call[name[prog_orbit].t][constant[0]]] begin[:] <ast.Raise object at 0x7da1b0d54bb0> variable[c_w] assign[=] call[name[np].squeeze, parameter[call[name[prog_orbit].w, parameter[name[hamiltonian].units]]]].T variable[prog_w] assign[=] call[name[np].ascontiguousarray, parameter[name[c_w]]] variable[prog_t] assign[=] call[name[np].ascontiguousarray, parameter[call[name[prog_orbit].t.decompose, parameter[name[hamiltonian].units]].value]] if <ast.UnaryOp object at 0x7da1b0d57670> begin[:] variable[prog_mass] assign[=] binary_operation[name[prog_mass] * call[name[hamiltonian].units][constant[mass]]] if <ast.UnaryOp object at 0x7da1b0d54430> begin[:] if compare[call[name[len], parameter[name[prog_mass]]] not_equal[!=] name[prog_orbit].ntimes] begin[:] <ast.Raise object at 0x7da1b0d57be0> variable[prog_mass] assign[=] call[name[prog_mass].decompose, parameter[name[hamiltonian].units]].value if compare[name[Integrator] equal[==] name[LeapfrogIntegrator]] begin[:] variable[stream_w] assign[=] call[name[_mock_stream_leapfrog], parameter[name[hamiltonian]]] return[call[name[PhaseSpacePosition].from_w, parameter[]]]
keyword[def] identifier[mock_stream] ( identifier[hamiltonian] , identifier[prog_orbit] , identifier[prog_mass] , identifier[k_mean] , identifier[k_disp] , identifier[release_every] = literal[int] , identifier[Integrator] = identifier[DOPRI853Integrator] , identifier[Integrator_kwargs] = identifier[dict] (), identifier[snapshot_filename] = keyword[None] , identifier[output_every] = literal[int] , identifier[seed] = keyword[None] ): literal[string] keyword[if] identifier[isinstance] ( identifier[hamiltonian] , identifier[CPotentialBase] ): identifier[warnings] . identifier[warn] ( literal[string] literal[string] literal[string] literal[string] literal[string] , identifier[DeprecationWarning] ) identifier[hamiltonian] = identifier[Hamiltonian] ( identifier[hamiltonian] ) keyword[if] identifier[Integrator] keyword[not] keyword[in] [ identifier[LeapfrogIntegrator] , identifier[DOPRI853Integrator] ]: keyword[raise] identifier[ValueError] ( literal[string] literal[string] ) keyword[if] keyword[not] identifier[isinstance] ( identifier[hamiltonian] , identifier[Hamiltonian] ) keyword[or] keyword[not] identifier[hamiltonian] . identifier[c_enabled] : keyword[raise] identifier[TypeError] ( literal[string] ) keyword[if] keyword[not] identifier[isinstance] ( identifier[prog_orbit] , identifier[Orbit] ): keyword[raise] identifier[TypeError] ( literal[string] ) keyword[if] identifier[snapshot_filename] keyword[is] keyword[not] keyword[None] keyword[and] identifier[Integrator] != identifier[DOPRI853Integrator] : keyword[raise] identifier[ValueError] ( literal[string] ) identifier[k_mean] = identifier[np] . identifier[atleast_1d] ( identifier[k_mean] ) identifier[k_disp] = identifier[np] . identifier[atleast_1d] ( identifier[k_disp] ) keyword[if] identifier[k_mean] . identifier[ndim] > literal[int] : keyword[assert] identifier[k_mean] . identifier[shape] [ literal[int] ]== identifier[prog_orbit] . identifier[t] . identifier[size] keyword[assert] identifier[k_disp] . identifier[shape] [ literal[int] ]== identifier[prog_orbit] . identifier[t] . identifier[size] keyword[if] identifier[prog_orbit] . identifier[t] [ literal[int] ]< identifier[prog_orbit] . identifier[t] [ literal[int] ]: keyword[raise] identifier[ValueError] ( literal[string] literal[string] literal[string] literal[string] literal[string] ) identifier[c_w] = identifier[np] . identifier[squeeze] ( identifier[prog_orbit] . identifier[w] ( identifier[hamiltonian] . identifier[units] )). identifier[T] identifier[prog_w] = identifier[np] . identifier[ascontiguousarray] ( identifier[c_w] ) identifier[prog_t] = identifier[np] . identifier[ascontiguousarray] ( identifier[prog_orbit] . identifier[t] . identifier[decompose] ( identifier[hamiltonian] . identifier[units] ). identifier[value] ) keyword[if] keyword[not] identifier[hasattr] ( identifier[prog_mass] , literal[string] ): identifier[prog_mass] = identifier[prog_mass] * identifier[hamiltonian] . identifier[units] [ literal[string] ] keyword[if] keyword[not] identifier[prog_mass] . identifier[isscalar] : keyword[if] identifier[len] ( identifier[prog_mass] )!= identifier[prog_orbit] . identifier[ntimes] : keyword[raise] identifier[ValueError] ( literal[string] literal[string] literal[string] ) identifier[prog_mass] = identifier[prog_mass] . identifier[decompose] ( identifier[hamiltonian] . identifier[units] ). identifier[value] keyword[if] identifier[Integrator] == identifier[LeapfrogIntegrator] : identifier[stream_w] = identifier[_mock_stream_leapfrog] ( identifier[hamiltonian] , identifier[t] = identifier[prog_t] , identifier[prog_w] = identifier[prog_w] , identifier[release_every] = identifier[release_every] , identifier[_k_mean] = identifier[k_mean] , identifier[_k_disp] = identifier[k_disp] , identifier[G] = identifier[hamiltonian] . identifier[potential] . identifier[G] , identifier[_prog_mass] = identifier[prog_mass] , identifier[seed] = identifier[seed] , ** identifier[Integrator_kwargs] ) keyword[elif] identifier[Integrator] == identifier[DOPRI853Integrator] : keyword[if] identifier[snapshot_filename] keyword[is] keyword[not] keyword[None] : keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[snapshot_filename] ): keyword[raise] identifier[IOError] ( literal[string] ) keyword[import] identifier[h5py] identifier[_mock_stream_animate] ( identifier[snapshot_filename] , identifier[hamiltonian] , identifier[t] = identifier[prog_t] , identifier[prog_w] = identifier[prog_w] , identifier[release_every] = identifier[release_every] , identifier[output_every] = identifier[output_every] , identifier[_k_mean] = identifier[k_mean] , identifier[_k_disp] = identifier[k_disp] , identifier[G] = identifier[hamiltonian] . identifier[potential] . identifier[G] , identifier[_prog_mass] = identifier[prog_mass] , identifier[seed] = identifier[seed] , ** identifier[Integrator_kwargs] ) keyword[with] identifier[h5py] . identifier[File] ( identifier[str] ( identifier[snapshot_filename] ), literal[string] ) keyword[as] identifier[h5f] : identifier[h5f] [ literal[string] ]. identifier[attrs] [ literal[string] ]= identifier[str] ( identifier[hamiltonian] . identifier[units] [ literal[string] ]) identifier[h5f] [ literal[string] ]. identifier[attrs] [ literal[string] ]= identifier[str] ( identifier[hamiltonian] . identifier[units] [ literal[string] ]/ identifier[hamiltonian] . identifier[units] [ literal[string] ]) identifier[h5f] [ literal[string] ]. identifier[attrs] [ literal[string] ]= identifier[str] ( identifier[hamiltonian] . identifier[units] [ literal[string] ]) keyword[return] keyword[None] keyword[else] : identifier[stream_w] = identifier[_mock_stream_dop853] ( identifier[hamiltonian] , identifier[t] = identifier[prog_t] , identifier[prog_w] = identifier[prog_w] , identifier[release_every] = identifier[release_every] , identifier[_k_mean] = identifier[k_mean] , identifier[_k_disp] = identifier[k_disp] , identifier[G] = identifier[hamiltonian] . identifier[potential] . identifier[G] , identifier[_prog_mass] = identifier[prog_mass] , identifier[seed] = identifier[seed] , ** identifier[Integrator_kwargs] ) keyword[else] : keyword[raise] identifier[RuntimeError] ( literal[string] ) keyword[return] identifier[PhaseSpacePosition] . identifier[from_w] ( identifier[w] = identifier[stream_w] . identifier[T] , identifier[units] = identifier[hamiltonian] . identifier[units] )
def mock_stream(hamiltonian, prog_orbit, prog_mass, k_mean, k_disp, release_every=1, Integrator=DOPRI853Integrator, Integrator_kwargs=dict(), snapshot_filename=None, output_every=1, seed=None): """ Generate a mock stellar stream in the specified potential with a progenitor system that ends up at the specified position. Parameters ---------- hamiltonian : `~gala.potential.Hamiltonian` The system Hamiltonian. prog_orbit : `~gala.dynamics.Orbit` The orbit of the progenitor system. prog_mass : numeric, array_like A single mass or an array of masses if the progenitor mass evolves with time. k_mean : `numpy.ndarray` Array of mean :math:`k` values (see Fardal et al. 2015). These are used to determine the exact prescription for generating the mock stream. The components are for: :math:`(R,\\phi,z,v_R,v_\\phi,v_z)`. If 1D, assumed constant in time. If 2D, time axis is axis 0. k_disp : `numpy.ndarray` Array of :math:`k` value dispersions (see Fardal et al. 2015). These are used to determine the exact prescription for generating the mock stream. The components are for: :math:`(R,\\phi,z,v_R,v_\\phi,v_z)`. If 1D, assumed constant in time. If 2D, time axis is axis 0. release_every : int (optional) Release particles at the Lagrange points every X timesteps. Integrator : `~gala.integrate.Integrator` (optional) Integrator to use. Integrator_kwargs : dict (optional) Any extra keyword argumets to pass to the integrator function. snapshot_filename : str (optional) Filename to save all incremental snapshots of particle positions and velocities. Warning: this can make very large files if you are not careful! output_every : int (optional) If outputing snapshots (i.e., if snapshot_filename is specified), this controls how often to output a snapshot. seed : int (optional) A random number seed for initializing the particle positions. Returns ------- stream : `~gala.dynamics.PhaseSpacePosition` """ if isinstance(hamiltonian, CPotentialBase): warnings.warn('This function now expects a `Hamiltonian` instance instead of a `PotentialBase` subclass instance. If you are using a static reference frame, you just need to pass your potential object in to the Hamiltonian constructor to use, e.g., Hamiltonian(potential).', DeprecationWarning) hamiltonian = Hamiltonian(hamiltonian) # depends on [control=['if'], data=[]] # ------------------------------------------------------------------------ # Some initial checks to short-circuit if input is bad if Integrator not in [LeapfrogIntegrator, DOPRI853Integrator]: raise ValueError('Only Leapfrog and dop853 integration is supported for generating mock streams.') # depends on [control=['if'], data=[]] if not isinstance(hamiltonian, Hamiltonian) or not hamiltonian.c_enabled: raise TypeError('Input potential must be a CPotentialBase subclass.') # depends on [control=['if'], data=[]] if not isinstance(prog_orbit, Orbit): raise TypeError('Progenitor orbit must be an Orbit subclass.') # depends on [control=['if'], data=[]] if snapshot_filename is not None and Integrator != DOPRI853Integrator: raise ValueError('If saving snapshots, must use the DOP853Integrator.') # depends on [control=['if'], data=[]] k_mean = np.atleast_1d(k_mean) k_disp = np.atleast_1d(k_disp) if k_mean.ndim > 1: assert k_mean.shape[0] == prog_orbit.t.size assert k_disp.shape[0] == prog_orbit.t.size # depends on [control=['if'], data=[]] # ------------------------------------------------------------------------ if prog_orbit.t[1] < prog_orbit.t[0]: raise ValueError('Progenitor orbit goes backwards in time. Streams can only be generated on orbits that run forwards. Hint: you can reverse the orbit with prog_orbit[::-1], but make sure the array of k_mean values is ordered correctly.') # depends on [control=['if'], data=[]] c_w = np.squeeze(prog_orbit.w(hamiltonian.units)).T # transpose for Cython funcs prog_w = np.ascontiguousarray(c_w) prog_t = np.ascontiguousarray(prog_orbit.t.decompose(hamiltonian.units).value) if not hasattr(prog_mass, 'unit'): prog_mass = prog_mass * hamiltonian.units['mass'] # depends on [control=['if'], data=[]] if not prog_mass.isscalar: if len(prog_mass) != prog_orbit.ntimes: raise ValueError('If passing in an array of progenitor masses, it must have the same length as the number of timesteps in the input orbit.') # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] prog_mass = prog_mass.decompose(hamiltonian.units).value if Integrator == LeapfrogIntegrator: stream_w = _mock_stream_leapfrog(hamiltonian, t=prog_t, prog_w=prog_w, release_every=release_every, _k_mean=k_mean, _k_disp=k_disp, G=hamiltonian.potential.G, _prog_mass=prog_mass, seed=seed, **Integrator_kwargs) # depends on [control=['if'], data=[]] elif Integrator == DOPRI853Integrator: if snapshot_filename is not None: if os.path.exists(snapshot_filename): raise IOError("Mockstream save file '{}' already exists.") # depends on [control=['if'], data=[]] import h5py _mock_stream_animate(snapshot_filename, hamiltonian, t=prog_t, prog_w=prog_w, release_every=release_every, output_every=output_every, _k_mean=k_mean, _k_disp=k_disp, G=hamiltonian.potential.G, _prog_mass=prog_mass, seed=seed, **Integrator_kwargs) with h5py.File(str(snapshot_filename), 'a') as h5f: h5f['pos'].attrs['unit'] = str(hamiltonian.units['length']) h5f['vel'].attrs['unit'] = str(hamiltonian.units['length'] / hamiltonian.units['time']) h5f['t'].attrs['unit'] = str(hamiltonian.units['time']) # depends on [control=['with'], data=['h5f']] return None # depends on [control=['if'], data=['snapshot_filename']] else: stream_w = _mock_stream_dop853(hamiltonian, t=prog_t, prog_w=prog_w, release_every=release_every, _k_mean=k_mean, _k_disp=k_disp, G=hamiltonian.potential.G, _prog_mass=prog_mass, seed=seed, **Integrator_kwargs) # depends on [control=['if'], data=[]] else: raise RuntimeError('Should never get here...') return PhaseSpacePosition.from_w(w=stream_w.T, units=hamiltonian.units)
def cmd(*args, **kwargs): r""" A really roundabout way to issue a system call # FIXME: This function needs some work # It should work without a hitch on windows or unix. # It should be able to spit out stdout in realtime. # Should be able to configure detatchment, shell, and sudo. FIXME: on a mac ut.cmd('/Users/joncrall/Library/Application Support/ibeis/tomcat/bin/shutdown.sh') will fail due to spaces Kwargs: quiet (bool) : silence (bool) : verbose (bool) : detatch (bool) : shell (bool) : sudo (bool) : pad_stdout (bool) : dryrun (bool) : Returns: tuple: (None, None, None) CommandLine: python -m utool.util_cplat --test-cmd python -m utool.util_cplat --test-cmd:0 python -m utool.util_cplat --test-cmd:1 python -m utool.util_cplat --test-cmd:2 python -m utool.util_cplat --test-cmd:1 --test-sudo python -m utool.util_cplat --test-cmd:2 --test-sudo Example0: >>> # ENABLE_DOCTEST >>> import utool as ut >>> (out, err, ret) = ut.cmd('echo', 'hello world') >>> result = ut.repr4(list(zip(('out', 'err', 'ret'), (out, err, ret))), nobraces=True) >>> print(result) ('out', 'hello world\n'), ('err', None), ('ret', 0), Example1: >>> # ENABLE_DOCTEST >>> import utool as ut >>> target = ut.codeblock( ... r''' ('out', 'hello world\n'), ('err', None), ('ret', 0), ''') >>> varydict = { ... 'shell': [True, False], ... 'detatch': [False], ... 'sudo': [True, False] if ut.get_argflag('--test-sudo') else [False], ... 'args': ['echo hello world', ('echo', 'hello world')], ... } >>> for count, kw in enumerate(ut.all_dict_combinations(varydict), start=1): >>> print('+ --- TEST CMD %d ---' % (count,)) >>> print('testing cmd with params ' + ut.repr4(kw)) >>> args = kw.pop('args') >>> restup = ut.cmd(args, pad_stdout=False, **kw) >>> tupfields = ('out', 'err', 'ret') >>> output = ut.repr4(list(zip(tupfields, restup)), nobraces=True) >>> ut.assert_eq(output, target) >>> print('L ___ TEST CMD %d ___\n' % (count,)) Example2: >>> # DISABLE_DOCTEST >>> # UNSTABLE_DOCTEST >>> # ping is not as universal of a command as I thought >>> from utool.util_cplat import * # NOQA >>> import utool as ut >>> varydict = { ... 'shell': [True, False], ... 'detatch': [True], ... 'args': ['ping localhost', ('ping', 'localhost')], ... } >>> proc_list = [] >>> for count, kw in enumerate(ut.all_dict_combinations(varydict), start=1): >>> print('+ --- TEST CMD %d ---' % (count,)) >>> print('testing cmd with params ' + ut.repr4(kw)) >>> args = kw.pop('args') >>> restup = ut.cmd(args, pad_stdout=False, **kw) >>> out, err, proc = restup >>> proc_list.append(proc) >>> print(proc) >>> print(proc) >>> print(proc.poll()) >>> print('L ___ TEST CMD %d ___\n' % (count,)) """ try: # Parse the keyword arguments verbose, detatch, shell, sudo, pad_stdout = __parse_cmd_kwargs(kwargs) quiet = kwargs.pop('quiet', False) silence = kwargs.pop('silence', False) if pad_stdout: sys.stdout.flush() print('\n+--------') args = __parse_cmd_args(args, sudo, shell) # Print what you are about to do if not quiet: print('[ut.cmd] RUNNING: %r' % (args,)) # Open a subprocess with a pipe if kwargs.get('dryrun', False): print('[ut.cmd] Exiting because dryrun=True') return None, None, None proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=shell, universal_newlines=True # universal_newlines=False ) hack_use_stdout = True if detatch: if not quiet: print('[ut.cmd] PROCESS DETATCHING. No stdoutput can be reported...') # There is no immediate confirmation as to whether or not the script # finished. It might still be running for all you know return None, None, proc else: if verbose and not detatch: if not quiet: print('[ut.cmd] RUNNING WITH VERBOSE OUTPUT') logged_out = [] for line in _run_process(proc): #line_ = line if six.PY2 else line.decode('utf-8') line_ = line if six.PY2 else line if len(line_) > 0: if not silence: if hack_use_stdout: sys.stdout.write(line_) sys.stdout.flush() else: # TODO make this play nicely with loggers print_(line_) logged_out.append(line) try: from utool import util_str # NOQA # logged_out = util_str.ensure_unicode_strlist(logged_out) out = '\n'.join(logged_out) except UnicodeDecodeError: from utool import util_str # NOQA logged_out = util_str.ensure_unicode_strlist(logged_out) out = '\n'.join(logged_out) # print('logged_out = %r' % (logged_out,)) # raise (out_, err) = proc.communicate() #print('[ut.cmd] out: %s' % (out,)) if not quiet: try: print('[ut.cmd] stdout: %s' % (out_,)) print('[ut.cmd] stderr: %s' % (err,)) except UnicodeDecodeError: from utool import util_str # NOQA print('[ut.cmd] stdout: %s' % (util_str.ensure_unicode(out_),)) print('[ut.cmd] stderr: %s' % (util_str.ensure_unicode(err),)) else: # Surpress output #print('[ut.cmd] RUNNING WITH SUPRESSED OUTPUT') (out, err) = proc.communicate() # Make sure process if finished ret = proc.wait() if not quiet: print('[ut.cmd] PROCESS FINISHED') if pad_stdout: print('L________\n') return out, err, ret except Exception as ex: import utool as ut #if isinstance(args, tuple): # print(ut.truepath(args[0])) #elif isinstance(args, six.string_types): # print(ut.unixpath(args)) ut.printex(ex, 'Exception running ut.cmd', keys=['verbose', 'detatch', 'shell', 'sudo', 'pad_stdout'], tb=True)
def function[cmd, parameter[]]: constant[ A really roundabout way to issue a system call # FIXME: This function needs some work # It should work without a hitch on windows or unix. # It should be able to spit out stdout in realtime. # Should be able to configure detatchment, shell, and sudo. FIXME: on a mac ut.cmd('/Users/joncrall/Library/Application Support/ibeis/tomcat/bin/shutdown.sh') will fail due to spaces Kwargs: quiet (bool) : silence (bool) : verbose (bool) : detatch (bool) : shell (bool) : sudo (bool) : pad_stdout (bool) : dryrun (bool) : Returns: tuple: (None, None, None) CommandLine: python -m utool.util_cplat --test-cmd python -m utool.util_cplat --test-cmd:0 python -m utool.util_cplat --test-cmd:1 python -m utool.util_cplat --test-cmd:2 python -m utool.util_cplat --test-cmd:1 --test-sudo python -m utool.util_cplat --test-cmd:2 --test-sudo Example0: >>> # ENABLE_DOCTEST >>> import utool as ut >>> (out, err, ret) = ut.cmd('echo', 'hello world') >>> result = ut.repr4(list(zip(('out', 'err', 'ret'), (out, err, ret))), nobraces=True) >>> print(result) ('out', 'hello world\n'), ('err', None), ('ret', 0), Example1: >>> # ENABLE_DOCTEST >>> import utool as ut >>> target = ut.codeblock( ... r''' ('out', 'hello world\n'), ('err', None), ('ret', 0), ''') >>> varydict = { ... 'shell': [True, False], ... 'detatch': [False], ... 'sudo': [True, False] if ut.get_argflag('--test-sudo') else [False], ... 'args': ['echo hello world', ('echo', 'hello world')], ... } >>> for count, kw in enumerate(ut.all_dict_combinations(varydict), start=1): >>> print('+ --- TEST CMD %d ---' % (count,)) >>> print('testing cmd with params ' + ut.repr4(kw)) >>> args = kw.pop('args') >>> restup = ut.cmd(args, pad_stdout=False, **kw) >>> tupfields = ('out', 'err', 'ret') >>> output = ut.repr4(list(zip(tupfields, restup)), nobraces=True) >>> ut.assert_eq(output, target) >>> print('L ___ TEST CMD %d ___\n' % (count,)) Example2: >>> # DISABLE_DOCTEST >>> # UNSTABLE_DOCTEST >>> # ping is not as universal of a command as I thought >>> from utool.util_cplat import * # NOQA >>> import utool as ut >>> varydict = { ... 'shell': [True, False], ... 'detatch': [True], ... 'args': ['ping localhost', ('ping', 'localhost')], ... } >>> proc_list = [] >>> for count, kw in enumerate(ut.all_dict_combinations(varydict), start=1): >>> print('+ --- TEST CMD %d ---' % (count,)) >>> print('testing cmd with params ' + ut.repr4(kw)) >>> args = kw.pop('args') >>> restup = ut.cmd(args, pad_stdout=False, **kw) >>> out, err, proc = restup >>> proc_list.append(proc) >>> print(proc) >>> print(proc) >>> print(proc.poll()) >>> print('L ___ TEST CMD %d ___\n' % (count,)) ] <ast.Try object at 0x7da1b2424e50>
keyword[def] identifier[cmd] (* identifier[args] ,** identifier[kwargs] ): literal[string] keyword[try] : identifier[verbose] , identifier[detatch] , identifier[shell] , identifier[sudo] , identifier[pad_stdout] = identifier[__parse_cmd_kwargs] ( identifier[kwargs] ) identifier[quiet] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[False] ) identifier[silence] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[False] ) keyword[if] identifier[pad_stdout] : identifier[sys] . identifier[stdout] . identifier[flush] () identifier[print] ( literal[string] ) identifier[args] = identifier[__parse_cmd_args] ( identifier[args] , identifier[sudo] , identifier[shell] ) keyword[if] keyword[not] identifier[quiet] : identifier[print] ( literal[string] %( identifier[args] ,)) keyword[if] identifier[kwargs] . identifier[get] ( literal[string] , keyword[False] ): identifier[print] ( literal[string] ) keyword[return] keyword[None] , keyword[None] , keyword[None] identifier[proc] = identifier[subprocess] . identifier[Popen] ( identifier[args] , identifier[stdout] = identifier[subprocess] . identifier[PIPE] , identifier[stderr] = identifier[subprocess] . identifier[STDOUT] , identifier[shell] = identifier[shell] , identifier[universal_newlines] = keyword[True] ) identifier[hack_use_stdout] = keyword[True] keyword[if] identifier[detatch] : keyword[if] keyword[not] identifier[quiet] : identifier[print] ( literal[string] ) keyword[return] keyword[None] , keyword[None] , identifier[proc] keyword[else] : keyword[if] identifier[verbose] keyword[and] keyword[not] identifier[detatch] : keyword[if] keyword[not] identifier[quiet] : identifier[print] ( literal[string] ) identifier[logged_out] =[] keyword[for] identifier[line] keyword[in] identifier[_run_process] ( identifier[proc] ): identifier[line_] = identifier[line] keyword[if] identifier[six] . identifier[PY2] keyword[else] identifier[line] keyword[if] identifier[len] ( identifier[line_] )> literal[int] : keyword[if] keyword[not] identifier[silence] : keyword[if] identifier[hack_use_stdout] : identifier[sys] . identifier[stdout] . identifier[write] ( identifier[line_] ) identifier[sys] . identifier[stdout] . identifier[flush] () keyword[else] : identifier[print_] ( identifier[line_] ) identifier[logged_out] . identifier[append] ( identifier[line] ) keyword[try] : keyword[from] identifier[utool] keyword[import] identifier[util_str] identifier[out] = literal[string] . identifier[join] ( identifier[logged_out] ) keyword[except] identifier[UnicodeDecodeError] : keyword[from] identifier[utool] keyword[import] identifier[util_str] identifier[logged_out] = identifier[util_str] . identifier[ensure_unicode_strlist] ( identifier[logged_out] ) identifier[out] = literal[string] . identifier[join] ( identifier[logged_out] ) ( identifier[out_] , identifier[err] )= identifier[proc] . identifier[communicate] () keyword[if] keyword[not] identifier[quiet] : keyword[try] : identifier[print] ( literal[string] %( identifier[out_] ,)) identifier[print] ( literal[string] %( identifier[err] ,)) keyword[except] identifier[UnicodeDecodeError] : keyword[from] identifier[utool] keyword[import] identifier[util_str] identifier[print] ( literal[string] %( identifier[util_str] . identifier[ensure_unicode] ( identifier[out_] ),)) identifier[print] ( literal[string] %( identifier[util_str] . identifier[ensure_unicode] ( identifier[err] ),)) keyword[else] : ( identifier[out] , identifier[err] )= identifier[proc] . identifier[communicate] () identifier[ret] = identifier[proc] . identifier[wait] () keyword[if] keyword[not] identifier[quiet] : identifier[print] ( literal[string] ) keyword[if] identifier[pad_stdout] : identifier[print] ( literal[string] ) keyword[return] identifier[out] , identifier[err] , identifier[ret] keyword[except] identifier[Exception] keyword[as] identifier[ex] : keyword[import] identifier[utool] keyword[as] identifier[ut] identifier[ut] . identifier[printex] ( identifier[ex] , literal[string] , identifier[keys] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ], identifier[tb] = keyword[True] )
def cmd(*args, **kwargs): """ A really roundabout way to issue a system call # FIXME: This function needs some work # It should work without a hitch on windows or unix. # It should be able to spit out stdout in realtime. # Should be able to configure detatchment, shell, and sudo. FIXME: on a mac ut.cmd('/Users/joncrall/Library/Application Support/ibeis/tomcat/bin/shutdown.sh') will fail due to spaces Kwargs: quiet (bool) : silence (bool) : verbose (bool) : detatch (bool) : shell (bool) : sudo (bool) : pad_stdout (bool) : dryrun (bool) : Returns: tuple: (None, None, None) CommandLine: python -m utool.util_cplat --test-cmd python -m utool.util_cplat --test-cmd:0 python -m utool.util_cplat --test-cmd:1 python -m utool.util_cplat --test-cmd:2 python -m utool.util_cplat --test-cmd:1 --test-sudo python -m utool.util_cplat --test-cmd:2 --test-sudo Example0: >>> # ENABLE_DOCTEST >>> import utool as ut >>> (out, err, ret) = ut.cmd('echo', 'hello world') >>> result = ut.repr4(list(zip(('out', 'err', 'ret'), (out, err, ret))), nobraces=True) >>> print(result) ('out', 'hello world\\n'), ('err', None), ('ret', 0), Example1: >>> # ENABLE_DOCTEST >>> import utool as ut >>> target = ut.codeblock( ... r''' ('out', 'hello world\\n'), ('err', None), ('ret', 0), ''') >>> varydict = { ... 'shell': [True, False], ... 'detatch': [False], ... 'sudo': [True, False] if ut.get_argflag('--test-sudo') else [False], ... 'args': ['echo hello world', ('echo', 'hello world')], ... } >>> for count, kw in enumerate(ut.all_dict_combinations(varydict), start=1): >>> print('+ --- TEST CMD %d ---' % (count,)) >>> print('testing cmd with params ' + ut.repr4(kw)) >>> args = kw.pop('args') >>> restup = ut.cmd(args, pad_stdout=False, **kw) >>> tupfields = ('out', 'err', 'ret') >>> output = ut.repr4(list(zip(tupfields, restup)), nobraces=True) >>> ut.assert_eq(output, target) >>> print('L ___ TEST CMD %d ___\\n' % (count,)) Example2: >>> # DISABLE_DOCTEST >>> # UNSTABLE_DOCTEST >>> # ping is not as universal of a command as I thought >>> from utool.util_cplat import * # NOQA >>> import utool as ut >>> varydict = { ... 'shell': [True, False], ... 'detatch': [True], ... 'args': ['ping localhost', ('ping', 'localhost')], ... } >>> proc_list = [] >>> for count, kw in enumerate(ut.all_dict_combinations(varydict), start=1): >>> print('+ --- TEST CMD %d ---' % (count,)) >>> print('testing cmd with params ' + ut.repr4(kw)) >>> args = kw.pop('args') >>> restup = ut.cmd(args, pad_stdout=False, **kw) >>> out, err, proc = restup >>> proc_list.append(proc) >>> print(proc) >>> print(proc) >>> print(proc.poll()) >>> print('L ___ TEST CMD %d ___\\n' % (count,)) """ try: # Parse the keyword arguments (verbose, detatch, shell, sudo, pad_stdout) = __parse_cmd_kwargs(kwargs) quiet = kwargs.pop('quiet', False) silence = kwargs.pop('silence', False) if pad_stdout: sys.stdout.flush() print('\n+--------') # depends on [control=['if'], data=[]] args = __parse_cmd_args(args, sudo, shell) # Print what you are about to do if not quiet: print('[ut.cmd] RUNNING: %r' % (args,)) # depends on [control=['if'], data=[]] # Open a subprocess with a pipe if kwargs.get('dryrun', False): print('[ut.cmd] Exiting because dryrun=True') return (None, None, None) # depends on [control=['if'], data=[]] # universal_newlines=False proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=shell, universal_newlines=True) hack_use_stdout = True if detatch: if not quiet: print('[ut.cmd] PROCESS DETATCHING. No stdoutput can be reported...') # depends on [control=['if'], data=[]] # There is no immediate confirmation as to whether or not the script # finished. It might still be running for all you know return (None, None, proc) # depends on [control=['if'], data=[]] else: if verbose and (not detatch): if not quiet: print('[ut.cmd] RUNNING WITH VERBOSE OUTPUT') # depends on [control=['if'], data=[]] logged_out = [] for line in _run_process(proc): #line_ = line if six.PY2 else line.decode('utf-8') line_ = line if six.PY2 else line if len(line_) > 0: if not silence: if hack_use_stdout: sys.stdout.write(line_) sys.stdout.flush() # depends on [control=['if'], data=[]] else: # TODO make this play nicely with loggers print_(line_) # depends on [control=['if'], data=[]] logged_out.append(line) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['line']] try: from utool import util_str # NOQA # logged_out = util_str.ensure_unicode_strlist(logged_out) out = '\n'.join(logged_out) # depends on [control=['try'], data=[]] except UnicodeDecodeError: from utool import util_str # NOQA logged_out = util_str.ensure_unicode_strlist(logged_out) out = '\n'.join(logged_out) # depends on [control=['except'], data=[]] # print('logged_out = %r' % (logged_out,)) # raise (out_, err) = proc.communicate() #print('[ut.cmd] out: %s' % (out,)) if not quiet: try: print('[ut.cmd] stdout: %s' % (out_,)) print('[ut.cmd] stderr: %s' % (err,)) # depends on [control=['try'], data=[]] except UnicodeDecodeError: from utool import util_str # NOQA print('[ut.cmd] stdout: %s' % (util_str.ensure_unicode(out_),)) print('[ut.cmd] stderr: %s' % (util_str.ensure_unicode(err),)) # depends on [control=['except'], data=[]] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] else: # Surpress output #print('[ut.cmd] RUNNING WITH SUPRESSED OUTPUT') (out, err) = proc.communicate() # Make sure process if finished ret = proc.wait() if not quiet: print('[ut.cmd] PROCESS FINISHED') # depends on [control=['if'], data=[]] if pad_stdout: print('L________\n') # depends on [control=['if'], data=[]] return (out, err, ret) # depends on [control=['try'], data=[]] except Exception as ex: import utool as ut #if isinstance(args, tuple): # print(ut.truepath(args[0])) #elif isinstance(args, six.string_types): # print(ut.unixpath(args)) ut.printex(ex, 'Exception running ut.cmd', keys=['verbose', 'detatch', 'shell', 'sudo', 'pad_stdout'], tb=True) # depends on [control=['except'], data=['ex']]
def fmt(str, args=None, env=None): """fmt(string, [tuple]) -> string Interpolate a string, replacing {patterns} with the variables with the same name. If given a tuple, use the keys from the tuple to substitute. If not given a tuple, uses the current environment as the variable source. """ # Normally, we'd just call str.format(**args), but we only want to evaluate # values from the tuple which are actually used in the string interpolation, # so we use proxy objects. # If no args are given, we're able to take the current environment. args = args or env proxies = {k: StringInterpolationProxy(args, k) for k in args.keys()} return str.format(**proxies)
def function[fmt, parameter[str, args, env]]: constant[fmt(string, [tuple]) -> string Interpolate a string, replacing {patterns} with the variables with the same name. If given a tuple, use the keys from the tuple to substitute. If not given a tuple, uses the current environment as the variable source. ] variable[args] assign[=] <ast.BoolOp object at 0x7da20c992e00> variable[proxies] assign[=] <ast.DictComp object at 0x7da20c9919c0> return[call[name[str].format, parameter[]]]
keyword[def] identifier[fmt] ( identifier[str] , identifier[args] = keyword[None] , identifier[env] = keyword[None] ): literal[string] identifier[args] = identifier[args] keyword[or] identifier[env] identifier[proxies] ={ identifier[k] : identifier[StringInterpolationProxy] ( identifier[args] , identifier[k] ) keyword[for] identifier[k] keyword[in] identifier[args] . identifier[keys] ()} keyword[return] identifier[str] . identifier[format] (** identifier[proxies] )
def fmt(str, args=None, env=None): """fmt(string, [tuple]) -> string Interpolate a string, replacing {patterns} with the variables with the same name. If given a tuple, use the keys from the tuple to substitute. If not given a tuple, uses the current environment as the variable source. """ # Normally, we'd just call str.format(**args), but we only want to evaluate # values from the tuple which are actually used in the string interpolation, # so we use proxy objects. # If no args are given, we're able to take the current environment. args = args or env proxies = {k: StringInterpolationProxy(args, k) for k in args.keys()} return str.format(**proxies)
def update_shared_sources(f): """ Context manager to ensures data sources shared between multiple plots are cleared and updated appropriately avoiding warnings and allowing empty frames on subplots. Expects a list of shared_sources and a mapping of the columns expected columns for each source in the plots handles. """ def wrapper(self, *args, **kwargs): source_cols = self.handles.get('source_cols', {}) shared_sources = self.handles.get('shared_sources', []) for source in shared_sources: source.data.clear() if self.document and self.document._held_events: self.document._held_events = self.document._held_events[:-1] ret = f(self, *args, **kwargs) for source in shared_sources: expected = source_cols[id(source)] found = [c for c in expected if c in source.data] empty = np.full_like(source.data[found[0]], np.NaN) if found else [] patch = {c: empty for c in expected if c not in source.data} source.data.update(patch) return ret return wrapper
def function[update_shared_sources, parameter[f]]: constant[ Context manager to ensures data sources shared between multiple plots are cleared and updated appropriately avoiding warnings and allowing empty frames on subplots. Expects a list of shared_sources and a mapping of the columns expected columns for each source in the plots handles. ] def function[wrapper, parameter[self]]: variable[source_cols] assign[=] call[name[self].handles.get, parameter[constant[source_cols], dictionary[[], []]]] variable[shared_sources] assign[=] call[name[self].handles.get, parameter[constant[shared_sources], list[[]]]] for taget[name[source]] in starred[name[shared_sources]] begin[:] call[name[source].data.clear, parameter[]] if <ast.BoolOp object at 0x7da2044c3f70> begin[:] name[self].document._held_events assign[=] call[name[self].document._held_events][<ast.Slice object at 0x7da2044c0be0>] variable[ret] assign[=] call[name[f], parameter[name[self], <ast.Starred object at 0x7da2044c1300>]] for taget[name[source]] in starred[name[shared_sources]] begin[:] variable[expected] assign[=] call[name[source_cols]][call[name[id], parameter[name[source]]]] variable[found] assign[=] <ast.ListComp object at 0x7da2044c16c0> variable[empty] assign[=] <ast.IfExp object at 0x7da2044c1de0> variable[patch] assign[=] <ast.DictComp object at 0x7da2044c2a70> call[name[source].data.update, parameter[name[patch]]] return[name[ret]] return[name[wrapper]]
keyword[def] identifier[update_shared_sources] ( identifier[f] ): literal[string] keyword[def] identifier[wrapper] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ): identifier[source_cols] = identifier[self] . identifier[handles] . identifier[get] ( literal[string] ,{}) identifier[shared_sources] = identifier[self] . identifier[handles] . identifier[get] ( literal[string] ,[]) keyword[for] identifier[source] keyword[in] identifier[shared_sources] : identifier[source] . identifier[data] . identifier[clear] () keyword[if] identifier[self] . identifier[document] keyword[and] identifier[self] . identifier[document] . identifier[_held_events] : identifier[self] . identifier[document] . identifier[_held_events] = identifier[self] . identifier[document] . identifier[_held_events] [:- literal[int] ] identifier[ret] = identifier[f] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ) keyword[for] identifier[source] keyword[in] identifier[shared_sources] : identifier[expected] = identifier[source_cols] [ identifier[id] ( identifier[source] )] identifier[found] =[ identifier[c] keyword[for] identifier[c] keyword[in] identifier[expected] keyword[if] identifier[c] keyword[in] identifier[source] . identifier[data] ] identifier[empty] = identifier[np] . identifier[full_like] ( identifier[source] . identifier[data] [ identifier[found] [ literal[int] ]], identifier[np] . identifier[NaN] ) keyword[if] identifier[found] keyword[else] [] identifier[patch] ={ identifier[c] : identifier[empty] keyword[for] identifier[c] keyword[in] identifier[expected] keyword[if] identifier[c] keyword[not] keyword[in] identifier[source] . identifier[data] } identifier[source] . identifier[data] . identifier[update] ( identifier[patch] ) keyword[return] identifier[ret] keyword[return] identifier[wrapper]
def update_shared_sources(f): """ Context manager to ensures data sources shared between multiple plots are cleared and updated appropriately avoiding warnings and allowing empty frames on subplots. Expects a list of shared_sources and a mapping of the columns expected columns for each source in the plots handles. """ def wrapper(self, *args, **kwargs): source_cols = self.handles.get('source_cols', {}) shared_sources = self.handles.get('shared_sources', []) for source in shared_sources: source.data.clear() if self.document and self.document._held_events: self.document._held_events = self.document._held_events[:-1] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['source']] ret = f(self, *args, **kwargs) for source in shared_sources: expected = source_cols[id(source)] found = [c for c in expected if c in source.data] empty = np.full_like(source.data[found[0]], np.NaN) if found else [] patch = {c: empty for c in expected if c not in source.data} source.data.update(patch) # depends on [control=['for'], data=['source']] return ret return wrapper
def get_average(self, field=None): """ Create an avg aggregation object and add it to the aggregation dict :param field: the field present in the index that is to be aggregated :returns: self, which allows the method to be chainable with the other methods """ if not field: raise AttributeError("Please provide field to apply aggregation to!") agg = A("avg", field=field) self.aggregations['avg_' + field] = agg return self
def function[get_average, parameter[self, field]]: constant[ Create an avg aggregation object and add it to the aggregation dict :param field: the field present in the index that is to be aggregated :returns: self, which allows the method to be chainable with the other methods ] if <ast.UnaryOp object at 0x7da1b26068f0> begin[:] <ast.Raise object at 0x7da1b2605570> variable[agg] assign[=] call[name[A], parameter[constant[avg]]] call[name[self].aggregations][binary_operation[constant[avg_] + name[field]]] assign[=] name[agg] return[name[self]]
keyword[def] identifier[get_average] ( identifier[self] , identifier[field] = keyword[None] ): literal[string] keyword[if] keyword[not] identifier[field] : keyword[raise] identifier[AttributeError] ( literal[string] ) identifier[agg] = identifier[A] ( literal[string] , identifier[field] = identifier[field] ) identifier[self] . identifier[aggregations] [ literal[string] + identifier[field] ]= identifier[agg] keyword[return] identifier[self]
def get_average(self, field=None): """ Create an avg aggregation object and add it to the aggregation dict :param field: the field present in the index that is to be aggregated :returns: self, which allows the method to be chainable with the other methods """ if not field: raise AttributeError('Please provide field to apply aggregation to!') # depends on [control=['if'], data=[]] agg = A('avg', field=field) self.aggregations['avg_' + field] = agg return self
def import_config(config_path): """Import a Config from a given path, relative to the current directory. The module specified by the config file must contain a variable called `configuration` that is assigned to a Config object. """ if not os.path.isfile(config_path): raise ConfigBuilderError( 'Could not find config file: ' + config_path) loader = importlib.machinery.SourceFileLoader(config_path, config_path) module = loader.load_module() if not hasattr(module, 'config') or not isinstance(module.config, Config): raise ConfigBuilderError( 'Could not load config file "{}": config files must contain ' 'a variable called "config" that is ' 'assigned to a Config object.'.format(config_path)) return module.config
def function[import_config, parameter[config_path]]: constant[Import a Config from a given path, relative to the current directory. The module specified by the config file must contain a variable called `configuration` that is assigned to a Config object. ] if <ast.UnaryOp object at 0x7da1b2361540> begin[:] <ast.Raise object at 0x7da1b2360460> variable[loader] assign[=] call[name[importlib].machinery.SourceFileLoader, parameter[name[config_path], name[config_path]]] variable[module] assign[=] call[name[loader].load_module, parameter[]] if <ast.BoolOp object at 0x7da1b242bb50> begin[:] <ast.Raise object at 0x7da1b2428430> return[name[module].config]
keyword[def] identifier[import_config] ( identifier[config_path] ): literal[string] keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[isfile] ( identifier[config_path] ): keyword[raise] identifier[ConfigBuilderError] ( literal[string] + identifier[config_path] ) identifier[loader] = identifier[importlib] . identifier[machinery] . identifier[SourceFileLoader] ( identifier[config_path] , identifier[config_path] ) identifier[module] = identifier[loader] . identifier[load_module] () keyword[if] keyword[not] identifier[hasattr] ( identifier[module] , literal[string] ) keyword[or] keyword[not] identifier[isinstance] ( identifier[module] . identifier[config] , identifier[Config] ): keyword[raise] identifier[ConfigBuilderError] ( literal[string] literal[string] literal[string] . identifier[format] ( identifier[config_path] )) keyword[return] identifier[module] . identifier[config]
def import_config(config_path): """Import a Config from a given path, relative to the current directory. The module specified by the config file must contain a variable called `configuration` that is assigned to a Config object. """ if not os.path.isfile(config_path): raise ConfigBuilderError('Could not find config file: ' + config_path) # depends on [control=['if'], data=[]] loader = importlib.machinery.SourceFileLoader(config_path, config_path) module = loader.load_module() if not hasattr(module, 'config') or not isinstance(module.config, Config): raise ConfigBuilderError('Could not load config file "{}": config files must contain a variable called "config" that is assigned to a Config object.'.format(config_path)) # depends on [control=['if'], data=[]] return module.config
def add(self, key, val, priority=None): """add a value to the queue with priority, using the key to know uniqueness key -- str -- this is used to determine if val already exists in the queue, if key is already in the queue, then the val will be replaced in the queue with the new priority val -- mixed -- the value to add to the queue priority -- int -- the priority of val """ if key in self.item_finder: self.remove(key) else: # keep the queue contained if self.full(): raise OverflowError("Queue is full") if priority is None: priority = next(self.counter) item = [priority, key, val] self.item_finder[key] = item heapq.heappush(self.pq, item)
def function[add, parameter[self, key, val, priority]]: constant[add a value to the queue with priority, using the key to know uniqueness key -- str -- this is used to determine if val already exists in the queue, if key is already in the queue, then the val will be replaced in the queue with the new priority val -- mixed -- the value to add to the queue priority -- int -- the priority of val ] if compare[name[key] in name[self].item_finder] begin[:] call[name[self].remove, parameter[name[key]]] if compare[name[priority] is constant[None]] begin[:] variable[priority] assign[=] call[name[next], parameter[name[self].counter]] variable[item] assign[=] list[[<ast.Name object at 0x7da20c7c88e0>, <ast.Name object at 0x7da20c7ca920>, <ast.Name object at 0x7da20c7ca200>]] call[name[self].item_finder][name[key]] assign[=] name[item] call[name[heapq].heappush, parameter[name[self].pq, name[item]]]
keyword[def] identifier[add] ( identifier[self] , identifier[key] , identifier[val] , identifier[priority] = keyword[None] ): literal[string] keyword[if] identifier[key] keyword[in] identifier[self] . identifier[item_finder] : identifier[self] . identifier[remove] ( identifier[key] ) keyword[else] : keyword[if] identifier[self] . identifier[full] (): keyword[raise] identifier[OverflowError] ( literal[string] ) keyword[if] identifier[priority] keyword[is] keyword[None] : identifier[priority] = identifier[next] ( identifier[self] . identifier[counter] ) identifier[item] =[ identifier[priority] , identifier[key] , identifier[val] ] identifier[self] . identifier[item_finder] [ identifier[key] ]= identifier[item] identifier[heapq] . identifier[heappush] ( identifier[self] . identifier[pq] , identifier[item] )
def add(self, key, val, priority=None): """add a value to the queue with priority, using the key to know uniqueness key -- str -- this is used to determine if val already exists in the queue, if key is already in the queue, then the val will be replaced in the queue with the new priority val -- mixed -- the value to add to the queue priority -- int -- the priority of val """ if key in self.item_finder: self.remove(key) # depends on [control=['if'], data=['key']] # keep the queue contained elif self.full(): raise OverflowError('Queue is full') # depends on [control=['if'], data=[]] if priority is None: priority = next(self.counter) # depends on [control=['if'], data=['priority']] item = [priority, key, val] self.item_finder[key] = item heapq.heappush(self.pq, item)
def zoomedHealpixMap(title, map, lon, lat, radius, xsize=1000, **kwargs): """ Inputs: lon (deg), lat (deg), radius (deg) """ reso = 60. * 2. * radius / xsize # Deg to arcmin hp.gnomview(map=map, rot=[lon, lat, 0], title=title, xsize=xsize, reso=reso, degree=False, **kwargs)
def function[zoomedHealpixMap, parameter[title, map, lon, lat, radius, xsize]]: constant[ Inputs: lon (deg), lat (deg), radius (deg) ] variable[reso] assign[=] binary_operation[binary_operation[binary_operation[constant[60.0] * constant[2.0]] * name[radius]] / name[xsize]] call[name[hp].gnomview, parameter[]]
keyword[def] identifier[zoomedHealpixMap] ( identifier[title] , identifier[map] , identifier[lon] , identifier[lat] , identifier[radius] , identifier[xsize] = literal[int] ,** identifier[kwargs] ): literal[string] identifier[reso] = literal[int] * literal[int] * identifier[radius] / identifier[xsize] identifier[hp] . identifier[gnomview] ( identifier[map] = identifier[map] , identifier[rot] =[ identifier[lon] , identifier[lat] , literal[int] ], identifier[title] = identifier[title] , identifier[xsize] = identifier[xsize] , identifier[reso] = identifier[reso] , identifier[degree] = keyword[False] ,** identifier[kwargs] )
def zoomedHealpixMap(title, map, lon, lat, radius, xsize=1000, **kwargs): """ Inputs: lon (deg), lat (deg), radius (deg) """ reso = 60.0 * 2.0 * radius / xsize # Deg to arcmin hp.gnomview(map=map, rot=[lon, lat, 0], title=title, xsize=xsize, reso=reso, degree=False, **kwargs)
def modeled_savings( baseline_model, reporting_model, result_index, temperature_data, with_disaggregated=False, confidence_level=0.90, predict_kwargs=None, ): """ Compute modeled savings, i.e., savings in which baseline and reporting usage values are based on models. This is appropriate for annualizing or weather normalizing models. Parameters ---------- baseline_model : :any:`eemeter.CalTRACKUsagePerDayCandidateModel` Model to use for predicting pre-intervention usage. reporting_model : :any:`eemeter.CalTRACKUsagePerDayCandidateModel` Model to use for predicting post-intervention usage. result_index : :any:`pandas.DatetimeIndex` The dates for which usage should be modeled. temperature_data : :any:`pandas.Series` Hourly-frequency timeseries of temperature data during the modeled period. with_disaggregated : :any:`bool`, optional If True, calculate modeled disaggregated usage estimates and savings. confidence_level : :any:`float`, optional The two-tailed confidence level used to calculate the t-statistic used in calculation of the error bands. Ignored if not computing error bands. predict_kwargs : :any:`dict`, optional Extra kwargs to pass to the baseline_model.predict and reporting_model.predict methods. Returns ------- results : :any:`pandas.DataFrame` DataFrame with modeled savings, indexed with the result_index. Will include the following columns: - ``modeled_baseline_usage`` - ``modeled_reporting_usage`` - ``modeled_savings`` If `with_disaggregated` is set to True, the following columns will also be in the results DataFrame: - ``modeled_baseline_base_load`` - ``modeled_baseline_cooling_load`` - ``modeled_baseline_heating_load`` - ``modeled_reporting_base_load`` - ``modeled_reporting_cooling_load`` - ``modeled_reporting_heating_load`` - ``modeled_base_load_savings`` - ``modeled_cooling_load_savings`` - ``modeled_heating_load_savings`` error_bands : :any:`dict`, optional If baseline_model and reporting_model are instances of CalTRACKUsagePerDayModelResults, will also return a dictionary of FSU and error bands for the aggregated energy savings over the normal year period. """ prediction_index = result_index if predict_kwargs is None: predict_kwargs = {} model_type = None # generic if isinstance(baseline_model, CalTRACKUsagePerDayModelResults): model_type = "usage_per_day" if model_type == "usage_per_day" and with_disaggregated: predict_kwargs["with_disaggregated"] = True def _predicted_usage(model): model_prediction = model.predict( prediction_index, temperature_data, **predict_kwargs ) predicted_usage = model_prediction.result return predicted_usage predicted_baseline_usage = _predicted_usage(baseline_model) predicted_reporting_usage = _predicted_usage(reporting_model) modeled_baseline_usage = predicted_baseline_usage["predicted_usage"].to_frame( "modeled_baseline_usage" ) modeled_reporting_usage = predicted_reporting_usage["predicted_usage"].to_frame( "modeled_reporting_usage" ) def modeled_savings_func(row): return row.modeled_baseline_usage - row.modeled_reporting_usage results = modeled_baseline_usage.join(modeled_reporting_usage).assign( modeled_savings=modeled_savings_func ) if model_type == "usage_per_day" and with_disaggregated: modeled_baseline_usage_disaggregated = predicted_baseline_usage[ ["base_load", "heating_load", "cooling_load"] ].rename( columns={ "base_load": "modeled_baseline_base_load", "heating_load": "modeled_baseline_heating_load", "cooling_load": "modeled_baseline_cooling_load", } ) modeled_reporting_usage_disaggregated = predicted_reporting_usage[ ["base_load", "heating_load", "cooling_load"] ].rename( columns={ "base_load": "modeled_reporting_base_load", "heating_load": "modeled_reporting_heating_load", "cooling_load": "modeled_reporting_cooling_load", } ) def modeled_base_load_savings_func(row): return row.modeled_baseline_base_load - row.modeled_reporting_base_load def modeled_heating_load_savings_func(row): return ( row.modeled_baseline_heating_load - row.modeled_reporting_heating_load ) def modeled_cooling_load_savings_func(row): return ( row.modeled_baseline_cooling_load - row.modeled_reporting_cooling_load ) results = ( results.join(modeled_baseline_usage_disaggregated) .join(modeled_reporting_usage_disaggregated) .assign( modeled_base_load_savings=modeled_base_load_savings_func, modeled_heating_load_savings=modeled_heating_load_savings_func, modeled_cooling_load_savings=modeled_cooling_load_savings_func, ) ) results = results.dropna().reindex(results.index) # carry NaNs error_bands = None if model_type == "usage_per_day": # has totals_metrics error_bands = _compute_error_bands_modeled_savings( baseline_model.totals_metrics, reporting_model.totals_metrics, results, baseline_model.interval, reporting_model.interval, confidence_level, ) return results, error_bands
def function[modeled_savings, parameter[baseline_model, reporting_model, result_index, temperature_data, with_disaggregated, confidence_level, predict_kwargs]]: constant[ Compute modeled savings, i.e., savings in which baseline and reporting usage values are based on models. This is appropriate for annualizing or weather normalizing models. Parameters ---------- baseline_model : :any:`eemeter.CalTRACKUsagePerDayCandidateModel` Model to use for predicting pre-intervention usage. reporting_model : :any:`eemeter.CalTRACKUsagePerDayCandidateModel` Model to use for predicting post-intervention usage. result_index : :any:`pandas.DatetimeIndex` The dates for which usage should be modeled. temperature_data : :any:`pandas.Series` Hourly-frequency timeseries of temperature data during the modeled period. with_disaggregated : :any:`bool`, optional If True, calculate modeled disaggregated usage estimates and savings. confidence_level : :any:`float`, optional The two-tailed confidence level used to calculate the t-statistic used in calculation of the error bands. Ignored if not computing error bands. predict_kwargs : :any:`dict`, optional Extra kwargs to pass to the baseline_model.predict and reporting_model.predict methods. Returns ------- results : :any:`pandas.DataFrame` DataFrame with modeled savings, indexed with the result_index. Will include the following columns: - ``modeled_baseline_usage`` - ``modeled_reporting_usage`` - ``modeled_savings`` If `with_disaggregated` is set to True, the following columns will also be in the results DataFrame: - ``modeled_baseline_base_load`` - ``modeled_baseline_cooling_load`` - ``modeled_baseline_heating_load`` - ``modeled_reporting_base_load`` - ``modeled_reporting_cooling_load`` - ``modeled_reporting_heating_load`` - ``modeled_base_load_savings`` - ``modeled_cooling_load_savings`` - ``modeled_heating_load_savings`` error_bands : :any:`dict`, optional If baseline_model and reporting_model are instances of CalTRACKUsagePerDayModelResults, will also return a dictionary of FSU and error bands for the aggregated energy savings over the normal year period. ] variable[prediction_index] assign[=] name[result_index] if compare[name[predict_kwargs] is constant[None]] begin[:] variable[predict_kwargs] assign[=] dictionary[[], []] variable[model_type] assign[=] constant[None] if call[name[isinstance], parameter[name[baseline_model], name[CalTRACKUsagePerDayModelResults]]] begin[:] variable[model_type] assign[=] constant[usage_per_day] if <ast.BoolOp object at 0x7da18c4cf580> begin[:] call[name[predict_kwargs]][constant[with_disaggregated]] assign[=] constant[True] def function[_predicted_usage, parameter[model]]: variable[model_prediction] assign[=] call[name[model].predict, parameter[name[prediction_index], name[temperature_data]]] variable[predicted_usage] assign[=] name[model_prediction].result return[name[predicted_usage]] variable[predicted_baseline_usage] assign[=] call[name[_predicted_usage], parameter[name[baseline_model]]] variable[predicted_reporting_usage] assign[=] call[name[_predicted_usage], parameter[name[reporting_model]]] variable[modeled_baseline_usage] assign[=] call[call[name[predicted_baseline_usage]][constant[predicted_usage]].to_frame, parameter[constant[modeled_baseline_usage]]] variable[modeled_reporting_usage] assign[=] call[call[name[predicted_reporting_usage]][constant[predicted_usage]].to_frame, parameter[constant[modeled_reporting_usage]]] def function[modeled_savings_func, parameter[row]]: return[binary_operation[name[row].modeled_baseline_usage - name[row].modeled_reporting_usage]] variable[results] assign[=] call[call[name[modeled_baseline_usage].join, parameter[name[modeled_reporting_usage]]].assign, parameter[]] if <ast.BoolOp object at 0x7da18c4cff70> begin[:] variable[modeled_baseline_usage_disaggregated] assign[=] call[call[name[predicted_baseline_usage]][list[[<ast.Constant object at 0x7da18c4cf070>, <ast.Constant object at 0x7da18c4cc580>, <ast.Constant object at 0x7da18c4cd1b0>]]].rename, parameter[]] variable[modeled_reporting_usage_disaggregated] assign[=] call[call[name[predicted_reporting_usage]][list[[<ast.Constant object at 0x7da18c4cdf00>, <ast.Constant object at 0x7da18c4cc4f0>, <ast.Constant object at 0x7da18c4ce650>]]].rename, parameter[]] def function[modeled_base_load_savings_func, parameter[row]]: return[binary_operation[name[row].modeled_baseline_base_load - name[row].modeled_reporting_base_load]] def function[modeled_heating_load_savings_func, parameter[row]]: return[binary_operation[name[row].modeled_baseline_heating_load - name[row].modeled_reporting_heating_load]] def function[modeled_cooling_load_savings_func, parameter[row]]: return[binary_operation[name[row].modeled_baseline_cooling_load - name[row].modeled_reporting_cooling_load]] variable[results] assign[=] call[call[call[name[results].join, parameter[name[modeled_baseline_usage_disaggregated]]].join, parameter[name[modeled_reporting_usage_disaggregated]]].assign, parameter[]] variable[results] assign[=] call[call[name[results].dropna, parameter[]].reindex, parameter[name[results].index]] variable[error_bands] assign[=] constant[None] if compare[name[model_type] equal[==] constant[usage_per_day]] begin[:] variable[error_bands] assign[=] call[name[_compute_error_bands_modeled_savings], parameter[name[baseline_model].totals_metrics, name[reporting_model].totals_metrics, name[results], name[baseline_model].interval, name[reporting_model].interval, name[confidence_level]]] return[tuple[[<ast.Name object at 0x7da18fe93730>, <ast.Name object at 0x7da18fe91f90>]]]
keyword[def] identifier[modeled_savings] ( identifier[baseline_model] , identifier[reporting_model] , identifier[result_index] , identifier[temperature_data] , identifier[with_disaggregated] = keyword[False] , identifier[confidence_level] = literal[int] , identifier[predict_kwargs] = keyword[None] , ): literal[string] identifier[prediction_index] = identifier[result_index] keyword[if] identifier[predict_kwargs] keyword[is] keyword[None] : identifier[predict_kwargs] ={} identifier[model_type] = keyword[None] keyword[if] identifier[isinstance] ( identifier[baseline_model] , identifier[CalTRACKUsagePerDayModelResults] ): identifier[model_type] = literal[string] keyword[if] identifier[model_type] == literal[string] keyword[and] identifier[with_disaggregated] : identifier[predict_kwargs] [ literal[string] ]= keyword[True] keyword[def] identifier[_predicted_usage] ( identifier[model] ): identifier[model_prediction] = identifier[model] . identifier[predict] ( identifier[prediction_index] , identifier[temperature_data] ,** identifier[predict_kwargs] ) identifier[predicted_usage] = identifier[model_prediction] . identifier[result] keyword[return] identifier[predicted_usage] identifier[predicted_baseline_usage] = identifier[_predicted_usage] ( identifier[baseline_model] ) identifier[predicted_reporting_usage] = identifier[_predicted_usage] ( identifier[reporting_model] ) identifier[modeled_baseline_usage] = identifier[predicted_baseline_usage] [ literal[string] ]. identifier[to_frame] ( literal[string] ) identifier[modeled_reporting_usage] = identifier[predicted_reporting_usage] [ literal[string] ]. identifier[to_frame] ( literal[string] ) keyword[def] identifier[modeled_savings_func] ( identifier[row] ): keyword[return] identifier[row] . identifier[modeled_baseline_usage] - identifier[row] . identifier[modeled_reporting_usage] identifier[results] = identifier[modeled_baseline_usage] . identifier[join] ( identifier[modeled_reporting_usage] ). identifier[assign] ( identifier[modeled_savings] = identifier[modeled_savings_func] ) keyword[if] identifier[model_type] == literal[string] keyword[and] identifier[with_disaggregated] : identifier[modeled_baseline_usage_disaggregated] = identifier[predicted_baseline_usage] [ [ literal[string] , literal[string] , literal[string] ] ]. identifier[rename] ( identifier[columns] ={ literal[string] : literal[string] , literal[string] : literal[string] , literal[string] : literal[string] , } ) identifier[modeled_reporting_usage_disaggregated] = identifier[predicted_reporting_usage] [ [ literal[string] , literal[string] , literal[string] ] ]. identifier[rename] ( identifier[columns] ={ literal[string] : literal[string] , literal[string] : literal[string] , literal[string] : literal[string] , } ) keyword[def] identifier[modeled_base_load_savings_func] ( identifier[row] ): keyword[return] identifier[row] . identifier[modeled_baseline_base_load] - identifier[row] . identifier[modeled_reporting_base_load] keyword[def] identifier[modeled_heating_load_savings_func] ( identifier[row] ): keyword[return] ( identifier[row] . identifier[modeled_baseline_heating_load] - identifier[row] . identifier[modeled_reporting_heating_load] ) keyword[def] identifier[modeled_cooling_load_savings_func] ( identifier[row] ): keyword[return] ( identifier[row] . identifier[modeled_baseline_cooling_load] - identifier[row] . identifier[modeled_reporting_cooling_load] ) identifier[results] =( identifier[results] . identifier[join] ( identifier[modeled_baseline_usage_disaggregated] ) . identifier[join] ( identifier[modeled_reporting_usage_disaggregated] ) . identifier[assign] ( identifier[modeled_base_load_savings] = identifier[modeled_base_load_savings_func] , identifier[modeled_heating_load_savings] = identifier[modeled_heating_load_savings_func] , identifier[modeled_cooling_load_savings] = identifier[modeled_cooling_load_savings_func] , ) ) identifier[results] = identifier[results] . identifier[dropna] (). identifier[reindex] ( identifier[results] . identifier[index] ) identifier[error_bands] = keyword[None] keyword[if] identifier[model_type] == literal[string] : identifier[error_bands] = identifier[_compute_error_bands_modeled_savings] ( identifier[baseline_model] . identifier[totals_metrics] , identifier[reporting_model] . identifier[totals_metrics] , identifier[results] , identifier[baseline_model] . identifier[interval] , identifier[reporting_model] . identifier[interval] , identifier[confidence_level] , ) keyword[return] identifier[results] , identifier[error_bands]
def modeled_savings(baseline_model, reporting_model, result_index, temperature_data, with_disaggregated=False, confidence_level=0.9, predict_kwargs=None): """ Compute modeled savings, i.e., savings in which baseline and reporting usage values are based on models. This is appropriate for annualizing or weather normalizing models. Parameters ---------- baseline_model : :any:`eemeter.CalTRACKUsagePerDayCandidateModel` Model to use for predicting pre-intervention usage. reporting_model : :any:`eemeter.CalTRACKUsagePerDayCandidateModel` Model to use for predicting post-intervention usage. result_index : :any:`pandas.DatetimeIndex` The dates for which usage should be modeled. temperature_data : :any:`pandas.Series` Hourly-frequency timeseries of temperature data during the modeled period. with_disaggregated : :any:`bool`, optional If True, calculate modeled disaggregated usage estimates and savings. confidence_level : :any:`float`, optional The two-tailed confidence level used to calculate the t-statistic used in calculation of the error bands. Ignored if not computing error bands. predict_kwargs : :any:`dict`, optional Extra kwargs to pass to the baseline_model.predict and reporting_model.predict methods. Returns ------- results : :any:`pandas.DataFrame` DataFrame with modeled savings, indexed with the result_index. Will include the following columns: - ``modeled_baseline_usage`` - ``modeled_reporting_usage`` - ``modeled_savings`` If `with_disaggregated` is set to True, the following columns will also be in the results DataFrame: - ``modeled_baseline_base_load`` - ``modeled_baseline_cooling_load`` - ``modeled_baseline_heating_load`` - ``modeled_reporting_base_load`` - ``modeled_reporting_cooling_load`` - ``modeled_reporting_heating_load`` - ``modeled_base_load_savings`` - ``modeled_cooling_load_savings`` - ``modeled_heating_load_savings`` error_bands : :any:`dict`, optional If baseline_model and reporting_model are instances of CalTRACKUsagePerDayModelResults, will also return a dictionary of FSU and error bands for the aggregated energy savings over the normal year period. """ prediction_index = result_index if predict_kwargs is None: predict_kwargs = {} # depends on [control=['if'], data=['predict_kwargs']] model_type = None # generic if isinstance(baseline_model, CalTRACKUsagePerDayModelResults): model_type = 'usage_per_day' # depends on [control=['if'], data=[]] if model_type == 'usage_per_day' and with_disaggregated: predict_kwargs['with_disaggregated'] = True # depends on [control=['if'], data=[]] def _predicted_usage(model): model_prediction = model.predict(prediction_index, temperature_data, **predict_kwargs) predicted_usage = model_prediction.result return predicted_usage predicted_baseline_usage = _predicted_usage(baseline_model) predicted_reporting_usage = _predicted_usage(reporting_model) modeled_baseline_usage = predicted_baseline_usage['predicted_usage'].to_frame('modeled_baseline_usage') modeled_reporting_usage = predicted_reporting_usage['predicted_usage'].to_frame('modeled_reporting_usage') def modeled_savings_func(row): return row.modeled_baseline_usage - row.modeled_reporting_usage results = modeled_baseline_usage.join(modeled_reporting_usage).assign(modeled_savings=modeled_savings_func) if model_type == 'usage_per_day' and with_disaggregated: modeled_baseline_usage_disaggregated = predicted_baseline_usage[['base_load', 'heating_load', 'cooling_load']].rename(columns={'base_load': 'modeled_baseline_base_load', 'heating_load': 'modeled_baseline_heating_load', 'cooling_load': 'modeled_baseline_cooling_load'}) modeled_reporting_usage_disaggregated = predicted_reporting_usage[['base_load', 'heating_load', 'cooling_load']].rename(columns={'base_load': 'modeled_reporting_base_load', 'heating_load': 'modeled_reporting_heating_load', 'cooling_load': 'modeled_reporting_cooling_load'}) def modeled_base_load_savings_func(row): return row.modeled_baseline_base_load - row.modeled_reporting_base_load def modeled_heating_load_savings_func(row): return row.modeled_baseline_heating_load - row.modeled_reporting_heating_load def modeled_cooling_load_savings_func(row): return row.modeled_baseline_cooling_load - row.modeled_reporting_cooling_load results = results.join(modeled_baseline_usage_disaggregated).join(modeled_reporting_usage_disaggregated).assign(modeled_base_load_savings=modeled_base_load_savings_func, modeled_heating_load_savings=modeled_heating_load_savings_func, modeled_cooling_load_savings=modeled_cooling_load_savings_func) # depends on [control=['if'], data=[]] results = results.dropna().reindex(results.index) # carry NaNs error_bands = None if model_type == 'usage_per_day': # has totals_metrics error_bands = _compute_error_bands_modeled_savings(baseline_model.totals_metrics, reporting_model.totals_metrics, results, baseline_model.interval, reporting_model.interval, confidence_level) # depends on [control=['if'], data=[]] return (results, error_bands)
def intersect(lst1, lst2): ''' Returns the intersection of two lists. .. code-block:: jinja {% my_list = [1,2,3,4] -%} {{ set my_list | intersect([2, 4, 6]) }} will be rendered as: .. code-block:: text [2, 4] ''' if isinstance(lst1, collections.Hashable) and isinstance(lst2, collections.Hashable): return set(lst1) & set(lst2) return unique([ele for ele in lst1 if ele in lst2])
def function[intersect, parameter[lst1, lst2]]: constant[ Returns the intersection of two lists. .. code-block:: jinja {% my_list = [1,2,3,4] -%} {{ set my_list | intersect([2, 4, 6]) }} will be rendered as: .. code-block:: text [2, 4] ] if <ast.BoolOp object at 0x7da1b1c15540> begin[:] return[binary_operation[call[name[set], parameter[name[lst1]]] <ast.BitAnd object at 0x7da2590d6b60> call[name[set], parameter[name[lst2]]]]] return[call[name[unique], parameter[<ast.ListComp object at 0x7da1b215ded0>]]]
keyword[def] identifier[intersect] ( identifier[lst1] , identifier[lst2] ): literal[string] keyword[if] identifier[isinstance] ( identifier[lst1] , identifier[collections] . identifier[Hashable] ) keyword[and] identifier[isinstance] ( identifier[lst2] , identifier[collections] . identifier[Hashable] ): keyword[return] identifier[set] ( identifier[lst1] )& identifier[set] ( identifier[lst2] ) keyword[return] identifier[unique] ([ identifier[ele] keyword[for] identifier[ele] keyword[in] identifier[lst1] keyword[if] identifier[ele] keyword[in] identifier[lst2] ])
def intersect(lst1, lst2): """ Returns the intersection of two lists. .. code-block:: jinja {% my_list = [1,2,3,4] -%} {{ set my_list | intersect([2, 4, 6]) }} will be rendered as: .. code-block:: text [2, 4] """ if isinstance(lst1, collections.Hashable) and isinstance(lst2, collections.Hashable): return set(lst1) & set(lst2) # depends on [control=['if'], data=[]] return unique([ele for ele in lst1 if ele in lst2])
def expand_role(self, role): """ If the IAM role is a role name, get the Amazon Resource Name (ARN) for the role. If IAM role is already an IAM role ARN, no change is made. :param role: IAM role name or ARN :return: IAM role ARN """ if '/' in role: return role else: return self.get_client_type('iam').get_role(RoleName=role)['Role']['Arn']
def function[expand_role, parameter[self, role]]: constant[ If the IAM role is a role name, get the Amazon Resource Name (ARN) for the role. If IAM role is already an IAM role ARN, no change is made. :param role: IAM role name or ARN :return: IAM role ARN ] if compare[constant[/] in name[role]] begin[:] return[name[role]]
keyword[def] identifier[expand_role] ( identifier[self] , identifier[role] ): literal[string] keyword[if] literal[string] keyword[in] identifier[role] : keyword[return] identifier[role] keyword[else] : keyword[return] identifier[self] . identifier[get_client_type] ( literal[string] ). identifier[get_role] ( identifier[RoleName] = identifier[role] )[ literal[string] ][ literal[string] ]
def expand_role(self, role): """ If the IAM role is a role name, get the Amazon Resource Name (ARN) for the role. If IAM role is already an IAM role ARN, no change is made. :param role: IAM role name or ARN :return: IAM role ARN """ if '/' in role: return role # depends on [control=['if'], data=['role']] else: return self.get_client_type('iam').get_role(RoleName=role)['Role']['Arn']
def setMaxZoomAmount( self, amount ): """ Sets the maximum amount that a user can zoom into to. Default is 100. :param amount | <int> """ self._maxZoomAmount = amount view = self.mainView() if view: view.maxZoomAmountChanged.emit(amount)
def function[setMaxZoomAmount, parameter[self, amount]]: constant[ Sets the maximum amount that a user can zoom into to. Default is 100. :param amount | <int> ] name[self]._maxZoomAmount assign[=] name[amount] variable[view] assign[=] call[name[self].mainView, parameter[]] if name[view] begin[:] call[name[view].maxZoomAmountChanged.emit, parameter[name[amount]]]
keyword[def] identifier[setMaxZoomAmount] ( identifier[self] , identifier[amount] ): literal[string] identifier[self] . identifier[_maxZoomAmount] = identifier[amount] identifier[view] = identifier[self] . identifier[mainView] () keyword[if] identifier[view] : identifier[view] . identifier[maxZoomAmountChanged] . identifier[emit] ( identifier[amount] )
def setMaxZoomAmount(self, amount): """ Sets the maximum amount that a user can zoom into to. Default is 100. :param amount | <int> """ self._maxZoomAmount = amount view = self.mainView() if view: view.maxZoomAmountChanged.emit(amount) # depends on [control=['if'], data=[]]
def _time_stretcher(self, stretch_factor): """ Real time time-scale without pitch modification. :param int i: index of the beginning of the chunk to stretch :param float stretch_factor: audio scale factor (if > 1 speed up the sound else slow it down) .. warning:: This method needs to store the phase computed from the previous chunk. Thus, it can only be called chunk by chunk. """ start = self._i2 end = min(self._i2 + self._N, len(self._sy) - (self._N + self._H)) if start >= end: raise StopIteration # The not so clean code below basically implements a phase vocoder out = numpy.zeros(self._N, dtype=numpy.complex) while self._i2 < end: if self._i1 + self._N + self._H > len(self.y): raise StopIteration a, b = self._i1, self._i1 + self._N S1 = numpy.fft.fft(self._win * self.y[a: b]) S2 = numpy.fft.fft(self._win * self.y[a + self._H: b + self._H]) self._phi += (numpy.angle(S2) - numpy.angle(S1)) self._phi = self._phi - 2.0 * numpy.pi * numpy.round(self._phi / (2.0 * numpy.pi)) out.real, out.imag = numpy.cos(self._phi), numpy.sin(self._phi) self._sy[self._i2: self._i2 + self._N] += self._win * numpy.fft.ifft(numpy.abs(S2) * out).real self._i1 += int(self._H * self.stretch_factor) self._i2 += self._H chunk = self._sy[start:end] if stretch_factor == 1.0: chunk = self.y[start:end] return chunk
def function[_time_stretcher, parameter[self, stretch_factor]]: constant[ Real time time-scale without pitch modification. :param int i: index of the beginning of the chunk to stretch :param float stretch_factor: audio scale factor (if > 1 speed up the sound else slow it down) .. warning:: This method needs to store the phase computed from the previous chunk. Thus, it can only be called chunk by chunk. ] variable[start] assign[=] name[self]._i2 variable[end] assign[=] call[name[min], parameter[binary_operation[name[self]._i2 + name[self]._N], binary_operation[call[name[len], parameter[name[self]._sy]] - binary_operation[name[self]._N + name[self]._H]]]] if compare[name[start] greater_or_equal[>=] name[end]] begin[:] <ast.Raise object at 0x7da18f09e6b0> variable[out] assign[=] call[name[numpy].zeros, parameter[name[self]._N]] while compare[name[self]._i2 less[<] name[end]] begin[:] if compare[binary_operation[binary_operation[name[self]._i1 + name[self]._N] + name[self]._H] greater[>] call[name[len], parameter[name[self].y]]] begin[:] <ast.Raise object at 0x7da18f09ee30> <ast.Tuple object at 0x7da18f09ebf0> assign[=] tuple[[<ast.Attribute object at 0x7da18f09c040>, <ast.BinOp object at 0x7da18f09e7d0>]] variable[S1] assign[=] call[name[numpy].fft.fft, parameter[binary_operation[name[self]._win * call[name[self].y][<ast.Slice object at 0x7da18f09c220>]]]] variable[S2] assign[=] call[name[numpy].fft.fft, parameter[binary_operation[name[self]._win * call[name[self].y][<ast.Slice object at 0x7da18f09cd00>]]]] <ast.AugAssign object at 0x7da18f09fdf0> name[self]._phi assign[=] binary_operation[name[self]._phi - binary_operation[binary_operation[constant[2.0] * name[numpy].pi] * call[name[numpy].round, parameter[binary_operation[name[self]._phi / binary_operation[constant[2.0] * name[numpy].pi]]]]]] <ast.Tuple object at 0x7da18f09e470> assign[=] tuple[[<ast.Call object at 0x7da18f09f310>, <ast.Call object at 0x7da18f09ee00>]] <ast.AugAssign object at 0x7da18f09eef0> <ast.AugAssign object at 0x7da18f09d570> <ast.AugAssign object at 0x7da18f09cb50> variable[chunk] assign[=] call[name[self]._sy][<ast.Slice object at 0x7da18f720700>] if compare[name[stretch_factor] equal[==] constant[1.0]] begin[:] variable[chunk] assign[=] call[name[self].y][<ast.Slice object at 0x7da18f7210f0>] return[name[chunk]]
keyword[def] identifier[_time_stretcher] ( identifier[self] , identifier[stretch_factor] ): literal[string] identifier[start] = identifier[self] . identifier[_i2] identifier[end] = identifier[min] ( identifier[self] . identifier[_i2] + identifier[self] . identifier[_N] , identifier[len] ( identifier[self] . identifier[_sy] )-( identifier[self] . identifier[_N] + identifier[self] . identifier[_H] )) keyword[if] identifier[start] >= identifier[end] : keyword[raise] identifier[StopIteration] identifier[out] = identifier[numpy] . identifier[zeros] ( identifier[self] . identifier[_N] , identifier[dtype] = identifier[numpy] . identifier[complex] ) keyword[while] identifier[self] . identifier[_i2] < identifier[end] : keyword[if] identifier[self] . identifier[_i1] + identifier[self] . identifier[_N] + identifier[self] . identifier[_H] > identifier[len] ( identifier[self] . identifier[y] ): keyword[raise] identifier[StopIteration] identifier[a] , identifier[b] = identifier[self] . identifier[_i1] , identifier[self] . identifier[_i1] + identifier[self] . identifier[_N] identifier[S1] = identifier[numpy] . identifier[fft] . identifier[fft] ( identifier[self] . identifier[_win] * identifier[self] . identifier[y] [ identifier[a] : identifier[b] ]) identifier[S2] = identifier[numpy] . identifier[fft] . identifier[fft] ( identifier[self] . identifier[_win] * identifier[self] . identifier[y] [ identifier[a] + identifier[self] . identifier[_H] : identifier[b] + identifier[self] . identifier[_H] ]) identifier[self] . identifier[_phi] +=( identifier[numpy] . identifier[angle] ( identifier[S2] )- identifier[numpy] . identifier[angle] ( identifier[S1] )) identifier[self] . identifier[_phi] = identifier[self] . identifier[_phi] - literal[int] * identifier[numpy] . identifier[pi] * identifier[numpy] . identifier[round] ( identifier[self] . identifier[_phi] /( literal[int] * identifier[numpy] . identifier[pi] )) identifier[out] . identifier[real] , identifier[out] . identifier[imag] = identifier[numpy] . identifier[cos] ( identifier[self] . identifier[_phi] ), identifier[numpy] . identifier[sin] ( identifier[self] . identifier[_phi] ) identifier[self] . identifier[_sy] [ identifier[self] . identifier[_i2] : identifier[self] . identifier[_i2] + identifier[self] . identifier[_N] ]+= identifier[self] . identifier[_win] * identifier[numpy] . identifier[fft] . identifier[ifft] ( identifier[numpy] . identifier[abs] ( identifier[S2] )* identifier[out] ). identifier[real] identifier[self] . identifier[_i1] += identifier[int] ( identifier[self] . identifier[_H] * identifier[self] . identifier[stretch_factor] ) identifier[self] . identifier[_i2] += identifier[self] . identifier[_H] identifier[chunk] = identifier[self] . identifier[_sy] [ identifier[start] : identifier[end] ] keyword[if] identifier[stretch_factor] == literal[int] : identifier[chunk] = identifier[self] . identifier[y] [ identifier[start] : identifier[end] ] keyword[return] identifier[chunk]
def _time_stretcher(self, stretch_factor): """ Real time time-scale without pitch modification. :param int i: index of the beginning of the chunk to stretch :param float stretch_factor: audio scale factor (if > 1 speed up the sound else slow it down) .. warning:: This method needs to store the phase computed from the previous chunk. Thus, it can only be called chunk by chunk. """ start = self._i2 end = min(self._i2 + self._N, len(self._sy) - (self._N + self._H)) if start >= end: raise StopIteration # depends on [control=['if'], data=[]] # The not so clean code below basically implements a phase vocoder out = numpy.zeros(self._N, dtype=numpy.complex) while self._i2 < end: if self._i1 + self._N + self._H > len(self.y): raise StopIteration # depends on [control=['if'], data=[]] (a, b) = (self._i1, self._i1 + self._N) S1 = numpy.fft.fft(self._win * self.y[a:b]) S2 = numpy.fft.fft(self._win * self.y[a + self._H:b + self._H]) self._phi += numpy.angle(S2) - numpy.angle(S1) self._phi = self._phi - 2.0 * numpy.pi * numpy.round(self._phi / (2.0 * numpy.pi)) (out.real, out.imag) = (numpy.cos(self._phi), numpy.sin(self._phi)) self._sy[self._i2:self._i2 + self._N] += self._win * numpy.fft.ifft(numpy.abs(S2) * out).real self._i1 += int(self._H * self.stretch_factor) self._i2 += self._H # depends on [control=['while'], data=[]] chunk = self._sy[start:end] if stretch_factor == 1.0: chunk = self.y[start:end] # depends on [control=['if'], data=[]] return chunk
def _build_namespace_dict(cls, obj, dots=False): """Recursively replaces all argparse.Namespace and optparse.Values with dicts and drops any keys with None values. Additionally, if dots is True, will expand any dot delimited keys. :param obj: Namespace, Values, or dict to iterate over. Other values will simply be returned. :type obj: argparse.Namespace or optparse.Values or dict or * :param dots: If True, any properties on obj that contain dots (.) will be broken down into child dictionaries. :return: A new dictionary or the value passed if obj was not a dict, Namespace, or Values. :rtype: dict or * """ # We expect our root object to be a dict, but it may come in as # a namespace obj = namespace_to_dict(obj) # We only deal with dictionaries if not isinstance(obj, dict): return obj # Get keys iterator keys = obj.keys() if PY3 else obj.iterkeys() if dots: # Dots needs sorted keys to prevent parents from # clobbering children keys = sorted(list(keys)) output = {} for key in keys: value = obj[key] if value is None: # Avoid unset options. continue save_to = output result = cls._build_namespace_dict(value, dots) if dots: # Split keys by dots as this signifies nesting split = key.split('.') if len(split) > 1: # The last index will be the key we assign result to key = split.pop() # Build the dict tree if needed and change where # we're saving to for child_key in split: if child_key in save_to and \ isinstance(save_to[child_key], dict): save_to = save_to[child_key] else: # Clobber or create save_to[child_key] = {} save_to = save_to[child_key] # Save if key in save_to: save_to[key].update(result) else: save_to[key] = result return output
def function[_build_namespace_dict, parameter[cls, obj, dots]]: constant[Recursively replaces all argparse.Namespace and optparse.Values with dicts and drops any keys with None values. Additionally, if dots is True, will expand any dot delimited keys. :param obj: Namespace, Values, or dict to iterate over. Other values will simply be returned. :type obj: argparse.Namespace or optparse.Values or dict or * :param dots: If True, any properties on obj that contain dots (.) will be broken down into child dictionaries. :return: A new dictionary or the value passed if obj was not a dict, Namespace, or Values. :rtype: dict or * ] variable[obj] assign[=] call[name[namespace_to_dict], parameter[name[obj]]] if <ast.UnaryOp object at 0x7da20e9b1450> begin[:] return[name[obj]] variable[keys] assign[=] <ast.IfExp object at 0x7da20e9b35b0> if name[dots] begin[:] variable[keys] assign[=] call[name[sorted], parameter[call[name[list], parameter[name[keys]]]]] variable[output] assign[=] dictionary[[], []] for taget[name[key]] in starred[name[keys]] begin[:] variable[value] assign[=] call[name[obj]][name[key]] if compare[name[value] is constant[None]] begin[:] continue variable[save_to] assign[=] name[output] variable[result] assign[=] call[name[cls]._build_namespace_dict, parameter[name[value], name[dots]]] if name[dots] begin[:] variable[split] assign[=] call[name[key].split, parameter[constant[.]]] if compare[call[name[len], parameter[name[split]]] greater[>] constant[1]] begin[:] variable[key] assign[=] call[name[split].pop, parameter[]] for taget[name[child_key]] in starred[name[split]] begin[:] if <ast.BoolOp object at 0x7da20e9b1a50> begin[:] variable[save_to] assign[=] call[name[save_to]][name[child_key]] if compare[name[key] in name[save_to]] begin[:] call[call[name[save_to]][name[key]].update, parameter[name[result]]] return[name[output]]
keyword[def] identifier[_build_namespace_dict] ( identifier[cls] , identifier[obj] , identifier[dots] = keyword[False] ): literal[string] identifier[obj] = identifier[namespace_to_dict] ( identifier[obj] ) keyword[if] keyword[not] identifier[isinstance] ( identifier[obj] , identifier[dict] ): keyword[return] identifier[obj] identifier[keys] = identifier[obj] . identifier[keys] () keyword[if] identifier[PY3] keyword[else] identifier[obj] . identifier[iterkeys] () keyword[if] identifier[dots] : identifier[keys] = identifier[sorted] ( identifier[list] ( identifier[keys] )) identifier[output] ={} keyword[for] identifier[key] keyword[in] identifier[keys] : identifier[value] = identifier[obj] [ identifier[key] ] keyword[if] identifier[value] keyword[is] keyword[None] : keyword[continue] identifier[save_to] = identifier[output] identifier[result] = identifier[cls] . identifier[_build_namespace_dict] ( identifier[value] , identifier[dots] ) keyword[if] identifier[dots] : identifier[split] = identifier[key] . identifier[split] ( literal[string] ) keyword[if] identifier[len] ( identifier[split] )> literal[int] : identifier[key] = identifier[split] . identifier[pop] () keyword[for] identifier[child_key] keyword[in] identifier[split] : keyword[if] identifier[child_key] keyword[in] identifier[save_to] keyword[and] identifier[isinstance] ( identifier[save_to] [ identifier[child_key] ], identifier[dict] ): identifier[save_to] = identifier[save_to] [ identifier[child_key] ] keyword[else] : identifier[save_to] [ identifier[child_key] ]={} identifier[save_to] = identifier[save_to] [ identifier[child_key] ] keyword[if] identifier[key] keyword[in] identifier[save_to] : identifier[save_to] [ identifier[key] ]. identifier[update] ( identifier[result] ) keyword[else] : identifier[save_to] [ identifier[key] ]= identifier[result] keyword[return] identifier[output]
def _build_namespace_dict(cls, obj, dots=False): """Recursively replaces all argparse.Namespace and optparse.Values with dicts and drops any keys with None values. Additionally, if dots is True, will expand any dot delimited keys. :param obj: Namespace, Values, or dict to iterate over. Other values will simply be returned. :type obj: argparse.Namespace or optparse.Values or dict or * :param dots: If True, any properties on obj that contain dots (.) will be broken down into child dictionaries. :return: A new dictionary or the value passed if obj was not a dict, Namespace, or Values. :rtype: dict or * """ # We expect our root object to be a dict, but it may come in as # a namespace obj = namespace_to_dict(obj) # We only deal with dictionaries if not isinstance(obj, dict): return obj # depends on [control=['if'], data=[]] # Get keys iterator keys = obj.keys() if PY3 else obj.iterkeys() if dots: # Dots needs sorted keys to prevent parents from # clobbering children keys = sorted(list(keys)) # depends on [control=['if'], data=[]] output = {} for key in keys: value = obj[key] if value is None: # Avoid unset options. continue # depends on [control=['if'], data=[]] save_to = output result = cls._build_namespace_dict(value, dots) if dots: # Split keys by dots as this signifies nesting split = key.split('.') if len(split) > 1: # The last index will be the key we assign result to key = split.pop() # Build the dict tree if needed and change where # we're saving to for child_key in split: if child_key in save_to and isinstance(save_to[child_key], dict): save_to = save_to[child_key] # depends on [control=['if'], data=[]] else: # Clobber or create save_to[child_key] = {} save_to = save_to[child_key] # depends on [control=['for'], data=['child_key']] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # Save if key in save_to: save_to[key].update(result) # depends on [control=['if'], data=['key', 'save_to']] else: save_to[key] = result # depends on [control=['for'], data=['key']] return output
def set_refresh_interval(self, seconds, **kwargs): """ :param seconds: -1 FOR NO REFRESH :param kwargs: ANY OTHER REQUEST PARAMETERS :return: None """ if seconds <= 0: interval = -1 else: interval = text_type(seconds) + "s" if self.cluster.version.startswith("0.90."): response = self.cluster.put( "/" + self.settings.index + "/_settings", data='{"index":{"refresh_interval":' + value2json(interval) + '}}', **kwargs ) result = json2value(utf82unicode(response.all_content)) if not result.ok: Log.error("Can not set refresh interval ({{error}})", { "error": utf82unicode(response.all_content) }) elif self.cluster.version.startswith(("1.4.", "1.5.", "1.6.", "1.7.", "5.", "6.")): result = self.cluster.put( "/" + self.settings.index + "/_settings", data={"index": {"refresh_interval": interval}}, **kwargs ) if not result.acknowledged: Log.error("Can not set refresh interval ({{error}})", { "error": result }) else: Log.error("Do not know how to handle ES version {{version}}", version=self.cluster.version)
def function[set_refresh_interval, parameter[self, seconds]]: constant[ :param seconds: -1 FOR NO REFRESH :param kwargs: ANY OTHER REQUEST PARAMETERS :return: None ] if compare[name[seconds] less_or_equal[<=] constant[0]] begin[:] variable[interval] assign[=] <ast.UnaryOp object at 0x7da20e957490> if call[name[self].cluster.version.startswith, parameter[constant[0.90.]]] begin[:] variable[response] assign[=] call[name[self].cluster.put, parameter[binary_operation[binary_operation[constant[/] + name[self].settings.index] + constant[/_settings]]]] variable[result] assign[=] call[name[json2value], parameter[call[name[utf82unicode], parameter[name[response].all_content]]]] if <ast.UnaryOp object at 0x7da20e957850> begin[:] call[name[Log].error, parameter[constant[Can not set refresh interval ({{error}})], dictionary[[<ast.Constant object at 0x7da20e9549a0>], [<ast.Call object at 0x7da20e955fc0>]]]]
keyword[def] identifier[set_refresh_interval] ( identifier[self] , identifier[seconds] ,** identifier[kwargs] ): literal[string] keyword[if] identifier[seconds] <= literal[int] : identifier[interval] =- literal[int] keyword[else] : identifier[interval] = identifier[text_type] ( identifier[seconds] )+ literal[string] keyword[if] identifier[self] . identifier[cluster] . identifier[version] . identifier[startswith] ( literal[string] ): identifier[response] = identifier[self] . identifier[cluster] . identifier[put] ( literal[string] + identifier[self] . identifier[settings] . identifier[index] + literal[string] , identifier[data] = literal[string] + identifier[value2json] ( identifier[interval] )+ literal[string] , ** identifier[kwargs] ) identifier[result] = identifier[json2value] ( identifier[utf82unicode] ( identifier[response] . identifier[all_content] )) keyword[if] keyword[not] identifier[result] . identifier[ok] : identifier[Log] . identifier[error] ( literal[string] ,{ literal[string] : identifier[utf82unicode] ( identifier[response] . identifier[all_content] ) }) keyword[elif] identifier[self] . identifier[cluster] . identifier[version] . identifier[startswith] (( literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] )): identifier[result] = identifier[self] . identifier[cluster] . identifier[put] ( literal[string] + identifier[self] . identifier[settings] . identifier[index] + literal[string] , identifier[data] ={ literal[string] :{ literal[string] : identifier[interval] }}, ** identifier[kwargs] ) keyword[if] keyword[not] identifier[result] . identifier[acknowledged] : identifier[Log] . identifier[error] ( literal[string] ,{ literal[string] : identifier[result] }) keyword[else] : identifier[Log] . identifier[error] ( literal[string] , identifier[version] = identifier[self] . identifier[cluster] . identifier[version] )
def set_refresh_interval(self, seconds, **kwargs): """ :param seconds: -1 FOR NO REFRESH :param kwargs: ANY OTHER REQUEST PARAMETERS :return: None """ if seconds <= 0: interval = -1 # depends on [control=['if'], data=[]] else: interval = text_type(seconds) + 's' if self.cluster.version.startswith('0.90.'): response = self.cluster.put('/' + self.settings.index + '/_settings', data='{"index":{"refresh_interval":' + value2json(interval) + '}}', **kwargs) result = json2value(utf82unicode(response.all_content)) if not result.ok: Log.error('Can not set refresh interval ({{error}})', {'error': utf82unicode(response.all_content)}) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] elif self.cluster.version.startswith(('1.4.', '1.5.', '1.6.', '1.7.', '5.', '6.')): result = self.cluster.put('/' + self.settings.index + '/_settings', data={'index': {'refresh_interval': interval}}, **kwargs) if not result.acknowledged: Log.error('Can not set refresh interval ({{error}})', {'error': result}) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] else: Log.error('Do not know how to handle ES version {{version}}', version=self.cluster.version)
def runner(self): """ Run the necessary methods in the correct order """ printtime('Starting {} analysis pipeline'.format(self.analysistype), self.starttime) # Create the objects to be used in the analyses objects = Objectprep(self) objects.objectprep() self.runmetadata = objects.samples # Run the analyses sippr = Sippr(self, self.cutoff) sippr.clear() # Print the metadata printer = MetadataPrinter(self) printer.printmetadata()
def function[runner, parameter[self]]: constant[ Run the necessary methods in the correct order ] call[name[printtime], parameter[call[constant[Starting {} analysis pipeline].format, parameter[name[self].analysistype]], name[self].starttime]] variable[objects] assign[=] call[name[Objectprep], parameter[name[self]]] call[name[objects].objectprep, parameter[]] name[self].runmetadata assign[=] name[objects].samples variable[sippr] assign[=] call[name[Sippr], parameter[name[self], name[self].cutoff]] call[name[sippr].clear, parameter[]] variable[printer] assign[=] call[name[MetadataPrinter], parameter[name[self]]] call[name[printer].printmetadata, parameter[]]
keyword[def] identifier[runner] ( identifier[self] ): literal[string] identifier[printtime] ( literal[string] . identifier[format] ( identifier[self] . identifier[analysistype] ), identifier[self] . identifier[starttime] ) identifier[objects] = identifier[Objectprep] ( identifier[self] ) identifier[objects] . identifier[objectprep] () identifier[self] . identifier[runmetadata] = identifier[objects] . identifier[samples] identifier[sippr] = identifier[Sippr] ( identifier[self] , identifier[self] . identifier[cutoff] ) identifier[sippr] . identifier[clear] () identifier[printer] = identifier[MetadataPrinter] ( identifier[self] ) identifier[printer] . identifier[printmetadata] ()
def runner(self): """ Run the necessary methods in the correct order """ printtime('Starting {} analysis pipeline'.format(self.analysistype), self.starttime) # Create the objects to be used in the analyses objects = Objectprep(self) objects.objectprep() self.runmetadata = objects.samples # Run the analyses sippr = Sippr(self, self.cutoff) sippr.clear() # Print the metadata printer = MetadataPrinter(self) printer.printmetadata()
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): """Compute the IQR normalized root mean square error between the simulated and observed data. .. image:: /pictures/NRMSE_IQR.png **Range:** 0 ≤ NRMSE < inf. **Notes:** This metric is the RMSE normalized by the interquartile range of the observed time series (x). Normalizing allows comparison between data sets with different scales. The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics. Parameters ---------- simulated_array: one dimensional ndarray An array of simulated data from the time series. observed_array: one dimensional ndarray An array of observed data from the time series. replace_nan: float, optional If given, indicates which value to replace NaN values with in the two arrays. If None, when a NaN value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. replace_inf: float, optional If given, indicates which value to replace Inf values with in the two arrays. If None, when an inf value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. remove_neg: boolean, optional If True, when a negative value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. remove_zero: boolean, optional If true, when a zero value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. Returns ------- float The IQR normalized root mean square error. Examples -------- >>> import HydroErr as he >>> import numpy as np >>> sim = np.array([5, 7, 9, 2, 4.5, 6.7]) >>> obs = np.array([4.7, 6, 10, 2.5, 4, 7]) >>> he.nrmse_iqr(sim, obs) 0.2595461185212093 References ---------- - Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple resolution comparison between maps that share a real variable. Environmental and Ecological Statistics 15(2) 111-142. """ # Checking and cleaning the data simulated_array, observed_array = treat_values( simulated_array, observed_array, replace_nan=replace_nan, replace_inf=replace_inf, remove_neg=remove_neg, remove_zero=remove_zero ) rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2)) q1 = np.percentile(observed_array, 25) q3 = np.percentile(observed_array, 75) iqr = q3 - q1 return rmse_value / iqr
def function[nrmse_iqr, parameter[simulated_array, observed_array, replace_nan, replace_inf, remove_neg, remove_zero]]: constant[Compute the IQR normalized root mean square error between the simulated and observed data. .. image:: /pictures/NRMSE_IQR.png **Range:** 0 ≤ NRMSE < inf. **Notes:** This metric is the RMSE normalized by the interquartile range of the observed time series (x). Normalizing allows comparison between data sets with different scales. The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics. Parameters ---------- simulated_array: one dimensional ndarray An array of simulated data from the time series. observed_array: one dimensional ndarray An array of observed data from the time series. replace_nan: float, optional If given, indicates which value to replace NaN values with in the two arrays. If None, when a NaN value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. replace_inf: float, optional If given, indicates which value to replace Inf values with in the two arrays. If None, when an inf value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. remove_neg: boolean, optional If True, when a negative value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. remove_zero: boolean, optional If true, when a zero value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. Returns ------- float The IQR normalized root mean square error. Examples -------- >>> import HydroErr as he >>> import numpy as np >>> sim = np.array([5, 7, 9, 2, 4.5, 6.7]) >>> obs = np.array([4.7, 6, 10, 2.5, 4, 7]) >>> he.nrmse_iqr(sim, obs) 0.2595461185212093 References ---------- - Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple resolution comparison between maps that share a real variable. Environmental and Ecological Statistics 15(2) 111-142. ] <ast.Tuple object at 0x7da1b0467340> assign[=] call[name[treat_values], parameter[name[simulated_array], name[observed_array]]] variable[rmse_value] assign[=] call[name[np].sqrt, parameter[call[name[np].mean, parameter[binary_operation[binary_operation[name[simulated_array] - name[observed_array]] ** constant[2]]]]]] variable[q1] assign[=] call[name[np].percentile, parameter[name[observed_array], constant[25]]] variable[q3] assign[=] call[name[np].percentile, parameter[name[observed_array], constant[75]]] variable[iqr] assign[=] binary_operation[name[q3] - name[q1]] return[binary_operation[name[rmse_value] / name[iqr]]]
keyword[def] identifier[nrmse_iqr] ( identifier[simulated_array] , identifier[observed_array] , identifier[replace_nan] = keyword[None] , identifier[replace_inf] = keyword[None] , identifier[remove_neg] = keyword[False] , identifier[remove_zero] = keyword[False] ): literal[string] identifier[simulated_array] , identifier[observed_array] = identifier[treat_values] ( identifier[simulated_array] , identifier[observed_array] , identifier[replace_nan] = identifier[replace_nan] , identifier[replace_inf] = identifier[replace_inf] , identifier[remove_neg] = identifier[remove_neg] , identifier[remove_zero] = identifier[remove_zero] ) identifier[rmse_value] = identifier[np] . identifier[sqrt] ( identifier[np] . identifier[mean] (( identifier[simulated_array] - identifier[observed_array] )** literal[int] )) identifier[q1] = identifier[np] . identifier[percentile] ( identifier[observed_array] , literal[int] ) identifier[q3] = identifier[np] . identifier[percentile] ( identifier[observed_array] , literal[int] ) identifier[iqr] = identifier[q3] - identifier[q1] keyword[return] identifier[rmse_value] / identifier[iqr]
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): """Compute the IQR normalized root mean square error between the simulated and observed data. .. image:: /pictures/NRMSE_IQR.png **Range:** 0 ≤ NRMSE < inf. **Notes:** This metric is the RMSE normalized by the interquartile range of the observed time series (x). Normalizing allows comparison between data sets with different scales. The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics. Parameters ---------- simulated_array: one dimensional ndarray An array of simulated data from the time series. observed_array: one dimensional ndarray An array of observed data from the time series. replace_nan: float, optional If given, indicates which value to replace NaN values with in the two arrays. If None, when a NaN value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. replace_inf: float, optional If given, indicates which value to replace Inf values with in the two arrays. If None, when an inf value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. remove_neg: boolean, optional If True, when a negative value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. remove_zero: boolean, optional If true, when a zero value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. Returns ------- float The IQR normalized root mean square error. Examples -------- >>> import HydroErr as he >>> import numpy as np >>> sim = np.array([5, 7, 9, 2, 4.5, 6.7]) >>> obs = np.array([4.7, 6, 10, 2.5, 4, 7]) >>> he.nrmse_iqr(sim, obs) 0.2595461185212093 References ---------- - Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple resolution comparison between maps that share a real variable. Environmental and Ecological Statistics 15(2) 111-142. """ # Checking and cleaning the data (simulated_array, observed_array) = treat_values(simulated_array, observed_array, replace_nan=replace_nan, replace_inf=replace_inf, remove_neg=remove_neg, remove_zero=remove_zero) rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2)) q1 = np.percentile(observed_array, 25) q3 = np.percentile(observed_array, 75) iqr = q3 - q1 return rmse_value / iqr
def execute_deferred_effects(self, pos): """ Evaluates deferred effects that are triggered by the prefix of the pos on the current beliefstate. For instance, if the effect is triggered by the 'NN' pos, then the effect will be triggered by 'NN' or 'NNS'.""" costs = 0 to_delete = [] for entry in self.__dict__['deferred_effects']: effect_pos, effect = entry if pos.startswith(effect_pos): costs += effect(self) to_delete.append(entry) # we delete afterwards, because Python cannot delete from a list that # is being iterated over without screwing up the iteration. for entry in to_delete: self.__dict__['deferred_effects'].remove(entry) return costs
def function[execute_deferred_effects, parameter[self, pos]]: constant[ Evaluates deferred effects that are triggered by the prefix of the pos on the current beliefstate. For instance, if the effect is triggered by the 'NN' pos, then the effect will be triggered by 'NN' or 'NNS'.] variable[costs] assign[=] constant[0] variable[to_delete] assign[=] list[[]] for taget[name[entry]] in starred[call[name[self].__dict__][constant[deferred_effects]]] begin[:] <ast.Tuple object at 0x7da1b15d4d60> assign[=] name[entry] if call[name[pos].startswith, parameter[name[effect_pos]]] begin[:] <ast.AugAssign object at 0x7da1b15d5060> call[name[to_delete].append, parameter[name[entry]]] for taget[name[entry]] in starred[name[to_delete]] begin[:] call[call[name[self].__dict__][constant[deferred_effects]].remove, parameter[name[entry]]] return[name[costs]]
keyword[def] identifier[execute_deferred_effects] ( identifier[self] , identifier[pos] ): literal[string] identifier[costs] = literal[int] identifier[to_delete] =[] keyword[for] identifier[entry] keyword[in] identifier[self] . identifier[__dict__] [ literal[string] ]: identifier[effect_pos] , identifier[effect] = identifier[entry] keyword[if] identifier[pos] . identifier[startswith] ( identifier[effect_pos] ): identifier[costs] += identifier[effect] ( identifier[self] ) identifier[to_delete] . identifier[append] ( identifier[entry] ) keyword[for] identifier[entry] keyword[in] identifier[to_delete] : identifier[self] . identifier[__dict__] [ literal[string] ]. identifier[remove] ( identifier[entry] ) keyword[return] identifier[costs]
def execute_deferred_effects(self, pos): """ Evaluates deferred effects that are triggered by the prefix of the pos on the current beliefstate. For instance, if the effect is triggered by the 'NN' pos, then the effect will be triggered by 'NN' or 'NNS'.""" costs = 0 to_delete = [] for entry in self.__dict__['deferred_effects']: (effect_pos, effect) = entry if pos.startswith(effect_pos): costs += effect(self) to_delete.append(entry) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['entry']] # we delete afterwards, because Python cannot delete from a list that # is being iterated over without screwing up the iteration. for entry in to_delete: self.__dict__['deferred_effects'].remove(entry) # depends on [control=['for'], data=['entry']] return costs
def blocks(self): """ The RDD of sub-matrix blocks ((blockRowIndex, blockColIndex), sub-matrix) that form this distributed matrix. >>> mat = BlockMatrix( ... sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])), ... ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12]))]), 3, 2) >>> blocks = mat.blocks >>> blocks.first() ((0, 0), DenseMatrix(3, 2, [1.0, 2.0, 3.0, 4.0, 5.0, 6.0], 0)) """ # We use DataFrames for serialization of sub-matrix blocks # from Java, so we first convert the RDD of blocks to a # DataFrame on the Scala/Java side. Then we map each Row in # the DataFrame back to a sub-matrix block on this side. blocks_df = callMLlibFunc("getMatrixBlocks", self._java_matrix_wrapper._java_model) blocks = blocks_df.rdd.map(lambda row: ((row[0][0], row[0][1]), row[1])) return blocks
def function[blocks, parameter[self]]: constant[ The RDD of sub-matrix blocks ((blockRowIndex, blockColIndex), sub-matrix) that form this distributed matrix. >>> mat = BlockMatrix( ... sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])), ... ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12]))]), 3, 2) >>> blocks = mat.blocks >>> blocks.first() ((0, 0), DenseMatrix(3, 2, [1.0, 2.0, 3.0, 4.0, 5.0, 6.0], 0)) ] variable[blocks_df] assign[=] call[name[callMLlibFunc], parameter[constant[getMatrixBlocks], name[self]._java_matrix_wrapper._java_model]] variable[blocks] assign[=] call[name[blocks_df].rdd.map, parameter[<ast.Lambda object at 0x7da20e9547f0>]] return[name[blocks]]
keyword[def] identifier[blocks] ( identifier[self] ): literal[string] identifier[blocks_df] = identifier[callMLlibFunc] ( literal[string] , identifier[self] . identifier[_java_matrix_wrapper] . identifier[_java_model] ) identifier[blocks] = identifier[blocks_df] . identifier[rdd] . identifier[map] ( keyword[lambda] identifier[row] :(( identifier[row] [ literal[int] ][ literal[int] ], identifier[row] [ literal[int] ][ literal[int] ]), identifier[row] [ literal[int] ])) keyword[return] identifier[blocks]
def blocks(self): """ The RDD of sub-matrix blocks ((blockRowIndex, blockColIndex), sub-matrix) that form this distributed matrix. >>> mat = BlockMatrix( ... sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])), ... ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12]))]), 3, 2) >>> blocks = mat.blocks >>> blocks.first() ((0, 0), DenseMatrix(3, 2, [1.0, 2.0, 3.0, 4.0, 5.0, 6.0], 0)) """ # We use DataFrames for serialization of sub-matrix blocks # from Java, so we first convert the RDD of blocks to a # DataFrame on the Scala/Java side. Then we map each Row in # the DataFrame back to a sub-matrix block on this side. blocks_df = callMLlibFunc('getMatrixBlocks', self._java_matrix_wrapper._java_model) blocks = blocks_df.rdd.map(lambda row: ((row[0][0], row[0][1]), row[1])) return blocks
def get_name(self): """ Tries to get WF name from 'process' or 'collobration' or 'pariticipant' Returns: str. WF name. """ paths = ['bpmn:process', 'bpmn:collaboration/bpmn:participant/', 'bpmn:collaboration', ] for path in paths: tag = self.root.find(path, NS) if tag is not None and len(tag): name = tag.get('name') if name: return name
def function[get_name, parameter[self]]: constant[ Tries to get WF name from 'process' or 'collobration' or 'pariticipant' Returns: str. WF name. ] variable[paths] assign[=] list[[<ast.Constant object at 0x7da18fe93910>, <ast.Constant object at 0x7da18fe93940>, <ast.Constant object at 0x7da18fe92c20>]] for taget[name[path]] in starred[name[paths]] begin[:] variable[tag] assign[=] call[name[self].root.find, parameter[name[path], name[NS]]] if <ast.BoolOp object at 0x7da18fe91030> begin[:] variable[name] assign[=] call[name[tag].get, parameter[constant[name]]] if name[name] begin[:] return[name[name]]
keyword[def] identifier[get_name] ( identifier[self] ): literal[string] identifier[paths] =[ literal[string] , literal[string] , literal[string] , ] keyword[for] identifier[path] keyword[in] identifier[paths] : identifier[tag] = identifier[self] . identifier[root] . identifier[find] ( identifier[path] , identifier[NS] ) keyword[if] identifier[tag] keyword[is] keyword[not] keyword[None] keyword[and] identifier[len] ( identifier[tag] ): identifier[name] = identifier[tag] . identifier[get] ( literal[string] ) keyword[if] identifier[name] : keyword[return] identifier[name]
def get_name(self): """ Tries to get WF name from 'process' or 'collobration' or 'pariticipant' Returns: str. WF name. """ paths = ['bpmn:process', 'bpmn:collaboration/bpmn:participant/', 'bpmn:collaboration'] for path in paths: tag = self.root.find(path, NS) if tag is not None and len(tag): name = tag.get('name') if name: return name # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['path']]
def _get_resource(self, label: str, source: dict, resource_type: str): """ Generic resoure fetcher handling errors. Args: label (str): The label to fetch source (dict): The dictionary to look up the label resource_type str: The display name of the resource type (used in errors) """ try: return source[label] except KeyError: raise ValueError("Cannot find {0} with label '{1}'.\nExisting {0} labels: {2}".format( resource_type, label, list(source.keys())))
def function[_get_resource, parameter[self, label, source, resource_type]]: constant[ Generic resoure fetcher handling errors. Args: label (str): The label to fetch source (dict): The dictionary to look up the label resource_type str: The display name of the resource type (used in errors) ] <ast.Try object at 0x7da20c6e7910>
keyword[def] identifier[_get_resource] ( identifier[self] , identifier[label] : identifier[str] , identifier[source] : identifier[dict] , identifier[resource_type] : identifier[str] ): literal[string] keyword[try] : keyword[return] identifier[source] [ identifier[label] ] keyword[except] identifier[KeyError] : keyword[raise] identifier[ValueError] ( literal[string] . identifier[format] ( identifier[resource_type] , identifier[label] , identifier[list] ( identifier[source] . identifier[keys] ())))
def _get_resource(self, label: str, source: dict, resource_type: str): """ Generic resoure fetcher handling errors. Args: label (str): The label to fetch source (dict): The dictionary to look up the label resource_type str: The display name of the resource type (used in errors) """ try: return source[label] # depends on [control=['try'], data=[]] except KeyError: raise ValueError("Cannot find {0} with label '{1}'.\nExisting {0} labels: {2}".format(resource_type, label, list(source.keys()))) # depends on [control=['except'], data=[]]
def get_tl(self): """Returns the top left border of the cell""" cell_above_left = CellBorders(self.cell_attributes, *self.cell.get_above_left_key_rect()) return cell_above_left.get_r()
def function[get_tl, parameter[self]]: constant[Returns the top left border of the cell] variable[cell_above_left] assign[=] call[name[CellBorders], parameter[name[self].cell_attributes, <ast.Starred object at 0x7da1b153eb30>]] return[call[name[cell_above_left].get_r, parameter[]]]
keyword[def] identifier[get_tl] ( identifier[self] ): literal[string] identifier[cell_above_left] = identifier[CellBorders] ( identifier[self] . identifier[cell_attributes] , * identifier[self] . identifier[cell] . identifier[get_above_left_key_rect] ()) keyword[return] identifier[cell_above_left] . identifier[get_r] ()
def get_tl(self): """Returns the top left border of the cell""" cell_above_left = CellBorders(self.cell_attributes, *self.cell.get_above_left_key_rect()) return cell_above_left.get_r()
def Canonicalize(node, output=None, **kw): '''Canonicalize(node, output=None, **kw) -> UTF-8 Canonicalize a DOM document/element node and all descendents. Return the text; if output is specified then output.write will be called to output the text and None will be returned Keyword parameters: nsdict: a dictionary of prefix:uri namespace entries assumed to exist in the surrounding context comments: keep comments if non-zero (default is 0) subset: Canonical XML subsetting resulting from XPath (default is []) unsuppressedPrefixes: do exclusive C14N, and this specifies the prefixes that should be inherited. ''' if output: apply(_implementation, (node, output.write), kw) else: s = StringIO.StringIO() apply(_implementation, (node, s.write), kw) return s.getvalue()
def function[Canonicalize, parameter[node, output]]: constant[Canonicalize(node, output=None, **kw) -> UTF-8 Canonicalize a DOM document/element node and all descendents. Return the text; if output is specified then output.write will be called to output the text and None will be returned Keyword parameters: nsdict: a dictionary of prefix:uri namespace entries assumed to exist in the surrounding context comments: keep comments if non-zero (default is 0) subset: Canonical XML subsetting resulting from XPath (default is []) unsuppressedPrefixes: do exclusive C14N, and this specifies the prefixes that should be inherited. ] if name[output] begin[:] call[name[apply], parameter[name[_implementation], tuple[[<ast.Name object at 0x7da18f722d10>, <ast.Attribute object at 0x7da18f720580>]], name[kw]]]
keyword[def] identifier[Canonicalize] ( identifier[node] , identifier[output] = keyword[None] ,** identifier[kw] ): literal[string] keyword[if] identifier[output] : identifier[apply] ( identifier[_implementation] ,( identifier[node] , identifier[output] . identifier[write] ), identifier[kw] ) keyword[else] : identifier[s] = identifier[StringIO] . identifier[StringIO] () identifier[apply] ( identifier[_implementation] ,( identifier[node] , identifier[s] . identifier[write] ), identifier[kw] ) keyword[return] identifier[s] . identifier[getvalue] ()
def Canonicalize(node, output=None, **kw): """Canonicalize(node, output=None, **kw) -> UTF-8 Canonicalize a DOM document/element node and all descendents. Return the text; if output is specified then output.write will be called to output the text and None will be returned Keyword parameters: nsdict: a dictionary of prefix:uri namespace entries assumed to exist in the surrounding context comments: keep comments if non-zero (default is 0) subset: Canonical XML subsetting resulting from XPath (default is []) unsuppressedPrefixes: do exclusive C14N, and this specifies the prefixes that should be inherited. """ if output: apply(_implementation, (node, output.write), kw) # depends on [control=['if'], data=[]] else: s = StringIO.StringIO() apply(_implementation, (node, s.write), kw) return s.getvalue()
def closeSession(self): """ C_CloseSession """ rv = self.lib.C_CloseSession(self.session) if rv != CKR_OK: raise PyKCS11Error(rv)
def function[closeSession, parameter[self]]: constant[ C_CloseSession ] variable[rv] assign[=] call[name[self].lib.C_CloseSession, parameter[name[self].session]] if compare[name[rv] not_equal[!=] name[CKR_OK]] begin[:] <ast.Raise object at 0x7da20e9549a0>
keyword[def] identifier[closeSession] ( identifier[self] ): literal[string] identifier[rv] = identifier[self] . identifier[lib] . identifier[C_CloseSession] ( identifier[self] . identifier[session] ) keyword[if] identifier[rv] != identifier[CKR_OK] : keyword[raise] identifier[PyKCS11Error] ( identifier[rv] )
def closeSession(self): """ C_CloseSession """ rv = self.lib.C_CloseSession(self.session) if rv != CKR_OK: raise PyKCS11Error(rv) # depends on [control=['if'], data=['rv']]
def printout(self, print_area, print_data): """Print out print area See: http://aspn.activestate.com/ASPN/Mail/Message/wxpython-users/3471083 """ print_info = \ self.main_window.interfaces.get_cairo_export_info("Print") if print_info is None: # Dialog has been canceled return pdd = wx.PrintDialogData(print_data) printer = wx.Printer(pdd) printout = Printout(self.grid, print_data, print_info) if printer.Print(self.main_window, printout, True): self.print_data = \ wx.PrintData(printer.GetPrintDialogData().GetPrintData()) printout.Destroy()
def function[printout, parameter[self, print_area, print_data]]: constant[Print out print area See: http://aspn.activestate.com/ASPN/Mail/Message/wxpython-users/3471083 ] variable[print_info] assign[=] call[name[self].main_window.interfaces.get_cairo_export_info, parameter[constant[Print]]] if compare[name[print_info] is constant[None]] begin[:] return[None] variable[pdd] assign[=] call[name[wx].PrintDialogData, parameter[name[print_data]]] variable[printer] assign[=] call[name[wx].Printer, parameter[name[pdd]]] variable[printout] assign[=] call[name[Printout], parameter[name[self].grid, name[print_data], name[print_info]]] if call[name[printer].Print, parameter[name[self].main_window, name[printout], constant[True]]] begin[:] name[self].print_data assign[=] call[name[wx].PrintData, parameter[call[call[name[printer].GetPrintDialogData, parameter[]].GetPrintData, parameter[]]]] call[name[printout].Destroy, parameter[]]
keyword[def] identifier[printout] ( identifier[self] , identifier[print_area] , identifier[print_data] ): literal[string] identifier[print_info] = identifier[self] . identifier[main_window] . identifier[interfaces] . identifier[get_cairo_export_info] ( literal[string] ) keyword[if] identifier[print_info] keyword[is] keyword[None] : keyword[return] identifier[pdd] = identifier[wx] . identifier[PrintDialogData] ( identifier[print_data] ) identifier[printer] = identifier[wx] . identifier[Printer] ( identifier[pdd] ) identifier[printout] = identifier[Printout] ( identifier[self] . identifier[grid] , identifier[print_data] , identifier[print_info] ) keyword[if] identifier[printer] . identifier[Print] ( identifier[self] . identifier[main_window] , identifier[printout] , keyword[True] ): identifier[self] . identifier[print_data] = identifier[wx] . identifier[PrintData] ( identifier[printer] . identifier[GetPrintDialogData] (). identifier[GetPrintData] ()) identifier[printout] . identifier[Destroy] ()
def printout(self, print_area, print_data): """Print out print area See: http://aspn.activestate.com/ASPN/Mail/Message/wxpython-users/3471083 """ print_info = self.main_window.interfaces.get_cairo_export_info('Print') if print_info is None: # Dialog has been canceled return # depends on [control=['if'], data=[]] pdd = wx.PrintDialogData(print_data) printer = wx.Printer(pdd) printout = Printout(self.grid, print_data, print_info) if printer.Print(self.main_window, printout, True): self.print_data = wx.PrintData(printer.GetPrintDialogData().GetPrintData()) # depends on [control=['if'], data=[]] printout.Destroy()
def related_archives(self): """ The pathnames of the source distribution(s) for this requirement (a list of strings). .. note:: This property is very new in pip-accel and its logic may need some time to mature. For now any misbehavior by this property shouldn't be too much of a problem because the pathnames reported by this property are only used for cache invalidation (see the :attr:`last_modified` and :attr:`checksum` properties). """ # Escape the requirement's name for use in a regular expression. name_pattern = escape_name(self.name) # Escape the requirement's version for in a regular expression. version_pattern = re.escape(self.version) # Create a regular expression that matches any of the known source # distribution archive extensions. extension_pattern = '|'.join(re.escape(ext) for ext in ARCHIVE_EXTENSIONS if ext != '.whl') # Compose the regular expression pattern to match filenames of source # distribution archives in the local source index directory. pattern = '^%s-%s(%s)$' % (name_pattern, version_pattern, extension_pattern) # Compile the regular expression for case insensitive matching. compiled_pattern = re.compile(pattern, re.IGNORECASE) # Find the matching source distribution archives. return [os.path.join(self.config.source_index, fn) for fn in os.listdir(self.config.source_index) if compiled_pattern.match(fn)]
def function[related_archives, parameter[self]]: constant[ The pathnames of the source distribution(s) for this requirement (a list of strings). .. note:: This property is very new in pip-accel and its logic may need some time to mature. For now any misbehavior by this property shouldn't be too much of a problem because the pathnames reported by this property are only used for cache invalidation (see the :attr:`last_modified` and :attr:`checksum` properties). ] variable[name_pattern] assign[=] call[name[escape_name], parameter[name[self].name]] variable[version_pattern] assign[=] call[name[re].escape, parameter[name[self].version]] variable[extension_pattern] assign[=] call[constant[|].join, parameter[<ast.GeneratorExp object at 0x7da1b05395a0>]] variable[pattern] assign[=] binary_operation[constant[^%s-%s(%s)$] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da1b053b610>, <ast.Name object at 0x7da1b053b160>, <ast.Name object at 0x7da1b053a710>]]] variable[compiled_pattern] assign[=] call[name[re].compile, parameter[name[pattern], name[re].IGNORECASE]] return[<ast.ListComp object at 0x7da1b0538130>]
keyword[def] identifier[related_archives] ( identifier[self] ): literal[string] identifier[name_pattern] = identifier[escape_name] ( identifier[self] . identifier[name] ) identifier[version_pattern] = identifier[re] . identifier[escape] ( identifier[self] . identifier[version] ) identifier[extension_pattern] = literal[string] . identifier[join] ( identifier[re] . identifier[escape] ( identifier[ext] ) keyword[for] identifier[ext] keyword[in] identifier[ARCHIVE_EXTENSIONS] keyword[if] identifier[ext] != literal[string] ) identifier[pattern] = literal[string] %( identifier[name_pattern] , identifier[version_pattern] , identifier[extension_pattern] ) identifier[compiled_pattern] = identifier[re] . identifier[compile] ( identifier[pattern] , identifier[re] . identifier[IGNORECASE] ) keyword[return] [ identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[config] . identifier[source_index] , identifier[fn] ) keyword[for] identifier[fn] keyword[in] identifier[os] . identifier[listdir] ( identifier[self] . identifier[config] . identifier[source_index] ) keyword[if] identifier[compiled_pattern] . identifier[match] ( identifier[fn] )]
def related_archives(self): """ The pathnames of the source distribution(s) for this requirement (a list of strings). .. note:: This property is very new in pip-accel and its logic may need some time to mature. For now any misbehavior by this property shouldn't be too much of a problem because the pathnames reported by this property are only used for cache invalidation (see the :attr:`last_modified` and :attr:`checksum` properties). """ # Escape the requirement's name for use in a regular expression. name_pattern = escape_name(self.name) # Escape the requirement's version for in a regular expression. version_pattern = re.escape(self.version) # Create a regular expression that matches any of the known source # distribution archive extensions. extension_pattern = '|'.join((re.escape(ext) for ext in ARCHIVE_EXTENSIONS if ext != '.whl')) # Compose the regular expression pattern to match filenames of source # distribution archives in the local source index directory. pattern = '^%s-%s(%s)$' % (name_pattern, version_pattern, extension_pattern) # Compile the regular expression for case insensitive matching. compiled_pattern = re.compile(pattern, re.IGNORECASE) # Find the matching source distribution archives. return [os.path.join(self.config.source_index, fn) for fn in os.listdir(self.config.source_index) if compiled_pattern.match(fn)]
def _get_triplets_reciprocal_mesh_at_q(fixed_grid_number, mesh, rotations, is_time_reversal=True, swappable=True): """Search symmetry reduced triplets fixing one q-point Triplets of (q0, q1, q2) are searched. Parameters ---------- fixed_grid_number : int Grid point of q0 mesh : array_like Mesh numbers dtype='intc' shape=(3,) rotations : array_like Rotation matrices in real space. Note that those in reciprocal space mean these matrices transposed (local terminology). dtype='intc' shape=(n_rot, 3, 3) is_time_reversal : bool Inversion symemtry is added if it doesn't exist. swappable : bool q1 and q2 can be swapped. By this number of triplets decreases. """ import phono3py._phono3py as phono3c map_triplets = np.zeros(np.prod(mesh), dtype='uintp') map_q = np.zeros(np.prod(mesh), dtype='uintp') grid_address = np.zeros((np.prod(mesh), 3), dtype='intc') phono3c.triplets_reciprocal_mesh_at_q( map_triplets, map_q, grid_address, fixed_grid_number, np.array(mesh, dtype='intc'), is_time_reversal * 1, np.array(rotations, dtype='intc', order='C'), swappable * 1) return map_triplets, map_q, grid_address
def function[_get_triplets_reciprocal_mesh_at_q, parameter[fixed_grid_number, mesh, rotations, is_time_reversal, swappable]]: constant[Search symmetry reduced triplets fixing one q-point Triplets of (q0, q1, q2) are searched. Parameters ---------- fixed_grid_number : int Grid point of q0 mesh : array_like Mesh numbers dtype='intc' shape=(3,) rotations : array_like Rotation matrices in real space. Note that those in reciprocal space mean these matrices transposed (local terminology). dtype='intc' shape=(n_rot, 3, 3) is_time_reversal : bool Inversion symemtry is added if it doesn't exist. swappable : bool q1 and q2 can be swapped. By this number of triplets decreases. ] import module[phono3py._phono3py] as alias[phono3c] variable[map_triplets] assign[=] call[name[np].zeros, parameter[call[name[np].prod, parameter[name[mesh]]]]] variable[map_q] assign[=] call[name[np].zeros, parameter[call[name[np].prod, parameter[name[mesh]]]]] variable[grid_address] assign[=] call[name[np].zeros, parameter[tuple[[<ast.Call object at 0x7da18bccbdf0>, <ast.Constant object at 0x7da18bccb430>]]]] call[name[phono3c].triplets_reciprocal_mesh_at_q, parameter[name[map_triplets], name[map_q], name[grid_address], name[fixed_grid_number], call[name[np].array, parameter[name[mesh]]], binary_operation[name[is_time_reversal] * constant[1]], call[name[np].array, parameter[name[rotations]]], binary_operation[name[swappable] * constant[1]]]] return[tuple[[<ast.Name object at 0x7da18bcc8af0>, <ast.Name object at 0x7da18bcc9d50>, <ast.Name object at 0x7da18bcc9180>]]]
keyword[def] identifier[_get_triplets_reciprocal_mesh_at_q] ( identifier[fixed_grid_number] , identifier[mesh] , identifier[rotations] , identifier[is_time_reversal] = keyword[True] , identifier[swappable] = keyword[True] ): literal[string] keyword[import] identifier[phono3py] . identifier[_phono3py] keyword[as] identifier[phono3c] identifier[map_triplets] = identifier[np] . identifier[zeros] ( identifier[np] . identifier[prod] ( identifier[mesh] ), identifier[dtype] = literal[string] ) identifier[map_q] = identifier[np] . identifier[zeros] ( identifier[np] . identifier[prod] ( identifier[mesh] ), identifier[dtype] = literal[string] ) identifier[grid_address] = identifier[np] . identifier[zeros] (( identifier[np] . identifier[prod] ( identifier[mesh] ), literal[int] ), identifier[dtype] = literal[string] ) identifier[phono3c] . identifier[triplets_reciprocal_mesh_at_q] ( identifier[map_triplets] , identifier[map_q] , identifier[grid_address] , identifier[fixed_grid_number] , identifier[np] . identifier[array] ( identifier[mesh] , identifier[dtype] = literal[string] ), identifier[is_time_reversal] * literal[int] , identifier[np] . identifier[array] ( identifier[rotations] , identifier[dtype] = literal[string] , identifier[order] = literal[string] ), identifier[swappable] * literal[int] ) keyword[return] identifier[map_triplets] , identifier[map_q] , identifier[grid_address]
def _get_triplets_reciprocal_mesh_at_q(fixed_grid_number, mesh, rotations, is_time_reversal=True, swappable=True): """Search symmetry reduced triplets fixing one q-point Triplets of (q0, q1, q2) are searched. Parameters ---------- fixed_grid_number : int Grid point of q0 mesh : array_like Mesh numbers dtype='intc' shape=(3,) rotations : array_like Rotation matrices in real space. Note that those in reciprocal space mean these matrices transposed (local terminology). dtype='intc' shape=(n_rot, 3, 3) is_time_reversal : bool Inversion symemtry is added if it doesn't exist. swappable : bool q1 and q2 can be swapped. By this number of triplets decreases. """ import phono3py._phono3py as phono3c map_triplets = np.zeros(np.prod(mesh), dtype='uintp') map_q = np.zeros(np.prod(mesh), dtype='uintp') grid_address = np.zeros((np.prod(mesh), 3), dtype='intc') phono3c.triplets_reciprocal_mesh_at_q(map_triplets, map_q, grid_address, fixed_grid_number, np.array(mesh, dtype='intc'), is_time_reversal * 1, np.array(rotations, dtype='intc', order='C'), swappable * 1) return (map_triplets, map_q, grid_address)
def idle_task(self): '''called on idle''' if self.module('console') is not None and not self.menu_added_console: self.menu_added_console = True self.module('console').add_menu(self.menu) if self.module('map') is not None and not self.menu_added_map: self.menu_added_map = True self.module('map').add_menu(self.menu)
def function[idle_task, parameter[self]]: constant[called on idle] if <ast.BoolOp object at 0x7da20e9b1c90> begin[:] name[self].menu_added_console assign[=] constant[True] call[call[name[self].module, parameter[constant[console]]].add_menu, parameter[name[self].menu]] if <ast.BoolOp object at 0x7da20c993c40> begin[:] name[self].menu_added_map assign[=] constant[True] call[call[name[self].module, parameter[constant[map]]].add_menu, parameter[name[self].menu]]
keyword[def] identifier[idle_task] ( identifier[self] ): literal[string] keyword[if] identifier[self] . identifier[module] ( literal[string] ) keyword[is] keyword[not] keyword[None] keyword[and] keyword[not] identifier[self] . identifier[menu_added_console] : identifier[self] . identifier[menu_added_console] = keyword[True] identifier[self] . identifier[module] ( literal[string] ). identifier[add_menu] ( identifier[self] . identifier[menu] ) keyword[if] identifier[self] . identifier[module] ( literal[string] ) keyword[is] keyword[not] keyword[None] keyword[and] keyword[not] identifier[self] . identifier[menu_added_map] : identifier[self] . identifier[menu_added_map] = keyword[True] identifier[self] . identifier[module] ( literal[string] ). identifier[add_menu] ( identifier[self] . identifier[menu] )
def idle_task(self): """called on idle""" if self.module('console') is not None and (not self.menu_added_console): self.menu_added_console = True self.module('console').add_menu(self.menu) # depends on [control=['if'], data=[]] if self.module('map') is not None and (not self.menu_added_map): self.menu_added_map = True self.module('map').add_menu(self.menu) # depends on [control=['if'], data=[]]
def _if_not_closed(f): """Run the method iff. the memory view hasn't been closed and the parent object has not been freed.""" @add_signature_to_docstring(f) @functools.wraps(f) def f_(self, *args, **kwargs): if self.closed or self._parent._freed: raise OSError return f(self, *args, **kwargs) return f_
def function[_if_not_closed, parameter[f]]: constant[Run the method iff. the memory view hasn't been closed and the parent object has not been freed.] def function[f_, parameter[self]]: if <ast.BoolOp object at 0x7da1b19c8910> begin[:] <ast.Raise object at 0x7da1b19c8be0> return[call[name[f], parameter[name[self], <ast.Starred object at 0x7da1b19ca2c0>]]] return[name[f_]]
keyword[def] identifier[_if_not_closed] ( identifier[f] ): literal[string] @ identifier[add_signature_to_docstring] ( identifier[f] ) @ identifier[functools] . identifier[wraps] ( identifier[f] ) keyword[def] identifier[f_] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ): keyword[if] identifier[self] . identifier[closed] keyword[or] identifier[self] . identifier[_parent] . identifier[_freed] : keyword[raise] identifier[OSError] keyword[return] identifier[f] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ) keyword[return] identifier[f_]
def _if_not_closed(f): """Run the method iff. the memory view hasn't been closed and the parent object has not been freed.""" @add_signature_to_docstring(f) @functools.wraps(f) def f_(self, *args, **kwargs): if self.closed or self._parent._freed: raise OSError # depends on [control=['if'], data=[]] return f(self, *args, **kwargs) return f_
def filter(self, record): """Determines if the record should be logged and injects context info into the record. Always returns True""" fmt = LogManager.spec.context_format if fmt: data = self.context.to_dict() if data: record.context = fmt % ",".join("%s=%s" % (key, val) for key, val in sorted(data.items()) if key and val) else: record.context = "" return True
def function[filter, parameter[self, record]]: constant[Determines if the record should be logged and injects context info into the record. Always returns True] variable[fmt] assign[=] name[LogManager].spec.context_format if name[fmt] begin[:] variable[data] assign[=] call[name[self].context.to_dict, parameter[]] if name[data] begin[:] name[record].context assign[=] binary_operation[name[fmt] <ast.Mod object at 0x7da2590d6920> call[constant[,].join, parameter[<ast.GeneratorExp object at 0x7da1b242a3e0>]]] return[constant[True]]
keyword[def] identifier[filter] ( identifier[self] , identifier[record] ): literal[string] identifier[fmt] = identifier[LogManager] . identifier[spec] . identifier[context_format] keyword[if] identifier[fmt] : identifier[data] = identifier[self] . identifier[context] . identifier[to_dict] () keyword[if] identifier[data] : identifier[record] . identifier[context] = identifier[fmt] % literal[string] . identifier[join] ( literal[string] %( identifier[key] , identifier[val] ) keyword[for] identifier[key] , identifier[val] keyword[in] identifier[sorted] ( identifier[data] . identifier[items] ()) keyword[if] identifier[key] keyword[and] identifier[val] ) keyword[else] : identifier[record] . identifier[context] = literal[string] keyword[return] keyword[True]
def filter(self, record): """Determines if the record should be logged and injects context info into the record. Always returns True""" fmt = LogManager.spec.context_format if fmt: data = self.context.to_dict() if data: record.context = fmt % ','.join(('%s=%s' % (key, val) for (key, val) in sorted(data.items()) if key and val)) # depends on [control=['if'], data=[]] else: record.context = '' # depends on [control=['if'], data=[]] return True
def __put_key(self, local_file, target_file, acl='public-read', del_after_upload=False, overwrite=True, source="filename"): """Copy a file to s3.""" action_word = "moving" if del_after_upload else "copying" try: self.k.key = target_file # setting the path (key) of file in the container if source == "filename": # grabs the contents from local_file address. Note that it loads the whole file into memory self.k.set_contents_from_filename(local_file, self.AWS_HEADERS) elif source == "fileobj": self.k.set_contents_from_file(local_file, self.AWS_HEADERS) elif source == "string": self.k.set_contents_from_string(local_file, self.AWS_HEADERS) else: raise Exception("%s is not implemented as a source." % source) self.k.set_acl(acl) # setting the file permissions self.k.close() # not sure if it is needed. Somewhere I read it is recommended. self.printv("%s %s to %s" % (action_word, local_file, target_file)) # if it is supposed to delete the local file after uploading if del_after_upload and source == "filename": try: os.remove(local_file) except: logger.error("Unable to delete the file: ", local_file, exc_info=True) return True except: logger.error("Error in writing to %s", target_file, exc_info=True) return False
def function[__put_key, parameter[self, local_file, target_file, acl, del_after_upload, overwrite, source]]: constant[Copy a file to s3.] variable[action_word] assign[=] <ast.IfExp object at 0x7da20c6a8880> <ast.Try object at 0x7da20c6a9780>
keyword[def] identifier[__put_key] ( identifier[self] , identifier[local_file] , identifier[target_file] , identifier[acl] = literal[string] , identifier[del_after_upload] = keyword[False] , identifier[overwrite] = keyword[True] , identifier[source] = literal[string] ): literal[string] identifier[action_word] = literal[string] keyword[if] identifier[del_after_upload] keyword[else] literal[string] keyword[try] : identifier[self] . identifier[k] . identifier[key] = identifier[target_file] keyword[if] identifier[source] == literal[string] : identifier[self] . identifier[k] . identifier[set_contents_from_filename] ( identifier[local_file] , identifier[self] . identifier[AWS_HEADERS] ) keyword[elif] identifier[source] == literal[string] : identifier[self] . identifier[k] . identifier[set_contents_from_file] ( identifier[local_file] , identifier[self] . identifier[AWS_HEADERS] ) keyword[elif] identifier[source] == literal[string] : identifier[self] . identifier[k] . identifier[set_contents_from_string] ( identifier[local_file] , identifier[self] . identifier[AWS_HEADERS] ) keyword[else] : keyword[raise] identifier[Exception] ( literal[string] % identifier[source] ) identifier[self] . identifier[k] . identifier[set_acl] ( identifier[acl] ) identifier[self] . identifier[k] . identifier[close] () identifier[self] . identifier[printv] ( literal[string] %( identifier[action_word] , identifier[local_file] , identifier[target_file] )) keyword[if] identifier[del_after_upload] keyword[and] identifier[source] == literal[string] : keyword[try] : identifier[os] . identifier[remove] ( identifier[local_file] ) keyword[except] : identifier[logger] . identifier[error] ( literal[string] , identifier[local_file] , identifier[exc_info] = keyword[True] ) keyword[return] keyword[True] keyword[except] : identifier[logger] . identifier[error] ( literal[string] , identifier[target_file] , identifier[exc_info] = keyword[True] ) keyword[return] keyword[False]
def __put_key(self, local_file, target_file, acl='public-read', del_after_upload=False, overwrite=True, source='filename'): """Copy a file to s3.""" action_word = 'moving' if del_after_upload else 'copying' try: self.k.key = target_file # setting the path (key) of file in the container if source == 'filename': # grabs the contents from local_file address. Note that it loads the whole file into memory self.k.set_contents_from_filename(local_file, self.AWS_HEADERS) # depends on [control=['if'], data=[]] elif source == 'fileobj': self.k.set_contents_from_file(local_file, self.AWS_HEADERS) # depends on [control=['if'], data=[]] elif source == 'string': self.k.set_contents_from_string(local_file, self.AWS_HEADERS) # depends on [control=['if'], data=[]] else: raise Exception('%s is not implemented as a source.' % source) self.k.set_acl(acl) # setting the file permissions self.k.close() # not sure if it is needed. Somewhere I read it is recommended. self.printv('%s %s to %s' % (action_word, local_file, target_file)) # if it is supposed to delete the local file after uploading if del_after_upload and source == 'filename': try: os.remove(local_file) # depends on [control=['try'], data=[]] except: logger.error('Unable to delete the file: ', local_file, exc_info=True) # depends on [control=['except'], data=[]] # depends on [control=['if'], data=[]] return True # depends on [control=['try'], data=[]] except: logger.error('Error in writing to %s', target_file, exc_info=True) return False # depends on [control=['except'], data=[]]
def SOAPUriToVersion(self, uri): """Return the SOAP version related to an envelope uri.""" value = self._soap_uri_mapping.get(uri) if value is not None: return value raise ValueError( 'Unsupported SOAP envelope uri: %s' % uri )
def function[SOAPUriToVersion, parameter[self, uri]]: constant[Return the SOAP version related to an envelope uri.] variable[value] assign[=] call[name[self]._soap_uri_mapping.get, parameter[name[uri]]] if compare[name[value] is_not constant[None]] begin[:] return[name[value]] <ast.Raise object at 0x7da1b15f3eb0>
keyword[def] identifier[SOAPUriToVersion] ( identifier[self] , identifier[uri] ): literal[string] identifier[value] = identifier[self] . identifier[_soap_uri_mapping] . identifier[get] ( identifier[uri] ) keyword[if] identifier[value] keyword[is] keyword[not] keyword[None] : keyword[return] identifier[value] keyword[raise] identifier[ValueError] ( literal[string] % identifier[uri] )
def SOAPUriToVersion(self, uri): """Return the SOAP version related to an envelope uri.""" value = self._soap_uri_mapping.get(uri) if value is not None: return value # depends on [control=['if'], data=['value']] raise ValueError('Unsupported SOAP envelope uri: %s' % uri)
def on_user_status( self=None, filters=None, group: int = 0 ) -> callable: """Use this decorator to automatically register a function for handling user status updates. This does the same thing as :meth:`add_handler` using the :class:`UserStatusHandler`. Args: filters (:obj:`Filters <pyrogram.Filters>`): Pass one or more filters to allow only a subset of UserStatus updated to be passed in your function. group (``int``, *optional*): The group identifier, defaults to 0. """ def decorator(func: callable) -> Tuple[Handler, int]: if isinstance(func, tuple): func = func[0].callback handler = pyrogram.UserStatusHandler(func, filters) if isinstance(self, Filter): return pyrogram.UserStatusHandler(func, self), group if filters is None else filters if self is not None: self.add_handler(handler, group) return handler, group return decorator
def function[on_user_status, parameter[self, filters, group]]: constant[Use this decorator to automatically register a function for handling user status updates. This does the same thing as :meth:`add_handler` using the :class:`UserStatusHandler`. Args: filters (:obj:`Filters <pyrogram.Filters>`): Pass one or more filters to allow only a subset of UserStatus updated to be passed in your function. group (``int``, *optional*): The group identifier, defaults to 0. ] def function[decorator, parameter[func]]: if call[name[isinstance], parameter[name[func], name[tuple]]] begin[:] variable[func] assign[=] call[name[func]][constant[0]].callback variable[handler] assign[=] call[name[pyrogram].UserStatusHandler, parameter[name[func], name[filters]]] if call[name[isinstance], parameter[name[self], name[Filter]]] begin[:] return[tuple[[<ast.Call object at 0x7da20c6e6ad0>, <ast.IfExp object at 0x7da20c6e6080>]]] if compare[name[self] is_not constant[None]] begin[:] call[name[self].add_handler, parameter[name[handler], name[group]]] return[tuple[[<ast.Name object at 0x7da20c6e5e10>, <ast.Name object at 0x7da20c6e7640>]]] return[name[decorator]]
keyword[def] identifier[on_user_status] ( identifier[self] = keyword[None] , identifier[filters] = keyword[None] , identifier[group] : identifier[int] = literal[int] )-> identifier[callable] : literal[string] keyword[def] identifier[decorator] ( identifier[func] : identifier[callable] )-> identifier[Tuple] [ identifier[Handler] , identifier[int] ]: keyword[if] identifier[isinstance] ( identifier[func] , identifier[tuple] ): identifier[func] = identifier[func] [ literal[int] ]. identifier[callback] identifier[handler] = identifier[pyrogram] . identifier[UserStatusHandler] ( identifier[func] , identifier[filters] ) keyword[if] identifier[isinstance] ( identifier[self] , identifier[Filter] ): keyword[return] identifier[pyrogram] . identifier[UserStatusHandler] ( identifier[func] , identifier[self] ), identifier[group] keyword[if] identifier[filters] keyword[is] keyword[None] keyword[else] identifier[filters] keyword[if] identifier[self] keyword[is] keyword[not] keyword[None] : identifier[self] . identifier[add_handler] ( identifier[handler] , identifier[group] ) keyword[return] identifier[handler] , identifier[group] keyword[return] identifier[decorator]
def on_user_status(self=None, filters=None, group: int=0) -> callable: """Use this decorator to automatically register a function for handling user status updates. This does the same thing as :meth:`add_handler` using the :class:`UserStatusHandler`. Args: filters (:obj:`Filters <pyrogram.Filters>`): Pass one or more filters to allow only a subset of UserStatus updated to be passed in your function. group (``int``, *optional*): The group identifier, defaults to 0. """ def decorator(func: callable) -> Tuple[Handler, int]: if isinstance(func, tuple): func = func[0].callback # depends on [control=['if'], data=[]] handler = pyrogram.UserStatusHandler(func, filters) if isinstance(self, Filter): return (pyrogram.UserStatusHandler(func, self), group if filters is None else filters) # depends on [control=['if'], data=[]] if self is not None: self.add_handler(handler, group) # depends on [control=['if'], data=['self']] return (handler, group) return decorator
def retcode_pillar(pillar_name): ''' Run one or more nagios plugins from pillar data and get the result of cmd.retcode The pillar have to be in this format:: ------ webserver: Ping_google: - check_icmp: 8.8.8.8 - check_icmp: google.com Load: - check_load: -w 0.8 -c 1 APT: - check_apt ------- webserver is the role to check, the next keys are the group and the items the check with the arguments if needed You must to group different checks(one o more) and always it will return the highest value of all the checks CLI Example: .. code-block:: bash salt '*' nagios.retcode webserver ''' groups = __salt__['pillar.get'](pillar_name) check = {} data = {} for group in groups: commands = groups[group] for command in commands: # Check if is a dict to get the arguments # in command if not set the arguments to empty string if isinstance(command, dict): plugin = next(six.iterkeys(command)) args = command[plugin] else: plugin = command args = '' check.update(retcode(plugin, args, group)) current_value = 0 new_value = int(check[group]['status']) if group in data: current_value = int(data[group]['status']) if (new_value > current_value) or (group not in data): if group not in data: data[group] = {} data[group]['status'] = new_value return data
def function[retcode_pillar, parameter[pillar_name]]: constant[ Run one or more nagios plugins from pillar data and get the result of cmd.retcode The pillar have to be in this format:: ------ webserver: Ping_google: - check_icmp: 8.8.8.8 - check_icmp: google.com Load: - check_load: -w 0.8 -c 1 APT: - check_apt ------- webserver is the role to check, the next keys are the group and the items the check with the arguments if needed You must to group different checks(one o more) and always it will return the highest value of all the checks CLI Example: .. code-block:: bash salt '*' nagios.retcode webserver ] variable[groups] assign[=] call[call[name[__salt__]][constant[pillar.get]], parameter[name[pillar_name]]] variable[check] assign[=] dictionary[[], []] variable[data] assign[=] dictionary[[], []] for taget[name[group]] in starred[name[groups]] begin[:] variable[commands] assign[=] call[name[groups]][name[group]] for taget[name[command]] in starred[name[commands]] begin[:] if call[name[isinstance], parameter[name[command], name[dict]]] begin[:] variable[plugin] assign[=] call[name[next], parameter[call[name[six].iterkeys, parameter[name[command]]]]] variable[args] assign[=] call[name[command]][name[plugin]] call[name[check].update, parameter[call[name[retcode], parameter[name[plugin], name[args], name[group]]]]] variable[current_value] assign[=] constant[0] variable[new_value] assign[=] call[name[int], parameter[call[call[name[check]][name[group]]][constant[status]]]] if compare[name[group] in name[data]] begin[:] variable[current_value] assign[=] call[name[int], parameter[call[call[name[data]][name[group]]][constant[status]]]] if <ast.BoolOp object at 0x7da1b26ac100> begin[:] if compare[name[group] <ast.NotIn object at 0x7da2590d7190> name[data]] begin[:] call[name[data]][name[group]] assign[=] dictionary[[], []] call[call[name[data]][name[group]]][constant[status]] assign[=] name[new_value] return[name[data]]
keyword[def] identifier[retcode_pillar] ( identifier[pillar_name] ): literal[string] identifier[groups] = identifier[__salt__] [ literal[string] ]( identifier[pillar_name] ) identifier[check] ={} identifier[data] ={} keyword[for] identifier[group] keyword[in] identifier[groups] : identifier[commands] = identifier[groups] [ identifier[group] ] keyword[for] identifier[command] keyword[in] identifier[commands] : keyword[if] identifier[isinstance] ( identifier[command] , identifier[dict] ): identifier[plugin] = identifier[next] ( identifier[six] . identifier[iterkeys] ( identifier[command] )) identifier[args] = identifier[command] [ identifier[plugin] ] keyword[else] : identifier[plugin] = identifier[command] identifier[args] = literal[string] identifier[check] . identifier[update] ( identifier[retcode] ( identifier[plugin] , identifier[args] , identifier[group] )) identifier[current_value] = literal[int] identifier[new_value] = identifier[int] ( identifier[check] [ identifier[group] ][ literal[string] ]) keyword[if] identifier[group] keyword[in] identifier[data] : identifier[current_value] = identifier[int] ( identifier[data] [ identifier[group] ][ literal[string] ]) keyword[if] ( identifier[new_value] > identifier[current_value] ) keyword[or] ( identifier[group] keyword[not] keyword[in] identifier[data] ): keyword[if] identifier[group] keyword[not] keyword[in] identifier[data] : identifier[data] [ identifier[group] ]={} identifier[data] [ identifier[group] ][ literal[string] ]= identifier[new_value] keyword[return] identifier[data]
def retcode_pillar(pillar_name): """ Run one or more nagios plugins from pillar data and get the result of cmd.retcode The pillar have to be in this format:: ------ webserver: Ping_google: - check_icmp: 8.8.8.8 - check_icmp: google.com Load: - check_load: -w 0.8 -c 1 APT: - check_apt ------- webserver is the role to check, the next keys are the group and the items the check with the arguments if needed You must to group different checks(one o more) and always it will return the highest value of all the checks CLI Example: .. code-block:: bash salt '*' nagios.retcode webserver """ groups = __salt__['pillar.get'](pillar_name) check = {} data = {} for group in groups: commands = groups[group] for command in commands: # Check if is a dict to get the arguments # in command if not set the arguments to empty string if isinstance(command, dict): plugin = next(six.iterkeys(command)) args = command[plugin] # depends on [control=['if'], data=[]] else: plugin = command args = '' check.update(retcode(plugin, args, group)) current_value = 0 new_value = int(check[group]['status']) if group in data: current_value = int(data[group]['status']) # depends on [control=['if'], data=['group', 'data']] if new_value > current_value or group not in data: if group not in data: data[group] = {} # depends on [control=['if'], data=['group', 'data']] data[group]['status'] = new_value # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['command']] # depends on [control=['for'], data=['group']] return data
def request_io(self, iocb): """Called by a client to start processing a request.""" if _debug: IOController._debug("request_io %r", iocb) # check that the parameter is an IOCB if not isinstance(iocb, IOCB): raise TypeError("IOCB expected") # bind the iocb to this controller iocb.ioController = self try: # hopefully there won't be an error err = None # change the state iocb.ioState = PENDING # let derived class figure out how to process this self.process_io(iocb) except: # extract the error err = sys.exc_info()[1] # if there was an error, abort the request if err: self.abort_io(iocb, err)
def function[request_io, parameter[self, iocb]]: constant[Called by a client to start processing a request.] if name[_debug] begin[:] call[name[IOController]._debug, parameter[constant[request_io %r], name[iocb]]] if <ast.UnaryOp object at 0x7da1b0812830> begin[:] <ast.Raise object at 0x7da1b0812e00> name[iocb].ioController assign[=] name[self] <ast.Try object at 0x7da1b0812e60> if name[err] begin[:] call[name[self].abort_io, parameter[name[iocb], name[err]]]
keyword[def] identifier[request_io] ( identifier[self] , identifier[iocb] ): literal[string] keyword[if] identifier[_debug] : identifier[IOController] . identifier[_debug] ( literal[string] , identifier[iocb] ) keyword[if] keyword[not] identifier[isinstance] ( identifier[iocb] , identifier[IOCB] ): keyword[raise] identifier[TypeError] ( literal[string] ) identifier[iocb] . identifier[ioController] = identifier[self] keyword[try] : identifier[err] = keyword[None] identifier[iocb] . identifier[ioState] = identifier[PENDING] identifier[self] . identifier[process_io] ( identifier[iocb] ) keyword[except] : identifier[err] = identifier[sys] . identifier[exc_info] ()[ literal[int] ] keyword[if] identifier[err] : identifier[self] . identifier[abort_io] ( identifier[iocb] , identifier[err] )
def request_io(self, iocb): """Called by a client to start processing a request.""" if _debug: IOController._debug('request_io %r', iocb) # depends on [control=['if'], data=[]] # check that the parameter is an IOCB if not isinstance(iocb, IOCB): raise TypeError('IOCB expected') # depends on [control=['if'], data=[]] # bind the iocb to this controller iocb.ioController = self try: # hopefully there won't be an error err = None # change the state iocb.ioState = PENDING # let derived class figure out how to process this self.process_io(iocb) # depends on [control=['try'], data=[]] except: # extract the error err = sys.exc_info()[1] # depends on [control=['except'], data=[]] # if there was an error, abort the request if err: self.abort_io(iocb, err) # depends on [control=['if'], data=[]]
def headerHTML(self,fname=None): """read the ABF header and save it HTML formatted.""" if fname is None: fname = self.fname.replace(".abf","_header.html") html="<html><body><code>" html+="<h2>abfinfo() for %s.abf</h2>"%self.ID html+=self.abfinfo().replace("<","&lt;").replace(">","&gt;").replace("\n","<br>") html+="<h2>Header for %s.abf</h2>"%self.ID html+=pprint.pformat(self.header, indent=1) html=html.replace("\n",'<br>').replace(" ","&nbsp;") html=html.replace(r"\x00","") html+="</code></body></html>" print("WRITING HEADER TO:") print(fname) f=open(fname,'w') f.write(html) f.close()
def function[headerHTML, parameter[self, fname]]: constant[read the ABF header and save it HTML formatted.] if compare[name[fname] is constant[None]] begin[:] variable[fname] assign[=] call[name[self].fname.replace, parameter[constant[.abf], constant[_header.html]]] variable[html] assign[=] constant[<html><body><code>] <ast.AugAssign object at 0x7da1afe1b5e0> <ast.AugAssign object at 0x7da1afe1a1d0> <ast.AugAssign object at 0x7da1afe1a230> <ast.AugAssign object at 0x7da1afe19750> variable[html] assign[=] call[call[name[html].replace, parameter[constant[ ], constant[<br>]]].replace, parameter[constant[ ], constant[&nbsp;]]] variable[html] assign[=] call[name[html].replace, parameter[constant[\x00], constant[]]] <ast.AugAssign object at 0x7da1afef0fd0> call[name[print], parameter[constant[WRITING HEADER TO:]]] call[name[print], parameter[name[fname]]] variable[f] assign[=] call[name[open], parameter[name[fname], constant[w]]] call[name[f].write, parameter[name[html]]] call[name[f].close, parameter[]]
keyword[def] identifier[headerHTML] ( identifier[self] , identifier[fname] = keyword[None] ): literal[string] keyword[if] identifier[fname] keyword[is] keyword[None] : identifier[fname] = identifier[self] . identifier[fname] . identifier[replace] ( literal[string] , literal[string] ) identifier[html] = literal[string] identifier[html] += literal[string] % identifier[self] . identifier[ID] identifier[html] += identifier[self] . identifier[abfinfo] (). identifier[replace] ( literal[string] , literal[string] ). identifier[replace] ( literal[string] , literal[string] ). identifier[replace] ( literal[string] , literal[string] ) identifier[html] += literal[string] % identifier[self] . identifier[ID] identifier[html] += identifier[pprint] . identifier[pformat] ( identifier[self] . identifier[header] , identifier[indent] = literal[int] ) identifier[html] = identifier[html] . identifier[replace] ( literal[string] , literal[string] ). identifier[replace] ( literal[string] , literal[string] ) identifier[html] = identifier[html] . identifier[replace] ( literal[string] , literal[string] ) identifier[html] += literal[string] identifier[print] ( literal[string] ) identifier[print] ( identifier[fname] ) identifier[f] = identifier[open] ( identifier[fname] , literal[string] ) identifier[f] . identifier[write] ( identifier[html] ) identifier[f] . identifier[close] ()
def headerHTML(self, fname=None): """read the ABF header and save it HTML formatted.""" if fname is None: fname = self.fname.replace('.abf', '_header.html') # depends on [control=['if'], data=['fname']] html = '<html><body><code>' html += '<h2>abfinfo() for %s.abf</h2>' % self.ID html += self.abfinfo().replace('<', '&lt;').replace('>', '&gt;').replace('\n', '<br>') html += '<h2>Header for %s.abf</h2>' % self.ID html += pprint.pformat(self.header, indent=1) html = html.replace('\n', '<br>').replace(' ', '&nbsp;') html = html.replace('\\x00', '') html += '</code></body></html>' print('WRITING HEADER TO:') print(fname) f = open(fname, 'w') f.write(html) f.close()
def hscan(self, key, cursor=0, match=None, count=None): """Incrementally iterate hash fields and associated values.""" args = [key, cursor] match is not None and args.extend([b'MATCH', match]) count is not None and args.extend([b'COUNT', count]) fut = self.execute(b'HSCAN', *args) return wait_convert(fut, _make_pairs)
def function[hscan, parameter[self, key, cursor, match, count]]: constant[Incrementally iterate hash fields and associated values.] variable[args] assign[=] list[[<ast.Name object at 0x7da2054a7790>, <ast.Name object at 0x7da2054a7ac0>]] <ast.BoolOp object at 0x7da2054a5150> <ast.BoolOp object at 0x7da2054a4730> variable[fut] assign[=] call[name[self].execute, parameter[constant[b'HSCAN'], <ast.Starred object at 0x7da2054a5cc0>]] return[call[name[wait_convert], parameter[name[fut], name[_make_pairs]]]]
keyword[def] identifier[hscan] ( identifier[self] , identifier[key] , identifier[cursor] = literal[int] , identifier[match] = keyword[None] , identifier[count] = keyword[None] ): literal[string] identifier[args] =[ identifier[key] , identifier[cursor] ] identifier[match] keyword[is] keyword[not] keyword[None] keyword[and] identifier[args] . identifier[extend] ([ literal[string] , identifier[match] ]) identifier[count] keyword[is] keyword[not] keyword[None] keyword[and] identifier[args] . identifier[extend] ([ literal[string] , identifier[count] ]) identifier[fut] = identifier[self] . identifier[execute] ( literal[string] ,* identifier[args] ) keyword[return] identifier[wait_convert] ( identifier[fut] , identifier[_make_pairs] )
def hscan(self, key, cursor=0, match=None, count=None): """Incrementally iterate hash fields and associated values.""" args = [key, cursor] match is not None and args.extend([b'MATCH', match]) count is not None and args.extend([b'COUNT', count]) fut = self.execute(b'HSCAN', *args) return wait_convert(fut, _make_pairs)
def _exc_to_net(param1, success): """ translate http code to net code. if accertion failed, set net code to 314 """ if len(param1) <= 3: # FIXME: we're unable to use better logic here, because we should support non-http codes # but, we should look for core.util.HTTP or some other common logic # here if success: return 0 else: return 314 exc = param1.split(' ')[-1] if exc in KNOWN_EXC.keys(): return KNOWN_EXC[exc] else: logger.warning( "Unknown Java exception, consider adding it to dictionary: %s", param1) return 41
def function[_exc_to_net, parameter[param1, success]]: constant[ translate http code to net code. if accertion failed, set net code to 314 ] if compare[call[name[len], parameter[name[param1]]] less_or_equal[<=] constant[3]] begin[:] if name[success] begin[:] return[constant[0]] variable[exc] assign[=] call[call[name[param1].split, parameter[constant[ ]]]][<ast.UnaryOp object at 0x7da1b0352920>] if compare[name[exc] in call[name[KNOWN_EXC].keys, parameter[]]] begin[:] return[call[name[KNOWN_EXC]][name[exc]]]
keyword[def] identifier[_exc_to_net] ( identifier[param1] , identifier[success] ): literal[string] keyword[if] identifier[len] ( identifier[param1] )<= literal[int] : keyword[if] identifier[success] : keyword[return] literal[int] keyword[else] : keyword[return] literal[int] identifier[exc] = identifier[param1] . identifier[split] ( literal[string] )[- literal[int] ] keyword[if] identifier[exc] keyword[in] identifier[KNOWN_EXC] . identifier[keys] (): keyword[return] identifier[KNOWN_EXC] [ identifier[exc] ] keyword[else] : identifier[logger] . identifier[warning] ( literal[string] , identifier[param1] ) keyword[return] literal[int]
def _exc_to_net(param1, success): """ translate http code to net code. if accertion failed, set net code to 314 """ if len(param1) <= 3: # FIXME: we're unable to use better logic here, because we should support non-http codes # but, we should look for core.util.HTTP or some other common logic # here if success: return 0 # depends on [control=['if'], data=[]] else: return 314 # depends on [control=['if'], data=[]] exc = param1.split(' ')[-1] if exc in KNOWN_EXC.keys(): return KNOWN_EXC[exc] # depends on [control=['if'], data=['exc']] else: logger.warning('Unknown Java exception, consider adding it to dictionary: %s', param1) return 41
def get_stops(records, group_dist): """ Group records arounds stop locations and returns a list of dict(location, records) for each stop. Parameters ---------- records : list A list of Record objects ordered by non-decreasing datetime group_dist : float Minimum distance (in meters) to switch to a new stop. """ def traverse(start, next): position_prev = records[next - 1].position.location position_next = records[next].position.location dist = 1000 * great_circle_distance(position_prev, position_next) return dist <= group_dist groups = _groupwhile(records, traverse) def median(x): return sorted(x)[len(x) // 2] stops = [] for g in groups: _lat = median([gv.position.location[0] for gv in g]) _lon = median([gv.position.location[1] for gv in g]) stops.append({ 'location': (_lat, _lon), 'records': g, }) return stops
def function[get_stops, parameter[records, group_dist]]: constant[ Group records arounds stop locations and returns a list of dict(location, records) for each stop. Parameters ---------- records : list A list of Record objects ordered by non-decreasing datetime group_dist : float Minimum distance (in meters) to switch to a new stop. ] def function[traverse, parameter[start, next]]: variable[position_prev] assign[=] call[name[records]][binary_operation[name[next] - constant[1]]].position.location variable[position_next] assign[=] call[name[records]][name[next]].position.location variable[dist] assign[=] binary_operation[constant[1000] * call[name[great_circle_distance], parameter[name[position_prev], name[position_next]]]] return[compare[name[dist] less_or_equal[<=] name[group_dist]]] variable[groups] assign[=] call[name[_groupwhile], parameter[name[records], name[traverse]]] def function[median, parameter[x]]: return[call[call[name[sorted], parameter[name[x]]]][binary_operation[call[name[len], parameter[name[x]]] <ast.FloorDiv object at 0x7da2590d6bc0> constant[2]]]] variable[stops] assign[=] list[[]] for taget[name[g]] in starred[name[groups]] begin[:] variable[_lat] assign[=] call[name[median], parameter[<ast.ListComp object at 0x7da20c6e5ed0>]] variable[_lon] assign[=] call[name[median], parameter[<ast.ListComp object at 0x7da20c6e7400>]] call[name[stops].append, parameter[dictionary[[<ast.Constant object at 0x7da20c6e4c40>, <ast.Constant object at 0x7da20c6e7dc0>], [<ast.Tuple object at 0x7da20c6e73a0>, <ast.Name object at 0x7da20c6e5000>]]]] return[name[stops]]
keyword[def] identifier[get_stops] ( identifier[records] , identifier[group_dist] ): literal[string] keyword[def] identifier[traverse] ( identifier[start] , identifier[next] ): identifier[position_prev] = identifier[records] [ identifier[next] - literal[int] ]. identifier[position] . identifier[location] identifier[position_next] = identifier[records] [ identifier[next] ]. identifier[position] . identifier[location] identifier[dist] = literal[int] * identifier[great_circle_distance] ( identifier[position_prev] , identifier[position_next] ) keyword[return] identifier[dist] <= identifier[group_dist] identifier[groups] = identifier[_groupwhile] ( identifier[records] , identifier[traverse] ) keyword[def] identifier[median] ( identifier[x] ): keyword[return] identifier[sorted] ( identifier[x] )[ identifier[len] ( identifier[x] )// literal[int] ] identifier[stops] =[] keyword[for] identifier[g] keyword[in] identifier[groups] : identifier[_lat] = identifier[median] ([ identifier[gv] . identifier[position] . identifier[location] [ literal[int] ] keyword[for] identifier[gv] keyword[in] identifier[g] ]) identifier[_lon] = identifier[median] ([ identifier[gv] . identifier[position] . identifier[location] [ literal[int] ] keyword[for] identifier[gv] keyword[in] identifier[g] ]) identifier[stops] . identifier[append] ({ literal[string] :( identifier[_lat] , identifier[_lon] ), literal[string] : identifier[g] , }) keyword[return] identifier[stops]
def get_stops(records, group_dist): """ Group records arounds stop locations and returns a list of dict(location, records) for each stop. Parameters ---------- records : list A list of Record objects ordered by non-decreasing datetime group_dist : float Minimum distance (in meters) to switch to a new stop. """ def traverse(start, next): position_prev = records[next - 1].position.location position_next = records[next].position.location dist = 1000 * great_circle_distance(position_prev, position_next) return dist <= group_dist groups = _groupwhile(records, traverse) def median(x): return sorted(x)[len(x) // 2] stops = [] for g in groups: _lat = median([gv.position.location[0] for gv in g]) _lon = median([gv.position.location[1] for gv in g]) stops.append({'location': (_lat, _lon), 'records': g}) # depends on [control=['for'], data=['g']] return stops
def lambda_not_found_response(*args): """ Constructs a Flask Response for when a Lambda function is not found for an endpoint :return: a Flask Response """ response_data = jsonify(ServiceErrorResponses._NO_LAMBDA_INTEGRATION) return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502)
def function[lambda_not_found_response, parameter[]]: constant[ Constructs a Flask Response for when a Lambda function is not found for an endpoint :return: a Flask Response ] variable[response_data] assign[=] call[name[jsonify], parameter[name[ServiceErrorResponses]._NO_LAMBDA_INTEGRATION]] return[call[name[make_response], parameter[name[response_data], name[ServiceErrorResponses].HTTP_STATUS_CODE_502]]]
keyword[def] identifier[lambda_not_found_response] (* identifier[args] ): literal[string] identifier[response_data] = identifier[jsonify] ( identifier[ServiceErrorResponses] . identifier[_NO_LAMBDA_INTEGRATION] ) keyword[return] identifier[make_response] ( identifier[response_data] , identifier[ServiceErrorResponses] . identifier[HTTP_STATUS_CODE_502] )
def lambda_not_found_response(*args): """ Constructs a Flask Response for when a Lambda function is not found for an endpoint :return: a Flask Response """ response_data = jsonify(ServiceErrorResponses._NO_LAMBDA_INTEGRATION) return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502)
def _dict(content): """ Helper funcation that converts text-based get response to a python dictionary for additional manipulation. """ if _has_pandas: data = _data_frame(content).to_dict(orient='records') else: response = loads(content) key = [x for x in response.keys() if x in c.response_data][0] data = response[key] return data
def function[_dict, parameter[content]]: constant[ Helper funcation that converts text-based get response to a python dictionary for additional manipulation. ] if name[_has_pandas] begin[:] variable[data] assign[=] call[call[name[_data_frame], parameter[name[content]]].to_dict, parameter[]] return[name[data]]
keyword[def] identifier[_dict] ( identifier[content] ): literal[string] keyword[if] identifier[_has_pandas] : identifier[data] = identifier[_data_frame] ( identifier[content] ). identifier[to_dict] ( identifier[orient] = literal[string] ) keyword[else] : identifier[response] = identifier[loads] ( identifier[content] ) identifier[key] =[ identifier[x] keyword[for] identifier[x] keyword[in] identifier[response] . identifier[keys] () keyword[if] identifier[x] keyword[in] identifier[c] . identifier[response_data] ][ literal[int] ] identifier[data] = identifier[response] [ identifier[key] ] keyword[return] identifier[data]
def _dict(content): """ Helper funcation that converts text-based get response to a python dictionary for additional manipulation. """ if _has_pandas: data = _data_frame(content).to_dict(orient='records') # depends on [control=['if'], data=[]] else: response = loads(content) key = [x for x in response.keys() if x in c.response_data][0] data = response[key] return data
def reject(self, reason): """ Reject this promise for a given reason. """ assert self._state==self.PENDING self._state=self.REJECTED; self.reason = reason for errback in self._errbacks: try: errback(reason) except Exception: # Ignore errors in callbacks pass # We will never call these errbacks again, so allow # them to be garbage collected. This is important since # they probably include closures which are binding variables # that might otherwise be garbage collected. self._errbacks = []
def function[reject, parameter[self, reason]]: constant[ Reject this promise for a given reason. ] assert[compare[name[self]._state equal[==] name[self].PENDING]] name[self]._state assign[=] name[self].REJECTED name[self].reason assign[=] name[reason] for taget[name[errback]] in starred[name[self]._errbacks] begin[:] <ast.Try object at 0x7da1b0966230> name[self]._errbacks assign[=] list[[]]
keyword[def] identifier[reject] ( identifier[self] , identifier[reason] ): literal[string] keyword[assert] identifier[self] . identifier[_state] == identifier[self] . identifier[PENDING] identifier[self] . identifier[_state] = identifier[self] . identifier[REJECTED] ; identifier[self] . identifier[reason] = identifier[reason] keyword[for] identifier[errback] keyword[in] identifier[self] . identifier[_errbacks] : keyword[try] : identifier[errback] ( identifier[reason] ) keyword[except] identifier[Exception] : keyword[pass] identifier[self] . identifier[_errbacks] =[]
def reject(self, reason): """ Reject this promise for a given reason. """ assert self._state == self.PENDING self._state = self.REJECTED self.reason = reason for errback in self._errbacks: try: errback(reason) # depends on [control=['try'], data=[]] except Exception: # Ignore errors in callbacks pass # depends on [control=['except'], data=[]] # depends on [control=['for'], data=['errback']] # We will never call these errbacks again, so allow # them to be garbage collected. This is important since # they probably include closures which are binding variables # that might otherwise be garbage collected. self._errbacks = []
def mfpt(T, target): r"""Mean first passage times to a set of target states. Parameters ---------- T : ndarray, shape=(n,n) Transition matrix. target : int or list of int Target states for mfpt calculation. Returns ------- m_t : ndarray, shape=(n,) Vector of mean first passage times to target states. Notes ----- The mean first passage time :math:`\mathbf{E}_x[T_Y]` is the expected hitting time of one state :math:`y` in :math:`Y` when starting in state :math:`x`. For a fixed target state :math:`y` it is given by .. math :: \mathbb{E}_x[T_y] = \left \{ \begin{array}{cc} 0 & x=y \\ 1+\sum_{z} T_{x,z} \mathbb{E}_z[T_y] & x \neq y \end{array} \right. For a set of target states :math:`Y` it is given by .. math :: \mathbb{E}_x[T_Y] = \left \{ \begin{array}{cc} 0 & x \in Y \\ 1+\sum_{z} T_{x,z} \mathbb{E}_z[T_Y] & x \notin Y \end{array} \right. References ---------- .. [1] Hoel, P G and S C Port and C J Stone. 1972. Introduction to Stochastic Processes. Examples -------- >>> from msmtools.analysis import mfpt >>> T = np.array([[0.9, 0.1, 0.0], [0.5, 0.0, 0.5], [0.0, 0.1, 0.9]]) >>> m_t = mfpt(T, 0) >>> m_t array([ 0., 12., 22.]) """ dim = T.shape[0] A = np.eye(dim) - T A[target, :] = 0.0 A[target, target] = 1.0 b = np.ones(dim) b[target] = 0.0 m_t = solve(A, b) return m_t
def function[mfpt, parameter[T, target]]: constant[Mean first passage times to a set of target states. Parameters ---------- T : ndarray, shape=(n,n) Transition matrix. target : int or list of int Target states for mfpt calculation. Returns ------- m_t : ndarray, shape=(n,) Vector of mean first passage times to target states. Notes ----- The mean first passage time :math:`\mathbf{E}_x[T_Y]` is the expected hitting time of one state :math:`y` in :math:`Y` when starting in state :math:`x`. For a fixed target state :math:`y` it is given by .. math :: \mathbb{E}_x[T_y] = \left \{ \begin{array}{cc} 0 & x=y \\ 1+\sum_{z} T_{x,z} \mathbb{E}_z[T_y] & x \neq y \end{array} \right. For a set of target states :math:`Y` it is given by .. math :: \mathbb{E}_x[T_Y] = \left \{ \begin{array}{cc} 0 & x \in Y \\ 1+\sum_{z} T_{x,z} \mathbb{E}_z[T_Y] & x \notin Y \end{array} \right. References ---------- .. [1] Hoel, P G and S C Port and C J Stone. 1972. Introduction to Stochastic Processes. Examples -------- >>> from msmtools.analysis import mfpt >>> T = np.array([[0.9, 0.1, 0.0], [0.5, 0.0, 0.5], [0.0, 0.1, 0.9]]) >>> m_t = mfpt(T, 0) >>> m_t array([ 0., 12., 22.]) ] variable[dim] assign[=] call[name[T].shape][constant[0]] variable[A] assign[=] binary_operation[call[name[np].eye, parameter[name[dim]]] - name[T]] call[name[A]][tuple[[<ast.Name object at 0x7da1b26a2c50>, <ast.Slice object at 0x7da1b26a2410>]]] assign[=] constant[0.0] call[name[A]][tuple[[<ast.Name object at 0x7da1b26a1600>, <ast.Name object at 0x7da1b26a1b40>]]] assign[=] constant[1.0] variable[b] assign[=] call[name[np].ones, parameter[name[dim]]] call[name[b]][name[target]] assign[=] constant[0.0] variable[m_t] assign[=] call[name[solve], parameter[name[A], name[b]]] return[name[m_t]]
keyword[def] identifier[mfpt] ( identifier[T] , identifier[target] ): literal[string] identifier[dim] = identifier[T] . identifier[shape] [ literal[int] ] identifier[A] = identifier[np] . identifier[eye] ( identifier[dim] )- identifier[T] identifier[A] [ identifier[target] ,:]= literal[int] identifier[A] [ identifier[target] , identifier[target] ]= literal[int] identifier[b] = identifier[np] . identifier[ones] ( identifier[dim] ) identifier[b] [ identifier[target] ]= literal[int] identifier[m_t] = identifier[solve] ( identifier[A] , identifier[b] ) keyword[return] identifier[m_t]
def mfpt(T, target): """Mean first passage times to a set of target states. Parameters ---------- T : ndarray, shape=(n,n) Transition matrix. target : int or list of int Target states for mfpt calculation. Returns ------- m_t : ndarray, shape=(n,) Vector of mean first passage times to target states. Notes ----- The mean first passage time :math:`\\mathbf{E}_x[T_Y]` is the expected hitting time of one state :math:`y` in :math:`Y` when starting in state :math:`x`. For a fixed target state :math:`y` it is given by .. math :: \\mathbb{E}_x[T_y] = \\left \\{ \\begin{array}{cc} 0 & x=y \\\\ 1+\\sum_{z} T_{x,z} \\mathbb{E}_z[T_y] & x \\neq y \\end{array} \\right. For a set of target states :math:`Y` it is given by .. math :: \\mathbb{E}_x[T_Y] = \\left \\{ \\begin{array}{cc} 0 & x \\in Y \\\\ 1+\\sum_{z} T_{x,z} \\mathbb{E}_z[T_Y] & x \\notin Y \\end{array} \\right. References ---------- .. [1] Hoel, P G and S C Port and C J Stone. 1972. Introduction to Stochastic Processes. Examples -------- >>> from msmtools.analysis import mfpt >>> T = np.array([[0.9, 0.1, 0.0], [0.5, 0.0, 0.5], [0.0, 0.1, 0.9]]) >>> m_t = mfpt(T, 0) >>> m_t array([ 0., 12., 22.]) """ dim = T.shape[0] A = np.eye(dim) - T A[target, :] = 0.0 A[target, target] = 1.0 b = np.ones(dim) b[target] = 0.0 m_t = solve(A, b) return m_t
def pdf_rotate( input: str, counter_clockwise: bool = False, pages: [str] = None, output: str = None, ): """ Rotate the given Pdf files clockwise or counter clockwise. :param inputs: pdf files :param counter_clockwise: rotate counter clockwise if true else clockwise :param pages: list of page numbers to rotate, if None all pages will be rotated """ infile = open(input, "rb") reader = PdfFileReader(infile) writer = PdfFileWriter() # get pages from source depending on pages parameter if pages is None: source_pages = reader.pages else: pages = parse_rangearg(pages, len(reader.pages)) source_pages = [reader.getPage(i) for i in pages] # rotate pages and add to writer for i, page in enumerate(source_pages): if pages is None or i in pages: if counter_clockwise: writer.addPage(page.rotateCounterClockwise(90)) else: writer.addPage(page.rotateClockwise(90)) else: writer.addPage(page) # Open output file or temporary file for writing if output is None: outfile = NamedTemporaryFile(delete=False) else: if not os.path.isfile(output) or overwrite_dlg(output): outfile = open(output, "wb") else: return # Write to file writer.write(outfile) infile.close() outfile.close() # If no output defined move temporary file to input if output is None: if overwrite_dlg(input): os.remove(input) move(outfile.name, input) else: os.remove(outfile.name)
def function[pdf_rotate, parameter[input, counter_clockwise, pages, output]]: constant[ Rotate the given Pdf files clockwise or counter clockwise. :param inputs: pdf files :param counter_clockwise: rotate counter clockwise if true else clockwise :param pages: list of page numbers to rotate, if None all pages will be rotated ] variable[infile] assign[=] call[name[open], parameter[name[input], constant[rb]]] variable[reader] assign[=] call[name[PdfFileReader], parameter[name[infile]]] variable[writer] assign[=] call[name[PdfFileWriter], parameter[]] if compare[name[pages] is constant[None]] begin[:] variable[source_pages] assign[=] name[reader].pages for taget[tuple[[<ast.Name object at 0x7da1b03da2c0>, <ast.Name object at 0x7da1b03da560>]]] in starred[call[name[enumerate], parameter[name[source_pages]]]] begin[:] if <ast.BoolOp object at 0x7da1b03db910> begin[:] if name[counter_clockwise] begin[:] call[name[writer].addPage, parameter[call[name[page].rotateCounterClockwise, parameter[constant[90]]]]] if compare[name[output] is constant[None]] begin[:] variable[outfile] assign[=] call[name[NamedTemporaryFile], parameter[]] call[name[writer].write, parameter[name[outfile]]] call[name[infile].close, parameter[]] call[name[outfile].close, parameter[]] if compare[name[output] is constant[None]] begin[:] if call[name[overwrite_dlg], parameter[name[input]]] begin[:] call[name[os].remove, parameter[name[input]]] call[name[move], parameter[name[outfile].name, name[input]]]
keyword[def] identifier[pdf_rotate] ( identifier[input] : identifier[str] , identifier[counter_clockwise] : identifier[bool] = keyword[False] , identifier[pages] :[ identifier[str] ]= keyword[None] , identifier[output] : identifier[str] = keyword[None] , ): literal[string] identifier[infile] = identifier[open] ( identifier[input] , literal[string] ) identifier[reader] = identifier[PdfFileReader] ( identifier[infile] ) identifier[writer] = identifier[PdfFileWriter] () keyword[if] identifier[pages] keyword[is] keyword[None] : identifier[source_pages] = identifier[reader] . identifier[pages] keyword[else] : identifier[pages] = identifier[parse_rangearg] ( identifier[pages] , identifier[len] ( identifier[reader] . identifier[pages] )) identifier[source_pages] =[ identifier[reader] . identifier[getPage] ( identifier[i] ) keyword[for] identifier[i] keyword[in] identifier[pages] ] keyword[for] identifier[i] , identifier[page] keyword[in] identifier[enumerate] ( identifier[source_pages] ): keyword[if] identifier[pages] keyword[is] keyword[None] keyword[or] identifier[i] keyword[in] identifier[pages] : keyword[if] identifier[counter_clockwise] : identifier[writer] . identifier[addPage] ( identifier[page] . identifier[rotateCounterClockwise] ( literal[int] )) keyword[else] : identifier[writer] . identifier[addPage] ( identifier[page] . identifier[rotateClockwise] ( literal[int] )) keyword[else] : identifier[writer] . identifier[addPage] ( identifier[page] ) keyword[if] identifier[output] keyword[is] keyword[None] : identifier[outfile] = identifier[NamedTemporaryFile] ( identifier[delete] = keyword[False] ) keyword[else] : keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[isfile] ( identifier[output] ) keyword[or] identifier[overwrite_dlg] ( identifier[output] ): identifier[outfile] = identifier[open] ( identifier[output] , literal[string] ) keyword[else] : keyword[return] identifier[writer] . identifier[write] ( identifier[outfile] ) identifier[infile] . identifier[close] () identifier[outfile] . identifier[close] () keyword[if] identifier[output] keyword[is] keyword[None] : keyword[if] identifier[overwrite_dlg] ( identifier[input] ): identifier[os] . identifier[remove] ( identifier[input] ) identifier[move] ( identifier[outfile] . identifier[name] , identifier[input] ) keyword[else] : identifier[os] . identifier[remove] ( identifier[outfile] . identifier[name] )
def pdf_rotate(input: str, counter_clockwise: bool=False, pages: [str]=None, output: str=None): """ Rotate the given Pdf files clockwise or counter clockwise. :param inputs: pdf files :param counter_clockwise: rotate counter clockwise if true else clockwise :param pages: list of page numbers to rotate, if None all pages will be rotated """ infile = open(input, 'rb') reader = PdfFileReader(infile) writer = PdfFileWriter() # get pages from source depending on pages parameter if pages is None: source_pages = reader.pages # depends on [control=['if'], data=[]] else: pages = parse_rangearg(pages, len(reader.pages)) source_pages = [reader.getPage(i) for i in pages] # rotate pages and add to writer for (i, page) in enumerate(source_pages): if pages is None or i in pages: if counter_clockwise: writer.addPage(page.rotateCounterClockwise(90)) # depends on [control=['if'], data=[]] else: writer.addPage(page.rotateClockwise(90)) # depends on [control=['if'], data=[]] else: writer.addPage(page) # depends on [control=['for'], data=[]] # Open output file or temporary file for writing if output is None: outfile = NamedTemporaryFile(delete=False) # depends on [control=['if'], data=[]] elif not os.path.isfile(output) or overwrite_dlg(output): outfile = open(output, 'wb') # depends on [control=['if'], data=[]] else: return # Write to file writer.write(outfile) infile.close() outfile.close() # If no output defined move temporary file to input if output is None: if overwrite_dlg(input): os.remove(input) move(outfile.name, input) # depends on [control=['if'], data=[]] else: os.remove(outfile.name) # depends on [control=['if'], data=[]]
def GetUsernameByIdentifier( self, user_identifier, session_identifier=CURRENT_SESSION): """Retrieves the username based on an user identifier. Args: user_identifier (str): user identifier, either a UID or SID. session_identifier (Optional[str])): session identifier, where CURRENT_SESSION represents the active session. Returns: str: username. """ user_accounts = self._user_accounts.get(session_identifier, {}) user_account = user_accounts.get(user_identifier, None) if not user_account: return '' return user_account.username or ''
def function[GetUsernameByIdentifier, parameter[self, user_identifier, session_identifier]]: constant[Retrieves the username based on an user identifier. Args: user_identifier (str): user identifier, either a UID or SID. session_identifier (Optional[str])): session identifier, where CURRENT_SESSION represents the active session. Returns: str: username. ] variable[user_accounts] assign[=] call[name[self]._user_accounts.get, parameter[name[session_identifier], dictionary[[], []]]] variable[user_account] assign[=] call[name[user_accounts].get, parameter[name[user_identifier], constant[None]]] if <ast.UnaryOp object at 0x7da207f98730> begin[:] return[constant[]] return[<ast.BoolOp object at 0x7da207f991e0>]
keyword[def] identifier[GetUsernameByIdentifier] ( identifier[self] , identifier[user_identifier] , identifier[session_identifier] = identifier[CURRENT_SESSION] ): literal[string] identifier[user_accounts] = identifier[self] . identifier[_user_accounts] . identifier[get] ( identifier[session_identifier] ,{}) identifier[user_account] = identifier[user_accounts] . identifier[get] ( identifier[user_identifier] , keyword[None] ) keyword[if] keyword[not] identifier[user_account] : keyword[return] literal[string] keyword[return] identifier[user_account] . identifier[username] keyword[or] literal[string]
def GetUsernameByIdentifier(self, user_identifier, session_identifier=CURRENT_SESSION): """Retrieves the username based on an user identifier. Args: user_identifier (str): user identifier, either a UID or SID. session_identifier (Optional[str])): session identifier, where CURRENT_SESSION represents the active session. Returns: str: username. """ user_accounts = self._user_accounts.get(session_identifier, {}) user_account = user_accounts.get(user_identifier, None) if not user_account: return '' # depends on [control=['if'], data=[]] return user_account.username or ''
def register_task(self, task_def): ''' Register a task for a python dict :param task_def: dict defining gbdx task ''' r = self.session.post( self.task_url, data=task_def, headers={'Content-Type': 'application/json', 'Accept': 'application/json'} ) task_dict = json.loads(task_def) if r.status_code == 200: return r.status_code, 'Task %s registered' % task_dict['name'] else: return r.status_code, 'Task %s was not registered: %s' % (task_dict['name'], r.text)
def function[register_task, parameter[self, task_def]]: constant[ Register a task for a python dict :param task_def: dict defining gbdx task ] variable[r] assign[=] call[name[self].session.post, parameter[name[self].task_url]] variable[task_dict] assign[=] call[name[json].loads, parameter[name[task_def]]] if compare[name[r].status_code equal[==] constant[200]] begin[:] return[tuple[[<ast.Attribute object at 0x7da1b03bb1f0>, <ast.BinOp object at 0x7da1b03b82e0>]]]
keyword[def] identifier[register_task] ( identifier[self] , identifier[task_def] ): literal[string] identifier[r] = identifier[self] . identifier[session] . identifier[post] ( identifier[self] . identifier[task_url] , identifier[data] = identifier[task_def] , identifier[headers] ={ literal[string] : literal[string] , literal[string] : literal[string] } ) identifier[task_dict] = identifier[json] . identifier[loads] ( identifier[task_def] ) keyword[if] identifier[r] . identifier[status_code] == literal[int] : keyword[return] identifier[r] . identifier[status_code] , literal[string] % identifier[task_dict] [ literal[string] ] keyword[else] : keyword[return] identifier[r] . identifier[status_code] , literal[string] %( identifier[task_dict] [ literal[string] ], identifier[r] . identifier[text] )
def register_task(self, task_def): """ Register a task for a python dict :param task_def: dict defining gbdx task """ r = self.session.post(self.task_url, data=task_def, headers={'Content-Type': 'application/json', 'Accept': 'application/json'}) task_dict = json.loads(task_def) if r.status_code == 200: return (r.status_code, 'Task %s registered' % task_dict['name']) # depends on [control=['if'], data=[]] else: return (r.status_code, 'Task %s was not registered: %s' % (task_dict['name'], r.text))
def plot_strat(fignum, data, labels): """ plots a time/depth series Parameters _________ fignum : matplotlib figure number data : nested list of [X,Y] pairs labels : [xlabel, ylabel, title] """ vertical_plot_init(fignum, 10, 3) xlab, ylab, title = labels[0], labels[1], labels[2] X, Y = [], [] for rec in data: X.append(rec[0]) Y.append(rec[1]) plt.plot(X, Y) plt.plot(X, Y, 'ro') plt.xlabel(xlab) plt.ylabel(ylab) plt.title(title)
def function[plot_strat, parameter[fignum, data, labels]]: constant[ plots a time/depth series Parameters _________ fignum : matplotlib figure number data : nested list of [X,Y] pairs labels : [xlabel, ylabel, title] ] call[name[vertical_plot_init], parameter[name[fignum], constant[10], constant[3]]] <ast.Tuple object at 0x7da18eb553f0> assign[=] tuple[[<ast.Subscript object at 0x7da18eb55900>, <ast.Subscript object at 0x7da1b05befe0>, <ast.Subscript object at 0x7da1b05be410>]] <ast.Tuple object at 0x7da1b05bc3a0> assign[=] tuple[[<ast.List object at 0x7da1b05bf010>, <ast.List object at 0x7da1b05bc220>]] for taget[name[rec]] in starred[name[data]] begin[:] call[name[X].append, parameter[call[name[rec]][constant[0]]]] call[name[Y].append, parameter[call[name[rec]][constant[1]]]] call[name[plt].plot, parameter[name[X], name[Y]]] call[name[plt].plot, parameter[name[X], name[Y], constant[ro]]] call[name[plt].xlabel, parameter[name[xlab]]] call[name[plt].ylabel, parameter[name[ylab]]] call[name[plt].title, parameter[name[title]]]
keyword[def] identifier[plot_strat] ( identifier[fignum] , identifier[data] , identifier[labels] ): literal[string] identifier[vertical_plot_init] ( identifier[fignum] , literal[int] , literal[int] ) identifier[xlab] , identifier[ylab] , identifier[title] = identifier[labels] [ literal[int] ], identifier[labels] [ literal[int] ], identifier[labels] [ literal[int] ] identifier[X] , identifier[Y] =[],[] keyword[for] identifier[rec] keyword[in] identifier[data] : identifier[X] . identifier[append] ( identifier[rec] [ literal[int] ]) identifier[Y] . identifier[append] ( identifier[rec] [ literal[int] ]) identifier[plt] . identifier[plot] ( identifier[X] , identifier[Y] ) identifier[plt] . identifier[plot] ( identifier[X] , identifier[Y] , literal[string] ) identifier[plt] . identifier[xlabel] ( identifier[xlab] ) identifier[plt] . identifier[ylabel] ( identifier[ylab] ) identifier[plt] . identifier[title] ( identifier[title] )
def plot_strat(fignum, data, labels): """ plots a time/depth series Parameters _________ fignum : matplotlib figure number data : nested list of [X,Y] pairs labels : [xlabel, ylabel, title] """ vertical_plot_init(fignum, 10, 3) (xlab, ylab, title) = (labels[0], labels[1], labels[2]) (X, Y) = ([], []) for rec in data: X.append(rec[0]) Y.append(rec[1]) # depends on [control=['for'], data=['rec']] plt.plot(X, Y) plt.plot(X, Y, 'ro') plt.xlabel(xlab) plt.ylabel(ylab) plt.title(title)
def events_log(self, details=False, count=0, timestamp=0): """Get the most recent Alignak events If count is specifies it is the maximum number of events to return. If timestamp is specified, events older than this timestamp will not be returned The arbiter maintains a list of the most recent Alignak events. This endpoint provides this list. The default format is: [ "2018-07-23 15:14:43 - E - SERVICE NOTIFICATION: guest;host_0;dummy_random;CRITICAL;1; notify-service-by-log;Service internal check result: 2", "2018-07-23 15:14:43 - E - SERVICE NOTIFICATION: admin;host_0;dummy_random;CRITICAL;1; notify-service-by-log;Service internal check result: 2", "2018-07-23 15:14:42 - E - SERVICE ALERT: host_0;dummy_critical;CRITICAL;SOFT;1; host_0-dummy_critical-2", "2018-07-23 15:14:42 - E - SERVICE ALERT: host_0;dummy_random;CRITICAL;HARD;2; Service internal check result: 2", "2018-07-23 15:14:42 - I - SERVICE ALERT: host_0;dummy_unknown;UNKNOWN;HARD;2; host_0-dummy_unknown-3" ] If you request on this endpoint with the *details* parameter (whatever its value...), you will get a detailed JSON output: [ { timestamp: 1535517701.1817362, date: "2018-07-23 15:16:35", message: "SERVICE ALERT: host_11;dummy_echo;UNREACHABLE;HARD;2;", level: "info" }, { timestamp: 1535517701.1817362, date: "2018-07-23 15:16:32", message: "SERVICE NOTIFICATION: guest;host_0;dummy_random;OK;0; notify-service-by-log;Service internal check result: 0", level: "info" }, { timestamp: 1535517701.1817362, date: "2018-07-23 15:16:32", message: "SERVICE NOTIFICATION: admin;host_0;dummy_random;OK;0; notify-service-by-log;Service internal check result: 0", level: "info" }, { timestamp: 1535517701.1817362, date: "2018-07-23 15:16:32", message: "SERVICE ALERT: host_0;dummy_random;OK;HARD;2; Service internal check result: 0", level: "info" }, { timestamp: 1535517701.1817362, date: "2018-07-23 15:16:19", message: "SERVICE ALERT: host_11;dummy_random;OK;HARD;2; Service internal check result: 0", level: "info" } ] In this example, only the 5 most recent events are provided whereas the default value is to provide the 100 last events. This default counter may be changed thanks to the ``events_log_count`` configuration variable or ``ALIGNAK_EVENTS_LOG_COUNT`` environment variable. The date format may also be changed thanks to the ``events_date_format`` configuration variable. :return: list of the most recent events :rtype: list """ if not count: count = 1 + int(os.environ.get('ALIGNAK_EVENTS_LOG_COUNT', self.app.conf.events_log_count)) count = int(count) timestamp = float(timestamp) logger.debug('Get max %d events, newer than %s out of %d', count, timestamp, len(self.app.recent_events)) res = [] for log in reversed(self.app.recent_events): if timestamp and timestamp > log['timestamp']: break if not count: break if details: # Exposes the full object res.append(log) else: res.append("%s - %s - %s" % (log['date'], log['level'][0].upper(), log['message'])) logger.debug('Got %d events', len(res)) return res
def function[events_log, parameter[self, details, count, timestamp]]: constant[Get the most recent Alignak events If count is specifies it is the maximum number of events to return. If timestamp is specified, events older than this timestamp will not be returned The arbiter maintains a list of the most recent Alignak events. This endpoint provides this list. The default format is: [ "2018-07-23 15:14:43 - E - SERVICE NOTIFICATION: guest;host_0;dummy_random;CRITICAL;1; notify-service-by-log;Service internal check result: 2", "2018-07-23 15:14:43 - E - SERVICE NOTIFICATION: admin;host_0;dummy_random;CRITICAL;1; notify-service-by-log;Service internal check result: 2", "2018-07-23 15:14:42 - E - SERVICE ALERT: host_0;dummy_critical;CRITICAL;SOFT;1; host_0-dummy_critical-2", "2018-07-23 15:14:42 - E - SERVICE ALERT: host_0;dummy_random;CRITICAL;HARD;2; Service internal check result: 2", "2018-07-23 15:14:42 - I - SERVICE ALERT: host_0;dummy_unknown;UNKNOWN;HARD;2; host_0-dummy_unknown-3" ] If you request on this endpoint with the *details* parameter (whatever its value...), you will get a detailed JSON output: [ { timestamp: 1535517701.1817362, date: "2018-07-23 15:16:35", message: "SERVICE ALERT: host_11;dummy_echo;UNREACHABLE;HARD;2;", level: "info" }, { timestamp: 1535517701.1817362, date: "2018-07-23 15:16:32", message: "SERVICE NOTIFICATION: guest;host_0;dummy_random;OK;0; notify-service-by-log;Service internal check result: 0", level: "info" }, { timestamp: 1535517701.1817362, date: "2018-07-23 15:16:32", message: "SERVICE NOTIFICATION: admin;host_0;dummy_random;OK;0; notify-service-by-log;Service internal check result: 0", level: "info" }, { timestamp: 1535517701.1817362, date: "2018-07-23 15:16:32", message: "SERVICE ALERT: host_0;dummy_random;OK;HARD;2; Service internal check result: 0", level: "info" }, { timestamp: 1535517701.1817362, date: "2018-07-23 15:16:19", message: "SERVICE ALERT: host_11;dummy_random;OK;HARD;2; Service internal check result: 0", level: "info" } ] In this example, only the 5 most recent events are provided whereas the default value is to provide the 100 last events. This default counter may be changed thanks to the ``events_log_count`` configuration variable or ``ALIGNAK_EVENTS_LOG_COUNT`` environment variable. The date format may also be changed thanks to the ``events_date_format`` configuration variable. :return: list of the most recent events :rtype: list ] if <ast.UnaryOp object at 0x7da18dc04580> begin[:] variable[count] assign[=] binary_operation[constant[1] + call[name[int], parameter[call[name[os].environ.get, parameter[constant[ALIGNAK_EVENTS_LOG_COUNT], name[self].app.conf.events_log_count]]]]] variable[count] assign[=] call[name[int], parameter[name[count]]] variable[timestamp] assign[=] call[name[float], parameter[name[timestamp]]] call[name[logger].debug, parameter[constant[Get max %d events, newer than %s out of %d], name[count], name[timestamp], call[name[len], parameter[name[self].app.recent_events]]]] variable[res] assign[=] list[[]] for taget[name[log]] in starred[call[name[reversed], parameter[name[self].app.recent_events]]] begin[:] if <ast.BoolOp object at 0x7da18f723d60> begin[:] break if <ast.UnaryOp object at 0x7da18f7238b0> begin[:] break if name[details] begin[:] call[name[res].append, parameter[name[log]]] call[name[logger].debug, parameter[constant[Got %d events], call[name[len], parameter[name[res]]]]] return[name[res]]
keyword[def] identifier[events_log] ( identifier[self] , identifier[details] = keyword[False] , identifier[count] = literal[int] , identifier[timestamp] = literal[int] ): literal[string] keyword[if] keyword[not] identifier[count] : identifier[count] = literal[int] + identifier[int] ( identifier[os] . identifier[environ] . identifier[get] ( literal[string] , identifier[self] . identifier[app] . identifier[conf] . identifier[events_log_count] )) identifier[count] = identifier[int] ( identifier[count] ) identifier[timestamp] = identifier[float] ( identifier[timestamp] ) identifier[logger] . identifier[debug] ( literal[string] , identifier[count] , identifier[timestamp] , identifier[len] ( identifier[self] . identifier[app] . identifier[recent_events] )) identifier[res] =[] keyword[for] identifier[log] keyword[in] identifier[reversed] ( identifier[self] . identifier[app] . identifier[recent_events] ): keyword[if] identifier[timestamp] keyword[and] identifier[timestamp] > identifier[log] [ literal[string] ]: keyword[break] keyword[if] keyword[not] identifier[count] : keyword[break] keyword[if] identifier[details] : identifier[res] . identifier[append] ( identifier[log] ) keyword[else] : identifier[res] . identifier[append] ( literal[string] %( identifier[log] [ literal[string] ], identifier[log] [ literal[string] ][ literal[int] ]. identifier[upper] (), identifier[log] [ literal[string] ])) identifier[logger] . identifier[debug] ( literal[string] , identifier[len] ( identifier[res] )) keyword[return] identifier[res]
def events_log(self, details=False, count=0, timestamp=0): """Get the most recent Alignak events If count is specifies it is the maximum number of events to return. If timestamp is specified, events older than this timestamp will not be returned The arbiter maintains a list of the most recent Alignak events. This endpoint provides this list. The default format is: [ "2018-07-23 15:14:43 - E - SERVICE NOTIFICATION: guest;host_0;dummy_random;CRITICAL;1; notify-service-by-log;Service internal check result: 2", "2018-07-23 15:14:43 - E - SERVICE NOTIFICATION: admin;host_0;dummy_random;CRITICAL;1; notify-service-by-log;Service internal check result: 2", "2018-07-23 15:14:42 - E - SERVICE ALERT: host_0;dummy_critical;CRITICAL;SOFT;1; host_0-dummy_critical-2", "2018-07-23 15:14:42 - E - SERVICE ALERT: host_0;dummy_random;CRITICAL;HARD;2; Service internal check result: 2", "2018-07-23 15:14:42 - I - SERVICE ALERT: host_0;dummy_unknown;UNKNOWN;HARD;2; host_0-dummy_unknown-3" ] If you request on this endpoint with the *details* parameter (whatever its value...), you will get a detailed JSON output: [ { timestamp: 1535517701.1817362, date: "2018-07-23 15:16:35", message: "SERVICE ALERT: host_11;dummy_echo;UNREACHABLE;HARD;2;", level: "info" }, { timestamp: 1535517701.1817362, date: "2018-07-23 15:16:32", message: "SERVICE NOTIFICATION: guest;host_0;dummy_random;OK;0; notify-service-by-log;Service internal check result: 0", level: "info" }, { timestamp: 1535517701.1817362, date: "2018-07-23 15:16:32", message: "SERVICE NOTIFICATION: admin;host_0;dummy_random;OK;0; notify-service-by-log;Service internal check result: 0", level: "info" }, { timestamp: 1535517701.1817362, date: "2018-07-23 15:16:32", message: "SERVICE ALERT: host_0;dummy_random;OK;HARD;2; Service internal check result: 0", level: "info" }, { timestamp: 1535517701.1817362, date: "2018-07-23 15:16:19", message: "SERVICE ALERT: host_11;dummy_random;OK;HARD;2; Service internal check result: 0", level: "info" } ] In this example, only the 5 most recent events are provided whereas the default value is to provide the 100 last events. This default counter may be changed thanks to the ``events_log_count`` configuration variable or ``ALIGNAK_EVENTS_LOG_COUNT`` environment variable. The date format may also be changed thanks to the ``events_date_format`` configuration variable. :return: list of the most recent events :rtype: list """ if not count: count = 1 + int(os.environ.get('ALIGNAK_EVENTS_LOG_COUNT', self.app.conf.events_log_count)) # depends on [control=['if'], data=[]] count = int(count) timestamp = float(timestamp) logger.debug('Get max %d events, newer than %s out of %d', count, timestamp, len(self.app.recent_events)) res = [] for log in reversed(self.app.recent_events): if timestamp and timestamp > log['timestamp']: break # depends on [control=['if'], data=[]] if not count: break # depends on [control=['if'], data=[]] if details: # Exposes the full object res.append(log) # depends on [control=['if'], data=[]] else: res.append('%s - %s - %s' % (log['date'], log['level'][0].upper(), log['message'])) # depends on [control=['for'], data=['log']] logger.debug('Got %d events', len(res)) return res
def cos(d, alpha=1.0, phase=0.0): """ Create TT-vector for :math:`\\cos(\\alpha n + \\varphi)`.""" return sin(d, alpha, phase + _math.pi * 0.5)
def function[cos, parameter[d, alpha, phase]]: constant[ Create TT-vector for :math:`\cos(\alpha n + \varphi)`.] return[call[name[sin], parameter[name[d], name[alpha], binary_operation[name[phase] + binary_operation[name[_math].pi * constant[0.5]]]]]]
keyword[def] identifier[cos] ( identifier[d] , identifier[alpha] = literal[int] , identifier[phase] = literal[int] ): literal[string] keyword[return] identifier[sin] ( identifier[d] , identifier[alpha] , identifier[phase] + identifier[_math] . identifier[pi] * literal[int] )
def cos(d, alpha=1.0, phase=0.0): """ Create TT-vector for :math:`\\cos(\\alpha n + \\varphi)`.""" return sin(d, alpha, phase + _math.pi * 0.5)
def is_json_file(filename, show_warnings = False): """Check configuration file type is JSON Return a boolean indicating wheather the file is JSON format or not """ try: config_dict = load_config(filename, file_type = "json") is_json = True except: is_json = False return(is_json)
def function[is_json_file, parameter[filename, show_warnings]]: constant[Check configuration file type is JSON Return a boolean indicating wheather the file is JSON format or not ] <ast.Try object at 0x7da20e962530> return[name[is_json]]
keyword[def] identifier[is_json_file] ( identifier[filename] , identifier[show_warnings] = keyword[False] ): literal[string] keyword[try] : identifier[config_dict] = identifier[load_config] ( identifier[filename] , identifier[file_type] = literal[string] ) identifier[is_json] = keyword[True] keyword[except] : identifier[is_json] = keyword[False] keyword[return] ( identifier[is_json] )
def is_json_file(filename, show_warnings=False): """Check configuration file type is JSON Return a boolean indicating wheather the file is JSON format or not """ try: config_dict = load_config(filename, file_type='json') is_json = True # depends on [control=['try'], data=[]] except: is_json = False # depends on [control=['except'], data=[]] return is_json
def run(args): """Load YAML and JSON configs and run the command specified in args.command""" repos = load_config(args.config, args.expand_env, args.force) jobs = max(args.jobs, 1) threads = [] sem = threading.Semaphore(jobs) err_queue = Queue() for repo_dict in repos: if not err_queue.empty(): break sem.acquire() r = Repo(**repo_dict) tname = os.path.basename(repo_dict['cwd']) if jobs > 1: t = threading.Thread( target=aggregate_repo, args=(r, args, sem, err_queue)) t.daemon = True t.name = tname threads.append(t) t.start() else: with ThreadNameKeeper(): threading.current_thread().name = tname aggregate_repo(r, args, sem, err_queue) for t in threads: t.join() if not err_queue.empty(): while True: try: exc_type, exc_obj, exc_trace = err_queue.get_nowait() except EmptyQueue: break traceback.print_exception(exc_type, exc_obj, exc_trace) sys.exit(1)
def function[run, parameter[args]]: constant[Load YAML and JSON configs and run the command specified in args.command] variable[repos] assign[=] call[name[load_config], parameter[name[args].config, name[args].expand_env, name[args].force]] variable[jobs] assign[=] call[name[max], parameter[name[args].jobs, constant[1]]] variable[threads] assign[=] list[[]] variable[sem] assign[=] call[name[threading].Semaphore, parameter[name[jobs]]] variable[err_queue] assign[=] call[name[Queue], parameter[]] for taget[name[repo_dict]] in starred[name[repos]] begin[:] if <ast.UnaryOp object at 0x7da1b02e53f0> begin[:] break call[name[sem].acquire, parameter[]] variable[r] assign[=] call[name[Repo], parameter[]] variable[tname] assign[=] call[name[os].path.basename, parameter[call[name[repo_dict]][constant[cwd]]]] if compare[name[jobs] greater[>] constant[1]] begin[:] variable[t] assign[=] call[name[threading].Thread, parameter[]] name[t].daemon assign[=] constant[True] name[t].name assign[=] name[tname] call[name[threads].append, parameter[name[t]]] call[name[t].start, parameter[]] for taget[name[t]] in starred[name[threads]] begin[:] call[name[t].join, parameter[]] if <ast.UnaryOp object at 0x7da1b02bd7e0> begin[:] while constant[True] begin[:] <ast.Try object at 0x7da1b02bf820> call[name[traceback].print_exception, parameter[name[exc_type], name[exc_obj], name[exc_trace]]] call[name[sys].exit, parameter[constant[1]]]
keyword[def] identifier[run] ( identifier[args] ): literal[string] identifier[repos] = identifier[load_config] ( identifier[args] . identifier[config] , identifier[args] . identifier[expand_env] , identifier[args] . identifier[force] ) identifier[jobs] = identifier[max] ( identifier[args] . identifier[jobs] , literal[int] ) identifier[threads] =[] identifier[sem] = identifier[threading] . identifier[Semaphore] ( identifier[jobs] ) identifier[err_queue] = identifier[Queue] () keyword[for] identifier[repo_dict] keyword[in] identifier[repos] : keyword[if] keyword[not] identifier[err_queue] . identifier[empty] (): keyword[break] identifier[sem] . identifier[acquire] () identifier[r] = identifier[Repo] (** identifier[repo_dict] ) identifier[tname] = identifier[os] . identifier[path] . identifier[basename] ( identifier[repo_dict] [ literal[string] ]) keyword[if] identifier[jobs] > literal[int] : identifier[t] = identifier[threading] . identifier[Thread] ( identifier[target] = identifier[aggregate_repo] , identifier[args] =( identifier[r] , identifier[args] , identifier[sem] , identifier[err_queue] )) identifier[t] . identifier[daemon] = keyword[True] identifier[t] . identifier[name] = identifier[tname] identifier[threads] . identifier[append] ( identifier[t] ) identifier[t] . identifier[start] () keyword[else] : keyword[with] identifier[ThreadNameKeeper] (): identifier[threading] . identifier[current_thread] (). identifier[name] = identifier[tname] identifier[aggregate_repo] ( identifier[r] , identifier[args] , identifier[sem] , identifier[err_queue] ) keyword[for] identifier[t] keyword[in] identifier[threads] : identifier[t] . identifier[join] () keyword[if] keyword[not] identifier[err_queue] . identifier[empty] (): keyword[while] keyword[True] : keyword[try] : identifier[exc_type] , identifier[exc_obj] , identifier[exc_trace] = identifier[err_queue] . identifier[get_nowait] () keyword[except] identifier[EmptyQueue] : keyword[break] identifier[traceback] . identifier[print_exception] ( identifier[exc_type] , identifier[exc_obj] , identifier[exc_trace] ) identifier[sys] . identifier[exit] ( literal[int] )
def run(args): """Load YAML and JSON configs and run the command specified in args.command""" repos = load_config(args.config, args.expand_env, args.force) jobs = max(args.jobs, 1) threads = [] sem = threading.Semaphore(jobs) err_queue = Queue() for repo_dict in repos: if not err_queue.empty(): break # depends on [control=['if'], data=[]] sem.acquire() r = Repo(**repo_dict) tname = os.path.basename(repo_dict['cwd']) if jobs > 1: t = threading.Thread(target=aggregate_repo, args=(r, args, sem, err_queue)) t.daemon = True t.name = tname threads.append(t) t.start() # depends on [control=['if'], data=[]] else: with ThreadNameKeeper(): threading.current_thread().name = tname aggregate_repo(r, args, sem, err_queue) # depends on [control=['with'], data=[]] # depends on [control=['for'], data=['repo_dict']] for t in threads: t.join() # depends on [control=['for'], data=['t']] if not err_queue.empty(): while True: try: (exc_type, exc_obj, exc_trace) = err_queue.get_nowait() # depends on [control=['try'], data=[]] except EmptyQueue: break # depends on [control=['except'], data=[]] traceback.print_exception(exc_type, exc_obj, exc_trace) # depends on [control=['while'], data=[]] sys.exit(1) # depends on [control=['if'], data=[]]
def all(self, element_type=None, response_path=None): """ Generates Bunches, each representing a single subelement of the response. If an element_type is requested, only elements whose tag matches the element_type are returned. If the response has no subelements (for example, in a <return>-less command), yields None. """ path = self.RETURN_PATH if response_path is not None: path += "/" + response_path response_element = self.response_etree.find(path) if response_element is None: return for subelement in self.response_etree.find(path).getchildren(): if element_type is None or subelement.tag == element_type: yield _populate_bunch_with_element(subelement)
def function[all, parameter[self, element_type, response_path]]: constant[ Generates Bunches, each representing a single subelement of the response. If an element_type is requested, only elements whose tag matches the element_type are returned. If the response has no subelements (for example, in a <return>-less command), yields None. ] variable[path] assign[=] name[self].RETURN_PATH if compare[name[response_path] is_not constant[None]] begin[:] <ast.AugAssign object at 0x7da1b1981e70> variable[response_element] assign[=] call[name[self].response_etree.find, parameter[name[path]]] if compare[name[response_element] is constant[None]] begin[:] return[None] for taget[name[subelement]] in starred[call[call[name[self].response_etree.find, parameter[name[path]]].getchildren, parameter[]]] begin[:] if <ast.BoolOp object at 0x7da1b19081c0> begin[:] <ast.Yield object at 0x7da1b190a1a0>
keyword[def] identifier[all] ( identifier[self] , identifier[element_type] = keyword[None] , identifier[response_path] = keyword[None] ): literal[string] identifier[path] = identifier[self] . identifier[RETURN_PATH] keyword[if] identifier[response_path] keyword[is] keyword[not] keyword[None] : identifier[path] += literal[string] + identifier[response_path] identifier[response_element] = identifier[self] . identifier[response_etree] . identifier[find] ( identifier[path] ) keyword[if] identifier[response_element] keyword[is] keyword[None] : keyword[return] keyword[for] identifier[subelement] keyword[in] identifier[self] . identifier[response_etree] . identifier[find] ( identifier[path] ). identifier[getchildren] (): keyword[if] identifier[element_type] keyword[is] keyword[None] keyword[or] identifier[subelement] . identifier[tag] == identifier[element_type] : keyword[yield] identifier[_populate_bunch_with_element] ( identifier[subelement] )
def all(self, element_type=None, response_path=None): """ Generates Bunches, each representing a single subelement of the response. If an element_type is requested, only elements whose tag matches the element_type are returned. If the response has no subelements (for example, in a <return>-less command), yields None. """ path = self.RETURN_PATH if response_path is not None: path += '/' + response_path # depends on [control=['if'], data=['response_path']] response_element = self.response_etree.find(path) if response_element is None: return # depends on [control=['if'], data=[]] for subelement in self.response_etree.find(path).getchildren(): if element_type is None or subelement.tag == element_type: yield _populate_bunch_with_element(subelement) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['subelement']]
def buffer(self, distance): """ Return a new Extrusion object which is expanded in profile and in height by a specified distance. Returns ---------- buffered: Extrusion object """ distance = float(distance) # start with current height height = self.primitive.height # if current height is negative offset by negative amount height += np.sign(height) * 2.0 * distance buffered = Extrusion( transform=self.primitive.transform.copy(), polygon=self.primitive.polygon.buffer(distance), height=height) # slide the stock along the axis buffered.slide(-np.sign(height) * distance) return buffered
def function[buffer, parameter[self, distance]]: constant[ Return a new Extrusion object which is expanded in profile and in height by a specified distance. Returns ---------- buffered: Extrusion object ] variable[distance] assign[=] call[name[float], parameter[name[distance]]] variable[height] assign[=] name[self].primitive.height <ast.AugAssign object at 0x7da18bc72a40> variable[buffered] assign[=] call[name[Extrusion], parameter[]] call[name[buffered].slide, parameter[binary_operation[<ast.UnaryOp object at 0x7da18bc71a80> * name[distance]]]] return[name[buffered]]
keyword[def] identifier[buffer] ( identifier[self] , identifier[distance] ): literal[string] identifier[distance] = identifier[float] ( identifier[distance] ) identifier[height] = identifier[self] . identifier[primitive] . identifier[height] identifier[height] += identifier[np] . identifier[sign] ( identifier[height] )* literal[int] * identifier[distance] identifier[buffered] = identifier[Extrusion] ( identifier[transform] = identifier[self] . identifier[primitive] . identifier[transform] . identifier[copy] (), identifier[polygon] = identifier[self] . identifier[primitive] . identifier[polygon] . identifier[buffer] ( identifier[distance] ), identifier[height] = identifier[height] ) identifier[buffered] . identifier[slide] (- identifier[np] . identifier[sign] ( identifier[height] )* identifier[distance] ) keyword[return] identifier[buffered]
def buffer(self, distance): """ Return a new Extrusion object which is expanded in profile and in height by a specified distance. Returns ---------- buffered: Extrusion object """ distance = float(distance) # start with current height height = self.primitive.height # if current height is negative offset by negative amount height += np.sign(height) * 2.0 * distance buffered = Extrusion(transform=self.primitive.transform.copy(), polygon=self.primitive.polygon.buffer(distance), height=height) # slide the stock along the axis buffered.slide(-np.sign(height) * distance) return buffered
def validate_page_size(ctx, param, value): """Ensure that a valid value for page size is chosen.""" # pylint: disable=unused-argument if value == 0: raise click.BadParameter("Page size must be non-zero or unset.", param=param) return value
def function[validate_page_size, parameter[ctx, param, value]]: constant[Ensure that a valid value for page size is chosen.] if compare[name[value] equal[==] constant[0]] begin[:] <ast.Raise object at 0x7da1b1a75ba0> return[name[value]]
keyword[def] identifier[validate_page_size] ( identifier[ctx] , identifier[param] , identifier[value] ): literal[string] keyword[if] identifier[value] == literal[int] : keyword[raise] identifier[click] . identifier[BadParameter] ( literal[string] , identifier[param] = identifier[param] ) keyword[return] identifier[value]
def validate_page_size(ctx, param, value): """Ensure that a valid value for page size is chosen.""" # pylint: disable=unused-argument if value == 0: raise click.BadParameter('Page size must be non-zero or unset.', param=param) # depends on [control=['if'], data=[]] return value
def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data
def function[vm_detach, parameter[name, kwargs, call]]: constant[ Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ] if compare[name[call] not_equal[!=] constant[action]] begin[:] <ast.Raise object at 0x7da1b2184910> if compare[name[kwargs] is constant[None]] begin[:] variable[kwargs] assign[=] dictionary[[], []] variable[disk_id] assign[=] call[name[kwargs].get, parameter[constant[disk_id], constant[None]]] if compare[name[disk_id] is constant[None]] begin[:] <ast.Raise object at 0x7da20c76f970> <ast.Tuple object at 0x7da20c76cdc0> assign[=] call[name[_get_xml_rpc], parameter[]] variable[auth] assign[=] call[constant[:].join, parameter[list[[<ast.Name object at 0x7da20c76ff70>, <ast.Name object at 0x7da20c76ed40>]]]] variable[vm_id] assign[=] call[name[int], parameter[call[name[get_vm_id], parameter[]]]] variable[response] assign[=] call[name[server].one.vm.detach, parameter[name[auth], name[vm_id], call[name[int], parameter[name[disk_id]]]]] variable[data] assign[=] dictionary[[<ast.Constant object at 0x7da20c76c370>, <ast.Constant object at 0x7da20c76c220>, <ast.Constant object at 0x7da20c76e020>, <ast.Constant object at 0x7da20c76e830>], [<ast.Constant object at 0x7da20c76c8b0>, <ast.Subscript object at 0x7da20c76df00>, <ast.Subscript object at 0x7da20c76e5c0>, <ast.Subscript object at 0x7da20c76ccd0>]] return[name[data]]
keyword[def] identifier[vm_detach] ( identifier[name] , identifier[kwargs] = keyword[None] , identifier[call] = keyword[None] ): literal[string] keyword[if] identifier[call] != literal[string] : keyword[raise] identifier[SaltCloudSystemExit] ( literal[string] ) keyword[if] identifier[kwargs] keyword[is] keyword[None] : identifier[kwargs] ={} identifier[disk_id] = identifier[kwargs] . identifier[get] ( literal[string] , keyword[None] ) keyword[if] identifier[disk_id] keyword[is] keyword[None] : keyword[raise] identifier[SaltCloudSystemExit] ( literal[string] ) identifier[server] , identifier[user] , identifier[password] = identifier[_get_xml_rpc] () identifier[auth] = literal[string] . identifier[join] ([ identifier[user] , identifier[password] ]) identifier[vm_id] = identifier[int] ( identifier[get_vm_id] ( identifier[kwargs] ={ literal[string] : identifier[name] })) identifier[response] = identifier[server] . identifier[one] . identifier[vm] . identifier[detach] ( identifier[auth] , identifier[vm_id] , identifier[int] ( identifier[disk_id] )) identifier[data] ={ literal[string] : literal[string] , literal[string] : identifier[response] [ literal[int] ], literal[string] : identifier[response] [ literal[int] ], literal[string] : identifier[response] [ literal[int] ], } keyword[return] identifier[data]
def vm_detach(name, kwargs=None, call=None): """ Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 """ if call != 'action': raise SaltCloudSystemExit('The vm_detach action must be called with -a or --action.') # depends on [control=['if'], data=[]] if kwargs is None: kwargs = {} # depends on [control=['if'], data=['kwargs']] disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit("The vm_detach function requires a 'disk_id' to be provided.") # depends on [control=['if'], data=[]] (server, user, password) = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = {'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2]} return data
def check_mod_enabled(mod): ''' Checks to see if the specific apache mod is enabled. This will only be functional on operating systems that support `a2enmod -l` to list the enabled mods. CLI Example: .. code-block:: bash salt '*' apache.check_mod_enabled status ''' if mod.endswith('.load') or mod.endswith('.conf'): mod_name = mod[:-5] else: mod_name = mod cmd = 'a2enmod -l' try: active_mods = __salt__['cmd.run'](cmd, python_shell=False).split(' ') except Exception as e: return e return mod_name in active_mods
def function[check_mod_enabled, parameter[mod]]: constant[ Checks to see if the specific apache mod is enabled. This will only be functional on operating systems that support `a2enmod -l` to list the enabled mods. CLI Example: .. code-block:: bash salt '*' apache.check_mod_enabled status ] if <ast.BoolOp object at 0x7da1b26ad390> begin[:] variable[mod_name] assign[=] call[name[mod]][<ast.Slice object at 0x7da1b26ac790>] variable[cmd] assign[=] constant[a2enmod -l] <ast.Try object at 0x7da1b26ad720> return[compare[name[mod_name] in name[active_mods]]]
keyword[def] identifier[check_mod_enabled] ( identifier[mod] ): literal[string] keyword[if] identifier[mod] . identifier[endswith] ( literal[string] ) keyword[or] identifier[mod] . identifier[endswith] ( literal[string] ): identifier[mod_name] = identifier[mod] [:- literal[int] ] keyword[else] : identifier[mod_name] = identifier[mod] identifier[cmd] = literal[string] keyword[try] : identifier[active_mods] = identifier[__salt__] [ literal[string] ]( identifier[cmd] , identifier[python_shell] = keyword[False] ). identifier[split] ( literal[string] ) keyword[except] identifier[Exception] keyword[as] identifier[e] : keyword[return] identifier[e] keyword[return] identifier[mod_name] keyword[in] identifier[active_mods]
def check_mod_enabled(mod): """ Checks to see if the specific apache mod is enabled. This will only be functional on operating systems that support `a2enmod -l` to list the enabled mods. CLI Example: .. code-block:: bash salt '*' apache.check_mod_enabled status """ if mod.endswith('.load') or mod.endswith('.conf'): mod_name = mod[:-5] # depends on [control=['if'], data=[]] else: mod_name = mod cmd = 'a2enmod -l' try: active_mods = __salt__['cmd.run'](cmd, python_shell=False).split(' ') # depends on [control=['try'], data=[]] except Exception as e: return e # depends on [control=['except'], data=['e']] return mod_name in active_mods
def get_ticker(self): """Return the latest ticker information. :return: Latest ticker information. :rtype: dict """ self._log('get ticker') return self._rest_client.get( endpoint='/ticker', params={'book': self.name} )
def function[get_ticker, parameter[self]]: constant[Return the latest ticker information. :return: Latest ticker information. :rtype: dict ] call[name[self]._log, parameter[constant[get ticker]]] return[call[name[self]._rest_client.get, parameter[]]]
keyword[def] identifier[get_ticker] ( identifier[self] ): literal[string] identifier[self] . identifier[_log] ( literal[string] ) keyword[return] identifier[self] . identifier[_rest_client] . identifier[get] ( identifier[endpoint] = literal[string] , identifier[params] ={ literal[string] : identifier[self] . identifier[name] } )
def get_ticker(self): """Return the latest ticker information. :return: Latest ticker information. :rtype: dict """ self._log('get ticker') return self._rest_client.get(endpoint='/ticker', params={'book': self.name})
def parameterized_expectations_direct(model, verbose=False, initial_dr=None, pert_order=1, grid={}, distribution={}, maxit=100, tol=1e-8): ''' Finds a global solution for ``model`` using parameterized expectations function. Requires the model to be written with controls as a direct function of the model objects. The algorithm iterates on the expectations function in the arbitrage equation. It follows the discussion in section 9.9 of Miranda and Fackler (2002). Parameters ---------- model : NumericModel "dtcscc" model to be solved verbose : boolean if True, display iterations initial_dr : decision rule initial guess for the decision rule pert_order : {1} if no initial guess is supplied, the perturbation solution at order ``pert_order`` is used as initial guess grid: grid options distribution: distribution options maxit: maximum number of iterations tol: tolerance criterium for successive approximations Returns ------- decision rule : approximated solution ''' t1 = time.time() g = model.functions['transition'] d = model.functions['direct_response'] h = model.functions['expectation'] parms = model.calibration['parameters'] if initial_dr is None: if pert_order == 1: initial_dr = approximate_controls(model) if pert_order > 1: raise Exception("Perturbation order > 1 not supported (yet).") approx = model.get_grid(**grid) grid = approx.grid interp_type = approx.interpolation dr = create_interpolator(approx, interp_type) expect = create_interpolator(approx, interp_type) distrib = model.get_distribution(**distribution) nodes, weights = distrib.discretize() N = grid.shape[0] z = np.zeros((N, len(model.symbols['expectations']))) x_0 = initial_dr(grid) x_0 = x_0.real # just in case ... h_0 = h(grid, x_0, parms) it = 0 err = 10 err_0 = 10 if verbose: headline = '|{0:^4} | {1:10} | {2:8} | {3:8} |' headline = headline.format('N', ' Error', 'Gain', 'Time') stars = '-'*len(headline) print(stars) print(headline) print(stars) # format string for within loop fmt_str = '|{0:4} | {1:10.3e} | {2:8.3f} | {3:8.3f} |' while err > tol and it <= maxit: it += 1 t_start = time.time() # dr.set_values(x_0) expect.set_values(h_0) z[...] = 0 for i in range(weights.shape[0]): e = nodes[i, :] S = g(grid, x_0, e, parms) # evaluate expectation over the future state z += weights[i]*expect(S) # TODO: check that control is admissible new_x = d(grid, z, parms) new_h = h(grid, new_x, parms) # update error err = (abs(new_h - h_0).max()) # Update guess for decision rule and expectations function x_0 = new_x h_0 = new_h # print error information if `verbose` err_SA = err/err_0 err_0 = err t_finish = time.time() elapsed = t_finish - t_start if verbose: print(fmt_str.format(it, err, err_SA, elapsed)) if it == maxit: import warnings warnings.warn(UserWarning("Maximum number of iterations reached")) # compute final fime and do final printout if `verbose` t2 = time.time() if verbose: print(stars) print('Elapsed: {} seconds.'.format(t2 - t1)) print(stars) # Interpolation for the decision rule dr.set_values(x_0) return dr
def function[parameterized_expectations_direct, parameter[model, verbose, initial_dr, pert_order, grid, distribution, maxit, tol]]: constant[ Finds a global solution for ``model`` using parameterized expectations function. Requires the model to be written with controls as a direct function of the model objects. The algorithm iterates on the expectations function in the arbitrage equation. It follows the discussion in section 9.9 of Miranda and Fackler (2002). Parameters ---------- model : NumericModel "dtcscc" model to be solved verbose : boolean if True, display iterations initial_dr : decision rule initial guess for the decision rule pert_order : {1} if no initial guess is supplied, the perturbation solution at order ``pert_order`` is used as initial guess grid: grid options distribution: distribution options maxit: maximum number of iterations tol: tolerance criterium for successive approximations Returns ------- decision rule : approximated solution ] variable[t1] assign[=] call[name[time].time, parameter[]] variable[g] assign[=] call[name[model].functions][constant[transition]] variable[d] assign[=] call[name[model].functions][constant[direct_response]] variable[h] assign[=] call[name[model].functions][constant[expectation]] variable[parms] assign[=] call[name[model].calibration][constant[parameters]] if compare[name[initial_dr] is constant[None]] begin[:] if compare[name[pert_order] equal[==] constant[1]] begin[:] variable[initial_dr] assign[=] call[name[approximate_controls], parameter[name[model]]] if compare[name[pert_order] greater[>] constant[1]] begin[:] <ast.Raise object at 0x7da20e9b2c20> variable[approx] assign[=] call[name[model].get_grid, parameter[]] variable[grid] assign[=] name[approx].grid variable[interp_type] assign[=] name[approx].interpolation variable[dr] assign[=] call[name[create_interpolator], parameter[name[approx], name[interp_type]]] variable[expect] assign[=] call[name[create_interpolator], parameter[name[approx], name[interp_type]]] variable[distrib] assign[=] call[name[model].get_distribution, parameter[]] <ast.Tuple object at 0x7da20e9b30d0> assign[=] call[name[distrib].discretize, parameter[]] variable[N] assign[=] call[name[grid].shape][constant[0]] variable[z] assign[=] call[name[np].zeros, parameter[tuple[[<ast.Name object at 0x7da20e9b2200>, <ast.Call object at 0x7da20e9b1120>]]]] variable[x_0] assign[=] call[name[initial_dr], parameter[name[grid]]] variable[x_0] assign[=] name[x_0].real variable[h_0] assign[=] call[name[h], parameter[name[grid], name[x_0], name[parms]]] variable[it] assign[=] constant[0] variable[err] assign[=] constant[10] variable[err_0] assign[=] constant[10] if name[verbose] begin[:] variable[headline] assign[=] constant[|{0:^4} | {1:10} | {2:8} | {3:8} |] variable[headline] assign[=] call[name[headline].format, parameter[constant[N], constant[ Error], constant[Gain], constant[Time]]] variable[stars] assign[=] binary_operation[constant[-] * call[name[len], parameter[name[headline]]]] call[name[print], parameter[name[stars]]] call[name[print], parameter[name[headline]]] call[name[print], parameter[name[stars]]] variable[fmt_str] assign[=] constant[|{0:4} | {1:10.3e} | {2:8.3f} | {3:8.3f} |] while <ast.BoolOp object at 0x7da20e9b00d0> begin[:] <ast.AugAssign object at 0x7da20e9b3af0> variable[t_start] assign[=] call[name[time].time, parameter[]] call[name[expect].set_values, parameter[name[h_0]]] call[name[z]][constant[Ellipsis]] assign[=] constant[0] for taget[name[i]] in starred[call[name[range], parameter[call[name[weights].shape][constant[0]]]]] begin[:] variable[e] assign[=] call[name[nodes]][tuple[[<ast.Name object at 0x7da20e748820>, <ast.Slice object at 0x7da20e74bf10>]]] variable[S] assign[=] call[name[g], parameter[name[grid], name[x_0], name[e], name[parms]]] <ast.AugAssign object at 0x7da18bc70130> variable[new_x] assign[=] call[name[d], parameter[name[grid], name[z], name[parms]]] variable[new_h] assign[=] call[name[h], parameter[name[grid], name[new_x], name[parms]]] variable[err] assign[=] call[call[name[abs], parameter[binary_operation[name[new_h] - name[h_0]]]].max, parameter[]] variable[x_0] assign[=] name[new_x] variable[h_0] assign[=] name[new_h] variable[err_SA] assign[=] binary_operation[name[err] / name[err_0]] variable[err_0] assign[=] name[err] variable[t_finish] assign[=] call[name[time].time, parameter[]] variable[elapsed] assign[=] binary_operation[name[t_finish] - name[t_start]] if name[verbose] begin[:] call[name[print], parameter[call[name[fmt_str].format, parameter[name[it], name[err], name[err_SA], name[elapsed]]]]] if compare[name[it] equal[==] name[maxit]] begin[:] import module[warnings] call[name[warnings].warn, parameter[call[name[UserWarning], parameter[constant[Maximum number of iterations reached]]]]] variable[t2] assign[=] call[name[time].time, parameter[]] if name[verbose] begin[:] call[name[print], parameter[name[stars]]] call[name[print], parameter[call[constant[Elapsed: {} seconds.].format, parameter[binary_operation[name[t2] - name[t1]]]]]] call[name[print], parameter[name[stars]]] call[name[dr].set_values, parameter[name[x_0]]] return[name[dr]]
keyword[def] identifier[parameterized_expectations_direct] ( identifier[model] , identifier[verbose] = keyword[False] , identifier[initial_dr] = keyword[None] , identifier[pert_order] = literal[int] , identifier[grid] ={}, identifier[distribution] ={}, identifier[maxit] = literal[int] , identifier[tol] = literal[int] ): literal[string] identifier[t1] = identifier[time] . identifier[time] () identifier[g] = identifier[model] . identifier[functions] [ literal[string] ] identifier[d] = identifier[model] . identifier[functions] [ literal[string] ] identifier[h] = identifier[model] . identifier[functions] [ literal[string] ] identifier[parms] = identifier[model] . identifier[calibration] [ literal[string] ] keyword[if] identifier[initial_dr] keyword[is] keyword[None] : keyword[if] identifier[pert_order] == literal[int] : identifier[initial_dr] = identifier[approximate_controls] ( identifier[model] ) keyword[if] identifier[pert_order] > literal[int] : keyword[raise] identifier[Exception] ( literal[string] ) identifier[approx] = identifier[model] . identifier[get_grid] (** identifier[grid] ) identifier[grid] = identifier[approx] . identifier[grid] identifier[interp_type] = identifier[approx] . identifier[interpolation] identifier[dr] = identifier[create_interpolator] ( identifier[approx] , identifier[interp_type] ) identifier[expect] = identifier[create_interpolator] ( identifier[approx] , identifier[interp_type] ) identifier[distrib] = identifier[model] . identifier[get_distribution] (** identifier[distribution] ) identifier[nodes] , identifier[weights] = identifier[distrib] . identifier[discretize] () identifier[N] = identifier[grid] . identifier[shape] [ literal[int] ] identifier[z] = identifier[np] . identifier[zeros] (( identifier[N] , identifier[len] ( identifier[model] . identifier[symbols] [ literal[string] ]))) identifier[x_0] = identifier[initial_dr] ( identifier[grid] ) identifier[x_0] = identifier[x_0] . identifier[real] identifier[h_0] = identifier[h] ( identifier[grid] , identifier[x_0] , identifier[parms] ) identifier[it] = literal[int] identifier[err] = literal[int] identifier[err_0] = literal[int] keyword[if] identifier[verbose] : identifier[headline] = literal[string] identifier[headline] = identifier[headline] . identifier[format] ( literal[string] , literal[string] , literal[string] , literal[string] ) identifier[stars] = literal[string] * identifier[len] ( identifier[headline] ) identifier[print] ( identifier[stars] ) identifier[print] ( identifier[headline] ) identifier[print] ( identifier[stars] ) identifier[fmt_str] = literal[string] keyword[while] identifier[err] > identifier[tol] keyword[and] identifier[it] <= identifier[maxit] : identifier[it] += literal[int] identifier[t_start] = identifier[time] . identifier[time] () identifier[expect] . identifier[set_values] ( identifier[h_0] ) identifier[z] [...]= literal[int] keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[weights] . identifier[shape] [ literal[int] ]): identifier[e] = identifier[nodes] [ identifier[i] ,:] identifier[S] = identifier[g] ( identifier[grid] , identifier[x_0] , identifier[e] , identifier[parms] ) identifier[z] += identifier[weights] [ identifier[i] ]* identifier[expect] ( identifier[S] ) identifier[new_x] = identifier[d] ( identifier[grid] , identifier[z] , identifier[parms] ) identifier[new_h] = identifier[h] ( identifier[grid] , identifier[new_x] , identifier[parms] ) identifier[err] =( identifier[abs] ( identifier[new_h] - identifier[h_0] ). identifier[max] ()) identifier[x_0] = identifier[new_x] identifier[h_0] = identifier[new_h] identifier[err_SA] = identifier[err] / identifier[err_0] identifier[err_0] = identifier[err] identifier[t_finish] = identifier[time] . identifier[time] () identifier[elapsed] = identifier[t_finish] - identifier[t_start] keyword[if] identifier[verbose] : identifier[print] ( identifier[fmt_str] . identifier[format] ( identifier[it] , identifier[err] , identifier[err_SA] , identifier[elapsed] )) keyword[if] identifier[it] == identifier[maxit] : keyword[import] identifier[warnings] identifier[warnings] . identifier[warn] ( identifier[UserWarning] ( literal[string] )) identifier[t2] = identifier[time] . identifier[time] () keyword[if] identifier[verbose] : identifier[print] ( identifier[stars] ) identifier[print] ( literal[string] . identifier[format] ( identifier[t2] - identifier[t1] )) identifier[print] ( identifier[stars] ) identifier[dr] . identifier[set_values] ( identifier[x_0] ) keyword[return] identifier[dr]
def parameterized_expectations_direct(model, verbose=False, initial_dr=None, pert_order=1, grid={}, distribution={}, maxit=100, tol=1e-08): """ Finds a global solution for ``model`` using parameterized expectations function. Requires the model to be written with controls as a direct function of the model objects. The algorithm iterates on the expectations function in the arbitrage equation. It follows the discussion in section 9.9 of Miranda and Fackler (2002). Parameters ---------- model : NumericModel "dtcscc" model to be solved verbose : boolean if True, display iterations initial_dr : decision rule initial guess for the decision rule pert_order : {1} if no initial guess is supplied, the perturbation solution at order ``pert_order`` is used as initial guess grid: grid options distribution: distribution options maxit: maximum number of iterations tol: tolerance criterium for successive approximations Returns ------- decision rule : approximated solution """ t1 = time.time() g = model.functions['transition'] d = model.functions['direct_response'] h = model.functions['expectation'] parms = model.calibration['parameters'] if initial_dr is None: if pert_order == 1: initial_dr = approximate_controls(model) # depends on [control=['if'], data=[]] if pert_order > 1: raise Exception('Perturbation order > 1 not supported (yet).') # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['initial_dr']] approx = model.get_grid(**grid) grid = approx.grid interp_type = approx.interpolation dr = create_interpolator(approx, interp_type) expect = create_interpolator(approx, interp_type) distrib = model.get_distribution(**distribution) (nodes, weights) = distrib.discretize() N = grid.shape[0] z = np.zeros((N, len(model.symbols['expectations']))) x_0 = initial_dr(grid) x_0 = x_0.real # just in case ... h_0 = h(grid, x_0, parms) it = 0 err = 10 err_0 = 10 if verbose: headline = '|{0:^4} | {1:10} | {2:8} | {3:8} |' headline = headline.format('N', ' Error', 'Gain', 'Time') stars = '-' * len(headline) print(stars) print(headline) print(stars) # format string for within loop fmt_str = '|{0:4} | {1:10.3e} | {2:8.3f} | {3:8.3f} |' # depends on [control=['if'], data=[]] while err > tol and it <= maxit: it += 1 t_start = time.time() # dr.set_values(x_0) expect.set_values(h_0) z[...] = 0 for i in range(weights.shape[0]): e = nodes[i, :] S = g(grid, x_0, e, parms) # evaluate expectation over the future state z += weights[i] * expect(S) # depends on [control=['for'], data=['i']] # TODO: check that control is admissible new_x = d(grid, z, parms) new_h = h(grid, new_x, parms) # update error err = abs(new_h - h_0).max() # Update guess for decision rule and expectations function x_0 = new_x h_0 = new_h # print error information if `verbose` err_SA = err / err_0 err_0 = err t_finish = time.time() elapsed = t_finish - t_start if verbose: print(fmt_str.format(it, err, err_SA, elapsed)) # depends on [control=['if'], data=[]] # depends on [control=['while'], data=[]] if it == maxit: import warnings warnings.warn(UserWarning('Maximum number of iterations reached')) # depends on [control=['if'], data=[]] # compute final fime and do final printout if `verbose` t2 = time.time() if verbose: print(stars) print('Elapsed: {} seconds.'.format(t2 - t1)) print(stars) # depends on [control=['if'], data=[]] # Interpolation for the decision rule dr.set_values(x_0) return dr
def _get_all(self): ''' return all items ''' rowid = 0 while True: SQL_SELECT_MANY = 'SELECT rowid, * FROM %s WHERE rowid > ? LIMIT ?;' % self._table self._cursor.execute(SQL_SELECT_MANY, (rowid, ITEMS_PER_REQUEST)) items = self._cursor.fetchall() if len(items) == 0: break for item in items: rowid = item['_id'] yield self._make_item(item)
def function[_get_all, parameter[self]]: constant[ return all items ] variable[rowid] assign[=] constant[0] while constant[True] begin[:] variable[SQL_SELECT_MANY] assign[=] binary_operation[constant[SELECT rowid, * FROM %s WHERE rowid > ? LIMIT ?;] <ast.Mod object at 0x7da2590d6920> name[self]._table] call[name[self]._cursor.execute, parameter[name[SQL_SELECT_MANY], tuple[[<ast.Name object at 0x7da1b0c644f0>, <ast.Name object at 0x7da1b0c65240>]]]] variable[items] assign[=] call[name[self]._cursor.fetchall, parameter[]] if compare[call[name[len], parameter[name[items]]] equal[==] constant[0]] begin[:] break for taget[name[item]] in starred[name[items]] begin[:] variable[rowid] assign[=] call[name[item]][constant[_id]] <ast.Yield object at 0x7da1b0c64850>
keyword[def] identifier[_get_all] ( identifier[self] ): literal[string] identifier[rowid] = literal[int] keyword[while] keyword[True] : identifier[SQL_SELECT_MANY] = literal[string] % identifier[self] . identifier[_table] identifier[self] . identifier[_cursor] . identifier[execute] ( identifier[SQL_SELECT_MANY] ,( identifier[rowid] , identifier[ITEMS_PER_REQUEST] )) identifier[items] = identifier[self] . identifier[_cursor] . identifier[fetchall] () keyword[if] identifier[len] ( identifier[items] )== literal[int] : keyword[break] keyword[for] identifier[item] keyword[in] identifier[items] : identifier[rowid] = identifier[item] [ literal[string] ] keyword[yield] identifier[self] . identifier[_make_item] ( identifier[item] )
def _get_all(self): """ return all items """ rowid = 0 while True: SQL_SELECT_MANY = 'SELECT rowid, * FROM %s WHERE rowid > ? LIMIT ?;' % self._table self._cursor.execute(SQL_SELECT_MANY, (rowid, ITEMS_PER_REQUEST)) items = self._cursor.fetchall() if len(items) == 0: break # depends on [control=['if'], data=[]] for item in items: rowid = item['_id'] yield self._make_item(item) # depends on [control=['for'], data=['item']] # depends on [control=['while'], data=[]]
def get_shake_info(self, ticket): """ 获取摇周边的设备及用户信息 详情请参考 http://mp.weixin.qq.com/wiki/3/34904a5db3d0ec7bb5306335b8da1faf.html :param ticket: 摇周边业务的ticket,可在摇到的URL中得到,ticket生效时间为30分钟 :return: 设备及用户信息 """ res = self._post( 'shakearound/user/getshakeinfo', data={ 'ticket': ticket }, result_processor=lambda x: x['data'] ) return res
def function[get_shake_info, parameter[self, ticket]]: constant[ 获取摇周边的设备及用户信息 详情请参考 http://mp.weixin.qq.com/wiki/3/34904a5db3d0ec7bb5306335b8da1faf.html :param ticket: 摇周边业务的ticket,可在摇到的URL中得到,ticket生效时间为30分钟 :return: 设备及用户信息 ] variable[res] assign[=] call[name[self]._post, parameter[constant[shakearound/user/getshakeinfo]]] return[name[res]]
keyword[def] identifier[get_shake_info] ( identifier[self] , identifier[ticket] ): literal[string] identifier[res] = identifier[self] . identifier[_post] ( literal[string] , identifier[data] ={ literal[string] : identifier[ticket] }, identifier[result_processor] = keyword[lambda] identifier[x] : identifier[x] [ literal[string] ] ) keyword[return] identifier[res]
def get_shake_info(self, ticket): """ 获取摇周边的设备及用户信息 详情请参考 http://mp.weixin.qq.com/wiki/3/34904a5db3d0ec7bb5306335b8da1faf.html :param ticket: 摇周边业务的ticket,可在摇到的URL中得到,ticket生效时间为30分钟 :return: 设备及用户信息 """ res = self._post('shakearound/user/getshakeinfo', data={'ticket': ticket}, result_processor=lambda x: x['data']) return res
def _add_sync_queues_and_barrier(self, name, dependencies): """Adds ops to enqueue on all worker queues. Args: name: prefixed for the shared_name of ops. dependencies: control dependency from ops. Returns: an op that should be used as control dependency before starting next step. """ self._sync_queue_counter += 1 with tf.device(self.sync_queue_devices[self._sync_queue_counter % len(self.sync_queue_devices)]): sync_queues = [ tf.FIFOQueue(self.num_worker, [tf.bool], shapes=[[]], shared_name='%s%s' % (name, i)) for i in range(self.num_worker)] queue_ops = [] # For each other worker, add an entry in a queue, signaling that it can finish this step. token = tf.constant(False) with tf.control_dependencies(dependencies): for i, q in enumerate(sync_queues): if i != self.task_index: queue_ops.append(q.enqueue(token)) # Drain tokens off queue for this worker, one for each other worker. queue_ops.append( sync_queues[self.task_index].dequeue_many(len(sync_queues) - 1)) return tf.group(*queue_ops, name=name)
def function[_add_sync_queues_and_barrier, parameter[self, name, dependencies]]: constant[Adds ops to enqueue on all worker queues. Args: name: prefixed for the shared_name of ops. dependencies: control dependency from ops. Returns: an op that should be used as control dependency before starting next step. ] <ast.AugAssign object at 0x7da18f7213c0> with call[name[tf].device, parameter[call[name[self].sync_queue_devices][binary_operation[name[self]._sync_queue_counter <ast.Mod object at 0x7da2590d6920> call[name[len], parameter[name[self].sync_queue_devices]]]]]] begin[:] variable[sync_queues] assign[=] <ast.ListComp object at 0x7da18f7219f0> variable[queue_ops] assign[=] list[[]] variable[token] assign[=] call[name[tf].constant, parameter[constant[False]]] with call[name[tf].control_dependencies, parameter[name[dependencies]]] begin[:] for taget[tuple[[<ast.Name object at 0x7da18f7232e0>, <ast.Name object at 0x7da18f721cc0>]]] in starred[call[name[enumerate], parameter[name[sync_queues]]]] begin[:] if compare[name[i] not_equal[!=] name[self].task_index] begin[:] call[name[queue_ops].append, parameter[call[name[q].enqueue, parameter[name[token]]]]] call[name[queue_ops].append, parameter[call[call[name[sync_queues]][name[self].task_index].dequeue_many, parameter[binary_operation[call[name[len], parameter[name[sync_queues]]] - constant[1]]]]]] return[call[name[tf].group, parameter[<ast.Starred object at 0x7da18f721bd0>]]]
keyword[def] identifier[_add_sync_queues_and_barrier] ( identifier[self] , identifier[name] , identifier[dependencies] ): literal[string] identifier[self] . identifier[_sync_queue_counter] += literal[int] keyword[with] identifier[tf] . identifier[device] ( identifier[self] . identifier[sync_queue_devices] [ identifier[self] . identifier[_sync_queue_counter] % identifier[len] ( identifier[self] . identifier[sync_queue_devices] )]): identifier[sync_queues] =[ identifier[tf] . identifier[FIFOQueue] ( identifier[self] . identifier[num_worker] ,[ identifier[tf] . identifier[bool] ], identifier[shapes] =[[]], identifier[shared_name] = literal[string] %( identifier[name] , identifier[i] )) keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[self] . identifier[num_worker] )] identifier[queue_ops] =[] identifier[token] = identifier[tf] . identifier[constant] ( keyword[False] ) keyword[with] identifier[tf] . identifier[control_dependencies] ( identifier[dependencies] ): keyword[for] identifier[i] , identifier[q] keyword[in] identifier[enumerate] ( identifier[sync_queues] ): keyword[if] identifier[i] != identifier[self] . identifier[task_index] : identifier[queue_ops] . identifier[append] ( identifier[q] . identifier[enqueue] ( identifier[token] )) identifier[queue_ops] . identifier[append] ( identifier[sync_queues] [ identifier[self] . identifier[task_index] ]. identifier[dequeue_many] ( identifier[len] ( identifier[sync_queues] )- literal[int] )) keyword[return] identifier[tf] . identifier[group] (* identifier[queue_ops] , identifier[name] = identifier[name] )
def _add_sync_queues_and_barrier(self, name, dependencies): """Adds ops to enqueue on all worker queues. Args: name: prefixed for the shared_name of ops. dependencies: control dependency from ops. Returns: an op that should be used as control dependency before starting next step. """ self._sync_queue_counter += 1 with tf.device(self.sync_queue_devices[self._sync_queue_counter % len(self.sync_queue_devices)]): sync_queues = [tf.FIFOQueue(self.num_worker, [tf.bool], shapes=[[]], shared_name='%s%s' % (name, i)) for i in range(self.num_worker)] queue_ops = [] # For each other worker, add an entry in a queue, signaling that it can finish this step. token = tf.constant(False) with tf.control_dependencies(dependencies): for (i, q) in enumerate(sync_queues): if i != self.task_index: queue_ops.append(q.enqueue(token)) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] # depends on [control=['with'], data=[]] # Drain tokens off queue for this worker, one for each other worker. queue_ops.append(sync_queues[self.task_index].dequeue_many(len(sync_queues) - 1)) return tf.group(*queue_ops, name=name) # depends on [control=['with'], data=[]]
def detect_pattern_format(pattern_filename, encoding, on_word_boundaries): ''' Automatically detects the pattern file format, and determines whether the Aho-Corasick string matching should pay attention to word boundaries or not. Arguments: - `pattern_filename`: - `encoding`: - `on_word_boundaries`: ''' tsv = True boundaries = on_word_boundaries with open_file(pattern_filename) as input_file: for line in input_file: line = line.decode(encoding) if line.count('\t') != 1: tsv = False if '\\b' in line: boundaries = True if boundaries and not tsv: break return tsv, boundaries
def function[detect_pattern_format, parameter[pattern_filename, encoding, on_word_boundaries]]: constant[ Automatically detects the pattern file format, and determines whether the Aho-Corasick string matching should pay attention to word boundaries or not. Arguments: - `pattern_filename`: - `encoding`: - `on_word_boundaries`: ] variable[tsv] assign[=] constant[True] variable[boundaries] assign[=] name[on_word_boundaries] with call[name[open_file], parameter[name[pattern_filename]]] begin[:] for taget[name[line]] in starred[name[input_file]] begin[:] variable[line] assign[=] call[name[line].decode, parameter[name[encoding]]] if compare[call[name[line].count, parameter[constant[ ]]] not_equal[!=] constant[1]] begin[:] variable[tsv] assign[=] constant[False] if compare[constant[\b] in name[line]] begin[:] variable[boundaries] assign[=] constant[True] if <ast.BoolOp object at 0x7da1b242fb50> begin[:] break return[tuple[[<ast.Name object at 0x7da1b242ff10>, <ast.Name object at 0x7da1b242fc10>]]]
keyword[def] identifier[detect_pattern_format] ( identifier[pattern_filename] , identifier[encoding] , identifier[on_word_boundaries] ): literal[string] identifier[tsv] = keyword[True] identifier[boundaries] = identifier[on_word_boundaries] keyword[with] identifier[open_file] ( identifier[pattern_filename] ) keyword[as] identifier[input_file] : keyword[for] identifier[line] keyword[in] identifier[input_file] : identifier[line] = identifier[line] . identifier[decode] ( identifier[encoding] ) keyword[if] identifier[line] . identifier[count] ( literal[string] )!= literal[int] : identifier[tsv] = keyword[False] keyword[if] literal[string] keyword[in] identifier[line] : identifier[boundaries] = keyword[True] keyword[if] identifier[boundaries] keyword[and] keyword[not] identifier[tsv] : keyword[break] keyword[return] identifier[tsv] , identifier[boundaries]
def detect_pattern_format(pattern_filename, encoding, on_word_boundaries): """ Automatically detects the pattern file format, and determines whether the Aho-Corasick string matching should pay attention to word boundaries or not. Arguments: - `pattern_filename`: - `encoding`: - `on_word_boundaries`: """ tsv = True boundaries = on_word_boundaries with open_file(pattern_filename) as input_file: for line in input_file: line = line.decode(encoding) if line.count('\t') != 1: tsv = False # depends on [control=['if'], data=[]] if '\\b' in line: boundaries = True # depends on [control=['if'], data=[]] if boundaries and (not tsv): break # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['line']] # depends on [control=['with'], data=['input_file']] return (tsv, boundaries)
def is_finite(val_1, val_2=None): """Checks if the supplied values are finite. Args: val_1: A namedtuple instance with the function value and derivative, as returned e.g. by value_and_gradients_function evaluations. val_2: (Optional) A namedtuple instance with the function value and derivative, as returned e.g. by value_and_gradients_function evaluations. Returns: is_finite: Scalar boolean `Tensor` indicating whether the function value and the derivative in `val_1` (and optionally in `val_2`) are all finite. """ val_1_finite = tf.math.is_finite(val_1.f) & tf.math.is_finite(val_1.df) if val_2 is not None: return val_1_finite & tf.math.is_finite(val_2.f) & tf.math.is_finite( val_2.df) return val_1_finite
def function[is_finite, parameter[val_1, val_2]]: constant[Checks if the supplied values are finite. Args: val_1: A namedtuple instance with the function value and derivative, as returned e.g. by value_and_gradients_function evaluations. val_2: (Optional) A namedtuple instance with the function value and derivative, as returned e.g. by value_and_gradients_function evaluations. Returns: is_finite: Scalar boolean `Tensor` indicating whether the function value and the derivative in `val_1` (and optionally in `val_2`) are all finite. ] variable[val_1_finite] assign[=] binary_operation[call[name[tf].math.is_finite, parameter[name[val_1].f]] <ast.BitAnd object at 0x7da2590d6b60> call[name[tf].math.is_finite, parameter[name[val_1].df]]] if compare[name[val_2] is_not constant[None]] begin[:] return[binary_operation[binary_operation[name[val_1_finite] <ast.BitAnd object at 0x7da2590d6b60> call[name[tf].math.is_finite, parameter[name[val_2].f]]] <ast.BitAnd object at 0x7da2590d6b60> call[name[tf].math.is_finite, parameter[name[val_2].df]]]] return[name[val_1_finite]]
keyword[def] identifier[is_finite] ( identifier[val_1] , identifier[val_2] = keyword[None] ): literal[string] identifier[val_1_finite] = identifier[tf] . identifier[math] . identifier[is_finite] ( identifier[val_1] . identifier[f] )& identifier[tf] . identifier[math] . identifier[is_finite] ( identifier[val_1] . identifier[df] ) keyword[if] identifier[val_2] keyword[is] keyword[not] keyword[None] : keyword[return] identifier[val_1_finite] & identifier[tf] . identifier[math] . identifier[is_finite] ( identifier[val_2] . identifier[f] )& identifier[tf] . identifier[math] . identifier[is_finite] ( identifier[val_2] . identifier[df] ) keyword[return] identifier[val_1_finite]
def is_finite(val_1, val_2=None): """Checks if the supplied values are finite. Args: val_1: A namedtuple instance with the function value and derivative, as returned e.g. by value_and_gradients_function evaluations. val_2: (Optional) A namedtuple instance with the function value and derivative, as returned e.g. by value_and_gradients_function evaluations. Returns: is_finite: Scalar boolean `Tensor` indicating whether the function value and the derivative in `val_1` (and optionally in `val_2`) are all finite. """ val_1_finite = tf.math.is_finite(val_1.f) & tf.math.is_finite(val_1.df) if val_2 is not None: return val_1_finite & tf.math.is_finite(val_2.f) & tf.math.is_finite(val_2.df) # depends on [control=['if'], data=['val_2']] return val_1_finite
def minkowski(src, tar, qval=2, pval=1, normalized=False, alphabet=None): """Return the Minkowski distance (:math:`L^p`-norm) of two strings. This is a wrapper for :py:meth:`Minkowski.dist_abs`. Parameters ---------- src : str Source string (or QGrams/Counter objects) for comparison tar : str Target string (or QGrams/Counter objects) for comparison qval : int The length of each q-gram; 0 for non-q-gram version pval : int or float The :math:`p`-value of the :math:`L^p`-space normalized : bool Normalizes to [0, 1] if True alphabet : collection or int The values or size of the alphabet Returns ------- float The Minkowski distance Examples -------- >>> minkowski('cat', 'hat') 4.0 >>> minkowski('Niall', 'Neil') 7.0 >>> minkowski('Colin', 'Cuilen') 9.0 >>> minkowski('ATCG', 'TAGC') 10.0 """ return Minkowski().dist_abs(src, tar, qval, pval, normalized, alphabet)
def function[minkowski, parameter[src, tar, qval, pval, normalized, alphabet]]: constant[Return the Minkowski distance (:math:`L^p`-norm) of two strings. This is a wrapper for :py:meth:`Minkowski.dist_abs`. Parameters ---------- src : str Source string (or QGrams/Counter objects) for comparison tar : str Target string (or QGrams/Counter objects) for comparison qval : int The length of each q-gram; 0 for non-q-gram version pval : int or float The :math:`p`-value of the :math:`L^p`-space normalized : bool Normalizes to [0, 1] if True alphabet : collection or int The values or size of the alphabet Returns ------- float The Minkowski distance Examples -------- >>> minkowski('cat', 'hat') 4.0 >>> minkowski('Niall', 'Neil') 7.0 >>> minkowski('Colin', 'Cuilen') 9.0 >>> minkowski('ATCG', 'TAGC') 10.0 ] return[call[call[name[Minkowski], parameter[]].dist_abs, parameter[name[src], name[tar], name[qval], name[pval], name[normalized], name[alphabet]]]]
keyword[def] identifier[minkowski] ( identifier[src] , identifier[tar] , identifier[qval] = literal[int] , identifier[pval] = literal[int] , identifier[normalized] = keyword[False] , identifier[alphabet] = keyword[None] ): literal[string] keyword[return] identifier[Minkowski] (). identifier[dist_abs] ( identifier[src] , identifier[tar] , identifier[qval] , identifier[pval] , identifier[normalized] , identifier[alphabet] )
def minkowski(src, tar, qval=2, pval=1, normalized=False, alphabet=None): """Return the Minkowski distance (:math:`L^p`-norm) of two strings. This is a wrapper for :py:meth:`Minkowski.dist_abs`. Parameters ---------- src : str Source string (or QGrams/Counter objects) for comparison tar : str Target string (or QGrams/Counter objects) for comparison qval : int The length of each q-gram; 0 for non-q-gram version pval : int or float The :math:`p`-value of the :math:`L^p`-space normalized : bool Normalizes to [0, 1] if True alphabet : collection or int The values or size of the alphabet Returns ------- float The Minkowski distance Examples -------- >>> minkowski('cat', 'hat') 4.0 >>> minkowski('Niall', 'Neil') 7.0 >>> minkowski('Colin', 'Cuilen') 9.0 >>> minkowski('ATCG', 'TAGC') 10.0 """ return Minkowski().dist_abs(src, tar, qval, pval, normalized, alphabet)
def load_or_create(cls, filename=None, no_input=False, create_new=False, **kwargs): """ Load system from a dump, if dump file exists, or create a new system if it does not exist. """ parser = argparse.ArgumentParser() parser.add_argument('--no_input', action='store_true') parser.add_argument('--create_new', action='store_true') args = parser.parse_args() if args.no_input: print('Parameter --no_input was given') no_input = True if args.create_new: print('Parameter --create_new was given') create_new = True no_input = True def savefile_more_recent(): time_savefile = os.path.getmtime(filename) time_program = os.path.getmtime(sys.argv[0]) return time_savefile > time_program def load_pickle(): with open(filename, 'rb') as of: statefile_version, data = pickle.load(of) if statefile_version != STATEFILE_VERSION: raise RuntimeError(f'Wrong statefile version, please remove state file {filename}') return data def load(): print('Loading %s' % filename) obj_list, config = load_pickle() system = System(load_state=obj_list, filename=filename, **kwargs) return system def create(): print('Creating new system') config = None if filename: try: obj_list, config = load_pickle() except FileNotFoundError: config = None return cls(filename=filename, load_config=config, **kwargs) if filename and os.path.isfile(filename): if savefile_more_recent() and not create_new: return load() else: if no_input: print('Program file more recent. Loading that instead.') return create() while True: answer = input('Program file more recent. Do you want to load it? (y/n) ') if answer == 'y': return create() elif answer == 'n': return load() else: return create()
def function[load_or_create, parameter[cls, filename, no_input, create_new]]: constant[ Load system from a dump, if dump file exists, or create a new system if it does not exist. ] variable[parser] assign[=] call[name[argparse].ArgumentParser, parameter[]] call[name[parser].add_argument, parameter[constant[--no_input]]] call[name[parser].add_argument, parameter[constant[--create_new]]] variable[args] assign[=] call[name[parser].parse_args, parameter[]] if name[args].no_input begin[:] call[name[print], parameter[constant[Parameter --no_input was given]]] variable[no_input] assign[=] constant[True] if name[args].create_new begin[:] call[name[print], parameter[constant[Parameter --create_new was given]]] variable[create_new] assign[=] constant[True] variable[no_input] assign[=] constant[True] def function[savefile_more_recent, parameter[]]: variable[time_savefile] assign[=] call[name[os].path.getmtime, parameter[name[filename]]] variable[time_program] assign[=] call[name[os].path.getmtime, parameter[call[name[sys].argv][constant[0]]]] return[compare[name[time_savefile] greater[>] name[time_program]]] def function[load_pickle, parameter[]]: with call[name[open], parameter[name[filename], constant[rb]]] begin[:] <ast.Tuple object at 0x7da1b255c7c0> assign[=] call[name[pickle].load, parameter[name[of]]] if compare[name[statefile_version] not_equal[!=] name[STATEFILE_VERSION]] begin[:] <ast.Raise object at 0x7da1b255e3b0> return[name[data]] def function[load, parameter[]]: call[name[print], parameter[binary_operation[constant[Loading %s] <ast.Mod object at 0x7da2590d6920> name[filename]]]] <ast.Tuple object at 0x7da1b255d6c0> assign[=] call[name[load_pickle], parameter[]] variable[system] assign[=] call[name[System], parameter[]] return[name[system]] def function[create, parameter[]]: call[name[print], parameter[constant[Creating new system]]] variable[config] assign[=] constant[None] if name[filename] begin[:] <ast.Try object at 0x7da1b253db10> return[call[name[cls], parameter[]]] if <ast.BoolOp object at 0x7da1b253e020> begin[:] if <ast.BoolOp object at 0x7da1b253dae0> begin[:] return[call[name[load], parameter[]]]
keyword[def] identifier[load_or_create] ( identifier[cls] , identifier[filename] = keyword[None] , identifier[no_input] = keyword[False] , identifier[create_new] = keyword[False] ,** identifier[kwargs] ): literal[string] identifier[parser] = identifier[argparse] . identifier[ArgumentParser] () identifier[parser] . identifier[add_argument] ( literal[string] , identifier[action] = literal[string] ) identifier[parser] . identifier[add_argument] ( literal[string] , identifier[action] = literal[string] ) identifier[args] = identifier[parser] . identifier[parse_args] () keyword[if] identifier[args] . identifier[no_input] : identifier[print] ( literal[string] ) identifier[no_input] = keyword[True] keyword[if] identifier[args] . identifier[create_new] : identifier[print] ( literal[string] ) identifier[create_new] = keyword[True] identifier[no_input] = keyword[True] keyword[def] identifier[savefile_more_recent] (): identifier[time_savefile] = identifier[os] . identifier[path] . identifier[getmtime] ( identifier[filename] ) identifier[time_program] = identifier[os] . identifier[path] . identifier[getmtime] ( identifier[sys] . identifier[argv] [ literal[int] ]) keyword[return] identifier[time_savefile] > identifier[time_program] keyword[def] identifier[load_pickle] (): keyword[with] identifier[open] ( identifier[filename] , literal[string] ) keyword[as] identifier[of] : identifier[statefile_version] , identifier[data] = identifier[pickle] . identifier[load] ( identifier[of] ) keyword[if] identifier[statefile_version] != identifier[STATEFILE_VERSION] : keyword[raise] identifier[RuntimeError] ( literal[string] ) keyword[return] identifier[data] keyword[def] identifier[load] (): identifier[print] ( literal[string] % identifier[filename] ) identifier[obj_list] , identifier[config] = identifier[load_pickle] () identifier[system] = identifier[System] ( identifier[load_state] = identifier[obj_list] , identifier[filename] = identifier[filename] ,** identifier[kwargs] ) keyword[return] identifier[system] keyword[def] identifier[create] (): identifier[print] ( literal[string] ) identifier[config] = keyword[None] keyword[if] identifier[filename] : keyword[try] : identifier[obj_list] , identifier[config] = identifier[load_pickle] () keyword[except] identifier[FileNotFoundError] : identifier[config] = keyword[None] keyword[return] identifier[cls] ( identifier[filename] = identifier[filename] , identifier[load_config] = identifier[config] ,** identifier[kwargs] ) keyword[if] identifier[filename] keyword[and] identifier[os] . identifier[path] . identifier[isfile] ( identifier[filename] ): keyword[if] identifier[savefile_more_recent] () keyword[and] keyword[not] identifier[create_new] : keyword[return] identifier[load] () keyword[else] : keyword[if] identifier[no_input] : identifier[print] ( literal[string] ) keyword[return] identifier[create] () keyword[while] keyword[True] : identifier[answer] = identifier[input] ( literal[string] ) keyword[if] identifier[answer] == literal[string] : keyword[return] identifier[create] () keyword[elif] identifier[answer] == literal[string] : keyword[return] identifier[load] () keyword[else] : keyword[return] identifier[create] ()
def load_or_create(cls, filename=None, no_input=False, create_new=False, **kwargs): """ Load system from a dump, if dump file exists, or create a new system if it does not exist. """ parser = argparse.ArgumentParser() parser.add_argument('--no_input', action='store_true') parser.add_argument('--create_new', action='store_true') args = parser.parse_args() if args.no_input: print('Parameter --no_input was given') no_input = True # depends on [control=['if'], data=[]] if args.create_new: print('Parameter --create_new was given') create_new = True no_input = True # depends on [control=['if'], data=[]] def savefile_more_recent(): time_savefile = os.path.getmtime(filename) time_program = os.path.getmtime(sys.argv[0]) return time_savefile > time_program def load_pickle(): with open(filename, 'rb') as of: (statefile_version, data) = pickle.load(of) # depends on [control=['with'], data=['of']] if statefile_version != STATEFILE_VERSION: raise RuntimeError(f'Wrong statefile version, please remove state file {filename}') # depends on [control=['if'], data=[]] return data def load(): print('Loading %s' % filename) (obj_list, config) = load_pickle() system = System(load_state=obj_list, filename=filename, **kwargs) return system def create(): print('Creating new system') config = None if filename: try: (obj_list, config) = load_pickle() # depends on [control=['try'], data=[]] except FileNotFoundError: config = None # depends on [control=['except'], data=[]] # depends on [control=['if'], data=[]] return cls(filename=filename, load_config=config, **kwargs) if filename and os.path.isfile(filename): if savefile_more_recent() and (not create_new): return load() # depends on [control=['if'], data=[]] else: if no_input: print('Program file more recent. Loading that instead.') return create() # depends on [control=['if'], data=[]] while True: answer = input('Program file more recent. Do you want to load it? (y/n) ') if answer == 'y': return create() # depends on [control=['if'], data=[]] elif answer == 'n': return load() # depends on [control=['if'], data=[]] # depends on [control=['while'], data=[]] # depends on [control=['if'], data=[]] else: return create()
def get(self, ns, label=None): """Return :class:`tags instances<~Tag>` for the namespace `ns`, ordered by label. If `label` is not None the only one instance may be returned, or `None` if no tags exists for this label. """ query = Tag.query.filter(Tag.ns == ns) if label is not None: return query.filter(Tag.label == label).first() return query.all()
def function[get, parameter[self, ns, label]]: constant[Return :class:`tags instances<~Tag>` for the namespace `ns`, ordered by label. If `label` is not None the only one instance may be returned, or `None` if no tags exists for this label. ] variable[query] assign[=] call[name[Tag].query.filter, parameter[compare[name[Tag].ns equal[==] name[ns]]]] if compare[name[label] is_not constant[None]] begin[:] return[call[call[name[query].filter, parameter[compare[name[Tag].label equal[==] name[label]]]].first, parameter[]]] return[call[name[query].all, parameter[]]]
keyword[def] identifier[get] ( identifier[self] , identifier[ns] , identifier[label] = keyword[None] ): literal[string] identifier[query] = identifier[Tag] . identifier[query] . identifier[filter] ( identifier[Tag] . identifier[ns] == identifier[ns] ) keyword[if] identifier[label] keyword[is] keyword[not] keyword[None] : keyword[return] identifier[query] . identifier[filter] ( identifier[Tag] . identifier[label] == identifier[label] ). identifier[first] () keyword[return] identifier[query] . identifier[all] ()
def get(self, ns, label=None): """Return :class:`tags instances<~Tag>` for the namespace `ns`, ordered by label. If `label` is not None the only one instance may be returned, or `None` if no tags exists for this label. """ query = Tag.query.filter(Tag.ns == ns) if label is not None: return query.filter(Tag.label == label).first() # depends on [control=['if'], data=['label']] return query.all()
def summarize(self, text, n): """ Return a list of n sentences which represent the summary of text. """ sents = sent_tokenize(text) assert n <= len(sents) word_sent = [word_tokenize(s.lower()) for s in sents] self._freq = self._compute_frequencies(word_sent) ranking = defaultdict(int) for i,sent in enumerate(word_sent): for w in sent: if w in self._freq: ranking[i] += self._freq[w] sents_idx = self._rank(ranking, n) return [sents[j] for j in sents_idx]
def function[summarize, parameter[self, text, n]]: constant[ Return a list of n sentences which represent the summary of text. ] variable[sents] assign[=] call[name[sent_tokenize], parameter[name[text]]] assert[compare[name[n] less_or_equal[<=] call[name[len], parameter[name[sents]]]]] variable[word_sent] assign[=] <ast.ListComp object at 0x7da1b1521a80> name[self]._freq assign[=] call[name[self]._compute_frequencies, parameter[name[word_sent]]] variable[ranking] assign[=] call[name[defaultdict], parameter[name[int]]] for taget[tuple[[<ast.Name object at 0x7da1b15217b0>, <ast.Name object at 0x7da1b1521000>]]] in starred[call[name[enumerate], parameter[name[word_sent]]]] begin[:] for taget[name[w]] in starred[name[sent]] begin[:] if compare[name[w] in name[self]._freq] begin[:] <ast.AugAssign object at 0x7da1b1521690> variable[sents_idx] assign[=] call[name[self]._rank, parameter[name[ranking], name[n]]] return[<ast.ListComp object at 0x7da1b1520760>]
keyword[def] identifier[summarize] ( identifier[self] , identifier[text] , identifier[n] ): literal[string] identifier[sents] = identifier[sent_tokenize] ( identifier[text] ) keyword[assert] identifier[n] <= identifier[len] ( identifier[sents] ) identifier[word_sent] =[ identifier[word_tokenize] ( identifier[s] . identifier[lower] ()) keyword[for] identifier[s] keyword[in] identifier[sents] ] identifier[self] . identifier[_freq] = identifier[self] . identifier[_compute_frequencies] ( identifier[word_sent] ) identifier[ranking] = identifier[defaultdict] ( identifier[int] ) keyword[for] identifier[i] , identifier[sent] keyword[in] identifier[enumerate] ( identifier[word_sent] ): keyword[for] identifier[w] keyword[in] identifier[sent] : keyword[if] identifier[w] keyword[in] identifier[self] . identifier[_freq] : identifier[ranking] [ identifier[i] ]+= identifier[self] . identifier[_freq] [ identifier[w] ] identifier[sents_idx] = identifier[self] . identifier[_rank] ( identifier[ranking] , identifier[n] ) keyword[return] [ identifier[sents] [ identifier[j] ] keyword[for] identifier[j] keyword[in] identifier[sents_idx] ]
def summarize(self, text, n): """ Return a list of n sentences which represent the summary of text. """ sents = sent_tokenize(text) assert n <= len(sents) word_sent = [word_tokenize(s.lower()) for s in sents] self._freq = self._compute_frequencies(word_sent) ranking = defaultdict(int) for (i, sent) in enumerate(word_sent): for w in sent: if w in self._freq: ranking[i] += self._freq[w] # depends on [control=['if'], data=['w']] # depends on [control=['for'], data=['w']] # depends on [control=['for'], data=[]] sents_idx = self._rank(ranking, n) return [sents[j] for j in sents_idx]
def _siren_settings(setting, value, validate_value): """Will validate siren settings and values, returns data packet.""" if validate_value: if value not in CONST.SETTING_DISABLE_ENABLE: raise AbodeException(ERROR.INVALID_SETTING_VALUE, CONST.SETTING_DISABLE_ENABLE) return {'action': setting, 'option': value}
def function[_siren_settings, parameter[setting, value, validate_value]]: constant[Will validate siren settings and values, returns data packet.] if name[validate_value] begin[:] if compare[name[value] <ast.NotIn object at 0x7da2590d7190> name[CONST].SETTING_DISABLE_ENABLE] begin[:] <ast.Raise object at 0x7da1b0c51120> return[dictionary[[<ast.Constant object at 0x7da1b0c50820>, <ast.Constant object at 0x7da1b0c500d0>], [<ast.Name object at 0x7da1b0c526b0>, <ast.Name object at 0x7da1b0c51c90>]]]
keyword[def] identifier[_siren_settings] ( identifier[setting] , identifier[value] , identifier[validate_value] ): literal[string] keyword[if] identifier[validate_value] : keyword[if] identifier[value] keyword[not] keyword[in] identifier[CONST] . identifier[SETTING_DISABLE_ENABLE] : keyword[raise] identifier[AbodeException] ( identifier[ERROR] . identifier[INVALID_SETTING_VALUE] , identifier[CONST] . identifier[SETTING_DISABLE_ENABLE] ) keyword[return] { literal[string] : identifier[setting] , literal[string] : identifier[value] }
def _siren_settings(setting, value, validate_value): """Will validate siren settings and values, returns data packet.""" if validate_value: if value not in CONST.SETTING_DISABLE_ENABLE: raise AbodeException(ERROR.INVALID_SETTING_VALUE, CONST.SETTING_DISABLE_ENABLE) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] return {'action': setting, 'option': value}
def send_empty(self, transaction, related, message): """ Manage ACK or RST related to a transaction. Sets if the transaction has been acknowledged or rejected. :param transaction: the transaction :param related: if the ACK/RST message is related to the request or the response. Must be equal to transaction.request or to transaction.response or None :type message: Message :param message: the ACK or RST message to send """ logger.debug("send_empty - " + str(message)) if transaction is None: try: host, port = message.destination except AttributeError: return key_mid = str_append_hash(host, port, message.mid) key_token = str_append_hash(host, port, message.token) if key_mid in self._transactions: transaction = self._transactions[key_mid] related = transaction.response elif key_token in self._transactions_token: transaction = self._transactions_token[key_token] related = transaction.response else: return message if message.type == defines.Types["ACK"]: if transaction.request == related: transaction.request.acknowledged = True transaction.completed = True message.mid = transaction.request.mid message.code = 0 message.destination = transaction.request.source elif transaction.response == related: transaction.response.acknowledged = True transaction.completed = True message.mid = transaction.response.mid message.code = 0 message.token = transaction.response.token message.destination = transaction.response.source elif message.type == defines.Types["RST"]: if transaction.request == related: transaction.request.rejected = True message._mid = transaction.request.mid if message.mid is None: message.mid = self.fetch_mid() message.code = 0 message.token = transaction.request.token message.destination = transaction.request.source elif transaction.response == related: transaction.response.rejected = True transaction.completed = True message._mid = transaction.response.mid if message.mid is None: message.mid = self.fetch_mid() message.code = 0 message.token = transaction.response.token message.destination = transaction.response.source return message
def function[send_empty, parameter[self, transaction, related, message]]: constant[ Manage ACK or RST related to a transaction. Sets if the transaction has been acknowledged or rejected. :param transaction: the transaction :param related: if the ACK/RST message is related to the request or the response. Must be equal to transaction.request or to transaction.response or None :type message: Message :param message: the ACK or RST message to send ] call[name[logger].debug, parameter[binary_operation[constant[send_empty - ] + call[name[str], parameter[name[message]]]]]] if compare[name[transaction] is constant[None]] begin[:] <ast.Try object at 0x7da20c6aacb0> variable[key_mid] assign[=] call[name[str_append_hash], parameter[name[host], name[port], name[message].mid]] variable[key_token] assign[=] call[name[str_append_hash], parameter[name[host], name[port], name[message].token]] if compare[name[key_mid] in name[self]._transactions] begin[:] variable[transaction] assign[=] call[name[self]._transactions][name[key_mid]] variable[related] assign[=] name[transaction].response if compare[name[message].type equal[==] call[name[defines].Types][constant[ACK]]] begin[:] if compare[name[transaction].request equal[==] name[related]] begin[:] name[transaction].request.acknowledged assign[=] constant[True] name[transaction].completed assign[=] constant[True] name[message].mid assign[=] name[transaction].request.mid name[message].code assign[=] constant[0] name[message].destination assign[=] name[transaction].request.source return[name[message]]
keyword[def] identifier[send_empty] ( identifier[self] , identifier[transaction] , identifier[related] , identifier[message] ): literal[string] identifier[logger] . identifier[debug] ( literal[string] + identifier[str] ( identifier[message] )) keyword[if] identifier[transaction] keyword[is] keyword[None] : keyword[try] : identifier[host] , identifier[port] = identifier[message] . identifier[destination] keyword[except] identifier[AttributeError] : keyword[return] identifier[key_mid] = identifier[str_append_hash] ( identifier[host] , identifier[port] , identifier[message] . identifier[mid] ) identifier[key_token] = identifier[str_append_hash] ( identifier[host] , identifier[port] , identifier[message] . identifier[token] ) keyword[if] identifier[key_mid] keyword[in] identifier[self] . identifier[_transactions] : identifier[transaction] = identifier[self] . identifier[_transactions] [ identifier[key_mid] ] identifier[related] = identifier[transaction] . identifier[response] keyword[elif] identifier[key_token] keyword[in] identifier[self] . identifier[_transactions_token] : identifier[transaction] = identifier[self] . identifier[_transactions_token] [ identifier[key_token] ] identifier[related] = identifier[transaction] . identifier[response] keyword[else] : keyword[return] identifier[message] keyword[if] identifier[message] . identifier[type] == identifier[defines] . identifier[Types] [ literal[string] ]: keyword[if] identifier[transaction] . identifier[request] == identifier[related] : identifier[transaction] . identifier[request] . identifier[acknowledged] = keyword[True] identifier[transaction] . identifier[completed] = keyword[True] identifier[message] . identifier[mid] = identifier[transaction] . identifier[request] . identifier[mid] identifier[message] . identifier[code] = literal[int] identifier[message] . identifier[destination] = identifier[transaction] . identifier[request] . identifier[source] keyword[elif] identifier[transaction] . identifier[response] == identifier[related] : identifier[transaction] . identifier[response] . identifier[acknowledged] = keyword[True] identifier[transaction] . identifier[completed] = keyword[True] identifier[message] . identifier[mid] = identifier[transaction] . identifier[response] . identifier[mid] identifier[message] . identifier[code] = literal[int] identifier[message] . identifier[token] = identifier[transaction] . identifier[response] . identifier[token] identifier[message] . identifier[destination] = identifier[transaction] . identifier[response] . identifier[source] keyword[elif] identifier[message] . identifier[type] == identifier[defines] . identifier[Types] [ literal[string] ]: keyword[if] identifier[transaction] . identifier[request] == identifier[related] : identifier[transaction] . identifier[request] . identifier[rejected] = keyword[True] identifier[message] . identifier[_mid] = identifier[transaction] . identifier[request] . identifier[mid] keyword[if] identifier[message] . identifier[mid] keyword[is] keyword[None] : identifier[message] . identifier[mid] = identifier[self] . identifier[fetch_mid] () identifier[message] . identifier[code] = literal[int] identifier[message] . identifier[token] = identifier[transaction] . identifier[request] . identifier[token] identifier[message] . identifier[destination] = identifier[transaction] . identifier[request] . identifier[source] keyword[elif] identifier[transaction] . identifier[response] == identifier[related] : identifier[transaction] . identifier[response] . identifier[rejected] = keyword[True] identifier[transaction] . identifier[completed] = keyword[True] identifier[message] . identifier[_mid] = identifier[transaction] . identifier[response] . identifier[mid] keyword[if] identifier[message] . identifier[mid] keyword[is] keyword[None] : identifier[message] . identifier[mid] = identifier[self] . identifier[fetch_mid] () identifier[message] . identifier[code] = literal[int] identifier[message] . identifier[token] = identifier[transaction] . identifier[response] . identifier[token] identifier[message] . identifier[destination] = identifier[transaction] . identifier[response] . identifier[source] keyword[return] identifier[message]
def send_empty(self, transaction, related, message): """ Manage ACK or RST related to a transaction. Sets if the transaction has been acknowledged or rejected. :param transaction: the transaction :param related: if the ACK/RST message is related to the request or the response. Must be equal to transaction.request or to transaction.response or None :type message: Message :param message: the ACK or RST message to send """ logger.debug('send_empty - ' + str(message)) if transaction is None: try: (host, port) = message.destination # depends on [control=['try'], data=[]] except AttributeError: return # depends on [control=['except'], data=[]] key_mid = str_append_hash(host, port, message.mid) key_token = str_append_hash(host, port, message.token) if key_mid in self._transactions: transaction = self._transactions[key_mid] related = transaction.response # depends on [control=['if'], data=['key_mid']] elif key_token in self._transactions_token: transaction = self._transactions_token[key_token] related = transaction.response # depends on [control=['if'], data=['key_token']] else: return message # depends on [control=['if'], data=['transaction']] if message.type == defines.Types['ACK']: if transaction.request == related: transaction.request.acknowledged = True transaction.completed = True message.mid = transaction.request.mid message.code = 0 message.destination = transaction.request.source # depends on [control=['if'], data=[]] elif transaction.response == related: transaction.response.acknowledged = True transaction.completed = True message.mid = transaction.response.mid message.code = 0 message.token = transaction.response.token message.destination = transaction.response.source # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] elif message.type == defines.Types['RST']: if transaction.request == related: transaction.request.rejected = True message._mid = transaction.request.mid if message.mid is None: message.mid = self.fetch_mid() # depends on [control=['if'], data=[]] message.code = 0 message.token = transaction.request.token message.destination = transaction.request.source # depends on [control=['if'], data=[]] elif transaction.response == related: transaction.response.rejected = True transaction.completed = True message._mid = transaction.response.mid if message.mid is None: message.mid = self.fetch_mid() # depends on [control=['if'], data=[]] message.code = 0 message.token = transaction.response.token message.destination = transaction.response.source # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] return message
def get_instance(self, payload): """ Build an instance of AuthCallsCredentialListMappingInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingInstance :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingInstance """ return AuthCallsCredentialListMappingInstance( self._version, payload, account_sid=self._solution['account_sid'], domain_sid=self._solution['domain_sid'], )
def function[get_instance, parameter[self, payload]]: constant[ Build an instance of AuthCallsCredentialListMappingInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingInstance :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingInstance ] return[call[name[AuthCallsCredentialListMappingInstance], parameter[name[self]._version, name[payload]]]]
keyword[def] identifier[get_instance] ( identifier[self] , identifier[payload] ): literal[string] keyword[return] identifier[AuthCallsCredentialListMappingInstance] ( identifier[self] . identifier[_version] , identifier[payload] , identifier[account_sid] = identifier[self] . identifier[_solution] [ literal[string] ], identifier[domain_sid] = identifier[self] . identifier[_solution] [ literal[string] ], )
def get_instance(self, payload): """ Build an instance of AuthCallsCredentialListMappingInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingInstance :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingInstance """ return AuthCallsCredentialListMappingInstance(self._version, payload, account_sid=self._solution['account_sid'], domain_sid=self._solution['domain_sid'])
def make_version(ref=None): """Build git version string for current directory""" cmd = 'git describe --tags --abbrev=6 {}'.format(ref or '') with hide('commands'): version = local(cmd, capture=True).strip() if re.match('^v[0-9]', version): version = version[1:] # replacements to match semver.org build numbers if '-' in version: head, _, tail = version.partition('-') count, _, sha = tail.partition('-g') version = head + '+' + count + '-' + sha return version
def function[make_version, parameter[ref]]: constant[Build git version string for current directory] variable[cmd] assign[=] call[constant[git describe --tags --abbrev=6 {}].format, parameter[<ast.BoolOp object at 0x7da1b0967550>]] with call[name[hide], parameter[constant[commands]]] begin[:] variable[version] assign[=] call[call[name[local], parameter[name[cmd]]].strip, parameter[]] if call[name[re].match, parameter[constant[^v[0-9]], name[version]]] begin[:] variable[version] assign[=] call[name[version]][<ast.Slice object at 0x7da1b0965f30>] if compare[constant[-] in name[version]] begin[:] <ast.Tuple object at 0x7da1b09673d0> assign[=] call[name[version].partition, parameter[constant[-]]] <ast.Tuple object at 0x7da1b0966620> assign[=] call[name[tail].partition, parameter[constant[-g]]] variable[version] assign[=] binary_operation[binary_operation[binary_operation[binary_operation[name[head] + constant[+]] + name[count]] + constant[-]] + name[sha]] return[name[version]]
keyword[def] identifier[make_version] ( identifier[ref] = keyword[None] ): literal[string] identifier[cmd] = literal[string] . identifier[format] ( identifier[ref] keyword[or] literal[string] ) keyword[with] identifier[hide] ( literal[string] ): identifier[version] = identifier[local] ( identifier[cmd] , identifier[capture] = keyword[True] ). identifier[strip] () keyword[if] identifier[re] . identifier[match] ( literal[string] , identifier[version] ): identifier[version] = identifier[version] [ literal[int] :] keyword[if] literal[string] keyword[in] identifier[version] : identifier[head] , identifier[_] , identifier[tail] = identifier[version] . identifier[partition] ( literal[string] ) identifier[count] , identifier[_] , identifier[sha] = identifier[tail] . identifier[partition] ( literal[string] ) identifier[version] = identifier[head] + literal[string] + identifier[count] + literal[string] + identifier[sha] keyword[return] identifier[version]
def make_version(ref=None): """Build git version string for current directory""" cmd = 'git describe --tags --abbrev=6 {}'.format(ref or '') with hide('commands'): version = local(cmd, capture=True).strip() # depends on [control=['with'], data=[]] if re.match('^v[0-9]', version): version = version[1:] # depends on [control=['if'], data=[]] # replacements to match semver.org build numbers if '-' in version: (head, _, tail) = version.partition('-') (count, _, sha) = tail.partition('-g') version = head + '+' + count + '-' + sha # depends on [control=['if'], data=['version']] return version
def get_method_by_name(self, class_name, method_name, method_descriptor): """ Search for a :class:`EncodedMethod` in all classes in this analysis :param class_name: name of the class, for example 'Ljava/lang/Object;' :param method_name: name of the method, for example 'onCreate' :param method_descriptor: descriptor, for example '(I I Ljava/lang/String)V :return: :class:`EncodedMethod` or None if method was not found """ if class_name in self.classes: for method in self.classes[class_name].get_vm_class().get_methods(): if method.get_name() == method_name and method.get_descriptor() == method_descriptor: return method return None
def function[get_method_by_name, parameter[self, class_name, method_name, method_descriptor]]: constant[ Search for a :class:`EncodedMethod` in all classes in this analysis :param class_name: name of the class, for example 'Ljava/lang/Object;' :param method_name: name of the method, for example 'onCreate' :param method_descriptor: descriptor, for example '(I I Ljava/lang/String)V :return: :class:`EncodedMethod` or None if method was not found ] if compare[name[class_name] in name[self].classes] begin[:] for taget[name[method]] in starred[call[call[call[name[self].classes][name[class_name]].get_vm_class, parameter[]].get_methods, parameter[]]] begin[:] if <ast.BoolOp object at 0x7da18c4ce320> begin[:] return[name[method]] return[constant[None]]
keyword[def] identifier[get_method_by_name] ( identifier[self] , identifier[class_name] , identifier[method_name] , identifier[method_descriptor] ): literal[string] keyword[if] identifier[class_name] keyword[in] identifier[self] . identifier[classes] : keyword[for] identifier[method] keyword[in] identifier[self] . identifier[classes] [ identifier[class_name] ]. identifier[get_vm_class] (). identifier[get_methods] (): keyword[if] identifier[method] . identifier[get_name] ()== identifier[method_name] keyword[and] identifier[method] . identifier[get_descriptor] ()== identifier[method_descriptor] : keyword[return] identifier[method] keyword[return] keyword[None]
def get_method_by_name(self, class_name, method_name, method_descriptor): """ Search for a :class:`EncodedMethod` in all classes in this analysis :param class_name: name of the class, for example 'Ljava/lang/Object;' :param method_name: name of the method, for example 'onCreate' :param method_descriptor: descriptor, for example '(I I Ljava/lang/String)V :return: :class:`EncodedMethod` or None if method was not found """ if class_name in self.classes: for method in self.classes[class_name].get_vm_class().get_methods(): if method.get_name() == method_name and method.get_descriptor() == method_descriptor: return method # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['method']] # depends on [control=['if'], data=['class_name']] return None
def filter(self, field, operator, value): """ Add a query filter to be applied to the next API list call for this resource. :param field: Field name to filter by :type field: str :param operator: Operator value :type operator: str :param value: Value of filter :type value: str :param object_type: Optional. Checks field for object association :type object_type: str Known Filters: Question [question(2)] surveyresponse Question Option [question(2), option(10001)] surveyresponse Date Submitted datesubmitted surveyresponse Is Test Data istestdata surveyresponse Status status surveyresponse Contact ID contact_id surveyresponse Creation Time createdon survey Last Modified Time modifiedon survey Survey Title title survey Type of Project subtype survey Team Survey Belongs To team survey Status status survey Type of Link type surveycampaign Name of Link name surveycampaign Secure / Unsecure Link ssl surveycampaign Link Created Date datecreated surveycampaign Link Last Modified Date datemodified surveycampaign Known Operators: = Is equal to (==) <> Is equal to (!=) IS NULL Value is not answered or is blank IS NOT NULL Value is answered or is not blank in Value is in comma separated list Unknown Operators: Not officially mentioned in documentation, but may work. == != >= <= > < """ instance = copy(self) i = len(instance._filters) instance._filters.append({ 'filter[field][%d]' % i: str(field), 'filter[operator][%d]' % i: str(operator), 'filter[value][%d]' % i: str(value), }) return instance
def function[filter, parameter[self, field, operator, value]]: constant[ Add a query filter to be applied to the next API list call for this resource. :param field: Field name to filter by :type field: str :param operator: Operator value :type operator: str :param value: Value of filter :type value: str :param object_type: Optional. Checks field for object association :type object_type: str Known Filters: Question [question(2)] surveyresponse Question Option [question(2), option(10001)] surveyresponse Date Submitted datesubmitted surveyresponse Is Test Data istestdata surveyresponse Status status surveyresponse Contact ID contact_id surveyresponse Creation Time createdon survey Last Modified Time modifiedon survey Survey Title title survey Type of Project subtype survey Team Survey Belongs To team survey Status status survey Type of Link type surveycampaign Name of Link name surveycampaign Secure / Unsecure Link ssl surveycampaign Link Created Date datecreated surveycampaign Link Last Modified Date datemodified surveycampaign Known Operators: = Is equal to (==) <> Is equal to (!=) IS NULL Value is not answered or is blank IS NOT NULL Value is answered or is not blank in Value is in comma separated list Unknown Operators: Not officially mentioned in documentation, but may work. == != >= <= > < ] variable[instance] assign[=] call[name[copy], parameter[name[self]]] variable[i] assign[=] call[name[len], parameter[name[instance]._filters]] call[name[instance]._filters.append, parameter[dictionary[[<ast.BinOp object at 0x7da20e9b0820>, <ast.BinOp object at 0x7da20e9b00d0>, <ast.BinOp object at 0x7da20e9b06a0>], [<ast.Call object at 0x7da20e9b2b60>, <ast.Call object at 0x7da20e9b33a0>, <ast.Call object at 0x7da20e9b0df0>]]]] return[name[instance]]
keyword[def] identifier[filter] ( identifier[self] , identifier[field] , identifier[operator] , identifier[value] ): literal[string] identifier[instance] = identifier[copy] ( identifier[self] ) identifier[i] = identifier[len] ( identifier[instance] . identifier[_filters] ) identifier[instance] . identifier[_filters] . identifier[append] ({ literal[string] % identifier[i] : identifier[str] ( identifier[field] ), literal[string] % identifier[i] : identifier[str] ( identifier[operator] ), literal[string] % identifier[i] : identifier[str] ( identifier[value] ), }) keyword[return] identifier[instance]
def filter(self, field, operator, value): """ Add a query filter to be applied to the next API list call for this resource. :param field: Field name to filter by :type field: str :param operator: Operator value :type operator: str :param value: Value of filter :type value: str :param object_type: Optional. Checks field for object association :type object_type: str Known Filters: Question [question(2)] surveyresponse Question Option [question(2), option(10001)] surveyresponse Date Submitted datesubmitted surveyresponse Is Test Data istestdata surveyresponse Status status surveyresponse Contact ID contact_id surveyresponse Creation Time createdon survey Last Modified Time modifiedon survey Survey Title title survey Type of Project subtype survey Team Survey Belongs To team survey Status status survey Type of Link type surveycampaign Name of Link name surveycampaign Secure / Unsecure Link ssl surveycampaign Link Created Date datecreated surveycampaign Link Last Modified Date datemodified surveycampaign Known Operators: = Is equal to (==) <> Is equal to (!=) IS NULL Value is not answered or is blank IS NOT NULL Value is answered or is not blank in Value is in comma separated list Unknown Operators: Not officially mentioned in documentation, but may work. == != >= <= > < """ instance = copy(self) i = len(instance._filters) instance._filters.append({'filter[field][%d]' % i: str(field), 'filter[operator][%d]' % i: str(operator), 'filter[value][%d]' % i: str(value)}) return instance
def ro(self): """ Return read-only copy of this object :return: WHTTPHeaders """ ro_headers = WHTTPHeaders() names = self.headers() for name in names: ro_headers.add_headers(name, *self.get_headers(name)) ro_headers.__cookies = self.__set_cookies.ro() ro_headers.__ro_flag = True return ro_headers
def function[ro, parameter[self]]: constant[ Return read-only copy of this object :return: WHTTPHeaders ] variable[ro_headers] assign[=] call[name[WHTTPHeaders], parameter[]] variable[names] assign[=] call[name[self].headers, parameter[]] for taget[name[name]] in starred[name[names]] begin[:] call[name[ro_headers].add_headers, parameter[name[name], <ast.Starred object at 0x7da20e9575e0>]] name[ro_headers].__cookies assign[=] call[name[self].__set_cookies.ro, parameter[]] name[ro_headers].__ro_flag assign[=] constant[True] return[name[ro_headers]]
keyword[def] identifier[ro] ( identifier[self] ): literal[string] identifier[ro_headers] = identifier[WHTTPHeaders] () identifier[names] = identifier[self] . identifier[headers] () keyword[for] identifier[name] keyword[in] identifier[names] : identifier[ro_headers] . identifier[add_headers] ( identifier[name] ,* identifier[self] . identifier[get_headers] ( identifier[name] )) identifier[ro_headers] . identifier[__cookies] = identifier[self] . identifier[__set_cookies] . identifier[ro] () identifier[ro_headers] . identifier[__ro_flag] = keyword[True] keyword[return] identifier[ro_headers]
def ro(self): """ Return read-only copy of this object :return: WHTTPHeaders """ ro_headers = WHTTPHeaders() names = self.headers() for name in names: ro_headers.add_headers(name, *self.get_headers(name)) # depends on [control=['for'], data=['name']] ro_headers.__cookies = self.__set_cookies.ro() ro_headers.__ro_flag = True return ro_headers
def init_model_gaussian1d(observations, nstates, reversible=True): """Generate an initial model with 1D-Gaussian output densities Parameters ---------- observations : list of ndarray((T_i), dtype=float) list of arrays of length T_i with observation data nstates : int The number of states. Examples -------- Generate initial model for a gaussian output model. >>> from bhmm import testsystems >>> [model, observations, states] = testsystems.generate_synthetic_observations(output='gaussian') >>> initial_model = init_model_gaussian1d(observations, model.nstates) """ ntrajectories = len(observations) # Concatenate all observations. collected_observations = np.array([], dtype=config.dtype) for o_t in observations: collected_observations = np.append(collected_observations, o_t) # Fit a Gaussian mixture model to obtain emission distributions and state stationary probabilities. from bhmm._external.sklearn import mixture gmm = mixture.GMM(n_components=nstates) gmm.fit(collected_observations[:,None]) from bhmm import GaussianOutputModel output_model = GaussianOutputModel(nstates, means=gmm.means_[:,0], sigmas=np.sqrt(gmm.covars_[:,0])) logger().info("Gaussian output model:\n"+str(output_model)) # Extract stationary distributions. Pi = np.zeros([nstates], np.float64) Pi[:] = gmm.weights_[:] logger().info("GMM weights: %s" % str(gmm.weights_)) # Compute fractional state memberships. Nij = np.zeros([nstates, nstates], np.float64) for o_t in observations: # length of trajectory T = o_t.shape[0] # output probability pobs = output_model.p_obs(o_t) # normalize pobs /= pobs.sum(axis=1)[:,None] # Accumulate fractional transition counts from this trajectory. for t in range(T-1): Nij[:,:] = Nij[:,:] + np.outer(pobs[t,:], pobs[t+1,:]) logger().info("Nij\n"+str(Nij)) # Compute transition matrix maximum likelihood estimate. import msmtools.estimation as msmest import msmtools.analysis as msmana Tij = msmest.transition_matrix(Nij, reversible=reversible) pi = msmana.stationary_distribution(Tij) # Update model. model = HMM(pi, Tij, output_model) return model
def function[init_model_gaussian1d, parameter[observations, nstates, reversible]]: constant[Generate an initial model with 1D-Gaussian output densities Parameters ---------- observations : list of ndarray((T_i), dtype=float) list of arrays of length T_i with observation data nstates : int The number of states. Examples -------- Generate initial model for a gaussian output model. >>> from bhmm import testsystems >>> [model, observations, states] = testsystems.generate_synthetic_observations(output='gaussian') >>> initial_model = init_model_gaussian1d(observations, model.nstates) ] variable[ntrajectories] assign[=] call[name[len], parameter[name[observations]]] variable[collected_observations] assign[=] call[name[np].array, parameter[list[[]]]] for taget[name[o_t]] in starred[name[observations]] begin[:] variable[collected_observations] assign[=] call[name[np].append, parameter[name[collected_observations], name[o_t]]] from relative_module[bhmm._external.sklearn] import module[mixture] variable[gmm] assign[=] call[name[mixture].GMM, parameter[]] call[name[gmm].fit, parameter[call[name[collected_observations]][tuple[[<ast.Slice object at 0x7da18eb56590>, <ast.Constant object at 0x7da18eb57d90>]]]]] from relative_module[bhmm] import module[GaussianOutputModel] variable[output_model] assign[=] call[name[GaussianOutputModel], parameter[name[nstates]]] call[call[name[logger], parameter[]].info, parameter[binary_operation[constant[Gaussian output model: ] + call[name[str], parameter[name[output_model]]]]]] variable[Pi] assign[=] call[name[np].zeros, parameter[list[[<ast.Name object at 0x7da18eb56ce0>]], name[np].float64]] call[name[Pi]][<ast.Slice object at 0x7da18eb55f00>] assign[=] call[name[gmm].weights_][<ast.Slice object at 0x7da18eb541c0>] call[call[name[logger], parameter[]].info, parameter[binary_operation[constant[GMM weights: %s] <ast.Mod object at 0x7da2590d6920> call[name[str], parameter[name[gmm].weights_]]]]] variable[Nij] assign[=] call[name[np].zeros, parameter[list[[<ast.Name object at 0x7da18eb56800>, <ast.Name object at 0x7da18eb56350>]], name[np].float64]] for taget[name[o_t]] in starred[name[observations]] begin[:] variable[T] assign[=] call[name[o_t].shape][constant[0]] variable[pobs] assign[=] call[name[output_model].p_obs, parameter[name[o_t]]] <ast.AugAssign object at 0x7da18eb579d0> for taget[name[t]] in starred[call[name[range], parameter[binary_operation[name[T] - constant[1]]]]] begin[:] call[name[Nij]][tuple[[<ast.Slice object at 0x7da18eb55750>, <ast.Slice object at 0x7da18eb57d60>]]] assign[=] binary_operation[call[name[Nij]][tuple[[<ast.Slice object at 0x7da18eb55bd0>, <ast.Slice object at 0x7da18eb54f70>]]] + call[name[np].outer, parameter[call[name[pobs]][tuple[[<ast.Name object at 0x7da18eb56110>, <ast.Slice object at 0x7da18eb54610>]]], call[name[pobs]][tuple[[<ast.BinOp object at 0x7da18eb545b0>, <ast.Slice object at 0x7da18eb56dd0>]]]]]] call[call[name[logger], parameter[]].info, parameter[binary_operation[constant[Nij ] + call[name[str], parameter[name[Nij]]]]]] import module[msmtools.estimation] as alias[msmest] import module[msmtools.analysis] as alias[msmana] variable[Tij] assign[=] call[name[msmest].transition_matrix, parameter[name[Nij]]] variable[pi] assign[=] call[name[msmana].stationary_distribution, parameter[name[Tij]]] variable[model] assign[=] call[name[HMM], parameter[name[pi], name[Tij], name[output_model]]] return[name[model]]
keyword[def] identifier[init_model_gaussian1d] ( identifier[observations] , identifier[nstates] , identifier[reversible] = keyword[True] ): literal[string] identifier[ntrajectories] = identifier[len] ( identifier[observations] ) identifier[collected_observations] = identifier[np] . identifier[array] ([], identifier[dtype] = identifier[config] . identifier[dtype] ) keyword[for] identifier[o_t] keyword[in] identifier[observations] : identifier[collected_observations] = identifier[np] . identifier[append] ( identifier[collected_observations] , identifier[o_t] ) keyword[from] identifier[bhmm] . identifier[_external] . identifier[sklearn] keyword[import] identifier[mixture] identifier[gmm] = identifier[mixture] . identifier[GMM] ( identifier[n_components] = identifier[nstates] ) identifier[gmm] . identifier[fit] ( identifier[collected_observations] [:, keyword[None] ]) keyword[from] identifier[bhmm] keyword[import] identifier[GaussianOutputModel] identifier[output_model] = identifier[GaussianOutputModel] ( identifier[nstates] , identifier[means] = identifier[gmm] . identifier[means_] [:, literal[int] ], identifier[sigmas] = identifier[np] . identifier[sqrt] ( identifier[gmm] . identifier[covars_] [:, literal[int] ])) identifier[logger] (). identifier[info] ( literal[string] + identifier[str] ( identifier[output_model] )) identifier[Pi] = identifier[np] . identifier[zeros] ([ identifier[nstates] ], identifier[np] . identifier[float64] ) identifier[Pi] [:]= identifier[gmm] . identifier[weights_] [:] identifier[logger] (). identifier[info] ( literal[string] % identifier[str] ( identifier[gmm] . identifier[weights_] )) identifier[Nij] = identifier[np] . identifier[zeros] ([ identifier[nstates] , identifier[nstates] ], identifier[np] . identifier[float64] ) keyword[for] identifier[o_t] keyword[in] identifier[observations] : identifier[T] = identifier[o_t] . identifier[shape] [ literal[int] ] identifier[pobs] = identifier[output_model] . identifier[p_obs] ( identifier[o_t] ) identifier[pobs] /= identifier[pobs] . identifier[sum] ( identifier[axis] = literal[int] )[:, keyword[None] ] keyword[for] identifier[t] keyword[in] identifier[range] ( identifier[T] - literal[int] ): identifier[Nij] [:,:]= identifier[Nij] [:,:]+ identifier[np] . identifier[outer] ( identifier[pobs] [ identifier[t] ,:], identifier[pobs] [ identifier[t] + literal[int] ,:]) identifier[logger] (). identifier[info] ( literal[string] + identifier[str] ( identifier[Nij] )) keyword[import] identifier[msmtools] . identifier[estimation] keyword[as] identifier[msmest] keyword[import] identifier[msmtools] . identifier[analysis] keyword[as] identifier[msmana] identifier[Tij] = identifier[msmest] . identifier[transition_matrix] ( identifier[Nij] , identifier[reversible] = identifier[reversible] ) identifier[pi] = identifier[msmana] . identifier[stationary_distribution] ( identifier[Tij] ) identifier[model] = identifier[HMM] ( identifier[pi] , identifier[Tij] , identifier[output_model] ) keyword[return] identifier[model]
def init_model_gaussian1d(observations, nstates, reversible=True): """Generate an initial model with 1D-Gaussian output densities Parameters ---------- observations : list of ndarray((T_i), dtype=float) list of arrays of length T_i with observation data nstates : int The number of states. Examples -------- Generate initial model for a gaussian output model. >>> from bhmm import testsystems >>> [model, observations, states] = testsystems.generate_synthetic_observations(output='gaussian') >>> initial_model = init_model_gaussian1d(observations, model.nstates) """ ntrajectories = len(observations) # Concatenate all observations. collected_observations = np.array([], dtype=config.dtype) for o_t in observations: collected_observations = np.append(collected_observations, o_t) # depends on [control=['for'], data=['o_t']] # Fit a Gaussian mixture model to obtain emission distributions and state stationary probabilities. from bhmm._external.sklearn import mixture gmm = mixture.GMM(n_components=nstates) gmm.fit(collected_observations[:, None]) from bhmm import GaussianOutputModel output_model = GaussianOutputModel(nstates, means=gmm.means_[:, 0], sigmas=np.sqrt(gmm.covars_[:, 0])) logger().info('Gaussian output model:\n' + str(output_model)) # Extract stationary distributions. Pi = np.zeros([nstates], np.float64) Pi[:] = gmm.weights_[:] logger().info('GMM weights: %s' % str(gmm.weights_)) # Compute fractional state memberships. Nij = np.zeros([nstates, nstates], np.float64) for o_t in observations: # length of trajectory T = o_t.shape[0] # output probability pobs = output_model.p_obs(o_t) # normalize pobs /= pobs.sum(axis=1)[:, None] # Accumulate fractional transition counts from this trajectory. for t in range(T - 1): Nij[:, :] = Nij[:, :] + np.outer(pobs[t, :], pobs[t + 1, :]) # depends on [control=['for'], data=['t']] logger().info('Nij\n' + str(Nij)) # depends on [control=['for'], data=['o_t']] # Compute transition matrix maximum likelihood estimate. import msmtools.estimation as msmest import msmtools.analysis as msmana Tij = msmest.transition_matrix(Nij, reversible=reversible) pi = msmana.stationary_distribution(Tij) # Update model. model = HMM(pi, Tij, output_model) return model
def _map_generator(f, generator): """Apply ``f`` to the results of the given bi-directional generator. Unfortunately, generator comprehension (``f(x) for x in gen``) does not work for as expected for bi-directional generators. It won't send exceptions and results back. This function implements a map function for generators that sends values and exceptions back and forth as expected. """ item = next(generator) while True: try: result = yield f(item) except Exception: item = generator.throw(*sys.exc_info()) else: item = generator.send(result)
def function[_map_generator, parameter[f, generator]]: constant[Apply ``f`` to the results of the given bi-directional generator. Unfortunately, generator comprehension (``f(x) for x in gen``) does not work for as expected for bi-directional generators. It won't send exceptions and results back. This function implements a map function for generators that sends values and exceptions back and forth as expected. ] variable[item] assign[=] call[name[next], parameter[name[generator]]] while constant[True] begin[:] <ast.Try object at 0x7da1b1397cd0>
keyword[def] identifier[_map_generator] ( identifier[f] , identifier[generator] ): literal[string] identifier[item] = identifier[next] ( identifier[generator] ) keyword[while] keyword[True] : keyword[try] : identifier[result] = keyword[yield] identifier[f] ( identifier[item] ) keyword[except] identifier[Exception] : identifier[item] = identifier[generator] . identifier[throw] (* identifier[sys] . identifier[exc_info] ()) keyword[else] : identifier[item] = identifier[generator] . identifier[send] ( identifier[result] )
def _map_generator(f, generator): """Apply ``f`` to the results of the given bi-directional generator. Unfortunately, generator comprehension (``f(x) for x in gen``) does not work for as expected for bi-directional generators. It won't send exceptions and results back. This function implements a map function for generators that sends values and exceptions back and forth as expected. """ item = next(generator) while True: try: result = (yield f(item)) # depends on [control=['try'], data=[]] except Exception: item = generator.throw(*sys.exc_info()) # depends on [control=['except'], data=[]] else: item = generator.send(result) # depends on [control=['while'], data=[]]
def showMenu(self, pos): """ Creates a new menu for this widget and displays it. :param pos | <QPoint> """ glbl_pos = self.viewport().mapToGlobal(pos) # lookup the specific item at the given position item = self.itemAt(pos) selected = self.selectedRecords() if not self._recordEditors: return if item and not isinstance(item, XOrbRecordItem): return menu = QMenu(self) acts = {} # modify a particular item if item: if self.editorFlags() & XOrbTreeWidget.EditorFlags.Edit: record = item.record() editor = self.recordEditor(type(record)) if editor: name = record.schema().displayName() act = menu.addAction('Edit {}...'.format(name)) act.setIcon(QIcon(resources.find('img/edit.png'))) acts[act] = (editor, 'edit', record) # add items if self.editorFlags() & XOrbTreeWidget.EditorFlags.Create: menu.addSeparator() typs = self._recordEditors.keys() typs.sort(key=lambda x: x.schema().displayName()) for typ in typs: name = typ.schema().displayName() act = menu.addAction('Add {}...'.format(name)) act.setIcon(QIcon(resources.find('img/add.png'))) acts[act] = (self._recordEditors[typ], 'create', None) # remove selected items if selected and self.editorFlags() & XOrbTreeWidget.EditorFlags.Remove: menu.addSeparator() act = menu.addAction('Remove Selected Records') act.setIcon(QIcon(resources.find('img/remove.png'))) acts[act] =(None, 'remove', selected) if not acts: return act = menu.exec_(glbl_pos) editor, action, record = acts.get(act, (None, None, None)) # create a new record if action == 'create': record = editor.create(autoCommit=False) if record: self.recordCreated.emit(record) record.commit() self.refresh() # edit an existing record elif action == 'edit': self.editRecord(record, glbl_pos) # remove selected records elif action == 'remove': title = 'Remove Records' msg = 'Are you sure you want to remove these records?' btns = QMessageBox.Yes | QMessageBox.No ans = QMessageBox.information(self.window(), title, msg, btns) if ans == QMessageBox.Yes: self.recordsRemoved.emit(selected) if RecordSet(selected).remove(): self.refresh()
def function[showMenu, parameter[self, pos]]: constant[ Creates a new menu for this widget and displays it. :param pos | <QPoint> ] variable[glbl_pos] assign[=] call[call[name[self].viewport, parameter[]].mapToGlobal, parameter[name[pos]]] variable[item] assign[=] call[name[self].itemAt, parameter[name[pos]]] variable[selected] assign[=] call[name[self].selectedRecords, parameter[]] if <ast.UnaryOp object at 0x7da1b2425bd0> begin[:] return[None] if <ast.BoolOp object at 0x7da1b2426500> begin[:] return[None] variable[menu] assign[=] call[name[QMenu], parameter[name[self]]] variable[acts] assign[=] dictionary[[], []] if name[item] begin[:] if binary_operation[call[name[self].editorFlags, parameter[]] <ast.BitAnd object at 0x7da2590d6b60> name[XOrbTreeWidget].EditorFlags.Edit] begin[:] variable[record] assign[=] call[name[item].record, parameter[]] variable[editor] assign[=] call[name[self].recordEditor, parameter[call[name[type], parameter[name[record]]]]] if name[editor] begin[:] variable[name] assign[=] call[call[name[record].schema, parameter[]].displayName, parameter[]] variable[act] assign[=] call[name[menu].addAction, parameter[call[constant[Edit {}...].format, parameter[name[name]]]]] call[name[act].setIcon, parameter[call[name[QIcon], parameter[call[name[resources].find, parameter[constant[img/edit.png]]]]]]] call[name[acts]][name[act]] assign[=] tuple[[<ast.Name object at 0x7da1b2427b20>, <ast.Constant object at 0x7da1b2425e10>, <ast.Name object at 0x7da1b2424d60>]] if binary_operation[call[name[self].editorFlags, parameter[]] <ast.BitAnd object at 0x7da2590d6b60> name[XOrbTreeWidget].EditorFlags.Create] begin[:] call[name[menu].addSeparator, parameter[]] variable[typs] assign[=] call[name[self]._recordEditors.keys, parameter[]] call[name[typs].sort, parameter[]] for taget[name[typ]] in starred[name[typs]] begin[:] variable[name] assign[=] call[call[name[typ].schema, parameter[]].displayName, parameter[]] variable[act] assign[=] call[name[menu].addAction, parameter[call[constant[Add {}...].format, parameter[name[name]]]]] call[name[act].setIcon, parameter[call[name[QIcon], parameter[call[name[resources].find, parameter[constant[img/add.png]]]]]]] call[name[acts]][name[act]] assign[=] tuple[[<ast.Subscript object at 0x7da1b24256f0>, <ast.Constant object at 0x7da1b2424e80>, <ast.Constant object at 0x7da1b2426ef0>]] if <ast.BoolOp object at 0x7da1b2425360> begin[:] call[name[menu].addSeparator, parameter[]] variable[act] assign[=] call[name[menu].addAction, parameter[constant[Remove Selected Records]]] call[name[act].setIcon, parameter[call[name[QIcon], parameter[call[name[resources].find, parameter[constant[img/remove.png]]]]]]] call[name[acts]][name[act]] assign[=] tuple[[<ast.Constant object at 0x7da1b24265f0>, <ast.Constant object at 0x7da1b2427250>, <ast.Name object at 0x7da1b2427d60>]] if <ast.UnaryOp object at 0x7da1b2426800> begin[:] return[None] variable[act] assign[=] call[name[menu].exec_, parameter[name[glbl_pos]]] <ast.Tuple object at 0x7da1b24262f0> assign[=] call[name[acts].get, parameter[name[act], tuple[[<ast.Constant object at 0x7da1b2427c10>, <ast.Constant object at 0x7da1b2427b80>, <ast.Constant object at 0x7da1b2425750>]]]] if compare[name[action] equal[==] constant[create]] begin[:] variable[record] assign[=] call[name[editor].create, parameter[]] if name[record] begin[:] call[name[self].recordCreated.emit, parameter[name[record]]] call[name[record].commit, parameter[]] call[name[self].refresh, parameter[]]
keyword[def] identifier[showMenu] ( identifier[self] , identifier[pos] ): literal[string] identifier[glbl_pos] = identifier[self] . identifier[viewport] (). identifier[mapToGlobal] ( identifier[pos] ) identifier[item] = identifier[self] . identifier[itemAt] ( identifier[pos] ) identifier[selected] = identifier[self] . identifier[selectedRecords] () keyword[if] keyword[not] identifier[self] . identifier[_recordEditors] : keyword[return] keyword[if] identifier[item] keyword[and] keyword[not] identifier[isinstance] ( identifier[item] , identifier[XOrbRecordItem] ): keyword[return] identifier[menu] = identifier[QMenu] ( identifier[self] ) identifier[acts] ={} keyword[if] identifier[item] : keyword[if] identifier[self] . identifier[editorFlags] ()& identifier[XOrbTreeWidget] . identifier[EditorFlags] . identifier[Edit] : identifier[record] = identifier[item] . identifier[record] () identifier[editor] = identifier[self] . identifier[recordEditor] ( identifier[type] ( identifier[record] )) keyword[if] identifier[editor] : identifier[name] = identifier[record] . identifier[schema] (). identifier[displayName] () identifier[act] = identifier[menu] . identifier[addAction] ( literal[string] . identifier[format] ( identifier[name] )) identifier[act] . identifier[setIcon] ( identifier[QIcon] ( identifier[resources] . identifier[find] ( literal[string] ))) identifier[acts] [ identifier[act] ]=( identifier[editor] , literal[string] , identifier[record] ) keyword[if] identifier[self] . identifier[editorFlags] ()& identifier[XOrbTreeWidget] . identifier[EditorFlags] . identifier[Create] : identifier[menu] . identifier[addSeparator] () identifier[typs] = identifier[self] . identifier[_recordEditors] . identifier[keys] () identifier[typs] . identifier[sort] ( identifier[key] = keyword[lambda] identifier[x] : identifier[x] . identifier[schema] (). identifier[displayName] ()) keyword[for] identifier[typ] keyword[in] identifier[typs] : identifier[name] = identifier[typ] . identifier[schema] (). identifier[displayName] () identifier[act] = identifier[menu] . identifier[addAction] ( literal[string] . identifier[format] ( identifier[name] )) identifier[act] . identifier[setIcon] ( identifier[QIcon] ( identifier[resources] . identifier[find] ( literal[string] ))) identifier[acts] [ identifier[act] ]=( identifier[self] . identifier[_recordEditors] [ identifier[typ] ], literal[string] , keyword[None] ) keyword[if] identifier[selected] keyword[and] identifier[self] . identifier[editorFlags] ()& identifier[XOrbTreeWidget] . identifier[EditorFlags] . identifier[Remove] : identifier[menu] . identifier[addSeparator] () identifier[act] = identifier[menu] . identifier[addAction] ( literal[string] ) identifier[act] . identifier[setIcon] ( identifier[QIcon] ( identifier[resources] . identifier[find] ( literal[string] ))) identifier[acts] [ identifier[act] ]=( keyword[None] , literal[string] , identifier[selected] ) keyword[if] keyword[not] identifier[acts] : keyword[return] identifier[act] = identifier[menu] . identifier[exec_] ( identifier[glbl_pos] ) identifier[editor] , identifier[action] , identifier[record] = identifier[acts] . identifier[get] ( identifier[act] ,( keyword[None] , keyword[None] , keyword[None] )) keyword[if] identifier[action] == literal[string] : identifier[record] = identifier[editor] . identifier[create] ( identifier[autoCommit] = keyword[False] ) keyword[if] identifier[record] : identifier[self] . identifier[recordCreated] . identifier[emit] ( identifier[record] ) identifier[record] . identifier[commit] () identifier[self] . identifier[refresh] () keyword[elif] identifier[action] == literal[string] : identifier[self] . identifier[editRecord] ( identifier[record] , identifier[glbl_pos] ) keyword[elif] identifier[action] == literal[string] : identifier[title] = literal[string] identifier[msg] = literal[string] identifier[btns] = identifier[QMessageBox] . identifier[Yes] | identifier[QMessageBox] . identifier[No] identifier[ans] = identifier[QMessageBox] . identifier[information] ( identifier[self] . identifier[window] (), identifier[title] , identifier[msg] , identifier[btns] ) keyword[if] identifier[ans] == identifier[QMessageBox] . identifier[Yes] : identifier[self] . identifier[recordsRemoved] . identifier[emit] ( identifier[selected] ) keyword[if] identifier[RecordSet] ( identifier[selected] ). identifier[remove] (): identifier[self] . identifier[refresh] ()
def showMenu(self, pos): """ Creates a new menu for this widget and displays it. :param pos | <QPoint> """ glbl_pos = self.viewport().mapToGlobal(pos) # lookup the specific item at the given position item = self.itemAt(pos) selected = self.selectedRecords() if not self._recordEditors: return # depends on [control=['if'], data=[]] if item and (not isinstance(item, XOrbRecordItem)): return # depends on [control=['if'], data=[]] menu = QMenu(self) acts = {} # modify a particular item if item: if self.editorFlags() & XOrbTreeWidget.EditorFlags.Edit: record = item.record() editor = self.recordEditor(type(record)) if editor: name = record.schema().displayName() act = menu.addAction('Edit {}...'.format(name)) act.setIcon(QIcon(resources.find('img/edit.png'))) acts[act] = (editor, 'edit', record) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # add items if self.editorFlags() & XOrbTreeWidget.EditorFlags.Create: menu.addSeparator() typs = self._recordEditors.keys() typs.sort(key=lambda x: x.schema().displayName()) for typ in typs: name = typ.schema().displayName() act = menu.addAction('Add {}...'.format(name)) act.setIcon(QIcon(resources.find('img/add.png'))) acts[act] = (self._recordEditors[typ], 'create', None) # depends on [control=['for'], data=['typ']] # depends on [control=['if'], data=[]] # remove selected items if selected and self.editorFlags() & XOrbTreeWidget.EditorFlags.Remove: menu.addSeparator() act = menu.addAction('Remove Selected Records') act.setIcon(QIcon(resources.find('img/remove.png'))) acts[act] = (None, 'remove', selected) # depends on [control=['if'], data=[]] if not acts: return # depends on [control=['if'], data=[]] act = menu.exec_(glbl_pos) (editor, action, record) = acts.get(act, (None, None, None)) # create a new record if action == 'create': record = editor.create(autoCommit=False) if record: self.recordCreated.emit(record) record.commit() self.refresh() # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # edit an existing record elif action == 'edit': self.editRecord(record, glbl_pos) # depends on [control=['if'], data=[]] # remove selected records elif action == 'remove': title = 'Remove Records' msg = 'Are you sure you want to remove these records?' btns = QMessageBox.Yes | QMessageBox.No ans = QMessageBox.information(self.window(), title, msg, btns) if ans == QMessageBox.Yes: self.recordsRemoved.emit(selected) if RecordSet(selected).remove(): self.refresh() # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]]
def which(self, cmd, parent_environ=None, fallback=False): """Find a program in the resolved environment. Args: cmd: String name of the program to find. parent_environ: Environment to interpret the context within, defaults to os.environ if None. fallback: If True, and the program is not found in the context, the current environment will then be searched. Returns: Path to the program, or None if the program was not found. """ env = self.get_environ(parent_environ=parent_environ) path = which(cmd, env=env) if fallback and path is None: path = which(cmd) return path
def function[which, parameter[self, cmd, parent_environ, fallback]]: constant[Find a program in the resolved environment. Args: cmd: String name of the program to find. parent_environ: Environment to interpret the context within, defaults to os.environ if None. fallback: If True, and the program is not found in the context, the current environment will then be searched. Returns: Path to the program, or None if the program was not found. ] variable[env] assign[=] call[name[self].get_environ, parameter[]] variable[path] assign[=] call[name[which], parameter[name[cmd]]] if <ast.BoolOp object at 0x7da1b175eb00> begin[:] variable[path] assign[=] call[name[which], parameter[name[cmd]]] return[name[path]]
keyword[def] identifier[which] ( identifier[self] , identifier[cmd] , identifier[parent_environ] = keyword[None] , identifier[fallback] = keyword[False] ): literal[string] identifier[env] = identifier[self] . identifier[get_environ] ( identifier[parent_environ] = identifier[parent_environ] ) identifier[path] = identifier[which] ( identifier[cmd] , identifier[env] = identifier[env] ) keyword[if] identifier[fallback] keyword[and] identifier[path] keyword[is] keyword[None] : identifier[path] = identifier[which] ( identifier[cmd] ) keyword[return] identifier[path]
def which(self, cmd, parent_environ=None, fallback=False): """Find a program in the resolved environment. Args: cmd: String name of the program to find. parent_environ: Environment to interpret the context within, defaults to os.environ if None. fallback: If True, and the program is not found in the context, the current environment will then be searched. Returns: Path to the program, or None if the program was not found. """ env = self.get_environ(parent_environ=parent_environ) path = which(cmd, env=env) if fallback and path is None: path = which(cmd) # depends on [control=['if'], data=[]] return path
def set_parent_commit(self, commit, check=True): """Set this instance to use the given commit whose tree is supposed to contain the .gitmodules blob. :param commit: Commit'ish reference pointing at the root_tree, or None to always point to the most recent commit :param check: if True, relatively expensive checks will be performed to verify validity of the submodule. :raise ValueError: if the commit's tree didn't contain the .gitmodules blob. :raise ValueError: if the parent commit didn't store this submodule under the current path :return: self""" if commit is None: self._parent_commit = None return self # end handle None pcommit = self.repo.commit(commit) pctree = pcommit.tree if self.k_modules_file not in pctree: raise ValueError("Tree of commit %s did not contain the %s file" % (commit, self.k_modules_file)) # END handle exceptions prev_pc = self._parent_commit self._parent_commit = pcommit if check: parser = self._config_parser(self.repo, self._parent_commit, read_only=True) if not parser.has_section(sm_section(self.name)): self._parent_commit = prev_pc raise ValueError("Submodule at path %r did not exist in parent commit %s" % (self.path, commit)) # END handle submodule did not exist # END handle checking mode # update our sha, it could have changed # If check is False, we might see a parent-commit that doesn't even contain the submodule anymore. # in that case, mark our sha as being NULL try: self.binsha = pctree[self.path].binsha except KeyError: self.binsha = self.NULL_BIN_SHA # end self._clear_cache() return self
def function[set_parent_commit, parameter[self, commit, check]]: constant[Set this instance to use the given commit whose tree is supposed to contain the .gitmodules blob. :param commit: Commit'ish reference pointing at the root_tree, or None to always point to the most recent commit :param check: if True, relatively expensive checks will be performed to verify validity of the submodule. :raise ValueError: if the commit's tree didn't contain the .gitmodules blob. :raise ValueError: if the parent commit didn't store this submodule under the current path :return: self] if compare[name[commit] is constant[None]] begin[:] name[self]._parent_commit assign[=] constant[None] return[name[self]] variable[pcommit] assign[=] call[name[self].repo.commit, parameter[name[commit]]] variable[pctree] assign[=] name[pcommit].tree if compare[name[self].k_modules_file <ast.NotIn object at 0x7da2590d7190> name[pctree]] begin[:] <ast.Raise object at 0x7da2043457b0> variable[prev_pc] assign[=] name[self]._parent_commit name[self]._parent_commit assign[=] name[pcommit] if name[check] begin[:] variable[parser] assign[=] call[name[self]._config_parser, parameter[name[self].repo, name[self]._parent_commit]] if <ast.UnaryOp object at 0x7da204345390> begin[:] name[self]._parent_commit assign[=] name[prev_pc] <ast.Raise object at 0x7da204346380> <ast.Try object at 0x7da204347340> call[name[self]._clear_cache, parameter[]] return[name[self]]
keyword[def] identifier[set_parent_commit] ( identifier[self] , identifier[commit] , identifier[check] = keyword[True] ): literal[string] keyword[if] identifier[commit] keyword[is] keyword[None] : identifier[self] . identifier[_parent_commit] = keyword[None] keyword[return] identifier[self] identifier[pcommit] = identifier[self] . identifier[repo] . identifier[commit] ( identifier[commit] ) identifier[pctree] = identifier[pcommit] . identifier[tree] keyword[if] identifier[self] . identifier[k_modules_file] keyword[not] keyword[in] identifier[pctree] : keyword[raise] identifier[ValueError] ( literal[string] %( identifier[commit] , identifier[self] . identifier[k_modules_file] )) identifier[prev_pc] = identifier[self] . identifier[_parent_commit] identifier[self] . identifier[_parent_commit] = identifier[pcommit] keyword[if] identifier[check] : identifier[parser] = identifier[self] . identifier[_config_parser] ( identifier[self] . identifier[repo] , identifier[self] . identifier[_parent_commit] , identifier[read_only] = keyword[True] ) keyword[if] keyword[not] identifier[parser] . identifier[has_section] ( identifier[sm_section] ( identifier[self] . identifier[name] )): identifier[self] . identifier[_parent_commit] = identifier[prev_pc] keyword[raise] identifier[ValueError] ( literal[string] %( identifier[self] . identifier[path] , identifier[commit] )) keyword[try] : identifier[self] . identifier[binsha] = identifier[pctree] [ identifier[self] . identifier[path] ]. identifier[binsha] keyword[except] identifier[KeyError] : identifier[self] . identifier[binsha] = identifier[self] . identifier[NULL_BIN_SHA] identifier[self] . identifier[_clear_cache] () keyword[return] identifier[self]
def set_parent_commit(self, commit, check=True): """Set this instance to use the given commit whose tree is supposed to contain the .gitmodules blob. :param commit: Commit'ish reference pointing at the root_tree, or None to always point to the most recent commit :param check: if True, relatively expensive checks will be performed to verify validity of the submodule. :raise ValueError: if the commit's tree didn't contain the .gitmodules blob. :raise ValueError: if the parent commit didn't store this submodule under the current path :return: self""" if commit is None: self._parent_commit = None return self # depends on [control=['if'], data=[]] # end handle None pcommit = self.repo.commit(commit) pctree = pcommit.tree if self.k_modules_file not in pctree: raise ValueError('Tree of commit %s did not contain the %s file' % (commit, self.k_modules_file)) # depends on [control=['if'], data=[]] # END handle exceptions prev_pc = self._parent_commit self._parent_commit = pcommit if check: parser = self._config_parser(self.repo, self._parent_commit, read_only=True) if not parser.has_section(sm_section(self.name)): self._parent_commit = prev_pc raise ValueError('Submodule at path %r did not exist in parent commit %s' % (self.path, commit)) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # END handle submodule did not exist # END handle checking mode # update our sha, it could have changed # If check is False, we might see a parent-commit that doesn't even contain the submodule anymore. # in that case, mark our sha as being NULL try: self.binsha = pctree[self.path].binsha # depends on [control=['try'], data=[]] except KeyError: self.binsha = self.NULL_BIN_SHA # depends on [control=['except'], data=[]] # end self._clear_cache() return self
def replace_name_with_id(cls, name): """ Used to replace a foreign key reference using a name with an ID. Works by searching the record in Pulsar and expects to find exactly one hit. First, will check if the foreign key reference is an integer value and if so, returns that as it is presumed to be the foreign key. Raises: `pulsarpy.elasticsearch_utils.MultipleHitsException`: Multiple hits were returned from the name search. `pulsarpy.models.RecordNotFound`: No results were produced from the name search. """ try: int(name) return name #Already a presumed ID. except ValueError: pass #Not an int, so maybe a combination of MODEL_ABBR and Primary Key, i.e. B-8. if name.split("-")[0] in Meta._MODEL_ABBREVS: return int(name.split("-", 1)[1]) try: result = cls.ES.get_record_by_name(cls.ES_INDEX_NAME, name) if result: return result["id"] except pulsarpy.elasticsearch_utils.MultipleHitsException as e: raise raise RecordNotFound("Name '{}' for model '{}' not found.".format(name, cls.__name__))
def function[replace_name_with_id, parameter[cls, name]]: constant[ Used to replace a foreign key reference using a name with an ID. Works by searching the record in Pulsar and expects to find exactly one hit. First, will check if the foreign key reference is an integer value and if so, returns that as it is presumed to be the foreign key. Raises: `pulsarpy.elasticsearch_utils.MultipleHitsException`: Multiple hits were returned from the name search. `pulsarpy.models.RecordNotFound`: No results were produced from the name search. ] <ast.Try object at 0x7da1b10d46d0> if compare[call[call[name[name].split, parameter[constant[-]]]][constant[0]] in name[Meta]._MODEL_ABBREVS] begin[:] return[call[name[int], parameter[call[call[name[name].split, parameter[constant[-], constant[1]]]][constant[1]]]]] <ast.Try object at 0x7da1b10d4a60> <ast.Raise object at 0x7da1b10d5660>
keyword[def] identifier[replace_name_with_id] ( identifier[cls] , identifier[name] ): literal[string] keyword[try] : identifier[int] ( identifier[name] ) keyword[return] identifier[name] keyword[except] identifier[ValueError] : keyword[pass] keyword[if] identifier[name] . identifier[split] ( literal[string] )[ literal[int] ] keyword[in] identifier[Meta] . identifier[_MODEL_ABBREVS] : keyword[return] identifier[int] ( identifier[name] . identifier[split] ( literal[string] , literal[int] )[ literal[int] ]) keyword[try] : identifier[result] = identifier[cls] . identifier[ES] . identifier[get_record_by_name] ( identifier[cls] . identifier[ES_INDEX_NAME] , identifier[name] ) keyword[if] identifier[result] : keyword[return] identifier[result] [ literal[string] ] keyword[except] identifier[pulsarpy] . identifier[elasticsearch_utils] . identifier[MultipleHitsException] keyword[as] identifier[e] : keyword[raise] keyword[raise] identifier[RecordNotFound] ( literal[string] . identifier[format] ( identifier[name] , identifier[cls] . identifier[__name__] ))
def replace_name_with_id(cls, name): """ Used to replace a foreign key reference using a name with an ID. Works by searching the record in Pulsar and expects to find exactly one hit. First, will check if the foreign key reference is an integer value and if so, returns that as it is presumed to be the foreign key. Raises: `pulsarpy.elasticsearch_utils.MultipleHitsException`: Multiple hits were returned from the name search. `pulsarpy.models.RecordNotFound`: No results were produced from the name search. """ try: int(name) return name #Already a presumed ID. # depends on [control=['try'], data=[]] except ValueError: pass # depends on [control=['except'], data=[]] #Not an int, so maybe a combination of MODEL_ABBR and Primary Key, i.e. B-8. if name.split('-')[0] in Meta._MODEL_ABBREVS: return int(name.split('-', 1)[1]) # depends on [control=['if'], data=[]] try: result = cls.ES.get_record_by_name(cls.ES_INDEX_NAME, name) if result: return result['id'] # depends on [control=['if'], data=[]] # depends on [control=['try'], data=[]] except pulsarpy.elasticsearch_utils.MultipleHitsException as e: raise # depends on [control=['except'], data=[]] raise RecordNotFound("Name '{}' for model '{}' not found.".format(name, cls.__name__))
def get_object_params(self): """Returns all of the parameters which should be used to create/update an object. * Omits any parameters not defined in the schema * Omits any null parameters if they were not explicitly specified """ return {name: value for (name, value) in six.iteritems(self.params) if (name not in self.additional_argument_spec and name not in self.login_argument_spec and (value is not None or name in self.specified_params))}
def function[get_object_params, parameter[self]]: constant[Returns all of the parameters which should be used to create/update an object. * Omits any parameters not defined in the schema * Omits any null parameters if they were not explicitly specified ] return[<ast.DictComp object at 0x7da1b235bac0>]
keyword[def] identifier[get_object_params] ( identifier[self] ): literal[string] keyword[return] { identifier[name] : identifier[value] keyword[for] ( identifier[name] , identifier[value] ) keyword[in] identifier[six] . identifier[iteritems] ( identifier[self] . identifier[params] ) keyword[if] ( identifier[name] keyword[not] keyword[in] identifier[self] . identifier[additional_argument_spec] keyword[and] identifier[name] keyword[not] keyword[in] identifier[self] . identifier[login_argument_spec] keyword[and] ( identifier[value] keyword[is] keyword[not] keyword[None] keyword[or] identifier[name] keyword[in] identifier[self] . identifier[specified_params] ))}
def get_object_params(self): """Returns all of the parameters which should be used to create/update an object. * Omits any parameters not defined in the schema * Omits any null parameters if they were not explicitly specified """ return {name: value for (name, value) in six.iteritems(self.params) if name not in self.additional_argument_spec and name not in self.login_argument_spec and (value is not None or name in self.specified_params)}
def build_rgb_and_opacity(s): """ Given a KML color string, return an equivalent RGB hex color string and an opacity float rounded to 2 decimal places. EXAMPLE:: >>> build_rgb_and_opacity('ee001122') ('#221100', 0.93) """ # Set defaults color = '000000' opacity = 1 if s.startswith('#'): s = s[1:] if len(s) == 8: color = s[6:8] + s[4:6] + s[2:4] opacity = round(int(s[0:2], 16)/256, 2) elif len(s) == 6: color = s[4:6] + s[2:4] + s[0:2] elif len(s) == 3: color = s[::-1] return '#' + color, opacity
def function[build_rgb_and_opacity, parameter[s]]: constant[ Given a KML color string, return an equivalent RGB hex color string and an opacity float rounded to 2 decimal places. EXAMPLE:: >>> build_rgb_and_opacity('ee001122') ('#221100', 0.93) ] variable[color] assign[=] constant[000000] variable[opacity] assign[=] constant[1] if call[name[s].startswith, parameter[constant[#]]] begin[:] variable[s] assign[=] call[name[s]][<ast.Slice object at 0x7da18bccb7c0>] if compare[call[name[len], parameter[name[s]]] equal[==] constant[8]] begin[:] variable[color] assign[=] binary_operation[binary_operation[call[name[s]][<ast.Slice object at 0x7da18bcc8e20>] + call[name[s]][<ast.Slice object at 0x7da18bcca710>]] + call[name[s]][<ast.Slice object at 0x7da18bcc9690>]] variable[opacity] assign[=] call[name[round], parameter[binary_operation[call[name[int], parameter[call[name[s]][<ast.Slice object at 0x7da18bcca1d0>], constant[16]]] / constant[256]], constant[2]]] return[tuple[[<ast.BinOp object at 0x7da18bcca350>, <ast.Name object at 0x7da18bccb5e0>]]]
keyword[def] identifier[build_rgb_and_opacity] ( identifier[s] ): literal[string] identifier[color] = literal[string] identifier[opacity] = literal[int] keyword[if] identifier[s] . identifier[startswith] ( literal[string] ): identifier[s] = identifier[s] [ literal[int] :] keyword[if] identifier[len] ( identifier[s] )== literal[int] : identifier[color] = identifier[s] [ literal[int] : literal[int] ]+ identifier[s] [ literal[int] : literal[int] ]+ identifier[s] [ literal[int] : literal[int] ] identifier[opacity] = identifier[round] ( identifier[int] ( identifier[s] [ literal[int] : literal[int] ], literal[int] )/ literal[int] , literal[int] ) keyword[elif] identifier[len] ( identifier[s] )== literal[int] : identifier[color] = identifier[s] [ literal[int] : literal[int] ]+ identifier[s] [ literal[int] : literal[int] ]+ identifier[s] [ literal[int] : literal[int] ] keyword[elif] identifier[len] ( identifier[s] )== literal[int] : identifier[color] = identifier[s] [::- literal[int] ] keyword[return] literal[string] + identifier[color] , identifier[opacity]
def build_rgb_and_opacity(s): """ Given a KML color string, return an equivalent RGB hex color string and an opacity float rounded to 2 decimal places. EXAMPLE:: >>> build_rgb_and_opacity('ee001122') ('#221100', 0.93) """ # Set defaults color = '000000' opacity = 1 if s.startswith('#'): s = s[1:] # depends on [control=['if'], data=[]] if len(s) == 8: color = s[6:8] + s[4:6] + s[2:4] opacity = round(int(s[0:2], 16) / 256, 2) # depends on [control=['if'], data=[]] elif len(s) == 6: color = s[4:6] + s[2:4] + s[0:2] # depends on [control=['if'], data=[]] elif len(s) == 3: color = s[::-1] # depends on [control=['if'], data=[]] return ('#' + color, opacity)
def createFromFile(self, sid, filename): """ Create a new named (sid) Seed from a file containing URLs It's assumed URLs are whitespace seperated. :param sid: the name to assign to the new seed list :param filename: the name of the file that contains URLs :return: the created Seed object """ urls = [] with open(filename) as f: for line in f: for url in line.split(): urls.append(url) return self.create(sid, tuple(urls))
def function[createFromFile, parameter[self, sid, filename]]: constant[ Create a new named (sid) Seed from a file containing URLs It's assumed URLs are whitespace seperated. :param sid: the name to assign to the new seed list :param filename: the name of the file that contains URLs :return: the created Seed object ] variable[urls] assign[=] list[[]] with call[name[open], parameter[name[filename]]] begin[:] for taget[name[line]] in starred[name[f]] begin[:] for taget[name[url]] in starred[call[name[line].split, parameter[]]] begin[:] call[name[urls].append, parameter[name[url]]] return[call[name[self].create, parameter[name[sid], call[name[tuple], parameter[name[urls]]]]]]
keyword[def] identifier[createFromFile] ( identifier[self] , identifier[sid] , identifier[filename] ): literal[string] identifier[urls] =[] keyword[with] identifier[open] ( identifier[filename] ) keyword[as] identifier[f] : keyword[for] identifier[line] keyword[in] identifier[f] : keyword[for] identifier[url] keyword[in] identifier[line] . identifier[split] (): identifier[urls] . identifier[append] ( identifier[url] ) keyword[return] identifier[self] . identifier[create] ( identifier[sid] , identifier[tuple] ( identifier[urls] ))
def createFromFile(self, sid, filename): """ Create a new named (sid) Seed from a file containing URLs It's assumed URLs are whitespace seperated. :param sid: the name to assign to the new seed list :param filename: the name of the file that contains URLs :return: the created Seed object """ urls = [] with open(filename) as f: for line in f: for url in line.split(): urls.append(url) # depends on [control=['for'], data=['url']] # depends on [control=['for'], data=['line']] # depends on [control=['with'], data=['f']] return self.create(sid, tuple(urls))
def get_job(job_id): """Gets a job.""" job = current_app.apscheduler.get_job(job_id) if not job: return jsonify(dict(error_message='Job %s not found' % job_id), status=404) return jsonify(job)
def function[get_job, parameter[job_id]]: constant[Gets a job.] variable[job] assign[=] call[name[current_app].apscheduler.get_job, parameter[name[job_id]]] if <ast.UnaryOp object at 0x7da18f58c370> begin[:] return[call[name[jsonify], parameter[call[name[dict], parameter[]]]]] return[call[name[jsonify], parameter[name[job]]]]
keyword[def] identifier[get_job] ( identifier[job_id] ): literal[string] identifier[job] = identifier[current_app] . identifier[apscheduler] . identifier[get_job] ( identifier[job_id] ) keyword[if] keyword[not] identifier[job] : keyword[return] identifier[jsonify] ( identifier[dict] ( identifier[error_message] = literal[string] % identifier[job_id] ), identifier[status] = literal[int] ) keyword[return] identifier[jsonify] ( identifier[job] )
def get_job(job_id): """Gets a job.""" job = current_app.apscheduler.get_job(job_id) if not job: return jsonify(dict(error_message='Job %s not found' % job_id), status=404) # depends on [control=['if'], data=[]] return jsonify(job)
def start_redis(node_ip_address, redirect_files, port=None, redis_shard_ports=None, num_redis_shards=1, redis_max_clients=None, redirect_worker_output=False, password=None, use_credis=None, redis_max_memory=None, include_java=False): """Start the Redis global state store. Args: node_ip_address: The IP address of the current node. This is only used for recording the log filenames in Redis. redirect_files: The list of (stdout, stderr) file pairs. port (int): If provided, the primary Redis shard will be started on this port. redis_shard_ports: A list of the ports to use for the non-primary Redis shards. num_redis_shards (int): If provided, the number of Redis shards to start, in addition to the primary one. The default value is one shard. redis_max_clients: If this is provided, Ray will attempt to configure Redis with this maxclients number. redirect_worker_output (bool): True if worker output should be redirected to a file and false otherwise. Workers will have access to this value when they start up. password (str): Prevents external clients without the password from connecting to Redis if provided. use_credis: If True, additionally load the chain-replicated libraries into the redis servers. Defaults to None, which means its value is set by the presence of "RAY_USE_NEW_GCS" in os.environ. redis_max_memory: The max amount of memory (in bytes) to allow each redis shard to use. Once the limit is exceeded, redis will start LRU eviction of entries. This only applies to the sharded redis tables (task, object, and profile tables). By default, this is capped at 10GB but can be set higher. include_java (bool): If True, the raylet backend can also support Java worker. Returns: A tuple of the address for the primary Redis shard, a list of addresses for the remaining shards, and the processes that were started. """ if len(redirect_files) != 1 + num_redis_shards: raise ValueError("The number of redirect file pairs should be equal " "to the number of redis shards (including the " "primary shard) we will start.") if redis_shard_ports is None: redis_shard_ports = num_redis_shards * [None] elif len(redis_shard_ports) != num_redis_shards: raise Exception("The number of Redis shard ports does not match the " "number of Redis shards.") processes = [] if use_credis is None: use_credis = ("RAY_USE_NEW_GCS" in os.environ) if use_credis: if password is not None: # TODO(pschafhalter) remove this once credis supports # authenticating Redis ports raise Exception("Setting the `redis_password` argument is not " "supported in credis. To run Ray with " "password-protected Redis ports, ensure that " "the environment variable `RAY_USE_NEW_GCS=off`.") assert num_redis_shards == 1, ( "For now, RAY_USE_NEW_GCS supports 1 shard, and credis " "supports 1-node chain for that shard only.") if use_credis: redis_executable = CREDIS_EXECUTABLE # TODO(suquark): We need credis here because some symbols need to be # imported from credis dynamically through dlopen when Ray is built # with RAY_USE_NEW_GCS=on. We should remove them later for the primary # shard. # See src/ray/gcs/redis_module/ray_redis_module.cc redis_modules = [CREDIS_MASTER_MODULE, REDIS_MODULE] else: redis_executable = REDIS_EXECUTABLE redis_modules = [REDIS_MODULE] redis_stdout_file, redis_stderr_file = redirect_files[0] # Start the primary Redis shard. port, p = _start_redis_instance( redis_executable, modules=redis_modules, port=port, password=password, redis_max_clients=redis_max_clients, # Below we use None to indicate no limit on the memory of the # primary Redis shard. redis_max_memory=None, stdout_file=redis_stdout_file, stderr_file=redis_stderr_file) processes.append(p) redis_address = address(node_ip_address, port) # Register the number of Redis shards in the primary shard, so that clients # know how many redis shards to expect under RedisShards. primary_redis_client = redis.StrictRedis( host=node_ip_address, port=port, password=password) primary_redis_client.set("NumRedisShards", str(num_redis_shards)) # Put the redirect_worker_output bool in the Redis shard so that workers # can access it and know whether or not to redirect their output. primary_redis_client.set("RedirectOutput", 1 if redirect_worker_output else 0) # put the include_java bool to primary redis-server, so that other nodes # can access it and know whether or not to enable cross-languages. primary_redis_client.set("INCLUDE_JAVA", 1 if include_java else 0) # Store version information in the primary Redis shard. _put_version_info_in_redis(primary_redis_client) # Calculate the redis memory. system_memory = ray.utils.get_system_memory() if redis_max_memory is None: redis_max_memory = min( ray_constants.DEFAULT_REDIS_MAX_MEMORY_BYTES, max( int(system_memory * 0.2), ray_constants.REDIS_MINIMUM_MEMORY_BYTES)) if redis_max_memory < ray_constants.REDIS_MINIMUM_MEMORY_BYTES: raise ValueError("Attempting to cap Redis memory usage at {} bytes, " "but the minimum allowed is {} bytes.".format( redis_max_memory, ray_constants.REDIS_MINIMUM_MEMORY_BYTES)) # Start other Redis shards. Each Redis shard logs to a separate file, # prefixed by "redis-<shard number>". redis_shards = [] for i in range(num_redis_shards): redis_stdout_file, redis_stderr_file = redirect_files[i + 1] if use_credis: redis_executable = CREDIS_EXECUTABLE # It is important to load the credis module BEFORE the ray module, # as the latter contains an extern declaration that the former # supplies. redis_modules = [CREDIS_MEMBER_MODULE, REDIS_MODULE] else: redis_executable = REDIS_EXECUTABLE redis_modules = [REDIS_MODULE] redis_shard_port, p = _start_redis_instance( redis_executable, modules=redis_modules, port=redis_shard_ports[i], password=password, redis_max_clients=redis_max_clients, redis_max_memory=redis_max_memory, stdout_file=redis_stdout_file, stderr_file=redis_stderr_file) processes.append(p) shard_address = address(node_ip_address, redis_shard_port) redis_shards.append(shard_address) # Store redis shard information in the primary redis shard. primary_redis_client.rpush("RedisShards", shard_address) if use_credis: # Configure the chain state. The way it is intended to work is # the following: # # PRIMARY_SHARD # # SHARD_1 (master replica) -> SHARD_1 (member replica) # -> SHARD_1 (member replica) # # SHARD_2 (master replica) -> SHARD_2 (member replica) # -> SHARD_2 (member replica) # ... # # # If we have credis members in future, their modules should be: # [CREDIS_MEMBER_MODULE, REDIS_MODULE], and they will be initialized by # execute_command("MEMBER.CONNECT_TO_MASTER", node_ip_address, port) # # Currently we have num_redis_shards == 1, so only one chain will be # created, and the chain only contains master. # TODO(suquark): Currently, this is not correct because we are # using the master replica as the primary shard. This should be # fixed later. I had tried to fix it but failed because of heartbeat # issues. primary_client = redis.StrictRedis( host=node_ip_address, port=port, password=password) shard_client = redis.StrictRedis( host=node_ip_address, port=redis_shard_port, password=password) primary_client.execute_command("MASTER.ADD", node_ip_address, redis_shard_port) shard_client.execute_command("MEMBER.CONNECT_TO_MASTER", node_ip_address, port) return redis_address, redis_shards, processes
def function[start_redis, parameter[node_ip_address, redirect_files, port, redis_shard_ports, num_redis_shards, redis_max_clients, redirect_worker_output, password, use_credis, redis_max_memory, include_java]]: constant[Start the Redis global state store. Args: node_ip_address: The IP address of the current node. This is only used for recording the log filenames in Redis. redirect_files: The list of (stdout, stderr) file pairs. port (int): If provided, the primary Redis shard will be started on this port. redis_shard_ports: A list of the ports to use for the non-primary Redis shards. num_redis_shards (int): If provided, the number of Redis shards to start, in addition to the primary one. The default value is one shard. redis_max_clients: If this is provided, Ray will attempt to configure Redis with this maxclients number. redirect_worker_output (bool): True if worker output should be redirected to a file and false otherwise. Workers will have access to this value when they start up. password (str): Prevents external clients without the password from connecting to Redis if provided. use_credis: If True, additionally load the chain-replicated libraries into the redis servers. Defaults to None, which means its value is set by the presence of "RAY_USE_NEW_GCS" in os.environ. redis_max_memory: The max amount of memory (in bytes) to allow each redis shard to use. Once the limit is exceeded, redis will start LRU eviction of entries. This only applies to the sharded redis tables (task, object, and profile tables). By default, this is capped at 10GB but can be set higher. include_java (bool): If True, the raylet backend can also support Java worker. Returns: A tuple of the address for the primary Redis shard, a list of addresses for the remaining shards, and the processes that were started. ] if compare[call[name[len], parameter[name[redirect_files]]] not_equal[!=] binary_operation[constant[1] + name[num_redis_shards]]] begin[:] <ast.Raise object at 0x7da2044c0f40> if compare[name[redis_shard_ports] is constant[None]] begin[:] variable[redis_shard_ports] assign[=] binary_operation[name[num_redis_shards] * list[[<ast.Constant object at 0x7da2044c3b20>]]] variable[processes] assign[=] list[[]] if compare[name[use_credis] is constant[None]] begin[:] variable[use_credis] assign[=] compare[constant[RAY_USE_NEW_GCS] in name[os].environ] if name[use_credis] begin[:] if compare[name[password] is_not constant[None]] begin[:] <ast.Raise object at 0x7da2044c29b0> assert[compare[name[num_redis_shards] equal[==] constant[1]]] if name[use_credis] begin[:] variable[redis_executable] assign[=] name[CREDIS_EXECUTABLE] variable[redis_modules] assign[=] list[[<ast.Name object at 0x7da2044c0e20>, <ast.Name object at 0x7da2044c2fb0>]] <ast.Tuple object at 0x7da2044c0100> assign[=] call[name[redirect_files]][constant[0]] <ast.Tuple object at 0x7da2044c3070> assign[=] call[name[_start_redis_instance], parameter[name[redis_executable]]] call[name[processes].append, parameter[name[p]]] variable[redis_address] assign[=] call[name[address], parameter[name[node_ip_address], name[port]]] variable[primary_redis_client] assign[=] call[name[redis].StrictRedis, parameter[]] call[name[primary_redis_client].set, parameter[constant[NumRedisShards], call[name[str], parameter[name[num_redis_shards]]]]] call[name[primary_redis_client].set, parameter[constant[RedirectOutput], <ast.IfExp object at 0x7da2044c1330>]] call[name[primary_redis_client].set, parameter[constant[INCLUDE_JAVA], <ast.IfExp object at 0x7da2044c1600>]] call[name[_put_version_info_in_redis], parameter[name[primary_redis_client]]] variable[system_memory] assign[=] call[name[ray].utils.get_system_memory, parameter[]] if compare[name[redis_max_memory] is constant[None]] begin[:] variable[redis_max_memory] assign[=] call[name[min], parameter[name[ray_constants].DEFAULT_REDIS_MAX_MEMORY_BYTES, call[name[max], parameter[call[name[int], parameter[binary_operation[name[system_memory] * constant[0.2]]]], name[ray_constants].REDIS_MINIMUM_MEMORY_BYTES]]]] if compare[name[redis_max_memory] less[<] name[ray_constants].REDIS_MINIMUM_MEMORY_BYTES] begin[:] <ast.Raise object at 0x7da2044c1b70> variable[redis_shards] assign[=] list[[]] for taget[name[i]] in starred[call[name[range], parameter[name[num_redis_shards]]]] begin[:] <ast.Tuple object at 0x7da2044c1c00> assign[=] call[name[redirect_files]][binary_operation[name[i] + constant[1]]] if name[use_credis] begin[:] variable[redis_executable] assign[=] name[CREDIS_EXECUTABLE] variable[redis_modules] assign[=] list[[<ast.Name object at 0x7da2044c23e0>, <ast.Name object at 0x7da2044c17b0>]] <ast.Tuple object at 0x7da2044c0c70> assign[=] call[name[_start_redis_instance], parameter[name[redis_executable]]] call[name[processes].append, parameter[name[p]]] variable[shard_address] assign[=] call[name[address], parameter[name[node_ip_address], name[redis_shard_port]]] call[name[redis_shards].append, parameter[name[shard_address]]] call[name[primary_redis_client].rpush, parameter[constant[RedisShards], name[shard_address]]] if name[use_credis] begin[:] variable[primary_client] assign[=] call[name[redis].StrictRedis, parameter[]] variable[shard_client] assign[=] call[name[redis].StrictRedis, parameter[]] call[name[primary_client].execute_command, parameter[constant[MASTER.ADD], name[node_ip_address], name[redis_shard_port]]] call[name[shard_client].execute_command, parameter[constant[MEMBER.CONNECT_TO_MASTER], name[node_ip_address], name[port]]] return[tuple[[<ast.Name object at 0x7da18f00f670>, <ast.Name object at 0x7da18f00fe50>, <ast.Name object at 0x7da18f00e440>]]]
keyword[def] identifier[start_redis] ( identifier[node_ip_address] , identifier[redirect_files] , identifier[port] = keyword[None] , identifier[redis_shard_ports] = keyword[None] , identifier[num_redis_shards] = literal[int] , identifier[redis_max_clients] = keyword[None] , identifier[redirect_worker_output] = keyword[False] , identifier[password] = keyword[None] , identifier[use_credis] = keyword[None] , identifier[redis_max_memory] = keyword[None] , identifier[include_java] = keyword[False] ): literal[string] keyword[if] identifier[len] ( identifier[redirect_files] )!= literal[int] + identifier[num_redis_shards] : keyword[raise] identifier[ValueError] ( literal[string] literal[string] literal[string] ) keyword[if] identifier[redis_shard_ports] keyword[is] keyword[None] : identifier[redis_shard_ports] = identifier[num_redis_shards] *[ keyword[None] ] keyword[elif] identifier[len] ( identifier[redis_shard_ports] )!= identifier[num_redis_shards] : keyword[raise] identifier[Exception] ( literal[string] literal[string] ) identifier[processes] =[] keyword[if] identifier[use_credis] keyword[is] keyword[None] : identifier[use_credis] =( literal[string] keyword[in] identifier[os] . identifier[environ] ) keyword[if] identifier[use_credis] : keyword[if] identifier[password] keyword[is] keyword[not] keyword[None] : keyword[raise] identifier[Exception] ( literal[string] literal[string] literal[string] literal[string] ) keyword[assert] identifier[num_redis_shards] == literal[int] ,( literal[string] literal[string] ) keyword[if] identifier[use_credis] : identifier[redis_executable] = identifier[CREDIS_EXECUTABLE] identifier[redis_modules] =[ identifier[CREDIS_MASTER_MODULE] , identifier[REDIS_MODULE] ] keyword[else] : identifier[redis_executable] = identifier[REDIS_EXECUTABLE] identifier[redis_modules] =[ identifier[REDIS_MODULE] ] identifier[redis_stdout_file] , identifier[redis_stderr_file] = identifier[redirect_files] [ literal[int] ] identifier[port] , identifier[p] = identifier[_start_redis_instance] ( identifier[redis_executable] , identifier[modules] = identifier[redis_modules] , identifier[port] = identifier[port] , identifier[password] = identifier[password] , identifier[redis_max_clients] = identifier[redis_max_clients] , identifier[redis_max_memory] = keyword[None] , identifier[stdout_file] = identifier[redis_stdout_file] , identifier[stderr_file] = identifier[redis_stderr_file] ) identifier[processes] . identifier[append] ( identifier[p] ) identifier[redis_address] = identifier[address] ( identifier[node_ip_address] , identifier[port] ) identifier[primary_redis_client] = identifier[redis] . identifier[StrictRedis] ( identifier[host] = identifier[node_ip_address] , identifier[port] = identifier[port] , identifier[password] = identifier[password] ) identifier[primary_redis_client] . identifier[set] ( literal[string] , identifier[str] ( identifier[num_redis_shards] )) identifier[primary_redis_client] . identifier[set] ( literal[string] , literal[int] keyword[if] identifier[redirect_worker_output] keyword[else] literal[int] ) identifier[primary_redis_client] . identifier[set] ( literal[string] , literal[int] keyword[if] identifier[include_java] keyword[else] literal[int] ) identifier[_put_version_info_in_redis] ( identifier[primary_redis_client] ) identifier[system_memory] = identifier[ray] . identifier[utils] . identifier[get_system_memory] () keyword[if] identifier[redis_max_memory] keyword[is] keyword[None] : identifier[redis_max_memory] = identifier[min] ( identifier[ray_constants] . identifier[DEFAULT_REDIS_MAX_MEMORY_BYTES] , identifier[max] ( identifier[int] ( identifier[system_memory] * literal[int] ), identifier[ray_constants] . identifier[REDIS_MINIMUM_MEMORY_BYTES] )) keyword[if] identifier[redis_max_memory] < identifier[ray_constants] . identifier[REDIS_MINIMUM_MEMORY_BYTES] : keyword[raise] identifier[ValueError] ( literal[string] literal[string] . identifier[format] ( identifier[redis_max_memory] , identifier[ray_constants] . identifier[REDIS_MINIMUM_MEMORY_BYTES] )) identifier[redis_shards] =[] keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[num_redis_shards] ): identifier[redis_stdout_file] , identifier[redis_stderr_file] = identifier[redirect_files] [ identifier[i] + literal[int] ] keyword[if] identifier[use_credis] : identifier[redis_executable] = identifier[CREDIS_EXECUTABLE] identifier[redis_modules] =[ identifier[CREDIS_MEMBER_MODULE] , identifier[REDIS_MODULE] ] keyword[else] : identifier[redis_executable] = identifier[REDIS_EXECUTABLE] identifier[redis_modules] =[ identifier[REDIS_MODULE] ] identifier[redis_shard_port] , identifier[p] = identifier[_start_redis_instance] ( identifier[redis_executable] , identifier[modules] = identifier[redis_modules] , identifier[port] = identifier[redis_shard_ports] [ identifier[i] ], identifier[password] = identifier[password] , identifier[redis_max_clients] = identifier[redis_max_clients] , identifier[redis_max_memory] = identifier[redis_max_memory] , identifier[stdout_file] = identifier[redis_stdout_file] , identifier[stderr_file] = identifier[redis_stderr_file] ) identifier[processes] . identifier[append] ( identifier[p] ) identifier[shard_address] = identifier[address] ( identifier[node_ip_address] , identifier[redis_shard_port] ) identifier[redis_shards] . identifier[append] ( identifier[shard_address] ) identifier[primary_redis_client] . identifier[rpush] ( literal[string] , identifier[shard_address] ) keyword[if] identifier[use_credis] : identifier[primary_client] = identifier[redis] . identifier[StrictRedis] ( identifier[host] = identifier[node_ip_address] , identifier[port] = identifier[port] , identifier[password] = identifier[password] ) identifier[shard_client] = identifier[redis] . identifier[StrictRedis] ( identifier[host] = identifier[node_ip_address] , identifier[port] = identifier[redis_shard_port] , identifier[password] = identifier[password] ) identifier[primary_client] . identifier[execute_command] ( literal[string] , identifier[node_ip_address] , identifier[redis_shard_port] ) identifier[shard_client] . identifier[execute_command] ( literal[string] , identifier[node_ip_address] , identifier[port] ) keyword[return] identifier[redis_address] , identifier[redis_shards] , identifier[processes]
def start_redis(node_ip_address, redirect_files, port=None, redis_shard_ports=None, num_redis_shards=1, redis_max_clients=None, redirect_worker_output=False, password=None, use_credis=None, redis_max_memory=None, include_java=False): """Start the Redis global state store. Args: node_ip_address: The IP address of the current node. This is only used for recording the log filenames in Redis. redirect_files: The list of (stdout, stderr) file pairs. port (int): If provided, the primary Redis shard will be started on this port. redis_shard_ports: A list of the ports to use for the non-primary Redis shards. num_redis_shards (int): If provided, the number of Redis shards to start, in addition to the primary one. The default value is one shard. redis_max_clients: If this is provided, Ray will attempt to configure Redis with this maxclients number. redirect_worker_output (bool): True if worker output should be redirected to a file and false otherwise. Workers will have access to this value when they start up. password (str): Prevents external clients without the password from connecting to Redis if provided. use_credis: If True, additionally load the chain-replicated libraries into the redis servers. Defaults to None, which means its value is set by the presence of "RAY_USE_NEW_GCS" in os.environ. redis_max_memory: The max amount of memory (in bytes) to allow each redis shard to use. Once the limit is exceeded, redis will start LRU eviction of entries. This only applies to the sharded redis tables (task, object, and profile tables). By default, this is capped at 10GB but can be set higher. include_java (bool): If True, the raylet backend can also support Java worker. Returns: A tuple of the address for the primary Redis shard, a list of addresses for the remaining shards, and the processes that were started. """ if len(redirect_files) != 1 + num_redis_shards: raise ValueError('The number of redirect file pairs should be equal to the number of redis shards (including the primary shard) we will start.') # depends on [control=['if'], data=[]] if redis_shard_ports is None: redis_shard_ports = num_redis_shards * [None] # depends on [control=['if'], data=['redis_shard_ports']] elif len(redis_shard_ports) != num_redis_shards: raise Exception('The number of Redis shard ports does not match the number of Redis shards.') # depends on [control=['if'], data=[]] processes = [] if use_credis is None: use_credis = 'RAY_USE_NEW_GCS' in os.environ # depends on [control=['if'], data=['use_credis']] if use_credis: if password is not None: # TODO(pschafhalter) remove this once credis supports # authenticating Redis ports raise Exception('Setting the `redis_password` argument is not supported in credis. To run Ray with password-protected Redis ports, ensure that the environment variable `RAY_USE_NEW_GCS=off`.') # depends on [control=['if'], data=[]] assert num_redis_shards == 1, 'For now, RAY_USE_NEW_GCS supports 1 shard, and credis supports 1-node chain for that shard only.' # depends on [control=['if'], data=[]] if use_credis: redis_executable = CREDIS_EXECUTABLE # TODO(suquark): We need credis here because some symbols need to be # imported from credis dynamically through dlopen when Ray is built # with RAY_USE_NEW_GCS=on. We should remove them later for the primary # shard. # See src/ray/gcs/redis_module/ray_redis_module.cc redis_modules = [CREDIS_MASTER_MODULE, REDIS_MODULE] # depends on [control=['if'], data=[]] else: redis_executable = REDIS_EXECUTABLE redis_modules = [REDIS_MODULE] (redis_stdout_file, redis_stderr_file) = redirect_files[0] # Start the primary Redis shard. # Below we use None to indicate no limit on the memory of the # primary Redis shard. (port, p) = _start_redis_instance(redis_executable, modules=redis_modules, port=port, password=password, redis_max_clients=redis_max_clients, redis_max_memory=None, stdout_file=redis_stdout_file, stderr_file=redis_stderr_file) processes.append(p) redis_address = address(node_ip_address, port) # Register the number of Redis shards in the primary shard, so that clients # know how many redis shards to expect under RedisShards. primary_redis_client = redis.StrictRedis(host=node_ip_address, port=port, password=password) primary_redis_client.set('NumRedisShards', str(num_redis_shards)) # Put the redirect_worker_output bool in the Redis shard so that workers # can access it and know whether or not to redirect their output. primary_redis_client.set('RedirectOutput', 1 if redirect_worker_output else 0) # put the include_java bool to primary redis-server, so that other nodes # can access it and know whether or not to enable cross-languages. primary_redis_client.set('INCLUDE_JAVA', 1 if include_java else 0) # Store version information in the primary Redis shard. _put_version_info_in_redis(primary_redis_client) # Calculate the redis memory. system_memory = ray.utils.get_system_memory() if redis_max_memory is None: redis_max_memory = min(ray_constants.DEFAULT_REDIS_MAX_MEMORY_BYTES, max(int(system_memory * 0.2), ray_constants.REDIS_MINIMUM_MEMORY_BYTES)) # depends on [control=['if'], data=['redis_max_memory']] if redis_max_memory < ray_constants.REDIS_MINIMUM_MEMORY_BYTES: raise ValueError('Attempting to cap Redis memory usage at {} bytes, but the minimum allowed is {} bytes.'.format(redis_max_memory, ray_constants.REDIS_MINIMUM_MEMORY_BYTES)) # depends on [control=['if'], data=['redis_max_memory']] # Start other Redis shards. Each Redis shard logs to a separate file, # prefixed by "redis-<shard number>". redis_shards = [] for i in range(num_redis_shards): (redis_stdout_file, redis_stderr_file) = redirect_files[i + 1] if use_credis: redis_executable = CREDIS_EXECUTABLE # It is important to load the credis module BEFORE the ray module, # as the latter contains an extern declaration that the former # supplies. redis_modules = [CREDIS_MEMBER_MODULE, REDIS_MODULE] # depends on [control=['if'], data=[]] else: redis_executable = REDIS_EXECUTABLE redis_modules = [REDIS_MODULE] (redis_shard_port, p) = _start_redis_instance(redis_executable, modules=redis_modules, port=redis_shard_ports[i], password=password, redis_max_clients=redis_max_clients, redis_max_memory=redis_max_memory, stdout_file=redis_stdout_file, stderr_file=redis_stderr_file) processes.append(p) shard_address = address(node_ip_address, redis_shard_port) redis_shards.append(shard_address) # Store redis shard information in the primary redis shard. primary_redis_client.rpush('RedisShards', shard_address) # depends on [control=['for'], data=['i']] if use_credis: # Configure the chain state. The way it is intended to work is # the following: # # PRIMARY_SHARD # # SHARD_1 (master replica) -> SHARD_1 (member replica) # -> SHARD_1 (member replica) # # SHARD_2 (master replica) -> SHARD_2 (member replica) # -> SHARD_2 (member replica) # ... # # # If we have credis members in future, their modules should be: # [CREDIS_MEMBER_MODULE, REDIS_MODULE], and they will be initialized by # execute_command("MEMBER.CONNECT_TO_MASTER", node_ip_address, port) # # Currently we have num_redis_shards == 1, so only one chain will be # created, and the chain only contains master. # TODO(suquark): Currently, this is not correct because we are # using the master replica as the primary shard. This should be # fixed later. I had tried to fix it but failed because of heartbeat # issues. primary_client = redis.StrictRedis(host=node_ip_address, port=port, password=password) shard_client = redis.StrictRedis(host=node_ip_address, port=redis_shard_port, password=password) primary_client.execute_command('MASTER.ADD', node_ip_address, redis_shard_port) shard_client.execute_command('MEMBER.CONNECT_TO_MASTER', node_ip_address, port) # depends on [control=['if'], data=[]] return (redis_address, redis_shards, processes)
def first_items(self, index): """Meant to reproduce the results of the following grouper = pandas.Grouper(...) first_items = pd.Series(np.arange(len(index)), index).groupby(grouper).first() with index being a CFTimeIndex instead of a DatetimeIndex. """ datetime_bins, labels = _get_time_bins(index, self.freq, self.closed, self.label, self.base) if self.loffset is not None: if isinstance(self.loffset, datetime.timedelta): labels = labels + self.loffset else: labels = labels + to_offset(self.loffset) # check binner fits data if index[0] < datetime_bins[0]: raise ValueError("Value falls before first bin") if index[-1] > datetime_bins[-1]: raise ValueError("Value falls after last bin") integer_bins = np.searchsorted( index, datetime_bins, side=self.closed)[:-1] first_items = pd.Series(integer_bins, labels) # Mask duplicate values with NaNs, preserving the last values non_duplicate = ~first_items.duplicated('last') return first_items.where(non_duplicate)
def function[first_items, parameter[self, index]]: constant[Meant to reproduce the results of the following grouper = pandas.Grouper(...) first_items = pd.Series(np.arange(len(index)), index).groupby(grouper).first() with index being a CFTimeIndex instead of a DatetimeIndex. ] <ast.Tuple object at 0x7da18eb552d0> assign[=] call[name[_get_time_bins], parameter[name[index], name[self].freq, name[self].closed, name[self].label, name[self].base]] if compare[name[self].loffset is_not constant[None]] begin[:] if call[name[isinstance], parameter[name[self].loffset, name[datetime].timedelta]] begin[:] variable[labels] assign[=] binary_operation[name[labels] + name[self].loffset] if compare[call[name[index]][constant[0]] less[<] call[name[datetime_bins]][constant[0]]] begin[:] <ast.Raise object at 0x7da18eb56ef0> if compare[call[name[index]][<ast.UnaryOp object at 0x7da18eb57970>] greater[>] call[name[datetime_bins]][<ast.UnaryOp object at 0x7da18eb547c0>]] begin[:] <ast.Raise object at 0x7da18eb54ca0> variable[integer_bins] assign[=] call[call[name[np].searchsorted, parameter[name[index], name[datetime_bins]]]][<ast.Slice object at 0x7da18eb56a70>] variable[first_items] assign[=] call[name[pd].Series, parameter[name[integer_bins], name[labels]]] variable[non_duplicate] assign[=] <ast.UnaryOp object at 0x7da18eb56620> return[call[name[first_items].where, parameter[name[non_duplicate]]]]
keyword[def] identifier[first_items] ( identifier[self] , identifier[index] ): literal[string] identifier[datetime_bins] , identifier[labels] = identifier[_get_time_bins] ( identifier[index] , identifier[self] . identifier[freq] , identifier[self] . identifier[closed] , identifier[self] . identifier[label] , identifier[self] . identifier[base] ) keyword[if] identifier[self] . identifier[loffset] keyword[is] keyword[not] keyword[None] : keyword[if] identifier[isinstance] ( identifier[self] . identifier[loffset] , identifier[datetime] . identifier[timedelta] ): identifier[labels] = identifier[labels] + identifier[self] . identifier[loffset] keyword[else] : identifier[labels] = identifier[labels] + identifier[to_offset] ( identifier[self] . identifier[loffset] ) keyword[if] identifier[index] [ literal[int] ]< identifier[datetime_bins] [ literal[int] ]: keyword[raise] identifier[ValueError] ( literal[string] ) keyword[if] identifier[index] [- literal[int] ]> identifier[datetime_bins] [- literal[int] ]: keyword[raise] identifier[ValueError] ( literal[string] ) identifier[integer_bins] = identifier[np] . identifier[searchsorted] ( identifier[index] , identifier[datetime_bins] , identifier[side] = identifier[self] . identifier[closed] )[:- literal[int] ] identifier[first_items] = identifier[pd] . identifier[Series] ( identifier[integer_bins] , identifier[labels] ) identifier[non_duplicate] =~ identifier[first_items] . identifier[duplicated] ( literal[string] ) keyword[return] identifier[first_items] . identifier[where] ( identifier[non_duplicate] )
def first_items(self, index): """Meant to reproduce the results of the following grouper = pandas.Grouper(...) first_items = pd.Series(np.arange(len(index)), index).groupby(grouper).first() with index being a CFTimeIndex instead of a DatetimeIndex. """ (datetime_bins, labels) = _get_time_bins(index, self.freq, self.closed, self.label, self.base) if self.loffset is not None: if isinstance(self.loffset, datetime.timedelta): labels = labels + self.loffset # depends on [control=['if'], data=[]] else: labels = labels + to_offset(self.loffset) # depends on [control=['if'], data=[]] # check binner fits data if index[0] < datetime_bins[0]: raise ValueError('Value falls before first bin') # depends on [control=['if'], data=[]] if index[-1] > datetime_bins[-1]: raise ValueError('Value falls after last bin') # depends on [control=['if'], data=[]] integer_bins = np.searchsorted(index, datetime_bins, side=self.closed)[:-1] first_items = pd.Series(integer_bins, labels) # Mask duplicate values with NaNs, preserving the last values non_duplicate = ~first_items.duplicated('last') return first_items.where(non_duplicate)
def compute(mechanism, subsystem, purviews, cause_purviews, effect_purviews): """Compute a |Concept| for a mechanism, in this |Subsystem| with the provided purviews. """ concept = subsystem.concept(mechanism, purviews=purviews, cause_purviews=cause_purviews, effect_purviews=effect_purviews) # Don't serialize the subsystem. # This is replaced on the other side of the queue, and ensures # that all concepts in the CES reference the same subsystem. concept.subsystem = None return concept
def function[compute, parameter[mechanism, subsystem, purviews, cause_purviews, effect_purviews]]: constant[Compute a |Concept| for a mechanism, in this |Subsystem| with the provided purviews. ] variable[concept] assign[=] call[name[subsystem].concept, parameter[name[mechanism]]] name[concept].subsystem assign[=] constant[None] return[name[concept]]
keyword[def] identifier[compute] ( identifier[mechanism] , identifier[subsystem] , identifier[purviews] , identifier[cause_purviews] , identifier[effect_purviews] ): literal[string] identifier[concept] = identifier[subsystem] . identifier[concept] ( identifier[mechanism] , identifier[purviews] = identifier[purviews] , identifier[cause_purviews] = identifier[cause_purviews] , identifier[effect_purviews] = identifier[effect_purviews] ) identifier[concept] . identifier[subsystem] = keyword[None] keyword[return] identifier[concept]
def compute(mechanism, subsystem, purviews, cause_purviews, effect_purviews): """Compute a |Concept| for a mechanism, in this |Subsystem| with the provided purviews. """ concept = subsystem.concept(mechanism, purviews=purviews, cause_purviews=cause_purviews, effect_purviews=effect_purviews) # Don't serialize the subsystem. # This is replaced on the other side of the queue, and ensures # that all concepts in the CES reference the same subsystem. concept.subsystem = None return concept
def initialize_model(self, root_node): """ Initializes the Model using given root node. :param root_node: Graph root node. :type root_node: DefaultNode :return: Method success :rtype: bool """ LOGGER.debug("> Initializing model with '{0}' root node.".format(root_node)) self.beginResetModel() self.root_node = root_node self.enable_model_triggers(True) self.endResetModel() return True
def function[initialize_model, parameter[self, root_node]]: constant[ Initializes the Model using given root node. :param root_node: Graph root node. :type root_node: DefaultNode :return: Method success :rtype: bool ] call[name[LOGGER].debug, parameter[call[constant[> Initializing model with '{0}' root node.].format, parameter[name[root_node]]]]] call[name[self].beginResetModel, parameter[]] name[self].root_node assign[=] name[root_node] call[name[self].enable_model_triggers, parameter[constant[True]]] call[name[self].endResetModel, parameter[]] return[constant[True]]
keyword[def] identifier[initialize_model] ( identifier[self] , identifier[root_node] ): literal[string] identifier[LOGGER] . identifier[debug] ( literal[string] . identifier[format] ( identifier[root_node] )) identifier[self] . identifier[beginResetModel] () identifier[self] . identifier[root_node] = identifier[root_node] identifier[self] . identifier[enable_model_triggers] ( keyword[True] ) identifier[self] . identifier[endResetModel] () keyword[return] keyword[True]
def initialize_model(self, root_node): """ Initializes the Model using given root node. :param root_node: Graph root node. :type root_node: DefaultNode :return: Method success :rtype: bool """ LOGGER.debug("> Initializing model with '{0}' root node.".format(root_node)) self.beginResetModel() self.root_node = root_node self.enable_model_triggers(True) self.endResetModel() return True
def unsubscribe_from_hub(self, event, callback): """ :calls: `POST /hub <http://developer.github.com/>`_ :param event: string :param callback: string :param secret: string :rtype: None """ return self._hub("unsubscribe", event, callback, github.GithubObject.NotSet)
def function[unsubscribe_from_hub, parameter[self, event, callback]]: constant[ :calls: `POST /hub <http://developer.github.com/>`_ :param event: string :param callback: string :param secret: string :rtype: None ] return[call[name[self]._hub, parameter[constant[unsubscribe], name[event], name[callback], name[github].GithubObject.NotSet]]]
keyword[def] identifier[unsubscribe_from_hub] ( identifier[self] , identifier[event] , identifier[callback] ): literal[string] keyword[return] identifier[self] . identifier[_hub] ( literal[string] , identifier[event] , identifier[callback] , identifier[github] . identifier[GithubObject] . identifier[NotSet] )
def unsubscribe_from_hub(self, event, callback): """ :calls: `POST /hub <http://developer.github.com/>`_ :param event: string :param callback: string :param secret: string :rtype: None """ return self._hub('unsubscribe', event, callback, github.GithubObject.NotSet)
def identity_is(self,item_category,item_type=None): """Check if the item described by `self` belongs to the given category and type. :Parameters: - `item_category`: the category name. - `item_type`: the type name. If `None` then only the category is checked. :Types: - `item_category`: `unicode` - `item_type`: `unicode` :return: `True` if `self` contains at least one <identity/> object with given type and category. :returntype: `bool`""" if not item_category: raise ValueError("bad category") if not item_type: type_expr=u"" elif '"' not in item_type: type_expr=u' and @type="%s"' % (item_type,) elif "'" not in type: type_expr=u" and @type='%s'" % (item_type,) else: raise ValueError("Invalid type name") if '"' not in item_category: expr=u'd:identity[@category="%s"%s]' % (item_category,type_expr) elif "'" not in item_category: expr=u"d:identity[@category='%s'%s]" % (item_category,type_expr) else: raise ValueError("Invalid category name") l=self.xpath_ctxt.xpathEval(to_utf8(expr)) if l: return True else: return False
def function[identity_is, parameter[self, item_category, item_type]]: constant[Check if the item described by `self` belongs to the given category and type. :Parameters: - `item_category`: the category name. - `item_type`: the type name. If `None` then only the category is checked. :Types: - `item_category`: `unicode` - `item_type`: `unicode` :return: `True` if `self` contains at least one <identity/> object with given type and category. :returntype: `bool`] if <ast.UnaryOp object at 0x7da20cabe410> begin[:] <ast.Raise object at 0x7da20cabd8d0> if <ast.UnaryOp object at 0x7da20c990100> begin[:] variable[type_expr] assign[=] constant[] if compare[constant["] <ast.NotIn object at 0x7da2590d7190> name[item_category]] begin[:] variable[expr] assign[=] binary_operation[constant[d:identity[@category="%s"%s]] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da1b00e6ec0>, <ast.Name object at 0x7da1b00e74c0>]]] variable[l] assign[=] call[name[self].xpath_ctxt.xpathEval, parameter[call[name[to_utf8], parameter[name[expr]]]]] if name[l] begin[:] return[constant[True]]
keyword[def] identifier[identity_is] ( identifier[self] , identifier[item_category] , identifier[item_type] = keyword[None] ): literal[string] keyword[if] keyword[not] identifier[item_category] : keyword[raise] identifier[ValueError] ( literal[string] ) keyword[if] keyword[not] identifier[item_type] : identifier[type_expr] = literal[string] keyword[elif] literal[string] keyword[not] keyword[in] identifier[item_type] : identifier[type_expr] = literal[string] %( identifier[item_type] ,) keyword[elif] literal[string] keyword[not] keyword[in] identifier[type] : identifier[type_expr] = literal[string] %( identifier[item_type] ,) keyword[else] : keyword[raise] identifier[ValueError] ( literal[string] ) keyword[if] literal[string] keyword[not] keyword[in] identifier[item_category] : identifier[expr] = literal[string] %( identifier[item_category] , identifier[type_expr] ) keyword[elif] literal[string] keyword[not] keyword[in] identifier[item_category] : identifier[expr] = literal[string] %( identifier[item_category] , identifier[type_expr] ) keyword[else] : keyword[raise] identifier[ValueError] ( literal[string] ) identifier[l] = identifier[self] . identifier[xpath_ctxt] . identifier[xpathEval] ( identifier[to_utf8] ( identifier[expr] )) keyword[if] identifier[l] : keyword[return] keyword[True] keyword[else] : keyword[return] keyword[False]
def identity_is(self, item_category, item_type=None): """Check if the item described by `self` belongs to the given category and type. :Parameters: - `item_category`: the category name. - `item_type`: the type name. If `None` then only the category is checked. :Types: - `item_category`: `unicode` - `item_type`: `unicode` :return: `True` if `self` contains at least one <identity/> object with given type and category. :returntype: `bool`""" if not item_category: raise ValueError('bad category') # depends on [control=['if'], data=[]] if not item_type: type_expr = u'' # depends on [control=['if'], data=[]] elif '"' not in item_type: type_expr = u' and @type="%s"' % (item_type,) # depends on [control=['if'], data=['item_type']] elif "'" not in type: type_expr = u" and @type='%s'" % (item_type,) # depends on [control=['if'], data=[]] else: raise ValueError('Invalid type name') if '"' not in item_category: expr = u'd:identity[@category="%s"%s]' % (item_category, type_expr) # depends on [control=['if'], data=['item_category']] elif "'" not in item_category: expr = u"d:identity[@category='%s'%s]" % (item_category, type_expr) # depends on [control=['if'], data=['item_category']] else: raise ValueError('Invalid category name') l = self.xpath_ctxt.xpathEval(to_utf8(expr)) if l: return True # depends on [control=['if'], data=[]] else: return False
def discover(name, wait_for_s=60): """Discover a service by name Look for an advert to a named service:: address = nw0.discover("myservice") :param name: any text :param wait_for_s: how many seconds to wait before giving up :returns: the address found or None """ _start_beacon() # # It's possible to enter a deadlock situation where the first # process fires off a discovery request and waits for the # second process to advertise. But the second process has to # connect to the rpc port of the first process' beacon and # its advertisement is queued behind the pending discovery. # # To give both a chance of succeeding we operate in bursts, # allowing them to interleave. # t0 = time.time() while True: discovery = _rpc("discover", name, 0.5) if discovery: return discovery if timed_out(t0, wait_for_s): return None
def function[discover, parameter[name, wait_for_s]]: constant[Discover a service by name Look for an advert to a named service:: address = nw0.discover("myservice") :param name: any text :param wait_for_s: how many seconds to wait before giving up :returns: the address found or None ] call[name[_start_beacon], parameter[]] variable[t0] assign[=] call[name[time].time, parameter[]] while constant[True] begin[:] variable[discovery] assign[=] call[name[_rpc], parameter[constant[discover], name[name], constant[0.5]]] if name[discovery] begin[:] return[name[discovery]] if call[name[timed_out], parameter[name[t0], name[wait_for_s]]] begin[:] return[constant[None]]
keyword[def] identifier[discover] ( identifier[name] , identifier[wait_for_s] = literal[int] ): literal[string] identifier[_start_beacon] () identifier[t0] = identifier[time] . identifier[time] () keyword[while] keyword[True] : identifier[discovery] = identifier[_rpc] ( literal[string] , identifier[name] , literal[int] ) keyword[if] identifier[discovery] : keyword[return] identifier[discovery] keyword[if] identifier[timed_out] ( identifier[t0] , identifier[wait_for_s] ): keyword[return] keyword[None]
def discover(name, wait_for_s=60): """Discover a service by name Look for an advert to a named service:: address = nw0.discover("myservice") :param name: any text :param wait_for_s: how many seconds to wait before giving up :returns: the address found or None """ _start_beacon() # # It's possible to enter a deadlock situation where the first # process fires off a discovery request and waits for the # second process to advertise. But the second process has to # connect to the rpc port of the first process' beacon and # its advertisement is queued behind the pending discovery. # # To give both a chance of succeeding we operate in bursts, # allowing them to interleave. # t0 = time.time() while True: discovery = _rpc('discover', name, 0.5) if discovery: return discovery # depends on [control=['if'], data=[]] if timed_out(t0, wait_for_s): return None # depends on [control=['if'], data=[]] # depends on [control=['while'], data=[]]
def A_multiple_hole_cylinder(Do, L, holes): r'''Returns the surface area of a cylinder with multiple holes. Calculation will naively return a negative value or other impossible result if the number of cylinders added is physically impossible. Holes may be of different shapes, but must be perpendicular to the axis of the cylinder. .. math:: A = \pi D_o L + 2\cdot \frac{\pi D_o^2}{4} + \sum_{i}^n \left( \pi D_i L - 2\cdot \frac{\pi D_i^2}{4}\right) Parameters ---------- Do : float Diameter of the exterior of the cylinder, [m] L : float Length of the cylinder, [m] holes : list List of tuples containing (diameter, count) pairs of descriptions for each of the holes sizes. Returns ------- A : float Surface area [m^2] Examples -------- >>> A_multiple_hole_cylinder(0.01, 0.1, [(0.005, 1)]) 0.004830198704894308 ''' side_o = pi*Do*L cap_circle = pi*Do**2/4*2 A = cap_circle + side_o for Di, n in holes: side_i = pi*Di*L cap_removed = pi*Di**2/4*2 A = A + side_i*n - cap_removed*n return A
def function[A_multiple_hole_cylinder, parameter[Do, L, holes]]: constant[Returns the surface area of a cylinder with multiple holes. Calculation will naively return a negative value or other impossible result if the number of cylinders added is physically impossible. Holes may be of different shapes, but must be perpendicular to the axis of the cylinder. .. math:: A = \pi D_o L + 2\cdot \frac{\pi D_o^2}{4} + \sum_{i}^n \left( \pi D_i L - 2\cdot \frac{\pi D_i^2}{4}\right) Parameters ---------- Do : float Diameter of the exterior of the cylinder, [m] L : float Length of the cylinder, [m] holes : list List of tuples containing (diameter, count) pairs of descriptions for each of the holes sizes. Returns ------- A : float Surface area [m^2] Examples -------- >>> A_multiple_hole_cylinder(0.01, 0.1, [(0.005, 1)]) 0.004830198704894308 ] variable[side_o] assign[=] binary_operation[binary_operation[name[pi] * name[Do]] * name[L]] variable[cap_circle] assign[=] binary_operation[binary_operation[binary_operation[name[pi] * binary_operation[name[Do] ** constant[2]]] / constant[4]] * constant[2]] variable[A] assign[=] binary_operation[name[cap_circle] + name[side_o]] for taget[tuple[[<ast.Name object at 0x7da1b12f2980>, <ast.Name object at 0x7da1b12f37c0>]]] in starred[name[holes]] begin[:] variable[side_i] assign[=] binary_operation[binary_operation[name[pi] * name[Di]] * name[L]] variable[cap_removed] assign[=] binary_operation[binary_operation[binary_operation[name[pi] * binary_operation[name[Di] ** constant[2]]] / constant[4]] * constant[2]] variable[A] assign[=] binary_operation[binary_operation[name[A] + binary_operation[name[side_i] * name[n]]] - binary_operation[name[cap_removed] * name[n]]] return[name[A]]
keyword[def] identifier[A_multiple_hole_cylinder] ( identifier[Do] , identifier[L] , identifier[holes] ): literal[string] identifier[side_o] = identifier[pi] * identifier[Do] * identifier[L] identifier[cap_circle] = identifier[pi] * identifier[Do] ** literal[int] / literal[int] * literal[int] identifier[A] = identifier[cap_circle] + identifier[side_o] keyword[for] identifier[Di] , identifier[n] keyword[in] identifier[holes] : identifier[side_i] = identifier[pi] * identifier[Di] * identifier[L] identifier[cap_removed] = identifier[pi] * identifier[Di] ** literal[int] / literal[int] * literal[int] identifier[A] = identifier[A] + identifier[side_i] * identifier[n] - identifier[cap_removed] * identifier[n] keyword[return] identifier[A]
def A_multiple_hole_cylinder(Do, L, holes): """Returns the surface area of a cylinder with multiple holes. Calculation will naively return a negative value or other impossible result if the number of cylinders added is physically impossible. Holes may be of different shapes, but must be perpendicular to the axis of the cylinder. .. math:: A = \\pi D_o L + 2\\cdot \\frac{\\pi D_o^2}{4} + \\sum_{i}^n \\left( \\pi D_i L - 2\\cdot \\frac{\\pi D_i^2}{4}\\right) Parameters ---------- Do : float Diameter of the exterior of the cylinder, [m] L : float Length of the cylinder, [m] holes : list List of tuples containing (diameter, count) pairs of descriptions for each of the holes sizes. Returns ------- A : float Surface area [m^2] Examples -------- >>> A_multiple_hole_cylinder(0.01, 0.1, [(0.005, 1)]) 0.004830198704894308 """ side_o = pi * Do * L cap_circle = pi * Do ** 2 / 4 * 2 A = cap_circle + side_o for (Di, n) in holes: side_i = pi * Di * L cap_removed = pi * Di ** 2 / 4 * 2 A = A + side_i * n - cap_removed * n # depends on [control=['for'], data=[]] return A
def select_whole_line(self, line=None, apply_selection=True): """ Selects an entire line. :param line: Line to select. If None, the current line will be selected :param apply_selection: True to apply selection on the text editor widget, False to just return the text cursor without setting it on the editor. :return: QTextCursor """ if line is None: line = self.current_line_nbr() return self.select_lines(line, line, apply_selection=apply_selection)
def function[select_whole_line, parameter[self, line, apply_selection]]: constant[ Selects an entire line. :param line: Line to select. If None, the current line will be selected :param apply_selection: True to apply selection on the text editor widget, False to just return the text cursor without setting it on the editor. :return: QTextCursor ] if compare[name[line] is constant[None]] begin[:] variable[line] assign[=] call[name[self].current_line_nbr, parameter[]] return[call[name[self].select_lines, parameter[name[line], name[line]]]]
keyword[def] identifier[select_whole_line] ( identifier[self] , identifier[line] = keyword[None] , identifier[apply_selection] = keyword[True] ): literal[string] keyword[if] identifier[line] keyword[is] keyword[None] : identifier[line] = identifier[self] . identifier[current_line_nbr] () keyword[return] identifier[self] . identifier[select_lines] ( identifier[line] , identifier[line] , identifier[apply_selection] = identifier[apply_selection] )
def select_whole_line(self, line=None, apply_selection=True): """ Selects an entire line. :param line: Line to select. If None, the current line will be selected :param apply_selection: True to apply selection on the text editor widget, False to just return the text cursor without setting it on the editor. :return: QTextCursor """ if line is None: line = self.current_line_nbr() # depends on [control=['if'], data=['line']] return self.select_lines(line, line, apply_selection=apply_selection)
def integrity_check(bounddict, max_dtu_offset): """Integrity check of 'bounddict' content. Parameters ---------- bounddict : JSON structure Structure employed to store bounddict information. max_dtu_offset : float Maximum allowed difference in DTU location (mm) for each parameter """ if 'meta_info' not in bounddict.keys(): raise ValueError('"meta_info" not found in JSON file') if 'description' not in bounddict['meta_info'].keys(): raise ValueError('"description" not found in JSON file') if bounddict['meta_info']['description'] != \ 'slitlet boundaries from fits to continuum-lamp exposures': raise ValueError('Unexpected "description" in JSON file') grism = bounddict['tags']['grism'] print('>>> grism...:', grism) spfilter = bounddict['tags']['filter'] print('>>> filter..:', spfilter) valid_slitlets = ["slitlet" + str(i).zfill(2) for i in range(1, EMIR_NBARS + 1)] read_slitlets = list(bounddict['contents'].keys()) read_slitlets.sort() first_dtu = True first_dtu_configuration = None # avoid PyCharm warning list_dtu_configurations = [] for tmp_slitlet in read_slitlets: if tmp_slitlet not in valid_slitlets: raise ValueError("Unexpected slitlet key: " + tmp_slitlet) # for each slitlet, check valid DATE-OBS (ISO 8601) read_dateobs = list(bounddict['contents'][tmp_slitlet].keys()) read_dateobs.sort() for tmp_dateobs in read_dateobs: try: datetime.strptime(tmp_dateobs, "%Y-%m-%dT%H:%M:%S.%f") except ValueError: print("Unexpected date_obs key: " + tmp_dateobs) raise # for each DATE-OBS, check expected fields tmp_dict = bounddict['contents'][tmp_slitlet][tmp_dateobs] valid_keys = ["boundary_coef_lower", "boundary_coef_upper", "boundary_xmax_lower", "boundary_xmax_upper", "boundary_xmin_lower", "boundary_xmin_upper", "csu_bar_left", "csu_bar_right", "csu_bar_slit_center", "csu_bar_slit_width", "rotang", "xdtu", "xdtu_0", "ydtu", "ydtu_0", "zdtu", "zdtu_0", "zzz_info1", "zzz_info2"] read_keys = tmp_dict.keys() for tmp_key in read_keys: if tmp_key not in valid_keys: print("ERROR:") print("grism...:", grism) print("slitlet.:", tmp_slitlet) print("date_obs:", tmp_dateobs) raise ValueError("Unexpected key " + tmp_key) for tmp_key in valid_keys: if tmp_key not in read_keys: print("ERROR:") print("grism...:", grism) print("slitlet.:", tmp_slitlet) print("date_obs:", tmp_dateobs) raise ValueError("Expected key " + tmp_key + " not found") if tmp_dict['boundary_xmax_lower'] <= \ tmp_dict['boundary_xmin_lower']: print("ERROR:") print("grism...:", grism) print("slitlet.:", tmp_slitlet) print("date_obs:", tmp_dateobs) print("boundary_xmin_lower", tmp_dict['boundary_xmin_lower']) print("boundary_xmax_lower", tmp_dict['boundary_xmax_lower']) raise ValueError("Unexpected boundary_xmax_lower <= " "boundary_xmin_lower") if tmp_dict['boundary_xmax_upper'] <= \ tmp_dict['boundary_xmin_upper']: print("ERROR:") print("grism...:", grism) print("slitlet.:", tmp_slitlet) print("date_obs:", tmp_dateobs) print("boundary_xmin_upper", tmp_dict['boundary_xmin_upper']) print("boundary_xmax_upper", tmp_dict['boundary_xmax_upper']) raise ValueError("Unexpected boundary_xmax_upper <= " "boundary_xmin_upper") if first_dtu: first_dtu_configuration = \ DtuConfiguration.define_from_dictionary(tmp_dict) first_dtu = False list_dtu_configurations.append(first_dtu_configuration) else: last_dtu_configuration = \ DtuConfiguration.define_from_dictionary(tmp_dict) if not first_dtu_configuration.closeto( last_dtu_configuration, abserror=max_dtu_offset ): print("ERROR:") print("grism...:", grism) print("slitlet.:", tmp_slitlet) print("date_obs:", tmp_dateobs) print("First DTU configuration..:\n\t", first_dtu_configuration) print("Last DTU configuration...:\n\t", last_dtu_configuration) raise ValueError("Unexpected DTU configuration") list_dtu_configurations.append(last_dtu_configuration) print("* Integrity check OK!") averaged_dtu_configuration = average_dtu_configurations( list_dtu_configurations) maxdiff_dtu_configuration = maxdiff_dtu_configurations( list_dtu_configurations ) return averaged_dtu_configuration, maxdiff_dtu_configuration
def function[integrity_check, parameter[bounddict, max_dtu_offset]]: constant[Integrity check of 'bounddict' content. Parameters ---------- bounddict : JSON structure Structure employed to store bounddict information. max_dtu_offset : float Maximum allowed difference in DTU location (mm) for each parameter ] if compare[constant[meta_info] <ast.NotIn object at 0x7da2590d7190> call[name[bounddict].keys, parameter[]]] begin[:] <ast.Raise object at 0x7da2044c2d70> if compare[constant[description] <ast.NotIn object at 0x7da2590d7190> call[call[name[bounddict]][constant[meta_info]].keys, parameter[]]] begin[:] <ast.Raise object at 0x7da2044c33d0> if compare[call[call[name[bounddict]][constant[meta_info]]][constant[description]] not_equal[!=] constant[slitlet boundaries from fits to continuum-lamp exposures]] begin[:] <ast.Raise object at 0x7da2044c2890> variable[grism] assign[=] call[call[name[bounddict]][constant[tags]]][constant[grism]] call[name[print], parameter[constant[>>> grism...:], name[grism]]] variable[spfilter] assign[=] call[call[name[bounddict]][constant[tags]]][constant[filter]] call[name[print], parameter[constant[>>> filter..:], name[spfilter]]] variable[valid_slitlets] assign[=] <ast.ListComp object at 0x7da2044c1480> variable[read_slitlets] assign[=] call[name[list], parameter[call[call[name[bounddict]][constant[contents]].keys, parameter[]]]] call[name[read_slitlets].sort, parameter[]] variable[first_dtu] assign[=] constant[True] variable[first_dtu_configuration] assign[=] constant[None] variable[list_dtu_configurations] assign[=] list[[]] for taget[name[tmp_slitlet]] in starred[name[read_slitlets]] begin[:] if compare[name[tmp_slitlet] <ast.NotIn object at 0x7da2590d7190> name[valid_slitlets]] begin[:] <ast.Raise object at 0x7da2044c28c0> variable[read_dateobs] assign[=] call[name[list], parameter[call[call[call[name[bounddict]][constant[contents]]][name[tmp_slitlet]].keys, parameter[]]]] call[name[read_dateobs].sort, parameter[]] for taget[name[tmp_dateobs]] in starred[name[read_dateobs]] begin[:] <ast.Try object at 0x7da2044c2260> variable[tmp_dict] assign[=] call[call[call[name[bounddict]][constant[contents]]][name[tmp_slitlet]]][name[tmp_dateobs]] variable[valid_keys] assign[=] list[[<ast.Constant object at 0x7da2044c3940>, <ast.Constant object at 0x7da2044c0d90>, <ast.Constant object at 0x7da2044c2320>, <ast.Constant object at 0x7da2044c2080>, <ast.Constant object at 0x7da2044c3fa0>, <ast.Constant object at 0x7da2044c27d0>, <ast.Constant object at 0x7da2044c2fe0>, <ast.Constant object at 0x7da2044c1960>, <ast.Constant object at 0x7da2044c10f0>, <ast.Constant object at 0x7da2044c1510>, <ast.Constant object at 0x7da2044c3ac0>, <ast.Constant object at 0x7da2044c2710>, <ast.Constant object at 0x7da2044c24a0>, <ast.Constant object at 0x7da2044c22c0>, <ast.Constant object at 0x7da2044c2fb0>, <ast.Constant object at 0x7da2044c03a0>, <ast.Constant object at 0x7da2044c3d60>, <ast.Constant object at 0x7da2044c2110>, <ast.Constant object at 0x7da2044c0f70>]] variable[read_keys] assign[=] call[name[tmp_dict].keys, parameter[]] for taget[name[tmp_key]] in starred[name[read_keys]] begin[:] if compare[name[tmp_key] <ast.NotIn object at 0x7da2590d7190> name[valid_keys]] begin[:] call[name[print], parameter[constant[ERROR:]]] call[name[print], parameter[constant[grism...:], name[grism]]] call[name[print], parameter[constant[slitlet.:], name[tmp_slitlet]]] call[name[print], parameter[constant[date_obs:], name[tmp_dateobs]]] <ast.Raise object at 0x7da2041d9d50> for taget[name[tmp_key]] in starred[name[valid_keys]] begin[:] if compare[name[tmp_key] <ast.NotIn object at 0x7da2590d7190> name[read_keys]] begin[:] call[name[print], parameter[constant[ERROR:]]] call[name[print], parameter[constant[grism...:], name[grism]]] call[name[print], parameter[constant[slitlet.:], name[tmp_slitlet]]] call[name[print], parameter[constant[date_obs:], name[tmp_dateobs]]] <ast.Raise object at 0x7da2041da8f0> if compare[call[name[tmp_dict]][constant[boundary_xmax_lower]] less_or_equal[<=] call[name[tmp_dict]][constant[boundary_xmin_lower]]] begin[:] call[name[print], parameter[constant[ERROR:]]] call[name[print], parameter[constant[grism...:], name[grism]]] call[name[print], parameter[constant[slitlet.:], name[tmp_slitlet]]] call[name[print], parameter[constant[date_obs:], name[tmp_dateobs]]] call[name[print], parameter[constant[boundary_xmin_lower], call[name[tmp_dict]][constant[boundary_xmin_lower]]]] call[name[print], parameter[constant[boundary_xmax_lower], call[name[tmp_dict]][constant[boundary_xmax_lower]]]] <ast.Raise object at 0x7da2041d95d0> if compare[call[name[tmp_dict]][constant[boundary_xmax_upper]] less_or_equal[<=] call[name[tmp_dict]][constant[boundary_xmin_upper]]] begin[:] call[name[print], parameter[constant[ERROR:]]] call[name[print], parameter[constant[grism...:], name[grism]]] call[name[print], parameter[constant[slitlet.:], name[tmp_slitlet]]] call[name[print], parameter[constant[date_obs:], name[tmp_dateobs]]] call[name[print], parameter[constant[boundary_xmin_upper], call[name[tmp_dict]][constant[boundary_xmin_upper]]]] call[name[print], parameter[constant[boundary_xmax_upper], call[name[tmp_dict]][constant[boundary_xmax_upper]]]] <ast.Raise object at 0x7da207f01960> if name[first_dtu] begin[:] variable[first_dtu_configuration] assign[=] call[name[DtuConfiguration].define_from_dictionary, parameter[name[tmp_dict]]] variable[first_dtu] assign[=] constant[False] call[name[list_dtu_configurations].append, parameter[name[first_dtu_configuration]]] call[name[print], parameter[constant[* Integrity check OK!]]] variable[averaged_dtu_configuration] assign[=] call[name[average_dtu_configurations], parameter[name[list_dtu_configurations]]] variable[maxdiff_dtu_configuration] assign[=] call[name[maxdiff_dtu_configurations], parameter[name[list_dtu_configurations]]] return[tuple[[<ast.Name object at 0x7da1b26aeaa0>, <ast.Name object at 0x7da1b26ac670>]]]
keyword[def] identifier[integrity_check] ( identifier[bounddict] , identifier[max_dtu_offset] ): literal[string] keyword[if] literal[string] keyword[not] keyword[in] identifier[bounddict] . identifier[keys] (): keyword[raise] identifier[ValueError] ( literal[string] ) keyword[if] literal[string] keyword[not] keyword[in] identifier[bounddict] [ literal[string] ]. identifier[keys] (): keyword[raise] identifier[ValueError] ( literal[string] ) keyword[if] identifier[bounddict] [ literal[string] ][ literal[string] ]!= literal[string] : keyword[raise] identifier[ValueError] ( literal[string] ) identifier[grism] = identifier[bounddict] [ literal[string] ][ literal[string] ] identifier[print] ( literal[string] , identifier[grism] ) identifier[spfilter] = identifier[bounddict] [ literal[string] ][ literal[string] ] identifier[print] ( literal[string] , identifier[spfilter] ) identifier[valid_slitlets] =[ literal[string] + identifier[str] ( identifier[i] ). identifier[zfill] ( literal[int] ) keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] , identifier[EMIR_NBARS] + literal[int] )] identifier[read_slitlets] = identifier[list] ( identifier[bounddict] [ literal[string] ]. identifier[keys] ()) identifier[read_slitlets] . identifier[sort] () identifier[first_dtu] = keyword[True] identifier[first_dtu_configuration] = keyword[None] identifier[list_dtu_configurations] =[] keyword[for] identifier[tmp_slitlet] keyword[in] identifier[read_slitlets] : keyword[if] identifier[tmp_slitlet] keyword[not] keyword[in] identifier[valid_slitlets] : keyword[raise] identifier[ValueError] ( literal[string] + identifier[tmp_slitlet] ) identifier[read_dateobs] = identifier[list] ( identifier[bounddict] [ literal[string] ][ identifier[tmp_slitlet] ]. identifier[keys] ()) identifier[read_dateobs] . identifier[sort] () keyword[for] identifier[tmp_dateobs] keyword[in] identifier[read_dateobs] : keyword[try] : identifier[datetime] . identifier[strptime] ( identifier[tmp_dateobs] , literal[string] ) keyword[except] identifier[ValueError] : identifier[print] ( literal[string] + identifier[tmp_dateobs] ) keyword[raise] identifier[tmp_dict] = identifier[bounddict] [ literal[string] ][ identifier[tmp_slitlet] ][ identifier[tmp_dateobs] ] identifier[valid_keys] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ] identifier[read_keys] = identifier[tmp_dict] . identifier[keys] () keyword[for] identifier[tmp_key] keyword[in] identifier[read_keys] : keyword[if] identifier[tmp_key] keyword[not] keyword[in] identifier[valid_keys] : identifier[print] ( literal[string] ) identifier[print] ( literal[string] , identifier[grism] ) identifier[print] ( literal[string] , identifier[tmp_slitlet] ) identifier[print] ( literal[string] , identifier[tmp_dateobs] ) keyword[raise] identifier[ValueError] ( literal[string] + identifier[tmp_key] ) keyword[for] identifier[tmp_key] keyword[in] identifier[valid_keys] : keyword[if] identifier[tmp_key] keyword[not] keyword[in] identifier[read_keys] : identifier[print] ( literal[string] ) identifier[print] ( literal[string] , identifier[grism] ) identifier[print] ( literal[string] , identifier[tmp_slitlet] ) identifier[print] ( literal[string] , identifier[tmp_dateobs] ) keyword[raise] identifier[ValueError] ( literal[string] + identifier[tmp_key] + literal[string] ) keyword[if] identifier[tmp_dict] [ literal[string] ]<= identifier[tmp_dict] [ literal[string] ]: identifier[print] ( literal[string] ) identifier[print] ( literal[string] , identifier[grism] ) identifier[print] ( literal[string] , identifier[tmp_slitlet] ) identifier[print] ( literal[string] , identifier[tmp_dateobs] ) identifier[print] ( literal[string] , identifier[tmp_dict] [ literal[string] ]) identifier[print] ( literal[string] , identifier[tmp_dict] [ literal[string] ]) keyword[raise] identifier[ValueError] ( literal[string] literal[string] ) keyword[if] identifier[tmp_dict] [ literal[string] ]<= identifier[tmp_dict] [ literal[string] ]: identifier[print] ( literal[string] ) identifier[print] ( literal[string] , identifier[grism] ) identifier[print] ( literal[string] , identifier[tmp_slitlet] ) identifier[print] ( literal[string] , identifier[tmp_dateobs] ) identifier[print] ( literal[string] , identifier[tmp_dict] [ literal[string] ]) identifier[print] ( literal[string] , identifier[tmp_dict] [ literal[string] ]) keyword[raise] identifier[ValueError] ( literal[string] literal[string] ) keyword[if] identifier[first_dtu] : identifier[first_dtu_configuration] = identifier[DtuConfiguration] . identifier[define_from_dictionary] ( identifier[tmp_dict] ) identifier[first_dtu] = keyword[False] identifier[list_dtu_configurations] . identifier[append] ( identifier[first_dtu_configuration] ) keyword[else] : identifier[last_dtu_configuration] = identifier[DtuConfiguration] . identifier[define_from_dictionary] ( identifier[tmp_dict] ) keyword[if] keyword[not] identifier[first_dtu_configuration] . identifier[closeto] ( identifier[last_dtu_configuration] , identifier[abserror] = identifier[max_dtu_offset] ): identifier[print] ( literal[string] ) identifier[print] ( literal[string] , identifier[grism] ) identifier[print] ( literal[string] , identifier[tmp_slitlet] ) identifier[print] ( literal[string] , identifier[tmp_dateobs] ) identifier[print] ( literal[string] , identifier[first_dtu_configuration] ) identifier[print] ( literal[string] , identifier[last_dtu_configuration] ) keyword[raise] identifier[ValueError] ( literal[string] ) identifier[list_dtu_configurations] . identifier[append] ( identifier[last_dtu_configuration] ) identifier[print] ( literal[string] ) identifier[averaged_dtu_configuration] = identifier[average_dtu_configurations] ( identifier[list_dtu_configurations] ) identifier[maxdiff_dtu_configuration] = identifier[maxdiff_dtu_configurations] ( identifier[list_dtu_configurations] ) keyword[return] identifier[averaged_dtu_configuration] , identifier[maxdiff_dtu_configuration]
def integrity_check(bounddict, max_dtu_offset): """Integrity check of 'bounddict' content. Parameters ---------- bounddict : JSON structure Structure employed to store bounddict information. max_dtu_offset : float Maximum allowed difference in DTU location (mm) for each parameter """ if 'meta_info' not in bounddict.keys(): raise ValueError('"meta_info" not found in JSON file') # depends on [control=['if'], data=[]] if 'description' not in bounddict['meta_info'].keys(): raise ValueError('"description" not found in JSON file') # depends on [control=['if'], data=[]] if bounddict['meta_info']['description'] != 'slitlet boundaries from fits to continuum-lamp exposures': raise ValueError('Unexpected "description" in JSON file') # depends on [control=['if'], data=[]] grism = bounddict['tags']['grism'] print('>>> grism...:', grism) spfilter = bounddict['tags']['filter'] print('>>> filter..:', spfilter) valid_slitlets = ['slitlet' + str(i).zfill(2) for i in range(1, EMIR_NBARS + 1)] read_slitlets = list(bounddict['contents'].keys()) read_slitlets.sort() first_dtu = True first_dtu_configuration = None # avoid PyCharm warning list_dtu_configurations = [] for tmp_slitlet in read_slitlets: if tmp_slitlet not in valid_slitlets: raise ValueError('Unexpected slitlet key: ' + tmp_slitlet) # depends on [control=['if'], data=['tmp_slitlet']] # for each slitlet, check valid DATE-OBS (ISO 8601) read_dateobs = list(bounddict['contents'][tmp_slitlet].keys()) read_dateobs.sort() for tmp_dateobs in read_dateobs: try: datetime.strptime(tmp_dateobs, '%Y-%m-%dT%H:%M:%S.%f') # depends on [control=['try'], data=[]] except ValueError: print('Unexpected date_obs key: ' + tmp_dateobs) raise # depends on [control=['except'], data=[]] # for each DATE-OBS, check expected fields tmp_dict = bounddict['contents'][tmp_slitlet][tmp_dateobs] valid_keys = ['boundary_coef_lower', 'boundary_coef_upper', 'boundary_xmax_lower', 'boundary_xmax_upper', 'boundary_xmin_lower', 'boundary_xmin_upper', 'csu_bar_left', 'csu_bar_right', 'csu_bar_slit_center', 'csu_bar_slit_width', 'rotang', 'xdtu', 'xdtu_0', 'ydtu', 'ydtu_0', 'zdtu', 'zdtu_0', 'zzz_info1', 'zzz_info2'] read_keys = tmp_dict.keys() for tmp_key in read_keys: if tmp_key not in valid_keys: print('ERROR:') print('grism...:', grism) print('slitlet.:', tmp_slitlet) print('date_obs:', tmp_dateobs) raise ValueError('Unexpected key ' + tmp_key) # depends on [control=['if'], data=['tmp_key']] # depends on [control=['for'], data=['tmp_key']] for tmp_key in valid_keys: if tmp_key not in read_keys: print('ERROR:') print('grism...:', grism) print('slitlet.:', tmp_slitlet) print('date_obs:', tmp_dateobs) raise ValueError('Expected key ' + tmp_key + ' not found') # depends on [control=['if'], data=['tmp_key']] # depends on [control=['for'], data=['tmp_key']] if tmp_dict['boundary_xmax_lower'] <= tmp_dict['boundary_xmin_lower']: print('ERROR:') print('grism...:', grism) print('slitlet.:', tmp_slitlet) print('date_obs:', tmp_dateobs) print('boundary_xmin_lower', tmp_dict['boundary_xmin_lower']) print('boundary_xmax_lower', tmp_dict['boundary_xmax_lower']) raise ValueError('Unexpected boundary_xmax_lower <= boundary_xmin_lower') # depends on [control=['if'], data=[]] if tmp_dict['boundary_xmax_upper'] <= tmp_dict['boundary_xmin_upper']: print('ERROR:') print('grism...:', grism) print('slitlet.:', tmp_slitlet) print('date_obs:', tmp_dateobs) print('boundary_xmin_upper', tmp_dict['boundary_xmin_upper']) print('boundary_xmax_upper', tmp_dict['boundary_xmax_upper']) raise ValueError('Unexpected boundary_xmax_upper <= boundary_xmin_upper') # depends on [control=['if'], data=[]] if first_dtu: first_dtu_configuration = DtuConfiguration.define_from_dictionary(tmp_dict) first_dtu = False list_dtu_configurations.append(first_dtu_configuration) # depends on [control=['if'], data=[]] else: last_dtu_configuration = DtuConfiguration.define_from_dictionary(tmp_dict) if not first_dtu_configuration.closeto(last_dtu_configuration, abserror=max_dtu_offset): print('ERROR:') print('grism...:', grism) print('slitlet.:', tmp_slitlet) print('date_obs:', tmp_dateobs) print('First DTU configuration..:\n\t', first_dtu_configuration) print('Last DTU configuration...:\n\t', last_dtu_configuration) raise ValueError('Unexpected DTU configuration') # depends on [control=['if'], data=[]] list_dtu_configurations.append(last_dtu_configuration) # depends on [control=['for'], data=['tmp_dateobs']] # depends on [control=['for'], data=['tmp_slitlet']] print('* Integrity check OK!') averaged_dtu_configuration = average_dtu_configurations(list_dtu_configurations) maxdiff_dtu_configuration = maxdiff_dtu_configurations(list_dtu_configurations) return (averaged_dtu_configuration, maxdiff_dtu_configuration)
def _remove_vm(name, datacenter, service_instance, placement=None, power_off=None): ''' Helper function to remove a virtual machine name Name of the virtual machine service_instance vCenter service instance for connection and configuration datacenter Datacenter of the virtual machine placement Placement information of the virtual machine ''' results = {} if placement: (resourcepool_object, placement_object) = \ salt.utils.vmware.get_placement(service_instance, datacenter, placement) else: placement_object = salt.utils.vmware.get_datacenter(service_instance, datacenter) if power_off: power_off_vm(name, datacenter, service_instance) results['powered_off'] = True vm_ref = salt.utils.vmware.get_mor_by_property( service_instance, vim.VirtualMachine, name, property_name='name', container_ref=placement_object) if not vm_ref: raise salt.exceptions.VMwareObjectRetrievalError( 'The virtual machine object {0} in datacenter ' '{1} was not found'.format(name, datacenter)) return results, vm_ref
def function[_remove_vm, parameter[name, datacenter, service_instance, placement, power_off]]: constant[ Helper function to remove a virtual machine name Name of the virtual machine service_instance vCenter service instance for connection and configuration datacenter Datacenter of the virtual machine placement Placement information of the virtual machine ] variable[results] assign[=] dictionary[[], []] if name[placement] begin[:] <ast.Tuple object at 0x7da18eb56830> assign[=] call[name[salt].utils.vmware.get_placement, parameter[name[service_instance], name[datacenter], name[placement]]] if name[power_off] begin[:] call[name[power_off_vm], parameter[name[name], name[datacenter], name[service_instance]]] call[name[results]][constant[powered_off]] assign[=] constant[True] variable[vm_ref] assign[=] call[name[salt].utils.vmware.get_mor_by_property, parameter[name[service_instance], name[vim].VirtualMachine, name[name]]] if <ast.UnaryOp object at 0x7da1b26ae6e0> begin[:] <ast.Raise object at 0x7da1b26ae650> return[tuple[[<ast.Name object at 0x7da1b26ae9e0>, <ast.Name object at 0x7da1b26afd00>]]]
keyword[def] identifier[_remove_vm] ( identifier[name] , identifier[datacenter] , identifier[service_instance] , identifier[placement] = keyword[None] , identifier[power_off] = keyword[None] ): literal[string] identifier[results] ={} keyword[if] identifier[placement] : ( identifier[resourcepool_object] , identifier[placement_object] )= identifier[salt] . identifier[utils] . identifier[vmware] . identifier[get_placement] ( identifier[service_instance] , identifier[datacenter] , identifier[placement] ) keyword[else] : identifier[placement_object] = identifier[salt] . identifier[utils] . identifier[vmware] . identifier[get_datacenter] ( identifier[service_instance] , identifier[datacenter] ) keyword[if] identifier[power_off] : identifier[power_off_vm] ( identifier[name] , identifier[datacenter] , identifier[service_instance] ) identifier[results] [ literal[string] ]= keyword[True] identifier[vm_ref] = identifier[salt] . identifier[utils] . identifier[vmware] . identifier[get_mor_by_property] ( identifier[service_instance] , identifier[vim] . identifier[VirtualMachine] , identifier[name] , identifier[property_name] = literal[string] , identifier[container_ref] = identifier[placement_object] ) keyword[if] keyword[not] identifier[vm_ref] : keyword[raise] identifier[salt] . identifier[exceptions] . identifier[VMwareObjectRetrievalError] ( literal[string] literal[string] . identifier[format] ( identifier[name] , identifier[datacenter] )) keyword[return] identifier[results] , identifier[vm_ref]
def _remove_vm(name, datacenter, service_instance, placement=None, power_off=None): """ Helper function to remove a virtual machine name Name of the virtual machine service_instance vCenter service instance for connection and configuration datacenter Datacenter of the virtual machine placement Placement information of the virtual machine """ results = {} if placement: (resourcepool_object, placement_object) = salt.utils.vmware.get_placement(service_instance, datacenter, placement) # depends on [control=['if'], data=[]] else: placement_object = salt.utils.vmware.get_datacenter(service_instance, datacenter) if power_off: power_off_vm(name, datacenter, service_instance) results['powered_off'] = True # depends on [control=['if'], data=[]] vm_ref = salt.utils.vmware.get_mor_by_property(service_instance, vim.VirtualMachine, name, property_name='name', container_ref=placement_object) if not vm_ref: raise salt.exceptions.VMwareObjectRetrievalError('The virtual machine object {0} in datacenter {1} was not found'.format(name, datacenter)) # depends on [control=['if'], data=[]] return (results, vm_ref)
def cpt2seg(file_name, sym=False, discrete=False): """Reads a .cpt palette and returns a segmented colormap. sym : If True, the returned colormap contains the palette and a mirrored copy. For example, a blue-red-green palette would return a blue-red-green-green-red-blue colormap. discrete : If true, the returned colormap has a fixed number of uniform colors. That is, colors are not interpolated to form a continuous range. Example : >>> _palette_data = cpt2seg('palette.cpt') >>> palette = matplotlib.colors.LinearSegmentedColormap('palette', _palette_data, 100) >>> imshow(X, cmap=palette) """ dic = {} # io # f = scipy.io.open(file_name, 'r') # rgb = f.read_array(f) #Check flags: # with open(file_name) as f: # content = f.readlines() # header=np.where(np.array([c.startswith('#') for c in content]))[0][-1] # footer=np.where(np.array([c[0].isalpha() for c in content]))[0][0] rgb = np.genfromtxt(file_name,comments='#',invalid_raise=False) # rgb = np.genfromtxt(file_name) rgb = rgb/255. s = shape(rgb) colors = ['red', 'green', 'blue'] for c in colors: i = colors.index(c) x = rgb[:, i+1] if discrete: if sym: dic[c] = zeros((2*s[0]+1, 3), dtype=Float) dic[c][:,0] = linspace(0,1,2*s[0]+1) vec = concatenate((x ,x[::-1])) else: dic[c] = zeros((s[0]+1, 3), dtype=Float) dic[c][:,0] = linspace(0,1,s[0]+1) vec = x dic[c][1:, 1] = vec dic[c][:-1,2] = vec else: if sym: dic[c] = zeros((2*s[0], 3), dtype=Float) dic[c][:,0] = linspace(0,1,2*s[0]) vec = concatenate((x ,x[::-1])) else: dic[c] = zeros((s[0], 3), dtype=Float) dic[c][:,0] = linspace(0,1,s[0]) vec = x dic[c][:, 1] = vec dic[c][:, 2] = vec return dic
def function[cpt2seg, parameter[file_name, sym, discrete]]: constant[Reads a .cpt palette and returns a segmented colormap. sym : If True, the returned colormap contains the palette and a mirrored copy. For example, a blue-red-green palette would return a blue-red-green-green-red-blue colormap. discrete : If true, the returned colormap has a fixed number of uniform colors. That is, colors are not interpolated to form a continuous range. Example : >>> _palette_data = cpt2seg('palette.cpt') >>> palette = matplotlib.colors.LinearSegmentedColormap('palette', _palette_data, 100) >>> imshow(X, cmap=palette) ] variable[dic] assign[=] dictionary[[], []] variable[rgb] assign[=] call[name[np].genfromtxt, parameter[name[file_name]]] variable[rgb] assign[=] binary_operation[name[rgb] / constant[255.0]] variable[s] assign[=] call[name[shape], parameter[name[rgb]]] variable[colors] assign[=] list[[<ast.Constant object at 0x7da1b0abbf40>, <ast.Constant object at 0x7da1b0abb820>, <ast.Constant object at 0x7da1b0abb580>]] for taget[name[c]] in starred[name[colors]] begin[:] variable[i] assign[=] call[name[colors].index, parameter[name[c]]] variable[x] assign[=] call[name[rgb]][tuple[[<ast.Slice object at 0x7da1b0aba890>, <ast.BinOp object at 0x7da1b0ab8b20>]]] if name[discrete] begin[:] if name[sym] begin[:] call[name[dic]][name[c]] assign[=] call[name[zeros], parameter[tuple[[<ast.BinOp object at 0x7da1b0ab92d0>, <ast.Constant object at 0x7da1b0ab80d0>]]]] call[call[name[dic]][name[c]]][tuple[[<ast.Slice object at 0x7da1b0ab8d30>, <ast.Constant object at 0x7da204622620>]]] assign[=] call[name[linspace], parameter[constant[0], constant[1], binary_operation[binary_operation[constant[2] * call[name[s]][constant[0]]] + constant[1]]]] variable[vec] assign[=] call[name[concatenate], parameter[tuple[[<ast.Name object at 0x7da204623df0>, <ast.Subscript object at 0x7da204620d00>]]]] call[call[name[dic]][name[c]]][tuple[[<ast.Slice object at 0x7da18f722470>, <ast.Constant object at 0x7da18f723880>]]] assign[=] name[vec] call[call[name[dic]][name[c]]][tuple[[<ast.Slice object at 0x7da18f723d30>, <ast.Constant object at 0x7da18f723850>]]] assign[=] name[vec] return[name[dic]]
keyword[def] identifier[cpt2seg] ( identifier[file_name] , identifier[sym] = keyword[False] , identifier[discrete] = keyword[False] ): literal[string] identifier[dic] ={} identifier[rgb] = identifier[np] . identifier[genfromtxt] ( identifier[file_name] , identifier[comments] = literal[string] , identifier[invalid_raise] = keyword[False] ) identifier[rgb] = identifier[rgb] / literal[int] identifier[s] = identifier[shape] ( identifier[rgb] ) identifier[colors] =[ literal[string] , literal[string] , literal[string] ] keyword[for] identifier[c] keyword[in] identifier[colors] : identifier[i] = identifier[colors] . identifier[index] ( identifier[c] ) identifier[x] = identifier[rgb] [:, identifier[i] + literal[int] ] keyword[if] identifier[discrete] : keyword[if] identifier[sym] : identifier[dic] [ identifier[c] ]= identifier[zeros] (( literal[int] * identifier[s] [ literal[int] ]+ literal[int] , literal[int] ), identifier[dtype] = identifier[Float] ) identifier[dic] [ identifier[c] ][:, literal[int] ]= identifier[linspace] ( literal[int] , literal[int] , literal[int] * identifier[s] [ literal[int] ]+ literal[int] ) identifier[vec] = identifier[concatenate] (( identifier[x] , identifier[x] [::- literal[int] ])) keyword[else] : identifier[dic] [ identifier[c] ]= identifier[zeros] (( identifier[s] [ literal[int] ]+ literal[int] , literal[int] ), identifier[dtype] = identifier[Float] ) identifier[dic] [ identifier[c] ][:, literal[int] ]= identifier[linspace] ( literal[int] , literal[int] , identifier[s] [ literal[int] ]+ literal[int] ) identifier[vec] = identifier[x] identifier[dic] [ identifier[c] ][ literal[int] :, literal[int] ]= identifier[vec] identifier[dic] [ identifier[c] ][:- literal[int] , literal[int] ]= identifier[vec] keyword[else] : keyword[if] identifier[sym] : identifier[dic] [ identifier[c] ]= identifier[zeros] (( literal[int] * identifier[s] [ literal[int] ], literal[int] ), identifier[dtype] = identifier[Float] ) identifier[dic] [ identifier[c] ][:, literal[int] ]= identifier[linspace] ( literal[int] , literal[int] , literal[int] * identifier[s] [ literal[int] ]) identifier[vec] = identifier[concatenate] (( identifier[x] , identifier[x] [::- literal[int] ])) keyword[else] : identifier[dic] [ identifier[c] ]= identifier[zeros] (( identifier[s] [ literal[int] ], literal[int] ), identifier[dtype] = identifier[Float] ) identifier[dic] [ identifier[c] ][:, literal[int] ]= identifier[linspace] ( literal[int] , literal[int] , identifier[s] [ literal[int] ]) identifier[vec] = identifier[x] identifier[dic] [ identifier[c] ][:, literal[int] ]= identifier[vec] identifier[dic] [ identifier[c] ][:, literal[int] ]= identifier[vec] keyword[return] identifier[dic]
def cpt2seg(file_name, sym=False, discrete=False): """Reads a .cpt palette and returns a segmented colormap. sym : If True, the returned colormap contains the palette and a mirrored copy. For example, a blue-red-green palette would return a blue-red-green-green-red-blue colormap. discrete : If true, the returned colormap has a fixed number of uniform colors. That is, colors are not interpolated to form a continuous range. Example : >>> _palette_data = cpt2seg('palette.cpt') >>> palette = matplotlib.colors.LinearSegmentedColormap('palette', _palette_data, 100) >>> imshow(X, cmap=palette) """ dic = {} # io # f = scipy.io.open(file_name, 'r') # rgb = f.read_array(f) #Check flags: # with open(file_name) as f: # content = f.readlines() # header=np.where(np.array([c.startswith('#') for c in content]))[0][-1] # footer=np.where(np.array([c[0].isalpha() for c in content]))[0][0] rgb = np.genfromtxt(file_name, comments='#', invalid_raise=False) # rgb = np.genfromtxt(file_name) rgb = rgb / 255.0 s = shape(rgb) colors = ['red', 'green', 'blue'] for c in colors: i = colors.index(c) x = rgb[:, i + 1] if discrete: if sym: dic[c] = zeros((2 * s[0] + 1, 3), dtype=Float) dic[c][:, 0] = linspace(0, 1, 2 * s[0] + 1) vec = concatenate((x, x[::-1])) # depends on [control=['if'], data=[]] else: dic[c] = zeros((s[0] + 1, 3), dtype=Float) dic[c][:, 0] = linspace(0, 1, s[0] + 1) vec = x dic[c][1:, 1] = vec dic[c][:-1, 2] = vec # depends on [control=['if'], data=[]] else: if sym: dic[c] = zeros((2 * s[0], 3), dtype=Float) dic[c][:, 0] = linspace(0, 1, 2 * s[0]) vec = concatenate((x, x[::-1])) # depends on [control=['if'], data=[]] else: dic[c] = zeros((s[0], 3), dtype=Float) dic[c][:, 0] = linspace(0, 1, s[0]) vec = x dic[c][:, 1] = vec dic[c][:, 2] = vec # depends on [control=['for'], data=['c']] return dic
def ls(self, files, silent=True, exclude_deleted=False): """List files :param files: Perforce file spec :type files: list :param silent: Will not raise error for invalid files or files not under the client :type silent: bool :param exclude_deleted: Exclude deleted files from the query :type exclude_deleted: bool :raises: :class:`.errors.RevisionError` :returns: list<:class:`.Revision`> """ try: cmd = ['fstat'] if exclude_deleted: cmd += ['-F', '^headAction=delete ^headAction=move/delete'] cmd += files results = self.run(cmd) except errors.CommandError as err: if silent: results = [] elif "is not under client's root" in str(err): raise errors.RevisionError(err.args[0]) else: raise return [Revision(r, self) for r in results if r.get('code') != 'error']
def function[ls, parameter[self, files, silent, exclude_deleted]]: constant[List files :param files: Perforce file spec :type files: list :param silent: Will not raise error for invalid files or files not under the client :type silent: bool :param exclude_deleted: Exclude deleted files from the query :type exclude_deleted: bool :raises: :class:`.errors.RevisionError` :returns: list<:class:`.Revision`> ] <ast.Try object at 0x7da1b245b2b0> return[<ast.ListComp object at 0x7da2054a6620>]
keyword[def] identifier[ls] ( identifier[self] , identifier[files] , identifier[silent] = keyword[True] , identifier[exclude_deleted] = keyword[False] ): literal[string] keyword[try] : identifier[cmd] =[ literal[string] ] keyword[if] identifier[exclude_deleted] : identifier[cmd] +=[ literal[string] , literal[string] ] identifier[cmd] += identifier[files] identifier[results] = identifier[self] . identifier[run] ( identifier[cmd] ) keyword[except] identifier[errors] . identifier[CommandError] keyword[as] identifier[err] : keyword[if] identifier[silent] : identifier[results] =[] keyword[elif] literal[string] keyword[in] identifier[str] ( identifier[err] ): keyword[raise] identifier[errors] . identifier[RevisionError] ( identifier[err] . identifier[args] [ literal[int] ]) keyword[else] : keyword[raise] keyword[return] [ identifier[Revision] ( identifier[r] , identifier[self] ) keyword[for] identifier[r] keyword[in] identifier[results] keyword[if] identifier[r] . identifier[get] ( literal[string] )!= literal[string] ]
def ls(self, files, silent=True, exclude_deleted=False): """List files :param files: Perforce file spec :type files: list :param silent: Will not raise error for invalid files or files not under the client :type silent: bool :param exclude_deleted: Exclude deleted files from the query :type exclude_deleted: bool :raises: :class:`.errors.RevisionError` :returns: list<:class:`.Revision`> """ try: cmd = ['fstat'] if exclude_deleted: cmd += ['-F', '^headAction=delete ^headAction=move/delete'] # depends on [control=['if'], data=[]] cmd += files results = self.run(cmd) # depends on [control=['try'], data=[]] except errors.CommandError as err: if silent: results = [] # depends on [control=['if'], data=[]] elif "is not under client's root" in str(err): raise errors.RevisionError(err.args[0]) # depends on [control=['if'], data=[]] else: raise # depends on [control=['except'], data=['err']] return [Revision(r, self) for r in results if r.get('code') != 'error']
def wanmen_download_by_course(json_api_content, output_dir='.', merge=True, info_only=False, **kwargs): """int->None Download a WHOLE course. Reuse the API call to save time.""" for tIndex in range(len(json_api_content[0]['Topics'])): for pIndex in range(len(json_api_content[0]['Topics'][tIndex]['Parts'])): wanmen_download_by_course_topic_part(json_api_content, tIndex, pIndex, output_dir=output_dir, merge=merge, info_only=info_only, **kwargs)
def function[wanmen_download_by_course, parameter[json_api_content, output_dir, merge, info_only]]: constant[int->None Download a WHOLE course. Reuse the API call to save time.] for taget[name[tIndex]] in starred[call[name[range], parameter[call[name[len], parameter[call[call[name[json_api_content]][constant[0]]][constant[Topics]]]]]]] begin[:] for taget[name[pIndex]] in starred[call[name[range], parameter[call[name[len], parameter[call[call[call[call[name[json_api_content]][constant[0]]][constant[Topics]]][name[tIndex]]][constant[Parts]]]]]]] begin[:] call[name[wanmen_download_by_course_topic_part], parameter[name[json_api_content], name[tIndex], name[pIndex]]]
keyword[def] identifier[wanmen_download_by_course] ( identifier[json_api_content] , identifier[output_dir] = literal[string] , identifier[merge] = keyword[True] , identifier[info_only] = keyword[False] ,** identifier[kwargs] ): literal[string] keyword[for] identifier[tIndex] keyword[in] identifier[range] ( identifier[len] ( identifier[json_api_content] [ literal[int] ][ literal[string] ])): keyword[for] identifier[pIndex] keyword[in] identifier[range] ( identifier[len] ( identifier[json_api_content] [ literal[int] ][ literal[string] ][ identifier[tIndex] ][ literal[string] ])): identifier[wanmen_download_by_course_topic_part] ( identifier[json_api_content] , identifier[tIndex] , identifier[pIndex] , identifier[output_dir] = identifier[output_dir] , identifier[merge] = identifier[merge] , identifier[info_only] = identifier[info_only] , ** identifier[kwargs] )
def wanmen_download_by_course(json_api_content, output_dir='.', merge=True, info_only=False, **kwargs): """int->None Download a WHOLE course. Reuse the API call to save time.""" for tIndex in range(len(json_api_content[0]['Topics'])): for pIndex in range(len(json_api_content[0]['Topics'][tIndex]['Parts'])): wanmen_download_by_course_topic_part(json_api_content, tIndex, pIndex, output_dir=output_dir, merge=merge, info_only=info_only, **kwargs) # depends on [control=['for'], data=['pIndex']] # depends on [control=['for'], data=['tIndex']]
def Enable(self, value): "enable or disable all top menus" for i in range(self.GetMenuCount()): self.EnableTop(i, value)
def function[Enable, parameter[self, value]]: constant[enable or disable all top menus] for taget[name[i]] in starred[call[name[range], parameter[call[name[self].GetMenuCount, parameter[]]]]] begin[:] call[name[self].EnableTop, parameter[name[i], name[value]]]
keyword[def] identifier[Enable] ( identifier[self] , identifier[value] ): literal[string] keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[self] . identifier[GetMenuCount] ()): identifier[self] . identifier[EnableTop] ( identifier[i] , identifier[value] )
def Enable(self, value): """enable or disable all top menus""" for i in range(self.GetMenuCount()): self.EnableTop(i, value) # depends on [control=['for'], data=['i']]