blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
69
license_type
stringclasses
2 values
repo_name
stringlengths
5
118
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
63
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
2.91k
686M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
213 values
src_encoding
stringclasses
30 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
2
10.3M
extension
stringclasses
246 values
content
stringlengths
2
10.3M
authors
listlengths
1
1
author_id
stringlengths
0
212
06659e0120fe341e4324f996fe0a30551303f6f1
a663eb28d9c5e05d505a94aba511649b68e951cf
/pytype/constant_folding.py
5873a1aad6ba2dda15ba79caa2491b7feefed22d
[ "Apache-2.0", "MIT" ]
permissive
CyberFlameGO/pytype
603240757291e066aad4259ce0b93221d90a4710
c8cbeea997634455b5abcb27c76c58aa0dfc25ae
refs/heads/master
2023-07-02T14:39:55.343774
2021-08-06T21:55:02
2021-08-06T21:55:02
393,544,239
0
0
NOASSERTION
2021-08-07T01:12:39
2021-08-07T01:10:49
null
UTF-8
Python
false
false
14,305
py
"""Constant folding optimisation for bytecode. This optimisation adds a new pseudo-opcode, LOAD_FOLDED_CONST, which encodes the type of a complex literal constant in its `arg` field, in a "typestruct" format described below. There is a corresponding function, build_folded_type, which constructs a vm type from the encoded typestruct. The type structure stored in LOAD_FOLDED_CONST is an immutable (for easy hashing) tree with the following elements: ('prim', <python type>) : a primitive type, e.g. ('prim', str) (tag, types) : a collection type; 'types' represent the type params frozenset(types): a union of types tag = prim | tuple | list | map | set the types python supports for a literal constant types = a tuple of type | frozenset(types) where the size of the tuple depends on the tag, e.g ('map', (k, v)) For ease of testing and debugging there is also a simplified literal syntax to construct and examine these typestructs, see constant_folding_test for examples. This is less uniform, and therefore not recommended to use other than for input/output. """ from typing import Any, Dict, FrozenSet, Tuple import attr from pytype.pyc import loadmarshal from pytype.pyc import opcodes from pytype.pyc import pyc # Copied from typegraph/cfg.py # If we have more than 64 elements in a map/list, the type variable accumulates # too many bindings and falls back to Any. So if we find a constant with too # many elements, we go directly to constructing an abstract type, and do not # attempt to track keys/element positions. MAX_VAR_SIZE = 64 # We track constants at three levels: # typ: A typestruct representing the abstract type of the constant # elements: A list or map of top-level types # value: The concrete python value # # 'elements' is an intermediate structure that tracks individual folded # constants for every element in a map or list. So e.g. for the constant # {'x': [1, 2], 'y': 3} # we would have # typ = ('map', {str}, {('list', {int}), int}) # value = {'x': [1, 2], 'y': 3} # elements = {'x': <<[1, 2]>>, 'y': <<3>>} # where <<x>> is the folded constant corresponding to x. This lets us # short-circuit pyval tracking at any level in the structure and fall back to # abstract types. # # Note that while we could in theory just track the python value, and then # construct 'typ' and 'elements' at the end, that would mean recursively # unfolding a structure that we have just folded; the code is simpler if we # track elements and types at every stage. @attr.s(auto_attribs=True) class _Constant: """A folded python constant.""" typ: Tuple[str, Any] value: Any elements: Any op: opcodes.Opcode @property def tag(self): return self.typ[0] @attr.s(auto_attribs=True) class _Collection: """A linear collection (e.g. list, tuple, set).""" types: FrozenSet[Any] values: Tuple[Any, ...] elements: Tuple[Any, ...] @attr.s(auto_attribs=True) class _Map: """A dictionary.""" key_types: FrozenSet[Any] keys: Tuple[Any, ...] value_types: FrozenSet[Any] values: Tuple[Any, ...] elements: Dict[Any, Any] class _CollectionBuilder: """Build up a collection of constants.""" def __init__(self): self.types = set() self.values = [] self.elements = [] def add(self, constant): self.types.add(constant.typ) self.elements.append(constant) self.values.append(constant.value) def build(self): return _Collection( types=frozenset(self.types), values=tuple(reversed(self.values)), elements=tuple(reversed(self.elements))) class _MapBuilder: """Build up a map of constants.""" def __init__(self): self.key_types = set() self.value_types = set() self.keys = [] self.values = [] self.elements = {} def add(self, key, value): self.key_types.add(key.typ) self.value_types.add(value.typ) self.keys.append(key.value) self.values.append(value.value) self.elements[key.value] = value def build(self): return _Map( key_types=frozenset(self.key_types), keys=tuple(reversed(self.keys)), value_types=frozenset(self.value_types), values=tuple(reversed(self.values)), elements=self.elements) class _Stack: """A simple opcode stack.""" def __init__(self): self.stack = [] self.consts = {} def __iter__(self): return self.stack.__iter__() def push(self, val): self.stack.append(val) def pop(self): return self.stack.pop() def _preserve_constant(self, c): if c and ( not isinstance(c.op, opcodes.LOAD_CONST) or isinstance(c.op, opcodes.BUILD_STRING)): self.consts[id(c.op)] = c def clear(self): # Preserve any constants in the stack before clearing it. for c in self.stack: self._preserve_constant(c) self.stack = [] def _pop_args(self, n): """Try to get n args off the stack for a BUILD call.""" if len(self.stack) < n: # We have started a new block in the middle of constructing a literal # (e.g. due to an inline function call). Clear the stack, since the # literal is not constant. self.clear() return None elif any(x is None for x in self.stack[-n:]): # We have something other than constants in the arg list. Pop all the args # for this op off the stack, preserving constants. for _ in range(n): self._preserve_constant(self.pop()) return None else: return [self.pop() for _ in range(n)] def fold_args(self, n, op): """Collect the arguments to a build call.""" ret = _CollectionBuilder() args = self._pop_args(n) if not args: self.push(None) return None for elt in args: ret.add(elt) elt.op.folded = op return ret.build() def fold_map_args(self, n, op): """Collect the arguments to a BUILD_MAP call.""" ret = _MapBuilder() args = self._pop_args(2 * n) if not args: self.push(None) return None for i in range(0, 2 * n, 2): v_elt, k_elt = args[i], args[i + 1] ret.add(k_elt, v_elt) k_elt.op.folded = op v_elt.op.folded = op return ret.build() def build_str(self, n, op): ret = self.fold_args(n, op) if ret: self.push(_Constant(('prim', str), '', None, op)) else: self.push(None) def build(self, python_type, op): collection = self.fold_args(op.arg, op) if collection: typename = python_type.__name__ typ = (typename, collection.types) value = python_type(collection.values) elements = collection.elements self.push(_Constant(typ, value, elements, op)) class _FoldedOps: """Mapping from a folded opcode to the top level constant that replaces it.""" def __init__(self): self.folds = {} def add(self, op): self.folds[id(op)] = op.folded def resolve(self, op): f = op while id(f) in self.folds: f = self.folds[id(f)] return f class _FoldConstants: """Fold constant literals in pyc code.""" def visit_code(self, code): """Visit code, folding literals.""" def build_tuple(tup): out = [] for e in tup: if isinstance(e, tuple): out.append(build_tuple(e)) else: out.append(('prim', type(e))) return ('tuple', tuple(out)) folds = _FoldedOps() for block in code.order: stack = _Stack() for op in block: if isinstance(op, opcodes.LOAD_CONST): elt = code.co_consts[op.arg] if isinstance(elt, tuple): typ = build_tuple(elt) stack.push(_Constant(typ, elt, typ[1], op)) else: stack.push(_Constant(('prim', type(elt)), elt, None, op)) elif isinstance(op, opcodes.BUILD_LIST): stack.build(list, op) elif isinstance(op, opcodes.BUILD_SET): stack.build(set, op) elif isinstance(op, opcodes.FORMAT_VALUE): if op.arg & loadmarshal.FVS_MASK: stack.pop() stack.build_str(1, op) elif isinstance(op, opcodes.BUILD_STRING): stack.build_str(op.arg, op) elif isinstance(op, opcodes.BUILD_MAP): map_ = stack.fold_map_args(op.arg, op) if map_: typ = ('map', (map_.key_types, map_.value_types)) val = dict(zip(map_.keys, map_.values)) stack.push(_Constant(typ, val, map_.elements, op)) elif isinstance(op, opcodes.BUILD_CONST_KEY_MAP): keys = stack.pop() vals = stack.fold_args(op.arg, op) if vals: keys.op.folded = op _, t = keys.typ typ = ('map', (frozenset(t), vals.types)) val = dict(zip(keys.value, vals.values)) elements = dict(zip(keys.value, vals.elements)) stack.push(_Constant(typ, val, elements, op)) else: # If we hit any other bytecode, we are no longer building a literal # constant. Insert a None as a sentinel to the next BUILD op to # not fold itself. stack.push(None) # Clear the stack to save any folded constants before exiting the block stack.clear() # Now rewrite the block to replace folded opcodes with a single # LOAD_FOLDED_CONSTANT opcode. out = [] for op in block: if id(op) in stack.consts: t = stack.consts[id(op)] arg = t pretty_arg = t o = opcodes.LOAD_FOLDED_CONST(op.index, op.line, arg, pretty_arg) o.next = op.next o.target = op.target o.block_target = op.block_target op.folded = o folds.add(op) out.append(o) elif op.folded: folds.add(op) else: out.append(op) block.code = out # Adjust 'next' and 'target' pointers to account for folding. for op in code.code_iter: if op.next: op.next = folds.resolve(op.next) if op.target: op.target = folds.resolve(op.target) return code def to_literal(typ, always_tuple=False): """Convert a typestruct item to a simplified form for ease of use.""" def expand(params): return (to_literal(x) for x in params) def union(params): ret = tuple(sorted(expand(params), key=str)) if len(ret) == 1 and not always_tuple: ret, = ret # pylint: disable=self-assigning-variable return ret tag, params = typ if tag == 'prim': return params elif tag == 'tuple': vals = tuple(expand(params)) return (tag, *vals) elif tag == 'map': k, v = params return (tag, union(k), union(v)) else: return (tag, union(params)) def from_literal(tup): """Convert from simple literal form to the more uniform typestruct.""" def expand(vals): return [from_literal(x) for x in vals] def union(vals): if not isinstance(vals, tuple): vals = (vals,) v = expand(vals) return frozenset(v) if not isinstance(tup, tuple): return ('prim', tup) elif isinstance(tup[0], str): tag, *vals = tup if tag == 'prim': return tup elif tag == 'tuple': params = tuple(expand(vals)) return (tag, params) elif tag == 'map': k, v = vals return (tag, (union(k), union(v))) else: vals, = vals # pylint: disable=self-assigning-variable return (tag, union(vals)) else: return tuple(expand(tup)) def optimize(code): """Fold all constant literals in the bytecode into LOAD_FOLDED_CONST ops.""" return pyc.visit(code, _FoldConstants()) def build_folded_type(vm, state, const): """Convert a typestruct to a vm type.""" def typeconst(t): """Create a constant purely to hold types for a recursive call.""" return _Constant(t, None, None, const.op) def build_pyval(state, const): if const.value is not None and const.tag in ('prim', 'tuple'): return state, vm.convert.constant_to_var(const.value) else: return build_folded_type(vm, state, const) def expand(state, elements): vs = [] for e in elements: state, v = build_pyval(state, e) vs.append(v) return state, vs def join_types(state, ts): xs = [typeconst(t) for t in ts] state, vs = expand(state, xs) val = vm.convert.build_content(vs) return state, val def collect(state, convert_type, params): state, t = join_types(state, params) ret = vm.convert.build_collection_of_type(state.node, convert_type, t) return state, ret def collect_tuple(state, elements): state, vs = expand(state, elements) return state, vm.convert.build_tuple(state.node, vs) def collect_list(state, params, elements): if elements is not None and len(elements) < MAX_VAR_SIZE: state, vs = expand(state, elements) return state, vm.convert.build_list(state.node, vs) else: return collect(state, vm.convert.list_type, params) def collect_map(state, params, elements): m = vm.convert.build_map(state.node) if elements is not None and len(elements) < MAX_VAR_SIZE: for (k, v) in elements.items(): k = vm.convert.constant_to_var(k) state, v = build_pyval(state, v) state = vm.store_subscr(state, m, k, v) else: k_types, v_types = params state, v = join_types(state, v_types) for t in k_types: state, k = build_folded_type(vm, state, typeconst(t)) state = vm.store_subscr(state, m, k, v) return state, m tag, params = const.typ if tag == 'prim': if const.value: return state, vm.convert.constant_to_var(const.value) else: val = vm.convert.primitive_class_instances[params] return state, val.to_variable(state.node) elif tag == 'list': return collect_list(state, params, const.elements) elif tag == 'set': return collect(state, vm.convert.set_type, params) elif tag == 'tuple': # If we get a tuple without const.elements, construct it from the type. # (e.g. this happens with a large dict with tuple keys) if not const.elements: elts = tuple(typeconst(t) for t in params) else: elts = const.elements return collect_tuple(state, elts) elif tag == 'map': return collect_map(state, params, const.elements) else: assert False, ('Unexpected type tag:', const.typ)
[ "rechen@google.com" ]
rechen@google.com
47271b52662a9586836d4b8ea903135c04084971
b320c665814aff4e705c7302eef4c43689cf037d
/test/vector_mediator/herwig4dm/KKpi.py
7a051efef428f4729535c84b298ca282f2cb85e4
[ "MIT" ]
permissive
LoganAMorrison/Hazma
a393d92a10c677e3ee6db83172c6fa8010f3d975
a40ffd3e5643303bb535d9b487faf201450ff4e9
refs/heads/master
2022-12-05T20:10:20.169282
2022-12-03T23:31:22
2022-12-03T23:31:22
113,697,781
12
2
MIT
2019-11-21T16:36:22
2017-12-09T20:06:27
Jupyter Notebook
UTF-8
Python
false
false
3,365
py
# Libraries to load import matplotlib.pyplot as plt from . import FKKpi, FPhiPi analyses = {} br00 = 0.342 brpp = 0.489 xSM = [] ySM_0 = [] ySM_1 = [] ySM_2 = [] xDP = [] yDP_0 = [] yDP_1 = [] yDP_2 = [] xBL = [] yBL_0 = [] yBL_1 = [] yBL_2 = [] # energy range low_lim = 1.21 upp_lim = 3.0 FKKpi.readHadronic_Current() # SM case scale = low_lim while scale < upp_lim: Q2 = scale ** 2 xSM.append(scale) ySM_0.append(FKKpi.sigmaSM(Q2, 0)) ySM_1.append(FKKpi.sigmaSM(Q2, 1) + br00 * FPhiPi.sigmaSMPhiPi(Q2)) ySM_2.append(FKKpi.sigmaSM(Q2, 2) + brpp * FPhiPi.sigmaSMPhiPi(Q2)) scale += 0.01 # set DM parameters # DM to mediator coupling gDM = 1.0 # DM mass mDM = 1.21 / 2 # mediator mass mMed = 10.0 # mediator width, file with total width will be added (work in progress) # wMed # Dark Photon case # couplings of mediator to quarks cMed_u = 2.0 / 3.0 cMed_d = -1.0 / 3.0 cMed_s = -1.0 / 3.0 # FKKpi.resetParameters(gDM,0.,0.,0.,cMed_u,cMed_d,cMed_s) while mDM < 2.0: energy = 2 * mDM + 0.0001 Q2 = energy ** 2 xDP.append(energy) wMed_0 = FKKpi.GammaDM(mMed, 0) FKKpi.resetParameters(gDM, mDM, mMed, wMed_0, cMed_u, cMed_d, cMed_s) yDP_0.append(FKKpi.sigmaDM(Q2, 0)) wMed_1 = FKKpi.GammaDM(mMed, 1) FKKpi.resetParameters(gDM, mDM, mMed, wMed_1, cMed_u, cMed_d, cMed_s) yDP_1.append(FKKpi.sigmaDM(Q2, 1)) wMed_2 = FKKpi.GammaDM(mMed, 2) FKKpi.resetParameters(gDM, mDM, mMed, wMed_2, cMed_u, cMed_d, cMed_s) yDP_2.append(FKKpi.sigmaDM(Q2, 2)) mDM += 0.05 # B-L model # couplings of mediator to quarks cMed_u = 1.0 / 3.0 cMed_d = 1.0 / 3.0 cMed_s = 1.0 / 3.0 # reset DM mass mDM = 1.21 / 2 # FKKpi.resetParameters(gDM,0.,0.,0.,cMed_u,cMed_d,cMed_s) while mDM < 2.0: energy = 2 * mDM + 0.0001 Q2 = energy ** 2 xBL.append(energy) wMed_0 = FKKpi.GammaDM(mMed, 0) FKKpi.resetParameters(gDM, mDM, mMed, wMed_0, cMed_u, cMed_d, cMed_s) yBL_0.append(FKKpi.sigmaDM(Q2, 0)) wMed_1 = FKKpi.GammaDM(mMed, 1) FKKpi.resetParameters(gDM, mDM, mMed, wMed_1, cMed_u, cMed_d, cMed_s) yBL_1.append(FKKpi.sigmaDM(Q2, 1)) wMed_2 = FKKpi.GammaDM(mMed, 2) FKKpi.resetParameters(gDM, mDM, mMed, wMed_2, cMed_u, cMed_d, cMed_s) yBL_2.append(FKKpi.sigmaDM(Q2, 2)) mDM += 0.05 plt.plot(xSM, ySM_0, color="blue", label="SM") plt.plot(xDP, yDP_0, color="red", label="DP") plt.plot(xBL, yBL_0, color="green", label="BL") plt.legend() plt.yscale("log") plt.xlim(1.2, 2.2) plt.title("$e^+e^- \\to K^0_SK^0_L\\pi^0$") plt.xlabel("$\\sqrt{s}$/GeV") plt.ylabel("$\\sigma$/nb") plt.savefig("plots/KKpi_K0K0Pi0.pdf") # plt.show() plt.close() plt.plot(xSM, ySM_1, color="blue", label="SM") plt.plot(xDP, yDP_1, color="red", label="DP") plt.plot(xBL, yBL_1, color="green", label="BL") plt.legend() plt.yscale("log") plt.xlim(1.2, 2.2) plt.title("$e^+e^- \\to K^+K^-\\pi^0$") plt.xlabel("$\\sqrt{s}$/GeV") plt.ylabel("$\\sigma$/nb") plt.savefig("plots/KKpi_KpKmPi0.pdf") # plt.show() plt.close() plt.plot(xSM, ySM_2, color="blue", label="SM") plt.plot(xDP, yDP_2, color="red", label="DP") plt.plot(xBL, yBL_2, color="green", label="BL") plt.legend() plt.yscale("log") plt.xlim(1.2, 2.2) plt.title("$e^+e^- \\to K^\\pm K^0_S\\pi^\\mp$") plt.xlabel("$\\sqrt{s}$/GeV") plt.ylabel("$\\sigma$/nb") plt.savefig("plots/KKpi_KpmK0pimp.pdf") # plt.show() plt.close()
[ "loganmorrison99@gmail.com" ]
loganmorrison99@gmail.com
c6b635d8975e1e9ddb2d14e64c1ceb9dae765e30
5a71a3e20e40bf39f35a5cdf2d8baae485fe1158
/gravitySim.py
155964f408f794aa0824f9e29908e206f1a9f409
[]
no_license
tspanther/FeriDrone
7cc0612083d11b26d9a2dd32dbb9dba770e192b0
911f545bbf8ac3a8c3c09cfc77ddccae40160bc3
refs/heads/master
2020-05-25T18:00:39.667947
2020-01-27T19:41:05
2020-01-27T19:41:05
187,918,038
0
1
null
2020-01-26T10:01:33
2019-05-21T21:46:46
C
UTF-8
Python
false
false
12,197
py
import numpy as np import matplotlib.pyplot as plt ## Noise generator - do not touch!!! def awgn_noise_single_element(x, SNR_dB): #np.random.seed(1) # set the random generator seed to same value (for comparison only) L = x.size SNR = np.power(10, (SNR_dB/10)) # SNR to linear scale Esym = np.sum(np.abs(x)**2) / (L) # Calculate actual symbol energy N0 = Esym / SNR # Find the noise spectral density if np.isreal(x).all(): noiseSigma = np.sqrt(N0) # Standard deviation for AWGN Noise when x is real n = noiseSigma * np.random.randn(1, L) else: noiseSigma = np.sqrt(N0/2) # Standard deviation for AWGN Noise when x is complex n = noiseSigma * (np.random.randn(1, L) + complex(0, 1) * np.random.randn(1, L)) return n[-1, -1] class GravitySim(): ''' Ustvarimo nov simulator. AutoLanderClass - razred AutoLander (ne objekt!), v katerem ste implementirali lastno implementacijo pristajanja. Parametri: AutoLanderClass - razred, ki implemetira zahtevan vmesnik timeDuration - čas trajanja simulacije timeStep - korak simulacije snr_dB - izbrana snr dB vrednost za šum, lahko ekperimentiramo objectMass - float, masa objekta v kg objectMaxThrust - maksimalni potisk motorjev, v N startHeight - začetna višina simulacije v m startVelocity - začetna hitrost v m/s (pozitivna je navzgor, negativna navzdol) ''' def __init__(self, AutoLanderClass, animate=False, # animate the plots timeDuration=3, # seconds timeStep=0.035, # seconds snr_dB=100.0, # power of signal over noise objectMass=0.5, # kg objectMaxThrust=11.06, # F (force of engines) startHeight=2.0, # meters (initial height) startVelocity=0.0, # meters / seconds (initial velocity) startThrust=0): # percentage of maxThrust (initial force) self.simTimeIndex = 0 # index of time step in simulation self.AutoLanderClass = AutoLanderClass self.autoLanderObj = None self.animate = animate ## simulation variables self.timeDuration = timeDuration # seconds self.timeStep = timeStep # seconds self.g = -9.81 # meters / seconds * seconds (gravitational change of velocity) self.snr_dB = snr_dB # power of signal over noise ## object variables # properties self.objectMass = objectMass self.objectMaxThrust = objectMaxThrust self.objectNeutralThrust = (self.objectMass * self.g / objectMaxThrust) * -1 # state self.startHeight = startHeight # meters (initial height) self.startVelocity = startVelocity # meters / seconds (initial velocity) self.startThrust = startThrust # percentage of maxThrust (initial force) # history self.historyTime = np.arange(self.timeStep, self.timeDuration+self.timeStep, self.timeStep) self.historyHeight = np.zeros(self.historyTime.shape) self.historyHeightWithNoise = np.zeros(self.historyTime.shape) self.historyHeightWithFilter = np.zeros(self.historyTime.shape) self.historyThrust = np.zeros(self.historyTime.shape) self.historyForce = np.zeros(self.historyTime.shape) self.historyVelocity = np.zeros(self.historyTime.shape) self.historyEnergy = np.zeros(self.historyTime.shape) def run(self): ''' Pozene simulacijo, stopi skozi vse korake in sproti prikazuje rezultate (ce je animate=True). ''' # prepare model currentHeight = self.startHeight currentVelocity = self.startVelocity currentThrust = self.startThrust currentEnergy = 0.5 * self.objectMass * np.power(currentVelocity, 2) autoLanderObj = self.AutoLanderClass(self.objectMass, self.objectMaxThrust, self.objectNeutralThrust) self.autoLanderObj = autoLanderObj ts_last_update = 0 if self.animate: self.animation_setup() # simulation model loop for ts in np.arange(1, self.historyTime.shape[0], 1): ## prepare for new loop ... previousHeight = currentHeight previousVelocity = currentVelocity # simulate noise :P currentNoise = awgn_noise_single_element(self.historyHeight[0:ts+1], self.snr_dB) currentHeight = currentHeight + currentNoise autoLanderObj.addHeightMeasurement(self.historyTime[ts], currentHeight) currentHeightFiltered = autoLanderObj.heightFiltered self.historyHeightWithFilter[ts] = currentHeightFiltered currentThrust = autoLanderObj.thrust ## comply with controll restraints if currentThrust < 0: currentThrust = 0 if currentThrust > 1: currentThrust = 1 self.historyThrust[ts] = currentThrust ## calculate new state ... # new force on object = force of gravity + current thrust currentForce = (self.objectMass * self.g) + (currentThrust * self.objectMaxThrust) self.historyForce[ts] = currentForce # new velocity of object = previous velocity + force * time / mass currentVelocity = previousVelocity + (currentForce * self.timeStep) / self.objectMass self.historyVelocity[ts] = currentVelocity # new displacement of object #dH = previousVelocity*timeStep + 0.5*timeStep**2*currentAcc #dH = (previousVelocity + currentVelocity) * 0.5 * self.timeStep currentAcc = currentForce*self.timeStep/self.objectMass dH = previousVelocity*self.timeStep + \ 0.5 * currentAcc*self.timeStep**2 # new height of object currentHeight = previousHeight + dH self.historyHeight[ts] = currentHeight self.historyHeightWithNoise[ts] = currentHeight + currentNoise # new kinetic energy of object (or force at distance 0) currentEnergy = 0.5 * self.objectMass * np.power(currentVelocity, 2) self.historyEnergy[ts] = currentEnergy if currentHeight <= 0: self.simTimeIndex = ts return if self.historyTime[ts]-self.historyTime[ts_last_update] >= 1/30: if self.animate: self.animation_update() ts_last_update = ts self.simTimeIndex = -1 def printResult(self): ''' Izpise koncne rezultate. ''' ts = self.simTimeIndex if ts > 0: print('Simulation results:') print('Landing time:', self.historyTime[ts], 's') print('Landing speed:', self.historyVelocity[ts], 'm/s') print('Landing force:', self.historyEnergy[ts], 'N') else: print('Simulation failed ...') def animation_setup(self): ''' setup animation frame ''' plt.figure() self.ax1 = plt.subplot(2, 2, 1) plt.title('Height of object') self.heightWithNoiseLine, = plt.plot(self.historyTime, self.historyHeightWithNoise, 'r', label='noise') self.heightWithFilterLine, = plt.plot(self.historyTime, self.historyHeightWithFilter, 'g', label='noise - filter') self.historyHeightLine, = plt.plot(self.historyTime, self.historyHeight, 'b', label='real') plt.xlabel('time (s)'); plt.ylabel('height (m)') plt.legend() self.ax2 = plt.subplot(2, 2, 2) self.axx2 = self.ax2.twinx() plt.title('Force acted on object') self.historyForceLine, = plt.plot(self.historyTime, self.historyForce, label='force') self.historyThrustLine, = plt.plot(self.historyTime, self.historyThrust, label='thrust') self.ax2.set_ylabel('thrust (%)') self.axx2.set_ylabel('force (N)') plt.xlabel('time (s)') plt.legend() self.ax3 = plt.subplot(2, 2, 3) plt.title('Velocity of object') self.historyVelocityLine, = plt.plot(self.historyTime, self.historyVelocity) plt.xlabel('time (s)'); plt.ylabel('velocity (m/s)') self.ax4 = plt.subplot(2, 2, 4) plt.title('Kinectic energy of object') self.historyEnergyLine, = plt.plot(self.historyTime, self.historyEnergy) plt.xlabel('time (s)'); plt.ylabel('energy (J)') plt.show(block=False) plt.waitforbuttonpress(0.01) def animation_update(self): ''' update animation frame ''' self.heightWithNoiseLine.set_ydata(self.historyHeightWithNoise) self.heightWithFilterLine.set_ydata(self.historyHeightWithFilter) self.historyHeightLine.set_ydata(self.historyHeight) self.ax1.relim() self.ax1.autoscale_view() self.historyForceLine.set_ydata(self.historyForce) self.ax2.relim() self.ax2.autoscale_view() self.historyThrustLine.set_ydata(self.historyThrust) self.axx2.relim() self.axx2.autoscale_view() self.historyVelocityLine.set_ydata(self.historyVelocity) self.ax3.relim() self.ax3.autoscale_view() self.historyEnergyLine.set_ydata(self.historyEnergy) self.ax4.relim() self.ax4.autoscale_view() plt.draw() plt.waitforbuttonpress(0.01) def plot(self): ''' plot progress ''' plt.figure() plt.subplot(2, 2, 1) plt.title('Height of object') plt.plot(self.historyTime, self.historyHeightWithNoise, 'r', label='noise') plt.plot(self.historyTime, self.historyHeightWithFilter, 'g', label='noise - filter') plt.plot(self.historyTime, self.historyHeight, 'b', label='real') plt.xlabel('time (s)'); plt.ylabel('height (m)') plt.legend() ax = plt.subplot(2, 2, 2) axx = ax.twinx() plt.title('Force acted on object') plt.plot(self.historyTime, self.historyForce, label='force') plt.plot(self.historyTime, self.historyThrust, label='thrust') ax.set_ylabel('thrust (%)') axx.set_ylabel('force (N)') plt.xlabel('time (s)') plt.legend() plt.subplot(2, 2, 3) plt.title('Velocity of object') plt.plot(self.historyTime, self.historyVelocity) plt.xlabel('time (s)'); plt.ylabel('velocity (m/s)') plt.subplot(2, 2, 4) plt.title('Kinectic energy of object') plt.plot(self.historyTime, self.historyEnergy) plt.xlabel('time (s)'); plt.ylabel('energy (J)') plt.show() #from autolander_comport import AutoLander from autolander2 import AutoLander if __name__ == '__main__': grav_sim = GravitySim(AutoLander, animate=False) grav_sim.run() grav_sim.printResult() grav_sim.plot()
[ "niko.uremovic@student.um.si" ]
niko.uremovic@student.um.si
8450ae9ac9e107829379b46d5b8489d02c6e26a9
efd190338aca71472812a22fa16a70b33481ae43
/web/mcc-import.py
d0cfb3fc9a248d06634eec61f4bb953d90cde2d0
[]
no_license
mgrundy/mcc
3b49a6869846fad1e56365ee62921ba4f05e2020
6a2e72fad986e39f15369462206802ba76e1f9df
refs/heads/master
2021-01-18T10:21:27.534886
2014-10-17T14:39:12
2014-10-17T14:39:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,557
py
# Copyright (C) 2014 MongoDB Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License, version 3, # as published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import string import os import sys import optparse import json import datetime import pymongo import tornado.httpclient def do_json_import(): """Insert all JSON files from root directory and below into database.""" parser = optparse.OptionParser(usage="""\ %prog [git_hash] [rootPath] [build_id] [connectionstring] [testname] [branch] [platform]""") # add in command line options. parser.add_option("-g", "--git-hash", dest="ghash", help="git hash of code being tested", default=None) parser.add_option("-b", "--build-id", dest="build", help="build ID of code being tested", default=None) parser.add_option("-c", "--connection-string", dest="connectstr", help="URL that will be connected to", default=None) parser.add_option("-t", "--test-name", dest="tname", help="name of the test", default=None) parser.add_option("-a", "--branch", dest="branch", help="name of the branch", default=None) parser.add_option("-p", "--platform", dest="pform", help="build platform", default=None) parser.add_option("-r", "--root-dir", dest="root", help="root directory of JSON files", default=None) parser.add_option("--recursive", dest="recurse", help="make import recursive", action="store_true", default=False) parser.add_option("-d", "--date", dest="date", help="date of build", default=None) (options, args) = parser.parse_args() if options.ghash is None: print "\nERROR: Must specify git hash \n" sys.exit(-1) if options.build is None: print "\nERROR: Must specify build ID \n" sys.exit(-1) if options.connectstr is None: print "\nERROR: Must specify connection string \n" sys.exit(-1) if options.tname is None: print "\nERROR: Must specify test name \n" sys.exit(-1) if options.branch is None: print "\nERROR: Must specify branch name \n" sys.exit(-1) if options.pform is None: print "\nERROR: Must specify platform \n" sys.exit(-1) if options.root is None: print "\nERROR: Must specify root directory \n" sys.exit(-1) if options.date is None: print "\nERROR: Must specify date \n" sys.exit(-1) http_client = tornado.httpclient.HTTPClient() # Check if date is properly formatted date = datetime.datetime.strptime(options.date, "%Y-%m-%dT%H:%M:%S.%f") if options.recurse: # Walk through files in root for dir_path, sub_dirs, file_names in os.walk(options.root): for file_name in file_names: if not file_name.endswith(".json"): continue print "\nNow importing " + file_name + ":\n" # Insert the record for a file do_import_file(os.path.join(dir_path, file_name), options.ghash, options.build, options.tname, http_client, options.connectstr) else: # Import all json files in root directory files = [os.path.join(options.root, f) for f in os.listdir(options.root) if os.path.isfile(os.path.join(options.root, f))] for f in files: if not f.endswith(".json"): continue do_import_file(f, options.ghash, options.build, options.tname, http_client, options.connectstr) # Gather meta info meta_record = {} meta_record["_id"] = {"build_id": options.build, "git_hash": options.ghash} meta_record["date"] = options.date meta_record["branch"] = options.branch meta_record["platform"] = options.pform request = tornado.httpclient.HTTPRequest(url=options.connectstr + "/meta", method="POST", request_timeout=300.0, body=json.dumps(meta_record)) try: response = http_client.fetch(request) print response.body except tornado.httpclient.HTTPError as e: print "Error: ", e http_client.close() def do_import_file(file_name, git_hash, build_id, test_name, http_client, url): """Import contents of a single file into database.""" with open(file_name, "r") as f: for line in f: if line == "\n": continue record = json.loads(line) record["git_hash"] = git_hash record["build_id"] = build_id record["test_name"] = test_name file_index = record["file"].rfind("/") + 1 record["dir"] = record["file"][: file_index] request = tornado.httpclient.HTTPRequest( url=url, method="POST", headers={"Content-Type": "application/json"}, request_timeout=300.0, body=json.dumps(record)) try: response = http_client.fetch(request) print response.body except tornado.httpclient.HTTPError as e: print "Error: ", e do_json_import()
[ "mvankeulen94@gmail.com" ]
mvankeulen94@gmail.com
2c7265b2668c7bcb4848c3635ee1b3d9f1cf3ae5
63fc7db58cef6c10622ae963e2cf7d89ffc665fe
/coremltools/converters/mil/mil/ops/tests/test_tensor_transformation.py
e6af34aaae3b5da789412e8aca73aaab68bb25ba
[ "BSD-3-Clause" ]
permissive
lexmz/coremltools
c3498d3a79a00806881833c61d0ad80fd226ace2
908ad2add3753b6b57336d6c26821e7074b9f669
refs/heads/main
2023-08-31T19:02:57.904850
2021-11-04T16:39:09
2021-11-04T16:39:09
424,665,865
0
0
BSD-3-Clause
2021-11-04T16:33:17
2021-11-04T16:33:17
null
UTF-8
Python
false
false
39,235
py
# Copyright (c) 2020, Apple Inc. All rights reserved. # # Use of this source code is governed by a BSD-3-clause license that can be # found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause from coremltools.converters.mil import testing_reqs from coremltools.converters.mil.mil import get_new_symbol, get_new_variadic_symbol from coremltools.converters.mil.testing_reqs import * from .testing_utils import UNK_SYM, UNK_VARIADIC, run_compare_builder backends = testing_reqs.backends class TestDepthToSpace: @pytest.mark.parametrize( "use_cpu_only, backend", itertools.product([True, False], backends,) ) def test_builder_to_backend_smoke(self, use_cpu_only, backend): # original input type is (1, 4, 1, 1, fp32) val = np.array([[[[9.0]], [[5.0]], [[1.0]], [[3.0]]]], dtype=np.float32) input_placeholders = {"x": mb.placeholder(shape=val.shape)} input_values = {"x": val} def build(x): return [mb.depth_to_space(x=x, block_size=2)] expected_output_types = (1, 1, 2, 2, types.fp32) expected_outputs = np.array([[[[9.0, 5.0], [1.0, 3.0]]]], dtype=np.float32) run_compare_builder( build, input_placeholders, input_values, expected_output_types, expected_outputs, use_cpu_only=use_cpu_only, frontend_only=False, backend=backend, ) class TestExpandDims: @pytest.mark.parametrize( "use_cpu_only, backend", itertools.product([True, False], backends,) ) def test_builder_to_backend_smoke(self, use_cpu_only, backend): t = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32) input_placeholders = {"x": mb.placeholder(shape=t.shape)} input_values = {"x": t} def build(x): return [ mb.expand_dims(x=x, axes=[0]), mb.expand_dims(x=x, axes=[1]), mb.expand_dims(x=x, axes=[2]), mb.expand_dims(x=x, axes=[-1]), mb.expand_dims(x=x, axes=[0, 1]), mb.expand_dims(x=x, axes=[-2, -1]), ] expected_output_types = [ (1, 2, 3, types.fp32), (2, 1, 3, types.fp32), (2, 3, 1, types.fp32), (2, 3, 1, types.fp32), (1, 1, 2, 3, types.fp32), (2, 3, 1, 1, types.fp32), ] expected_outputs = [ np.array([[[1, 2, 3], [4, 5, 6]]], dtype=np.float32), np.array([[[1, 2, 3]], [[4, 5, 6]]], dtype=np.float32), np.array([[[1], [2], [3]], [[4], [5], [6]]], dtype=np.float32), np.array([[[1], [2], [3]], [[4], [5], [6]]], dtype=np.float32), np.array([[[[1, 2, 3], [4, 5, 6]]]], dtype=np.float32), np.array([[[[1]], [[2]], [[3]]], [[[4]], [[5]], [[6]]]], dtype=np.float32), ] run_compare_builder( build, input_placeholders, input_values, expected_output_types, expected_outputs, use_cpu_only=use_cpu_only, frontend_only=False, backend=backend, ) @pytest.mark.parametrize( "use_cpu_only, backend", itertools.product([True, False], backends,) ) def test_builder_to_backend_symbolic(self, use_cpu_only, backend): s0 = get_new_symbol() input_placeholders = { "x": mb.placeholder(shape=(2, s0)), } def build(x): return [ mb.expand_dims(x=x, axes=[-1]), mb.expand_dims(x=x, axes=[1]), ] expected_output_types = [ (2, s0, 1, types.fp32), (2, 1, s0, types.fp32), ] expected_outputs = [ np.array([[[1], [2], [3]], [[4], [5], [6]]], dtype=np.float32), np.array([[[1, 2, 3]], [[4, 5, 6]]], dtype=np.float32), ] input_values = { "x": np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32), } run_compare_builder( build, input_placeholders, input_values, expected_output_types, expected_outputs, use_cpu_only=use_cpu_only, frontend_only=False, backend=backend, ) @ssa_fn def test_builder_eval(self): x_val = np.random.rand(1, 6) v1 = mb.expand_dims(x=x_val, axes=[2]) np.testing.assert_allclose(np.expand_dims(x_val, 2), v1.val, atol=1e-04, rtol=1e-05) v2 = mb.expand_dims(x=x_val, axes=[-1]) np.testing.assert_allclose(np.expand_dims(x_val, -1), v2.val, atol=1e-04, rtol=1e-05) v3 = mb.expand_dims(x=x_val, axes=[-1, -2]) ref = np.expand_dims(np.expand_dims(x_val, -1), -1) np.testing.assert_allclose(ref, v3.val, atol=1e-04, rtol=1e-05) v4 = mb.expand_dims(x=x_val, axes=[0, -1, -2]) np.testing.assert_allclose(np.reshape(x_val, (1, 1, 6, 1, 1)), v4.val, atol=1e-04, rtol=1e-05) @pytest.mark.parametrize( "use_cpu_only, backend, rank_and_axis", itertools.product( [True, False], backends, [ (rank, axis) for rank in range(1, 5) for axis in range(-rank - 1, rank + 1) ], ), ) def test_builder_to_backend_programmatic_one_axis( self, use_cpu_only, backend, rank_and_axis ): rank, axis = rank_and_axis x_shape = np.random.randint(low=2, high=6, size=rank) input_placeholders = {"x": mb.placeholder(shape=x_shape)} input_values = {"x": np.random.sample(x_shape).astype(np.float32)} def build(x): return mb.expand_dims(x=x, axes=[axis]) adjusted_axis = axis if axis >= 0 else rank + axis + 1 x_shape = list(x_shape) out_shape = x_shape[:adjusted_axis] + [1] + x_shape[adjusted_axis:] expected_output_types = tuple(out_shape[:]) + (types.fp32,) run_compare_builder( build, input_placeholders, input_values, expected_output_types, np.expand_dims(input_values["x"], axis), use_cpu_only=use_cpu_only, frontend_only=False, backend=backend, ) @pytest.mark.parametrize( "use_cpu_only, backend, rank_and_axes", itertools.product( [True, False], backends, [ (3, [0, 1]), (3, [1, 0]), (3, [-2, -1]), (3, [-1, -2]), (2, [-3, -1]), (2, [-3, 1, -1]), (2, [-2, 0]), (1, [-1, -2, -3, -4]), (1, [0, -1]), (1, [0, 1, -2, -1]), ], ), ) def test_builder_to_backend_programmatic_multiple_axes( self, use_cpu_only, backend, rank_and_axes ): rank, axes = rank_and_axes x_shape = np.random.randint(low=1, high=6, size=rank) input_placeholders = {"x": mb.placeholder(shape=x_shape)} input_values = {"x": np.random.sample(x_shape).astype(np.float32)} def build(x): return mb.expand_dims(x=x, axes=axes) out_shape = list(x_shape) out_rank = rank + len(axes) pos_axes = sorted([out_rank + axis if axis < 0 else axis for axis in axes]) for axis in pos_axes: out_shape.insert(axis, 1) expected_outputs = np.reshape(input_values["x"], out_shape) expected_output_types = tuple(out_shape) + (types.fp32,) run_compare_builder( build, input_placeholders, input_values, expected_output_types, expected_outputs, use_cpu_only=use_cpu_only, frontend_only=False, backend=backend, ) class TestReshape: @pytest.mark.parametrize( "use_cpu_only, backend", itertools.product([True, False], backends,) ) def test_builder_to_backend_smoke(self, use_cpu_only, backend): t = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32) input_placeholders = {"x": mb.placeholder(shape=t.shape)} input_values = {"x": t} def build(x): return [ mb.reshape(x=x, shape=[3, 2]), mb.reshape(x=x, shape=[2, -1]), mb.reshape(x=x, shape=[2, 1, 1, 3]), ] expected_output_types = [ (3, 2, types.fp32), (2, 3, types.fp32), (2, 1, 1, 3, types.fp32), ] expected_outputs = [ np.array([[1, 2], [3, 4], [5, 6]], dtype=np.float32), np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32), np.array([[[[1.0, 2.0, 3.0]]], [[[4.0, 5.0, 6.0]]]], dtype=np.float32), ] run_compare_builder( build, input_placeholders, input_values, expected_output_types, expected_outputs, use_cpu_only=use_cpu_only, frontend_only=False, backend=backend, ) @ssa_fn def test_builder_eval(self): t = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32) r = mb.reshape(x=t, shape=[3, 2]) expected_r = np.array([[1, 2], [3, 4], [5, 6]], dtype=np.float32) np.testing.assert_allclose(expected_r, r.val, atol=1e-04, rtol=1e-05) r2 = mb.reshape(x=t, shape=[2, -1]) expected_r2 = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32) np.testing.assert_allclose(expected_r2, r2.val, atol=1e-04, rtol=1e-05) @pytest.mark.parametrize( "use_cpu_only, backend", itertools.product([True, False], backends,) ) def test_builder_to_backend_symbolic(self, use_cpu_only, backend): s0 = get_new_symbol() s_len = get_new_symbol() s1 = get_new_variadic_symbol() input_placeholders = { "x": mb.placeholder(shape=(2, s0)), "shape": mb.placeholder(shape=(3,), dtype=types.int32), "shape2": mb.placeholder(shape=(s_len,), dtype=types.int32), } def build(x, shape, shape2): return [ mb.reshape(x=x, shape=[2, -1]), mb.reshape(x=x, shape=[1, -1]), mb.reshape(x=x, shape=[2, 1, 1, -1]), mb.reshape(x=x, shape=shape), mb.reshape(x=x, shape=shape2), ] expected_output_types = [ (2, s0, types.fp32), (1, 2 * s0, types.fp32), (2, 1, 1, s0, types.fp32), (UNK_SYM, UNK_SYM, UNK_SYM, types.fp32), (UNK_VARIADIC, types.fp32), ] expected_outputs = [ np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32), np.array([[1, 2, 3, 4, 5, 6]], dtype=np.float32), np.array([[[[1.0, 2.0, 3.0]]], [[[4.0, 5.0, 6.0]]]], dtype=np.float32), np.array([[[1, 2, 3]], [[4, 5, 6]]], dtype=np.float32), np.array([[[1, 2, 3]], [[4, 5, 6]]], dtype=np.float32), ] input_values = { "x": np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32), "shape": np.array([2, 1, 3], dtype=np.float32), "shape2": np.array([2, 1, 3], dtype=np.float32), } run_compare_builder( build, input_placeholders, input_values, expected_output_types, expected_outputs, use_cpu_only=use_cpu_only, frontend_only=False, backend=backend, ) class TestReverse: @pytest.mark.parametrize( "use_cpu_only, backend", itertools.product([True, False], backends,) ) def test_builder_to_backend_smoke(self, use_cpu_only, backend): val = np.array([[-1.0, 2.0, -3.0], [4.0, -5.0, 6.0]], dtype=np.float32) input_placeholders = {"x": mb.placeholder(shape=val.shape)} input_values = {"x": val} def build(x): return [mb.reverse(x=x), mb.reverse(x=x, axes=[0])] expected_output_types = [(2, 3, types.fp32), (2, 3, types.fp32)] expected_outputs = [ np.array([[6.0, -5.0, 4.0], [-3.0, 2.0, -1.0]], dtype=np.float32), np.array([[4.0, -5.0, 6.0], [-1.0, 2.0, -3.0]], dtype=np.float32), ] run_compare_builder( build, input_placeholders, input_values, expected_output_types, expected_outputs, use_cpu_only=use_cpu_only, backend=backend, ) @ssa_fn def test_builder_eval(self): val = np.array([[-1.0, 7.0, -3.0], [4.0, -5.0, 8.0]], dtype=np.float32) res = mb.reverse(x=val, axes=[0]) np.testing.assert_allclose(np.flip(val, axis=0), res.val, atol=1e-04, rtol=1e-05) @pytest.mark.parametrize( "use_cpu_only, backend", itertools.product([True, False], backends,) ) def test_builder_to_backend_symbolic(self, use_cpu_only, backend): s0 = get_new_symbol() val = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], dtype=np.float32) input_placeholders = {"x": mb.placeholder(shape=(s0, 3))} input_values = {"x": val} def build(x): return [ mb.reverse(x=x, axes=[1]), mb.reverse(x=x, axes=[0]), ] expected_output_types = [ (s0, 3, types.fp32), (s0, 3, types.fp32), ] expected_outputs = [ np.array([[3.0, 2.0, 1.0], [6.0, 5.0, 4.0]], dtype=np.float32), np.array([[4.0, 5.0, 6.0], [1.0, 2.0, 3.0]], dtype=np.float32), ] run_compare_builder( build, input_placeholders, input_values, expected_output_types, expected_outputs, use_cpu_only=use_cpu_only, backend=backend, ) class TestReverseSequence: @pytest.mark.parametrize( "use_cpu_only, backend", itertools.product([True, False], backends,) ) def test_builder_to_backend_smoke(self, use_cpu_only, backend): x_val = np.array( [ [1, 2, 3, 4, 5, 0, 0, 0], [1, 2, 0, 0, 0, 0, 0, 0], [1, 2, 3, 4, 0, 0, 0, 0], [1, 2, 3, 4, 5, 6, 7, 8], ], dtype=np.float32, ) input_placeholders = {"x": mb.placeholder(shape=x_val.shape)} input_values = {"x": x_val} def build(x): return [ mb.reverse_sequence( x=x, lengths=[7, 2, 3, 5], seq_axis=1, batch_axis=0 ), ] expected_output_types = [ (4, 8, types.fp32), ] expected_outputs = [ np.array( [ [0, 0, 5, 4, 3, 2, 1, 0], [2, 1, 0, 0, 0, 0, 0, 0], [3, 2, 1, 4, 0, 0, 0, 0], [5, 4, 3, 2, 1, 6, 7, 8], ], dtype=np.float32, ) ] run_compare_builder( build, input_placeholders, input_values, expected_output_types, expected_outputs, use_cpu_only=use_cpu_only, backend=backend, ) @pytest.mark.parametrize( "use_cpu_only, backend", itertools.product([True, False], backends,) ) def test_builder_to_backend_symbolic(self, use_cpu_only, backend): s0 = get_new_symbol() x_val = np.array( [ [1, 2, 3, 4, 5, 0, 0, 0], [1, 2, 0, 0, 0, 0, 0, 0], [1, 2, 3, 4, 0, 0, 0, 0], [1, 2, 3, 4, 5, 6, 7, 8], ], dtype=np.float32, ) input_placeholders = {"x": mb.placeholder(shape=(4, s0))} input_values = {"x": x_val} def build(x): return [ mb.reverse_sequence( x=x, lengths=[7, 2, 3, 5], seq_axis=1, batch_axis=0 ), ] expected_output_types = [ (4, s0, types.fp32), ] expected_outputs = [ np.array( [ [0, 0, 5, 4, 3, 2, 1, 0], [2, 1, 0, 0, 0, 0, 0, 0], [3, 2, 1, 4, 0, 0, 0, 0], [5, 4, 3, 2, 1, 6, 7, 8], ], dtype=np.float32, ) ] run_compare_builder( build, input_placeholders, input_values, expected_output_types, expected_outputs, use_cpu_only=use_cpu_only, backend=backend, ) class TestSliceBySize: @pytest.mark.parametrize( "use_cpu_only, backend", itertools.product([True, False], backends,) ) def test_builder_to_backend_smoke(self, use_cpu_only, backend): x_val = np.array(list(range(24))).reshape((2, 3, 4)).astype(np.float32) begin_val = np.array([1, 1, 1], dtype=np.int32) input_placeholders = { "x": mb.placeholder(shape=x_val.shape), "begin": mb.placeholder(shape=begin_val.shape, dtype=types.int32), } input_values = {"x": x_val, "begin": begin_val} def build_non_single(x, begin): return [ mb.slice_by_size(x=x, begin=begin, size=[1, 2, 3]), ] def build_single(x, begin): return [ mb.slice_by_size(x=x, begin=begin, size=[-1, 2, -1]), ] expected_output_types = [(1, 2, 3, types.fp32)] expected_outputs = [np.array([[[17, 18, 19], [21, 22, 23]]], dtype=np.float32)] run_compare_builder( build_non_single, input_placeholders, input_values, expected_output_types, expected_outputs, use_cpu_only=use_cpu_only, frontend_only=False, backend=backend, ) expected_output_types = [(UNK_SYM, 2, UNK_SYM, types.fp32)] run_compare_builder( build_single, input_placeholders, input_values, expected_output_types, expected_outputs, use_cpu_only=use_cpu_only, frontend_only=False, backend=backend, ) @ssa_fn def test_builder_eval(self): x = np.array(list(range(24))).reshape(2, 3, 4) v_1 = mb.slice_by_size(x=x, begin=(0, 1, 0), size=(-1, -1, -1)) v_2 = mb.slice_by_size(x=x, begin=(0, 1, 0), size=(-1, -1, 3)) v_3 = mb.slice_by_size(x=x, begin=(0, -2, 0), size=(-1, -1, 3)) np.testing.assert_allclose(x[:, 1:, :], v_1.val, atol=1e-04, rtol=1e-05) np.testing.assert_allclose(x[:, 1:, :3], v_2.val, atol=1e-04, rtol=1e-05) np.testing.assert_allclose(x[:, -2:, :3], v_3.val, atol=1e-04, rtol=1e-05) class TestSpaceToDepth: @pytest.mark.parametrize( "use_cpu_only, backend", itertools.product([True, False], backends,) ) def test_builder_to_backend_smoke(self, use_cpu_only, backend): # original input type is (1, 1, 2, 2, fp32) val = np.array([[[[7.0, 9.0], [4.0, 6.0]]]], dtype=np.float32) input_placeholders = {"x": mb.placeholder(shape=val.shape)} input_values = {"x": val} def build(x): return [mb.space_to_depth(x=x, block_size=2)] expected_output_types = (1, 4, 1, 1, types.fp32) expected_outputs = np.array( [[[[7.0]], [[9.0]], [[4.0]], [[6.0]]]], dtype=np.float32 ) run_compare_builder( build, input_placeholders, input_values, expected_output_types, expected_outputs, use_cpu_only=use_cpu_only, frontend_only=False, backend=backend, ) class TestSqueeze: @pytest.mark.parametrize( "use_cpu_for_conversion, backend", itertools.product([True, False], backends,) ) def test_builder_to_backend_smoke(self, use_cpu_for_conversion, backend): if backend[0] == "mlprogram" and not use_cpu_for_conversion: pytest.xfail("rdar://78343225 ((MIL GPU) Core ML Tools Unit Test failures [numerical error])") x = np.array([[[[1], [2], [3]]]], dtype=np.float32) input_placeholders = {"x": mb.placeholder(shape=x.shape)} input_values = {"x": x} def build(x): return [ mb.squeeze(x=x, axes=(-1,)), mb.squeeze(x=x, axes=(-3, 0)), mb.squeeze(x=x, axes=(0, 1, 3)), mb.squeeze(x=x), ] expected_output_types = [ (1, 1, 3, types.fp32), (3, 1, types.fp32), (3, types.fp32), (3, types.fp32), ] expected_outputs = [ np.array([[[1, 2, 3]]], dtype=np.float32), np.array([[1], [2], [3]], dtype=np.float32), np.array([1, 2, 3], dtype=np.float32), np.array([1, 2, 3], dtype=np.float32), ] run_compare_builder( build, input_placeholders, input_values, expected_output_types, expected_outputs, use_cpu_only=use_cpu_for_conversion, backend=backend, use_cpu_for_conversion=use_cpu_for_conversion, ) @ssa_fn def test_builder_eval(self): x = np.array([[[[1], [2], [3]], [[4], [5], [6]]]], dtype=np.float32) v = mb.squeeze(x=x, axes=(-4, 3)) np.testing.assert_allclose(np.squeeze(x, axis=(-4, 3)), v.val, atol=1e-04, rtol=1e-05) @ssa_fn def test_builder_eval_rank_0(self): x = np.array([1], dtype=np.float32) v = mb.squeeze(x=x) assert v.shape == () assert type(v.val) == np.float32 assert np.isclose(np.squeeze(x), v.val) class TestTranspose: @pytest.mark.parametrize( argnames=["use_cpu_only", "backend", "is_symbolic"], argvalues=itertools.product([True, False], backends, [True, False],), ) def test_builder_to_backend_smoke(self, use_cpu_only, backend, is_symbolic): x = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32) input_shape = x.shape if is_symbolic: input_shape = [get_new_symbol(), get_new_symbol()] input_placeholders = {"x": mb.placeholder(shape=input_shape)} input_values = {"x": x} def build(x): return [ mb.transpose(x=x, perm=(0, 1)), mb.transpose(x=x, perm=(1, 0)), mb.transpose(x=x, perm=(-1, 0)), mb.transpose(x=x, perm=(-2, -1)), ] d0 = input_shape[0] d1 = input_shape[1] expected_output_types = [ (d0, d1, types.fp32), (d1, d0, types.fp32), (d1, d0, types.fp32), (d0, d1, types.fp32), ] expected_outputs = [x, x.T, x.T, x] run_compare_builder( build, input_placeholders, input_values, expected_output_types, expected_outputs, use_cpu_only=use_cpu_only, frontend_only=False, backend=backend, ) @ssa_fn def test_builder_eval(self): x = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32) v = mb.transpose(x=x, perm=(1, 0)) np.testing.assert_allclose(x.T, v.val, atol=1e-04, rtol=1e-05) @pytest.mark.parametrize( "use_cpu_only, backend", itertools.product([True, False], backends,) ) def test_builder_to_backend_symbolic(self, use_cpu_only, backend): s0 = get_new_symbol() input_placeholders = { "x": mb.placeholder(shape=(2, s0)), } def build(x): return [ mb.transpose(x=x, perm=[1, 0]), ] expected_output_types = [ (s0, 2, types.fp32), ] expected_outputs = [ np.array([[1, 4], [2, 5], [3, 6]], dtype=np.float32), ] input_values = { "x": np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32), } run_compare_builder( build, input_placeholders, input_values, expected_output_types, expected_outputs, use_cpu_only=use_cpu_only, frontend_only=False, backend=backend, ) class TestPixelShuffle: @pytest.mark.parametrize( "use_cpu_only, backend", itertools.product([True, False], backends,) ) def test_builder_to_backend_smoke(self, use_cpu_only, backend): # original input type is (1, 4, 1, 1, fp32) val = np.array([[[[9.0]], [[5.0]], [[1.0]], [[3.0]]]], dtype=np.float32) input_placeholders = {"x": mb.placeholder(shape=val.shape)} input_values = {"x": val} def build(x): return [mb.pixel_shuffle(x=x, upscale_factor=2)] expected_output_types = (1, 1, 2, 2, types.fp32) expected_outputs = np.array([[[[9.0, 5.0], [1.0, 3.0]]]], dtype=np.float32) run_compare_builder( build, input_placeholders, input_values, expected_output_types, expected_outputs, use_cpu_only=use_cpu_only, backend=backend, ) @pytest.mark.skipif(not testing_reqs._HAS_TORCH, reason="PyTorch not found.") @pytest.mark.parametrize( "use_cpu_only, backend, shape, upscale_factor", itertools.product( [True, False], backends, [(1, 16, 1, 1), (2, 16, 3, 3), (1, 32, 1, 1)], [2, 4], ), ) def test_builder_to_backend_stress( self, use_cpu_only, backend, shape, upscale_factor ): val = np.random.rand(*shape) input_placeholders = {"x": mb.placeholder(shape=val.shape)} input_values = {"x": val} def build(x): return [mb.pixel_shuffle(x=x, upscale_factor=upscale_factor)] torch_pixel_shuffle = torch.nn.PixelShuffle(upscale_factor) expected_outputs = [torch_pixel_shuffle(torch.Tensor(val)).numpy()] expected_output_types = [o.shape[:] + (types.fp32,) for o in expected_outputs] run_compare_builder( build, input_placeholders, input_values, expected_output_types, expected_outputs, use_cpu_only=use_cpu_only, backend=backend, ) class TestSlidingWindows: @pytest.mark.parametrize( "use_cpu_only, backend", itertools.product([True, False], backends,) ) def test_builder_to_backend_smoke(self, use_cpu_only, backend): # original input type is (1, 4, 1, 1, fp32) val = np.array([[[[9.0]], [[5.0]], [[1.0]], [[3.0]]]], dtype=np.float32) input_placeholders = {"x": mb.placeholder(shape=val.shape)} input_values = {"x": val} def build(x): return [mb.sliding_windows(x=x, axis=1, size=2)] expected_output_types = (1, 3, 2, 1, 1, types.fp32) expected_outputs = np.array( [[[[[9.0]], [[5.0]]], [[[5.0]], [[1.0]]], [[[1.0]], [[3.0]]]]], dtype=np.float32, ) run_compare_builder( build, input_placeholders, input_values, expected_output_types, expected_outputs, use_cpu_only=use_cpu_only, backend=backend, ) @pytest.mark.parametrize( "use_cpu_only, backend, rank_and_axis, size, stride", itertools.product( [True, False], backends, [(rank, axis) for rank in range(1, 5) for axis in range(-rank, rank)], [1, 2], [1, 2], ), ) def test_builder_to_backend_stress( self, use_cpu_only, backend, rank_and_axis, size, stride ): def np_sliding_windows(a, np_axis, np_size, np_stride): n = (a.shape[np_axis] - np_size) // np_stride + 1 x_shape = list(a.shape) x_shape[np_axis] = n if np_axis < 0: np_axis += len(x_shape) x_shape.insert(np_axis + 1, np_size) strides = list(a.strides) eff_stride = strides[np_axis] * np_stride strides.insert(np_axis, eff_stride) return np.lib.stride_tricks.as_strided(a, x_shape, strides) rank, axis = rank_and_axis shape = np.random.randint(low=2, high=5, size=rank) val = np.random.rand(*shape) input_placeholders = {"x": mb.placeholder(shape=val.shape)} input_values = {"x": val} def build(x): return [mb.sliding_windows(x=x, axis=axis, size=size, stride=stride)] expected_outputs = [ np_sliding_windows(val, np_axis=axis, np_size=size, np_stride=stride) ] expected_output_types = [o.shape[:] + (types.fp32,) for o in expected_outputs] run_compare_builder( build, input_placeholders, input_values, expected_output_types, expected_outputs, use_cpu_only=use_cpu_only, backend=backend, ) class TestConcat: @pytest.mark.parametrize( "use_cpu_only, backend", itertools.product([True, False], backends, ) ) def test_builder_to_backend_smoke(self, use_cpu_only, backend): t1 = np.array([[1, 2], [4, 5]], dtype=np.float32) t2 = np.array([[7, 8]], dtype=np.float32) input_placeholders = { "x": mb.placeholder(shape=t1.shape), "y": mb.placeholder(shape=t2.shape), } input_values = {"x": t1, "y": t2} def build(x, y): return (mb.concat(values=(x, y), axis=0),) expected_output_types = [ (3, 2, types.fp32), ] expected_outputs = [ np.array([[1, 2], [4, 5], [7, 8]], dtype=np.float32), ] run_compare_builder( build, input_placeholders, input_values, expected_output_types, expected_outputs, use_cpu_only=use_cpu_only, frontend_only=False, backend=backend, ) @pytest.mark.parametrize( "use_cpu_only, backend", itertools.product([True, False], backends, ) ) def test_builder_to_backend_type_promotion(self, use_cpu_only, backend): t1 = np.array([[1, 2], [4, 5]], dtype=np.float32) t2 = np.array([[7, 8]], dtype=np.float32) input_placeholders = { "x": mb.placeholder(shape=t1.shape), } input_values = {"x": t1} def build(x): t2 = np.array([[7, 8]], dtype=np.int32) return (mb.concat(values=(x, t2), axis=0),) expected_output_types = [ # np.int32 should be promoted to fp32 (3, 2, types.fp32), ] expected_outputs = [ np.array([[1, 2], [4, 5], [7, 8]], dtype=np.float32), ] run_compare_builder( build, input_placeholders, input_values, expected_output_types, expected_outputs, use_cpu_only=use_cpu_only, frontend_only=False, backend=backend, ) @pytest.mark.parametrize( "use_cpu_only, backend, rank, n_inputs, negative_index", itertools.product( [True, False], backends, [1, 2, 3, 4, 5], [2, 3], [False, True], ) ) def test_builder_to_backend_stress_interleave(self, use_cpu_only, backend, rank, n_inputs, negative_index): def np_concat_interleave(arrays, axis): step = len(arrays) in_shape = arrays[0].shape out_shape = list(in_shape) if axis < 0: axis += len(in_shape) out_shape[axis] = step * in_shape[axis] concat_tensor = np.empty(tuple(out_shape), dtype=np.float32) for i in range(step): if rank == 5: if axis == 4: concat_tensor[:, :, :, :, i::step] = arrays[i] if axis == 3: concat_tensor[:, :, :, i::step, :] = arrays[i] if axis == 2: concat_tensor[:, :, i::step, :, :] = arrays[i] if axis == 1: concat_tensor[:, i::step, :, :, :] = arrays[i] if axis == 0: concat_tensor[i::step, :, :, :, :] = arrays[i] if rank == 4: if axis == 3: concat_tensor[:, :, :, i::step] = arrays[i] if axis == 2: concat_tensor[:, :, i::step, :] = arrays[i] if axis == 1: concat_tensor[:, i::step, :, :] = arrays[i] if axis == 0: concat_tensor[i::step, :, :, :] = arrays[i] if rank == 3: if axis == 2: concat_tensor[:, :, i::step] = arrays[i] if axis == 1: concat_tensor[:, i::step, :] = arrays[i] if axis == 0: concat_tensor[i::step, :, :] = arrays[i] if rank == 2: if axis == 1: concat_tensor[:, i::step] = arrays[i] if axis == 0: concat_tensor[i::step, :] = arrays[i] if rank == 1: concat_tensor[i::step] = arrays[i] return concat_tensor input_shape = [4, 2, 3, 6, 5] for axis in range(rank): if negative_index: axis = axis - rank shape = tuple(input_shape[:rank]) t1 = np.random.normal(size=shape).astype(np.float32) t2 = np.random.normal(size=shape).astype(np.float32) all_input_arrs = [t1, t2] input_placeholders = { "x": mb.placeholder(shape=t1.shape), "y": mb.placeholder(shape=t2.shape), } input_values = {"x": t1, "y": t2} if n_inputs == 3: t3 = np.random.normal(size=shape).astype(np.float32) input_placeholders["z"] = mb.placeholder(shape=t3.shape) input_values["z"] = t3 all_input_arrs.append(t3) def build_2_inputs(x, y): return (mb.concat(values=(x, y), axis=axis, interleave=True),) def build_3_inputs(x, y, z): return (mb.concat(values=(x, y, z), axis=axis, interleave=True),) np_out = np_concat_interleave(all_input_arrs, axis) expected_output_types = [np_out.shape + (types.fp32,)] expected_outputs = [np_out] run_compare_builder( build_3_inputs if n_inputs == 3 else build_2_inputs, input_placeholders, input_values, expected_output_types, expected_outputs, use_cpu_only=use_cpu_only, frontend_only=False, backend=backend, ) @ssa_fn def test_builder_eval(self): values = [ np.random.rand(1, 1, 6, 2), np.random.rand(1, 1, 3, 2), ] v = mb.concat(values=values, axis=2) np.testing.assert_allclose(np.concatenate(values, 2), v.val, atol=1e-04, rtol=1e-05) @ssa_fn def test_builder_eval_failure(self): values = [ np.random.rand(1, 1, 6, 2), np.random.rand(1, 1, 3, 1), ] with pytest.raises(ValueError): v = mb.concat(values=values, axis=2) class TestSplit: @pytest.mark.parametrize( "use_cpu_only, backend", itertools.product([True, False], backends, ) ) def test_builder_to_backend_smoke(self, use_cpu_only, backend): t = np.array([[1, 2], [3, 4], [5, 6]], dtype=np.float32) input_placeholders = { "x": mb.placeholder(shape=t.shape), } input_values = {"x": t} def build(x): return mb.split(x=x, num_splits=2, axis=1) + mb.split( x=x, split_sizes=[1, 2], axis=0 ) expected_output_types = [ (3, 1, types.fp32), (3, 1, types.fp32), (1, 2, types.fp32), (2, 2, types.fp32), ] expected_outputs = [ np.array([[1], [3], [5]], dtype=np.float32), np.array([[2], [4], [6]], dtype=np.float32), np.array([[1, 2]], dtype=np.float32), np.array([[3, 4], [5, 6]], dtype=np.float32), ] run_compare_builder( build, input_placeholders, input_values, expected_output_types, expected_outputs, use_cpu_only=use_cpu_only, frontend_only=False, backend=backend, ) @ssa_fn def test_builder_eval(self): t = np.array([[1, 2], [3, 4], [5, 6]], dtype=np.float32) vs = mb.split(x=t, num_splits=3, axis=0) es = np.split(t, [1, 2, 3], axis=0) for v, e in zip(vs, es): np.testing.assert_allclose(e, v.val, atol=1e-04, rtol=1e-05) class TestStack: @pytest.mark.parametrize( "use_cpu_only, backend", itertools.product([True, False], backends, ) ) def test_builder_to_backend_smoke(self, use_cpu_only, backend): t1 = np.array([1, 2, 3], dtype=np.float32) t2 = np.array([7, 8, 9], dtype=np.float32) input_placeholders = { "x": mb.placeholder(shape=t1.shape), "y": mb.placeholder(shape=t2.shape), } input_values = {"x": t1, "y": t2} def build(x, y): return [mb.stack(values=(x, y), axis=0), mb.stack(values=(x, y), axis=1)] expected_output_types = [ (2, 3, types.fp32), (3, 2, types.fp32), ] expected_outputs = [ np.array([[1, 2, 3], [7, 8, 9]], dtype=np.float32), np.array([[1, 7], [2, 8], [3, 9]], dtype=np.float32), ] run_compare_builder( build, input_placeholders, input_values, expected_output_types, expected_outputs, use_cpu_only=use_cpu_only, frontend_only=False, backend=backend, ) @ssa_fn def test_builder_eval(self): values = [ np.random.rand(1, 1, 3, 2).astype(np.float32), np.random.rand(1, 1, 3, 2).astype(np.float32), ] v = mb.stack(values=values, axis=2) np.testing.assert_allclose(np.stack(values, 2), v.val, atol=1e-04, rtol=1e-05)
[ "noreply@github.com" ]
lexmz.noreply@github.com
5e8eac17c25523e0b88ce7995848b477fcb94739
93cf8c25ad5475b9697489c0ad567fa861b11bc5
/trunk/multilts/timit/cmudict_to_timit.py
7ed859055ee30ea09e7ab1fe6b99cdf00f2e745a
[]
no_license
BackupTheBerlios/festlang-svn
2d1b0498995bd2620ac7d6bac3fb07cc76b206be
f7325adde1289529bc62aa3aff97f8ff67f1ab82
refs/heads/master
2020-04-11T03:21:02.650683
2011-03-17T09:57:28
2011-03-17T09:57:28
40,663,967
1
0
null
null
null
null
UTF-8
Python
false
false
583
py
#!/usr/bin/python import re # cmudict to timit replacement = { "ah0" : "ah", "ah1" : "ax", "er0" : "axr", "er1" : "er", "ih0" : "ih", "ih1" : "ix", } file = open ("cmudict.0.7a", "r") for line in file: tokens = line.lower().split() word = re.sub ("\([0-9]+\)", "", tokens[0]) result = "(" result += "\"%s\" nil (" % (word) for phone in tokens[1:]: if phone in replacement.keys(): new_phone = replacement[phone] else: new_phone = phone.strip("012") result += " %s" % (new_phone) result += "))" print result
[ "nsh@3ccbf08f-adf1-0310-975e-a3baaf75e68e" ]
nsh@3ccbf08f-adf1-0310-975e-a3baaf75e68e
8bef033af5cd564462af75d5a4bc0287381518cf
95eeebfd1283d8936fcb3b88729e977856fd4219
/Python_Challenge/PyPoll/main.py
1ef3a054b628720ab301998c53b49a5d87c72823
[]
no_license
lraynes/homework
d8e1e3dd782472accbb4ad8ce068e7e6c25dd771
feec8a8e862f2a50dc0f7516e0aa0a0e5571125d
refs/heads/master
2020-03-12T07:41:05.900790
2018-09-20T22:00:51
2018-09-20T22:00:51
130,511,406
0
0
null
null
null
null
UTF-8
Python
false
false
1,752
py
#import as a list of dictionaries #{["Voter ID": ____, "County": _____, "Candidate": _____]} import os import csv def percentage_calc(part,whole): return(str(part/whole * 100) + "%") vote_count = 0 candidate_list = [] can_0_count = 0 can_1_count = 0 can_2_count = 0 can_3_count = 0 #INSTEAD, MAKE THE CANDIDATE LIST INTO A DICTIONARY -> {"Candidate Name": number of votes} election_data_1_path = os.path.join(".", "election_data_1.csv") with open(election_data_1_path, newline="") as csvfile: reader = csv.DictReader(csvfile) for row in reader: vote_count += 1 if row["Candidate"] not in candidate_list: candidate_list.append(row["Candidate"]) if row["Candidate"] == candidate_list[0]: can_0_count += 1 elif row["Candidate"] == candidate_list[1]: can_1_count += 1 elif row["Candidate"] == candidate_list[2]: can_2_count += 1 elif row["Candidate"] == candidate_list[3]: can_3_count += 1 #The total number of votes cast #A complete list of candidates who received votes print(candidate_list) print("Vote count: " + str(vote_count)) print(candidate_list[0] + ": " + percentage_calc(can_0_count,vote_count) + " (" + str(can_0_count) + ")") print(candidate_list[1] + ": " + percentage_calc(can_1_count,vote_count) + " (" + str(can_1_count) + ")") print(candidate_list[2] + ": " + percentage_calc(can_2_count,vote_count) + " (" + str(can_2_count) + ")") print(candidate_list[3] + ": " + percentage_calc(can_3_count,vote_count) + " (" + str(can_3_count) + ")") print("Winner: ") #The percentage of votes each candidate won #The total number of votes each candidate won #The winner of the election based on popular vote.
[ "raynes.laura11@gmail.com" ]
raynes.laura11@gmail.com
40cb7bbdb15f45b488ddfd20090515b60abc5f99
55f5c304ce23c1b3214f2baa322013a3b8118a68
/src/semantic_segmentation/models/model_basic.py
fa138e8ce14b61ec4ce283843b77781bac810e5c
[ "MIT" ]
permissive
ISCAS007/Mask_RCNN
02fd479703c4e1eb2aaa3638f94b6e6ce7bacec7
a24794e68fae65f621abd6af474c78529b1473e8
refs/heads/master
2020-03-07T04:39:53.483184
2018-04-25T06:14:23
2018-04-25T06:14:23
127,272,831
0
0
null
2018-03-29T10:00:05
2018-03-29T10:00:05
null
UTF-8
Python
false
false
6,780
py
# -*- coding: utf-8 -*- import os from keras.applications import MobileNet, VGG16, VGG19, ResNet50, DenseNet121, DenseNet169, DenseNet201, NASNetMobile, InceptionV3, Xception, InceptionResNetV2 from keras.backend import tf as ktf import keras class Interp(keras.layers.Layer): def __init__(self, new_size, **kwargs): self.new_size = new_size super(Interp, self).__init__(**kwargs) def build(self, input_shape): super(Interp, self).build(input_shape) def call(self, inputs, **kwargs): new_height, new_width = self.new_size resized = ktf.image.resize_images(inputs, [new_height, new_width], align_corners=True) return resized def compute_output_shape(self, input_shape): return tuple([None, self.new_size[0], self.new_size[1], input_shape[3]]) def get_config(self): config = super(Interp, self).get_config() config['new_size'] = self.new_size return config def get_encoder(config): encoder = config['encoder'].lower() h, w, c = config['input_shape'] model_path = os.path.join(os.getenv('HOME'), '.keras', 'models') if encoder == 'mobilenet': base_model = MobileNet( include_top=False, weights=None, input_shape=(h, w, 3)) base_model.load_weights(filepath=os.path.join( model_path, 'mobilenet_1_0_224_tf_no_top.h5')) for layer in base_model.layers: layer.trainable = False input0 = base_model.get_layer(index=0) conv1 = base_model.get_layer('conv_pw_1_relu') conv2 = base_model.get_layer('conv_pw_3_relu') conv3 = base_model.get_layer('conv_pw_5_relu') conv4 = base_model.get_layer('conv_pw_11_relu') conv5 = base_model.get_layer('conv_pw_13_relu') elif encoder == 'vgg16': base_model = VGG16(include_top=False, input_shape=(h, w, 3)) for layer in base_model.layers: layer.trainable = False input0 = base_model.get_layer(index=0) conv1 = base_model.get_layer('block1_pool') conv2 = base_model.get_layer('block2_pool') conv3 = base_model.get_layer('block3_pool') conv4 = base_model.get_layer('block4_pool') conv5 = base_model.get_layer('block5_pool') elif encoder == 'vgg19': base_model = VGG19(include_top=False, input_shape=(h, w, 3)) for layer in base_model.layers: layer.trainable = False input0 = base_model.get_layer(index=0) conv1 = base_model.get_layer('block1_pool') conv2 = base_model.get_layer('block2_pool') conv3 = base_model.get_layer('block3_pool') conv4 = base_model.get_layer('block4_pool') conv5 = base_model.get_layer('block5_pool') elif encoder == 'resnet50': base_model = ResNet50( include_top=False, weights='imagenet', input_shape=(h, w, 3)) for layer in base_model.layers: layer.trainable = False # print(layer.name) # base_model.summary() input0 = base_model.get_layer(index=0) conv_names={'112':'activation_1', '55':'activation_10', '28':'activation_22', '14':'activation_40', '7':'activation_49'} # ============================================================================= # layer_idx layer_name # 3 activation_1 # 36 activation_10 # 78 activation_22 # 140 activation_40 # 172 activation_49 # ============================================================================= conv1 = base_model.get_layer(index=3) # 112 _conv2 = base_model.get_layer(index=36) # 55 # conv2 = keras.layers.ZeroPadding2D( # padding=((0, 1), (0, 1)), data_format=config['data_format']) # 56 conv2 = Interp(new_size=(56,56)) conv2(_conv2.output) conv2.trainable = False # print('_output shape is', conv2.output_shape) conv3 = base_model.get_layer(index=78) conv4 = base_model.get_layer(index=140) conv5 = base_model.get_layer(index=172) for layer in base_model.layers: layer.name="_".join([encoder,layer.name]) # for idx,layer in enumerate([conv1,conv2,conv3,conv4,conv5]): # print('conv%d: %s'%(idx,layer.name)) elif encoder.lower()=='NASNetMobile'.lower(): print('unknown encoder') assert False base_model = NASNetMobile( include_top=False, weights='imagenet', input_shape=(h, w, 3)) conv_names={'111':'reduction_bn_1_stem_1', '56':'adjust_bn_stem_2', '28':'adjust_bn_reduce_4', '14':'adjust_bn_reduce_8', '7':'normal_concat_12'} else: # simplify interface if encoder.lower()=='DenseNet121'.lower(): base_model = DenseNet121( include_top=False, weights='imagenet', input_shape=(h, w, 3)) conv_names=['conv1/relu','pool2_conv','pool3_conv','pool4_conv','conv5_block16_concat'] elif encoder.lower()=='DenseNet169'.lower(): base_model = DenseNet169( include_top=False, weights='imagenet', input_shape=(h, w, 3)) conv_names=['conv1/relu','pool2_conv','pool3_conv','pool4_conv','conv5_block32_concat'] elif encoder.lower()=='DenseNet201'.lower(): base_model = DenseNet201( include_top=False, weights='imagenet', input_shape=(h, w, 3)) conv_names=['conv1/relu','pool2_conv','pool3_conv','pool4_conv','conv5_block32_concat'] elif encoder.lower()=='InceptionResNetV2'.lower(): print('unknown encoder') assert False #input_shape=[(299,299,3)] elif encoder.lower()=='InceptionV3'.lower(): print('unknown encoder') assert False #input_shape=(299,299,3) pass elif encoder.lower()=='Xception'.lower(): print('unknown encoder') assert False #input_shape=(299,299,3) pass else: print('unknown encoder') assert False for layer in base_model.layers: layer.trainable = False input0 = base_model.get_layer(index=0) conv_layers=[input0] for layer_name in conv_names: layer=base_model.get_layer(layer_name) conv_layers.append(layer) return conv_layers input_layers = [input0, conv1, conv2, conv3, conv4, conv5] return input_layers
[ "youdaoyzbx@163.com" ]
youdaoyzbx@163.com
744df70ea05418f0a741e97fcc351ced8f4e5eda
b76615ff745c6d66803506251c3d4109faf50802
/pyobjc-framework-WebKit/Lib/WebKit/_metadata.py
7a409aa4e1b20a8ba287c34c47b34b62635a083f
[ "MIT" ]
permissive
danchr/pyobjc-git
6ef17e472f54251e283a0801ce29e9eff9c20ac0
62b787fddeb381184043c7ff136f1c480755ab69
refs/heads/master
2021-01-04T12:24:31.581750
2020-02-02T20:43:02
2020-02-02T20:43:02
240,537,392
0
0
null
null
null
null
UTF-8
Python
false
false
101,324
py
# This file is generated by objective.metadata # # Last update: Tue Jul 30 21:56:03 2019 import objc, sys if sys.maxsize > 2 ** 32: def sel32or64(a, b): return b else: def sel32or64(a, b): return a if sys.byteorder == "little": def littleOrBig(a, b): return a else: def littleOrBig(a, b): return b misc = {} misc.update( { "WebPreferencesPrivate": objc.createStructType( "WebPreferencesPrivate", b"{WebPreferencesPrivate=}", [] ), "DOMObjectInternal": objc.createStructType( "DOMObjectInternal", b"{DOMObjectInternal=}", [] ), } ) constants = """$DOMEventException$DOMException$DOMRangeException$DOMXPathException$NSReadAccessURLDocumentOption$WKErrorDomain$WKWebsiteDataTypeCookies$WKWebsiteDataTypeDiskCache$WKWebsiteDataTypeFetchCache$WKWebsiteDataTypeIndexedDBDatabases$WKWebsiteDataTypeLocalStorage$WKWebsiteDataTypeMemoryCache$WKWebsiteDataTypeOfflineWebApplicationCache$WKWebsiteDataTypeServiceWorkerRegistrations$WKWebsiteDataTypeSessionStorage$WKWebsiteDataTypeWebSQLDatabases$WebActionButtonKey$WebActionElementKey$WebActionModifierFlagsKey$WebActionNavigationTypeKey$WebActionOriginalURLKey$WebArchivePboardType$WebElementDOMNodeKey$WebElementFrameKey$WebElementImageAltStringKey$WebElementImageKey$WebElementImageRectKey$WebElementImageURLKey$WebElementIsSelectedKey$WebElementLinkLabelKey$WebElementLinkTargetFrameKey$WebElementLinkTitleKey$WebElementLinkURLKey$WebHistoryAllItemsRemovedNotification$WebHistoryItemChangedNotification$WebHistoryItemsAddedNotification$WebHistoryItemsKey$WebHistoryItemsRemovedNotification$WebHistoryLoadedNotification$WebHistorySavedNotification$WebKitErrorDomain$WebKitErrorMIMETypeKey$WebKitErrorPlugInNameKey$WebKitErrorPlugInPageURLStringKey$WebPlugInAttributesKey$WebPlugInBaseURLKey$WebPlugInContainerKey$WebPlugInContainingElementKey$WebPlugInShouldLoadMainResourceKey$WebPreferencesChangedNotification$WebViewDidBeginEditingNotification$WebViewDidChangeNotification$WebViewDidChangeSelectionNotification$WebViewDidChangeTypingStyleNotification$WebViewDidEndEditingNotification$WebViewProgressEstimateChangedNotification$WebViewProgressFinishedNotification$WebViewProgressStartedNotification$""" enums = """$DOM_ADDITION@2$DOM_ALLOW_KEYBOARD_INPUT@1$DOM_ANY_TYPE@0$DOM_ANY_UNORDERED_NODE_TYPE@8$DOM_ATTRIBUTE_NODE@2$DOM_AT_TARGET@2$DOM_BAD_BOUNDARYPOINTS_ERR@1$DOM_BOOLEAN_TYPE@3$DOM_BOTH@2$DOM_BUBBLING_PHASE@3$DOM_CAPTURING_PHASE@1$DOM_CDATA_SECTION_NODE@4$DOM_CHARSET_RULE@2$DOM_COMMENT_NODE@8$DOM_CSS_ATTR@22$DOM_CSS_CM@6$DOM_CSS_COUNTER@23$DOM_CSS_CUSTOM@3$DOM_CSS_DEG@11$DOM_CSS_DIMENSION@18$DOM_CSS_EMS@3$DOM_CSS_EXS@4$DOM_CSS_GRAD@13$DOM_CSS_HZ@16$DOM_CSS_IDENT@21$DOM_CSS_IN@8$DOM_CSS_INHERIT@0$DOM_CSS_KHZ@17$DOM_CSS_MM@7$DOM_CSS_MS@14$DOM_CSS_NUMBER@1$DOM_CSS_PC@10$DOM_CSS_PERCENTAGE@2$DOM_CSS_PRIMITIVE_VALUE@1$DOM_CSS_PT@9$DOM_CSS_PX@5$DOM_CSS_RAD@12$DOM_CSS_RECT@24$DOM_CSS_RGBCOLOR@25$DOM_CSS_S@15$DOM_CSS_STRING@19$DOM_CSS_UNKNOWN@0$DOM_CSS_URI@20$DOM_CSS_VALUE_LIST@2$DOM_CSS_VH@27$DOM_CSS_VMAX@29$DOM_CSS_VMIN@28$DOM_CSS_VW@26$DOM_DOCUMENT_FRAGMENT_NODE@11$DOM_DOCUMENT_NODE@9$DOM_DOCUMENT_POSITION_CONTAINED_BY@16$DOM_DOCUMENT_POSITION_CONTAINS@8$DOM_DOCUMENT_POSITION_DISCONNECTED@1$DOM_DOCUMENT_POSITION_FOLLOWING@4$DOM_DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC@32$DOM_DOCUMENT_POSITION_PRECEDING@2$DOM_DOCUMENT_TYPE_NODE@10$DOM_DOMSTRING_SIZE_ERR@2$DOM_DOM_DELTA_LINE@1$DOM_DOM_DELTA_PAGE@2$DOM_DOM_DELTA_PIXEL@0$DOM_ELEMENT_NODE@1$DOM_END_TO_END@2$DOM_END_TO_START@3$DOM_ENTITY_NODE@6$DOM_ENTITY_REFERENCE_NODE@5$DOM_FILTER_ACCEPT@1$DOM_FILTER_REJECT@2$DOM_FILTER_SKIP@3$DOM_FIRST_ORDERED_NODE_TYPE@9$DOM_FONT_FACE_RULE@5$DOM_HIERARCHY_REQUEST_ERR@3$DOM_HORIZONTAL@0$DOM_IMPORT_RULE@3$DOM_INDEX_SIZE_ERR@1$DOM_INUSE_ATTRIBUTE_ERR@10$DOM_INVALID_ACCESS_ERR@15$DOM_INVALID_CHARACTER_ERR@5$DOM_INVALID_EXPRESSION_ERR@51$DOM_INVALID_MODIFICATION_ERR@13$DOM_INVALID_NODE_TYPE_ERR@2$DOM_INVALID_STATE_ERR@11$DOM_KEYFRAMES_RULE@7$DOM_KEYFRAME_RULE@8$DOM_KEY_LOCATION_LEFT@1$DOM_KEY_LOCATION_NUMPAD@3$DOM_KEY_LOCATION_RIGHT@2$DOM_KEY_LOCATION_STANDARD@0$DOM_MEDIA_RULE@4$DOM_MODIFICATION@1$DOM_NAMESPACE_ERR@14$DOM_NAMESPACE_RULE@10$DOM_NODE_AFTER@1$DOM_NODE_BEFORE@0$DOM_NODE_BEFORE_AND_AFTER@2$DOM_NODE_INSIDE@3$DOM_NONE@0$DOM_NOTATION_NODE@12$DOM_NOT_FOUND_ERR@8$DOM_NOT_SUPPORTED_ERR@9$DOM_NO_DATA_ALLOWED_ERR@6$DOM_NO_MODIFICATION_ALLOWED_ERR@7$DOM_NUMBER_TYPE@1$DOM_ORDERED_NODE_ITERATOR_TYPE@5$DOM_ORDERED_NODE_SNAPSHOT_TYPE@7$DOM_PAGE_RULE@6$DOM_PROCESSING_INSTRUCTION_NODE@7$DOM_REMOVAL@3$DOM_SHOW_ALL@4294967295$DOM_SHOW_ATTRIBUTE@2$DOM_SHOW_CDATA_SECTION@8$DOM_SHOW_COMMENT@128$DOM_SHOW_DOCUMENT@256$DOM_SHOW_DOCUMENT_FRAGMENT@1024$DOM_SHOW_DOCUMENT_TYPE@512$DOM_SHOW_ELEMENT@1$DOM_SHOW_ENTITY@32$DOM_SHOW_ENTITY_REFERENCE@16$DOM_SHOW_NOTATION@2048$DOM_SHOW_PROCESSING_INSTRUCTION@64$DOM_SHOW_TEXT@4$DOM_START_TO_END@1$DOM_START_TO_START@0$DOM_STRING_TYPE@2$DOM_STYLE_RULE@1$DOM_SUPPORTS_RULE@12$DOM_SYNTAX_ERR@12$DOM_TEXT_NODE@3$DOM_TYPE_ERR@52$DOM_UNKNOWN_RULE@0$DOM_UNORDERED_NODE_ITERATOR_TYPE@4$DOM_UNORDERED_NODE_SNAPSHOT_TYPE@6$DOM_UNSPECIFIED_EVENT_TYPE_ERR@0$DOM_VARIABLES_RULE@7$DOM_VERTICAL@1$DOM_WEBKIT_KEYFRAMES_RULE@7$DOM_WEBKIT_KEYFRAME_RULE@8$DOM_WEBKIT_REGION_RULE@16$DOM_WRONG_DOCUMENT_ERR@4$WKAudiovisualMediaTypeAll@18446744073709551615$WKAudiovisualMediaTypeAudio@1$WKAudiovisualMediaTypeNone@0$WKAudiovisualMediaTypeVideo@2$WKContentModeDesktop@2$WKContentModeMobile@1$WKContentModeRecommended@0$WKErrorAttributedStringContentFailedToLoad@10$WKErrorAttributedStringContentLoadTimedOut@11$WKErrorContentRuleListStoreCompileFailed@6$WKErrorContentRuleListStoreLookUpFailed@7$WKErrorContentRuleListStoreRemoveFailed@8$WKErrorContentRuleListStoreVersionMismatch@9$WKErrorJavaScriptExceptionOccurred@4$WKErrorJavaScriptResultTypeIsUnsupported@5$WKErrorUnknown@1$WKErrorWebContentProcessTerminated@2$WKErrorWebViewInvalidated@3$WKNavigationActionPolicyAllow@1$WKNavigationActionPolicyCancel@0$WKNavigationResponsePolicyAllow@1$WKNavigationResponsePolicyCancel@0$WKNavigationTypeBackForward@2$WKNavigationTypeFormResubmitted@4$WKNavigationTypeFormSubmitted@1$WKNavigationTypeLinkActivated@0$WKNavigationTypeOther@-1$WKNavigationTypeReload@3$WKUserInterfaceDirectionPolicyContent@0$WKUserInterfaceDirectionPolicySystem@1$WKUserScriptInjectionTimeAtDocumentEnd@1$WKUserScriptInjectionTimeAtDocumentStart@0$WebCacheModelDocumentBrowser@1$WebCacheModelDocumentViewer@0$WebCacheModelPrimaryWebBrowser@2$WebDragDestinationActionAny@4294967295$WebDragDestinationActionDHTML@1$WebDragDestinationActionEdit@2$WebDragDestinationActionLoad@4$WebDragDestinationActionNone@0$WebDragSourceActionAny@4294967295$WebDragSourceActionDHTML@1$WebDragSourceActionImage@2$WebDragSourceActionLink@4$WebDragSourceActionNone@0$WebDragSourceActionSelection@8$WebJNIReturnTypeBoolean@3$WebJNIReturnTypeByte@4$WebJNIReturnTypeChar@5$WebJNIReturnTypeDouble@10$WebJNIReturnTypeFloat@9$WebJNIReturnTypeInt@7$WebJNIReturnTypeInvalid@0$WebJNIReturnTypeLong@8$WebJNIReturnTypeObject@2$WebJNIReturnTypeShort@6$WebJNIReturnTypeVoid@1$WebKitErrorBlockedPlugInVersion@203$WebKitErrorCannotFindPlugIn@200$WebKitErrorCannotLoadPlugIn@201$WebKitErrorCannotShowMIMEType@100$WebKitErrorCannotShowURL@101$WebKitErrorFrameLoadInterruptedByPolicyChange@102$WebKitErrorJavaUnavailable@202$WebMenuItemPDFActualSize@24$WebMenuItemPDFAutoSize@27$WebMenuItemPDFContinuous@30$WebMenuItemPDFFacingPages@29$WebMenuItemPDFNextPage@31$WebMenuItemPDFPreviousPage@32$WebMenuItemPDFSinglePage@28$WebMenuItemPDFZoomIn@25$WebMenuItemPDFZoomOut@26$WebMenuItemTagCopy@8$WebMenuItemTagCopyImageToClipboard@6$WebMenuItemTagCopyLinkToClipboard@3$WebMenuItemTagCut@13$WebMenuItemTagDownloadImageToDisk@5$WebMenuItemTagDownloadLinkToDisk@2$WebMenuItemTagGoBack@9$WebMenuItemTagGoForward@10$WebMenuItemTagIgnoreSpelling@17$WebMenuItemTagLearnSpelling@18$WebMenuItemTagLookUpInDictionary@22$WebMenuItemTagNoGuessesFound@16$WebMenuItemTagOpenFrameInNewWindow@7$WebMenuItemTagOpenImageInNewWindow@4$WebMenuItemTagOpenLinkInNewWindow@1$WebMenuItemTagOpenWithDefaultApplication@23$WebMenuItemTagOther@19$WebMenuItemTagPaste@14$WebMenuItemTagReload@12$WebMenuItemTagSearchInSpotlight@20$WebMenuItemTagSearchWeb@21$WebMenuItemTagSpellingGuess@15$WebMenuItemTagStop@11$WebNavigationTypeBackForward@2$WebNavigationTypeFormResubmitted@4$WebNavigationTypeFormSubmitted@1$WebNavigationTypeLinkClicked@0$WebNavigationTypeOther@5$WebNavigationTypeReload@3$WebViewInsertActionDropped@2$WebViewInsertActionPasted@1$WebViewInsertActionTyped@0$""" misc.update({"WK_API_ENABLED": sel32or64(0, 1)}) misc.update({}) functions = { "WebInitForCarbon": (b"v", "", {"deprecated": 1006}), "WebConvertNSImageToCGImageRef": (b"^{CGImage=}@", "", {"deprecated": 1006}), } aliases = { "WebNSUInteger": "NSUInteger", "WKAudiovisualMediaTypeAll": "NSUIntegerMax", "WebNSInteger": "NSInteger", } r = objc.registerMetaDataForSelector objc._updatingMetadata(True) try: r(b"DOMAttr", b"specified", {"retval": {"type": "Z"}}) r(b"DOMCSSStyleDeclaration", b"isPropertyImplicit:", {"retval": {"type": "Z"}}) r(b"DOMDocument", b"createNodeIterator::::", {"arguments": {5: {"type": "Z"}}}) r( b"DOMDocument", b"createNodeIterator:whatToShow:filter:expandEntityReferences:", {"arguments": {5: {"type": "Z"}}}, ) r(b"DOMDocument", b"createTreeWalker::::", {"arguments": {5: {"type": "Z"}}}) r( b"DOMDocument", b"createTreeWalker:whatToShow:filter:expandEntityReferences:", {"arguments": {5: {"type": "Z"}}}, ) r(b"DOMDocument", b"execCommand:", {"retval": {"type": "Z"}}) r( b"DOMDocument", b"execCommand:userInterface:", {"retval": {"type": "Z"}, "arguments": {3: {"type": "Z"}}}, ) r( b"DOMDocument", b"execCommand:userInterface:value:", {"retval": {"type": "Z"}, "arguments": {3: {"type": "Z"}}}, ) r( b"DOMDocument", b"getMatchedCSSRules:pseudoElement:authorOnly:", {"arguments": {4: {"type": "Z"}}}, ) r(b"DOMDocument", b"hasFocus", {"retval": {"type": b"Z"}}) r(b"DOMDocument", b"importNode::", {"arguments": {3: {"type": "Z"}}}) r(b"DOMDocument", b"importNode:deep:", {"arguments": {3: {"type": "Z"}}}) r(b"DOMDocument", b"queryCommandEnabled:", {"retval": {"type": "Z"}}) r(b"DOMDocument", b"queryCommandIndeterm:", {"retval": {"type": "Z"}}) r(b"DOMDocument", b"queryCommandState:", {"retval": {"type": "Z"}}) r(b"DOMDocument", b"queryCommandSupported:", {"retval": {"type": "Z"}}) r(b"DOMDocument", b"setXmlStandalone:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMDocument", b"xmlStandalone", {"retval": {"type": "Z"}}) r(b"DOMElement", b"contains:", {"retval": {"type": "Z"}}) r(b"DOMElement", b"hasAttribute:", {"retval": {"type": "Z"}}) r(b"DOMElement", b"hasAttributeNS::", {"retval": {"type": "Z"}}) r(b"DOMElement", b"hasAttributeNS:localName:", {"retval": {"type": "Z"}}) r(b"DOMElement", b"scrollIntoView:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMElement", b"scrollIntoViewIfNeeded:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMEvent", b"bubbles", {"retval": {"type": "Z"}}) r(b"DOMEvent", b"cancelBubble", {"retval": {"type": "Z"}}) r(b"DOMEvent", b"cancelable", {"retval": {"type": "Z"}}) r(b"DOMEvent", b"initEvent:::", {"arguments": {3: {"type": "Z"}, 4: {"type": "Z"}}}) r( b"DOMEvent", b"initEvent:canBubbleArg:cancelableArg:", {"arguments": {3: {"type": "Z"}, 4: {"type": "Z"}}}, ) r(b"DOMEvent", b"returnValue", {"retval": {"type": "Z"}}) r(b"DOMEvent", b"setCancelBubble:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMEvent", b"setReturnValue:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLAreaElement", b"noHref", {"retval": {"type": "Z"}}) r(b"DOMHTMLAreaElement", b"setNoHref:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLButtonElement", b"autofocus", {"retval": {"type": "Z"}}) r(b"DOMHTMLButtonElement", b"disabled", {"retval": {"type": "Z"}}) r(b"DOMHTMLButtonElement", b"setAutofocus:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLButtonElement", b"setDisabled:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLButtonElement", b"setWillValidate:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLButtonElement", b"willValidate", {"retval": {"type": "Z"}}) r(b"DOMHTMLDListElement", b"compact", {"retval": {"type": "Z"}}) r(b"DOMHTMLDListElement", b"setCompact:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLDirectoryElement", b"compact", {"retval": {"type": "Z"}}) r(b"DOMHTMLDirectoryElement", b"setCompact:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLDocument", b"hasFocus", {"retval": {"type": b"Z"}}) r(b"DOMHTMLElement", b"isContentEditable", {"retval": {"type": "Z"}}) r(b"DOMHTMLFrameElement", b"noResize", {"retval": {"type": "Z"}}) r(b"DOMHTMLFrameElement", b"setNoResize:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLHRElement", b"noShade", {"retval": {"type": "Z"}}) r(b"DOMHTMLHRElement", b"setNoShade:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLImageElement", b"complete", {"retval": {"type": "Z"}}) r(b"DOMHTMLImageElement", b"isMap", {"retval": {"type": "Z"}}) r(b"DOMHTMLImageElement", b"setComplete:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLImageElement", b"setIsMap:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLInputElement", b"autofocus", {"retval": {"type": "Z"}}) r(b"DOMHTMLInputElement", b"checked", {"retval": {"type": "Z"}}) r(b"DOMHTMLInputElement", b"defaultChecked", {"retval": {"type": "Z"}}) r(b"DOMHTMLInputElement", b"disabled", {"retval": {"type": "Z"}}) r(b"DOMHTMLInputElement", b"indeterminate", {"retval": {"type": "Z"}}) r(b"DOMHTMLInputElement", b"multiple", {"retval": {"type": "Z"}}) r(b"DOMHTMLInputElement", b"readOnly", {"retval": {"type": "Z"}}) r(b"DOMHTMLInputElement", b"setAutofocus:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLInputElement", b"setChecked:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLInputElement", b"setDefaultChecked:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLInputElement", b"setDisabled:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLInputElement", b"setIndeterminate:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLInputElement", b"setMultiple:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLInputElement", b"setReadOnly:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLInputElement", b"willValidate", {"retval": {"type": "Z"}}) r(b"DOMHTMLLinkElement", b"disabled", {"retval": {"type": "Z"}}) r(b"DOMHTMLLinkElement", b"setDisabled:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLMenuElement", b"compact", {"retval": {"type": "Z"}}) r(b"DOMHTMLMenuElement", b"setCompact:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLOListElement", b"compact", {"retval": {"type": "Z"}}) r(b"DOMHTMLOListElement", b"setCompact:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLObjectElement", b"declare", {"retval": {"type": "Z"}}) r(b"DOMHTMLObjectElement", b"setDeclare:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLOptGroupElement", b"disabled", {"retval": {"type": "Z"}}) r(b"DOMHTMLOptGroupElement", b"setDisabled:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLOptionElement", b"defaultSelected", {"retval": {"type": "Z"}}) r(b"DOMHTMLOptionElement", b"disabled", {"retval": {"type": "Z"}}) r(b"DOMHTMLOptionElement", b"selected", {"retval": {"type": "Z"}}) r( b"DOMHTMLOptionElement", b"setDefaultSelected:", {"arguments": {2: {"type": "Z"}}}, ) r(b"DOMHTMLOptionElement", b"setDisabled:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLOptionElement", b"setSelected:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLPreElement", b"setWrap:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLPreElement", b"wrap", {"retval": {"type": "Z"}}) r(b"DOMHTMLScriptElement", b"defer", {"retval": {"type": "Z"}}) r(b"DOMHTMLScriptElement", b"setDefer:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLSelectElement", b"autofocus", {"retval": {"type": "Z"}}) r(b"DOMHTMLSelectElement", b"disabled", {"retval": {"type": "Z"}}) r(b"DOMHTMLSelectElement", b"multiple", {"retval": {"type": "Z"}}) r(b"DOMHTMLSelectElement", b"setAutofocus:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLSelectElement", b"setDisabled:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLSelectElement", b"setMultiple:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLSelectElement", b"willValidate", {"retval": {"type": "Z"}}) r(b"DOMHTMLStyleElement", b"disabled", {"retval": {"type": "Z"}}) r(b"DOMHTMLStyleElement", b"setDisabled:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLTableCellElement", b"noWrap", {"retval": {"type": "Z"}}) r(b"DOMHTMLTableCellElement", b"setNoWrap:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLTextAreaElement", b"autofocus", {"retval": {"type": b"Z"}}) r(b"DOMHTMLTextAreaElement", b"disabled", {"retval": {"type": "Z"}}) r(b"DOMHTMLTextAreaElement", b"readOnly", {"retval": {"type": "Z"}}) r(b"DOMHTMLTextAreaElement", b"setAutofocus:", {"arguments": {2: {"type": b"Z"}}}) r(b"DOMHTMLTextAreaElement", b"setDisabled:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLTextAreaElement", b"setReadOnly:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMHTMLTextAreaElement", b"willValidate", {"retval": {"type": "Z"}}) r(b"DOMHTMLUListElement", b"compact", {"retval": {"type": "Z"}}) r(b"DOMHTMLUListElement", b"setCompact:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMImplementation", b"hasFeature::", {"retval": {"type": "Z"}}) r(b"DOMImplementation", b"hasFeature:version:", {"retval": {"type": "Z"}}) r(b"DOMKeyboardEvent", b"altGraphKey", {"retval": {"type": "Z"}}) r(b"DOMKeyboardEvent", b"altKey", {"retval": {"type": "Z"}}) r(b"DOMKeyboardEvent", b"ctrlKey", {"retval": {"type": "Z"}}) r(b"DOMKeyboardEvent", b"getModifierState:", {"retval": {"type": "Z"}}) r( b"DOMKeyboardEvent", b"initKeyboardEvent:canBubble:cancelable:view:keyIdentifier:keyLocation:ctrlKey:altKey:shiftKey:metaKey:", { "arguments": { 3: {"type": "Z"}, 4: {"type": "Z"}, 8: {"type": "Z"}, 9: {"type": "Z"}, 10: {"type": "Z"}, 11: {"type": "Z"}, } }, ) r( b"DOMKeyboardEvent", b"initKeyboardEvent:canBubble:cancelable:view:keyIdentifier:keyLocation:ctrlKey:altKey:shiftKey:metaKey:altGraphKey:", { "arguments": { 3: {"type": "Z"}, 4: {"type": "Z"}, 8: {"type": "Z"}, 9: {"type": "Z"}, 10: {"type": "Z"}, 11: {"type": "Z"}, 12: {"type": "Z"}, } }, ) r( b"DOMKeyboardEvent", b"initKeyboardEvent:canBubble:cancelable:view:keyIdentifier:location:ctrlKey:altKey:shiftKey:metaKey:", { "arguments": { 3: {"type": b"Z"}, 4: {"type": b"Z"}, 8: {"type": b"Z"}, 9: {"type": b"Z"}, 10: {"type": b"Z"}, 11: {"type": b"Z"}, } }, ) r( b"DOMKeyboardEvent", b"initKeyboardEvent:canBubble:cancelable:view:keyIdentifier:location:ctrlKey:altKey:shiftKey:metaKey:altGraphKey:", { "arguments": { 3: {"type": b"Z"}, 4: {"type": b"Z"}, 8: {"type": b"Z"}, 9: {"type": b"Z"}, 10: {"type": b"Z"}, 11: {"type": b"Z"}, 12: {"type": b"Z"}, } }, ) r(b"DOMKeyboardEvent", b"metaKey", {"retval": {"type": "Z"}}) r(b"DOMKeyboardEvent", b"shiftKey", {"retval": {"type": "Z"}}) r(b"DOMMouseEvent", b"altKey", {"retval": {"type": "Z"}}) r(b"DOMMouseEvent", b"ctrlKey", {"retval": {"type": "Z"}}) r( b"DOMMouseEvent", b"initMouseEvent:::::::::::::::", { "arguments": { 3: {"type": b"Z"}, 4: {"type": b"Z"}, 11: {"type": b"Z"}, 12: {"type": b"Z"}, 13: {"type": b"Z"}, 14: {"type": b"Z"}, } }, ) r( b"DOMMouseEvent", b"initMouseEvent:canBubble:cancelable:view:detail:screenX:screenY:clientX:clientY:ctrlKey:altKey:shiftKey:metaKey:button:relatedTarget:", { "arguments": { 3: {"type": "Z"}, 4: {"type": "Z"}, 11: {"type": "Z"}, 12: {"type": "Z"}, 13: {"type": "Z"}, 14: {"type": "Z"}, } }, ) r(b"DOMMouseEvent", b"metaKey", {"retval": {"type": "Z"}}) r(b"DOMMouseEvent", b"shiftKey", {"retval": {"type": "Z"}}) r( b"DOMMutationEvent", b"initMutationEvent::::::::", {"arguments": {3: {"type": "Z"}, 4: {"type": "Z"}}}, ) r( b"DOMMutationEvent", b"initMutationEvent:canBubble:cancelable:relatedNode:prevValue:newValue:attrName:attrChange:", {"arguments": {3: {"type": "Z"}, 4: {"type": "Z"}}}, ) r(b"DOMNode", b"cloneNode:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMNode", b"contains:", {"retval": {"type": "Z"}}) r(b"DOMNode", b"hasAttributes", {"retval": {"type": "Z"}}) r(b"DOMNode", b"hasChildNodes", {"retval": {"type": "Z"}}) r(b"DOMNode", b"isContentEditable", {"retval": {"type": "Z"}}) r(b"DOMNode", b"isDefaultNamespace:", {"retval": {"type": b"Z"}}) r(b"DOMNode", b"isEqualNode:", {"retval": {"type": "Z"}}) r(b"DOMNode", b"isSameNode:", {"retval": {"type": "Z"}}) r(b"DOMNode", b"isSupported::", {"retval": {"type": "Z"}}) r(b"DOMNode", b"isSupported:version:", {"retval": {"type": "Z"}}) r(b"DOMNode", b"setIsContentEditable:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMNodeIterator", b"expandEntityReferences", {"retval": {"type": "Z"}}) r(b"DOMNodeIterator", b"pointerBeforeReferenceNode", {"retval": {"type": "Z"}}) r(b"DOMOverflowEvent", b"horizontalOverflow", {"retval": {"type": "Z"}}) r( b"DOMOverflowEvent", b"initOverflowEvent:horizontalOverflow:verticalOverflow:", {"arguments": {3: {"type": "Z"}, 4: {"type": "Z"}}}, ) r(b"DOMOverflowEvent", b"verticalOverflow", {"retval": {"type": "Z"}}) r(b"DOMProgressEvent", b"lengthComputable", {"retval": {"type": b"Z"}}) r(b"DOMRange", b"collapse:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMRange", b"collapsed", {"retval": {"type": "Z"}}) r(b"DOMRange", b"intersectsNode:", {"retval": {"type": "Z"}}) r(b"DOMRange", b"isPointInRange:offset:", {"retval": {"type": "Z"}}) r(b"DOMStyleSheet", b"disabled", {"retval": {"type": "Z"}}) r(b"DOMStyleSheet", b"setDisabled:", {"arguments": {2: {"type": "Z"}}}) r(b"DOMTreeWalker", b"expandEntityReferences", {"retval": {"type": "Z"}}) r( b"DOMUIEvent", b"initUIEvent:::::", {"arguments": {3: {"type": "Z"}, 4: {"type": "Z"}}}, ) r( b"DOMUIEvent", b"initUIEvent:canBubble:cancelable:view:detail:", {"arguments": {3: {"type": "Z"}, 4: {"type": "Z"}}}, ) r(b"DOMWheelEvent", b"altKey", {"retval": {"type": "Z"}}) r(b"DOMWheelEvent", b"ctrlKey", {"retval": {"type": "Z"}}) r( b"DOMWheelEvent", b"initWheelEvent:wheelDeltaY:view:screenX:screenY:clientX:clientY:ctrlKey:altKey:shiftKey:metaKey:", { "arguments": { 9: {"type": b"Z"}, 10: {"type": b"Z"}, 11: {"type": b"Z"}, 12: {"type": b"Z"}, } }, ) r(b"DOMWheelEvent", b"isHorizontal", {"retval": {"type": "Z"}}) r(b"DOMWheelEvent", b"metaKey", {"retval": {"type": "Z"}}) r(b"DOMWheelEvent", b"shiftKey", {"retval": {"type": "Z"}}) r(b"DOMXPathResult", b"booleanValue", {"retval": {"type": "Z"}}) r(b"DOMXPathResult", b"invalidIteratorState", {"retval": {"type": "Z"}}) r( b"NSAttributedString", b"loadFromHTMLWithData:options:completionHandler:", { "arguments": { 4: { "callable": { "retval": {"type": b"v"}, "arguments": { 0: {"type": b"^v"}, 1: {"type": b"@"}, 2: {"type": b"@"}, 3: {"type": b"@"}, }, } } } }, ) r( b"NSAttributedString", b"loadFromHTMLWithFileURL:options:completionHandler:", { "arguments": { 4: { "callable": { "retval": {"type": b"v"}, "arguments": { 0: {"type": b"^v"}, 1: {"type": b"@"}, 2: {"type": b"@"}, 3: {"type": b"@"}, }, } } } }, ) r( b"NSAttributedString", b"loadFromHTMLWithRequest:options:completionHandler:", { "arguments": { 4: { "callable": { "retval": {"type": b"v"}, "arguments": { 0: {"type": b"^v"}, 1: {"type": b"@"}, 2: {"type": b"@"}, 3: {"type": b"@"}, }, } } } }, ) r( b"NSAttributedString", b"loadFromHTMLWithString:options:completionHandler:", { "arguments": { 4: { "callable": { "retval": {"type": b"v"}, "arguments": { 0: {"type": b"^v"}, 1: {"type": b"@"}, 2: {"type": b"@"}, 3: {"type": b"@"}, }, } } } }, ) r( b"NSObject", b"acceptNode:", {"required": True, "retval": {"type": "s"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"addEventListener:::", { "required": True, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": "Z"}}, }, ) r( b"NSObject", b"addEventListener:listener:useCapture:", { "required": True, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": "Z"}}, }, ) r(b"NSObject", b"attributedString", {"required": True, "retval": {"type": b"@"}}) r( b"NSObject", b"canProvideDocumentSource", {"required": True, "retval": {"type": "Z"}}, ) r(b"NSObject", b"cancel", {"required": True, "retval": {"type": b"v"}}) r( b"NSObject", b"chooseFilename:", {"required": True, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"chooseFilenames:", {"required": True, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"cookiesDidChangeInCookieStore:", {"required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"dataSourceUpdated:", {"required": True, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r(b"NSObject", b"deselectAll", {"required": True, "retval": {"type": b"v"}}) r( b"NSObject", b"didFailWithError:", {"required": True, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r(b"NSObject", b"didFinish", {"required": True, "retval": {"type": b"v"}}) r( b"NSObject", b"didReceiveData:", {"required": True, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"didReceiveResponse:", {"required": True, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"dispatchEvent:", {"required": True, "retval": {"type": "Z"}, "arguments": {2: {"type": b"@"}}}, ) r(b"NSObject", b"documentSource", {"required": True, "retval": {"type": b"@"}}) r(b"NSObject", b"download", {"required": True, "retval": {"type": b"v"}}) r( b"NSObject", b"downloadWindowForAuthenticationSheet:", {"required": False, "retval": {"type": b"@"}, "arguments": {2: {"type": b"@"}}}, ) r(b"NSObject", b"finalizeForWebScript", {"retval": {"type": b"v"}}) r( b"NSObject", b"finishedLoadingWithDataSource:", {"required": True, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"handleEvent:", {"required": True, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r(b"NSObject", b"ignore", {"required": True, "retval": {"type": b"v"}}) r( b"NSObject", b"invokeDefaultMethodWithArguments:", {"retval": {"type": b"@"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"invokeUndefinedMethodFromWebScript:withArguments:", {"retval": {"type": b"@"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}}, ) r( b"NSObject", b"isKeyExcludedFromWebScript:", { "retval": {"type": "Z"}, "arguments": {2: {"c_array_delimited_by_null": True, "type": "n^t"}}, }, ) r( b"NSObject", b"isSelectorExcludedFromWebScript:", {"retval": {"type": "Z"}, "arguments": {2: {"type": ":"}}}, ) r(b"NSObject", b"layout", {"required": True, "retval": {"type": b"v"}}) r( b"NSObject", b"lookupNamespaceURI:", {"required": True, "retval": {"type": b"@"}, "arguments": {2: {"type": b"@"}}}, ) r(b"NSObject", b"objectForWebScript", {"retval": {"type": b"@"}}) r( b"NSObject", b"plugInViewWithArguments:", {"required": True, "retval": {"type": b"@"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"receivedData:withDataSource:", { "required": True, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"receivedError:withDataSource:", { "required": True, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"removeEventListener:::", { "required": True, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": "Z"}}, }, ) r( b"NSObject", b"removeEventListener:listener:useCapture:", { "required": True, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": "Z"}}, }, ) r(b"NSObject", b"request", {"required": True, "retval": {"type": b"@"}}) r( b"NSObject", b"searchFor:direction:caseSensitive:wrap:", { "required": True, "retval": {"type": "Z"}, "arguments": { 2: {"type": b"@"}, 3: {"type": "Z"}, 4: {"type": "Z"}, 5: {"type": "Z"}, }, }, ) r(b"NSObject", b"selectAll", {"required": True, "retval": {"type": b"v"}}) r( b"NSObject", b"selectedAttributedString", {"required": True, "retval": {"type": b"@"}}, ) r(b"NSObject", b"selectedString", {"required": True, "retval": {"type": b"@"}}) r( b"NSObject", b"setDataSource:", {"required": True, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"setNeedsLayout:", {"required": True, "retval": {"type": b"v"}, "arguments": {2: {"type": "Z"}}}, ) r(b"NSObject", b"string", {"required": True, "retval": {"type": b"@"}}) r(b"NSObject", b"supportsTextEncoding", {"required": True, "retval": {"type": "Z"}}) r(b"NSObject", b"title", {"required": True, "retval": {"type": b"@"}}) r( b"NSObject", b"undoManagerForWebView:", {"required": False, "retval": {"type": b"@"}, "arguments": {2: {"type": b"@"}}}, ) r(b"NSObject", b"use", {"required": True, "retval": {"type": b"v"}}) r( b"NSObject", b"userContentController:didReceiveScriptMessage:", { "required": True, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"viewDidMoveToHostWindow", {"required": True, "retval": {"type": b"v"}}, ) r( b"NSObject", b"viewWillMoveToHostWindow:", {"required": True, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r(b"NSObject", b"webFrame", {"retval": {"type": b"@"}}) r( b"NSObject", b"webPlugInCallJava:isStatic:returnType:method:arguments:callingURL:exceptionDescription:", { "retval": { "type": sel32or64( b"(jvalue=CcSslqfd^{_jobject=})", b"(jvalue=CcSsiqfd^{_jobject=})" ) }, "arguments": { 2: {"type": "^{_jobject=}"}, 3: {"type": "Z"}, 4: {"type": b"i"}, 5: {"type": "^{_jmethodID=}"}, 6: {"type": "^(jvalue=CcSsiqfd^{_jobject})"}, 7: {"type": b"@"}, 8: {"type": b"^@", "type_modifier": b"o"}, }, }, ) r( b"NSObject", b"webPlugInContainerLoadRequest:inFrame:", {"retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}}, ) r(b"NSObject", b"webPlugInContainerSelectionColor", {"retval": {"type": b"@"}}) r( b"NSObject", b"webPlugInContainerShowStatus:", {"retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r(b"NSObject", b"webPlugInDestroy", {"retval": {"type": b"v"}}) r(b"NSObject", b"webPlugInGetApplet", {"retval": {"type": "^{_jobject=}"}}) r(b"NSObject", b"webPlugInInitialize", {"retval": {"type": b"v"}}) r( b"NSObject", b"webPlugInMainResourceDidFailWithError:", {"retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r(b"NSObject", b"webPlugInMainResourceDidFinishLoading", {"retval": {"type": b"v"}}) r( b"NSObject", b"webPlugInMainResourceDidReceiveData:", {"retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"webPlugInMainResourceDidReceiveResponse:", {"retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"webPlugInSetIsSelected:", {"retval": {"type": b"v"}, "arguments": {2: {"type": "Z"}}}, ) r(b"NSObject", b"webPlugInStart", {"retval": {"type": b"v"}}) r(b"NSObject", b"webPlugInStop", {"retval": {"type": b"v"}}) r( b"NSObject", b"webScriptNameForKey:", { "retval": {"type": b"@"}, "arguments": {2: {"c_array_delimited_by_null": True, "type": "n^t"}}, }, ) r( b"NSObject", b"webScriptNameForSelector:", {"retval": {"type": b"@"}, "arguments": {2: {"type": ":"}}}, ) r( b"NSObject", b"webView:contextMenuItemsForElement:defaultMenuItems:", { "required": False, "retval": {"type": b"@"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:createWebViewModalDialogWithRequest:", { "required": False, "retval": {"type": b"@"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:createWebViewWithConfiguration:forNavigationAction:windowFeatures:", { "required": False, "retval": {"type": b"@"}, "arguments": { 2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}, 5: {"type": b"@"}, }, }, ) r( b"NSObject", b"webView:createWebViewWithRequest:", { "required": False, "retval": {"type": b"@"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:decidePolicyForMIMEType:request:frame:decisionListener:", { "required": False, "retval": {"type": b"v"}, "arguments": { 2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}, 5: {"type": b"@"}, 6: {"type": b"@"}, }, }, ) r( b"NSObject", b"webView:decidePolicyForNavigationAction:decisionHandler:", { "required": False, "retval": {"type": b"v"}, "arguments": { 2: {"type": b"@"}, 3: {"type": b"@"}, 4: { "callable": { "retval": {"type": b"v"}, "arguments": { 0: {"type": b"^v"}, 1: {"type": sel32or64(b"i", b"q")}, }, }, "type": "@?", }, }, }, ) r( b"NSObject", b"webView:decidePolicyForNavigationAction:preferences:decisionHandler:", { "required": False, "retval": {"type": b"v"}, "arguments": { 2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}, 5: {"type": b"@?"}, }, }, ) r( b"NSObject", b"webView:decidePolicyForNavigationAction:request:frame:decisionListener:", { "required": False, "retval": {"type": b"v"}, "arguments": { 2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}, 5: {"type": b"@"}, 6: {"type": b"@"}, }, }, ) r( b"NSObject", b"webView:decidePolicyForNavigationResponse:decisionHandler:", { "required": False, "retval": {"type": b"v"}, "arguments": { 2: {"type": b"@"}, 3: {"type": b"@"}, 4: { "callable": { "retval": {"type": b"v"}, "arguments": { 0: {"type": b"^v"}, 1: {"type": sel32or64(b"i", b"q")}, }, }, "type": "@?", }, }, }, ) r( b"NSObject", b"webView:decidePolicyForNewWindowAction:request:newFrameName:decisionListener:", { "required": False, "retval": {"type": b"v"}, "arguments": { 2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}, 5: {"type": b"@"}, 6: {"type": b"@"}, }, }, ) r( b"NSObject", b"webView:didCancelClientRedirectForFrame:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:didChangeLocationWithinPageForFrame:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:didClearWindowObject:forFrame:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:didCommitLoadForFrame:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:didCommitNavigation:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:didCreateJavaScriptContext:forFrame:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:didFailLoadWithError:forFrame:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:didFailNavigation:withError:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:didFailProvisionalLoadWithError:forFrame:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:didFailProvisionalNavigation:withError:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:didFinishLoadForFrame:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:didFinishNavigation:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:didReceiveAuthenticationChallenge:completionHandler:", { "required": False, "retval": {"type": b"v"}, "arguments": { 2: {"type": b"@"}, 3: {"type": b"@"}, 4: { "callable": { "retval": {"type": b"v"}, "arguments": { 0: {"type": b"^v"}, 1: {"type": sel32or64(b"i", b"q")}, 2: {"type": b"@"}, }, }, "type": "@?", }, }, }, ) r( b"NSObject", b"webView:didReceiveIcon:forFrame:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:didReceiveServerRedirectForProvisionalLoadForFrame:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:didReceiveServerRedirectForProvisionalNavigation:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:didReceiveTitle:forFrame:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:didStartProvisionalLoadForFrame:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:didStartProvisionalNavigation:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:doCommandBySelector:", { "required": False, "retval": {"type": "Z"}, "arguments": {2: {"type": b"@"}, 3: {"type": ":"}}, }, ) r( b"NSObject", b"webView:dragDestinationActionMaskForDraggingInfo:", { "required": False, "retval": {"type": sel32or64(b"I", b"Q")}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:dragSourceActionMaskForPoint:", { "required": False, "retval": {"type": sel32or64(b"I", b"Q")}, "arguments": { 2: {"type": b"@"}, 3: {"type": sel32or64(b"{_NSPoint=ff}", b"{CGPoint=dd}")}, }, }, ) r( b"NSObject", b"webView:drawFooterInRect:", { "required": False, "retval": {"type": b"v"}, "arguments": { 2: {"type": b"@"}, 3: { "type": sel32or64( b"{_NSRect={_NSPoint=ff}{_NSSize=ff}}", b"{CGRect={CGPoint=dd}{CGSize=dd}}", ) }, }, }, ) r( b"NSObject", b"webView:drawHeaderInRect:", { "required": False, "retval": {"type": b"v"}, "arguments": { 2: {"type": b"@"}, 3: { "type": sel32or64( b"{_NSRect={_NSPoint=ff}{_NSSize=ff}}", b"{CGRect={CGPoint=dd}{CGSize=dd}}", ) }, }, }, ) r( b"NSObject", b"webView:identifierForInitialRequest:fromDataSource:", { "required": False, "retval": {"type": b"@"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:makeFirstResponder:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:mouseDidMoveOverElement:modifierFlags:", { "required": False, "retval": {"type": b"v"}, "arguments": { 2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": sel32or64(b"I", b"Q")}, }, }, ) r( b"NSObject", b"webView:plugInFailedWithError:dataSource:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:printFrameView:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:resource:didCancelAuthenticationChallenge:fromDataSource:", { "required": False, "retval": {"type": b"v"}, "arguments": { 2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}, 5: {"type": b"@"}, }, }, ) r( b"NSObject", b"webView:resource:didFailLoadingWithError:fromDataSource:", { "required": False, "retval": {"type": b"v"}, "arguments": { 2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}, 5: {"type": b"@"}, }, }, ) r( b"NSObject", b"webView:resource:didFinishLoadingFromDataSource:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:resource:didReceiveAuthenticationChallenge:fromDataSource:", { "required": False, "retval": {"type": b"v"}, "arguments": { 2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}, 5: {"type": b"@"}, }, }, ) r( b"NSObject", b"webView:resource:didReceiveContentLength:fromDataSource:", { "required": False, "retval": {"type": b"v"}, "arguments": { 2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": sel32or64(b"i", b"q")}, 5: {"type": b"@"}, }, }, ) r( b"NSObject", b"webView:resource:didReceiveResponse:fromDataSource:", { "required": False, "retval": {"type": b"v"}, "arguments": { 2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}, 5: {"type": b"@"}, }, }, ) r( b"NSObject", b"webView:resource:willSendRequest:redirectResponse:fromDataSource:", { "required": False, "retval": {"type": b"@"}, "arguments": { 2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}, 5: {"type": b"@"}, 6: {"type": b"@"}, }, }, ) r( b"NSObject", b"webView:runBeforeUnloadConfirmPanelWithMessage:initiatedByFrame:", { "required": False, "retval": {"type": "Z"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:runJavaScriptAlertPanelWithMessage:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:completionHandler:", { "required": False, "retval": {"type": b"v"}, "arguments": { 2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}, 5: { "callable": { "retval": {"type": b"v"}, "arguments": {0: {"type": b"^v"}}, }, "type": "@?", }, }, }, ) r( b"NSObject", b"webView:runJavaScriptConfirmPanelWithMessage:", { "required": False, "retval": {"type": "Z"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:runJavaScriptConfirmPanelWithMessage:initiatedByFrame:", { "required": False, "retval": {"type": "Z"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:runJavaScriptConfirmPanelWithMessage:initiatedByFrame:completionHandler:", { "required": False, "retval": {"type": b"v"}, "arguments": { 2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}, 5: { "callable": { "retval": {"type": b"v"}, "arguments": {0: {"type": b"^v"}}, }, "type": "@?", }, }, }, ) r( b"NSObject", b"webView:runJavaScriptTextInputPanelWithPrompt:defaultText:", { "required": False, "retval": {"type": b"@"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:runJavaScriptTextInputPanelWithPrompt:defaultText:initiatedByFrame:", { "required": False, "retval": {"type": b"@"}, "arguments": { 2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}, 5: {"type": b"@"}, }, }, ) r( b"NSObject", b"webView:runJavaScriptTextInputPanelWithPrompt:defaultText:initiatedByFrame:completionHandler:", { "required": False, "retval": {"type": b"v"}, "arguments": { 2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}, 5: {"type": b"@"}, 6: { "callable": { "retval": {"type": b"v"}, "arguments": {0: {"type": b"^v"}}, }, "type": "@?", }, }, }, ) r( b"NSObject", b"webView:runOpenPanelForFileButtonWithResultListener:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:runOpenPanelForFileButtonWithResultListener:allowMultipleFiles:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": "Z"}}, }, ) r( b"NSObject", b"webView:runOpenPanelWithParameters:initiatedByFrame:completionHandler:", { "required": False, "retval": {"type": b"v"}, "arguments": { 2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}, 5: { "callable": { "retval": {"type": b"v"}, "arguments": {0: {"type": b"^v"}, 1: {"type": b"@"}}, }, "type": "@?", }, }, }, ) r( b"NSObject", b"webView:setContentRect:", { "required": False, "retval": {"type": b"v"}, "arguments": { 2: {"type": b"@"}, 3: { "type": sel32or64( b"{_NSRect={_NSPoint=ff}{_NSSize=ff}}", b"{CGRect={CGPoint=dd}{CGSize=dd}}", ) }, }, }, ) r( b"NSObject", b"webView:setFrame:", { "required": False, "retval": {"type": b"v"}, "arguments": { 2: {"type": b"@"}, 3: { "type": sel32or64( b"{_NSRect={_NSPoint=ff}{_NSSize=ff}}", b"{CGRect={CGPoint=dd}{CGSize=dd}}", ) }, }, }, ) r( b"NSObject", b"webView:setResizable:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": "Z"}}, }, ) r( b"NSObject", b"webView:setStatusBarVisible:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": "Z"}}, }, ) r( b"NSObject", b"webView:setStatusText:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:setToolbarsVisible:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": "Z"}}, }, ) r( b"NSObject", b"webView:shouldApplyStyle:toElementsInDOMRange:", { "required": False, "retval": {"type": "Z"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:shouldBeginEditingInDOMRange:", { "required": False, "retval": {"type": "Z"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:shouldChangeSelectedDOMRange:toDOMRange:affinity:stillSelecting:", { "required": False, "retval": {"type": "Z"}, "arguments": { 2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}, 5: {"type": sel32or64(b"I", b"Q")}, 6: {"type": "Z"}, }, }, ) r( b"NSObject", b"webView:shouldChangeTypingStyle:toStyle:", { "required": False, "retval": {"type": "Z"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:shouldDeleteDOMRange:", { "required": False, "retval": {"type": "Z"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:shouldEndEditingInDOMRange:", { "required": False, "retval": {"type": "Z"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:shouldInsertNode:replacingDOMRange:givenAction:", { "required": False, "retval": {"type": "Z"}, "arguments": { 2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}, 5: {"type": sel32or64(b"i", b"q")}, }, }, ) r( b"NSObject", b"webView:shouldInsertText:replacingDOMRange:givenAction:", { "required": False, "retval": {"type": "Z"}, "arguments": { 2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}, 5: {"type": sel32or64(b"i", b"q")}, }, }, ) r( b"NSObject", b"webView:shouldPerformAction:fromSender:", { "required": False, "retval": {"type": "Z"}, "arguments": {2: {"type": b"@"}, 3: {"type": ":"}, 4: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:startURLSchemeTask:", { "required": True, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:stopURLSchemeTask:", { "required": True, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:unableToImplementPolicyWithError:frame:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:validateUserInterfaceItem:defaultValidation:", { "required": False, "retval": {"type": "Z"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": "Z"}}, }, ) r( b"NSObject", b"webView:willCloseFrame:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:", { "required": False, "retval": {"type": b"v"}, "arguments": { 2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"d"}, 5: {"type": b"@"}, 6: {"type": b"@"}, }, }, ) r( b"NSObject", b"webView:willPerformDragDestinationAction:forDraggingInfo:", { "required": False, "retval": {"type": b"v"}, "arguments": { 2: {"type": b"@"}, 3: {"type": sel32or64(b"I", b"Q")}, 4: {"type": b"@"}, }, }, ) r( b"NSObject", b"webView:willPerformDragSourceAction:fromPoint:withPasteboard:", { "required": False, "retval": {"type": b"v"}, "arguments": { 2: {"type": b"@"}, 3: {"type": sel32or64(b"I", b"Q")}, 4: {"type": sel32or64(b"{_NSPoint=ff}", b"{CGPoint=dd}")}, 5: {"type": b"@"}, }, }, ) r( b"NSObject", b"webView:windowScriptObjectAvailable:", { "required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}, }, ) r( b"NSObject", b"webViewAreToolbarsVisible:", {"required": False, "retval": {"type": "Z"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"webViewClose:", {"required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"webViewContentRect:", { "required": False, "retval": { "type": sel32or64( b"{_NSRect={_NSPoint=ff}{_NSSize=ff}}", b"{CGRect={CGPoint=dd}{CGSize=dd}}", ) }, "arguments": {2: {"type": b"@"}}, }, ) r( b"NSObject", b"webViewDidBeginEditing:", {"required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"webViewDidChange:", {"required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"webViewDidChangeSelection:", {"required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"webViewDidChangeTypingStyle:", {"required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"webViewDidClose:", {"required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"webViewDidEndEditing:", {"required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"webViewFirstResponder:", {"required": False, "retval": {"type": b"@"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"webViewFocus:", {"required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"webViewFooterHeight:", {"required": False, "retval": {"type": b"f"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"webViewFrame:", { "required": False, "retval": { "type": sel32or64( b"{_NSRect={_NSPoint=ff}{_NSSize=ff}}", b"{CGRect={CGPoint=dd}{CGSize=dd}}", ) }, "arguments": {2: {"type": b"@"}}, }, ) r( b"NSObject", b"webViewHeaderHeight:", {"required": False, "retval": {"type": b"f"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"webViewIsResizable:", {"required": False, "retval": {"type": "Z"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"webViewIsStatusBarVisible:", {"required": False, "retval": {"type": "Z"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"webViewRunModal:", {"required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"webViewShow:", {"required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"webViewStatusText:", {"required": False, "retval": {"type": b"@"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"webViewUnfocus:", {"required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"webViewWebContentProcessDidTerminate:", {"required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r( b"WKContentRuleListStore", b"compileContentRuleListForIdentifier:encodedContentRuleList:completionHandler:", { "arguments": { 4: { "callable": { "retval": {"type": b"v"}, "arguments": { 0: {"type": b"^v"}, 1: {"type": b"@"}, 2: {"type": b"@"}, }, } } } }, ) r( b"WKContentRuleListStore", b"getAvailableContentRuleListIdentifiers:", { "arguments": { 2: { "callable": { "retval": {"type": b"v"}, "arguments": {0: {"type": b"^v"}, 1: {"type": b"@"}}, } } } }, ) r( b"WKContentRuleListStore", b"lookUpContentRuleListForIdentifier:completionHandler:", { "arguments": { 3: { "callable": { "retval": {"type": b"v"}, "arguments": { 0: {"type": b"^v"}, 1: {"type": b"@"}, 2: {"type": b"@"}, }, } } } }, ) r( b"WKContentRuleListStore", b"removeContentRuleListForIdentifier:completionHandler:", { "arguments": { 3: { "callable": { "retval": {"type": b"v"}, "arguments": {0: {"type": b"^v"}, 1: {"type": b"@"}}, } } } }, ) r(b"WKFrameInfo", b"isMainFrame", {"retval": {"type": b"Z"}}) r( b"WKHTTPCookieStore", b"deleteCookie:completionHandler:", { "arguments": { 3: { "callable": { "retval": {"type": b"v"}, "arguments": {0: {"type": b"^v"}}, } } } }, ) r( b"WKHTTPCookieStore", b"getAllCookies:", { "arguments": { 2: { "callable": { "retval": {"type": b"v"}, "arguments": {0: {"type": b"^v"}, 1: {"type": b"@"}}, } } } }, ) r( b"WKHTTPCookieStore", b"setCookie:completionHandler:", { "arguments": { 3: { "callable": { "retval": {"type": b"v"}, "arguments": {0: {"type": b"^v"}}, } } } }, ) r(b"WKNavigationResponse", b"canShowMIMEType", {"retval": {"type": b"Z"}}) r(b"WKNavigationResponse", b"isForMainFrame", {"retval": {"type": b"Z"}}) r(b"WKOpenPanelParameters", b"allowsDirectories", {"retval": {"type": "Z"}}) r(b"WKOpenPanelParameters", b"allowsMultipleSelection", {"retval": {"type": "Z"}}) r( b"WKPreferences", b"isFraudulentWebsiteWarningEnabled", {"retval": {"type": b"Z"}}, ) r(b"WKPreferences", b"isSafeBrowsingEnabled", {"retval": {"type": b"Z"}}) r(b"WKPreferences", b"javaEnabled", {"retval": {"type": b"Z"}}) r( b"WKPreferences", b"javaScriptCanOpenWindowsAutomatically", {"retval": {"type": b"Z"}}, ) r(b"WKPreferences", b"javaScriptEnabled", {"retval": {"type": b"Z"}}) r(b"WKPreferences", b"plugInsEnabled", {"retval": {"type": b"Z"}}) r( b"WKPreferences", b"setFraudulentWebsiteWarningEnabled:", {"arguments": {2: {"type": b"Z"}}}, ) r(b"WKPreferences", b"setJavaEnabled:", {"arguments": {2: {"type": b"Z"}}}) r( b"WKPreferences", b"setJavaScriptCanOpenWindowsAutomatically:", {"arguments": {2: {"type": b"Z"}}}, ) r(b"WKPreferences", b"setJavaScriptEnabled:", {"arguments": {2: {"type": b"Z"}}}) r(b"WKPreferences", b"setPlugInsEnabled:", {"arguments": {2: {"type": b"Z"}}}) r(b"WKPreferences", b"setSafeBrowsingEnabled:", {"arguments": {2: {"type": b"Z"}}}) r(b"WKPreferences", b"setTabFocusesLinks:", {"arguments": {2: {"type": "Z"}}}) r(b"WKPreferences", b"tabFocusesLinks", {"retval": {"type": "Z"}}) r(b"WKSnapshotConfiguration", b"afterScreenUpdates", {"retval": {"type": "Z"}}) r( b"WKSnapshotConfiguration", b"setAfterScreenUpdates:", {"arguments": {2: {"type": "Z"}}}, ) r( b"WKUserScript", b"initWithSource:injectionTime:forMainFrameOnly:", {"arguments": {4: {"type": b"Z"}}}, ) r(b"WKUserScript", b"isForMainFrameOnly", {"retval": {"type": b"Z"}}) r(b"WKWebView", b"allowsBackForwardNavigationGestures", {"retval": {"type": b"Z"}}) r(b"WKWebView", b"allowsLinkPreview", {"retval": {"type": "Z"}}) r(b"WKWebView", b"allowsMagnification", {"retval": {"type": b"Z"}}) r(b"WKWebView", b"canGoBack", {"retval": {"type": b"Z"}}) r(b"WKWebView", b"canGoForward", {"retval": {"type": b"Z"}}) r( b"WKWebView", b"evaluateJavaScript:completionHandler:", { "arguments": { 3: { "callable": { "retval": {"type": b"v"}, "arguments": { 0: {"type": b"^v"}, 1: {"type": b"@"}, 2: {"type": b"@"}, }, } } } }, ) r(b"WKWebView", b"handlesURLScheme:", {"retval": {"type": "Z"}}) r(b"WKWebView", b"hasOnlySecureContent", {"retval": {"type": b"Z"}}) r(b"WKWebView", b"isLoading", {"retval": {"type": b"Z"}}) r( b"WKWebView", b"setAllowsBackForwardNavigationGestures:", {"arguments": {2: {"type": b"Z"}}}, ) r(b"WKWebView", b"setAllowsLinkPreview:", {"arguments": {2: {"type": "Z"}}}) r(b"WKWebView", b"setAllowsMagnification:", {"arguments": {2: {"type": b"Z"}}}) r( b"WKWebView", b"takeSnapshotWithConfiguration:completionHandler:", { "arguments": { 3: { "callable": { "retval": {"type": b"v"}, "arguments": { 0: {"type": b"^v"}, 1: {"type": b"@"}, 2: {"type": b"@"}, }, } } } }, ) r( b"WKWebViewConfiguration", b"allowsAirPlayForMediaPlayback", {"retval": {"type": "Z"}}, ) r( b"WKWebViewConfiguration", b"allowsPictureInPictureMediaPlayback", {"retval": {"type": "Z"}}, ) r( b"WKWebViewConfiguration", b"setAllowsAirPlayForMediaPlayback:", {"arguments": {2: {"type": "Z"}}}, ) r( b"WKWebViewConfiguration", b"setAllowsPictureInPictureMediaPlayback:", {"arguments": {2: {"type": "Z"}}}, ) r( b"WKWebViewConfiguration", b"setSuppressesIncrementalRendering:", {"arguments": {2: {"type": b"Z"}}}, ) r( b"WKWebViewConfiguration", b"suppressesIncrementalRendering", {"retval": {"type": b"Z"}}, ) r( b"WKWebsiteDataStore", b"fetchDataRecordsOfTypes:completionHandler:", { "arguments": { 3: { "callable": { "retval": {"type": b"v"}, "arguments": {0: {"type": b"^v"}, 1: {"type": b"@"}}, } } } }, ) r(b"WKWebsiteDataStore", b"isPersistent", {"retval": {"type": "Z"}}) r( b"WKWebsiteDataStore", b"removeDataOfTypes:forDataRecords:completionHandler:", { "arguments": { 4: { "callable": { "retval": {"type": b"v"}, "arguments": {0: {"type": b"^v"}}, } } } }, ) r( b"WKWebsiteDataStore", b"removeDataOfTypes:modifiedSince:completionHandler:", { "arguments": { 4: { "callable": { "retval": {"type": b"v"}, "arguments": {0: {"type": b"^v"}}, } } } }, ) r(b"WebBackForwardList", b"containsItem:", {"retval": {"type": "Z"}}) r(b"WebDataSource", b"isLoading", {"retval": {"type": "Z"}}) r(b"WebFrame", b"globalContext", {"retval": {"type": "^{OpaqueJSContext=}"}}) r(b"WebFrameView", b"allowsScrolling", {"retval": {"type": "Z"}}) r(b"WebFrameView", b"canPrintHeadersAndFooters", {"retval": {"type": "Z"}}) r(b"WebFrameView", b"documentViewShouldHandlePrint", {"retval": {"type": "Z"}}) r(b"WebFrameView", b"setAllowsScrolling:", {"arguments": {2: {"type": "Z"}}}) r( b"WebHistory", b"loadFromURL:error:", {"retval": {"type": "Z"}, "arguments": {3: {"type_modifier": b"o"}}}, ) r( b"WebHistory", b"saveToURL:error:", {"retval": {"type": "Z"}, "arguments": {3: {"type_modifier": b"o"}}}, ) r(b"WebPreferences", b"allowsAirPlayForMediaPlayback", {"retval": {"type": "Z"}}) r(b"WebPreferences", b"allowsAnimatedImageLooping", {"retval": {"type": "Z"}}) r(b"WebPreferences", b"allowsAnimatedImages", {"retval": {"type": "Z"}}) r(b"WebPreferences", b"arePlugInsEnabled", {"retval": {"type": "Z"}}) r(b"WebPreferences", b"autosaves", {"retval": {"type": "Z"}}) r(b"WebPreferences", b"isJavaEnabled", {"retval": {"type": "Z"}}) r(b"WebPreferences", b"isJavaScriptEnabled", {"retval": {"type": "Z"}}) r( b"WebPreferences", b"javaScriptCanOpenWindowsAutomatically", {"retval": {"type": "Z"}}, ) r(b"WebPreferences", b"loadsImagesAutomatically", {"retval": {"type": "Z"}}) r(b"WebPreferences", b"privateBrowsingEnabled", {"retval": {"type": "Z"}}) r( b"WebPreferences", b"setAllowsAirPlayForMediaPlayback:", {"arguments": {2: {"type": "Z"}}}, ) r( b"WebPreferences", b"setAllowsAnimatedImageLooping:", {"arguments": {2: {"type": "Z"}}}, ) r(b"WebPreferences", b"setAllowsAnimatedImages:", {"arguments": {2: {"type": "Z"}}}) r(b"WebPreferences", b"setAutosaves:", {"arguments": {2: {"type": "Z"}}}) r(b"WebPreferences", b"setJavaEnabled:", {"arguments": {2: {"type": "Z"}}}) r( b"WebPreferences", b"setJavaScriptCanOpenWindowsAutomatically:", {"arguments": {2: {"type": "Z"}}}, ) r(b"WebPreferences", b"setJavaScriptEnabled:", {"arguments": {2: {"type": "Z"}}}) r( b"WebPreferences", b"setLoadsImagesAutomatically:", {"arguments": {2: {"type": "Z"}}}, ) r(b"WebPreferences", b"setPlugInsEnabled:", {"arguments": {2: {"type": "Z"}}}) r( b"WebPreferences", b"setPrivateBrowsingEnabled:", {"arguments": {2: {"type": "Z"}}}, ) r( b"WebPreferences", b"setShouldPrintBackgrounds:", {"arguments": {2: {"type": "Z"}}}, ) r( b"WebPreferences", b"setSuppressesIncrementalRendering:", {"arguments": {2: {"type": b"Z"}}}, ) r(b"WebPreferences", b"setTabsToLinks:", {"arguments": {2: {"type": "Z"}}}) r( b"WebPreferences", b"setUserStyleSheetEnabled:", {"arguments": {2: {"type": "Z"}}}, ) r(b"WebPreferences", b"setUsesPageCache:", {"arguments": {2: {"type": "Z"}}}) r(b"WebPreferences", b"shouldPrintBackgrounds", {"retval": {"type": "Z"}}) r(b"WebPreferences", b"suppressesIncrementalRendering", {"retval": {"type": b"Z"}}) r(b"WebPreferences", b"tabsToLinks", {"retval": {"type": "Z"}}) r(b"WebPreferences", b"userStyleSheetEnabled", {"retval": {"type": "Z"}}) r(b"WebPreferences", b"usesPageCache", {"retval": {"type": "Z"}}) r(b"WebScriptObject", b"JSObject", {"retval": {"type": "^{OpaqueJSValue=}"}}) r(b"WebScriptObject", b"throwException:", {"retval": {"type": "Z"}}) r(b"WebView", b"canGoBack", {"retval": {"type": "Z"}}) r(b"WebView", b"canGoForward", {"retval": {"type": "Z"}}) r(b"WebView", b"canMakeTextLarger", {"retval": {"type": "Z"}}) r(b"WebView", b"canMakeTextSmaller", {"retval": {"type": "Z"}}) r(b"WebView", b"canMakeTextStandardSize", {"retval": {"type": "Z"}}) r(b"WebView", b"canShowMIMEType:", {"retval": {"type": "Z"}}) r(b"WebView", b"canShowMIMETypeAsHTML:", {"retval": {"type": "Z"}}) r(b"WebView", b"drawsBackground", {"retval": {"type": "Z"}}) r(b"WebView", b"goBack", {"retval": {"type": "Z"}}) r(b"WebView", b"goForward", {"retval": {"type": "Z"}}) r(b"WebView", b"goToBackForwardItem:", {"retval": {"type": "Z"}}) r(b"WebView", b"isContinuousSpellCheckingEnabled", {"retval": {"type": "Z"}}) r(b"WebView", b"isEditable", {"retval": {"type": "Z"}}) r(b"WebView", b"isLoading", {"retval": {"type": "Z"}}) r(b"WebView", b"maintainsInactiveSelection", {"retval": {"type": "Z"}}) r( b"WebView", b"searchFor:direction:caseSensitive:wrap:", { "retval": {"type": "Z"}, "arguments": {3: {"type": "Z"}, 4: {"type": "Z"}, 5: {"type": "Z"}}, }, ) r( b"WebView", b"setContinuousSpellCheckingEnabled:", {"arguments": {2: {"type": "Z"}}}, ) r(b"WebView", b"setDrawsBackground:", {"arguments": {2: {"type": "Z"}}}) r(b"WebView", b"setEditable:", {"arguments": {2: {"type": "Z"}}}) r(b"WebView", b"setMaintainsBackForwardList:", {"arguments": {2: {"type": "Z"}}}) r(b"WebView", b"setShouldCloseWithWindow:", {"arguments": {2: {"type": "Z"}}}) r(b"WebView", b"setShouldUpdateWhileOffscreen:", {"arguments": {2: {"type": "Z"}}}) r(b"WebView", b"setSmartInsertDeleteEnabled:", {"arguments": {2: {"type": "Z"}}}) r(b"WebView", b"shouldCloseWithWindow", {"retval": {"type": "Z"}}) r(b"WebView", b"shouldUpdateWhileOffscreen", {"retval": {"type": "Z"}}) r(b"WebView", b"smartInsertDeleteEnabled", {"retval": {"type": "Z"}}) r(b"WebView", b"supportsTextEncoding", {"retval": {"type": "Z"}}) finally: objc._updatingMetadata(False) protocols = { "WebUIDelegate": objc.informal_protocol( "WebUIDelegate", [ objc.selector( None, b"webView:runOpenPanelForFileButtonWithResultListener:", b"v@:@@", isRequired=False, ), objc.selector(None, b"webViewFirstResponder:", b"@@:@", isRequired=False), objc.selector( None, b"webView:runJavaScriptAlertPanelWithMessage:", b"v@:@@", isRequired=False, ), objc.selector( None, b"webView:runJavaScriptConfirmPanelWithMessage:initiatedByFrame:", b"Z@:@@@", isRequired=False, ), objc.selector(None, b"webViewShow:", b"v@:@", isRequired=False), objc.selector( None, b"webView:runBeforeUnloadConfirmPanelWithMessage:initiatedByFrame:", b"Z@:@@@", isRequired=False, ), objc.selector( None, b"webView:drawHeaderInRect:", sel32or64( b"v@:@{_NSRect={_NSPoint=ff}{_NSSize=ff}}", b"v@:@{CGRect={CGPoint=dd}{CGSize=dd}}", ), isRequired=False, ), objc.selector(None, b"webViewRunModal:", b"v@:@", isRequired=False), objc.selector( None, b"webViewIsStatusBarVisible:", b"Z@:@", isRequired=False ), objc.selector( None, b"webView:runOpenPanelForFileButtonWithResultListener:allowMultipleFiles:", b"v@:@@Z", isRequired=False, ), objc.selector( None, b"webView:validateUserInterfaceItem:defaultValidation:", b"Z@:@@Z", isRequired=False, ), objc.selector(None, b"webViewFooterHeight:", b"f@:@", isRequired=False), objc.selector( None, b"webView:runJavaScriptTextInputPanelWithPrompt:defaultText:initiatedByFrame:", b"@@:@@@@", isRequired=False, ), objc.selector(None, b"webViewIsResizable:", b"Z@:@", isRequired=False), objc.selector( None, b"webView:setToolbarsVisible:", b"v@:@Z", isRequired=False ), objc.selector( None, b"webView:setContentRect:", sel32or64( b"v@:@{_NSRect={_NSPoint=ff}{_NSSize=ff}}", b"v@:@{CGRect={CGPoint=dd}{CGSize=dd}}", ), isRequired=False, ), objc.selector( None, b"webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:", b"v@:@@@", isRequired=False, ), objc.selector( None, b"webView:drawFooterInRect:", sel32or64( b"v@:@{_NSRect={_NSPoint=ff}{_NSSize=ff}}", b"v@:@{CGRect={CGPoint=dd}{CGSize=dd}}", ), isRequired=False, ), objc.selector( None, b"webView:runJavaScriptTextInputPanelWithPrompt:defaultText:", b"@@:@@@", isRequired=False, ), objc.selector(None, b"webView:setResizable:", b"v@:@Z", isRequired=False), objc.selector( None, b"webViewContentRect:", sel32or64( b"{_NSRect={_NSPoint=ff}{_NSSize=ff}}@:@", b"{CGRect={CGPoint=dd}{CGSize=dd}}@:@", ), isRequired=False, ), objc.selector(None, b"webViewClose:", b"v@:@", isRequired=False), objc.selector( None, b"webView:shouldPerformAction:fromSender:", b"Z@:@:@", isRequired=False, ), objc.selector( None, b"webView:dragSourceActionMaskForPoint:", sel32or64(b"I@:@{_NSPoint=ff}", b"Q@:@{CGPoint=dd}"), isRequired=False, ), objc.selector( None, b"webViewAreToolbarsVisible:", b"Z@:@", isRequired=False ), objc.selector( None, b"webView:setFrame:", sel32or64( b"v@:@{_NSRect={_NSPoint=ff}{_NSSize=ff}}", b"v@:@{CGRect={CGPoint=dd}{CGSize=dd}}", ), isRequired=False, ), objc.selector( None, b"webView:dragDestinationActionMaskForDraggingInfo:", sel32or64(b"I@:@@", b"Q@:@@"), isRequired=False, ), objc.selector( None, b"webView:mouseDidMoveOverElement:modifierFlags:", sel32or64(b"v@:@@I", b"v@:@@Q"), isRequired=False, ), objc.selector(None, b"webViewHeaderHeight:", b"f@:@", isRequired=False), objc.selector( None, b"webView:runJavaScriptConfirmPanelWithMessage:", b"Z@:@@", isRequired=False, ), objc.selector(None, b"webViewStatusText:", b"@@:@", isRequired=False), objc.selector( None, b"webView:createWebViewWithRequest:", b"@@:@@", isRequired=False ), objc.selector( None, b"webView:willPerformDragDestinationAction:forDraggingInfo:", sel32or64(b"v@:@I@", b"v@:@Q@"), isRequired=False, ), objc.selector(None, b"webViewUnfocus:", b"v@:@", isRequired=False), objc.selector( None, b"webView:makeFirstResponder:", b"v@:@@", isRequired=False ), objc.selector(None, b"webView:setStatusText:", b"v@:@@", isRequired=False), objc.selector( None, b"webView:willPerformDragSourceAction:fromPoint:withPasteboard:", sel32or64(b"v@:@I{_NSPoint=ff}@", b"v@:@Q{CGPoint=dd}@"), isRequired=False, ), objc.selector( None, b"webView:contextMenuItemsForElement:defaultMenuItems:", b"@@:@@@", isRequired=False, ), objc.selector(None, b"webViewFocus:", b"v@:@", isRequired=False), objc.selector(None, b"webView:printFrameView:", b"v@:@@", isRequired=False), objc.selector( None, b"webViewFrame:", sel32or64( b"{_NSRect={_NSPoint=ff}{_NSSize=ff}}@:@", b"{CGRect={CGPoint=dd}{CGSize=dd}}@:@", ), isRequired=False, ), objc.selector( None, b"webView:setStatusBarVisible:", b"v@:@Z", isRequired=False ), objc.selector( None, b"webView:createWebViewModalDialogWithRequest:", b"@@:@@", isRequired=False, ), ], ), "WebViewEditingDelegate": objc.informal_protocol( "WebViewEditingDelegate", [ objc.selector(None, b"webViewDidBeginEditing:", b"v@:@", isRequired=False), objc.selector( None, b"webViewDidChangeSelection:", b"v@:@", isRequired=False ), objc.selector( None, b"webView:shouldDeleteDOMRange:", b"Z@:@@", isRequired=False ), objc.selector( None, b"webView:shouldChangeTypingStyle:toStyle:", b"Z@:@@@", isRequired=False, ), objc.selector( None, b"webView:shouldChangeSelectedDOMRange:toDOMRange:affinity:stillSelecting:", sel32or64(b"Z@:@@@IZ", b"Z@:@@@QZ"), isRequired=False, ), objc.selector( None, b"webView:shouldApplyStyle:toElementsInDOMRange:", b"Z@:@@@", isRequired=False, ), objc.selector( None, b"webView:doCommandBySelector:", b"Z@:@:", isRequired=False ), objc.selector( None, b"webViewDidChangeTypingStyle:", b"v@:@", isRequired=False ), objc.selector(None, b"undoManagerForWebView:", b"@@:@", isRequired=False), objc.selector(None, b"webViewDidEndEditing:", b"v@:@", isRequired=False), objc.selector( None, b"webView:shouldInsertText:replacingDOMRange:givenAction:", sel32or64(b"Z@:@@@i", b"Z@:@@@q"), isRequired=False, ), objc.selector(None, b"webViewDidChange:", b"v@:@", isRequired=False), objc.selector( None, b"webView:shouldEndEditingInDOMRange:", b"Z@:@@", isRequired=False ), objc.selector( None, b"webView:shouldBeginEditingInDOMRange:", b"Z@:@@", isRequired=False, ), objc.selector( None, b"webView:shouldInsertNode:replacingDOMRange:givenAction:", sel32or64(b"Z@:@@@i", b"Z@:@@@q"), isRequired=False, ), ], ), "WebPolicyDelegate": objc.informal_protocol( "WebPolicyDelegate", [ objc.selector( None, b"webView:unableToImplementPolicyWithError:frame:", b"v@:@@@", isRequired=False, ), objc.selector( None, b"webView:decidePolicyForNavigationAction:request:frame:decisionListener:", b"v@:@@@@@", isRequired=False, ), objc.selector( None, b"webView:decidePolicyForNewWindowAction:request:newFrameName:decisionListener:", b"v@:@@@@@", isRequired=False, ), objc.selector( None, b"webView:decidePolicyForMIMEType:request:frame:decisionListener:", b"v@:@@@@@", isRequired=False, ), ], ), "WebDownloadDelegate": objc.informal_protocol( "WebDownloadDelegate", [ objc.selector( None, b"downloadWindowForAuthenticationSheet:", b"@@:@", isRequired=False, ) ], ), "WebPlugIn": objc.informal_protocol( "WebPlugIn", [ objc.selector( None, b"webPlugInMainResourceDidReceiveResponse:", b"v@:@", isRequired=False, ), objc.selector(None, b"objectForWebScript", b"@@:", isRequired=False), objc.selector( None, b"webPlugInMainResourceDidFinishLoading", b"v@:", isRequired=False ), objc.selector( None, b"webPlugInMainResourceDidFailWithError:", b"v@:@", isRequired=False, ), objc.selector( None, b"webPlugInMainResourceDidReceiveData:", b"v@:@", isRequired=False ), objc.selector(None, b"webPlugInDestroy", b"v@:", isRequired=False), objc.selector(None, b"webPlugInStop", b"v@:", isRequired=False), objc.selector(None, b"webPlugInSetIsSelected:", b"v@:Z", isRequired=False), objc.selector(None, b"webPlugInInitialize", b"v@:", isRequired=False), objc.selector(None, b"webPlugInStart", b"v@:", isRequired=False), ], ), "WebJavaPlugIn": objc.informal_protocol( "WebJavaPlugIn", [ objc.selector( None, b"webPlugInCallJava:isStatic:returnType:method:arguments:callingURL:exceptionDescription:", sel32or64( b"(jvalue=CcSslqfd^{_jobject=})@:^{_jobject=}Zi^{_jmethodID=}^(jvalue=CcSslqfd^{_jobject=})@^@", b"(jvalue=CcSsiqfd^{_jobject=})@:^{_jobject=}Zi^{_jmethodID=}^(jvalue=CcSsiqfd^{_jobject=})@^@", ), isRequired=False, ), objc.selector( None, b"webPlugInGetApplet", b"^{_jobject=}@:", isRequired=False ), ], ), "WebResourceLoadDelegate": objc.informal_protocol( "WebResourceLoadDelegate", [ objc.selector( None, b"webView:resource:didCancelAuthenticationChallenge:fromDataSource:", b"v@:@@@@", isRequired=False, ), objc.selector( None, b"webView:resource:didFinishLoadingFromDataSource:", b"v@:@@@", isRequired=False, ), objc.selector( None, b"webView:identifierForInitialRequest:fromDataSource:", b"@@:@@@", isRequired=False, ), objc.selector( None, b"webView:resource:willSendRequest:redirectResponse:fromDataSource:", b"@@:@@@@@", isRequired=False, ), objc.selector( None, b"webView:plugInFailedWithError:dataSource:", b"v@:@@@", isRequired=False, ), objc.selector( None, b"webView:resource:didReceiveResponse:fromDataSource:", b"v@:@@@@", isRequired=False, ), objc.selector( None, b"webView:resource:didReceiveContentLength:fromDataSource:", sel32or64(b"v@:@@i@", b"v@:@@q@"), isRequired=False, ), objc.selector( None, b"webView:resource:didFailLoadingWithError:fromDataSource:", b"v@:@@@@", isRequired=False, ), objc.selector( None, b"webView:resource:didReceiveAuthenticationChallenge:fromDataSource:", b"v@:@@@@", isRequired=False, ), ], ), "WebFrameLoadDelegate": objc.informal_protocol( "WebFrameLoadDelegate", [ objc.selector( None, b"webView:didCancelClientRedirectForFrame:", b"v@:@@", isRequired=False, ), objc.selector( None, b"webView:didClearWindowObject:forFrame:", b"v@:@@@", isRequired=False, ), objc.selector( None, b"webView:didReceiveTitle:forFrame:", b"v@:@@@", isRequired=False ), objc.selector( None, b"webView:didStartProvisionalLoadForFrame:", b"v@:@@", isRequired=False, ), objc.selector( None, b"webView:didCommitLoadForFrame:", b"v@:@@", isRequired=False ), objc.selector( None, b"webView:didFinishLoadForFrame:", b"v@:@@", isRequired=False ), objc.selector( None, b"webView:didFailProvisionalLoadWithError:forFrame:", b"v@:@@@", isRequired=False, ), objc.selector( None, b"webView:didFailLoadWithError:forFrame:", b"v@:@@@", isRequired=False, ), objc.selector( None, b"webView:didReceiveIcon:forFrame:", b"v@:@@@", isRequired=False ), objc.selector( None, b"webView:didReceiveServerRedirectForProvisionalLoadForFrame:", b"v@:@@", isRequired=False, ), objc.selector( None, b"webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:", b"v@:@@d@@", isRequired=False, ), objc.selector( None, b"webView:windowScriptObjectAvailable:", b"v@:@@", isRequired=False, ), objc.selector( None, b"webView:didChangeLocationWithinPageForFrame:", b"v@:@@", isRequired=False, ), objc.selector(None, b"webView:willCloseFrame:", b"v@:@@", isRequired=False), ], ), "WebPlugInContainer": objc.informal_protocol( "WebPlugInContainer", [ objc.selector( None, b"webPlugInContainerShowStatus:", b"v@:@", isRequired=False ), objc.selector( None, b"webPlugInContainerSelectionColor", b"@@:", isRequired=False ), objc.selector(None, b"webFrame", b"@@:", isRequired=False), objc.selector( None, b"webPlugInContainerLoadRequest:inFrame:", b"v@:@@", isRequired=False, ), ], ), "WebScripting": objc.informal_protocol( "WebScripting", [ objc.selector(None, b"finalizeForWebScript", b"v@:", isRequired=False), objc.selector( None, b"invokeUndefinedMethodFromWebScript:withArguments:", b"@@:@@", isRequired=False, ), objc.selector(None, b"webScriptNameForKey:", b"@@:^c", isRequired=False), objc.selector( None, b"webScriptNameForSelector:", b"@@::", isRequired=False ), objc.selector( None, b"invokeDefaultMethodWithArguments:", b"@@:@", isRequired=False ), objc.selector( None, b"isSelectorExcludedFromWebScript:", b"Z@::", isRequired=False ), objc.selector( None, b"isKeyExcludedFromWebScript:", b"Z@:^c", isRequired=False ), ], ), } expressions = {} # END OF FILE
[ "ronaldoussoren@mac.com" ]
ronaldoussoren@mac.com
962661036d44067c7e93ad751d8e43088a30c916
22828678955eb92188a158528963a5fcbcd8b2ff
/蚁群算法.py
38108964d90201254fd65b60a44aa6d46f7f829d
[]
no_license
Satan121/ant
0a5cab4d85ead4f98173c81ebdf77e5ee2756cfa
e46bd9cdc60ee8f781a61ad44f8723ecd4e7b3ae
refs/heads/master
2020-04-02T13:03:46.740843
2018-03-11T08:12:09
2018-03-11T08:12:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
25,347
py
# -*- coding: UTF-8 -*- ''' 程序主体: 类BACA的实例化->类BACA的初始化->执行BACA.ReadCityInfo()方法->执行BACA.Search()方法->执行BACA.PutAnts()方法 ->类ANT的初始化->类ANT的实例化->执行ANT.MoveToNextCity()方法->执行ANT.SelectNextCity()方法->执行ANT.AddCity()方法 ->执行ANT.UpdatePathLen()方法->执行BACA.UpdatePheromoneTrail()方法 蚁群算法中关键两个问题,一个是选择下一个城市的算法,主要在ANT.SelectNextCity(self, alpha, beta)方法中,其中alpha为表征 信息素重要程度的参数,beta为表征启发式因子重要程度的参数;而更新信息素主要在BACA.UpdatePheromoneTrail(self)方法中。 ''' import os, sys, random#调入基本的python模块 from math import * import pylab as pl BestTour = []#用于放置最佳路径选择城市的顺序 CitySet = set()#sets数据类型是个无序的、没有重复元素的集合,两个sets之间可以做差集,即在第一个集合中移出第二个集合中也存在的元素 CityList = []#城市列表即存放代表城市的序号 PheromoneTrailList = []#信息素列表(矩阵) PheromoneDeltaTrailList = []#释放信息素列表(矩阵) CityDistanceList = []#两两城市距离列表(矩阵) AntList = []#蚂蚁列表 class BACA:#定义类BACA,执行蚁群基本算法 def __init__(self, cityCount=51, antCount=51, q=80, alpha=1, beta=3, rou=0.4, nMax=100): #self, cityCount=51, antCount=50, q=80, alpha=2, beta=5, rou=0.3, nMax=40 #初始化方法,antCount为蚂蚁数,nMax为迭代次数 self.CityCount = cityCount#城市数量,本例中为手工输入,也可以根据城市数据列表编写程序获得 self.AntCount = antCount#蚂蚁数量 self.Q = q#信息素增加强度系数 self.Alpha = alpha#表征信息素重要程度的参数 self.Beta = beta#表征启发因子重要程度的参数 self.Rou = rou#信息素蒸发系数 self.Nmax = nMax#最大迭代次数 self.Shortest = 10e6#初始最短距离应该尽可能大,至少大于估算的最大城市旅行距离 random.seed()#设置随机种子 #初始化全局数据结构及值 for nCity in range(self.CityCount):#循环城市总数的次数(即循环range(0,51),为0-50,不包括51) BestTour.append(0)#设置最佳路径初始值均为0 for row in range(self.CityCount):#再次循环城市总数的次数 pheromoneList = []#定义空的信息素列表 pheromoneDeltaList = []#定义空的释放信息素列表 for col in range(self.CityCount):#循环城市总数的次数 pheromoneList.append(100)#定义一个城市到所有城市路径信息素的初始值 pheromoneDeltaList.append(0)#定义一个城市到所有城市路径释放信息素的初始值 PheromoneTrailList.append(pheromoneList)#建立每个城市到所有城市路径信息素的初始值列表矩阵 PheromoneDeltaTrailList.append(pheromoneDeltaList)#建立每个城市到所有城市路径释放信息素的初始值列表矩阵 def ReadCityInfo(self, fileName):#定义读取城市文件的方法 file = open(fileName)#打开城市文件 for line in file.readlines():#逐行读取文件 cityN, cityX, cityY = line.split()#分别提取城市序号、X坐标和Y坐标,使用空格切分 CitySet.add(int(cityN))#在城市集合中逐步追加所有的城市序号 CityList.append((int(cityN), float(cityX), float(cityY)))#在城市列表中逐步追加每个城市序号、X坐标和Y坐标建立的元组 for row in range(self.CityCount):#循环总城市数的次数 distanceList = []#建立临时储存距离的空列表 for col in range(self.CityCount): distance = sqrt(pow(CityList[row][1]-CityList[col][1], 2) + pow(CityList[row][2]-CityList[col][2], 2))#逐一计算每个城市到所有城市的距离值 distance = round(distance) distanceList.append(distance)#追加一个城市到所有城市的距离值 CityDistanceList.append(distanceList)#追加么个城市到所有城市的距离值,为矩阵,即包含子列表 file.close()#关闭城市文件 def PutAnts(self):#定义蚂蚁所选择城市以及将城市作为参数定义蚂蚁的方法和属性 AntList.clear() # 先清空列表 for antNum in range(self.AntCount):#循环蚂蚁总数的次数 city = random.randint(1, self.CityCount)#随机选择一个城市 ant = ANT(city)#蚂蚁类ANT的实例化,即将每只蚂蚁随机选择的城市作为传入的参数,使之具有ANT蚂蚁类的方法和属性 AntList.append(ant)#将定义的每只蚂蚁追加到列表中 def Search(self):#定义搜索最佳旅行路径方法的主程序 for iter in range(self.Nmax):#循环指定的迭代次数 self.PutAnts()#执行self.PutAnts()方法,定义蚂蚁选择的初始城市和蚂蚁具有的方法和属性 for ant in AntList:#循环遍历蚂蚁列表,由self.PutAnts()方法定义获取 for ttt in range(len(CityList)):#循环遍历城市总数次数 ant.MoveToNextCity(self.Alpha, self.Beta)#执行蚂蚁的ant.MoveToNextCity()方法,获取蚂蚁每次旅行时的旅行路径长度CurrLen,禁忌城市城市列表TabuCityList等属性值 ant.two_opt_search()#使用邻域优化算法 $$$ ant.UpdatePathLen()#使用ant.UpdatePathLen更新蚂蚁旅行路径长度 tmpLen = AntList[0].CurrLen#将蚂蚁列表中第一只蚂蚁的旅行路径长度赋值给新的变量tmplen tmpTour = AntList[0].TabuCityList#将获取的蚂蚁列表的第一只蚂蚁的禁忌城市列表赋值给新的变量tmpTour for ant in AntList[1:]:#循环遍历蚂蚁列表,从索引值1开始,除第一只外 if ant.CurrLen < tmpLen:#如果循环到的蚂蚁旅行路径长度小于tmpLen即前次循环蚂蚁旅行路径长度,开始值为蚂蚁列表中第一只蚂蚁的旅行路径长度 tmpLen = ant.CurrLen#更新变量tmpLen的值 tmpTour = ant.TabuCityList#更新变量tmpTour的值,即更新禁忌城市列表 if tmpLen < self.Shortest:#如果从蚂蚁列表中获取的最短路径小于初始化时定义的长度 self.Shortest = tmpLen#更新旅行路径最短长度 BestTour = tmpTour #更新初始化时定义的最佳旅行城市次序列表 print(iter,":",self.Shortest,":",BestTour)#打印当前迭代次数、最短旅行路径长度和最佳旅行城市次序列表 self.UpdatePheromoneTrail()#完成每次迭代需要使用self,UpdatePheromoneTrail()方法更新信息素 #画图查看结果 x = []; y = [] for city in BestTour: x.append(CityList[city-1][1]) y.append(CityList[city-1][2]) x.append(x[0]) y.append(y[0]) pl.plot(x, y) #pl.figure() pl.scatter(x, y) pl.show() def UpdatePheromoneTrail(self):#定义更新信息素的方法,需要参考前文对于蚁群算法的阐述 for ant in AntList:#循环遍历蚂蚁列表 for city in ant.TabuCityList[0:-1]:#循环遍历蚂蚁的禁忌城市列表 idx = ant.TabuCityList.index(city)#获取当前循环 禁忌城市的索引值 nextCity = ant.TabuCityList[idx+1]#获取当前循环禁忌城市紧邻的下一个禁忌城市 PheromoneDeltaTrailList[city-1][nextCity-1] += self.Q / ant.CurrLen #逐次更新释放信息素列表,注意矩阵行列所代表的意义,[city-1]为选取的子列表即当前城市与所有城市间路径的 #释放信息素值,初始值均为0,[nextCity-1]为在子列表中对应紧邻的下一个城市,释放信息素为Q,信息素增加强度 #系数与蚂蚁当前旅行路径长度CurrLen的比值,路径长度越小释放信息素越大,反之则越小。 PheromoneDeltaTrailList[nextCity-1][city-1] += self.Q / ant.CurrLen #在二维矩阵中,每个城市路径均出现两次,分别为[city-1]对应的[nextCity-1]和[nextCity-1]对应的[city-1],因此都需要更新, #注意城市序列因为从1开始,而列表索引值均从0开始,所以需要减1 lastCity = ant.TabuCityList[-1]#获取禁忌城市列表的最后一个城市 firstCity = ant.TabuCityList[0]#获取禁忌城市列表的第一个城市 PheromoneDeltaTrailList[lastCity-1][firstCity-1] += self.Q / ant.CurrLen #因为蚂蚁旅行需要返回开始的城市,因此需要更新禁忌城市列表最后一个城市到第一个城市旅行路径的释放信息素值,即最后一个城市对应第一个城市的释放信息素值 PheromoneDeltaTrailList[firstCity-1][lastCity-1] += self.Q / ant.CurrLen #同理更新第一个城市对应最后一个城市的释放信息素值 for (city1, city1X, city1Y) in CityList:#循环遍历城市列表,主要是提取city1即城市的序号 for (city2, city2X, city2Y) in CityList:#再次循环遍历城市列表,主要是提取city2即城市序号,循环两次的目的仍然是对应列表矩阵的数据结构 PheromoneTrailList[city1-1][city2-1] = ( (1-self.Rou)*PheromoneTrailList[city1-1][city2-1] + PheromoneDeltaTrailList[city1-1][city2-1] ) PheromoneDeltaTrailList[city1-1][city2-1] = 0#将释放信息素列表值再次初始化为0,用于下次循环 #### print(PheromoneTrailList) class ANT:#定义蚂蚁类,使得蚂蚁具有相应的方法和属性 def __init__(self, currCity = 0):#蚂蚁类的初始化方法,默认传入当前城市序号为0 self.TabuCitySet = set() #定义禁忌城市集合,定义集合的目的是集合本身要素不重复并且之间可以做差集运算,例如AddCity()方法中 #self.AllowedCitySet = CitySet - self.TabuCitySet,可以方便地从城市集合中去除禁忌城市列表的城市,获取允许的城市列表 self.TabuCityList = []#定义禁忌城市空列表 self.AllowedCitySet = set()#定义允许城市集合 self.TransferProbabilityList = []#定义城市选择可能性列表 self.CurrCity = 0 #定义当前城市初始值为0 self.CurrLen = 0.0#定义当前旅行路径长度 self.AddCity(currCity)#执行AddCity()方法,获取每次迭代的当前城市CurrCity、禁忌城市列表TabuCityList和允许城市列表AllowedCitySet的值 pass#空语句,此行为空,不运行任何操作 def SelectNextCity(self, alpha, beta):#定义蚂蚁选择下一个城市的方法,需要参考前文描述的蚁群算法 if len(self.AllowedCitySet) == 0:#如果允许城市集合为0,则返回0 return (0) sumProbability = 0.0#定义概率,可能性初始值为0 self.TransferProbabilityList = []#建立选择下一个城市可能性空列表 for city in self.AllowedCitySet:#循环遍历允许城市集合 sumProbability = sumProbability + ( pow(PheromoneTrailList[self.CurrCity-1][city-1], alpha) * pow(1.0/CityDistanceList[self.CurrCity-1][city-1], beta) ) #蚂蚁选择下一个城市的可能性由信息素与城市间距离之间关系等综合因素确定,其中alpha为表征信息素重要程度的参数,beta为表征启发式因子重要程度的参数, #该语句为前文蚁群算法阐述的选择下一个转移城市的概率公式的分母部分 transferProbability = sumProbability#根据信息素选择公式和轮盘选择得出概率列表,非0-1 self.TransferProbabilityList.append((city, transferProbability))#将城市序号和对应的转移城市概率追加到转移概率列表中 threshold = sumProbability * random.random()#将概率值乘以一个0~1的随机数,获取轮盘指针值 for (cityNum, cityProb) in self.TransferProbabilityList:#再次循环遍历概率列表 if threshold <= cityProb:#如果轮盘指针值大于概率值,则返回对应的城市序号 #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! key step!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! return (cityNum) return (0)#否则返回0 def MoveToNextCity(self, alpha, beta):#定义转移城市方法 nextCity = self.SelectNextCity(alpha, beta)#执行SelectNextCity(),选择下一个城市的方法,获取选择城市的序号,并赋值给新的变量nextCity if nextCity > 0 : #如果选择的城市序号大于0,则执行self.AddCity()方法,获取每次迭代的当前城市Currcity、禁忌城市列表TabuCityList和允许城市列表AllowedCitySet的值 self.AddCity(nextCity)#执行self.AddCity()方法 def ClearTabu(self):#定义清楚禁忌城市方法,以用于下一次循环 self.TabuCityList = []#初始化禁忌城市列表为空 self.TabuCitySet.clear()#初始化城市禁忌列表为空 self.AllowedCitySet = CitySet - self.TabuCitySet#初始化允许城市集合 def UpdatePathLen(self):#定义更新旅行路径长度方法 for city in self.TabuCityList[0:-1]:#循环遍历禁忌城市列表 nextCity = self.TabuCityList[self.TabuCityList.index(city)+1]#获取禁忌城市列表中的下一个城市序号 self.CurrLen = self.CurrLen + CityDistanceList[city-1][nextCity-1]#从城市间距离之中提取当前循环城市与下一个城市之间的距离,并逐次求和 lastCity = self.TabuCityList[-1]#提取禁忌列表中的最后一个城市 firstCity = self.TabuCityList[0]#提取禁忌列表中的第一个城市 self.CurrLen = self.CurrLen + CityDistanceList[lastCity-1][firstCity-1]#将最后一个城市与第一个城市的距离值加到当前旅行路径长度,获取循环全部城市的路径长度 def AddCity(self, city):#定义增加城市到禁忌城市列表中的方法 if city <= 0:#如果城市序号小于等于0,则返回 return self.CurrCity = city#更新当前城市序号 self.TabuCityList.append(city)#将当前城市追加到禁忌城市列表中,因为已经旅行过的城市不应该再进入 self.TabuCitySet.add(city)#将当前城市追加到禁忌城市集合中,用于差集运算 self.AllowedCitySet = CitySet - self.TabuCitySet#使用集合差集的方法获取允许的城市列表 def two_opt_search(self): # 领域搜索 cityNum = len(CityList) for i in range(cityNum): for j in range(cityNum-1, i, -1): #for j in range(i+1, cityNum): #for j in range((i+10) if (i+10)<cityNum else cityNum-1, i, -1): curCity1 = self.TabuCityList[i] -1#此处风格不统一! preCity1 = self.TabuCityList[(i-1) % cityNum] -1 nextCity1 = self.TabuCityList[(i+1) % cityNum] -1 curCity2 = self.TabuCityList[j] -1#此处风格不统一! preCity2 = self.TabuCityList[(j-1) % cityNum] -1 nextCity2 = self.TabuCityList[(j+1) % cityNum] -1 CurrLen = CityDistanceList[preCity1][curCity1] + CityDistanceList[curCity2][nextCity2] NextLen = CityDistanceList[preCity1][curCity2] + CityDistanceList[curCity1][nextCity2] if NextLen < CurrLen: tempList = self.TabuCityList[i:j+1] self.TabuCityList[i:j+1] = tempList[::-1] # for i in range(cityNum): # curCity = self.TabuCityList[i] -1#此处风格不统一! # preCity = self.TabuCityList[(i-1) % cityNum] -1 # nextCity = self.TabuCityList[(i+1) % cityNum] -1 # forwardCity = self.TabuCityList[(i+2) % cityNum] -1 # CurrLen = CityDistanceList[preCity][curCity] + CityDistanceList[nextCity][forwardCity] # NextLen = CityDistanceList[preCity][nextCity] + CityDistanceList[curCity][forwardCity] # if NextLen < CurrLen : # #print i # self.TabuCityList[i], self.TabuCityList[(i+1) % cityNum] = self.TabuCityList[(i+1) % cityNum], self.TabuCityList[i] if __name__ == '__main__':#该语句说明之后的语句在该.py文件作为模块被调用时,语句之后的代码不执行;打开.py文件直接使用时,语句之后的代码则执行。通常该语句在模块测试中 theBaca = BACA()#BACA类的实例化 theBaca.ReadCityInfo('eil51.tsp')#读取城市数据 theBaca.Search()#执行Search()方法 代码2 去除注释,美化代码,增加了最大最小蚁群规则(详见文末资料),求解效果变好 # -*- coding: UTF-8 -*- import random from math import pow, sqrt import numpy as np import pandas as pd import pylab as pl class MMAS: def __init__(self, antCount=20, q=100, alpha=1, beta=3, rou=0.3, initialph=10, nMax=10000): ''' https://svn-d1.mpi-inf.mpg.de/AG1/MultiCoreLab/papers/StuetzleHoos00%20-%20MMAS.pdf ''' self.AntCount = antCount self.Q = q self.Alpha = alpha self.Beta = beta self.Rou = rou self.initialPh = initialph self.Nmax = nMax self.Shortest = float('inf') self.AntList = [] pl.show() def ReadCityInfo(self, fileName): ''' http://stackoverflow.com/questions/29281680/numpy-individual-element-access-slower-than-for-lists ''' city_info = pd.read_csv(fileName, sep=' ', skiprows=6, skipfooter=1, engine='python', header=None, names=('N', 'x', 'y')) self.CityCount = city_info.shape[0] self.CitySet = set() self.CityDistance = [ [0] * self.CityCount for i in range(self.CityCount)] self.CityDistanceBeta = np.zeros( (self.CityCount, self.CityCount)).tolist() self.Pheromone = [ [self.initialPh] * self.CityCount for i in range(self.CityCount)] self.PheromoneDelta = np.zeros( (self.CityCount, self.CityCount)).tolist() self.BestTour = [None] * self.CityCount for row in city_info.index: for col in city_info.index: if row != col: distance = round( sqrt(pow(city_info.x[row] - city_info.x[col], 2) + pow(city_info.y[row] - city_info.y[col], 2)) ) self.CityDistance[row][col] = distance self.CityDistanceBeta[row][col] = pow( 1.0 / distance, self.Beta) self.city_info = city_info def PutAnts(self): self.AntList.clear() for antNum in range(self.AntCount): city = random.choice(self.city_info.index) ant = ANT(city, self.city_info.index, self.CityDistance, self.Pheromone) self.AntList.append(ant) def Search(self): import time for iter in range(self.Nmax): start = time.time() self.PutAnts() tmpLen = float('inf') tmpTour = [] for ant in self.AntList: for ttt in range(self.CityCount): ant.MoveToNextCity(self.Alpha, self.Beta) ant.two_opt_search() ant.UpdatePathLen() if ant.CurrLen < tmpLen: self.bestAnt = ant tmpLen = ant.CurrLen tmpTour = ant.TabuCityList if tmpLen < self.Shortest: self.Shortest = tmpLen self.BestTour = tmpTour print(iter, "-->", self.Shortest, "-->", self.BestTour) # self.bestAnt.two_opt_search() self.UpdatePheromoneTrail() end = time.time() print(end - start) pl.clf() x = []; y = [] for city in self.BestTour: x.append(self.city_info.x[city]) y.append(self.city_info.y[city]) x.append(x[0]) y.append(y[0]) pl.plot(x, y) pl.scatter(x, y, s=30, c='r') pl.pause(0.01) def UpdatePheromoneTrail(self): ant = self.bestAnt pheromo_new = self.Q / ant.CurrLen tabu = ant.TabuCityList PD = self.PheromoneDelta P = self.Pheromone citys = self.city_info.index for city, nextCity in zip(tabu[:-1], tabu[1:]): PD[city][nextCity] = pheromo_new PD[nextCity][city] = pheromo_new lastCity = tabu[-1] firstCity = tabu[0] PD[lastCity][firstCity] = pheromo_new PD[firstCity][lastCity] = pheromo_new for c1 in citys: for c2 in citys: if c1 != c2: P[c1][c2] = ( (1 - self.Rou) * P[c1][c2] + PD[c1][c2] ) if P[c1][c2] < 0.001: P[c1][c2] = 0.001 if P[c1][c2] > 10: raise(Exception('too big Ph')) P[c1][c2] = 10 PD[c1][c2] = 0 class ANT: def __init__(self, currCity=0, citys=None, cityDis=None, pheromo=None): self.TabuCityList = [currCity, ] self.AllowedCitySet = set(citys) self.AllowedCitySet.remove(currCity) self.CityDistance = cityDis self.Pheromone = pheromo self.TransferProbabilityList = [] self.CurrCity = currCity self.CurrLen = 0 def SelectNextCity(self, alpha, beta): if self.AllowedCitySet: sumProbability = 0 self.TransferProbabilityList = [] for city in self.AllowedCitySet: sumProbability = sumProbability + ( pow(self.Pheromone[self.CurrCity][city], alpha) * pow(1.0 / self.CityDistance[self.CurrCity][city], beta) ) transferProbability = sumProbability self.TransferProbabilityList.append( (city, transferProbability)) threshold = sumProbability * random.random() #~print(self.TransferProbabilityList) for cityNum, cityProb in self.TransferProbabilityList: if threshold <= cityProb: return (cityNum) return None def MoveToNextCity(self, alpha, beta): ''' 对于有0返回值的if语句不能使用if x: ... 判断 ''' nextCity = self.SelectNextCity(alpha, beta) if nextCity is not None: self.CurrCity = nextCity self.TabuCityList.append(nextCity) self.AllowedCitySet.remove(nextCity) def UpdatePathLen(self): for city, nextCity in zip(self.TabuCityList[:-1], self.TabuCityList[1:]): self.CurrLen = self.CurrLen + self.CityDistance[city][nextCity] #~print(self.TabuCityList) lastCity = self.TabuCityList[-1] firstCity = self.TabuCityList[0] self.CurrLen = self.CurrLen + self.CityDistance[lastCity][firstCity] def two_opt_search(self): ''' 1-2-3-4, 1-2 + 3-4 > 1-3 + 2-4 则交换 ''' cityNum = len(self.TabuCityList) for i in range(cityNum): for j in range(cityNum - 1, i, -1): curCity1 = self.TabuCityList[i] preCity1 = self.TabuCityList[(i - 1) % cityNum] curCity2 = self.TabuCityList[j] nextCity2 = self.TabuCityList[(j + 1) % cityNum] CurrLen = self.CityDistance[preCity1][ curCity1] + self.CityDistance[curCity2][nextCity2] NextLen = self.CityDistance[preCity1][ curCity2] + self.CityDistance[curCity1][nextCity2] if NextLen < CurrLen: tempList = self.TabuCityList[i:j + 1] self.TabuCityList[i:j + 1] = tempList[::-1] if __name__ == '__main__': aco = MMAS() aco.ReadCityInfo('eil51.tsp') aco.Search()
[ "noreply@github.com" ]
Satan121.noreply@github.com
f28a60ffdd9c80cdba50e7b598f33aa9df46a759
13d309f050210d41c86142aa34dfb555d35dcff3
/englishsurveyor/views.py
0a8e5048b56881f373e3e80fc1f83fe12a41c362
[]
no_license
sabiut/erdsurvey
9df00885d5d771ff2dc3397730a66f3b2d8e86fe
980855a6ff68de346459cb2f63f4189d26da684e
refs/heads/main
2023-05-25T09:35:44.533643
2021-06-09T03:16:31
2021-06-09T03:16:31
363,824,776
0
0
null
null
null
null
UTF-8
Python
false
false
1,133
py
from django.shortcuts import render # Create your views here. from languages.models import Choice, Survey, SurveyAnswer, QuestionAnswer, TextChoice,CheckChoice def survey_view(request, object_id=None): try: survey = Survey.objects.get(id=object_id) questions = survey.question_set.all() ctx = {'survey': survey, 'questions': questions} except: return render(request, 'surveynotfound-error.html', {'sv_id': object_id}) return render(request, 'survey_take.html', ctx) def survey_fill(request): ans = SurveyAnswer() orig_survey = Survey.objects.get(id=request.POST['survey_id']) ans.orig_survey = orig_survey ans.save() questions = orig_survey.question_set.all() for question in questions: qc = request.POST['question' + str(question.id)] qa = QuestionAnswer() qa.answer = Choice.objects.get(id=int(qc)) # qa.answer = TextChoice.objects.get(id=int(qc)) # qa.answer = CheckChoice.objects.get(id=int(qc)) qa.survey_answer = ans qa.save() ans.save() return render(request, 'survey-complete.html', {})
[ "sa252@waikato.students.ac.nz" ]
sa252@waikato.students.ac.nz
c9e5047d03b59579c46003e86f166ca25faaec75
3dfceb181f9cf5bb29c671cc2f417ce877805390
/m2cf/M2P_root/uicharacter.py
1458dd9fa1bc14f526013065ce8f2a72f1e05215
[]
no_license
Sophie-Williams/M2-Project
74e1ce9e80a137b59b54dc8f42f192fb8293b6e9
b07c37b6c24b46040b21693402e4b1606ad67b48
refs/heads/master
2022-11-23T05:16:37.706348
2020-08-02T21:52:07
2020-08-02T21:52:07
null
0
0
null
null
null
null
UHC
Python
false
false
38,363
py
import ui import uiScriptLocale import app import net import dbg import snd import player import mouseModule import wndMgr import skill import playerSettingModule import quest import localeInfo import uiToolTip import constInfo import emotion import chr SHOW_ONLY_ACTIVE_SKILL = False SHOW_LIMIT_SUPPORT_SKILL_LIST = [] HIDE_SUPPORT_SKILL_POINT = False if localeInfo.IsYMIR(): SHOW_LIMIT_SUPPORT_SKILL_LIST = [121, 122, 123, 124, 126, 127, 129, 128, 131, 137, 138, 139, 140,141,142] if not localeInfo.IsCHEONMA(): HIDE_SUPPORT_SKILL_POINT = True SHOW_LIMIT_SUPPORT_SKILL_LIST = [121, 122, 123, 124, 126, 127, 129, 128, 131, 137, 138, 139, 140,141,142] elif localeInfo.IsJAPAN() or (localeInfo.IsEUROPE() and app.GetLocalePath() != "locale/ca") and (localeInfo.IsEUROPE() and app.GetLocalePath() != "locale/br"): HIDE_SUPPORT_SKILL_POINT = True SHOW_LIMIT_SUPPORT_SKILL_LIST = [121, 122, 123, 124, 126, 127, 129, 128, 131, 137, 138, 139, 140] else: HIDE_SUPPORT_SKILL_POINT = True FACE_IMAGE_DICT = { playerSettingModule.RACE_WARRIOR_M : "icon/face/warrior_m.tga", playerSettingModule.RACE_WARRIOR_W : "icon/face/warrior_w.tga", playerSettingModule.RACE_ASSASSIN_M : "icon/face/assassin_m.tga", playerSettingModule.RACE_ASSASSIN_W : "icon/face/assassin_w.tga", playerSettingModule.RACE_SURA_M : "icon/face/sura_m.tga", playerSettingModule.RACE_SURA_W : "icon/face/sura_w.tga", playerSettingModule.RACE_SHAMAN_M : "icon/face/shaman_m.tga", playerSettingModule.RACE_SHAMAN_W : "icon/face/shaman_w.tga", } def unsigned32(n): return n & 0xFFFFFFFFL class CharacterWindow(ui.ScriptWindow): ACTIVE_PAGE_SLOT_COUNT = 8 SUPPORT_PAGE_SLOT_COUNT = 12 PAGE_SLOT_COUNT = 12 PAGE_HORSE = 2 SKILL_GROUP_NAME_DICT = { playerSettingModule.JOB_WARRIOR : { 1 : localeInfo.SKILL_GROUP_WARRIOR_1, 2 : localeInfo.SKILL_GROUP_WARRIOR_2, }, playerSettingModule.JOB_ASSASSIN : { 1 : localeInfo.SKILL_GROUP_ASSASSIN_1, 2 : localeInfo.SKILL_GROUP_ASSASSIN_2, }, playerSettingModule.JOB_SURA : { 1 : localeInfo.SKILL_GROUP_SURA_1, 2 : localeInfo.SKILL_GROUP_SURA_2, }, playerSettingModule.JOB_SHAMAN : { 1 : localeInfo.SKILL_GROUP_SHAMAN_1, 2 : localeInfo.SKILL_GROUP_SHAMAN_2, }, } STAT_DESCRIPTION = { "HTH" : localeInfo.STAT_TOOLTIP_CON, "INT" : localeInfo.STAT_TOOLTIP_INT, "STR" : localeInfo.STAT_TOOLTIP_STR, "DEX" : localeInfo.STAT_TOOLTIP_DEX, } STAT_MINUS_DESCRIPTION = localeInfo.STAT_MINUS_DESCRIPTION def __init__(self): ui.ScriptWindow.__init__(self) self.state = "STATUS" self.isLoaded = 0 self.toolTipSkill = 0 self.__Initialize() self.__LoadWindow() self.statusPlusCommandDict={ "HTH" : "/stat ht", "INT" : "/stat iq", "STR" : "/stat st", "DEX" : "/stat dx", } self.statusMinusCommandDict={ "HTH-" : "/stat- ht", "INT-" : "/stat- iq", "STR-" : "/stat- st", "DEX-" : "/stat- dx", } def __del__(self): ui.ScriptWindow.__del__(self) def __Initialize(self): self.refreshToolTip = 0 self.curSelectedSkillGroup = 0 self.canUseHorseSkill = -1 self.toolTip = None self.toolTipJob = None self.toolTipAlignment = None self.toolTipSkill = None self.faceImage = None self.statusPlusLabel = None self.statusPlusValue = None self.activeSlot = None self.tabDict = None self.tabButtonDict = None self.pageDict = None self.titleBarDict = None self.statusPlusButtonDict = None self.statusMinusButtonDict = None self.skillPageDict = None self.questShowingStartIndex = 0 self.questScrollBar = None self.questSlot = None self.questNameList = None self.questLastTimeList = None self.questLastCountList = None self.skillGroupButton = () self.activeSlot = None self.activeSkillPointValue = None self.supportSkillPointValue = None self.skillGroupButton1 = None self.skillGroupButton2 = None self.activeSkillGroupName = None self.guildNameSlot = None self.guildNameValue = None self.characterNameSlot = None self.characterNameValue = None self.emotionToolTip = None self.soloEmotionSlot = None self.dualEmotionSlot = None def Show(self): self.__LoadWindow() ui.ScriptWindow.Show(self) def __LoadScript(self, fileName): pyScrLoader = ui.PythonScriptLoader() pyScrLoader.LoadScriptFile(self, fileName) def __BindObject(self): self.toolTip = uiToolTip.ToolTip() self.toolTipJob = uiToolTip.ToolTip() self.toolTipAlignment = uiToolTip.ToolTip(130) self.faceImage = self.GetChild("Face_Image") faceSlot=self.GetChild("Face_Slot") if 949 == app.GetDefaultCodePage(): faceSlot.SAFE_SetStringEvent("MOUSE_OVER_IN", self.__ShowJobToolTip) faceSlot.SAFE_SetStringEvent("MOUSE_OVER_OUT", self.__HideJobToolTip) self.statusPlusLabel = self.GetChild("Status_Plus_Label") self.statusPlusValue = self.GetChild("Status_Plus_Value") self.characterNameSlot = self.GetChild("Character_Name_Slot") self.characterNameValue = self.GetChild("Character_Name") self.guildNameSlot = self.GetChild("Guild_Name_Slot") self.guildNameValue = self.GetChild("Guild_Name") self.characterNameSlot.SAFE_SetStringEvent("MOUSE_OVER_IN", self.__ShowAlignmentToolTip) self.characterNameSlot.SAFE_SetStringEvent("MOUSE_OVER_OUT", self.__HideAlignmentToolTip) self.activeSlot = self.GetChild("Skill_Active_Slot") self.activeSkillPointValue = self.GetChild("Active_Skill_Point_Value") self.supportSkillPointValue = self.GetChild("Support_Skill_Point_Value") self.skillGroupButton1 = self.GetChild("Skill_Group_Button_1") self.skillGroupButton2 = self.GetChild("Skill_Group_Button_2") self.activeSkillGroupName = self.GetChild("Active_Skill_Group_Name") self.tabDict = { "STATUS" : self.GetChild("Tab_01"), "SKILL" : self.GetChild("Tab_02"), "EMOTICON" : self.GetChild("Tab_03"), "QUEST" : self.GetChild("Tab_04"), } self.tabButtonDict = { "STATUS" : self.GetChild("Tab_Button_01"), "SKILL" : self.GetChild("Tab_Button_02"), "EMOTICON" : self.GetChild("Tab_Button_03"), "QUEST" : self.GetChild("Tab_Button_04") } self.pageDict = { "STATUS" : self.GetChild("Character_Page"), "SKILL" : self.GetChild("Skill_Page"), "EMOTICON" : self.GetChild("Emoticon_Page"), "QUEST" : self.GetChild("Quest_Page") } self.titleBarDict = { "STATUS" : self.GetChild("Character_TitleBar"), "SKILL" : self.GetChild("Skill_TitleBar"), "EMOTICON" : self.GetChild("Emoticon_TitleBar"), "QUEST" : self.GetChild("Quest_TitleBar") } self.statusPlusButtonDict = { "HTH" : self.GetChild("HTH_Plus"), "INT" : self.GetChild("INT_Plus"), "STR" : self.GetChild("STR_Plus"), "DEX" : self.GetChild("DEX_Plus"), } self.statusMinusButtonDict = { "HTH-" : self.GetChild("HTH_Minus"), "INT-" : self.GetChild("INT_Minus"), "STR-" : self.GetChild("STR_Minus"), "DEX-" : self.GetChild("DEX_Minus"), } self.skillPageDict = { "ACTIVE" : self.GetChild("Skill_Active_Slot"), "SUPPORT" : self.GetChild("Skill_ETC_Slot"), "HORSE" : self.GetChild("Skill_Active_Slot"), } self.skillPageStatDict = { "SUPPORT" : player.SKILL_SUPPORT, "ACTIVE" : player.SKILL_ACTIVE, "HORSE" : player.SKILL_HORSE, } self.skillGroupButton = ( self.GetChild("Skill_Group_Button_1"), self.GetChild("Skill_Group_Button_2"), ) global SHOW_ONLY_ACTIVE_SKILL global HIDE_SUPPORT_SKILL_POINT if SHOW_ONLY_ACTIVE_SKILL or HIDE_SUPPORT_SKILL_POINT: self.GetChild("Support_Skill_Point_Label").Hide() self.soloEmotionSlot = self.GetChild("SoloEmotionSlot") self.dualEmotionSlot = self.GetChild("DualEmotionSlot") self.__SetEmotionSlot() self.questShowingStartIndex = 0 self.questScrollBar = self.GetChild("Quest_ScrollBar") self.questScrollBar.SetScrollEvent(ui.__mem_func__(self.OnQuestScroll)) self.questSlot = self.GetChild("Quest_Slot") for i in xrange(quest.QUEST_MAX_NUM): self.questSlot.HideSlotBaseImage(i) self.questSlot.SetCoverButton(i,\ "d:/ymir work/ui/game/quest/slot_button_01.sub",\ "d:/ymir work/ui/game/quest/slot_button_02.sub",\ "d:/ymir work/ui/game/quest/slot_button_03.sub",\ "d:/ymir work/ui/game/quest/slot_button_03.sub", True) self.questNameList = [] self.questLastTimeList = [] self.questLastCountList = [] for i in xrange(quest.QUEST_MAX_NUM): self.questNameList.append(self.GetChild("Quest_Name_0" + str(i))) self.questLastTimeList.append(self.GetChild("Quest_LastTime_0" + str(i))) self.questLastCountList.append(self.GetChild("Quest_LastCount_0" + str(i))) def __SetSkillSlotEvent(self): for skillPageValue in self.skillPageDict.itervalues(): skillPageValue.SetSlotStyle(wndMgr.SLOT_STYLE_NONE) skillPageValue.SetSelectItemSlotEvent(ui.__mem_func__(self.SelectSkill)) skillPageValue.SetSelectEmptySlotEvent(ui.__mem_func__(self.SelectEmptySlot)) skillPageValue.SetUnselectItemSlotEvent(ui.__mem_func__(self.ClickSkillSlot)) skillPageValue.SetUseSlotEvent(ui.__mem_func__(self.ClickSkillSlot)) skillPageValue.SetOverInItemEvent(ui.__mem_func__(self.OverInItem)) skillPageValue.SetOverOutItemEvent(ui.__mem_func__(self.OverOutItem)) skillPageValue.SetPressedSlotButtonEvent(ui.__mem_func__(self.OnPressedSlotButton)) skillPageValue.AppendSlotButton("d:/ymir work/ui/game/windows/btn_plus_up.sub",\ "d:/ymir work/ui/game/windows/btn_plus_over.sub",\ "d:/ymir work/ui/game/windows/btn_plus_down.sub") def __SetEmotionSlot(self): self.emotionToolTip = uiToolTip.ToolTip() for slot in (self.soloEmotionSlot, self.dualEmotionSlot): slot.SetSlotStyle(wndMgr.SLOT_STYLE_NONE) slot.SetSelectItemSlotEvent(ui.__mem_func__(self.__SelectEmotion)) slot.SetUnselectItemSlotEvent(ui.__mem_func__(self.__ClickEmotionSlot)) slot.SetUseSlotEvent(ui.__mem_func__(self.__ClickEmotionSlot)) slot.SetOverInItemEvent(ui.__mem_func__(self.__OverInEmotion)) slot.SetOverOutItemEvent(ui.__mem_func__(self.__OverOutEmotion)) slot.AppendSlotButton("d:/ymir work/ui/game/windows/btn_plus_up.sub",\ "d:/ymir work/ui/game/windows/btn_plus_over.sub",\ "d:/ymir work/ui/game/windows/btn_plus_down.sub") for slotIdx, datadict in emotion.EMOTION_DICT.items(): emotionIdx = slotIdx slot = self.soloEmotionSlot if slotIdx > 50: slot = self.dualEmotionSlot slot.SetEmotionSlot(slotIdx, emotionIdx) slot.SetCoverButton(slotIdx) def __SelectEmotion(self, slotIndex): if not slotIndex in emotion.EMOTION_DICT: return if app.IsPressed(app.DIK_LCONTROL): player.RequestAddToEmptyLocalQuickSlot(player.SLOT_TYPE_EMOTION, slotIndex) return mouseModule.mouseController.AttachObject(self, player.SLOT_TYPE_EMOTION, slotIndex, slotIndex) def __ClickEmotionSlot(self, slotIndex): print "click emotion" if not slotIndex in emotion.EMOTION_DICT: return print "check acting" if player.IsActingEmotion(): return command = emotion.EMOTION_DICT[slotIndex]["command"] print "command", command if slotIndex > 50: vid = player.GetTargetVID() if 0 == vid or vid == player.GetMainCharacterIndex() or chr.IsNPC(vid) or chr.IsEnemy(vid): import chat chat.AppendChat(chat.CHAT_TYPE_INFO, localeInfo.EMOTION_CHOOSE_ONE) return command += " " + chr.GetNameByVID(vid) print "send_command", command net.SendChatPacket(command) def ActEmotion(self, emotionIndex): self.__ClickEmotionSlot(emotionIndex) def __OverInEmotion(self, slotIndex): if self.emotionToolTip: if not slotIndex in emotion.EMOTION_DICT: return self.emotionToolTip.ClearToolTip() self.emotionToolTip.SetTitle(emotion.EMOTION_DICT[slotIndex]["name"]) self.emotionToolTip.AlignHorizonalCenter() self.emotionToolTip.ShowToolTip() def __OverOutEmotion(self): if self.emotionToolTip: self.emotionToolTip.HideToolTip() def __BindEvent(self): for i in xrange(len(self.skillGroupButton)): self.skillGroupButton[i].SetEvent(lambda arg=i: self.__SelectSkillGroup(arg)) self.RefreshQuest() self.__HideJobToolTip() for (tabKey, tabButton) in self.tabButtonDict.items(): tabButton.SetEvent(ui.__mem_func__(self.__OnClickTabButton), tabKey) for (statusPlusKey, statusPlusButton) in self.statusPlusButtonDict.items(): statusPlusButton.SAFE_SetEvent(self.__OnClickStatusPlusButton, statusPlusKey) statusPlusButton.ShowToolTip = lambda arg=statusPlusKey: self.__OverInStatButton(arg) statusPlusButton.HideToolTip = lambda arg=statusPlusKey: self.__OverOutStatButton() for (statusMinusKey, statusMinusButton) in self.statusMinusButtonDict.items(): statusMinusButton.SAFE_SetEvent(self.__OnClickStatusMinusButton, statusMinusKey) statusMinusButton.ShowToolTip = lambda arg=statusMinusKey: self.__OverInStatMinusButton(arg) statusMinusButton.HideToolTip = lambda arg=statusMinusKey: self.__OverOutStatMinusButton() for titleBarValue in self.titleBarDict.itervalues(): titleBarValue.SetCloseEvent(ui.__mem_func__(self.Hide)) self.questSlot.SetSelectItemSlotEvent(ui.__mem_func__(self.__SelectQuest)) def __LoadWindow(self): if self.isLoaded == 1: return self.isLoaded = 1 try: if localeInfo.IsARABIC() or localeInfo.IsVIETNAM() or localeInfo.IsJAPAN(): self.__LoadScript(uiScriptLocale.LOCALE_UISCRIPT_PATH + "CharacterWindow.py") else: self.__LoadScript("UIScript/CharacterWindow.py") self.__BindObject() self.__BindEvent() except: import exception exception.Abort("CharacterWindow.__LoadWindow") #self.tabButtonDict["EMOTICON"].Disable() self.SetState("STATUS") def Destroy(self): self.ClearDictionary() self.__Initialize() def Close(self): if 0 != self.toolTipSkill: self.toolTipSkill.Hide() self.Hide() def SetSkillToolTip(self, toolTipSkill): self.toolTipSkill = toolTipSkill def __OnClickStatusPlusButton(self, statusKey): try: statusPlusCommand=self.statusPlusCommandDict[statusKey] net.SendChatPacket(statusPlusCommand) except KeyError, msg: dbg.TraceError("CharacterWindow.__OnClickStatusPlusButton KeyError: %s", msg) def __OnClickStatusMinusButton(self, statusKey): try: statusMinusCommand=self.statusMinusCommandDict[statusKey] net.SendChatPacket(statusMinusCommand) except KeyError, msg: dbg.TraceError("CharacterWindow.__OnClickStatusMinusButton KeyError: %s", msg) def __OnClickTabButton(self, stateKey): self.SetState(stateKey) def SetState(self, stateKey): self.state = stateKey for (tabKey, tabButton) in self.tabButtonDict.items(): if stateKey!=tabKey: tabButton.SetUp() for tabValue in self.tabDict.itervalues(): tabValue.Hide() for pageValue in self.pageDict.itervalues(): pageValue.Hide() for titleBarValue in self.titleBarDict.itervalues(): titleBarValue.Hide() self.titleBarDict[stateKey].Show() self.tabDict[stateKey].Show() self.pageDict[stateKey].Show() def GetState(self): return self.state def __GetTotalAtkText(self): minAtk=player.GetStatus(player.ATT_MIN) maxAtk=player.GetStatus(player.ATT_MAX) atkBonus=player.GetStatus(player.ATT_BONUS) attackerBonus=player.GetStatus(player.ATTACKER_BONUS) if minAtk==maxAtk: return "%d" % (minAtk+atkBonus+attackerBonus) else: return "%d-%d" % (minAtk+atkBonus+attackerBonus, maxAtk+atkBonus+attackerBonus) def __GetTotalMagAtkText(self): minMagAtk=player.GetStatus(player.MAG_ATT)+player.GetStatus(player.MIN_MAGIC_WEP) maxMagAtk=player.GetStatus(player.MAG_ATT)+player.GetStatus(player.MAX_MAGIC_WEP) if minMagAtk==maxMagAtk: return "%d" % (minMagAtk) else: return "%d-%d" % (minMagAtk, maxMagAtk) def __GetTotalDefText(self): defValue=player.GetStatus(player.DEF_GRADE) if constInfo.ADD_DEF_BONUS_ENABLE: defValue+=player.GetStatus(player.DEF_BONUS) return "%d" % (defValue) def RefreshStatus(self): if self.isLoaded==0: return try: self.GetChild("Level_Value").SetText(str(player.GetStatus(player.LEVEL))) self.GetChild("Exp_Value").SetText(str(unsigned32(player.GetEXP()))) self.GetChild("RestExp_Value").SetText(str(unsigned32(player.GetStatus(player.NEXT_EXP)) - unsigned32(player.GetStatus(player.EXP)))) self.GetChild("HP_Value").SetText(str(player.GetStatus(player.HP)) + '/' + str(player.GetStatus(player.MAX_HP))) self.GetChild("SP_Value").SetText(str(player.GetStatus(player.SP)) + '/' + str(player.GetStatus(player.MAX_SP))) self.GetChild("STR_Value").SetText(str(player.GetStatus(player.ST))) self.GetChild("DEX_Value").SetText(str(player.GetStatus(player.DX))) self.GetChild("HTH_Value").SetText(str(player.GetStatus(player.HT))) self.GetChild("INT_Value").SetText(str(player.GetStatus(player.IQ))) self.GetChild("ATT_Value").SetText(self.__GetTotalAtkText()) self.GetChild("DEF_Value").SetText(self.__GetTotalDefText()) self.GetChild("MATT_Value").SetText(self.__GetTotalMagAtkText()) #self.GetChild("MATT_Value").SetText(str(player.GetStatus(player.MAG_ATT))) self.GetChild("MDEF_Value").SetText(str(player.GetStatus(player.MAG_DEF))) self.GetChild("ASPD_Value").SetText(str(player.GetStatus(player.ATT_SPEED))) self.GetChild("MSPD_Value").SetText(str(player.GetStatus(player.MOVING_SPEED))) self.GetChild("CSPD_Value").SetText(str(player.GetStatus(player.CASTING_SPEED))) self.GetChild("ER_Value").SetText(str(player.GetStatus(player.EVADE_RATE))) except: #import exception #exception.Abort("CharacterWindow.RefreshStatus.BindObject") ## 게임이 튕겨 버림 pass self.__RefreshStatusPlusButtonList() self.__RefreshStatusMinusButtonList() self.RefreshAlignment() if self.refreshToolTip: self.refreshToolTip() def __RefreshStatusPlusButtonList(self): if self.isLoaded==0: return statusPlusPoint=player.GetStatus(player.STAT) if statusPlusPoint>0: self.statusPlusValue.SetText(str(statusPlusPoint)) self.statusPlusLabel.Show() self.ShowStatusPlusButtonList() else: self.statusPlusValue.SetText(str(0)) self.statusPlusLabel.Hide() self.HideStatusPlusButtonList() def __RefreshStatusMinusButtonList(self): if self.isLoaded==0: return statusMinusPoint=self.__GetStatMinusPoint() if statusMinusPoint>0: self.__ShowStatusMinusButtonList() else: self.__HideStatusMinusButtonList() def RefreshAlignment(self): point, grade = player.GetAlignmentData() import colorInfo COLOR_DICT = { 0 : colorInfo.TITLE_RGB_GOOD_4, 1 : colorInfo.TITLE_RGB_GOOD_3, 2 : colorInfo.TITLE_RGB_GOOD_2, 3 : colorInfo.TITLE_RGB_GOOD_1, 4 : colorInfo.TITLE_RGB_NORMAL, 5 : colorInfo.TITLE_RGB_EVIL_1, 6 : colorInfo.TITLE_RGB_EVIL_2, 7 : colorInfo.TITLE_RGB_EVIL_3, 8 : colorInfo.TITLE_RGB_EVIL_4, } colorList = COLOR_DICT.get(grade, colorInfo.TITLE_RGB_NORMAL) gradeColor = ui.GenerateColor(colorList[0], colorList[1], colorList[2]) self.toolTipAlignment.ClearToolTip() self.toolTipAlignment.AutoAppendTextLine(localeInfo.TITLE_NAME_LIST[grade], gradeColor) self.toolTipAlignment.AutoAppendTextLine(localeInfo.ALIGNMENT_NAME + str(point)) self.toolTipAlignment.AlignHorizonalCenter() def __ShowStatusMinusButtonList(self): for (stateMinusKey, statusMinusButton) in self.statusMinusButtonDict.items(): statusMinusButton.Show() def __HideStatusMinusButtonList(self): for (stateMinusKey, statusMinusButton) in self.statusMinusButtonDict.items(): statusMinusButton.Hide() def ShowStatusPlusButtonList(self): for (statePlusKey, statusPlusButton) in self.statusPlusButtonDict.items(): statusPlusButton.Show() def HideStatusPlusButtonList(self): for (statePlusKey, statusPlusButton) in self.statusPlusButtonDict.items(): statusPlusButton.Hide() def SelectSkill(self, skillSlotIndex): mouseController = mouseModule.mouseController if False == mouseController.isAttached(): srcSlotIndex = self.__RealSkillSlotToSourceSlot(skillSlotIndex) selectedSkillIndex = player.GetSkillIndex(srcSlotIndex) if skill.CanUseSkill(selectedSkillIndex): if app.IsPressed(app.DIK_LCONTROL): player.RequestAddToEmptyLocalQuickSlot(player.SLOT_TYPE_SKILL, srcSlotIndex) return mouseController.AttachObject(self, player.SLOT_TYPE_SKILL, srcSlotIndex, selectedSkillIndex) else: mouseController.DeattachObject() def SelectEmptySlot(self, SlotIndex): mouseModule.mouseController.DeattachObject() ## ToolTip def OverInItem(self, slotNumber): if mouseModule.mouseController.isAttached(): return if 0 == self.toolTipSkill: return srcSlotIndex = self.__RealSkillSlotToSourceSlot(slotNumber) skillIndex = player.GetSkillIndex(srcSlotIndex) skillLevel = player.GetSkillLevel(srcSlotIndex) skillGrade = player.GetSkillGrade(srcSlotIndex) skillType = skill.GetSkillType(skillIndex) ## ACTIVE if skill.SKILL_TYPE_ACTIVE == skillType: overInSkillGrade = self.__GetSkillGradeFromSlot(slotNumber) if overInSkillGrade == skill.SKILL_GRADE_COUNT-1 and skillGrade == skill.SKILL_GRADE_COUNT: self.toolTipSkill.SetSkillNew(srcSlotIndex, skillIndex, skillGrade, skillLevel) elif overInSkillGrade == skillGrade: self.toolTipSkill.SetSkillNew(srcSlotIndex, skillIndex, overInSkillGrade, skillLevel) else: self.toolTipSkill.SetSkillOnlyName(srcSlotIndex, skillIndex, overInSkillGrade) else: self.toolTipSkill.SetSkillNew(srcSlotIndex, skillIndex, skillGrade, skillLevel) def OverOutItem(self): if 0 != self.toolTipSkill: self.toolTipSkill.HideToolTip() ## Quest def __SelectQuest(self, slotIndex): questIndex = quest.GetQuestIndex(self.questShowingStartIndex+slotIndex) import event event.QuestButtonClick(-2147483648 + questIndex) def RefreshQuest(self): if self.isLoaded==0: return questCount = quest.GetQuestCount() questRange = range(quest.QUEST_MAX_NUM) if questCount > quest.QUEST_MAX_NUM: self.questScrollBar.Show() else: self.questScrollBar.Hide() for i in questRange[:questCount]: (questName, questIcon, questCounterName, questCounterValue) = quest.GetQuestData(self.questShowingStartIndex+i) self.questNameList[i].SetText(questName) self.questNameList[i].Show() self.questLastCountList[i].Show() self.questLastTimeList[i].Show() if len(questCounterName) > 0: self.questLastCountList[i].SetText("%s : %d" % (questCounterName, questCounterValue)) else: self.questLastCountList[i].SetText("") ## Icon self.questSlot.SetSlot(i, i, 1, 1, questIcon) for i in questRange[questCount:]: self.questNameList[i].Hide() self.questLastTimeList[i].Hide() self.questLastCountList[i].Hide() self.questSlot.ClearSlot(i) self.questSlot.HideSlotBaseImage(i) self.__UpdateQuestClock() def __UpdateQuestClock(self): if "QUEST" == self.state: # QUEST_LIMIT_COUNT_BUG_FIX for i in xrange(min(quest.GetQuestCount(), quest.QUEST_MAX_NUM)): # END_OF_QUEST_LIMIT_COUNT_BUG_FIX (lastName, lastTime) = quest.GetQuestLastTime(i) clockText = localeInfo.QUEST_UNLIMITED_TIME if len(lastName) > 0: if lastTime <= 0: clockText = localeInfo.QUEST_TIMEOVER else: questLastMinute = lastTime / 60 questLastSecond = lastTime % 60 clockText = lastName + " : " if questLastMinute > 0: clockText += str(questLastMinute) + localeInfo.QUEST_MIN if questLastSecond > 0: clockText += " " if questLastSecond > 0: clockText += str(questLastSecond) + localeInfo.QUEST_SEC self.questLastTimeList[i].SetText(clockText) def __GetStatMinusPoint(self): POINT_STAT_RESET_COUNT = 112 return player.GetStatus(POINT_STAT_RESET_COUNT) def __OverInStatMinusButton(self, stat): try: self.__ShowStatToolTip(self.STAT_MINUS_DESCRIPTION[stat] % self.__GetStatMinusPoint()) except KeyError: pass self.refreshToolTip = lambda arg=stat: self.__OverInStatMinusButton(arg) def __OverOutStatMinusButton(self): self.__HideStatToolTip() self.refreshToolTip = 0 def __OverInStatButton(self, stat): try: self.__ShowStatToolTip(self.STAT_DESCRIPTION[stat]) except KeyError: pass def __OverOutStatButton(self): self.__HideStatToolTip() def __ShowStatToolTip(self, statDesc): self.toolTip.ClearToolTip() self.toolTip.AppendTextLine(statDesc) self.toolTip.Show() def __HideStatToolTip(self): self.toolTip.Hide() def OnPressEscapeKey(self): self.Close() return True def OnUpdate(self): self.__UpdateQuestClock() ## Skill Process def __RefreshSkillPage(self, name, slotCount): global SHOW_LIMIT_SUPPORT_SKILL_LIST skillPage = self.skillPageDict[name] startSlotIndex = skillPage.GetStartIndex() if "ACTIVE" == name: if self.PAGE_HORSE == self.curSelectedSkillGroup: startSlotIndex += slotCount getSkillType=skill.GetSkillType getSkillIndex=player.GetSkillIndex getSkillGrade=player.GetSkillGrade getSkillLevel=player.GetSkillLevel getSkillLevelUpPoint=skill.GetSkillLevelUpPoint getSkillMaxLevel=skill.GetSkillMaxLevel for i in xrange(slotCount+1): slotIndex = i + startSlotIndex skillIndex = getSkillIndex(slotIndex) for j in xrange(skill.SKILL_GRADE_COUNT): skillPage.ClearSlot(self.__GetRealSkillSlot(j, i)) if 0 == skillIndex: continue skillGrade = getSkillGrade(slotIndex) skillLevel = getSkillLevel(slotIndex) skillType = getSkillType(skillIndex) ## 승마 스킬 예외 처리 if player.SKILL_INDEX_RIDING == skillIndex: if 1 == skillGrade: skillLevel += 19 elif 2 == skillGrade: skillLevel += 29 elif 3 == skillGrade: skillLevel = 40 skillPage.SetSkillSlotNew(slotIndex, skillIndex, max(skillLevel-1, 0), skillLevel) skillPage.SetSlotCount(slotIndex, skillLevel) ## ACTIVE elif skill.SKILL_TYPE_ACTIVE == skillType: for j in xrange(skill.SKILL_GRADE_COUNT): realSlotIndex = self.__GetRealSkillSlot(j, slotIndex) skillPage.SetSkillSlotNew(realSlotIndex, skillIndex, j, skillLevel) skillPage.SetCoverButton(realSlotIndex) if (skillGrade == skill.SKILL_GRADE_COUNT) and j == (skill.SKILL_GRADE_COUNT-1): skillPage.SetSlotCountNew(realSlotIndex, skillGrade, skillLevel) elif (not self.__CanUseSkillNow()) or (skillGrade != j): skillPage.SetSlotCount(realSlotIndex, 0) skillPage.DisableCoverButton(realSlotIndex) else: skillPage.SetSlotCountNew(realSlotIndex, skillGrade, skillLevel) ## 그외 else: if not SHOW_LIMIT_SUPPORT_SKILL_LIST or skillIndex in SHOW_LIMIT_SUPPORT_SKILL_LIST: realSlotIndex = self.__GetETCSkillRealSlotIndex(slotIndex) skillPage.SetSkillSlot(realSlotIndex, skillIndex, skillLevel) skillPage.SetSlotCountNew(realSlotIndex, skillGrade, skillLevel) if skill.CanUseSkill(skillIndex): skillPage.SetCoverButton(realSlotIndex) skillPage.RefreshSlot() def RefreshSkill(self): if self.isLoaded==0: return if self.__IsChangedHorseRidingSkillLevel(): self.RefreshCharacter() return global SHOW_ONLY_ACTIVE_SKILL if SHOW_ONLY_ACTIVE_SKILL: self.__RefreshSkillPage("ACTIVE", self.ACTIVE_PAGE_SLOT_COUNT) else: self.__RefreshSkillPage("ACTIVE", self.ACTIVE_PAGE_SLOT_COUNT) self.__RefreshSkillPage("SUPPORT", self.SUPPORT_PAGE_SLOT_COUNT) self.RefreshSkillPlusButtonList() def CanShowPlusButton(self, skillIndex, skillLevel, curStatPoint): ## 스킬이 있으면 if 0 == skillIndex: return False ## 레벨업 조건을 만족한다면 if not skill.CanLevelUpSkill(skillIndex, skillLevel): return False return True def __RefreshSkillPlusButton(self, name): global HIDE_SUPPORT_SKILL_POINT if HIDE_SUPPORT_SKILL_POINT and "SUPPORT" == name: return slotWindow = self.skillPageDict[name] slotWindow.HideAllSlotButton() slotStatType = self.skillPageStatDict[name] if 0 == slotStatType: return statPoint = player.GetStatus(slotStatType) startSlotIndex = slotWindow.GetStartIndex() if "HORSE" == name: startSlotIndex += self.ACTIVE_PAGE_SLOT_COUNT if statPoint > 0: for i in xrange(self.PAGE_SLOT_COUNT): slotIndex = i + startSlotIndex skillIndex = player.GetSkillIndex(slotIndex) skillGrade = player.GetSkillGrade(slotIndex) skillLevel = player.GetSkillLevel(slotIndex) if skillIndex == 0: continue if skillGrade != 0: continue if name == "HORSE": if player.GetStatus(player.LEVEL) >= skill.GetSkillLevelLimit(skillIndex): if skillLevel < 20: slotWindow.ShowSlotButton(self.__GetETCSkillRealSlotIndex(slotIndex)) else: if "SUPPORT" == name: if not SHOW_LIMIT_SUPPORT_SKILL_LIST or skillIndex in SHOW_LIMIT_SUPPORT_SKILL_LIST: if self.CanShowPlusButton(skillIndex, skillLevel, statPoint): slotWindow.ShowSlotButton(slotIndex) else: if self.CanShowPlusButton(skillIndex, skillLevel, statPoint): slotWindow.ShowSlotButton(slotIndex) def RefreshSkillPlusButtonList(self): if self.isLoaded==0: return self.RefreshSkillPlusPointLabel() if not self.__CanUseSkillNow(): return try: if self.PAGE_HORSE == self.curSelectedSkillGroup: self.__RefreshSkillPlusButton("HORSE") else: self.__RefreshSkillPlusButton("ACTIVE") self.__RefreshSkillPlusButton("SUPPORT") except: import exception exception.Abort("CharacterWindow.RefreshSkillPlusButtonList.BindObject") def RefreshSkillPlusPointLabel(self): if self.isLoaded==0: return if self.PAGE_HORSE == self.curSelectedSkillGroup: activeStatPoint = player.GetStatus(player.SKILL_HORSE) self.activeSkillPointValue.SetText(str(activeStatPoint)) else: activeStatPoint = player.GetStatus(player.SKILL_ACTIVE) self.activeSkillPointValue.SetText(str(activeStatPoint)) supportStatPoint = max(0, player.GetStatus(player.SKILL_SUPPORT)) self.supportSkillPointValue.SetText(str(supportStatPoint)) ## Skill Level Up Button def OnPressedSlotButton(self, slotNumber): srcSlotIndex = self.__RealSkillSlotToSourceSlot(slotNumber) skillIndex = player.GetSkillIndex(srcSlotIndex) curLevel = player.GetSkillLevel(srcSlotIndex) maxLevel = skill.GetSkillMaxLevel(skillIndex) net.SendChatPacket("/skillup " + str(skillIndex)) ## Use Skill def ClickSkillSlot(self, slotIndex): srcSlotIndex = self.__RealSkillSlotToSourceSlot(slotIndex) skillIndex = player.GetSkillIndex(srcSlotIndex) skillType = skill.GetSkillType(skillIndex) if not self.__CanUseSkillNow(): if skill.SKILL_TYPE_ACTIVE == skillType: return for slotWindow in self.skillPageDict.values(): if slotWindow.HasSlot(slotIndex): if skill.CanUseSkill(skillIndex): player.ClickSkillSlot(srcSlotIndex) return mouseModule.mouseController.DeattachObject() ## FIXME : 스킬을 사용했을때 슬롯 번호를 가지고 해당 슬롯을 찾아서 업데이트 한다. ## 매우 불합리. 구조 자체를 개선해야 할듯. def OnUseSkill(self, slotIndex, coolTime): skillIndex = player.GetSkillIndex(slotIndex) skillType = skill.GetSkillType(skillIndex) ## ACTIVE if skill.SKILL_TYPE_ACTIVE == skillType: skillGrade = player.GetSkillGrade(slotIndex) slotIndex = self.__GetRealSkillSlot(skillGrade, slotIndex) ## ETC else: slotIndex = self.__GetETCSkillRealSlotIndex(slotIndex) for slotWindow in self.skillPageDict.values(): if slotWindow.HasSlot(slotIndex): slotWindow.SetSlotCoolTime(slotIndex, coolTime) return # def OnActivateSkill(self, slotIndex): # skillGrade = player.GetSkillGrade(slotIndex) # slotIndex = self.__GetRealSkillSlot(skillGrade, slotIndex) # for slotWindow in self.skillPageDict.values(): # if slotWindow.HasSlot(slotIndex): # slotWindow.ActivateSlot(slotIndex) # return # def OnDeactivateSkill(self, slotIndex): # skillGrade = player.GetSkillGrade(slotIndex) # slotIndex = self.__GetRealSkillSlot(skillGrade, slotIndex) # for slotWindow in self.skillPageDict.values(): # if slotWindow.HasSlot(slotIndex): # slotWindow.DeactivateSlot(slotIndex) # return def OnActivateSkill(self, slotIndex): skillGrade = player.GetSkillGrade(slotIndex) slotIndex = self.__GetRealSkillSlot(skillGrade, slotIndex) for slotWindow in self.skillPageDict.values(): if slotWindow.HasSlot(slotIndex): if app.ENABLE_ACCE_SYSTEM: slotWindow.ActivateSlotOld(slotIndex) else: slotWindow.ActivateSlot(slotIndex) return def OnDeactivateSkill(self, slotIndex): skillGrade = player.GetSkillGrade(slotIndex) slotIndex = self.__GetRealSkillSlot(skillGrade, slotIndex) for slotWindow in self.skillPageDict.values(): if slotWindow.HasSlot(slotIndex): if app.ENABLE_ACCE_SYSTEM: slotWindow.DeactivateSlotOld(slotIndex) else: slotWindow.DeactivateSlot(slotIndex) return def __ShowJobToolTip(self): self.toolTipJob.ShowToolTip() def __HideJobToolTip(self): self.toolTipJob.HideToolTip() def __SetJobText(self, mainJob, subJob): if player.GetStatus(player.LEVEL)<5: subJob=0 if 949 == app.GetDefaultCodePage(): self.toolTipJob.ClearToolTip() try: jobInfoTitle=localeInfo.JOBINFO_TITLE[mainJob][subJob] jobInfoData=localeInfo.JOBINFO_DATA_LIST[mainJob][subJob] except IndexError: print "uiCharacter.CharacterWindow.__SetJobText(mainJob=%d, subJob=%d)" % (mainJob, subJob) return self.toolTipJob.AutoAppendTextLine(jobInfoTitle) self.toolTipJob.AppendSpace(5) for jobInfoDataLine in jobInfoData: self.toolTipJob.AutoAppendTextLine(jobInfoDataLine) self.toolTipJob.AlignHorizonalCenter() def __ShowAlignmentToolTip(self): self.toolTipAlignment.ShowToolTip() def __HideAlignmentToolTip(self): self.toolTipAlignment.HideToolTip() def RefreshCharacter(self): if self.isLoaded==0: return ## Name try: characterName = player.GetName() guildName = player.GetGuildName() self.characterNameValue.SetText(characterName) self.guildNameValue.SetText(guildName) if not guildName: if localeInfo.IsARABIC(): self.characterNameSlot.SetPosition(190, 34) else: self.characterNameSlot.SetPosition(109, 34) self.guildNameSlot.Hide() else: if localeInfo.IsJAPAN(): self.characterNameSlot.SetPosition(143, 34) else: self.characterNameSlot.SetPosition(153, 34) self.guildNameSlot.Show() except: import exception exception.Abort("CharacterWindow.RefreshCharacter.BindObject") race = net.GetMainActorRace() group = net.GetMainActorSkillGroup() empire = net.GetMainActorEmpire() ## Job Text job = chr.RaceToJob(race) self.__SetJobText(job, group) ## FaceImage try: faceImageName = FACE_IMAGE_DICT[race] try: self.faceImage.LoadImage(faceImageName) except: print "CharacterWindow.RefreshCharacter(race=%d, faceImageName=%s)" % (race, faceImageName) self.faceImage.Hide() except KeyError: self.faceImage.Hide() ## GroupName self.__SetSkillGroupName(race, group) ## Skill if 0 == group: self.__SelectSkillGroup(0) else: self.__SetSkillSlotData(race, group, empire) if self.__CanUseHorseSkill(): self.__SelectSkillGroup(0) def __SetSkillGroupName(self, race, group): job = chr.RaceToJob(race) if not self.SKILL_GROUP_NAME_DICT.has_key(job): return nameList = self.SKILL_GROUP_NAME_DICT[job] if 0 == group: self.skillGroupButton1.SetText(nameList[1]) self.skillGroupButton2.SetText(nameList[2]) self.skillGroupButton1.Show() self.skillGroupButton2.Show() self.activeSkillGroupName.Hide() else: if self.__CanUseHorseSkill(): self.activeSkillGroupName.Hide() self.skillGroupButton1.SetText(nameList.get(group, "Noname")) self.skillGroupButton2.SetText(localeInfo.SKILL_GROUP_HORSE) self.skillGroupButton1.Show() self.skillGroupButton2.Show() else: self.activeSkillGroupName.SetText(nameList.get(group, "Noname")) self.activeSkillGroupName.Show() self.skillGroupButton1.Hide() self.skillGroupButton2.Hide() def __SetSkillSlotData(self, race, group, empire=0): ## SkillIndex playerSettingModule.RegisterSkill(race, group, empire) ## Event self.__SetSkillSlotEvent() ## Refresh self.RefreshSkill() def __SelectSkillGroup(self, index): for btn in self.skillGroupButton: btn.SetUp() self.skillGroupButton[index].Down() if self.__CanUseHorseSkill(): if 0 == index: index = net.GetMainActorSkillGroup()-1 elif 1 == index: index = self.PAGE_HORSE self.curSelectedSkillGroup = index self.__SetSkillSlotData(net.GetMainActorRace(), index+1, net.GetMainActorEmpire()) def __CanUseSkillNow(self): if 0 == net.GetMainActorSkillGroup(): return False return True def __CanUseHorseSkill(self): slotIndex = player.GetSkillSlotIndex(player.SKILL_INDEX_RIDING) if not slotIndex: return False grade = player.GetSkillGrade(slotIndex) level = player.GetSkillLevel(slotIndex) if level < 0: level *= -1 if grade >= 1 and level >= 1: return True return False def __IsChangedHorseRidingSkillLevel(self): ret = False if -1 == self.canUseHorseSkill: self.canUseHorseSkill = self.__CanUseHorseSkill() if self.canUseHorseSkill != self.__CanUseHorseSkill(): ret = True self.canUseHorseSkill = self.__CanUseHorseSkill() return ret def __GetRealSkillSlot(self, skillGrade, skillSlot): return skillSlot + min(skill.SKILL_GRADE_COUNT-1, skillGrade)*skill.SKILL_GRADE_STEP_COUNT def __GetETCSkillRealSlotIndex(self, skillSlot): if skillSlot > 100: return skillSlot return skillSlot % self.ACTIVE_PAGE_SLOT_COUNT def __RealSkillSlotToSourceSlot(self, realSkillSlot): if realSkillSlot > 100: return realSkillSlot if self.PAGE_HORSE == self.curSelectedSkillGroup: return realSkillSlot + self.ACTIVE_PAGE_SLOT_COUNT return realSkillSlot % skill.SKILL_GRADE_STEP_COUNT def __GetSkillGradeFromSlot(self, skillSlot): return int(skillSlot / skill.SKILL_GRADE_STEP_COUNT) def SelectSkillGroup(self, index): self.__SelectSkillGroup(index) def OnQuestScroll(self): questCount = quest.GetQuestCount() scrollLineCount = max(0, questCount - quest.QUEST_MAX_NUM) startIndex = int(scrollLineCount * self.questScrollBar.GetPos()) if startIndex != self.questShowingStartIndex: self.questShowingStartIndex = startIndex self.RefreshQuest()
[ "contact@asikoo.xyz" ]
contact@asikoo.xyz
7c453cb16c9b52badd781c88433bb42e7ce571d3
b2c44782b33a063bdb5066e92a924b596e5215d8
/botModule/botMSG.py
dfc5491dc8f9f69ef4cc80dca2c8402c191b153d
[ "Apache-2.0" ]
permissive
KL35Ronaldo/MegaUploaderbot
1e414ea93d2d5e801ac25eceaefd2fcf535b3577
ddd58980ee568f696d226b52750778ca138416e3
refs/heads/master
2023-09-02T17:19:52.795920
2021-11-19T16:41:56
2021-11-19T16:41:56
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,082
py
#!/usr/bin/env python3 # Bot defined Messages class BotMessage(object): '''Some permanent Variables defined''' common_text = "\n\n<b><u>If you are facing any problem😫, so report📝 at @AJPyroVerseGroup</u></b>" to_login = "<b>If you are not logged in then, send login detail in this format email,password.</b>\n" start_msg = f"<b>Hi, I am MegaUploaderBot🤖 Created by @AJPyroVerse and My Developer🧑‍💻 is @AJTimePyro.</b>\n\nAnd I support:-\n1. <u>Direct Downloading Link</u>\n2.<u>Telegram File</u>\n3. <u>Youtube URL</u>\n\n\n{to_login}\n😊We will store your login detail on our database.{common_text}" help_msg = f"{to_login}\n<b>After login😊 send Direct Downloading Link, Youtube URL or any Telegram File.\n\nTo remove your account from Database use /revoke.</b>{common_text}" userBanned = f"<b>You are Banned🚫 from AJPyroVerse Community.</b>" trying_to_login = "<code>I am trying to login your account.\nSo Please Wait...</code>" logged_in = "<b>Congratulations🥳🥳</b>, <i>Your account is successfully logged in😊.</i>" invalid_login = f"<b>Please provide a 😒valid login detail.</b>{common_text}" revoke_failed = f"<b><u>You are not even logged in😒. So how can I remove your account.</u></b>{common_text}" logged_out = "Your account is now logged out🥺.\nTo Login again send your login detail." already_login = "<b>Your account is already login🤪.</b>" not_joined_community = f'<b>To use this bot, you need to Join our channel and Group😁🤪.</b>{common_text}' not_loggin = f"<i>Your account is not logged in😒, so I am unable to upload file.</i>{common_text}" login_detail_changed = f"Seems like your <b>login detail is changed.</b> /revoke this account, and add new login detail.{common_text}" file_limit = f"I can't Upload file that are larger than 2000MB.{common_text}" starting_to_download = "<code>Starting to Download🚀 the file on server.... Have Some Patience!!!</code>" downloadingAudio = "<b>Now Downloading Audio🔉 File.</b>" merging = "<b>Merging Audio🔉 and Video🎥, This can take a while...</b>" unsuccessful_upload = f"Uploading went <b>unsuccessful</b>🥺, maybe url has problem.{common_text}" uploading_msg = '<b>File successfully downloaded to server, 😊Now uploading to Drive.</b>' successful_uploaded = "<b>Your file is successfully uploaded🥳🥳🥳.</b>" uploading_unsuccessful = f'Uploading went <b>unsuccessful</b>🥺, Something Went Wrong{common_text}' broadcast_failed = "<b>Broadcasting Message can't be empty😒</b>" choose_quality = '<b>Choose Which 🎥Video Quality you want to Upload.\n\nIt will automatically Deleted after 1 minute⏲️; If not selected any.</b>' all_above_limit = 'Sorry🥲, No Quality Found Under Limit' processing_url = '<code>Please wait⏳ while I am Processing Url</code>' processing_file = '<cpde>Please wait⏳ while I am Processing File</code>' ytVideoUnavailable = '<b>Youtube Video is unavailable😒.<b>'
[ "ajtimepyro@gmail.com" ]
ajtimepyro@gmail.com
27307f6f651010200bc164de7e8875e96c5b5af9
dd60231fa2d99a5100a800f43cb9cd93652fa63d
/lib/dknn_attack_l2.py
0f66da7bebf4798cc5cefb682f49eadc3b9732ce
[ "MIT" ]
permissive
XiaodanLi001/knn-defense
77150f40a9c20a500246d6c0aae91e2583b9fd40
7b390303a4fcfc26b627216649c75ca0f924f827
refs/heads/master
2020-07-31T22:52:52.567319
2019-09-23T21:23:30
2019-09-23T21:23:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
12,565
py
'''Implement gradient-based attack on DkNN''' import logging import numpy as np import torch import torch.nn.functional as F import torch.optim as optim INFTY = 1e10 class DKNNL2Attack(object): """ Implement gradient-based attack on Deep k-Nearest Neigbhor that uses L-2 distance as a metric """ def __call__(self, dknn, x_orig, label, guide_layer='relu1', m=100, binary_search_steps=5, max_iterations=500, learning_rate=1e-2, initial_const=1, abort_early=True, max_linf=None, random_start=False, guide_mode=1): """ Parameters ---------- dknn : DKNN object DkNN (defined in lin/dknn.py) that we want to attack x_orig : torch.tensor tensor of the original samples to attack. Does not need to require gradients, shape is (num_samples, ) + input_shape label : torch.tensor tensor of the label corresponding to x_orig guide_layer : str. optional layer name in which we want to find guide samples. Default is 'relu1' m : int, optional number of guide samples. Default is 100 binary_search_step : int, optional number of steps for binary search on the norm penalty constant. Default is 5 max_iterations : int, optional number of optimization steps (per one binary search). Default is 500 learning_rate : float , optional step size or learning rate for the optimizer. Default is 1e-2 initial_const : float, optional a number the norm penalty constant should be initialized to. Default is 1 abort_early : bool, optional whether or not to abort the optimization early (before reaching max_iterations) if the objective does not improve from the past (max_iterations // 10) steps. Default is True max_linf : float, optional use to bound the L-inf norm of the attacks (addition to L-2 norm penalty). Set to None to not use this option. Default is None random_start : bool, optional whether or not to initialize the perturbation with small isotropic Gaussian noise. Default is False guide_mode : int, optional Choose the guide_mode to use between 1 and 2. Default is 1 - guide_mode == 1: find m nearest neighbors to input that all have the same class but not equal its original label. - guide_mode == 2: find the nearest neighbor that has a different class from the input and find its m - 1 neighbors Returns ------- x_adv : torch.tensor adversarial examples found. If adversarial examples for some inputs are not found, return those inputs. """ min_, max_ = x_orig.min(), x_orig.max() if max_linf is not None: min_ = torch.max(x_orig - max_linf, min_) max_ = torch.min(x_orig + max_linf, max_) batch_size = x_orig.size(0) x_adv = x_orig.clone() label = label.cpu().numpy() input_shape = x_orig.detach().cpu().numpy().shape device = dknn.device def to_attack_space(x): # map from [min_, max_] to [-1, +1] a = (min_ + max_) / 2 b = (max_ - min_) / 2 x = (x - a) / b # from [-1, +1] to approx. (-1, +1) x = x * 0.999999 # from (-1, +1) to (-inf, +inf) return self.atanh(x) def to_model_space(x): """Transforms an input from the attack space to the model space. This transformation and the returned gradient are elementwise.""" # from (-inf, +inf) to (-1, +1) x = torch.tanh(x) # map from (-1, +1) to (min_, max_) a = (min_ + max_) / 2 b = (max_ - min_) / 2 x = x * b + a return x # variables representing inputs in attack space will be prefixed with z z_orig = to_attack_space(x_orig) x_recon = to_model_space(z_orig) # declare tensors that keep track of constants and binary search const = torch.zeros((batch_size, ), device=device) const += initial_const lower_bound = torch.zeros_like(const) upper_bound = torch.zeros_like(const) + INFTY best_l2dist = torch.zeros_like(const) + INFTY with torch.no_grad(): # choose guide samples and get their representations if guide_mode == 1: x_guide = self.find_guide_samples( dknn, x_orig, label, k=m, layer=guide_layer) elif guide_mode == 2: x_guide = self.find_guide_samples_v2( dknn, x_orig, label, k=m, layer=guide_layer) else: raise ValueError("Invalid guide_mode (choose between 1 and 2)") guide_reps = {} for i in range(batch_size): guide_rep = dknn.get_activations( x_guide[i], requires_grad=False) for layer in dknn.layers: if i == 0: # set a zero tensor before filling it size = (batch_size, ) + \ guide_rep[layer].view(m, -1).size() guide_reps[layer] = torch.zeros(size, device=device) guide_reps[layer][i] = guide_rep[layer].view( m, -1).detach() for binary_search_step in range(binary_search_steps): if (binary_search_step == binary_search_steps - 1 and binary_search_steps >= 10): # in the last binary search step, use the upper_bound instead # to ensure that unsuccessful attacks use the largest # possible constant const = upper_bound if not random_start: z_delta = torch.zeros_like(z_orig, requires_grad=True) else: rand = np.random.randn(*input_shape) * 1e-2 z_delta = torch.tensor( rand, dtype=torch.float32, requires_grad=True, device=device) loss_at_previous_check = torch.zeros(1, device=device) + INFTY # create a new optimizer optimizer = optim.Adam([z_delta], lr=learning_rate) # optimizer = optim.SGD([z_delta], lr=learning_rate) for iteration in range(max_iterations): optimizer.zero_grad() x = to_model_space(z_orig + z_delta) reps = dknn.get_activations(x, requires_grad=True) loss, l2dist = self.loss_function( x, reps, guide_reps, dknn.layers, const, x_recon, device) loss.backward() optimizer.step() if iteration % (np.ceil(max_iterations / 10)) == 0: print(' step: %d; loss: %.3f; l2dist: %.3f' % (iteration, loss.cpu().detach().numpy(), l2dist.mean().cpu().detach().numpy())) # DEBUG: # for i in range(5): # print(z_delta.grad[i].view(-1).norm().item()) if abort_early and iteration % (np.ceil(max_iterations / 10)) == 0: # after each tenth of the iterations, check progress if torch.gt(loss, .9999 * loss_at_previous_check): break # stop Adam if there has not been progress loss_at_previous_check = loss # check how many attacks have succeeded with torch.no_grad(): is_adv = self.check_adv(dknn, x, label) print(is_adv.sum()) for i in range(batch_size): # set new upper and lower bounds if is_adv[i]: upper_bound[i] = const[i] else: lower_bound[i] = const[i] # set new const if upper_bound[i] == INFTY: # exponential search if adv has not been found const[i] *= 10 else: # binary search if adv has been found const[i] = (lower_bound[i] + upper_bound[i]) / 2 # only keep adv with smallest l2dist if is_adv[i] and best_l2dist[i] > l2dist[i]: x_adv[i] = x[i] best_l2dist[i] = l2dist[i] # check the current attack success rate (combined with previous # binary search steps) with torch.no_grad(): is_adv = self.check_adv(dknn, x_adv, label) print('binary step: %d; number of successful adv: %d/%d' % (binary_search_step, is_adv.sum(), batch_size)) return x_adv @classmethod def check_adv(cls, dknn, x, label): """Check if label of <x> predicted by <dknn> matches with <label>""" y_pred = dknn.classify(x).argmax(1) return torch.tensor((y_pred != label).astype(np.float32)).to(dknn.device) @classmethod def loss_function(cls, x, reps, guide_reps, layers, const, x_recon, device): """Returns the loss averaged over the batch (first dimension of x) and L-2 norm squared of the perturbation """ batch_size = x.size(0) adv_loss = torch.zeros((batch_size, len(layers)), device=device) # find squared L-2 distance between original samples and their # adversarial examples at each layer for l, layer in enumerate(layers): rep = reps[layer].view(batch_size, 1, -1) adv_loss[:, l] = ((rep - guide_reps[layer])**2).sum((1, 2)) # find L-2 norm squared of perturbation l2dist = torch.norm((x - x_recon).view(batch_size, -1), dim=1)**2 # total_loss is sum of squared perturbation norm and squared distance # of representations, multiplied by constant total_loss = l2dist + const * adv_loss.mean(1) return total_loss.mean(), l2dist.sqrt() @staticmethod def find_guide_samples(dknn, x, label, k=100, layer='relu1'): """Find k nearest neighbors to <x> that all have the same class but not equal to <label> """ num_classes = dknn.num_classes nn = torch.zeros((k, ) + x.size()).transpose(0, 1) D, I = dknn.get_neighbors( x, k=dknn.x_train.size(0), layers=[layer])[0] for i, (d, ind) in enumerate(zip(D, I)): mean_dist = np.zeros((num_classes, )) for j in range(num_classes): mean_dist[j] = np.mean( d[np.where(dknn.y_train[ind] == j)[0]][:k]) mean_dist[label[i]] += INFTY nearest_label = mean_dist.argmin() nn_ind = np.where(dknn.y_train[ind] == nearest_label)[0][:k] nn[i] = dknn.x_train[ind[nn_ind]] return nn @classmethod def find_guide_samples_v2(cls, dknn, x, label, k=100, layer='relu1'): """Find the nearest neighbor to <x> that has a different label from <label>. Then find other <k> - 1 training samples that are closest to the neighbor and has the same class """ # find nearest sample with different class nn = dknn.find_nn_diff_class(x, label) # now find k neighbors that has the same class as x_nn x_nn = cls.find_nn_same_class(dknn, nn, k=k, layer=layer) return x_nn @staticmethod def find_nn_same_class(dknn, ind_x, k=100, layer='relu1'): """Find <k> training samples with the same class as and closest to the training sample with index <ind_x> in representation space at <layer> """ batch_size = ind_x.shape[0] label = dknn.y_train[ind_x] x_nn = torch.zeros((batch_size, k) + dknn.x_train[0].size()) _, I = dknn.get_neighbors( dknn.x_train[ind_x], k=dknn.x_train.size(0), layers=[layer])[0] for i, ind in enumerate(I): nn_ind = np.where(dknn.y_train[ind] == label[i])[0][:k] x_nn[i] = dknn.x_train[ind[nn_ind]] return x_nn @staticmethod def atanh(x): return 0.5 * torch.log((1 + x) / (1 - x)) @staticmethod def sigmoid(x, a=1): return 1 / (1 + torch.exp(-a * x))
[ "chawins@berkeley.edu" ]
chawins@berkeley.edu
eeb6395192dadc4713b52cf52005245c92361ded
a538c645b60c4081c693cfb58db8e574ac334011
/d000_analysis/dual_optimization.py
77f22dad72d7a3082701946d1623b0f9cad90510
[]
no_license
pdijksta/analysis_scripts
b5235550143c88354a922e6b01124acf911fbd0c
f84211304357b678ee1d9995a6adf9c4a18d7b61
refs/heads/master
2021-01-11T00:05:36.273740
2016-10-12T07:29:05
2016-10-12T07:29:05
70,569,640
0
0
null
null
null
null
UTF-8
Python
false
false
3,261
py
# Interpolate data for dual optim import numpy as np import matplotlib.pyplot as plt from pyecloud_device import pyecloud_device # Function for device def main(hl_pyecloud, device_list, coast_strs, scenarios_labels_dict, length, dict_keys, arcs, hl_measured, sey_list, args_l, verbose=False): pyecloud_device_easy = lambda device, coast_str: pyecloud_device(device, coast_str, device_list, coast_strs, hl_pyecloud) dip_begin = 1.10 dip_end = 1.51 step = 0.005 dip_sey_list = np.arange(dip_begin,dip_end+.1*step,step) dip_data = (pyecloud_device_easy('ArcDipReal', '0.5') + pyecloud_device_easy('ArcDipReal','1.0'))/2 * length['ArcDipReal'] quad_data = (pyecloud_device_easy('ArcQuadReal','0.5') + pyecloud_device_easy('ArcQuadReal','1.0'))/2 * length['ArcQuadReal'] data = np.zeros(shape=(len(dict_keys),len(arcs),len(dip_sey_list),2)) for key_ctr in xrange(len(dict_keys)): for arc_ctr in xrange(len(arcs)): measured = hl_measured[key_ctr,arc_ctr] for dip_ctr, dip_sey in enumerate(dip_sey_list): dip_hl = np.interp(dip_sey,sey_list,dip_data[key_ctr,:]) quad_hl_list = quad_data[key_ctr,:] data[key_ctr,arc_ctr,dip_ctr,0] = dip_sey if dip_hl + np.min(quad_hl_list) > measured or dip_hl + np.max(quad_hl_list) < measured: if verbose: print('continue for %.2f' % dip_sey) continue quad_hl = measured - dip_hl data[key_ctr,arc_ctr,dip_ctr,1] = np.interp(quad_hl,quad_data[key_ctr,:],sey_list) fig_ctr = 0 for arc_ctr, arc in enumerate(arcs): if arc_ctr%4 == 0: fig = plt.figure() fig_ctr += 1 title_str = 'Valid pairs of dip and quad SEY %i. Average of two coasting intensities.' % fig_ctr plt.suptitle(title_str,fontsize=25) fig.canvas.set_window_title(title_str) sp = plt.subplot(2,2,arc_ctr%4+1) # pyecloud data, measured only for labels/title for key_ctr, key in enumerate(dict_keys): hl = hl_measured[key_ctr,arc_ctr] label = scenarios_labels_dict[key] possible_xdata = data[key_ctr,arc_ctr,:,0] possible_ydata = data[key_ctr,arc_ctr,:,1] xdata, ydata = [], [] for ctr, yy in enumerate(possible_ydata): if yy != 0: xdata.append(possible_xdata[ctr]) ydata.append(yy) plt.plot(xdata, ydata, label=label) # Add diagonal lines xlim = (dip_begin,1.45) ylim = (1.1,1.51) diag_left = max(ylim[0], xlim[0]) diag_right = min(ylim[1], xlim[1]) sp.plot([diag_left, diag_right], [diag_left,diag_right], '--', color='black', label='diagonal') sp.set_title('Arc %s' % arc, fontsize=20) sp.set_xlabel('Dipole SEY') sp.set_ylabel('Quad SEY') sp.set_xlim(xlim) sp.set_ylim(ylim) # Add vertical line for Quad SEY if args_l is not None: sp.axhline(args_l, label='Average Q06', ls='--', color='orange') if arc_ctr % 4 == 3: sp.legend(bbox_to_anchor=(1.1, 1))
[ "philipp.dijkstal@cern.ch" ]
philipp.dijkstal@cern.ch
51734a0ca45afb045f0dea8304646a3fa66521c4
34d75743328defe85bb7e1a830fc20a0c667ed69
/Drank/D067.py
b1ebcc15e08e752c505ec9e11a6c9f3d6fc55f1e
[]
no_license
koyamaj/paiza_work
dc4cc5ac1793002ba41225690ece3ab34d872df2
2784d12777ed31a368f787bbc18d36e92c57b294
refs/heads/master
2020-03-17T16:23:36.705228
2018-05-23T02:59:30
2018-05-23T02:59:30
133,746,991
0
0
null
null
null
null
UTF-8
Python
false
false
65
py
n = int(input()) if n%2 == 0: print('OFF') else: print('ON')
[ "koyamaj818@gmail.com" ]
koyamaj818@gmail.com
4aaa6dcc305713880e0f29421a5d64406e92129d
fd2d467fa1d2d3e051a9bf2218db04e59310cef4
/src/process_log.py
3c4b4af2760d0045d2094653e576e3aebcbcfe7c
[]
no_license
MahinM/fansite-analytics-challenge
aa3c063224ab954ac28ec5867d5b88a3090d9353
d5ebbbb8168ac9982ba72d12892ba5864395f3da
refs/heads/master
2021-01-19T04:38:42.047623
2017-04-06T03:48:03
2017-04-06T03:48:03
87,384,024
0
0
null
null
null
null
UTF-8
Python
false
false
2,938
py
import parse_file import argparse def output_results(output_file, results): """Writes results to file""" with open(output_file,'w') as f: for line in results: print(line, file=f) def top_n(result_dict, n): """Returns a list of the top n entries in a dictionary based on the sorted values in the dictionary - or all of the sorted entries if n is < the length of the dictionary""" return sorted(result_dict.items(), key=lambda x: x[1], reverse = True)[:n] def feature1(result_dict, output_file): """Process input_file and write output to output_file for top 10 hosts""" top_hosts = top_n(result_dict,10) result = [str(item[0] + ',' + str(item[1])) for item in top_hosts] output_results(output_file, result) def feature2(result_dict, output_file): """Process input_file and write output to output_file for top 10 resources requested""" top_resources = top_n(result_dict,10) result = [resource[0].split(' ')[1] for resource in top_resources] output_results(output_file, result) def feature3(result_dict, output_file, time_format): """Process input_file and write output to output_file for top 10 hours of activity""" top_times = top_n(result_dict,10) result = [item[0].strftime(time_format) + ',' + str(item[1]) for item in top_times] output_results(output_file, result) def feature4(input_file, output_file): """Process input_file and write output to output_file for requests that would be blocked based on activity levels over threshold""" blocked_log = parse_file.failed_attempts(input_file) result = [item.strip() for item in blocked_log] output_results(output_file, result) def feature3_nonoverlapping(input_file, output_file,time_format): """Process input_file and write output to output_file for top 10 hours of activity""" timestamps = parse_file.feature3_non_overlapping(input_file) hours = parse_file.group_timestamps(timestamps) sorted_hours = sorted(hours, key=lambda x: x[1], reverse = True)[:10] result = [item[0].strftime(time_format) + ',' + str(item[1]) for item in sorted_hours] output_results(output_file, result) def main(): parser = argparse.ArgumentParser() parser.add_argument("input_file", help="path to log input file") parser.add_argument("host_output", help="feature 1: path to host output file") parser.add_argument("resources_output", help="feature 2: path to resources output file") parser.add_argument("hours_output", help="feature 3: path to hours output file") parser.add_argument("blocked_output", help="feature 4: path to blocked output file") args = parser.parse_args() time_format = "%d/%b/%Y:%H:%M:%S -0400" host_dict, resource_dict, time_totals_dict = parse_file.log_summary(args.input_file) feature1(host_dict,args.host_output) feature2(resource_dict,args.resources_output) feature3(time_totals_dict,args.hours_output,time_format) feature4(args.input_file, args.blocked_output) if __name__ == "__main__": main()
[ "MahinManley@gmail.com" ]
MahinManley@gmail.com
5af66268499d70e87325b63780fe51d69b3edb8e
ea3440abd4a8cb4b55dcff2cfba9b29f13a62958
/yuding/views.py
41be3e06ca383219cb74e0c336b023c3f655fd1d
[]
no_license
24python/CRBM
223a969f13d006a25423d82dbf255fb73ce7d0f5
80bee0f010fa03493d378401c47aaa2b4dc79c91
refs/heads/master
2020-03-15T17:16:47.281543
2018-05-05T14:55:56
2018-05-05T14:55:56
132,255,804
0
1
null
null
null
null
UTF-8
Python
false
false
8,388
py
from django.forms import Form from django.forms import fields from django.forms import widgets from django.http.response import JsonResponse from django.shortcuts import render, redirect from yuding import models # Create your views here. import datetime import json # def index(request): # #查看所有会议室的名称 # metting_list = models.ReserveRecord.time1 # print("4444444",metting_list) # room_obj = models.MeetingRoom.objects.all() # # return render(request,"index.html",{"metting_list":metting_list,"room_obj":room_obj}) # form组件生成login界面 class LoginForm(Form): username = fields.CharField( max_length=8, required=True, error_messages={ "max_length": "用户名长度不能大于8位", "required": "用户名不能为空", }, # label="用户名", # label_suffix=":", widget=widgets.TextInput(attrs={"class": "form-control", "placeholder": "username", "id": "username"}) ) password = fields.CharField( max_length=8, min_length=3, required=True, error_messages={ "max_length": "密码长度不能大于8位", "min_length": "密码长度不能小于3位", "required": "密码不能为空", }, # label="密码", # label_suffix=":", widget=widgets.PasswordInput(attrs={"class": "form-control", "placeholder": "password", "id": "password"})) def login(request): if request.method == "GET": form = LoginForm() return render(request, "login.html", {"form": form}) else: form = LoginForm(data=request.POST) if form.is_valid(): user = models.UserInfo.objects.filter(**form.cleaned_data).first() if user: request.session["userinfo"] = {"id": user.id, "name": user.username} return redirect("/index/") else: form.add_error('password', '密码错误') return render(request, "login.html", {"form": form}) return render(request, "login.html", {"form": form}) def index(request): metting_list = models.ReserveRecord.time1 return render(request, "index.html", {"metting_list": metting_list}) def recording(request): response = {"status": True, "msg": None, "data": None} if request.method == "GET": current_data = datetime.datetime.now().date() # 日期类型 # =======================获取指定日期所有的预定信息========================= try: ajax_date = request.GET.get("date") # 字符串类型 # print(ajax_date,"============") ajax_date = datetime.datetime.strptime(ajax_date, '%Y-%m-%d').date() # print("date....",ajax_date) if ajax_date < current_data: raise Exception("查询时间不能是以前的时间") recording_list = models.ReserveRecord.objects.filter(data=ajax_date) # 查询的这一天的所有的记录 # print(recording_list,"recording_list") # [OBJ(1,room_id,user_id.time_id.data),OBJ(2,room_id,user_id.time_id.data)] # 吧这样的数据处理成字典的形式,提升查询速度 # { # 1:{ #room_id # 2:{"username":2,"user_id":3} #2表示time_id # } # } recrding_dict = {} for i in recording_list: if i.room_id not in recrding_dict: recrding_dict[i.room_id] = {i.timeline: {"username": i.user.username, "user_id": i.user_id}} else: # recrding_dict[i.room_id][i.timeline] = {i.timeline:{"username":i.user.username,"user_id":i.user_id}} recrding_dict[i.room_id][i.timeline] = {"username": i.user.username, "user_id": i.user_id} print('--------', recrding_dict) # 获取所有的会议室信息 room_list = models.MeetingRoom.objects.all() # ===========================生成会议室信息======================== data = [] for room in room_list: print(room) tr = [] tr.append({"text": room.name, "attrs": {}}) for tm in models.ReserveRecord.time1: td = {"text": "", "attrs": {"room_id": room.id, "time_id": tm[0]}} if room.id in recrding_dict and tm[0] in recrding_dict[room.id]: # 已预订,不确定是谁预定的,还得判断一下 td['attrs']['class'] = "chosen" if recrding_dict[room.id][tm[0]]['user_id'] == request.session["userinfo"]["id"]: # 如果是自己预定 td['text'] = '预定成功' else: # 如果是别人预定,加一个disabled属性不可编辑,只有自己的能编辑 td['text'] = recrding_dict[room.id][tm[0]]['username'] td['attrs']['disable'] = True tr.append(td) data.append(tr) print('-==========', data) response["data"] = data except Exception as e: response["status"] = True response["msg"] = str(e) else: try: current_date = datetime.datetime.now().date() ajax_date = request.POST.get("date") ajax_date = datetime.datetime.strptime(ajax_date, '%Y-%m-%d').date() if ajax_date < current_date: raise Exception("查询时间不是当前的时间") post_data = json.loads(request.POST.get("data")) # 由于发过来的数据是字符串,所以要转一下才能是字典 print(post_data) # {'ADD': {'1': ['5', '4'], '2': ['4', '7']}, 'DEL': {'2': ['4']}}} date = request.POST.get("date") # 获取日期 # print(date) #2017-12-12 # 拿到数据以后 # 如果time_id在ADD里面有,在Del里面也有值,就删除了,因为数据库里面已经有值了。就直接把add里的和del里的删除就行了 for room_id, time_list in post_data["DEL"].items(): if room_id not in post_data["ADD"]: continue else: for time_id in list(time_list): if time_id in post_data["ADD"][room_id]: post_data["ADD"][room_id].remove(time_id) post_data["DEL"][room_id].remove(time_id) # print(post_data) # 新增数据 reserverecord_obj_list = [] for room_id, time_list in post_data["ADD"].items(): for time_id in time_list: # models.ReserveRecord.objects.create(room_id=room_id,time_id=time_id,date=date,user=request.session["userinfo"]["id"]) obj = models.ReserveRecord(room_id=room_id, timeline=time_id, data=date, user_id=request.session["userinfo"]["id"]) reserverecord_obj_list.append(obj) models.ReserveRecord.objects.bulk_create(reserverecord_obj_list) # 删除会议室预定信息 from django.db.models import Q remove_reserverecord = Q() for room_id, time_list in post_data["DEL"].items(): for time_id in time_list: temp = Q() temp.connector = "AND" temp.children.append(("user_id", request.session["userinfo"]["id"])) temp.children.append(("data", date)) temp.children.append(("room_id", room_id)) temp.children.append(("timeline", time_id)) remove_reserverecord.add(temp, "OR") if remove_reserverecord: print(models.ReserveRecord.objects.filter(remove_reserverecord)) models.ReserveRecord.objects.filter(remove_reserverecord).delete() # print(remove_reserverecord,"remove_reserverecord") except Exception as e: response["status"] = False response["msg"] = str(e) return JsonResponse(response)
[ "2414546214@qq.com" ]
2414546214@qq.com
2dbbe020be56a543dbaf3151406ae8c0cbf7fd5d
eb4581ac57524ac4a6f330e0963f09279ead3f24
/scraping/admin.py
52a5f26d80700752ecaa4777ac356acf04f24404
[]
no_license
GenesisBlock3301/scraper-gui-django
8c86975d01c5fa49ba01e0cf5691ad7e45fe42e2
238507ae625c201dcceb2ad188c3561aa5ff8d30
refs/heads/main
2023-01-24T04:02:03.832672
2020-11-24T18:30:51
2020-11-24T18:30:51
null
0
0
null
null
null
null
UTF-8
Python
false
false
225
py
from django.contrib import admin # Register your models here. from .models import * admin.site.register(Trust) admin.site.register(Facebook) admin.site.register(GOOGLE) admin.site.register(FeeFO) admin.site.register(Youtube)
[ "nur15-1463@diu.edu.bd" ]
nur15-1463@diu.edu.bd
bca42b05540c228d04735a0d6bc347d81e892fc6
92be2d8c4a64d5f8c43341be7f1e36b81fce56ab
/scripts/release/homebrew/docker/formula_generate.py
d44094ad0524ab437e79a6a20bdf6a9ce56e7124
[ "MIT", "BSD-3-Clause", "LGPL-2.0-or-later", "GPL-1.0-or-later", "MPL-2.0", "LGPL-2.1-only", "Apache-2.0", "LGPL-2.1-or-later", "BSD-2-Clause" ]
permissive
allanpedroni/azure-cli
b31d3347f377208b502231266d4839196e574c4b
4e21baa4ff126ada2bc232dff74d6027fd1323be
refs/heads/dev
2023-08-31T18:27:03.240944
2023-08-31T08:49:58
2023-08-31T08:49:58
204,767,533
0
0
MIT
2023-09-14T13:32:41
2019-08-27T18:41:15
Python
UTF-8
Python
false
false
7,645
py
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- import os import sys import re from typing import List, Tuple import requests import jinja2 from poet.poet import make_graph, RESOURCE_TEMPLATE from collections import OrderedDict import bisect import argparse TEMPLATE_FILE_NAME='formula_template.txt' CLI_VERSION=os.environ['CLI_VERSION'] HOMEBREW_UPSTREAM_URL=os.environ['HOMEBREW_UPSTREAM_URL'] HOMEBREW_FORMULAR_LATEST="https://raw.githubusercontent.com/Homebrew/homebrew-core/c882489d4cb39ca004387f0c5ef1a767046c68d6/Formula/azure-cli.rb" def main(): print('Generate formula for Azure CLI homebrew release.') parser = argparse.ArgumentParser(prog='formula_generator.py') parser.set_defaults(func=generate_formula) parser.add_argument('-b', dest='build_method', choices=['update_existing', 'use_template'], help='The build method, default is update_existing, the other option is use_template.') args = parser.parse_args() args.func(**vars(args)) def generate_formula(build_method: str, **_): content = '' if build_method is None or build_method == 'update_existing': content = update_formula() elif build_method == 'use_template': content = generate_formula_with_template() with open('azure-cli.rb', mode='w') as fq: fq.write(content) def generate_formula_with_template() -> str: """Generate a brew formula by using a template""" template_path = os.path.join(os.path.dirname(__file__), TEMPLATE_FILE_NAME) with open(template_path, mode='r') as fq: template_content = fq.read() template = jinja2.Template(template_content) content = template.render( cli_version=CLI_VERSION, upstream_url=HOMEBREW_UPSTREAM_URL, upstream_sha=compute_sha256(HOMEBREW_UPSTREAM_URL), resources=collect_resources(), bottle_hash=last_bottle_hash() ) if not content.endswith('\n'): content += '\n' return content def compute_sha256(resource_url: str) -> str: import hashlib sha256 = hashlib.sha256() resp = requests.get(resource_url) resp.raise_for_status() sha256.update(resp.content) return sha256.hexdigest() def collect_resources() -> str: nodes = make_graph('azure-cli') nodes_render = [] for node_name in sorted(nodes): if not resource_filter(node_name): continue nodes_render.append(RESOURCE_TEMPLATE.render(resource=nodes[node_name])) return '\n\n'.join(nodes_render) def collect_resources_dict() -> dict: nodes = make_graph('azure-cli') filtered_nodes = {nodes[node_name]['name']: nodes[node_name] for node_name in sorted(nodes) if resource_filter(node_name)} return filtered_nodes def resource_filter(name: str) -> bool: # TODO remove need for any filters and delete this method. return not name.startswith('azure-cli') and name not in ('futures', 'jeepney', 'entrypoints') def last_bottle_hash(): """Fetch the bottle do ... end from the latest brew formula""" resp = requests.get(HOMEBREW_FORMULAR_LATEST) resp.raise_for_status() lines = resp.text.split('\n') look_for_end = False start = 0 end = 0 for idx, content in enumerate(lines): if look_for_end: if 'end' in content: end = idx break else: if 'bottle do' in content: start = idx look_for_end = True return '\n'.join(lines[start: end + 1]) def update_formula() -> str: """Generate a brew formula by updating the existing one""" nodes = collect_resources_dict() resp = requests.get(HOMEBREW_FORMULAR_LATEST) resp.raise_for_status() text = resp.text # update url and sha256 of azure-cli text = re.sub('url ".*"', 'url "{}"'.format(HOMEBREW_UPSTREAM_URL), text, 1) upstream_sha = compute_sha256(HOMEBREW_UPSTREAM_URL) text = re.sub('sha256 ".*"', 'sha256 "{}"'.format(upstream_sha), text, 1) text = re.sub('.*revision.*\n', '', text, 1) # remove revision for previous version if exists # include pip when creating venv, see https://github.com/Homebrew/brew/pull/15792 # this can be removed after Homebrew merges our PR text = re.sub('system_site_packages: false', 'system_site_packages: false, without_pip: false', text, 1) pack = None packs_to_remove = set() lines = text.split('\n') node_index_dict = OrderedDict() line_idx_to_remove = set() upgrade = False for idx, line in enumerate(lines): # In released formula, the url is in the release tag format, such as # "https://github.com/Azure/azure-cli/archive/azure-cli-2.17.1.tar.gz". # version is extracted from url. During build, the url is in the format like # "https://codeload.github.com/Azure/azure-cli/legacy.tar.gz/7e09fd50c9ef02e1ed7d4709c7ab1a71acd3840b". # We need to add the version explicitly after url. # We will change the url in our release pipeline and remove version. if line.startswith(" url"): lines[idx] = lines[idx] + '\n' + ' version "{}"'.format(CLI_VERSION) elif line.strip().startswith("resource"): m = re.search(r'resource "(.*)" do', line) if m is not None: pack = m.group(1) node_index_dict[pack] = idx elif pack is not None: if line.startswith(" url"): #update the url of package if pack in nodes.keys(): url_match = re.search(r'url "(.*)"', line) if url_match is not None and nodes[pack]['url'] != url_match.group(1): lines[idx] = re.sub('url ".*"', 'url "{}"'.format(nodes[pack]['url']), line, 1) upgrade = True else: packs_to_remove.add(pack) elif line.startswith(" sha256"): #update the sha256 of package if pack in nodes.keys(): lines[idx] = re.sub('sha256 ".*"', 'sha256 "{}"'.format(nodes[pack]['checksum']), line, 1) del nodes[pack] elif line.startswith(" end"): pack = None upgrade = False elif upgrade: # In case of upgrading, remove any patch following url and sha256 but before end line_idx_to_remove.add(idx) elif line.strip().startswith('def install'): if nodes: # add new dependency packages for node_name, node in nodes.items(): # find the right place to insert the new resource per alphabetic order i = bisect.bisect_left(list(node_index_dict.keys()), node_name) line_idx = list(node_index_dict.items())[i][1] resource = RESOURCE_TEMPLATE.render(resource=node) lines[line_idx] = resource + '\n\n' + lines[line_idx] lines = [line for idx, line in enumerate(lines) if idx not in line_idx_to_remove] new_text = "\n".join(lines) # remove dependency packages that are no longer needed for pack in packs_to_remove: new_text = re.sub(r'resource "{}" do.*?\n end\n\s+'.format(pack), '', new_text, flags=re.DOTALL) return new_text if __name__ == '__main__': main()
[ "noreply@github.com" ]
allanpedroni.noreply@github.com
d1f5d63673f69802b8065714b366f829e39daa67
8d9008f378deb041771c17f380b54c2c0d1d85bc
/source_code/1331. 数组序号转换/mine_v1.py
05d481eefb7532ffab963adb4c37c58617db01f7
[]
no_license
kavin525zhang/leetcode
b2fc73fe710f6fdf3637d12218ed0bb21bab00bf
8de38466f286d7c2e73ddaac5d5dae5444cc1e4c
refs/heads/main
2023-06-27T20:30:44.252386
2021-08-05T14:09:24
2021-08-05T14:09:24
391,509,569
0
0
null
null
null
null
UTF-8
Python
false
false
510
py
from typing import List class Solution: def arrayRankTransform(self, arr: List[int]) -> List[int]: arr_sort = sorted(arr) num_index = {} for num in arr_sort: if num not in num_index: num_index[num] = len(num_index) + 1 results = [] for num in arr: results.append(num_index[num]) return results if __name__ == "__main__": solution = Solution() arr = [4, 1, 2, 3] print(solution.arrayRankTransform(arr))
[ "kavin@9527" ]
kavin@9527
c035852caa276f982e8835fe76e946fcadcdaf26
4b8fd6959ebe49e12ee9f6cbd9565b81a7819d49
/app.py
2c960453ba3e096a79c1be9f6bb007e9ac824e6c
[]
no_license
TMead21/UK_Towns
84f73271a40bae963aecd5b3d41366a8a7189eea
db40423fa9eb8f05e1ed7231dbd8d4bb22bf7214
refs/heads/main
2023-04-19T15:26:11.199605
2021-04-30T10:16:10
2021-04-30T10:16:10
362,107,098
0
0
null
null
null
null
UTF-8
Python
false
false
3,115
py
from flask import Flask, render_template from flask import flash from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from Towns import Town from UK_Town_Distance import Town_Distances from operator import attrgetter from Form import LoginForm1, LoginForm2, LoginForm3, LoginForm4 from config import Config app = Flask(__name__) app.config.from_object(Config) def get_session(): db = 'sqlite:///C:\\Users\\timwi\\Documents\\work\\other sql\\uk_towns.db' engine = create_engine(db) Session = sessionmaker(bind=engine) session = Session() return session @app.route('/', methods=['GET', 'POST']) def parameters(): session = get_session() towns = session.query(Town).all() # https://docs.python.org/3/howto/sorting.html townsSorted = sorted(towns, key=attrgetter('name')) choicesCentre = [] for town in townsSorted: townDetails = (town.id, town.name) choicesCentre.append(townDetails) # choicesCentre = [(1, "town One"), (2, "town Two"), (3, "town Three")] form1 = LoginForm1(choicesCentre) choicesMin = [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)] form2 = LoginForm2(choicesMin) choicesMax = [(1, 1), (5, 5), (10, 10), (15, 15), (20, 20)] form3 = LoginForm3(choicesMax) choicesNumber = [(5, 5), (10, 10), (15, 15), (20, 20), (1300, 1300)] form4 = LoginForm4(choicesNumber) # TODO: validation (to ensure that something was entered) is not working if form1.validate_on_submit(): # flash('City parameters for towns {}'.format( # form1.searchCentre.data)) # flash('City parameters for minimum {}'.format( # form2.minimum.data)) # flash('City parameters for maximum {}'.format( # form3.maximum.data)) # flash('City parameters for town Number {}'.format( # form4.townNumber.data)) this_distance = Town_Distances() all_towns_in_arc = \ this_distance.obtain_towns_within_specified_arc_miles_to_max_number\ (session, form1.searchCentre.data, form2.minimum.data, form3.maximum.data, form4.townNumber.data) this_town = Town() towns_details = this_town.obtain_town_details_for_specified_group(session, all_towns_in_arc) alltowns = [] allNames = [] for town in towns_details: allNames.append(town[1]) latLong = [float(town[3]), float(town[2])] alltowns.append(latLong) #return redirect('/') # To centre the towns html pass the lat/long of the selected town # So first obtain the lat/long selected_town = this_town.get_town_by_id(session, form1.searchCentre.data) return render_template("Towns.html", towns=alltowns, names=allNames, selected_town=selected_town) return render_template('parameters.html', title='Enter Parameters', form1=form1, form2=form2, form3=form3, form4=form4) if __name__ == '__main__': app.run(debug=True)
[ "noreply@github.com" ]
TMead21.noreply@github.com
8ce2ecfdd203f94cdf0f48b69d85027b44bb56b9
d4fb3837eab6caf7045c20f771ff2a2c03119ac4
/ProgBasics_1_2_3/dojo.py
2916739b81e6f00647cf0f5efed672b828092142
[]
no_license
wojciechGaudnik/InteliJ_MAC
de0d6b81af107318c3c2e6c819d98a663485c5fc
987ef2b50ab71049bea9b3728df068a078375de8
refs/heads/master
2023-08-19T08:14:32.587728
2021-09-27T06:14:16
2021-09-27T06:14:16
392,652,890
0
0
null
null
null
null
UTF-8
Python
false
false
840
py
# min(), max(), sum(), sort(), sorted() etc numbers = [-5, 23, 0, -9, 12, 99, 105, -43] numbers = [-5, 23, 0, "dupa", -9, 12, 99, [2, 44, -100, 200, [-200, "dupa2", 300]], None, 105, -43, 1.1] def min1(lista): i_buf = lista[0] for i in lista: if (type(i) == int or type(i) == float) and i_buf > i: i_buf = i if type(i) == list and i_buf > min1(i): i_buf = min1(i) return(i_buf) print(min1(numbers)) def max1(lista): i_buf = lista[0] for i in lista: if (type(i) == int or type(i) == float) and i_buf < i: i_buf = i if type(i) == list and i_buf < max1(i): i_buf = max1(i) return(i_buf) print(max1(numbers)) def avr1(lista): i_buf = 0 for i in lista: if type(i) == int or type(i) == float: i_buf += i if type(i) == list: i_buf += avr1(i) return(i_buf) print(avr1(numbers)) a = input('a:') print(a)
[ "wojciech.gaudnik@gmail.com" ]
wojciech.gaudnik@gmail.com
85a137fcddefdf19e9d0e91990275af3b1242bb8
e079a9f0e360ed3d06056faeb23e094237085ab9
/PieceView/wsgi.py
9d3b4c9f284bfb786a7b0b4b5dab6e323616ecad
[ "MIT" ]
permissive
David-Duefrene/PieceView
3c176e5859dd449e4be84012cd013f0f1febe4a8
028f40fa5e87fa7e167722b0f08591b13db34411
refs/heads/master
2023-04-06T15:26:02.924499
2020-08-19T12:22:07
2020-08-19T12:22:07
225,019,294
1
0
MIT
2023-03-29T19:28:43
2019-11-30T13:49:45
JavaScript
UTF-8
Python
false
false
466
py
""" WSGI config for PieceView project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ ### urls.py ### Copyright 2019 David J Duefrene, All rights reserved. """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'PieceView.settings') application = get_wsgi_application()
[ "fortismilite@gmail.com" ]
fortismilite@gmail.com
230cc44a01501e165e0c52465d919cfe34dcf403
625dff5531fc1fdf2de6f712a0f63e708ba46444
/webcrawler/webcrawler.py
d02d2375017489729c89df48b064edd3fb75d997
[]
no_license
brunoabia/devdojo_machinelearning
0ec38d7c7d0e76e3c392540ef9712afa7513e18d
3499ab0b642dac8b6824f0d2b014947ccbe74b83
refs/heads/master
2021-04-03T06:41:44.630090
2016-06-24T01:23:45
2016-06-24T01:23:45
61,846,726
10
4
null
null
null
null
UTF-8
Python
false
false
1,397
py
import tweepy import csv import time # CHAVES DE ACESSO FORNECIDAS NO SITE DO TWITTER consumer_key = "" consumer_secret = "" access_token = "" access_token_secret = "" # bruno.abia@gmail.com # Autenticando o acesso auth = tweepy.OAuthHandler(consumer_key,consumer_secret) auth.set_access_token(access_token,access_token_secret) api=tweepy.API(auth) # Onde os dados coletados serão salvos arq = csv.writer(open("base_teste.csv","w")) arq2 = open("base_teste_json.json","w") row=[] # api.search é a API que estamos utilizando. O q é onde vc deve informar qual termo quer consultar. Since e Until são as datas # lang é o parâmetro do idioma statuses = tweepy.Cursor(api.search,q='#orlando', since='2016-06-22', until='2016-06-23',lang='en').items() while True: try: # Lendo os tweets status = statuses.next() # capturando só alguns parametros row=str(status.user.screen_name),str(status.created_at),str(status.text),status.geo # Escrevendo no CSV arq.writerow(row) # Salvando o JSON arq2.write(str(status)) arq2.write("\n") exit() except tweepy.TweepError: # Devido a limitação a cada 3200 tweets é necessário esperar 15 minutos print("wait 15 minutes...") time.sleep(60*15) continue except StopIteration: print("Acabou!!") break
[ "bruno.abia@gmail.com" ]
bruno.abia@gmail.com
ddd511b7dc783c12cde406a6e8498fad7324cc38
bcd82f3398b4a6ea22b1b871e8a36e8162e0a0de
/chapter_14/simple_client.py
8a19e2a58d44d8961dfef3d3613cebee737c23e7
[]
no_license
VersionBeathon/Python_learning
a7ffc16ed53caa70f564e2185500a0cfbbe522ed
17959ee44d00b4e64902e89246eddfdd8479c575
refs/heads/master
2018-01-08T10:39:48.613653
2016-05-03T02:12:19
2016-05-03T02:12:19
49,426,286
0
0
null
null
null
null
UTF-8
Python
false
false
288
py
# _*_ coding:utf-8 _*_ import socket s = socket.socket() host = socket.gethostname() # 获取主机名 port = 1234 # 定义接口 s.connect((host, port)) # 使用connect方法连接到服务器 print s.recv(1024) # 调用recv来接收数据
[ "songmingyang@51jk.com" ]
songmingyang@51jk.com
d17689f91e16375d9deb6d3927d2cf21e870fedf
38e5089e01fadde6040b1015fafcc585da262a15
/ReverseString.py
187fa88bebb540de1b4c14018bd65b9a8c66e841
[]
no_license
ManishShiwlani/WallBreakers-Cohort5
3b0029d2f0160c9fefd2131a9b7afbbf11701341
92c809221c3388c9627a7679d2e9ed89678ca075
refs/heads/master
2021-01-03T15:13:15.275912
2020-02-27T00:46:06
2020-02-27T00:46:06
240,126,720
0
0
null
null
null
null
UTF-8
Python
false
false
357
py
class Solution: def reverseString(self, s: List[str]) -> None: left = 0 right = len(s) - 1 # condition for termination while (left < right): temp = s[left] s[left] = s[right] s[right] = temp # updating pointers left += 1 right -= 1 return s
[ "manishshiwlani@gmail.com" ]
manishshiwlani@gmail.com
dda912d12c5e8b8ac840b6bcf9abfd56a67b6a38
bc67563f9a0fdcc6ab827ae7797612d7716d6ae3
/tests/rift_expect_session.py
4e890ccb7a489827aee17a76b977f50663f68b20
[ "Apache-2.0" ]
permissive
jefftant/rift-python
96202b607b5381b5a5bc4728879ac419ee6e5a4f
d8f6bbdbe82199c9d89255f7d3957f1d070a3763
refs/heads/master
2020-03-27T11:53:21.701263
2018-08-17T00:13:18
2018-08-17T00:13:18
null
0
0
null
null
null
null
UTF-8
Python
false
false
9,791
py
import os import time import traceback import pexpect import pytest class RiftExpectSession: start_converge_secs = 10.0 # Maximum amount of time to fully reconverge after a uni-directional interface failure # If node1 can still send to node2, but node1 cannot receive from node2: # - It takes up to 3 seconds for node2 to detect that it is not receiving LIEs from node1 # - At that point node2 will stop reflecting node1 # - It takes up to 1 second for node1 to receive the first LIE without the reflection # - Add 1 second of slack time # reconverge_secs = 5.0 expect_timeout = 1.0 def __init__(self, topology_file, converge_secs=start_converge_secs): rift_cmd = ("rift " "--interactive " "--non-passive " "--log-level debug " "topology/{}.yaml" .format(topology_file)) cmd = "coverage run --parallel-mode {}".format(rift_cmd) results_file_name = "rift_expect.log" if "RIFT_TEST_RESULTS_DIR" in os.environ: results_file_name = os.environ["RIFT_TEST_RESULTS_DIR"] + "/" + results_file_name self._results_file = open(results_file_name, 'ab') self._expect_session = pexpect.spawn(cmd, logfile=self._results_file) time.sleep(converge_secs) self.wait_prompt() def stop(self): # Attempt graceful exit self._expect_session.sendline("exit") # Give some time for coverage to write .coverage results file time.sleep(1.0) # Terminate it forcefully, in case the graceful exit did not work for some reason self._expect_session.terminate(force=True) def sendline(self, line): self._expect_session.sendline(line) def log_expect_failure(self): self._results_file.write(b"\n\n*** Did not find expected pattern\n\n") # Generate a call stack in rift_expect.log for easier debugging # But pytest call stacks are very deep, so only show the "interesting" lines for line in traceback.format_stack(): if "tests/" in line: self._results_file.write(line.strip().encode()) self._results_file.write(b"\n") def expect(self, pattern, timeout=expect_timeout): msg = "\n\n*** Expect: {}\n\n".format(pattern) self._results_file.write(msg.encode()) try: self._expect_session.expect(pattern, timeout) except pexpect.TIMEOUT: # Report the failure outside of this block, otherwise pytest reports a huge callstack failed = True else: failed = False if failed: self.log_expect_failure() pytest.fail('Timeout expecting "{} (see rift_expect.log for details)"'.format(pattern)) def table_expect(self, pattern, timeout=expect_timeout): # Allow multiple spaces at end of each cell, even if only one was asked for pattern = pattern.replace(" |", " +|") # The | character is a literal end-of-cell, not a regexp OR pattern = pattern.replace("|", "[|]") pattern = pattern.replace("/", "|") return self.expect(pattern, timeout) def wait_prompt(self, node_name=None): if node_name is None: self.expect(".*> ") else: self.expect("{}> ".format(node_name)) def check_adjacency_1way(self, node, interface): # Go to the node that we want to check self.sendline("set node {}".format(node)) self.wait_prompt(node) # Show interfaces reports the adjacency with the other node as ONE_WAY self.sendline("show interfaces") self.table_expect("| {} | | .* | ONE_WAY |".format(interface)) self.wait_prompt(node) # Show interface <interface-name> reports the adjacency with the other node as ONE_WAY self.sendline("show interface {}".format(interface)) self.table_expect("Interface:") self.table_expect("| Interface Name | {} |".format(interface)) self.table_expect("| State | ONE_WAY |") self.table_expect("| Neighbor | False |") self.wait_prompt(node) def check_adjacency_2way(self, node, interface, other_node, other_interface): # Construct full interface names as reported in LIE packets other_full_name = other_node + "-" + other_interface # Go to the node that we want to check self.sendline("set node {}".format(node)) self.wait_prompt(node) # Show interfaces reports the adjacency with the other node as TWO_WAY self.sendline("show interfaces") self.table_expect("| {} | {} | .* | TWO_WAY |".format(interface, other_full_name)) self.wait_prompt(node) # Show interface <interface-name> reports the adjacency with the other node as TWO_WAY self.sendline("show interface {}".format(interface)) self.table_expect("Interface:") self.table_expect("| Interface Name | {} |".format(interface)) self.table_expect("| State | TWO_WAY |") self.table_expect("| Received LIE Accepted or Rejected | Accepted |") self.table_expect("| Neighbor | True |") self.table_expect("Neighbor:") self.table_expect("| Name | {} |".format(other_full_name)) self.wait_prompt(node) def check_adjacency_3way(self, node, interface): # Go to the node that we want to check self.sendline("set node {}".format(node)) self.wait_prompt(node) # Show interfaces reports the adjacency with the other node as THREE_WAY self.sendline("show interfaces") self.table_expect("| {} | .* | .* | THREE_WAY |".format(interface)) self.wait_prompt(node) # Show interface <interface-name> reports the adjacency with the other node as THREE_WAY self.sendline("show interface {}".format(interface)) self.table_expect("Interface:") self.table_expect("| Interface Name | {} |".format(interface)) self.table_expect("| State | THREE_WAY |") self.table_expect("| Received LIE Accepted or Rejected | Accepted |") self.table_expect("| Neighbor | True |") self.table_expect("Neighbor:") self.table_expect("| Name | .* |") self.wait_prompt(node) def check_rx_offer(self, node, interface, system_id, level, not_a_ztp_offer, state, best, best_3way, removed, removed_reason): # Go to the node that we want to check self.sendline("set node {}".format(node)) # Show node reports the offers self.sendline("show node") # Look for the expected offer expected_offer = "| {} | {} | {} | {} | {} | {} | {} | {} | {} |".format( interface, system_id, level, not_a_ztp_offer, state, best, best_3way, removed, removed_reason) self.table_expect("Received Offers:") self.table_expect(expected_offer) self.wait_prompt(node) def check_tx_offer(self, node, interface, system_id, level, not_a_ztp_offer, state): # Go to the node that we want to check self.sendline("set node {}".format(node)) # Show node reports the offers self.sendline("show node") # Look for the expected offer expected_offer = "| {} | {} | {} | {} | {} |".format(interface, system_id, level, not_a_ztp_offer, state) self.table_expect("Sent Offers:") self.table_expect(expected_offer) self.wait_prompt(node) def check_level(self, node, configured_level, hal, hat, level_value): # Check using "show node" self.sendline("set node {}".format(node)) self.sendline("show node") self.table_expect("| Configured Level | {} |".format(configured_level)) self.table_expect("| Highest Available Level .HAL. | {} |".format(hal)) self.table_expect("| Highest Adjacency Three-way .HAT. | {} |".format(hat)) self.table_expect("| Level Value | {} |".format(level_value)) # Check for consistency in "show nodes level" self.sendline("show nodes level") # Look for the expected offer expected_level = "| {} | .* | .* | {} | {} |".format(node, configured_level, level_value) self.table_expect(expected_level) self.wait_prompt() def check_lie_accepted(self, node, interface, reason): self.sendline("set node {}".format(node)) self.sendline("show interface {}".format(interface)) self.table_expect("Interface:") self.table_expect("| Received LIE Accepted or Rejected | Accepted |") self.table_expect("| Received LIE Accept or Reject Reason | {} |".format(reason)) self.wait_prompt() def check_lie_rejected(self, node, interface, reason): self.sendline("set node {}".format(node)) self.sendline("show interface {}".format(interface)) self.table_expect("Interface:") self.table_expect("| Received LIE Accepted or Rejected | Rejected |") self.table_expect("| Received LIE Accept or Reject Reason | {} |".format(reason)) self.wait_prompt() def interface_failure(self, node, interface, failure): # Go to the node whose interface needs to fail self.sendline("set node {}".format(node)) # Fail the interface self.sendline("set interface {} failure {}".format(interface, failure)) # Make sure it took self.sendline("show interface {}".format(interface)) expected_failure = "| Failure | {} |".format(failure) self.table_expect(expected_failure) self.wait_prompt() # Let reconverge time.sleep(self.reconverge_secs)
[ "brunorijsman@gmail.com" ]
brunorijsman@gmail.com
945f36dab7417d267090cb6db74296cae27e5b29
f5043ce6204500b264e8933b833aa8c41fab574a
/cochev112.py
f360c5ba28c817490581a362616168f92bfe9e03
[]
no_license
pulgares/coche
47723c43fd5a22537c4425ec12de8c81f387ac0a
d43f5036f36d9271e0cfe3c24f041cdbdebffa84
refs/heads/master
2021-01-21T13:30:08.908367
2016-04-19T18:40:56
2016-04-19T18:40:56
45,938,787
0
0
null
null
null
null
UTF-8
Python
false
false
10,873
py
#!/usr/bin/env python import serial import Tkinter as tk from Tkinter import * from time import sleep import ttk try: arduino = serial.Serial( 'COM7', 9600 ) except: print "Cannot conect to the port" def Luzposicionon(): arduino.write('b') print "Posicion on" def Luzposicionoff(): # pin arduino 6 arduino.write('a') print "Posicion off" def Calefacion(): def lift_win1(): otra_ventana.withdraw() # Oculta la otra_ventana root.deiconify() otra_ventana = tk.Toplevel() otra_ventana.config(bg="black") otra_ventana.geometry("800x420") otra_ventana.title('Calefacion') button1 = tk.Button(otra_ventana, text="A/C ON",command=ACon) button1.place (x=10, y=10) button1.config( height = 6, width = 20 ) root.iconify() button2 = tk.Button(otra_ventana, text="A/C OFF",command=ACoff) button2.place (x=250, y=10) button2.config( height = 6, width = 20 ) button3 = tk.Button(otra_ventana, image=imagenatras,fg="White",command=lift_win1) button3.place (x=410, y=300) button3.config( height = 96, width = 96 ) button3.config(bg="black") def ACon(): arduino.write('b') print "ACon" def ACoff(): arduino.write('c') print "ACoff" #------------------------------------------------------------------------------------------ def Luces(): def lift_win1(): otra_ventana1.withdraw() # Oculta la otra_ventana root.deiconify() otra_ventana1 = tk.Toplevel() otra_ventana1.config(bg="black") otra_ventana1.geometry("800x420") otra_ventana1.title('Luces') #------------------------------------------------------------------------------------------------ button4 = tk.Button(otra_ventana1, image=imagenatras,fg="White",command=lift_win1) button4.place (x=410, y=300) button4.config( height = 96, width = 96 ) button4.config(bg="black") #---------------------------------------------------------------------------------------------------- button5 = Button(otra_ventana1, text="Luces posicion ON",fg="red", command=Luzposicionon) button5.config( height = 6, width = 20 ) button5.place (x=10, y=10) # pin arduino 6 button6 = Button(otra_ventana1, text="Luces posicion OFF",fg="red", command=Luzposicionoff) button6.place (x=250, y=10) button6.config( height = 6, width = 20 ) #-------------------------------------------------------------------------------------------------- button7 = Button(otra_ventana1, text="Luz Cruze ON",fg="blue", command=Luzcruceon) #button8.grid(row=4, column=1) button7.place (x=10, y=150) #pin arduino 7 button7.config( height = 6, width = 20 ) button8 = Button(otra_ventana1, text="Luz cruze OFF",fg="blue", command=Luzcruceoff) #button7.grid(row=4, column=2) button8.config( height = 6, width = 20 ) button8.place (x=220, y=150) #------------------------------------------------------------------------------------------------------ button9 = Button(otra_ventana1, text="Luz techo OFF", fg="blue",command=Luztechooff) button9.place (x=640, y=10) button9.config( height = 6, width = 20 ) #pin arduino 5 button10 = Button(otra_ventana1, text="Luz techo ON", fg="blue",command=Luztecho) button10.place (x=440, y=10) button10.config( height = 6, width = 20 ) #------------------------------------------------------------------------------------------------------ button11 = Button(otra_ventana1, text="Luz espejo ON",fg="blue", command=Luzespejoon) #button9.grid(row=5, column=1) button11.config( height = 6, width = 20 ) #pin arduino 8 button11.place (x=430, y=150) button12 = Button(otra_ventana1, text="Luz espejo OFF",fg="blue", command=Luzespejooff) #button10.grid(row=5, column=2) button12.config( height = 6, width = 20 ) button12.place (x=640, y=150) #------------------------------------------------------------------------------------------------- button13 = Button(otra_ventana1, text="Apagar todos", fg="blue", command=todosoff) #button12.grid(row=6, column=2) button13.config( height = 6, width = 20 ) button13.place (x=220, y=300) root.iconify() #----------------------------------------------------------------------------------------------------- def todos(): arduino.write('i') print "todos on" def todosoff(): arduino.write('l') print "todos off" def Luzespejoon(): arduino.write('g') print "LuzespejoON" def Luzespejooff(): arduino.write('h') print "LuzespejoOFF" def Luzcruceon(): arduino.write('d') print "Cruce on" #pin arduino 7 def Luzcruceoff(): arduino.write('c') print "Cruce off" def Luztecho(): arduino.write('e') print "Luztecho on" def Luztechooff(): arduino.write('f') print "Luztecho on" #--------------------------------------------------------------------------------------- def Puertas(): def lift_win1(): otra_ventana2.withdraw() # Oculta la otra_ventana root.deiconify() otra_ventana2 = tk.Toplevel() otra_ventana2.config(bg="black") otra_ventana2.geometry("800x420") otra_ventana2.title('Puertas') button14 = Button(otra_ventana2, image=imagen1,fg="blue", command=Flipflop) button14.config( height = 18, width = 20) button14.place (x=10, y=10) button15 = tk.Button(otra_ventana2, image=imagenatras,fg="White", command=lift_win1) button15.place (x=410, y=300) button15.config( height = 96, width = 96 ) button15.config(bg="black") root.iconify() def Sensores(): def lift_win1(): otra_ventana3.withdraw() # Oculta la otra_ventana root.deiconify() otra_ventana3 = tk.Toplevel() otra_ventana3.config(bg="black") otra_ventana3.geometry("800x420") otra_ventana3.title('Sensores') w = Scale(otra_ventana3, label="Servo1", from_=0, to=255, orient=VERTICAL ,fg="White",command=Servo1, length=200) #Creamos un dial para recoger datos numericos w.config(bg="black") w.place (x=50, y=10) w = Scale(otra_ventana3, label="Servo2", from_=0, to=255, orient=VERTICAL ,fg="White",command=Servo2, length=200) #Creamos un dial para recoger datos numericos w.config(bg="black") w.place (x=250, y=10) w = Scale(otra_ventana3, label="Servo3", from_=0, to=255, orient=VERTICAL ,fg="White",command=Servo3, length=200) #Creamos un dial para recoger datos numericos w.config(bg="black") w.place (x=550, y=10) button16 = tk.Button(otra_ventana3, image=imagenatras, fg="White", command=lift_win1) button16.place (x=410, y=300) button16.config( height = 96, width = 96 ) button16.config(bg="black") root.iconify() def Parpadeo(): arduino.write('e') print "Se encendio el led 1" sleep(5) arduino.write('a') print "Se apago el led 1" sleep(5) arduino.write('e') print "Se encendio el led 1" sleep(5) arduino.write('a') print "Se apago el led 1" sleep(5) arduino.write('e') print "Se encendio el led 1" sleep(5) arduino.write('a') print "Se apago el led 1" sleep(5) def Flipflop(): arduino.write('e') print "Se encendio el led 1" sleep(1) arduino.write('a') print "Se apago el led 1" sleep(1) arduino.write('b') print "Se encendio el led 2" sleep(1) arduino.write('c') print "Se apago el led 2" sleep(1) def Servo1(int): arduino.write('q') arduino.write(int) arduino.write('\n') print (int) def Servo2(int): arduino.write('p') arduino.write(int) arduino.write('\n') print (int) def Servo3(int): arduino.write('r') arduino.write(int) arduino.write('\n') print (int) def onselect(evt): # Note here that Tkinter passes an event object to onselect() w = evt.widget index = int(w.curselection()[0]) value = w.get(index) print 'You selected item %d: "%s"' % (index, value) arduino = serial.Serial( value, 9600 ) def arrancar(): arduino.write('o') print "arrancar" root = Tk() #root.config(bg="black") imagenfondo=PhotoImage(file="car.gif") imagen1=PhotoImage(file="flechaarriba.gif") imagenatras=PhotoImage(file="izquierda.gif") imagenluz=PhotoImage(file="luz.gif") imagenpuerta=PhotoImage(file="puerta.gif") imagencalefacion=PhotoImage(file="calefacion.gif") imagensensor=PhotoImage(file="sensor.gif") imagencontacto=PhotoImage(file="contacto.gif") imagencerrar=PhotoImage(file="radioactive.gif") lblimagen=Label(root, image=imagenfondo).place(x=150, y=0) #w = Scale(root, label="Servo1", from_=0, to=255, orient=HORIZONTAL ,fg="blue",command=Servo1, #length=200) #Creamos un dial para recoger datos numericos #w.grid(row=7,column=1) #w.place (x=50, y=510) #w = Scale(root, label="Servo2", from_=0, to=255, orient=HORIZONTAL ,fg="blue",command=Servo2, #length=200) #Creamos un dial para recoger datos numericos #w.grid(row=10,column=1) #w.place (x=300, y=510) #w = Scale(root, label="Servo3", from_=0, to=255, orient=HORIZONTAL ,fg="blue",command=Servo3, #length=200) #Creamos un dial para recoger datos numericos #w.place (x=550, y=510) button17 = Button(root, text="Parpadeo",fg="blue", command=Parpadeo) #button3.grid(row=1, column=2) button17.config( height = 3, width = 11 ) button18 = Button(root, image=imagenluz, fg="blue", command=Luces) button18.place (x=10, y=10) button18.config( height = 96, width = 96 ) button19 = Button(root, image=imagenpuerta,fg="blue", command=Puertas) #button6 grid(row=1, column=1) button19.config( height = 96, width = 96) button19.place (x=570, y=10) button20 = Button(root, image=imagensensor,fg="blue", command=Sensores) #button11.grid(row=6, column=1) button20.config( height = 96, width = 96 ) button20.place (x=700, y=10) button21 = Button(root, image=imagencalefacion, fg="blue", command=Calefacion) #button13.grid(row=12, column=2) button21.config( height = 96, width = 96 ) button21.place (x=140, y=10) button22 = Button(root, image=imagencontacto, fg="blue", command=arrancar) #button13.grid(row=12, column=2) button22.config( height = 96, width = 96 ) button22.place (x=10, y=200) cerrar = Button(root,image=imagencerrar, command=root.destroy) cerrar.config( height = 96, width = 96 ) cerrar.place (x=700, y=200) #Button31.pack() root.title('GUI de Leds') root.geometry("800x420") root.mainloop()
[ "prusai3@pipo.es" ]
prusai3@pipo.es
ee1ce2bf57e0f7c08c5d867d980536478882b3b8
4e25aba778ed66c3d61c0faec1f987302ef5f27b
/tests/converters_tests/test_list_comp.py
52975d4111f98ffc65706af1020412ab9d45b93f
[]
no_license
giladbarnea/autosyntax-gui
1a2ebc504d2512061663a438d25b4dc16a068fca
50be537e2be5d74ca8ee0452e575e832b2d859bb
refs/heads/master
2020-03-21T09:19:27.751064
2018-06-23T10:59:15
2018-06-23T10:59:15
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,621
py
from . import get_expression def test_0(): assert get_expression('lcomp collection') == "[c for c in collection]" def test_1(): assert get_expression('my = lcomp collection') == "my = [c for c in collection]" def test_2(): assert get_expression('lcomp collections') == "[collection for collection in collections]" def test_3(): assert get_expression('my = lcomp collections') == "my = [collection for collection in collections]" def test_4(): assert get_expression('lcomp .collection') == "[c for c in 'collection']" def test_5(): assert get_expression('my = lcomp .collection') == "my = [c for c in 'collection']" def test_6(): assert get_expression('lcomp .collections') == "[collection for collection in 'collections']" def test_7(): assert get_expression('my = lcomp .collections') == "my = [collection for collection in 'collections']" def test_8(): assert get_expression('lcomp str zip dict collection') == "[str(zip(dict(c))) for c in collection]" def test_9(): assert get_expression('lcomp str zip dict .collection') == "[str(zip(dict(c))) for c in 'collection']" def test_10(): assert get_expression('lcomp str zip dict .collection') == "[str(zip(dict(c))) for c in 'collection']" def test_11(): assert get_expression('lcomp str zip dict self.collection') == "[str(zip(dict(c))) for c in self.collection]" def test_12(): assert get_expression( 'lcomp str zip dict self.collections') == "[str(zip(dict(collection))) for collection in self.collections]" def test_13(): assert get_expression('lcomp self.collections') == "[collection for collection in self.collections]"
[ "gbetech@gmail.com" ]
gbetech@gmail.com
4944d7c91ada4191e1fa51e7d9d73006e0867e8a
7942b457c56662743a6128517f1ba7287a4e7504
/2018_UCPC_본선/BOJ15947_JH.py
e68fee881451ac3548f6dde117a1148c24b559c1
[]
no_license
JungJaeLee-JJ/Algorithmic-Problem-Solving
8fdaf772b54fc21f9f1af64db4bd0b28fc69c48e
814d771b8d31c0bb5e1600c72a970db79103e45f
refs/heads/master
2021-07-15T20:46:17.515870
2020-12-06T13:34:09
2020-12-06T13:34:09
231,224,644
0
1
null
2021-07-24T08:51:49
2020-01-01T14:14:32
C++
UTF-8
Python
false
false
434
py
import sys string = ["sukhwan", "baby", "sukhwan", "tu", "tu", "very", "cute", "tu", "tu", "in", "bed", "tu", "tu", "baby"] n = int(sys.stdin.readline()) quota = n // 14 n = n % 14 print(string[n], end="") if n % 4 == 3 and n < 12: if 2+quota < 5: print("ru" * (2+quota)) else : print("+ru*%d" %(2+quota)) if n != 0 and n % 4 == 0 and n <= 12: if 1+quota < 5: print("ru" * (1+quota)) else : print("+ru*%d" %(1+quota))
[ "jihun.jeong219@gmail.com" ]
jihun.jeong219@gmail.com
c7378ea7cc43486c64b412f2fa77dbb3934d8bb1
a31ea008d1772776497307d565ba5072bee072f9
/manage.py
838b8322b996f06c4342863683d5ece10609c7a1
[]
no_license
MajjigaDeepak/Thirdplatform
540b77935ed266f239289fca94fd13130a8da52b
68ff134a37a650a5ff43829ea3f1f6fa1198410f
refs/heads/master
2016-09-13T16:54:33.516518
2016-05-04T14:27:51
2016-05-04T14:27:51
57,892,197
0
0
null
null
null
null
UTF-8
Python
false
false
256
py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Thirdplatform.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
[ "m.deepakeee1@gmail.com" ]
m.deepakeee1@gmail.com
0692cba6db756dc2b4db105199a9246bfd56c262
acb8e84e3b9c987fcab341f799f41d5a5ec4d587
/langs/4/kbn.py
79a097f2e1c35485021fbb608c2bd77d31403db3
[]
no_license
G4te-Keep3r/HowdyHackers
46bfad63eafe5ac515da363e1c75fa6f4b9bca32
fb6d391aaecb60ab5c4650d4ae2ddd599fd85db2
refs/heads/master
2020-08-01T12:08:10.782018
2016-11-13T20:45:50
2016-11-13T20:45:50
73,624,224
0
1
null
null
null
null
UTF-8
Python
false
false
486
py
import sys def printFunction(lineRemaining): if lineRemaining[0] == '"' and lineRemaining[-1] == '"': if len(lineRemaining) > 2: #data to print lineRemaining = lineRemaining[1:-1] print ' '.join(lineRemaining) else: print def main(fileName): with open(fileName) as f: for line in f: data = line.split() if data[0] == 'kBN': printFunction(data[1:]) else: print 'ERROR' return if __name__ == '__main__': main(sys.argv[1])
[ "juliettaylorswift@gmail.com" ]
juliettaylorswift@gmail.com
13592df07bf2bcd3a00656af54e09f394e1361ef
3fbf0d11a9c08b37e8e72c1640d958678e035d11
/lesson09c/settings.py
07e938ce447a5ca456bf5b33f419675996203949
[]
no_license
SMThorpe/lesson09c
a7e65ddbc287db4f9a8a09b8ec4a15aab6c01eb9
785bba277d3625962347eae8464a39230dc1577f
refs/heads/master
2020-06-03T04:48:33.491258
2015-01-29T15:14:00
2015-01-29T15:14:00
30,025,317
0
0
null
null
null
null
UTF-8
Python
false
false
2,051
py
""" Django settings for lesson09c project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = ')ts*=qy_o26mqfx@tx61=t%-a*o1s^%*t_=3mj)2$%k#^5qs*g' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'lesson09c.urls' WSGI_APPLICATION = 'lesson09c.wsgi.application' # Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.7/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.7/howto/static-files/ STATIC_URL = '/static/'
[ "x61714@USMANBUX61714.usma.ds.army.edu" ]
x61714@USMANBUX61714.usma.ds.army.edu
19acf460308d2ae73030a7feddd6223d4eccf4df
9a216260e3c3ba9c73f3cbad0b16c3bb4cd3b622
/imGcode/env_imGcode/Lib/site-packages/matplotlib/widgets.py
ba0168e48a17ef7e1a2693bce40a0463b1681587
[ "Apache-2.0" ]
permissive
vidmo91/imgcode
a214348650e349b81cc9c43c4f92e17d9f791875
7c8d0b6f01af4d96e70b9afb1bbb1e7b72603c3c
refs/heads/master
2023-07-19T17:00:44.757756
2020-07-27T15:07:44
2020-07-27T15:07:44
171,950,671
16
7
Apache-2.0
2023-07-06T21:33:35
2019-02-21T21:48:50
Python
UTF-8
Python
false
false
93,160
py
""" GUI neutral widgets =================== Widgets that are designed to work for any of the GUI backends. All of these widgets require you to predefine a `matplotlib.axes.Axes` instance and pass that as the first parameter. Matplotlib doesn't try to be too smart with respect to layout -- you will have to figure out how wide and tall you want your Axes to be to accommodate your widget. """ from contextlib import ExitStack import copy from numbers import Integral import numpy as np import matplotlib as mpl from . import cbook, ticker from .lines import Line2D from .patches import Circle, Rectangle, Ellipse from .transforms import blended_transform_factory class LockDraw: """ Some widgets, like the cursor, draw onto the canvas, and this is not desirable under all circumstances, like when the toolbar is in zoom-to-rect mode and drawing a rectangle. To avoid this, a widget can acquire a canvas' lock with ``canvas.widgetlock(widget)`` before drawing on the canvas; this will prevent other widgets from doing so at the same time (if they also try to acquire the lock first). """ def __init__(self): self._owner = None def __call__(self, o): """Reserve the lock for *o*.""" if not self.available(o): raise ValueError('already locked') self._owner = o def release(self, o): """Release the lock from *o*.""" if not self.available(o): raise ValueError('you do not own this lock') self._owner = None def available(self, o): """Return whether drawing is available to *o*.""" return not self.locked() or self.isowner(o) def isowner(self, o): """Return whether *o* owns this lock.""" return self._owner is o def locked(self): """Return whether the lock is currently held by an owner.""" return self._owner is not None class Widget: """ Abstract base class for GUI neutral widgets """ drawon = True eventson = True _active = True def set_active(self, active): """Set whether the widget is active.""" self._active = active def get_active(self): """Get whether the widget is active.""" return self._active # set_active is overridden by SelectorWidgets. active = property(get_active, set_active, doc="Is the widget active?") def ignore(self, event): """ Return whether *event* should be ignored. This method should be called at the beginning of any event callback. """ return not self.active class AxesWidget(Widget): """ Widget connected to a single `~matplotlib.axes.Axes`. To guarantee that the widget remains responsive and not garbage-collected, a reference to the object should be maintained by the user. This is necessary because the callback registry maintains only weak-refs to the functions, which are member functions of the widget. If there are no references to the widget object it may be garbage collected which will disconnect the callbacks. Attributes ---------- ax : `~matplotlib.axes.Axes` The parent axes for the widget. canvas : `~matplotlib.backend_bases.FigureCanvasBase` The parent figure canvas for the widget. active : bool If False, the widget does not respond to events. """ def __init__(self, ax): self.ax = ax self.canvas = ax.figure.canvas self.cids = [] def connect_event(self, event, callback): """ Connect callback with an event. This should be used in lieu of ``figure.canvas.mpl_connect`` since this function stores callback ids for later clean up. """ cid = self.canvas.mpl_connect(event, callback) self.cids.append(cid) def disconnect_events(self): """Disconnect all events created by this widget.""" for c in self.cids: self.canvas.mpl_disconnect(c) class Button(AxesWidget): """ A GUI neutral button. For the button to remain responsive you must keep a reference to it. Call `.on_clicked` to connect to the button. Attributes ---------- ax The `matplotlib.axes.Axes` the button renders into. label A `matplotlib.text.Text` instance. color The color of the button when not hovering. hovercolor The color of the button when hovering. """ def __init__(self, ax, label, image=None, color='0.85', hovercolor='0.95'): """ Parameters ---------- ax : `~matplotlib.axes.Axes` The `~.axes.Axes` instance the button will be placed into. label : str The button text. image : array-like or PIL Image The image to place in the button, if not *None*. The parameter is directly forwarded to `~matplotlib.axes.Axes.imshow`. color : color The color of the button when not activated. hovercolor : color The color of the button when the mouse is over it. """ AxesWidget.__init__(self, ax) if image is not None: ax.imshow(image) self.label = ax.text(0.5, 0.5, label, verticalalignment='center', horizontalalignment='center', transform=ax.transAxes) self.cnt = 0 self.observers = {} self.connect_event('button_press_event', self._click) self.connect_event('button_release_event', self._release) self.connect_event('motion_notify_event', self._motion) ax.set_navigate(False) ax.set_facecolor(color) ax.set_xticks([]) ax.set_yticks([]) self.color = color self.hovercolor = hovercolor def _click(self, event): if (self.ignore(event) or event.inaxes != self.ax or not self.eventson): return if event.canvas.mouse_grabber != self.ax: event.canvas.grab_mouse(self.ax) def _release(self, event): if (self.ignore(event) or event.canvas.mouse_grabber != self.ax): return event.canvas.release_mouse(self.ax) if (not self.eventson or event.inaxes != self.ax): return for cid, func in self.observers.items(): func(event) def _motion(self, event): if self.ignore(event): return c = self.hovercolor if event.inaxes == self.ax else self.color if c != self.ax.get_facecolor(): self.ax.set_facecolor(c) if self.drawon: self.ax.figure.canvas.draw() def on_clicked(self, func): """ Connect the callback function *func* to button click events. Returns a connection id, which can be used to disconnect the callback. """ cid = self.cnt self.observers[cid] = func self.cnt += 1 return cid def disconnect(self, cid): """Remove the callback function with connection id *cid*.""" try: del self.observers[cid] except KeyError: pass class Slider(AxesWidget): """ A slider representing a floating point range. Create a slider from *valmin* to *valmax* in axes *ax*. For the slider to remain responsive you must maintain a reference to it. Call :meth:`on_changed` to connect to the slider event. Attributes ---------- val : float Slider value. """ def __init__(self, ax, label, valmin, valmax, valinit=0.5, valfmt=None, closedmin=True, closedmax=True, slidermin=None, slidermax=None, dragging=True, valstep=None, orientation='horizontal', **kwargs): """ Parameters ---------- ax : Axes The Axes to put the slider in. label : str Slider label. valmin : float The minimum value of the slider. valmax : float The maximum value of the slider. valinit : float, default: 0.5 The slider initial position. valfmt : str, default: None %-format string used to format the slider value. If None, a `.ScalarFormatter` is used instead. closedmin : bool, default: True Whether the slider interval is closed on the bottom. closedmax : bool, default: True Whether the slider interval is closed on the top. slidermin : Slider, default: None Do not allow the current slider to have a value less than the value of the Slider *slidermin*. slidermax : Slider, default: None Do not allow the current slider to have a value greater than the value of the Slider *slidermax*. dragging : bool, default: True If True the slider can be dragged by the mouse. valstep : float, default: None If given, the slider will snap to multiples of *valstep*. orientation : {'horizontal', 'vertical'}, default: 'horizontal' The orientation of the slider. Notes ----- Additional kwargs are passed on to ``self.poly`` which is the `~matplotlib.patches.Rectangle` that draws the slider knob. See the `.Rectangle` documentation for valid property names (``facecolor``, ``edgecolor``, ``alpha``, etc.). """ if ax.name == '3d': raise ValueError('Sliders cannot be added to 3D Axes') AxesWidget.__init__(self, ax) if slidermin is not None and not hasattr(slidermin, 'val'): raise ValueError("Argument slidermin ({}) has no 'val'" .format(type(slidermin))) if slidermax is not None and not hasattr(slidermax, 'val'): raise ValueError("Argument slidermax ({}) has no 'val'" .format(type(slidermax))) if orientation not in ['horizontal', 'vertical']: raise ValueError("Argument orientation ({}) must be either" "'horizontal' or 'vertical'".format(orientation)) self.orientation = orientation self.closedmin = closedmin self.closedmax = closedmax self.slidermin = slidermin self.slidermax = slidermax self.drag_active = False self.valmin = valmin self.valmax = valmax self.valstep = valstep valinit = self._value_in_bounds(valinit) if valinit is None: valinit = valmin self.val = valinit self.valinit = valinit if orientation == 'vertical': self.poly = ax.axhspan(valmin, valinit, 0, 1, **kwargs) self.hline = ax.axhline(valinit, 0, 1, color='r', lw=1) else: self.poly = ax.axvspan(valmin, valinit, 0, 1, **kwargs) self.vline = ax.axvline(valinit, 0, 1, color='r', lw=1) if orientation == 'vertical': ax.set_ylim((valmin, valmax)) axis = ax.yaxis else: ax.set_xlim((valmin, valmax)) axis = ax.xaxis self.valfmt = valfmt self._fmt = axis.get_major_formatter() if not isinstance(self._fmt, ticker.ScalarFormatter): self._fmt = ticker.ScalarFormatter() self._fmt.set_axis(axis) self._fmt.set_useOffset(False) # No additive offset. self._fmt.set_useMathText(True) # x sign before multiplicative offset. ax.set_xticks([]) ax.set_yticks([]) ax.set_navigate(False) self.connect_event('button_press_event', self._update) self.connect_event('button_release_event', self._update) if dragging: self.connect_event('motion_notify_event', self._update) if orientation == 'vertical': self.label = ax.text(0.5, 1.02, label, transform=ax.transAxes, verticalalignment='bottom', horizontalalignment='center') self.valtext = ax.text(0.5, -0.02, self._format(valinit), transform=ax.transAxes, verticalalignment='top', horizontalalignment='center') else: self.label = ax.text(-0.02, 0.5, label, transform=ax.transAxes, verticalalignment='center', horizontalalignment='right') self.valtext = ax.text(1.02, 0.5, self._format(valinit), transform=ax.transAxes, verticalalignment='center', horizontalalignment='left') self.cnt = 0 self.observers = {} self.set_val(valinit) def _value_in_bounds(self, val): """Makes sure *val* is with given bounds.""" if self.valstep: val = (self.valmin + round((val - self.valmin) / self.valstep) * self.valstep) if val <= self.valmin: if not self.closedmin: return val = self.valmin elif val >= self.valmax: if not self.closedmax: return val = self.valmax if self.slidermin is not None and val <= self.slidermin.val: if not self.closedmin: return val = self.slidermin.val if self.slidermax is not None and val >= self.slidermax.val: if not self.closedmax: return val = self.slidermax.val return val def _update(self, event): """Update the slider position.""" if self.ignore(event) or event.button != 1: return if event.name == 'button_press_event' and event.inaxes == self.ax: self.drag_active = True event.canvas.grab_mouse(self.ax) if not self.drag_active: return elif ((event.name == 'button_release_event') or (event.name == 'button_press_event' and event.inaxes != self.ax)): self.drag_active = False event.canvas.release_mouse(self.ax) return if self.orientation == 'vertical': val = self._value_in_bounds(event.ydata) else: val = self._value_in_bounds(event.xdata) if val not in [None, self.val]: self.set_val(val) def _format(self, val): """Pretty-print *val*.""" if self.valfmt is not None: return self.valfmt % val else: _, s, _ = self._fmt.format_ticks([self.valmin, val, self.valmax]) # fmt.get_offset is actually the multiplicative factor, if any. return s + self._fmt.get_offset() def set_val(self, val): """ Set slider value to *val* Parameters ---------- val : float """ xy = self.poly.xy if self.orientation == 'vertical': xy[1] = 0, val xy[2] = 1, val else: xy[2] = val, 1 xy[3] = val, 0 self.poly.xy = xy self.valtext.set_text(self._format(val)) if self.drawon: self.ax.figure.canvas.draw_idle() self.val = val if not self.eventson: return for cid, func in self.observers.items(): func(val) def on_changed(self, func): """ When the slider value is changed call *func* with the new slider value Parameters ---------- func : callable Function to call when slider is changed. The function must accept a single float as its arguments. Returns ------- int Connection id (which can be used to disconnect *func*) """ cid = self.cnt self.observers[cid] = func self.cnt += 1 return cid def disconnect(self, cid): """ Remove the observer with connection id *cid* Parameters ---------- cid : int Connection id of the observer to be removed """ try: del self.observers[cid] except KeyError: pass def reset(self): """Reset the slider to the initial value""" if self.val != self.valinit: self.set_val(self.valinit) class CheckButtons(AxesWidget): r""" A GUI neutral set of check buttons. For the check buttons to remain responsive you must keep a reference to this object. Connect to the CheckButtons with the `.on_clicked` method. Attributes ---------- ax : `~matplotlib.axes.Axes` The parent axes for the widget. labels : list of `.Text` rectangles : list of `.Rectangle` lines : list of (`.Line2D`, `.Line2D`) pairs List of lines for the x's in the check boxes. These lines exist for each box, but have ``set_visible(False)`` when its box is not checked. """ def __init__(self, ax, labels, actives=None): """ Add check buttons to `matplotlib.axes.Axes` instance *ax* Parameters ---------- ax : `~matplotlib.axes.Axes` The parent axes for the widget. labels : list of str The labels of the check buttons. actives : list of bool, optional The initial check states of the buttons. The list must have the same length as *labels*. If not given, all buttons are unchecked. """ AxesWidget.__init__(self, ax) ax.set_xticks([]) ax.set_yticks([]) ax.set_navigate(False) if actives is None: actives = [False] * len(labels) if len(labels) > 1: dy = 1. / (len(labels) + 1) ys = np.linspace(1 - dy, dy, len(labels)) else: dy = 0.25 ys = [0.5] axcolor = ax.get_facecolor() self.labels = [] self.lines = [] self.rectangles = [] lineparams = {'color': 'k', 'linewidth': 1.25, 'transform': ax.transAxes, 'solid_capstyle': 'butt'} for y, label, active in zip(ys, labels, actives): t = ax.text(0.25, y, label, transform=ax.transAxes, horizontalalignment='left', verticalalignment='center') w, h = dy / 2, dy / 2 x, y = 0.05, y - h / 2 p = Rectangle(xy=(x, y), width=w, height=h, edgecolor='black', facecolor=axcolor, transform=ax.transAxes) l1 = Line2D([x, x + w], [y + h, y], **lineparams) l2 = Line2D([x, x + w], [y, y + h], **lineparams) l1.set_visible(active) l2.set_visible(active) self.labels.append(t) self.rectangles.append(p) self.lines.append((l1, l2)) ax.add_patch(p) ax.add_line(l1) ax.add_line(l2) self.connect_event('button_press_event', self._clicked) self.cnt = 0 self.observers = {} def _clicked(self, event): if self.ignore(event) or event.button != 1 or event.inaxes != self.ax: return for i, (p, t) in enumerate(zip(self.rectangles, self.labels)): if (t.get_window_extent().contains(event.x, event.y) or p.get_window_extent().contains(event.x, event.y)): self.set_active(i) break def set_active(self, index): """ Toggle (activate or deactivate) a check button by index. Callbacks will be triggered if :attr:`eventson` is True. Parameters ---------- index : int Index of the check button to toggle. Raises ------ ValueError If *index* is invalid. """ if not 0 <= index < len(self.labels): raise ValueError("Invalid CheckButton index: %d" % index) l1, l2 = self.lines[index] l1.set_visible(not l1.get_visible()) l2.set_visible(not l2.get_visible()) if self.drawon: self.ax.figure.canvas.draw() if not self.eventson: return for cid, func in self.observers.items(): func(self.labels[index].get_text()) def get_status(self): """ Return a tuple of the status (True/False) of all of the check buttons. """ return [l1.get_visible() for (l1, l2) in self.lines] def on_clicked(self, func): """ Connect the callback function *func* to button click events. Returns a connection id, which can be used to disconnect the callback. """ cid = self.cnt self.observers[cid] = func self.cnt += 1 return cid def disconnect(self, cid): """Remove the observer with connection id *cid*.""" try: del self.observers[cid] except KeyError: pass class TextBox(AxesWidget): """ A GUI neutral text input box. For the text box to remain responsive you must keep a reference to it. Call `.on_text_change` to be updated whenever the text changes. Call `.on_submit` to be updated whenever the user hits enter or leaves the text entry field. Attributes ---------- ax : `~matplotlib.axes.Axes` The parent axes for the widget. label : `.Text` color : color The color of the text box when not hovering. hovercolor : color The color of the text box when hovering. """ @cbook.deprecated("3.3") @property def params_to_disable(self): return [key for key in mpl.rcParams if 'keymap' in key] def __init__(self, ax, label, initial='', color='.95', hovercolor='1', label_pad=.01): """ Parameters ---------- ax : `~matplotlib.axes.Axes` The `~.axes.Axes` instance the button will be placed into. label : str Label for this text box. initial : str Initial value in the text box. color : color The color of the box. hovercolor : color The color of the box when the mouse is over it. label_pad : float The distance between the label and the right side of the textbox. """ AxesWidget.__init__(self, ax) self.DIST_FROM_LEFT = .05 self.label = ax.text( -label_pad, 0.5, label, transform=ax.transAxes, verticalalignment='center', horizontalalignment='right') self.text_disp = self.ax.text( self.DIST_FROM_LEFT, 0.5, initial, transform=self.ax.transAxes, verticalalignment='center', horizontalalignment='left') self.cnt = 0 self.change_observers = {} self.submit_observers = {} ax.set( xlim=(0, 1), ylim=(0, 1), # s.t. cursor appears from first click. navigate=False, facecolor=color, xticks=[], yticks=[]) self.cursor_index = 0 self.cursor = ax.vlines(0, 0, 0, visible=False, transform=mpl.transforms.IdentityTransform()) self.connect_event('button_press_event', self._click) self.connect_event('button_release_event', self._release) self.connect_event('motion_notify_event', self._motion) self.connect_event('key_press_event', self._keypress) self.connect_event('resize_event', self._resize) self.color = color self.hovercolor = hovercolor self.capturekeystrokes = False @property def text(self): return self.text_disp.get_text() def _rendercursor(self): # this is a hack to figure out where the cursor should go. # we draw the text up to where the cursor should go, measure # and save its dimensions, draw the real text, then put the cursor # at the saved dimensions # This causes a single extra draw if the figure has never been rendered # yet, which should be fine as we're going to repeatedly re-render the # figure later anyways. if self.ax.figure._cachedRenderer is None: self.ax.figure.canvas.draw() text = self.text_disp.get_text() # Save value before overwriting it. widthtext = text[:self.cursor_index] self.text_disp.set_text(widthtext or ",") bb = self.text_disp.get_window_extent() if not widthtext: # Use the comma for the height, but keep width to 0. bb.x1 = bb.x0 self.cursor.set( segments=[[(bb.x1, bb.y0), (bb.x1, bb.y1)]], visible=True) self.text_disp.set_text(text) self.ax.figure.canvas.draw() def _notify_submit_observers(self): if self.eventson: for cid, func in self.submit_observers.items(): func(self.text) def _release(self, event): if self.ignore(event): return if event.canvas.mouse_grabber != self.ax: return event.canvas.release_mouse(self.ax) def _keypress(self, event): if self.ignore(event): return if self.capturekeystrokes: key = event.key text = self.text if len(key) == 1: text = (text[:self.cursor_index] + key + text[self.cursor_index:]) self.cursor_index += 1 elif key == "right": if self.cursor_index != len(text): self.cursor_index += 1 elif key == "left": if self.cursor_index != 0: self.cursor_index -= 1 elif key == "home": self.cursor_index = 0 elif key == "end": self.cursor_index = len(text) elif key == "backspace": if self.cursor_index != 0: text = (text[:self.cursor_index - 1] + text[self.cursor_index:]) self.cursor_index -= 1 elif key == "delete": if self.cursor_index != len(self.text): text = (text[:self.cursor_index] + text[self.cursor_index + 1:]) self.text_disp.set_text(text) self._rendercursor() self._notify_change_observers() if key == "enter": self._notify_submit_observers() def set_val(self, val): newval = str(val) if self.text == newval: return self.text_disp.set_text(newval) self._rendercursor() self._notify_change_observers() self._notify_submit_observers() def _notify_change_observers(self): if self.eventson: for cid, func in self.change_observers.items(): func(self.text) def begin_typing(self, x): self.capturekeystrokes = True # Disable keypress shortcuts, which may otherwise cause the figure to # be saved, closed, etc., until the user stops typing. The way to # achieve this depends on whether toolmanager is in use. stack = ExitStack() # Register cleanup actions when user stops typing. self._on_stop_typing = stack.close toolmanager = getattr( self.ax.figure.canvas.manager, "toolmanager", None) if toolmanager is not None: # If using toolmanager, lock keypresses, and plan to release the # lock when typing stops. toolmanager.keypresslock(self) stack.push(toolmanager.keypresslock.release, self) else: # If not using toolmanager, disable all keypress-related rcParams. # Avoid spurious warnings if keymaps are getting deprecated. with cbook._suppress_matplotlib_deprecation_warning(): stack.enter_context(mpl.rc_context( {k: [] for k in mpl.rcParams if k.startswith("keymap.")})) def stop_typing(self): if self.capturekeystrokes: self._on_stop_typing() self._on_stop_typing = None notifysubmit = True else: notifysubmit = False self.capturekeystrokes = False self.cursor.set_visible(False) self.ax.figure.canvas.draw() if notifysubmit: # Because _notify_submit_observers might throw an error in the # user's code, only call it once we've already done our cleanup. self._notify_submit_observers() def position_cursor(self, x): # now, we have to figure out where the cursor goes. # approximate it based on assuming all characters the same length if len(self.text) == 0: self.cursor_index = 0 else: bb = self.text_disp.get_window_extent() ratio = np.clip((x - bb.x0) / bb.width, 0, 1) self.cursor_index = int(len(self.text) * ratio) self._rendercursor() def _click(self, event): if self.ignore(event): return if event.inaxes != self.ax: self.stop_typing() return if not self.eventson: return if event.canvas.mouse_grabber != self.ax: event.canvas.grab_mouse(self.ax) if not self.capturekeystrokes: self.begin_typing(event.x) self.position_cursor(event.x) def _resize(self, event): self.stop_typing() def _motion(self, event): if self.ignore(event): return c = self.hovercolor if event.inaxes == self.ax else self.color if c != self.ax.get_facecolor(): self.ax.set_facecolor(c) if self.drawon: self.ax.figure.canvas.draw() def on_text_change(self, func): """ When the text changes, call this *func* with event. A connection id is returned which can be used to disconnect. """ cid = self.cnt self.change_observers[cid] = func self.cnt += 1 return cid def on_submit(self, func): """ When the user hits enter or leaves the submission box, call this *func* with event. A connection id is returned which can be used to disconnect. """ cid = self.cnt self.submit_observers[cid] = func self.cnt += 1 return cid def disconnect(self, cid): """Remove the observer with connection id *cid*.""" for reg in [self.change_observers, self.submit_observers]: try: del reg[cid] except KeyError: pass class RadioButtons(AxesWidget): """ A GUI neutral radio button. For the buttons to remain responsive you must keep a reference to this object. Connect to the RadioButtons with the `.on_clicked` method. Attributes ---------- ax : `~matplotlib.axes.Axes` The parent axes for the widget. activecolor : color The color of the selected button. labels : list of `.Text` The button labels. circles : list of `~.patches.Circle` The buttons. value_selected : str The label text of the currently selected button. """ def __init__(self, ax, labels, active=0, activecolor='blue'): """ Add radio buttons to an `~.axes.Axes`. Parameters ---------- ax : `~matplotlib.axes.Axes` The axes to add the buttons to. labels : list of str The button labels. active : int The index of the initially selected button. activecolor : color The color of the selected button. """ AxesWidget.__init__(self, ax) self.activecolor = activecolor self.value_selected = None ax.set_xticks([]) ax.set_yticks([]) ax.set_navigate(False) dy = 1. / (len(labels) + 1) ys = np.linspace(1 - dy, dy, len(labels)) cnt = 0 axcolor = ax.get_facecolor() # scale the radius of the circle with the spacing between each one circle_radius = dy / 2 - 0.01 # default to hard-coded value if the radius becomes too large circle_radius = min(circle_radius, 0.05) self.labels = [] self.circles = [] for y, label in zip(ys, labels): t = ax.text(0.25, y, label, transform=ax.transAxes, horizontalalignment='left', verticalalignment='center') if cnt == active: self.value_selected = label facecolor = activecolor else: facecolor = axcolor p = Circle(xy=(0.15, y), radius=circle_radius, edgecolor='black', facecolor=facecolor, transform=ax.transAxes) self.labels.append(t) self.circles.append(p) ax.add_patch(p) cnt += 1 self.connect_event('button_press_event', self._clicked) self.cnt = 0 self.observers = {} def _clicked(self, event): if self.ignore(event) or event.button != 1 or event.inaxes != self.ax: return pclicked = self.ax.transAxes.inverted().transform((event.x, event.y)) distances = {} for i, (p, t) in enumerate(zip(self.circles, self.labels)): if (t.get_window_extent().contains(event.x, event.y) or np.linalg.norm(pclicked - p.center) < p.radius): distances[i] = np.linalg.norm(pclicked - p.center) if len(distances) > 0: closest = min(distances, key=distances.get) self.set_active(closest) def set_active(self, index): """ Select button with number *index*. Callbacks will be triggered if :attr:`eventson` is True. """ if 0 > index >= len(self.labels): raise ValueError("Invalid RadioButton index: %d" % index) self.value_selected = self.labels[index].get_text() for i, p in enumerate(self.circles): if i == index: color = self.activecolor else: color = self.ax.get_facecolor() p.set_facecolor(color) if self.drawon: self.ax.figure.canvas.draw() if not self.eventson: return for cid, func in self.observers.items(): func(self.labels[index].get_text()) def on_clicked(self, func): """ Connect the callback function *func* to button click events. Returns a connection id, which can be used to disconnect the callback. """ cid = self.cnt self.observers[cid] = func self.cnt += 1 return cid def disconnect(self, cid): """Remove the observer with connection id *cid*.""" try: del self.observers[cid] except KeyError: pass class SubplotTool(Widget): """ A tool to adjust the subplot params of a `matplotlib.figure.Figure`. """ def __init__(self, targetfig, toolfig): """ Parameters ---------- targetfig : `.Figure` The figure instance to adjust. toolfig : `.Figure` The figure instance to embed the subplot tool into. """ self.targetfig = targetfig toolfig.subplots_adjust(left=0.2, right=0.9) toolfig.suptitle("Click on slider to adjust subplot param") self._sliders = [] names = ["left", "bottom", "right", "top", "wspace", "hspace"] # The last subplot, removed below, keeps space for the "Reset" button. for name, ax in zip(names, toolfig.subplots(len(names) + 1)): ax.set_navigate(False) slider = Slider(ax, name, 0, 1, getattr(targetfig.subplotpars, name)) slider.on_changed(self._on_slider_changed) self._sliders.append(slider) toolfig.axes[-1].remove() (self.sliderleft, self.sliderbottom, self.sliderright, self.slidertop, self.sliderwspace, self.sliderhspace) = self._sliders for slider in [self.sliderleft, self.sliderbottom, self.sliderwspace, self.sliderhspace]: slider.closedmax = False for slider in [self.sliderright, self.slidertop]: slider.closedmin = False # constraints self.sliderleft.slidermax = self.sliderright self.sliderright.slidermin = self.sliderleft self.sliderbottom.slidermax = self.slidertop self.slidertop.slidermin = self.sliderbottom bax = toolfig.add_axes([0.8, 0.05, 0.15, 0.075]) self.buttonreset = Button(bax, 'Reset') # During reset there can be a temporary invalid state depending on the # order of the reset so we turn off validation for the resetting with cbook._setattr_cm(toolfig.subplotpars, validate=False): self.buttonreset.on_clicked(self._on_reset) def _on_slider_changed(self, _): self.targetfig.subplots_adjust( **{slider.label.get_text(): slider.val for slider in self._sliders}) if self.drawon: self.targetfig.canvas.draw() def _on_reset(self, event): with ExitStack() as stack: # Temporarily disable drawing on self and self's sliders. stack.enter_context(cbook._setattr_cm(self, drawon=False)) for slider in self._sliders: stack.enter_context(cbook._setattr_cm(slider, drawon=False)) # Reset the slider to the initial position. for slider in self._sliders: slider.reset() # Draw the canvas. if self.drawon: event.canvas.draw() self.targetfig.canvas.draw() axleft = cbook.deprecated("3.3", name="axleft")( property(lambda self: self.sliderleft.ax)) axright = cbook.deprecated("3.3", name="axright")( property(lambda self: self.sliderright.ax)) axbottom = cbook.deprecated("3.3", name="axbottom")( property(lambda self: self.sliderbottom.ax)) axtop = cbook.deprecated("3.3", name="axtop")( property(lambda self: self.slidertop.ax)) axwspace = cbook.deprecated("3.3", name="axwspace")( property(lambda self: self.sliderwspace.ax)) axhspace = cbook.deprecated("3.3", name="axhspace")( property(lambda self: self.sliderhspace.ax)) @cbook.deprecated("3.3") def funcleft(self, val): self.targetfig.subplots_adjust(left=val) if self.drawon: self.targetfig.canvas.draw() @cbook.deprecated("3.3") def funcright(self, val): self.targetfig.subplots_adjust(right=val) if self.drawon: self.targetfig.canvas.draw() @cbook.deprecated("3.3") def funcbottom(self, val): self.targetfig.subplots_adjust(bottom=val) if self.drawon: self.targetfig.canvas.draw() @cbook.deprecated("3.3") def functop(self, val): self.targetfig.subplots_adjust(top=val) if self.drawon: self.targetfig.canvas.draw() @cbook.deprecated("3.3") def funcwspace(self, val): self.targetfig.subplots_adjust(wspace=val) if self.drawon: self.targetfig.canvas.draw() @cbook.deprecated("3.3") def funchspace(self, val): self.targetfig.subplots_adjust(hspace=val) if self.drawon: self.targetfig.canvas.draw() class Cursor(AxesWidget): """ A crosshair cursor that spans the axes and moves with mouse cursor. For the cursor to remain responsive you must keep a reference to it. Parameters ---------- ax : `matplotlib.axes.Axes` The `~.axes.Axes` to attach the cursor to. horizOn : bool, default: True Whether to draw the horizontal line. vertOn : bool, default: True Whether to draw the vertical line. useblit : bool, default: False Use blitting for faster drawing if supported by the backend. Other Parameters ---------------- **lineprops `.Line2D` properties that control the appearance of the lines. See also `~.Axes.axhline`. Examples -------- See :doc:`/gallery/widgets/cursor`. """ def __init__(self, ax, horizOn=True, vertOn=True, useblit=False, **lineprops): AxesWidget.__init__(self, ax) self.connect_event('motion_notify_event', self.onmove) self.connect_event('draw_event', self.clear) self.visible = True self.horizOn = horizOn self.vertOn = vertOn self.useblit = useblit and self.canvas.supports_blit if self.useblit: lineprops['animated'] = True self.lineh = ax.axhline(ax.get_ybound()[0], visible=False, **lineprops) self.linev = ax.axvline(ax.get_xbound()[0], visible=False, **lineprops) self.background = None self.needclear = False def clear(self, event): """Internal event handler to clear the cursor.""" if self.ignore(event): return if self.useblit: self.background = self.canvas.copy_from_bbox(self.ax.bbox) self.linev.set_visible(False) self.lineh.set_visible(False) def onmove(self, event): """Internal event handler to draw the cursor when the mouse moves.""" if self.ignore(event): return if not self.canvas.widgetlock.available(self): return if event.inaxes != self.ax: self.linev.set_visible(False) self.lineh.set_visible(False) if self.needclear: self.canvas.draw() self.needclear = False return self.needclear = True if not self.visible: return self.linev.set_xdata((event.xdata, event.xdata)) self.lineh.set_ydata((event.ydata, event.ydata)) self.linev.set_visible(self.visible and self.vertOn) self.lineh.set_visible(self.visible and self.horizOn) self._update() def _update(self): if self.useblit: if self.background is not None: self.canvas.restore_region(self.background) self.ax.draw_artist(self.linev) self.ax.draw_artist(self.lineh) self.canvas.blit(self.ax.bbox) else: self.canvas.draw_idle() return False class MultiCursor(Widget): """ Provide a vertical (default) and/or horizontal line cursor shared between multiple axes. For the cursor to remain responsive you must keep a reference to it. Example usage:: from matplotlib.widgets import MultiCursor import matplotlib.pyplot as plt import numpy as np fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True) t = np.arange(0.0, 2.0, 0.01) ax1.plot(t, np.sin(2*np.pi*t)) ax2.plot(t, np.sin(4*np.pi*t)) multi = MultiCursor(fig.canvas, (ax1, ax2), color='r', lw=1, horizOn=False, vertOn=True) plt.show() """ def __init__(self, canvas, axes, useblit=True, horizOn=False, vertOn=True, **lineprops): self.canvas = canvas self.axes = axes self.horizOn = horizOn self.vertOn = vertOn xmin, xmax = axes[-1].get_xlim() ymin, ymax = axes[-1].get_ylim() xmid = 0.5 * (xmin + xmax) ymid = 0.5 * (ymin + ymax) self.visible = True self.useblit = useblit and self.canvas.supports_blit self.background = None self.needclear = False if self.useblit: lineprops['animated'] = True if vertOn: self.vlines = [ax.axvline(xmid, visible=False, **lineprops) for ax in axes] else: self.vlines = [] if horizOn: self.hlines = [ax.axhline(ymid, visible=False, **lineprops) for ax in axes] else: self.hlines = [] self.connect() def connect(self): """Connect events.""" self._cidmotion = self.canvas.mpl_connect('motion_notify_event', self.onmove) self._ciddraw = self.canvas.mpl_connect('draw_event', self.clear) def disconnect(self): """Disconnect events.""" self.canvas.mpl_disconnect(self._cidmotion) self.canvas.mpl_disconnect(self._ciddraw) def clear(self, event): """Clear the cursor.""" if self.ignore(event): return if self.useblit: self.background = ( self.canvas.copy_from_bbox(self.canvas.figure.bbox)) for line in self.vlines + self.hlines: line.set_visible(False) def onmove(self, event): if self.ignore(event): return if event.inaxes is None: return if not self.canvas.widgetlock.available(self): return self.needclear = True if not self.visible: return if self.vertOn: for line in self.vlines: line.set_xdata((event.xdata, event.xdata)) line.set_visible(self.visible) if self.horizOn: for line in self.hlines: line.set_ydata((event.ydata, event.ydata)) line.set_visible(self.visible) self._update() def _update(self): if self.useblit: if self.background is not None: self.canvas.restore_region(self.background) if self.vertOn: for ax, line in zip(self.axes, self.vlines): ax.draw_artist(line) if self.horizOn: for ax, line in zip(self.axes, self.hlines): ax.draw_artist(line) self.canvas.blit() else: self.canvas.draw_idle() class _SelectorWidget(AxesWidget): def __init__(self, ax, onselect, useblit=False, button=None, state_modifier_keys=None): AxesWidget.__init__(self, ax) self.visible = True self.onselect = onselect self.useblit = useblit and self.canvas.supports_blit self.connect_default_events() self.state_modifier_keys = dict(move=' ', clear='escape', square='shift', center='control') self.state_modifier_keys.update(state_modifier_keys or {}) self.background = None self.artists = [] if isinstance(button, Integral): self.validButtons = [button] else: self.validButtons = button # will save the data (position at mouseclick) self.eventpress = None # will save the data (pos. at mouserelease) self.eventrelease = None self._prev_event = None self.state = set() def set_active(self, active): AxesWidget.set_active(self, active) if active: self.update_background(None) def update_background(self, event): """Force an update of the background.""" # If you add a call to `ignore` here, you'll want to check edge case: # `release` can call a draw event even when `ignore` is True. if self.useblit: self.background = self.canvas.copy_from_bbox(self.ax.bbox) def connect_default_events(self): """Connect the major canvas events to methods.""" self.connect_event('motion_notify_event', self.onmove) self.connect_event('button_press_event', self.press) self.connect_event('button_release_event', self.release) self.connect_event('draw_event', self.update_background) self.connect_event('key_press_event', self.on_key_press) self.connect_event('key_release_event', self.on_key_release) self.connect_event('scroll_event', self.on_scroll) def ignore(self, event): # docstring inherited if not self.active or not self.ax.get_visible(): return True # If canvas was locked if not self.canvas.widgetlock.available(self): return True if not hasattr(event, 'button'): event.button = None # Only do rectangle selection if event was triggered # with a desired button if (self.validButtons is not None and event.button not in self.validButtons): return True # If no button was pressed yet ignore the event if it was out # of the axes if self.eventpress is None: return event.inaxes != self.ax # If a button was pressed, check if the release-button is the same. if event.button == self.eventpress.button: return False # If a button was pressed, check if the release-button is the same. return (event.inaxes != self.ax or event.button != self.eventpress.button) def update(self): """Draw using blit() or draw_idle(), depending on ``self.useblit``.""" if not self.ax.get_visible(): return False if self.useblit: if self.background is not None: self.canvas.restore_region(self.background) for artist in self.artists: self.ax.draw_artist(artist) self.canvas.blit(self.ax.bbox) else: self.canvas.draw_idle() return False def _get_data(self, event): """Get the xdata and ydata for event, with limits.""" if event.xdata is None: return None, None xdata = np.clip(event.xdata, *self.ax.get_xbound()) ydata = np.clip(event.ydata, *self.ax.get_ybound()) return xdata, ydata def _clean_event(self, event): """ Preprocess an event: - Replace *event* by the previous event if *event* has no ``xdata``. - Clip ``xdata`` and ``ydata`` to the axes limits. - Update the previous event. """ if event.xdata is None: event = self._prev_event else: event = copy.copy(event) event.xdata, event.ydata = self._get_data(event) self._prev_event = event return event def press(self, event): """Button press handler and validator.""" if not self.ignore(event): event = self._clean_event(event) self.eventpress = event self._prev_event = event key = event.key or '' key = key.replace('ctrl', 'control') # move state is locked in on a button press if key == self.state_modifier_keys['move']: self.state.add('move') self._press(event) return True return False def _press(self, event): """Button press handler.""" def release(self, event): """Button release event handler and validator.""" if not self.ignore(event) and self.eventpress: event = self._clean_event(event) self.eventrelease = event self._release(event) self.eventpress = None self.eventrelease = None self.state.discard('move') return True return False def _release(self, event): """Button release event handler.""" def onmove(self, event): """Cursor move event handler and validator.""" if not self.ignore(event) and self.eventpress: event = self._clean_event(event) self._onmove(event) return True return False def _onmove(self, event): """Cursor move event handler.""" def on_scroll(self, event): """Mouse scroll event handler and validator.""" if not self.ignore(event): self._on_scroll(event) def _on_scroll(self, event): """Mouse scroll event handler.""" def on_key_press(self, event): """Key press event handler and validator for all selection widgets.""" if self.active: key = event.key or '' key = key.replace('ctrl', 'control') if key == self.state_modifier_keys['clear']: for artist in self.artists: artist.set_visible(False) self.update() return for (state, modifier) in self.state_modifier_keys.items(): if modifier in key: self.state.add(state) self._on_key_press(event) def _on_key_press(self, event): """Key press event handler - for widget-specific key press actions.""" def on_key_release(self, event): """Key release event handler and validator.""" if self.active: key = event.key or '' for (state, modifier) in self.state_modifier_keys.items(): if modifier in key: self.state.discard(state) self._on_key_release(event) def _on_key_release(self, event): """Key release event handler.""" def set_visible(self, visible): """Set the visibility of our artists.""" self.visible = visible for artist in self.artists: artist.set_visible(visible) class SpanSelector(_SelectorWidget): """ Visually select a min/max range on a single axis and call a function with those values. To guarantee that the selector remains responsive, keep a reference to it. In order to turn off the SpanSelector, set ``span_selector.active`` to False. To turn it back on, set it to True. Parameters ---------- ax : `matplotlib.axes.Axes` onselect : func(min, max), min/max are floats direction : {"horizontal", "vertical"} The direction along which to draw the span selector. minspan : float, default: None If selection is less than *minspan*, do not call *onselect*. useblit : bool, default: False If True, use the backend-dependent blitting features for faster canvas updates. rectprops : dict, default: None Dictionary of `matplotlib.patches.Patch` properties. onmove_callback : func(min, max), min/max are floats, default: None Called on mouse move while the span is being selected. span_stays : bool, default: False If True, the span stays visible after the mouse is released. button : `.MouseButton` or list of `.MouseButton` The mouse buttons which activate the span selector. Examples -------- >>> import matplotlib.pyplot as plt >>> import matplotlib.widgets as mwidgets >>> fig, ax = plt.subplots() >>> ax.plot([1, 2, 3], [10, 50, 100]) >>> def onselect(vmin, vmax): ... print(vmin, vmax) >>> rectprops = dict(facecolor='blue', alpha=0.5) >>> span = mwidgets.SpanSelector(ax, onselect, 'horizontal', ... rectprops=rectprops) >>> fig.show() See also: :doc:`/gallery/widgets/span_selector` """ def __init__(self, ax, onselect, direction, minspan=None, useblit=False, rectprops=None, onmove_callback=None, span_stays=False, button=None): _SelectorWidget.__init__(self, ax, onselect, useblit=useblit, button=button) if rectprops is None: rectprops = dict(facecolor='red', alpha=0.5) rectprops['animated'] = self.useblit cbook._check_in_list(['horizontal', 'vertical'], direction=direction) self.direction = direction self.rect = None self.pressv = None self.rectprops = rectprops self.onmove_callback = onmove_callback self.minspan = minspan self.span_stays = span_stays # Needed when dragging out of axes self.prev = (0, 0) # Reset canvas so that `new_axes` connects events. self.canvas = None self.new_axes(ax) def new_axes(self, ax): """Set SpanSelector to operate on a new Axes.""" self.ax = ax if self.canvas is not ax.figure.canvas: if self.canvas is not None: self.disconnect_events() self.canvas = ax.figure.canvas self.connect_default_events() if self.direction == 'horizontal': trans = blended_transform_factory(self.ax.transData, self.ax.transAxes) w, h = 0, 1 else: trans = blended_transform_factory(self.ax.transAxes, self.ax.transData) w, h = 1, 0 self.rect = Rectangle((0, 0), w, h, transform=trans, visible=False, **self.rectprops) if self.span_stays: self.stay_rect = Rectangle((0, 0), w, h, transform=trans, visible=False, **self.rectprops) self.stay_rect.set_animated(False) self.ax.add_patch(self.stay_rect) self.ax.add_patch(self.rect) self.artists = [self.rect] def ignore(self, event): # docstring inherited return _SelectorWidget.ignore(self, event) or not self.visible def _press(self, event): """on button press event""" self.rect.set_visible(self.visible) if self.span_stays: self.stay_rect.set_visible(False) # really force a draw so that the stay rect is not in # the blit background if self.useblit: self.canvas.draw() xdata, ydata = self._get_data(event) if self.direction == 'horizontal': self.pressv = xdata else: self.pressv = ydata self._set_span_xy(event) return False def _release(self, event): """on button release event""" if self.pressv is None: return self.rect.set_visible(False) if self.span_stays: self.stay_rect.set_x(self.rect.get_x()) self.stay_rect.set_y(self.rect.get_y()) self.stay_rect.set_width(self.rect.get_width()) self.stay_rect.set_height(self.rect.get_height()) self.stay_rect.set_visible(True) self.canvas.draw_idle() vmin = self.pressv xdata, ydata = self._get_data(event) if self.direction == 'horizontal': vmax = xdata or self.prev[0] else: vmax = ydata or self.prev[1] if vmin > vmax: vmin, vmax = vmax, vmin span = vmax - vmin if self.minspan is not None and span < self.minspan: return self.onselect(vmin, vmax) self.pressv = None return False def _onmove(self, event): """on motion notify event""" if self.pressv is None: return self._set_span_xy(event) if self.onmove_callback is not None: vmin = self.pressv xdata, ydata = self._get_data(event) if self.direction == 'horizontal': vmax = xdata or self.prev[0] else: vmax = ydata or self.prev[1] if vmin > vmax: vmin, vmax = vmax, vmin self.onmove_callback(vmin, vmax) self.update() return False def _set_span_xy(self, event): """Set the span coordinates.""" x, y = self._get_data(event) if x is None: return self.prev = x, y if self.direction == 'horizontal': v = x else: v = y minv, maxv = v, self.pressv if minv > maxv: minv, maxv = maxv, minv if self.direction == 'horizontal': self.rect.set_x(minv) self.rect.set_width(maxv - minv) else: self.rect.set_y(minv) self.rect.set_height(maxv - minv) class ToolHandles: """ Control handles for canvas tools. Parameters ---------- ax : `matplotlib.axes.Axes` Matplotlib axes where tool handles are displayed. x, y : 1D arrays Coordinates of control handles. marker : str Shape of marker used to display handle. See `matplotlib.pyplot.plot`. marker_props : dict Additional marker properties. See `matplotlib.lines.Line2D`. """ def __init__(self, ax, x, y, marker='o', marker_props=None, useblit=True): self.ax = ax props = dict(marker=marker, markersize=7, mfc='w', ls='none', alpha=0.5, visible=False, label='_nolegend_') props.update(marker_props if marker_props is not None else {}) self._markers = Line2D(x, y, animated=useblit, **props) self.ax.add_line(self._markers) self.artist = self._markers @property def x(self): return self._markers.get_xdata() @property def y(self): return self._markers.get_ydata() def set_data(self, pts, y=None): """Set x and y positions of handles""" if y is not None: x = pts pts = np.array([x, y]) self._markers.set_data(pts) def set_visible(self, val): self._markers.set_visible(val) def set_animated(self, val): self._markers.set_animated(val) def closest(self, x, y): """Return index and pixel distance to closest index.""" pts = np.column_stack([self.x, self.y]) # Transform data coordinates to pixel coordinates. pts = self.ax.transData.transform(pts) diff = pts - [x, y] dist = np.hypot(*diff.T) min_index = np.argmin(dist) return min_index, dist[min_index] class RectangleSelector(_SelectorWidget): """ Select a rectangular region of an axes. For the cursor to remain responsive you must keep a reference to it. Examples -------- :doc:`/gallery/widgets/rectangle_selector` """ _shape_klass = Rectangle def __init__(self, ax, onselect, drawtype='box', minspanx=0, minspany=0, useblit=False, lineprops=None, rectprops=None, spancoords='data', button=None, maxdist=10, marker_props=None, interactive=False, state_modifier_keys=None): r""" Parameters ---------- ax : `~matplotlib.axes.Axes` The parent axes for the widget. onselect : function A callback function that is called after a selection is completed. It must have the signature:: def onselect(eclick: MouseEvent, erelease: MouseEvent) where *eclick* and *erelease* are the mouse click and release `.MouseEvent`\s that start and complete the selection. drawtype : {"box", "line", "none"}, default: "box" Whether to draw the full rectangle box, the diagonal line of the rectangle, or nothing at all. minspanx : float, default: 0 Selections with an x-span less than *minspanx* are ignored. minspany : float, default: 0 Selections with an y-span less than *minspany* are ignored. useblit : bool, default: False Whether to use blitting for faster drawing (if supported by the backend). lineprops : dict, optional Properties with which the line is drawn, if ``drawtype == "line"``. Default:: dict(color="black", linestyle="-", linewidth=2, alpha=0.5) rectprops : dict, optional Properties with which the rectangle is drawn, if ``drawtype == "box"``. Default:: dict(facecolor="red", edgecolor="black", alpha=0.2, fill=True) spancoords : {"data", "pixels"}, default: "data" Whether to interpret *minspanx* and *minspany* in data or in pixel coordinates. button : `.MouseButton`, list of `.MouseButton`, default: all buttons Button(s) that trigger rectangle selection. maxdist : float, default: 10 Distance in pixels within which the interactive tool handles can be activated. marker_props : dict Properties with which the interactive handles are drawn. Currently not implemented and ignored. interactive : bool, default: False Whether to draw a set of handles that allow interaction with the widget after it is drawn. state_modifier_keys : dict, optional Keyboard modifiers which affect the widget's behavior. Values amend the defaults. - "move": Move the existing shape, default: no modifier. - "clear": Clear the current shape, default: "escape". - "square": Makes the shape square, default: "shift". - "center": Make the initial point the center of the shape, default: "ctrl". "square" and "center" can be combined. """ _SelectorWidget.__init__(self, ax, onselect, useblit=useblit, button=button, state_modifier_keys=state_modifier_keys) self.to_draw = None self.visible = True self.interactive = interactive if drawtype == 'none': # draw a line but make it invisible drawtype = 'line' self.visible = False if drawtype == 'box': if rectprops is None: rectprops = dict(facecolor='red', edgecolor='black', alpha=0.2, fill=True) rectprops['animated'] = self.useblit self.rectprops = rectprops self.to_draw = self._shape_klass((0, 0), 0, 1, visible=False, **self.rectprops) self.ax.add_patch(self.to_draw) if drawtype == 'line': if lineprops is None: lineprops = dict(color='black', linestyle='-', linewidth=2, alpha=0.5) lineprops['animated'] = self.useblit self.lineprops = lineprops self.to_draw = Line2D([0, 0], [0, 0], visible=False, **self.lineprops) self.ax.add_line(self.to_draw) self.minspanx = minspanx self.minspany = minspany cbook._check_in_list(['data', 'pixels'], spancoords=spancoords) self.spancoords = spancoords self.drawtype = drawtype self.maxdist = maxdist if rectprops is None: props = dict(mec='r') else: props = dict(mec=rectprops.get('edgecolor', 'r')) self._corner_order = ['NW', 'NE', 'SE', 'SW'] xc, yc = self.corners self._corner_handles = ToolHandles(self.ax, xc, yc, marker_props=props, useblit=self.useblit) self._edge_order = ['W', 'N', 'E', 'S'] xe, ye = self.edge_centers self._edge_handles = ToolHandles(self.ax, xe, ye, marker='s', marker_props=props, useblit=self.useblit) xc, yc = self.center self._center_handle = ToolHandles(self.ax, [xc], [yc], marker='s', marker_props=props, useblit=self.useblit) self.active_handle = None self.artists = [self.to_draw, self._center_handle.artist, self._corner_handles.artist, self._edge_handles.artist] if not self.interactive: self.artists = [self.to_draw] self._extents_on_press = None def _press(self, event): """on button press event""" # make the drawn box/line visible get the click-coordinates, # button, ... if self.interactive and self.to_draw.get_visible(): self._set_active_handle(event) else: self.active_handle = None if self.active_handle is None or not self.interactive: # Clear previous rectangle before drawing new rectangle. self.update() if not self.interactive: x = event.xdata y = event.ydata self.extents = x, x, y, y self.set_visible(self.visible) def _release(self, event): """on button release event""" if not self.interactive: self.to_draw.set_visible(False) # update the eventpress and eventrelease with the resulting extents x1, x2, y1, y2 = self.extents self.eventpress.xdata = x1 self.eventpress.ydata = y1 xy1 = self.ax.transData.transform([x1, y1]) self.eventpress.x, self.eventpress.y = xy1 self.eventrelease.xdata = x2 self.eventrelease.ydata = y2 xy2 = self.ax.transData.transform([x2, y2]) self.eventrelease.x, self.eventrelease.y = xy2 # calculate dimensions of box or line if self.spancoords == 'data': spanx = abs(self.eventpress.xdata - self.eventrelease.xdata) spany = abs(self.eventpress.ydata - self.eventrelease.ydata) elif self.spancoords == 'pixels': spanx = abs(self.eventpress.x - self.eventrelease.x) spany = abs(self.eventpress.y - self.eventrelease.y) else: cbook._check_in_list(['data', 'pixels'], spancoords=self.spancoords) # check if drawn distance (if it exists) is not too small in # either x or y-direction if (self.drawtype != 'none' and (self.minspanx is not None and spanx < self.minspanx or self.minspany is not None and spany < self.minspany)): for artist in self.artists: artist.set_visible(False) self.update() return # call desired function self.onselect(self.eventpress, self.eventrelease) self.update() return False def _onmove(self, event): """on motion notify event if box/line is wanted""" # resize an existing shape if self.active_handle and self.active_handle != 'C': x1, x2, y1, y2 = self._extents_on_press if self.active_handle in ['E', 'W'] + self._corner_order: x2 = event.xdata if self.active_handle in ['N', 'S'] + self._corner_order: y2 = event.ydata # move existing shape elif (('move' in self.state or self.active_handle == 'C') and self._extents_on_press is not None): x1, x2, y1, y2 = self._extents_on_press dx = event.xdata - self.eventpress.xdata dy = event.ydata - self.eventpress.ydata x1 += dx x2 += dx y1 += dy y2 += dy # new shape else: center = [self.eventpress.xdata, self.eventpress.ydata] center_pix = [self.eventpress.x, self.eventpress.y] dx = (event.xdata - center[0]) / 2. dy = (event.ydata - center[1]) / 2. # square shape if 'square' in self.state: dx_pix = abs(event.x - center_pix[0]) dy_pix = abs(event.y - center_pix[1]) if not dx_pix: return maxd = max(abs(dx_pix), abs(dy_pix)) if abs(dx_pix) < maxd: dx *= maxd / (abs(dx_pix) + 1e-6) if abs(dy_pix) < maxd: dy *= maxd / (abs(dy_pix) + 1e-6) # from center if 'center' in self.state: dx *= 2 dy *= 2 # from corner else: center[0] += dx center[1] += dy x1, x2, y1, y2 = (center[0] - dx, center[0] + dx, center[1] - dy, center[1] + dy) self.extents = x1, x2, y1, y2 @property def _rect_bbox(self): if self.drawtype == 'box': x0 = self.to_draw.get_x() y0 = self.to_draw.get_y() width = self.to_draw.get_width() height = self.to_draw.get_height() return x0, y0, width, height else: x, y = self.to_draw.get_data() x0, x1 = min(x), max(x) y0, y1 = min(y), max(y) return x0, y0, x1 - x0, y1 - y0 @property def corners(self): """Corners of rectangle from lower left, moving clockwise.""" x0, y0, width, height = self._rect_bbox xc = x0, x0 + width, x0 + width, x0 yc = y0, y0, y0 + height, y0 + height return xc, yc @property def edge_centers(self): """Midpoint of rectangle edges from left, moving clockwise.""" x0, y0, width, height = self._rect_bbox w = width / 2. h = height / 2. xe = x0, x0 + w, x0 + width, x0 + w ye = y0 + h, y0, y0 + h, y0 + height return xe, ye @property def center(self): """Center of rectangle""" x0, y0, width, height = self._rect_bbox return x0 + width / 2., y0 + height / 2. @property def extents(self): """Return (xmin, xmax, ymin, ymax).""" x0, y0, width, height = self._rect_bbox xmin, xmax = sorted([x0, x0 + width]) ymin, ymax = sorted([y0, y0 + height]) return xmin, xmax, ymin, ymax @extents.setter def extents(self, extents): # Update displayed shape self.draw_shape(extents) # Update displayed handles self._corner_handles.set_data(*self.corners) self._edge_handles.set_data(*self.edge_centers) self._center_handle.set_data(*self.center) self.set_visible(self.visible) self.update() def draw_shape(self, extents): x0, x1, y0, y1 = extents xmin, xmax = sorted([x0, x1]) ymin, ymax = sorted([y0, y1]) xlim = sorted(self.ax.get_xlim()) ylim = sorted(self.ax.get_ylim()) xmin = max(xlim[0], xmin) ymin = max(ylim[0], ymin) xmax = min(xmax, xlim[1]) ymax = min(ymax, ylim[1]) if self.drawtype == 'box': self.to_draw.set_x(xmin) self.to_draw.set_y(ymin) self.to_draw.set_width(xmax - xmin) self.to_draw.set_height(ymax - ymin) elif self.drawtype == 'line': self.to_draw.set_data([xmin, xmax], [ymin, ymax]) def _set_active_handle(self, event): """Set active handle based on the location of the mouse event""" # Note: event.xdata/ydata in data coordinates, event.x/y in pixels c_idx, c_dist = self._corner_handles.closest(event.x, event.y) e_idx, e_dist = self._edge_handles.closest(event.x, event.y) m_idx, m_dist = self._center_handle.closest(event.x, event.y) if 'move' in self.state: self.active_handle = 'C' self._extents_on_press = self.extents # Set active handle as closest handle, if mouse click is close enough. elif m_dist < self.maxdist * 2: self.active_handle = 'C' elif c_dist > self.maxdist and e_dist > self.maxdist: self.active_handle = None return elif c_dist < e_dist: self.active_handle = self._corner_order[c_idx] else: self.active_handle = self._edge_order[e_idx] # Save coordinates of rectangle at the start of handle movement. x1, x2, y1, y2 = self.extents # Switch variables so that only x2 and/or y2 are updated on move. if self.active_handle in ['W', 'SW', 'NW']: x1, x2 = x2, event.xdata if self.active_handle in ['N', 'NW', 'NE']: y1, y2 = y2, event.ydata self._extents_on_press = x1, x2, y1, y2 @property def geometry(self): """ Return an array of shape (2, 5) containing the x (``RectangleSelector.geometry[1, :]``) and y (``RectangleSelector.geometry[0, :]``) coordinates of the four corners of the rectangle starting and ending in the top left corner. """ if hasattr(self.to_draw, 'get_verts'): xfm = self.ax.transData.inverted() y, x = xfm.transform(self.to_draw.get_verts()).T return np.array([x, y]) else: return np.array(self.to_draw.get_data()) class EllipseSelector(RectangleSelector): """ Select an elliptical region of an axes. For the cursor to remain responsive you must keep a reference to it. Example usage:: import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import EllipseSelector def onselect(eclick, erelease): "eclick and erelease are matplotlib events at press and release." print('startposition: (%f, %f)' % (eclick.xdata, eclick.ydata)) print('endposition : (%f, %f)' % (erelease.xdata, erelease.ydata)) print('used button : ', eclick.button) def toggle_selector(event): print(' Key pressed.') if event.key in ['Q', 'q'] and toggle_selector.ES.active: print('EllipseSelector deactivated.') toggle_selector.RS.set_active(False) if event.key in ['A', 'a'] and not toggle_selector.ES.active: print('EllipseSelector activated.') toggle_selector.ES.set_active(True) x = np.arange(100.) / 99 y = np.sin(x) fig, ax = plt.subplots() ax.plot(x, y) toggle_selector.ES = EllipseSelector(ax, onselect, drawtype='line') fig.canvas.mpl_connect('key_press_event', toggle_selector) plt.show() """ _shape_klass = Ellipse def draw_shape(self, extents): x1, x2, y1, y2 = extents xmin, xmax = sorted([x1, x2]) ymin, ymax = sorted([y1, y2]) center = [x1 + (x2 - x1) / 2., y1 + (y2 - y1) / 2.] a = (xmax - xmin) / 2. b = (ymax - ymin) / 2. if self.drawtype == 'box': self.to_draw.center = center self.to_draw.width = 2 * a self.to_draw.height = 2 * b else: rad = np.deg2rad(np.arange(31) * 12) x = a * np.cos(rad) + center[0] y = b * np.sin(rad) + center[1] self.to_draw.set_data(x, y) @property def _rect_bbox(self): if self.drawtype == 'box': x, y = self.to_draw.center width = self.to_draw.width height = self.to_draw.height return x - width / 2., y - height / 2., width, height else: x, y = self.to_draw.get_data() x0, x1 = min(x), max(x) y0, y1 = min(y), max(y) return x0, y0, x1 - x0, y1 - y0 class LassoSelector(_SelectorWidget): """ Selection curve of an arbitrary shape. For the selector to remain responsive you must keep a reference to it. The selected path can be used in conjunction with `~.Path.contains_point` to select data points from an image. In contrast to `Lasso`, `LassoSelector` is written with an interface similar to `RectangleSelector` and `SpanSelector`, and will continue to interact with the axes until disconnected. Example usage:: ax = subplot(111) ax.plot(x, y) def onselect(verts): print(verts) lasso = LassoSelector(ax, onselect) Parameters ---------- ax : `~matplotlib.axes.Axes` The parent axes for the widget. onselect : function Whenever the lasso is released, the *onselect* function is called and passed the vertices of the selected path. button : `.MouseButton` or list of `.MouseButton`, optional The mouse buttons used for rectangle selection. Default is ``None``, which corresponds to all buttons. """ def __init__(self, ax, onselect=None, useblit=True, lineprops=None, button=None): _SelectorWidget.__init__(self, ax, onselect, useblit=useblit, button=button) self.verts = None if lineprops is None: lineprops = dict() # self.useblit may be != useblit, if the canvas doesn't support blit. lineprops.update(animated=self.useblit, visible=False) self.line = Line2D([], [], **lineprops) self.ax.add_line(self.line) self.artists = [self.line] def onpress(self, event): self.press(event) def _press(self, event): self.verts = [self._get_data(event)] self.line.set_visible(True) def onrelease(self, event): self.release(event) def _release(self, event): if self.verts is not None: self.verts.append(self._get_data(event)) self.onselect(self.verts) self.line.set_data([[], []]) self.line.set_visible(False) self.verts = None def _onmove(self, event): if self.verts is None: return self.verts.append(self._get_data(event)) self.line.set_data(list(zip(*self.verts))) self.update() class PolygonSelector(_SelectorWidget): """ Select a polygon region of an axes. Place vertices with each mouse click, and make the selection by completing the polygon (clicking on the first vertex). Hold the *ctrl* key and click and drag a vertex to reposition it (the *ctrl* key is not necessary if the polygon has already been completed). Hold the *shift* key and click and drag anywhere in the axes to move all vertices. Press the *esc* key to start a new polygon. For the selector to remain responsive you must keep a reference to it. Parameters ---------- ax : `~matplotlib.axes.Axes` The parent axes for the widget. onselect : function When a polygon is completed or modified after completion, the *onselect* function is called and passed a list of the vertices as ``(xdata, ydata)`` tuples. useblit : bool, default: False lineprops : dict, default: \ ``dict(color='k', linestyle='-', linewidth=2, alpha=0.5)``. Artist properties for the line representing the edges of the polygon. markerprops : dict, default: \ ``dict(marker='o', markersize=7, mec='k', mfc='k', alpha=0.5)``. Artist properties for the markers drawn at the vertices of the polygon. vertex_select_radius : float, default: 15px A vertex is selected (to complete the polygon or to move a vertex) if the mouse click is within *vertex_select_radius* pixels of the vertex. Examples -------- :doc:`/gallery/widgets/polygon_selector_demo` """ def __init__(self, ax, onselect, useblit=False, lineprops=None, markerprops=None, vertex_select_radius=15): # The state modifiers 'move', 'square', and 'center' are expected by # _SelectorWidget but are not supported by PolygonSelector # Note: could not use the existing 'move' state modifier in-place of # 'move_all' because _SelectorWidget automatically discards 'move' # from the state on button release. state_modifier_keys = dict(clear='escape', move_vertex='control', move_all='shift', move='not-applicable', square='not-applicable', center='not-applicable') _SelectorWidget.__init__(self, ax, onselect, useblit=useblit, state_modifier_keys=state_modifier_keys) self._xs, self._ys = [0], [0] self._polygon_completed = False if lineprops is None: lineprops = dict(color='k', linestyle='-', linewidth=2, alpha=0.5) lineprops['animated'] = self.useblit self.line = Line2D(self._xs, self._ys, **lineprops) self.ax.add_line(self.line) if markerprops is None: markerprops = dict(mec='k', mfc=lineprops.get('color', 'k')) self._polygon_handles = ToolHandles(self.ax, self._xs, self._ys, useblit=self.useblit, marker_props=markerprops) self._active_handle_idx = -1 self.vertex_select_radius = vertex_select_radius self.artists = [self.line, self._polygon_handles.artist] self.set_visible(True) def _press(self, event): """Button press event handler""" # Check for selection of a tool handle. if ((self._polygon_completed or 'move_vertex' in self.state) and len(self._xs) > 0): h_idx, h_dist = self._polygon_handles.closest(event.x, event.y) if h_dist < self.vertex_select_radius: self._active_handle_idx = h_idx # Save the vertex positions at the time of the press event (needed to # support the 'move_all' state modifier). self._xs_at_press, self._ys_at_press = self._xs.copy(), self._ys.copy() def _release(self, event): """Button release event handler""" # Release active tool handle. if self._active_handle_idx >= 0: self._active_handle_idx = -1 # Complete the polygon. elif (len(self._xs) > 3 and self._xs[-1] == self._xs[0] and self._ys[-1] == self._ys[0]): self._polygon_completed = True # Place new vertex. elif (not self._polygon_completed and 'move_all' not in self.state and 'move_vertex' not in self.state): self._xs.insert(-1, event.xdata) self._ys.insert(-1, event.ydata) if self._polygon_completed: self.onselect(self.verts) def onmove(self, event): """Cursor move event handler and validator""" # Method overrides _SelectorWidget.onmove because the polygon selector # needs to process the move callback even if there is no button press. # _SelectorWidget.onmove include logic to ignore move event if # eventpress is None. if not self.ignore(event): event = self._clean_event(event) self._onmove(event) return True return False def _onmove(self, event): """Cursor move event handler""" # Move the active vertex (ToolHandle). if self._active_handle_idx >= 0: idx = self._active_handle_idx self._xs[idx], self._ys[idx] = event.xdata, event.ydata # Also update the end of the polygon line if the first vertex is # the active handle and the polygon is completed. if idx == 0 and self._polygon_completed: self._xs[-1], self._ys[-1] = event.xdata, event.ydata # Move all vertices. elif 'move_all' in self.state and self.eventpress: dx = event.xdata - self.eventpress.xdata dy = event.ydata - self.eventpress.ydata for k in range(len(self._xs)): self._xs[k] = self._xs_at_press[k] + dx self._ys[k] = self._ys_at_press[k] + dy # Do nothing if completed or waiting for a move. elif (self._polygon_completed or 'move_vertex' in self.state or 'move_all' in self.state): return # Position pending vertex. else: # Calculate distance to the start vertex. x0, y0 = self.line.get_transform().transform((self._xs[0], self._ys[0])) v0_dist = np.hypot(x0 - event.x, y0 - event.y) # Lock on to the start vertex if near it and ready to complete. if len(self._xs) > 3 and v0_dist < self.vertex_select_radius: self._xs[-1], self._ys[-1] = self._xs[0], self._ys[0] else: self._xs[-1], self._ys[-1] = event.xdata, event.ydata self._draw_polygon() def _on_key_press(self, event): """Key press event handler""" # Remove the pending vertex if entering the 'move_vertex' or # 'move_all' mode if (not self._polygon_completed and ('move_vertex' in self.state or 'move_all' in self.state)): self._xs, self._ys = self._xs[:-1], self._ys[:-1] self._draw_polygon() def _on_key_release(self, event): """Key release event handler""" # Add back the pending vertex if leaving the 'move_vertex' or # 'move_all' mode (by checking the released key) if (not self._polygon_completed and (event.key == self.state_modifier_keys.get('move_vertex') or event.key == self.state_modifier_keys.get('move_all'))): self._xs.append(event.xdata) self._ys.append(event.ydata) self._draw_polygon() # Reset the polygon if the released key is the 'clear' key. elif event.key == self.state_modifier_keys.get('clear'): event = self._clean_event(event) self._xs, self._ys = [event.xdata], [event.ydata] self._polygon_completed = False self.set_visible(True) def _draw_polygon(self): """Redraw the polygon based on the new vertex positions.""" self.line.set_data(self._xs, self._ys) # Only show one tool handle at the start and end vertex of the polygon # if the polygon is completed or the user is locked on to the start # vertex. if (self._polygon_completed or (len(self._xs) > 3 and self._xs[-1] == self._xs[0] and self._ys[-1] == self._ys[0])): self._polygon_handles.set_data(self._xs[:-1], self._ys[:-1]) else: self._polygon_handles.set_data(self._xs, self._ys) self.update() @property def verts(self): """The polygon vertices, as a list of ``(x, y)`` pairs.""" return list(zip(self._xs[:-1], self._ys[:-1])) class Lasso(AxesWidget): """ Selection curve of an arbitrary shape. The selected path can be used in conjunction with `~matplotlib.path.Path.contains_point` to select data points from an image. Unlike `LassoSelector`, this must be initialized with a starting point *xy*, and the `Lasso` events are destroyed upon release. Parameters ---------- ax : `~matplotlib.axes.Axes` The parent axes for the widget. xy : (float, float) Coordinates of the start of the lasso. callback : callable Whenever the lasso is released, the *callback* function is called and passed the vertices of the selected path. """ def __init__(self, ax, xy, callback=None, useblit=True): AxesWidget.__init__(self, ax) self.useblit = useblit and self.canvas.supports_blit if self.useblit: self.background = self.canvas.copy_from_bbox(self.ax.bbox) x, y = xy self.verts = [(x, y)] self.line = Line2D([x], [y], linestyle='-', color='black', lw=2) self.ax.add_line(self.line) self.callback = callback self.connect_event('button_release_event', self.onrelease) self.connect_event('motion_notify_event', self.onmove) def onrelease(self, event): if self.ignore(event): return if self.verts is not None: self.verts.append((event.xdata, event.ydata)) if len(self.verts) > 2: self.callback(self.verts) self.ax.lines.remove(self.line) self.verts = None self.disconnect_events() def onmove(self, event): if self.ignore(event): return if self.verts is None: return if event.inaxes != self.ax: return if event.button != 1: return self.verts.append((event.xdata, event.ydata)) self.line.set_data(list(zip(*self.verts))) if self.useblit: self.canvas.restore_region(self.background) self.ax.draw_artist(self.line) self.canvas.blit(self.ax.bbox) else: self.canvas.draw_idle()
[ "mateuszwidomski@gmail.com" ]
mateuszwidomski@gmail.com
77f3ff8130c26af341c8b729917f9e72a76f9efd
d5481fc03a8b243312e5bcf67d44f6c7788a7081
/lab3/worker.py
d9356f7a9b79595fd64fea777a435f21889fb8b5
[]
no_license
yklym/databases-2
c2bea85f209cf4e2cb08517e335d43840674196f
af0304cb2fd3eeef34306e4d41f60d18f547008e
refs/heads/main
2023-05-22T07:59:20.097891
2021-06-11T21:11:37
2021-06-11T21:11:37
336,562,906
0
0
null
null
null
null
UTF-8
Python
false
false
1,117
py
from repositories.message import MessageRepository from random import randint from time import sleep from threading import Thread from services.subscription_listener import MessagesListener DELAY = randint(0, 2) class MessageWorker(Thread): def __init__(self): Thread.__init__(self) pass def run(self): while True: message = MessageRepository.get_next_queue_message() if message is None: continue self.process_message(message) def process_message(self, message): is_spam = MessageRepository.spam_message_check(message) sleep(DELAY) if is_spam: MessageRepository.on_message_spam(message) else: MessageRepository.on_message_not_spam(message) def main(): subs_listener = MessagesListener() subs_listener.setDaemon(True) subs_listener.start() workers_count = 5 for _ in range(workers_count): worker = MessageWorker() worker.daemon = True worker.start() while True: pass if __name__ == '__main__': main()
[ "yaroslav.klymenko@binary-studio.com" ]
yaroslav.klymenko@binary-studio.com
932b625e63adad142bdca9e8c62eab580df0d5a7
e780771189d3f64cddc667eaa87edbc0f10bdce4
/fit_mle_GenericLikelihoodModel_1vM1U.py
578e291a476c5b65cc2988cb6576280f74e928ca
[]
no_license
dfafalis/fiberDirectionality
fa442a1bb97910866a2260ef728e9890c616da6e
72289b23a2fb6d0dd32bf5c717ef86101aed3781
refs/heads/master
2021-04-26T23:20:02.914896
2018-11-16T19:44:59
2018-11-16T19:44:59
123,973,841
0
0
null
2018-03-05T20:34:35
2018-03-05T20:21:07
null
UTF-8
Python
false
false
5,033
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 30 16:49:27 2018 Author Dimitrios Fafalis This code makes use of the "GenericLikelihoodModel" subclass of the package statsmodels, to fit random variables to a mixture model of one von Mises on the CIRCLE and one Uniform distribution. Its generalization to mixtures of von Mises and Uniform distributions has failed, at least to my attempts! @author: df """ import math import numpy as np from scipy import stats from statsmodels.base.model import GenericLikelihoodModel import matplotlib.pyplot as plt import dff_dispersionCalculator as dC #import dff_StatsTools as dfst # ---------------------------------------------------------------------- # # generate random variables from a mixture of von Mises and \ # uniform distributions: # size of sample: N = 1000 # parameters for the von Mises member: p_ = 0.8 # weight contribution of von Mises kappa_ = np.array((10.0)) # concentration for von Mises member loc_ = 0.*np.pi/2.0 # location for von Mises member loc_cs = np.array(( np.cos(loc_), np.sin(loc_) )) # cos and sin of location print('loc_cs = ',loc_cs) #XX_ = stats.vonmises(kappa_, loc_) #XX_samples = XX_.rvs(N) #dfst.plot_dist_samples(XX_, XX_samples, title=None, ax=None) #fig, ax = plt.subplots(1, 1, figsize=(9,3)) #ax.hist( XX_samples, bins=75, density=True ); #ax.set_title('Random sample from mixture of von Mises and Uniform distriburtions') # ---------------------------------------------------------------------- # # now generate the random sample: # "Creating a mixture of probability distributions for sampling" # a question on stackoverflow: # https://stackoverflow.com/questions/47759577/ # creating-a-mixture-of-probability-distributions-for-sampling xu_1 = -np.pi xu_2 = 2*np.pi distributions = [ { "type": stats.vonmises.rvs, "args": {"kappa":kappa_, "loc":loc_ } }, { "type": stats.uniform.rvs, "args": {"loc":xu_1, "scale":xu_2} } ] coefficients = np.array([p_, 1.-p_]) # these are the weights coefficients /= coefficients.sum() # in case these did not add up to 1 sample_size = N num_distr = len(distributions) data = np.zeros((sample_size, num_distr)) for idx, distr in enumerate(distributions): data[:, idx] = distr["type"]( **distr["args"], size=(sample_size,)) random_idx = np.random.choice( np.arange(num_distr), \ size=(sample_size,), p=coefficients ) X_samples = data[ np.arange(sample_size), random_idx ] fig, ax = plt.subplots(1, 1, figsize=(9,3)) ax.hist( X_samples, bins=100, density=True ); ax.set_title('Random sample from mixture of von Mises and Uniform distriburtions') # ---------------------------------------------------------------------- # # ---------------------------------------------------------------------- # # some preliminary quantities: CS = dC.getCosSin( X_samples ) r_ = ( sum(CS[:,0]), sum(CS[:,1]) ) print('r_ =',r_) r_r = np.sqrt( sum(CS[:,0])**2 + sum(CS[:,1])**2 ) print('r_r =',r_r) m_bar_cs = r_ / r_r print('m_bar_cs =',m_bar_cs) r_bar = r_r / N print('r_bar =',r_bar) m_bar = math.atan2( m_bar_cs[1], m_bar_cs[0]) print('m_bar =',m_bar,np.degrees(m_bar)) # for the uniform distribution: #xu_1 = min(X_samples) #xu_2 = (max(X_samples) - min(X_samples)) #xu_1 = -np.pi #xu_2 = 2*np.pi # ---------------------------------------------------------------------- # def unif_logpdf( x, loc=xu_1, scale=xu_2 ): return stats.uniform.logpdf( x, loc, scale ).sum() def vonMis_logpdf( x, kappa=kappa_, loc=loc_ ): return stats.vonmises.logpdf( x, kappa, loc ).sum() class Mix1vonMises1Uniform(GenericLikelihoodModel): def __init__(self, endog, exog=None, **kwds): if exog is None: exog = np.zeros_like(endog) super(Mix1vonMises1Uniform, self).__init__(endog, exog, **kwds) def nloglikeobs(self, params): # the unknown parameters: p_ = params[0] kappa_ = params[1] loc_ = params[2] # this is the log-likelihood for a single von Mises: # -np.log( vonMis_pdf( self.endog, kappa_=kappa1_, loc_=m1_ ) ) # the 1st von Mises distribution: fvm1_ = vonMis_logpdf( self.endog, kappa=kappa_, loc=loc_ ) # the uniform distribution: fu_ = unif_logpdf( self.endog, loc=xu_1, scale=xu_2 ) # total log-likelihood: nloglik = p_*fvm1_ + (1 - p_)*fu_ return -nloglik def fit(self, start_params=None, maxiter=10000, maxfun=5000, **kwds): return super( Mix1vonMises1Uniform, self ).fit( start_params=start_params, \ maxiter=maxiter, maxfun=maxfun, **kwds) start_params = np.array([ p_, kappa_, loc_ ]) model = Mix1vonMises1Uniform(X_samples) results = model.fit(start_params) #print(results.summary()) p_mle, kappa_mle, mu_mle = results.params print('-----------------------------------------') print('p, kappa, mu= ',p_mle, kappa_mle, mu_mle)
[ "df2472@columbia.edu" ]
df2472@columbia.edu
2b6425f91d7aec07d2685823ee370f4750527c55
f74ea6792ea917a420c68eb7a81ef76e5cad6fac
/image_synthesis/image_utils.py
ab60dbf80e5ed2b86087758be1f33ce44643d661
[ "MIT" ]
permissive
xcyan/eccv18_mtvae
aebb91d4f1348375df10089562fc7fe530ff8ed8
2b72bdcd09c004af89cbbaf30bad38d2ebae1706
refs/heads/master
2021-11-20T15:21:34.972804
2021-06-22T15:08:26
2021-06-22T15:08:26
143,248,197
40
9
null
null
null
null
UTF-8
Python
false
false
6,490
py
# import imageio import random import math import cv2 import time import numpy as np import scipy.io as sio import scipy.misc as sm from os import listdir, makedirs, system def transform(X): return X / 127.5 - 1 def inverse_transform(X): return (X + 1.) / 2. def save_images(images, size, image_path, bw=False, mean=None): if bw: imsave(images*255, size, image_path) else: if mean == None: return imsave(inverse_transform(images)*255., size, image_path) else: return imsave(images*255.+mean[None,None,None,:], size, image_path) def imsave(images, size, path): return sm.imsave(path, merge(images, size)) def merge(images, size): h, w = images.shape[1], images.shape[2] img = np.zeros((h * size[0], w * size[1], 3)) for idx, image in enumerate(images): i = idx % size[1] j = idx / size[1] img[j*h:j*h+h, i*w:i*w+w, :] = image return img def get_minibatches_idx(n, minibatch_size, shuffle=False): """ Used to shuffle the dataset at each iteration. """ idx_list = np.arange(n, dtype="int32") if shuffle: random.shuffle(idx_list) minibatches = [] minibatch_start = 0 for i in range(n // minibatch_size): minibatches.append( idx_list[minibatch_start:minibatch_start + minibatch_size]) minibatch_start += minibatch_size if (minibatch_start != n): # Make a minibatch out of what is left minibatches.append(idx_list[minibatch_start:]) return zip(range(len(minibatches)), minibatches) def gauss2D_mask(center, shape, sigma=0.5): m, n = [ss - 1 for ss in shape] y, x = np.ogrid[0:m + 1, 0:n + 1] y = y - center[0] x = x - center[1] z = x * x + y * y h = np.exp(-z / (2. * sigma * sigma)) sumh = h.sum() if sumh != 0: h = h / sumh return h def load_penn_data(f_name, data_path, image_size, steps): lines = [[0, 0, 1, 2], [1, 1, 2, 2], [1, 1, 3, 3], [3, 3, 5, 5], [2, 2, 4, 4], [4, 4, 6, 6], [1, 2, 7, 8], [7, 7, 8, 8], [7, 7, 9, 9], [9, 9, 11, 11], [8, 8, 10, 10], [10, 10, 12, 12]] rnd_steps = np.random.randint(1, steps) vid_path = f_name.split()[0] vid_imgs = sorted( [f for f in listdir(vid_path) if f.endswith('cropped.png')]) low = 0 high = len(vid_imgs) - rnd_steps - 1 if high < 1: rnd_steps = rnd_steps + high high = 1 stidx = np.random.randint(low=0, high=high) seq = np.zeros((image_size, image_size, 2, 3), dtype='float32') pose = np.zeros((image_size, image_size, 2, 48), dtype='float32') for t in xrange(2): img = cv2.imread(vid_path + '/' + vid_imgs[stidx + t * rnd_steps]) cpose = np.zeros((img.shape[0], img.shape[1], 48)) tks = vid_path.split('frames') ff = np.load(tks[0] + 'labels/' + tks[1][1:] + '.npz') posey = 1.0 * ff['y'][stidx + t * rnd_steps] posex = 1.0 * ff['x'][stidx + t * rnd_steps] visib = ff['visibility'][stidx + t * rnd_steps] for j in xrange(12): if (visib[lines[j][0]] and visib[lines[j][1]] and visib[lines[j][2]] and visib[lines[j][3]]): interp_x = np.linspace((posex[lines[j][0]] + posex[lines[j][1]]) / 2.0, (posex[lines[j][2]] + posex[lines[j][3]]) / 2.0, 4, True) interp_y = np.linspace((posey[lines[j][0]] + posey[lines[j][1]]) / 2.0, (posey[lines[j][2]] + posey[lines[j][3]]) / 2.0, 4, True) for k in xrange(4): gmask = gauss2D_mask( (interp_y[k], interp_x[k]), img.shape[:2], sigma=8.) cpose[:, :, j * 4 + k] = gmask / gmask.max() else: if visib[lines[j][0]] and visib[lines[j][1]]: point_x = (posex[lines[j][0]] + posex[lines[j][1]]) / 2.0 point_y = (posey[lines[j][0]] + posey[lines[j][1]]) / 2.0 gmask = gauss2D_mask((point_y, point_x), img.shape[:2], sigma=8.) cpose[:, :, j * 4] = gmask / gmask.max() if visib[lines[j][2]] and visib[lines[j][3]]: point_x = (posex[lines[j][2]] + posex[lines[j][3]]) / 2.0 point_y = (posey[lines[j][2]] + posey[lines[j][3]]) / 2.0 gmask = gauss2D_mask((point_y, point_x), img.shape[:2], sigma=8.) cpose[:, :, (j + 1) * 4 - 1] = gmask / gmask.max() img = cv2.resize(img, (image_size, image_size)) cpose = cv2.resize(cpose, (image_size, image_size)) seq[:, :, t] = transform(img) pose[:, :, t] = cpose return seq, pose def load_h36m_data(f_name, image_size, steps): rnd_steps = np.random.randint(1, steps) vid_path = f_name.split('\n')[0].split('.mp4')[0] vid_imgs = sorted([f for f in listdir(vid_path) if f.endswith('.png')]) anno_path = (vid_path.split('Videos')[0] + 'MyPoseFeatures/D2_Positions' + vid_path.split('Videos')[1] + '.npz') pose_data = np.load(anno_path) all_posey = pose_data['all_posey'] all_posex = pose_data['all_posex'] box = pose_data['box'] high = np.min([all_posey.shape[0], len(vid_imgs)]) - rnd_steps - 1 if high < 1: rnd_steps = rnd_steps + high high = 1 stidx = np.random.randint(low=0, high=high) seq = np.zeros((image_size, image_size, 2, 3), dtype='float32') pose = np.zeros((image_size, image_size, 2, 32), dtype='float32') shape = [box[2] - box[0], box[3] - box[1]] for t in xrange(2): posey = all_posey[stidx + t * rnd_steps, :] posex = all_posex[stidx + t * rnd_steps, :] img = cv2.imread(vid_path + '/' + vid_imgs[stidx + t * rnd_steps]) cpose = np.zeros((shape[0], shape[1], 32), dtype='float32') for j in xrange(32): gmask = gauss2D_mask((posey[j], posex[j]), shape, sigma=8.) cpose[:, :, j] = gmask / gmask.max() img = cv2.resize(img, (image_size, image_size)) cpose = cv2.resize(cpose, (image_size, image_size)) seq[:, :, t] = transform(img) pose[:, :, t] = cpose return seq, pose def draw_frame(img, is_input): if is_input: img[:2, :, 0] = img[:2, :, 2] = 0 img[:, :2, 0] = img[:, :2, 2] = 0 img[-2:, :, 0] = img[-2:, :, 2] = 0 img[:, -2:, 0] = img[:, -2:, 2] = 0 img[:2, :, 1] = 255 img[:, :2, 1] = 255 img[-2:, :, 1] = 255 img[:, -2:, 1] = 255 else: img[:2, :, 0] = img[:2, :, 1] = 0 img[:, :2, 0] = img[:, :2, 2] = 0 img[-2:, :, 0] = img[-2:, :, 1] = 0 img[:, -2:, 0] = img[:, -2:, 1] = 0 img[:2, :, 2] = 255 img[:, :2, 2] = 255 img[-2:, :, 2] = 255 img[:, -2:, 2] = 255 return img
[ "xcyan@umich.edu" ]
xcyan@umich.edu
8ebe82f6ab5430aae3b027ac9ee2cf298c21c342
dd2a441ec546dae92c30fead82a62d6e2a71f0a4
/unitedcp/tests.py
fb9ce907a89e73b2a427e263e9baa73e6c3fd1c4
[ "MIT" ]
permissive
sctnightcore/united_cp
5e7a400900c7bf13c1ac2d82c19bb042ed5b48c5
57483485510ad899bddf81c4f197921e76c9f990
refs/heads/master
2020-03-15T12:39:48.267403
2018-05-04T14:06:15
2018-05-04T14:06:15
null
0
0
null
null
null
null
UTF-8
Python
false
false
414
py
from django.test import TestCase from django.contrib.auth.models import User from unitedcp.models import UserProfile class RegisterTest(TestCase): def setUp(self): User.objects.create_user('tata12', 'tata@mail.ru', 'tata@11') def user_profile_created(self): user_profile = UserProfile.objects.get(user__username='tata12') self.assertEqual(user_profile.user.username, 'tata12')
[ "inspectahdeck227@gmail.com" ]
inspectahdeck227@gmail.com
05afa838fd50081e3b4f888e158897e0839c85ea
1498148e5d0af365cd7fd16197174174a7fa9800
/leetcode/t000541_3.py
284c9438e5ddf2ebc47b40712ca7845597fd8dc0
[]
no_license
feiyanshiren/myAcm
59a2b80fe7e02787defcb152eee3eae26135322a
00c7082d5143ddf87aeeafbdb6ce29da46dc8a12
refs/heads/master
2023-09-01T12:12:19.866447
2023-09-01T09:09:56
2023-09-01T09:09:56
148,560,672
0
0
null
null
null
null
UTF-8
Python
false
false
599
py
class Solution: def reverseStr(self, s: str, k: int) -> str: left, mid, right = 0, k, 2 * k # 初始化左中右指针 res = '' # 初始化结果字符串 while len(res) < len(s): # 满足条件时执行 res += s[left:mid][::-1] + s[mid:right] # 把当前单元的结果添加到结果字符串 left, mid, right = left + 2 * k, mid + 2 * k, right + 2 * k return res s = Solution() print(s.reverseStr("abcdefg", 2))
[ "feiyanshiren@163.com" ]
feiyanshiren@163.com
1a05df6b26d23688de3811c69b175a0dcb75ceae
85e867a8be7af4926b2defd4a58dcced0678090f
/pergunte/migrations/0010_materia_materiaativa.py
2fd6b93a170dc893c1f33feeafdcf2b63f5cf305
[]
no_license
marcelodeolive1ra/pergunte_backend
3c6f5106c547f0539fb60ae41284659d7a0c9a96
296b9dbe1d58232a9806679182200a9fd3d1600c
refs/heads/master
2021-01-12T06:35:05.700230
2017-02-14T04:53:30
2017-02-14T04:53:30
77,385,476
0
0
null
null
null
null
UTF-8
Python
false
false
486
py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-01-17 13:00 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pergunte', '0009_materia_turma'), ] operations = [ migrations.AddField( model_name='materia', name='materiaAtiva', field=models.BooleanField(default=True, verbose_name='Matéria ativa?'), ), ]
[ "marcelodeoliveira@outlook.com" ]
marcelodeoliveira@outlook.com
b9fa1c5775b9675a5d28f1c5da1a30ee4d3abf75
c503df9921554e337f4a1ea7f5e7dae18a40061d
/inherit.py
6d32e4636f2ac17e73ced7eabe46e9d53f26f119
[]
no_license
alvo254/tutorial
b6621a154b8a431e9fc954bf2038c3e9dad3dc0f
8193a421c7ffe6071a75bff3a979d26b53e12db4
refs/heads/master
2020-12-20T08:25:48.117590
2020-01-24T17:11:47
2020-01-24T17:11:47
236,014,718
0
0
null
null
null
null
UTF-8
Python
false
false
667
py
"""In inheritance there are two types superclass and subclass""" class Polygon: __width = None __height = None def set_value(self, width, height): self.__width = width self.__height = height def get_width(self): return self.__width def get_height(self): return self.__height # class Rectangle(Polygon): # def area(self): # return self.get_height() * self.get_width() class Triangle(Polygon): def area(self): return self.get_width() * self.get_height() / 2 # rect = Rectangle() tri = Triangle() # rect.set_value(50, 40) tri.set_value(50, 40) # print(rect.area()) print(tri.area())
[ "alvo@localhost.localdomain" ]
alvo@localhost.localdomain
c5bb56e9200cc3034c7b2b30adef7b1f45a7bd73
e1deed5bb2046e96b0fd2deb3a18148897f6c59f
/AST/expressions/plus_exp.py
d9d1d9837f9252f0106b85cdb758c192deaa4869
[]
no_license
Marcin-Szadkowski/JFTT-kompilator
3879272157d42eddff2d4020799df56c36136e25
525364a03b2d3c7ae46a3b15145c2a055ef4bcfa
refs/heads/master
2023-03-20T21:47:15.729067
2021-03-09T10:22:23
2021-03-09T10:22:23
330,029,547
0
0
null
null
null
null
UTF-8
Python
false
false
439
py
from compiler.reg_manager import RegManager from .expression import Expression from compiler.asm import Asm class PlusExp(Expression): """value + value""" def compile(self, code, reg): self.left.compile(code, reg) right_reg = RegManager.get_free_register() self.right.compile(code, right_reg) code.add_instr(Asm.ADD(reg, right_reg)) # rX <- expression RegManager.free_register(right_reg)
[ "marcinsz9045@gmail.com" ]
marcinsz9045@gmail.com
59501bc606dc946ce671b27b303db0ac3819f2ba
c8784310bea874acfce51a2ad0044ed25c7a060e
/convert_to_gaussian/cityscapes/cityscapesscripts/evaluation/instances2dict_with_polygons.py
10604b934269b3df446cd566c2990b9fc24e626a
[]
no_license
pesong/gaussian_data_api
3d0e2f2216a36a8f5c352634b6155c8c12bfbbba
2d0e73869ed1c4b74caf5ad4b7a28061036128ca
refs/heads/master
2020-03-25T19:42:11.794607
2019-05-08T07:32:12
2019-05-08T07:32:12
144,095,792
0
0
null
null
null
null
UTF-8
Python
false
false
2,178
py
#!/usr/bin/python # # Convert instances from png files to a dictionary # from __future__ import print_function import os, sys # Cityscapes imports from .instance import * sys.path.append( os.path.normpath( os.path.join( os.path.dirname( __file__ ) , '..' , 'helpers' ) ) ) from ..helpers.csHelpers import * import cv2 def instances2dict_with_polygons(imageFileList, verbose=False): imgCount = 0 instanceDict = {} if not isinstance(imageFileList, list): imageFileList = [imageFileList] if verbose: print("Processing {} images...".format(len(imageFileList))) for imageFileName in imageFileList: # Load image img = Image.open(imageFileName) # Image as numpy array imgNp = np.array(img) # Initialize label categories instances = {} for label in labels: instances[label.name] = [] # Loop through all instance ids in instance image for instanceId in np.unique(imgNp): # if instanceId < 1000: # continue instanceObj = Instance(imgNp, instanceId) instanceObj_dict = instanceObj.toDict() if id2label[instanceObj.labelID].hasInstances: mask = (imgNp == instanceId).astype(np.uint8) _, contour, hier, = cv2.findContours( mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) polygons = [c.reshape(-1).tolist() for c in contour] instanceObj_dict['contours'] = polygons instances[id2label[instanceObj.labelID].name].append( instanceObj_dict) imgKey = os.path.abspath(imageFileName) instanceDict[imgKey] = instances imgCount += 1 if verbose: print("\rImages Processed: {}".format(imgCount), end=' ') sys.stdout.flush() if verbose: print("") return instanceDict def main(argv): fileList = [] if (len(argv) > 2): for arg in argv: if ("png" in arg): fileList.append(arg) instances2dict(fileList, True) if __name__ == "__main__": main(sys.argv[1:])
[ "codeturbo@gmail.com" ]
codeturbo@gmail.com
a856a25d02c587188645a0940e1fcdb5e5fc7249
e4bd0ea58de9c4a7161e05244619a52689702952
/morph.py
e67440c1d49feb9df352c1786973813f354a7158
[]
no_license
mfaruqui/word-clustering
e787fba466dd12567483b3b89e039f372889a976
3165d047914a4db74fd8798e4723ebea83e57628
refs/heads/master
2021-01-19T06:18:33.628251
2013-03-20T18:33:26
2013-03-20T18:33:26
5,985,053
4
2
null
null
null
null
UTF-8
Python
false
false
8,135
py
import numpypy import numpy as np from math import log from collections import Counter from operator import itemgetter import sys class Morphology: def __init__(self, lang, morphWeight): self.transMat = None self.priorMat = None self.charSet = {} self.biCharSet = {} self.uniToBi = {} self.lang = lang self.weight = morphWeight self.suffixLen = 4 self.makeTransitionProbMatrix() return def makeTransitionProbMatrix(self): self.charSet = {'<w>':0, '</w>':1} index1 = 2 index2 = 0 for word in self.lang.wordDict.iterkeys(): if len(word) <= self.suffixLen: continue else: word = word[len(word)- self.suffixLen:] prevCh = '<w>' for ch in word: if ch not in self.charSet: self.charSet[ch] = index1 index1 += 1 if prevCh not in self.uniToBi: self.uniToBi[prevCh] = [] if (prevCh, ch) not in self.biCharSet: self.biCharSet[(prevCh, ch)] = index2 index2 += 1 self.uniToBi[prevCh].append(ch) prevCh = ch if (ch, '</w>') not in self.biCharSet: self.biCharSet[(ch, '</w>')] = index2 index2 += 1 if ch not in self.uniToBi: self.uniToBi[ch] = ['</w>'] elif '</w>' not in self.uniToBi[ch]: self.uniToBi[ch].append('</w>') assert len(self.biCharSet) == index2 assert len(self.charSet) == index1 assert len(self.biCharSet) == sum(len(self.uniToBi[ch]) for ch in self.uniToBi.keys()) numChar = len(self.charSet) numBiChar = len(self.biCharSet) numClus = len(self.lang.wordsInClusDict) self.transMat = np.ones((numClus, numBiChar)) self.priorMat = np.ones((numClus, numChar)) for clus, wordList in self.lang.wordsInClusDict.iteritems(): for word in wordList: if len(word) <= self.suffixLen: continue else: word = word[len(word)- self.suffixLen:] self.transMat[clus][self.biCharSet[('<w>', word[0])]] += 1.0 self.priorMat[clus][self.charSet['<w>']] += 1.0 for i, ch in enumerate(word): if i != 0: self.transMat[clus][self.biCharSet[(word[i-1], ch)]] += 1.0 self.priorMat[clus][self.charSet[ch]] += 1.0 self.transMat[clus][self.biCharSet[(ch, '</w>')]] += 1.0 self.priorMat[clus][self.charSet['</w>']] += 1.0 return def getClusMorphFactor(self, clus): fact = 0.0 for (ch1, ch2), index in self.biCharSet.iteritems(): p = self.transMat[clus][index]/self.priorMat[clus][self.charSet[ch1]] fact += p*log(p) return self.weight*fact/self.lang.numClusters def getChangeInMorph(self, wordToBeShifted, origClass, tempNewClass): if self.weight == 0: return 0.0 deltaMorph = 0.0 uniqBiGrams = Counter() uniqUniGrams = Counter() if len(wordToBeShifted) <= self.suffixLen: return 0.0 else: wordToBeShifted = wordToBeShifted[len(wordToBeShifted)- self.suffixLen:] for i, ch in enumerate(wordToBeShifted): if i > 0: if (wordToBeShifted[i-1], ch) not in uniqBiGrams: uniqBiGrams[(wordToBeShifted[i-1], ch)] += 1 if ch not in uniqUniGrams: uniqUniGrams[ch] += 1 uniqUniGrams['<w>'] = 1 uniqUniGrams['</w>'] = 1 uniqBiGrams[('<w>', wordToBeShifted[0])] = 1 uniqBiGrams[(wordToBeShifted[len(wordToBeShifted)-1], '</w>')] = 1 for ch1 in uniqUniGrams.iterkeys(): if ch1 in self.uniToBi: for ch2 in self.uniToBi[ch1]: if (ch1, ch2) in uniqBiGrams: #Changes to the old cluster pOldOrig = self.transMat[origClass][self.biCharSet[(ch1, ch2)]]/self.priorMat[origClass][self.charSet[ch1]] pNewOrig = (self.transMat[origClass][self.biCharSet[(ch1, ch2)]]-uniqBiGrams[(ch1, ch2)])/(self.priorMat[origClass][self.charSet[ch1]]-uniqUniGrams[ch1]) #Changes to the new cluster pOldNew = self.transMat[tempNewClass][self.biCharSet[(ch1, ch2)]]/self.priorMat[tempNewClass][self.charSet[ch1]] pNewNew = (self.transMat[tempNewClass][self.biCharSet[(ch1, ch2)]]+uniqBiGrams[(ch1, ch2)])/(self.priorMat[tempNewClass][self.charSet[ch1]]+uniqUniGrams[ch1]) #Removing old effects of both clusters deltaMorph += pOldOrig*log(pOldOrig) deltaMorph += pOldNew*log(pOldNew) #Adding new effects of both clusters deltaMorph -= pOldNew*log(pOldNew) deltaMorph -= pNewNew*log(pNewNew) else: #Changes to the old cluster pOldOrig = self.transMat[origClass][self.biCharSet[(ch1, ch2)]]/self.priorMat[origClass][self.charSet[ch1]] pNewOrig = self.transMat[origClass][self.biCharSet[(ch1, ch2)]]/(self.priorMat[origClass][self.charSet[ch1]]-uniqUniGrams[ch1]) #Changes to the new cluster pOldNew = self.transMat[tempNewClass][self.biCharSet[(ch1, ch2)]]/self.priorMat[tempNewClass][self.charSet[ch1]] pNewNew = self.transMat[tempNewClass][self.biCharSet[(ch1, ch2)]]/(self.priorMat[tempNewClass][self.charSet[ch1]]+uniqUniGrams[ch1]) #Removing old effects of both clusters deltaMorph += pOldOrig*log(pOldOrig) deltaMorph += pOldNew*log(pOldNew) #Adding new effects of both clusters deltaMorph -= pOldNew*log(pOldNew) deltaMorph -= pNewNew*log(pNewNew) return self.weight*deltaMorph/self.lang.numClusters def updateMorphData(self, wordToBeShifted, origClass, tempNewClass): if self.weight == 0: return if len(wordToBeShifted) <= self.suffixLen: return else: wordToBeShifted = wordToBeShifted[len(wordToBeShifted)- self.suffixLen:] for i, ch in enumerate(wordToBeShifted): if i > 0: self.transMat[origClass][self.biCharSet[(wordToBeShifted[i-1], ch)]] -= 1 self.transMat[tempNewClass][self.biCharSet[(wordToBeShifted[i-1], ch)]] += 1 self.priorMat[origClass][self.charSet[ch]] -= 1 self.priorMat[tempNewClass][self.charSet[ch]] += 1 self.priorMat[origClass][self.charSet['<w>']] -= 1 self.priorMat[origClass][self.charSet['</w>']] -= 1 self.priorMat[tempNewClass][self.charSet['<w>']] += 1 self.priorMat[tempNewClass][self.charSet['</w>']] += 1 self.transMat[origClass][self.biCharSet[('<w>', wordToBeShifted[0])]] -= 1 self.transMat[origClass][self.biCharSet[(wordToBeShifted[len(wordToBeShifted)-1], '</w>')]] -= 1 self.transMat[tempNewClass][self.biCharSet[('<w>', wordToBeShifted[0])]] += 1 self.transMat[tempNewClass][self.biCharSet[(wordToBeShifted[len(wordToBeShifted)-1], '</w>')]] += 1 return
[ "manaalfar@gmail.com" ]
manaalfar@gmail.com
ffb94808eb3bba39e0fc72eaf9e5277f911b9535
ac6fa3f540ba2e6ca3dd6141ca74775c0ae37900
/src/proto/metaDb/views.py
008039b013c1dbfbd3f8bb8eb59c0d573fd74364
[]
no_license
DarioGT/ProtoDict
c07927d9db20ac9ff03a6ad24be6e38802292f0e
68fc3382a5bc486f6ff875327ec4e227a7a0da7c
refs/heads/master
2016-09-05T14:36:35.094321
2011-11-27T06:26:17
2011-11-27T06:26:17
2,438,880
0
0
null
null
null
null
UTF-8
Python
false
false
3,996
py
# -*- encoding: UTF-8 -*- # import sys from django.db import models from django.contrib.auth.models import User from django import forms from django.http import HttpResponse, HttpResponseRedirect from django.template import Context from django.template import RequestContext from django.template.loader import get_template from protoExtJs import protoGrid, utils from protoExtJs.forms import ExtJsForm, getExtJsModelForm def getDjangoModel( appCode, modelName ): # llama directamente model = models.get_model( appCode, modelName ) # Encuentra el modelo # for m in models.get_models(): # if m._meta.object_name.lower() == modelName.lower(): # model = m # break return model # Create your views here. def protoGridDefinition(request): # used like this in the main urls.py : #(r'^apps/(?P<app>[^/]+)/(?P<view>[^/]+)$', 'core.appdispatcher.dispatch' ), --> apps/app/views.py/view #(r'^apps/(?P<app>[^/]+)/?$', 'core.appdispatcher.dispatch' ), --> apps/app/views.py/default # if you have an EditableModelGrid then you can use POST data to update your instances. if request.method == 'POST': protoFilter = request.POST.get('protoFilter', '') protoFilterBase = request.POST.get('protoFilterBase', '') protoApp = request.POST.get('protoApp', '') protoConcept = request.POST.get('protoConcept', '') # TODO: Independizar el llamado de la meta y de los datos # protoModelLoad = request.POST.get('protoConcept', '1') model = getDjangoModel(protoApp, protoConcept) grid = protoGrid.ProtoGridFactory( model ) # handle save of grid data ! if request.POST.get('delete', '')!='': modelName = request.GET.items()[0] dels = request.POST['delete'].split(',') User.objects.filter(id__in = dels).delete() return utils.JsonSuccess() # delete selected rows if request.POST.get('update', '')!='': # update rows data (update+inserts) if 1: #try: grid.update_instances_from_json(request.POST['update']) return utils.JsonSuccess() else: #except: #print "Unexpected error:", sys.exc_info()[0] msg = getattr(sys.exc_info()[1], 'message', sys.exc_info()[0]) #.message return utils.JsonError(str(msg)) # parametros de trabajo ( vienen en baseparam ) start = request.POST.get('start', 0) limit = request.POST.get('limit', 20) sort = request.POST.get('sort', 'id') sort_dir = request.POST.get('dir', 'ASC') # Convierte el filtro en un diccionario if (len (protoFilter) > 0 ): try: protoStmt = eval( protoFilter ) except: protoStmt = {'pk':0} else: protoStmt = {} # El filtro base viene en la configuracion MD if (len (protoFilterBase) > 0 ): try: protoStmtBase = eval( protoFilterBase ) except: protoStmtBase = {'pk':0} else: protoStmtBase = {} # Obtiene las filas del modelo # pRowsCount = model.objects.filter(**protoStmt ).count() # pRows = model.objects.filter(**protoStmt ).order_by('id')[start: limit] pRows = model.objects.filter(**protoStmt ).filter(**protoStmtBase ).order_by('id') pRowsCount = pRows.count() json = grid.to_grid( pRows, start = start, limit = limit, totalcount = pRowsCount, sort_field = sort, sort_direction = sort_dir ) resp = utils.JsonResponse(json) return resp
[ "dariogomezt@gmail.com" ]
dariogomezt@gmail.com
ca6fc80953c92152ef10dbcf1d8f13d0f2c2bb13
e74e0f6fbf0ea8dd438a75ee22f757e4cbde4aee
/webAutoTestTPshop/run_suite.py
d91aa477813039fe179f6dd1b70d5afe0ee82f18
[]
no_license
hgbanlen/-2021
c3f67d8906a371cfee5daf5b73ba74f4dfbd0351
1d9c35fdd7bcde6b91f9fdb81bd07856824da8c6
refs/heads/main
2023-03-23T05:04:23.651609
2021-03-06T10:05:27
2021-03-06T10:05:27
345,060,449
0
0
null
null
null
null
UTF-8
Python
false
false
35
py
""" 测试套件(程序入口) """
[ "hgbanlen45@126.com" ]
hgbanlen45@126.com
65e38637619fc5b209bdf8b5a66ebb43a5e18161
675839e604f82ab7c9edacf84ecc8c62a6acaefb
/v170117/RL4MT/core/optim.py
74a7b2923e86cfa636d95494fab167d8725d74da
[]
no_license
joelau94/RL4MT
3546c299975e3dda6258bee6ca33fb7b7b45cf9e
f3a102df45871e195f32c30232a12be5ec5f3526
refs/heads/master
2021-09-01T11:19:54.476147
2017-12-26T17:39:43
2017-12-26T17:39:43
115,440,618
0
0
null
null
null
null
UTF-8
Python
false
false
3,833
py
import numpy as np import theano import theano.tensor as TT from RL4MT.core.utils import * class Optimizer(object): def __init__(self, name=None): self.name = name class SGD(Optimizer): def __init__(self, inputs, costs, params, learning_rate, clipping, name=None): self.name = name self.params = params self.grads = [init_zeros(p.get_value().shape) for p in params] gradients = TT.grad(costs, params) grads_clip, grads_norm = clip(gradients, clipping, square=False) grads_upd = [(grads, new_grads) for grads, new_grads in zip(self.grads, grads_clip)] self.update_grads = theano.function(inputs, [costs, TT.sqrt(grads_norm)], updates=grads_upd) lr = np.float32(learning_rate) delta = [lr*grads for grads in self.grads] params_upd = [(p, p-d) for p, d in zip(self.params, delta)] self.update_params = theano.function([], [], updates=params_upd) class AdaDelta(Optimizer): def __init__(self, inputs, costs, params, gamma, eps, clipping, name=None): super(AdaDelta, self).__init__() self.name = name self.params = params self.grads = [init_zeros(p.get_value().shape) for p in params] self.grads_sqr_avg = [init_zeros(p.get_value().shape) for p in params] self.delta_sqr_avg = [init_zeros(p.get_value().shape) for p in params] gradients = TT.grad(costs, params) grads_clip, grads_norm = clip(gradients, clipping) grads_upd = [(grads, new_grads) for grads, new_grads in zip(self.grads, grads_clip)] grads_sqr_avg_upd = [(grads_sqr_avg, gamma*grads_sqr_avg + (1.-gamma)*(new_grads**2.)) for grads_sqr_avg, new_grads in zip(self.grads_sqr_avg, grads_clip) ] self.update_grads = theano.function(inputs, [costs, grads_norm], updates = grads_upd + grads_sqr_avg_upd) delta = [ grads * TT.sqrt(delta_sqr_avg+eps) / TT.sqrt(grads_sqr_avg+eps) for grads, delta_sqr_avg, grads_sqr_avg in zip(self.grads, self.delta_sqr_avg, self.grads_sqr_avg) ] delta_sqr_avg_upd = [ (delta_sqr_avg, gamma*delta_sqr_avg + (1.-gamma)*(new_delta**2.)) for delta_sqr_avg, new_delta in zip(self.delta_sqr_avg, delta) ] params_upd = [(p,p-d) for p, d in zip(self.params, delta)] self.update_params = theano.function([], [], updates = params_upd + delta_sqr_avg_upd) class ActorCriticAdaDelta(Optimizer): def __init__(self, inputs, actor_costs, critic_costs, actor_params, critic_params, gamma, eps, clipping, name=None): super(ActorCriticAdaDelta, self).__init__() self.name = name self.actor_params = actor_params self.critic_params = critic_params self.grads = [init_zeros(p.get_value().shape) for p in actor_params + critic_params] self.grads_sqr_avg = [init_zeros(p.get_value().shape) for p in actor_params + critic_params] self.delta_sqr_avg = [init_zeros(p.get_value().shape) for p in actor_params + critic_params] gradients = TT.grad(actor_costs, actor_params) + TT.grad(critic_costs, critic_params) grads_clip, grads_norm = clip(gradients, clipping) grads_upd = [(grads, new_grads) for grads, new_grads in zip(self.grads, grads_clip)] grads_sqr_avg_upd = [(grads_sqr_avg, gamma*grads_sqr_avg + (1.-gamma)*(new_grads**2.)) for grads_sqr_avg, new_grads in zip(self.grads_sqr_avg, grads_clip) ] self.update_grads = theano.function(inputs, [actor_costs, critic_costs, grads_norm], updates = grads_upd + grads_sqr_avg_upd) delta = [ grads * TT.sqrt(delta_sqr_avg+eps) / TT.sqrt(grads_sqr_avg+eps) for grads, delta_sqr_avg, grads_sqr_avg in zip(self.grads, self.delta_sqr_avg, self.grads_sqr_avg) ] delta_sqr_avg_upd = [ (delta_sqr_avg, gamma*delta_sqr_avg + (1.-gamma)*(new_delta**2.)) for delta_sqr_avg, new_delta in zip(self.delta_sqr_avg, delta) ] params_upd = [(p,p-d) for p, d in zip(actor_params+critic_params, delta)] self.update_params = theano.function([], [], updates = params_upd + delta_sqr_avg_upd)
[ "joelau94@gmail.com" ]
joelau94@gmail.com
258cdb81f0675756c518f9e9b4b3fa9b36ef89db
d7f0695df6b7a4c9a4264f8b9743c0681ac67638
/WebCafeteria/blog/admin.py
be3be9b904cca4f138fcef1abfcb5f95224ca7d9
[ "Apache-2.0" ]
permissive
CristianAAT/web-cafeteria
69767b3fc3188fba09613fce3fa708745fde4460
1ac0a53a1ffba497b56b9668aa771e881a64a8e4
refs/heads/master
2023-05-25T16:15:37.857455
2023-05-15T20:05:25
2023-05-15T20:05:25
271,836,421
0
0
null
null
null
null
UTF-8
Python
false
false
804
py
from django.contrib import admin from blog.models import Category, Post # Register your models here. class CategoryAdmin(admin.ModelAdmin): readonly_fields = ('created', 'updated') class PostAdmin(admin.ModelAdmin): readonly_fields = ('created', 'updated') list_display = ('title', 'author', 'published', 'post_categories') ordering = ('author', 'published') search_fields = ('title', 'content', 'author__username', 'categories__name') date_hierarchy = 'published' list_filter = ('author__username', 'categories__name') def post_categories(self, obj): return ", ".join([c.name for c in obj.categories.all().order_by('name')]) post_categories.short_description = "Categorias" admin.site.register(Category, CategoryAdmin) admin.site.register(Post, PostAdmin)
[ "=" ]
=
d7571f085e8d00b48c44e09eaf9bc0b8aba233ab
70e970ce9ec131449b0888388f65f0bb55f098cd
/SignalMC/python/pythia8/AMSB_gluinoToChargino_M-2200GeV_M-600GeV_CTau-10cm_TuneCP5_13TeV_pythia8_cff.py
ee3228ed082aa7a85fedf134f345b0aaa2edc422
[]
no_license
OSU-CMS/DisappTrks
53b790cc05cc8fe3a9f7fbd097284c5663e1421d
1d1c076863a9f8dbd3f0c077d5821a8333fc5196
refs/heads/master
2023-09-03T15:10:16.269126
2023-05-25T18:37:40
2023-05-25T18:37:40
13,272,469
5
12
null
2023-09-13T12:15:49
2013-10-02T13:58:51
Python
UTF-8
Python
false
false
8,098
py
COM_ENERGY = 13000. MGLU = 2200 # GeV MCHI = 600 # GeV CTAU = 100 # mm CROSS_SECTION = 0.000356 # pb SLHA_TABLE=""" # ISAJET SUSY parameters in SUSY Les Houches Accord 2 format # Created by ISALHA 2.0 Last revision: C. Balazs 21 Apr 2009 Block SPINFO # Program information 1 ISASUGRA from ISAJET # Spectrum Calculator 2 7.80 29-OCT-2009 12:50:36 # Version number Block MODSEL # Model selection 1 3 # Minimal anomaly mediated (AMSB) model Block SMINPUTS # Standard Model inputs 1 1.27836258E+02 # alpha_em^(-1) 2 1.16570000E-05 # G_Fermi 3 1.17200002E-01 # alpha_s(M_Z) 4 9.11699982E+01 # m_{Z}(pole) 5 4.19999981E+00 # m_{b}(m_{b}) 6 1.73070007E+02 # m_{top}(pole) 7 1.77699995E+00 # m_{tau}(pole) Block MINPAR # SUSY breaking input parameters 1 1.50000000E+03 # m_0 2 2.10300000E+05 # m_{3/2} 3 5.00000000E+00 # tan(beta) 4 1.00000000E+00 # sign(mu) Block EXTPAR # Non-universal SUSY breaking parameters 0 1.08399992E+16 # Input scale Block MASS # Scalar and gaugino mass spectrum # PDG code mass particle 24 8.04229965E+01 # W^+ 25 1.16262634E+02 # h^0 35 3.65780957E+03 # H^0 36 3.63369482E+03 # A^0 37 3.64751147E+03 # H^+ 1000001 4.12058105E+03 # dnl 1000002 4.11981787E+03 # upl 1000003 4.12058105E+03 # stl 1000004 4.11981787E+03 # chl 1000005 3.59533765E+03 # b1 1000006 2.98517871E+03 # t1 1000011 1.24901599E+03 # el- 1000012 1.23573743E+03 # nuel 1000013 1.24901599E+03 # mul- 1000014 1.23573743E+03 # numl 1000015 1.17080225E+03 # tau1 1000016 1.22719019E+03 # nutl 1000021 %.9g # glss 1000022 5.99874023E+02 # z1ss 1000023 1.93242529E+03 # z2ss 1000024 6.00047424E+02 # w1ss 1000025 -3.34248657E+03 # z3ss 1000035 3.34395361E+03 # z4ss 1000037 3.34808301E+03 # w2ss 2000001 4.18315088E+03 # dnr 2000002 4.14656396E+03 # upr 2000003 4.18315088E+03 # str 2000004 4.14656445E+03 # chr 2000005 4.15172412E+03 # b2 2000006 3.63008374E+03 # t2 2000011 1.17744092E+03 # er- 2000013 1.17744092E+03 # mur- 2000015 1.23730310E+03 # tau2 Block ALPHA # Effective Higgs mixing parameter -1.97738439E-01 # alpha Block STOPMIX # stop mixing matrix 1 1 9.25537199E-02 # O_{11} 1 2 -9.95707691E-01 # O_{12} 2 1 9.95707691E-01 # O_{21} 2 2 9.25537199E-02 # O_{22} Block SBOTMIX # sbottom mixing matrix 1 1 9.99980092E-01 # O_{11} 1 2 6.31465809E-03 # O_{12} 2 1 -6.31465809E-03 # O_{21} 2 2 9.99980092E-01 # O_{22} Block STAUMIX # stau mixing matrix 1 1 1.63745880E-01 # O_{11} 1 2 9.86502528E-01 # O_{12} 2 1 -9.86502528E-01 # O_{21} 2 2 1.63745880E-01 # O_{22} Block NMIX # neutralino mixing matrix 1 1 -8.85401911E-04 # 1 2 9.99694288E-01 # 1 3 -2.36074440E-02 # 1 4 7.30722025E-03 # 2 1 9.99720752E-01 # 2 2 1.44464616E-03 # 2 3 1.96342468E-02 # 2 4 -1.30743682E-02 # 3 1 -4.65229154E-03 # 3 2 1.15210889E-02 # 3 3 7.06939280E-01 # 3 4 7.07165360E-01 # 4 1 2.31538210E-02 # 4 2 -2.18327157E-02 # 4 3 -7.06607640E-01 # 4 4 7.06889749E-01 # Block UMIX # chargino U mixing matrix 1 1 -9.99414742E-01 # U_{11} 1 2 3.42073888E-02 # U_{12} 2 1 -3.42073888E-02 # U_{21} 2 2 -9.99414742E-01 # U_{22} Block VMIX # chargino V mixing matrix 1 1 -9.99915957E-01 # V_{11} 1 2 1.29629755E-02 # V_{12} 2 1 -1.29629755E-02 # V_{21} 2 2 -9.99915957E-01 # V_{22} Block GAUGE Q= 3.14105103E+03 # 1 3.57524991E-01 # g` 2 6.52378619E-01 # g_2 3 1.21927989E+00 # g_3 Block YU Q= 3.14105103E+03 # 3 3 8.41931880E-01 # y_t Block YD Q= 3.14105103E+03 # 3 3 6.57430291E-02 # y_b Block YE Q= 3.14105103E+03 # 3 3 5.15759252E-02 # y_tau Block HMIX Q= 3.14105103E+03 # Higgs mixing parameters 1 3.34447510E+03 # mu(Q) 2 5.00000000E+00 # tan(beta)(M_GUT) 3 2.51609634E+02 # Higgs vev at Q 4 1.32037380E+07 # m_A^2(Q) Block MSOFT Q= 3.14105103E+03 # DRbar SUSY breaking parameters 1 1.96140686E+03 # M_1(Q) 2 5.68461975E+02 # M_2(Q) 3 -3.88895142E+03 # M_3(Q) 31 1.23681946E+03 # MeL(Q) 32 1.23681946E+03 # MmuL(Q) 33 1.22848254E+03 # MtauL(Q) 34 1.17675854E+03 # MeR(Q) 35 1.17675854E+03 # MmuR(Q) 36 1.15583582E+03 # MtauR(Q) 41 3.92100171E+03 # MqL1(Q) 42 3.92100171E+03 # MqL2(Q) 43 3.43584668E+03 # MqL3(Q) 44 3.94716504E+03 # MuR(Q) 45 3.94716504E+03 # McR(Q) 46 2.87154858E+03 # MtR(Q) 47 3.98305713E+03 # MdR(Q) 48 3.98305713E+03 # MsR(Q) 49 4.00040381E+03 # MbR(Q) Block AU Q= 3.14105103E+03 # 1 1 3.34236670E+03 # A_u 2 2 3.34236670E+03 # A_c 3 3 3.34236670E+03 # A_t Block AD Q= 3.14105103E+03 # 1 1 7.95083057E+03 # A_d 2 2 7.95083057E+03 # A_s 3 3 7.95083057E+03 # A_b Block AE Q= 3.14105103E+03 # 1 1 2.20090503E+03 # A_e 2 2 2.20090503E+03 # A_mu 3 3 2.20090503E+03 # A_tau # # # # ================= # |The decay table| # ================= # # PDG Width DECAY 1000021 5.50675438E+00 # gluino decay # BR NDA ID1 ID2 ID3 2.50000000E-01 3 1 -1 1000022 2.50000000E-01 3 2 -2 1000022 2.50000000E-01 3 1 -2 1000024 2.50000000E-01 3 -1 2 -1000024 # # PDG Width DECAY 1000024 %.9g # chargino decay # """ % (MGLU, (1.97326979e-13 / CTAU)) import FWCore.ParameterSet.Config as cms from Configuration.Generator.Pythia8CommonSettings_cfi import * from Configuration.Generator.MCTunes2017.PythiaCP5Settings_cfi import * generator = cms.EDFilter("Pythia8GeneratorFilter", pythiaPylistVerbosity = cms.untracked.int32(0), filterEfficiency = cms.untracked.double(-1), pythiaHepMCVerbosity = cms.untracked.bool(False), SLHATableForPythia8 = cms.string('%s' % SLHA_TABLE), comEnergy = cms.double(COM_ENERGY), crossSection = cms.untracked.double(CROSS_SECTION), maxEventsToPrint = cms.untracked.int32(0), PythiaParameters = cms.PSet( pythia8CommonSettingsBlock, pythia8CP5SettingsBlock, processParameters = cms.vstring( 'SUSY:all = off', 'SUSY:gg2gluinogluino = on', 'SUSY:qqbar2gluinogluino = on', '1000024:isResonance = false', '1000024:oneChannel = 1 1.0 100 1000022 211', '1000024:tau0 = %.1f' % CTAU, 'ParticleDecays:tau0Max = %.1f' % (CTAU * 10), ), parameterSets = cms.vstring( 'pythia8CommonSettings', 'pythia8CP5Settings', 'processParameters') ), # The following parameters are required by Exotica_HSCP_SIM_cfi: slhaFile = cms.untracked.string(''), # value not used processFile = cms.untracked.string('SimG4Core/CustomPhysics/data/RhadronProcessList.txt'), useregge = cms.bool(False), hscpFlavor = cms.untracked.string('stau'), massPoint = cms.untracked.int32(MCHI), # value not used particleFile = cms.untracked.string('Configuration/GenProduction/python/ThirteenTeV/DisappTrksAMSBCascade/test/geant4_AMSB_chargino_%sGeV_ctau%scm.slha' % (MCHI, CTAU/10)) ) ProductionFilterSequence = cms.Sequence(generator)
[ "ahart@cern.ch" ]
ahart@cern.ch
9083a8a566ce6c7788d0215d62ac233f938951c1
ec3f9f1b1327ec8a69bd2fc056cdb2dbf7c243d3
/week_6/6.7.py
d704de0dc6dfdf9fbeb992db37312e1e65364891
[]
no_license
WhiteFeniks/Python_Cursera
e5d7e04c40eb586a9763f38de55c88cfb77318a4
0dbb85f0a225e7152599bbea75e1637d8f4dd04c
refs/heads/master
2022-11-15T22:39:35.663524
2020-07-11T16:55:39
2020-07-11T16:55:39
278,734,455
1
0
null
null
null
null
UTF-8
Python
false
false
383
py
import operator f_w = open('output.txt', 'w', encoding='utf8') with open('input.txt', 'r', encoding='utf8') as f_r: nums = f_r.read().splitlines()[1:] test_list = nums res = [tuple(map(str, sub.split(' '))) for sub in nums] res.sort(key=lambda x: int(x[1]), reverse=True) i = 0 while i < len(res): print(res[i][0]) f_w.write(res[i][0]) f_w.write("\n") i += 1
[ "macbookair@White-Fang-Mac.local" ]
macbookair@White-Fang-Mac.local
0a35eb5cceb4325b5bb86debed96c19bfa21b2eb
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5652388522229760_1/Python/LeoChen/PromblemA_Counting_Sheep.py
20d91b7daf0f04c4c1679635bf89afbd34320e90
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
Python
false
false
1,849
py
# -*- coding: utf-8 -*- """ Created on Sun Nov 8 06:29:02 2015 @author: chenchen """ #run: python PromblemA_Counting_Sheep.py file_in > file_out import sys f_name = sys.argv[1] w_name = sys.argv[3] print sys.argv #define the solution class class CountSheep(): def __init__(self,n): self.__start_number = n #return the output def result(self): if self.__start_number == 0: return "INSOMNIA" left_numbers = set(map(str,range(10))) #the loop_number = self.__start_number while len(left_numbers) > 0: current_numbers = set(str(loop_number)) left_numbers = left_numbers - current_numbers if len(left_numbers) == 0: return loop_number else: loop_number += self.__start_number #test case: #f = open("test.txt") #input file handle f = open(f_name) #output file handel w = open(w_name, 'w') cases = int(f.readline()) for c in xrange(cases): # alien_number, source_language, target_language \ # = f.readline().split() # # base = len(source_language) # temp_result = 0 # #print source_language # for s in alien_number: # #print temp_result , s , base, source_language.index(s) # temp_result = source_language.index(s) + temp_result * base # #print temp_result # #translate into target language: # result = "" # base_target = len(target_language) # #print temp_result # while(temp_result != 0): # remainder = temp_result % base_target # result = target_language[remainder] + result # temp_result /= base_target start_number = int(f.readline()) cs = CountSheep(int(start_number)) result = cs.result() w.write("Case #" + str(c+1) +": "+str(result) + "\n") w.flush() w.close() f.close()
[ "alexandra1.back@gmail.com" ]
alexandra1.back@gmail.com
0b80497296886daa6a7a0562b3901bc3f70e3ca6
dd666164758ab8ec71ae883236b313bade7f64ab
/src/c4-6/nest-list-c3.py
896e61b9b0f87ad185b297a87d2d82bc4fa75b68
[]
no_license
tosgit1989/pythstudy
331d8ed3b93248dd0a8541c68992e535375d1cd0
2e8f2638846183c434d383feb0c02c1388da303d
refs/heads/master
2020-06-18T12:01:26.295645
2017-01-07T00:15:09
2017-01-07T00:15:09
75,139,071
0
0
null
null
null
null
UTF-8
Python
false
false
88
py
base = [1, 2, 3] result = [ (x, y) for x in base for y in base if x != y ] print(result)
[ "purannaa1989@gmail.com" ]
purannaa1989@gmail.com
dc2b5c2ff2efb43458f0026c5020edbff67c793d
066c9798fa9bca9473808152c525443bf1dfa610
/bfs.py
b6871f37441c85f3c317a2ea3e818626fae7c6a0
[]
no_license
ashish0707/basic_webcrawler
99d118eb4af4196cbd3c842128b7626a400408ee
5f9f2a930607802f28bb329015fa6c8fdbd9372a
refs/heads/master
2021-01-10T23:12:00.976585
2016-12-15T05:38:51
2016-12-15T05:38:51
70,636,072
0
0
null
null
null
null
UTF-8
Python
false
false
171
py
from Searcher import Searcher class BFS(Searcher): name = '2.A_bfs.txt' def merge_list(self, list1, list2): list1 = list1 + list2 return list1
[ "saashaa0707@gmail.com" ]
saashaa0707@gmail.com
708b6ac5770facb72594d5672b90b036c027164f
7e69d3204619ca539e84af7d7da9b45d41760383
/DataLoader/ImbalanceCifar.py
94acca1550da79e527bb5ca74ce42d69fa8b89b2
[]
no_license
CoffeeCatt/Pytorch-Code-Snippet
ac6475e7b1707e81f9962b2484d409c644db50a9
5bc752212043b19628f54d674cd02dd600715a26
refs/heads/main
2023-06-26T21:46:56.250526
2021-07-29T18:04:16
2021-07-29T18:04:16
390,800,785
0
0
null
null
null
null
UTF-8
Python
false
false
2,928
py
import torch import torchvision import torchvision.transforms as transforms import numpy as np class IMBALANCECIFAR10(torchvision.datasets.CIFAR10): cls_num = 10 def __init__(self, root, imb_type='exp', imb_factor=0.01, rand_number=0, train=True, transform=None, target_transform=None, download=False): super(IMBALANCECIFAR10, self).__init__(root, train, transform, target_transform, download) np.random.seed(rand_number) img_num_list = self.get_img_num_per_cls(self.cls_num, imb_type, imb_factor) self.gen_imbalanced_data(img_num_list) def get_img_num_per_cls(self, cls_num, imb_type, imb_factor): img_max = len(self.data) / cls_num img_num_per_cls = [] if imb_type == 'exp': for cls_idx in range(cls_num): num = img_max * (imb_factor**(cls_idx / (cls_num - 1.0))) img_num_per_cls.append(int(num)) elif imb_type == 'step': for cls_idx in range(cls_num // 2): img_num_per_cls.append(int(img_max)) for cls_idx in range(cls_num // 2): img_num_per_cls.append(int(img_max * imb_factor)) else: img_num_per_cls.extend([int(img_max)] * cls_num) return img_num_per_cls def gen_imbalanced_data(self, img_num_per_cls): new_data = [] new_targets = [] targets_np = np.array(self.targets, dtype=np.int64) classes = np.unique(targets_np) # np.random.shuffle(classes) self.num_per_cls_dict = dict() for the_class, the_img_num in zip(classes, img_num_per_cls): self.num_per_cls_dict[the_class] = the_img_num idx = np.where(targets_np == the_class)[0] np.random.shuffle(idx) selec_idx = idx[:the_img_num] new_data.append(self.data[selec_idx, ...]) new_targets.extend([the_class, ] * the_img_num) new_data = np.vstack(new_data) self.data = new_data self.targets = new_targets def get_cls_num_list(self): cls_num_list = [] for i in range(self.cls_num): cls_num_list.append(self.num_per_cls_dict[i]) return cls_num_list class IMBALANCECIFAR100(IMBALANCECIFAR10): """`CIFAR100 <https://www.cs.toronto.edu/~kriz/cifar.html>`_ Dataset. This is a subclass of the `CIFAR10` Dataset. """ base_folder = 'cifar-100-python' url = "https://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz" filename = "cifar-100-python.tar.gz" tgz_md5 = 'eb9058c3a382ffc7106e4002c42a8d85' train_list = [ ['train', '16019d7e3df5f24257cddd939b257f8d'], ] test_list = [ ['test', 'f0ef6b0ae62326f3e7ffdfab6717acfc'], ] meta = { 'filename': 'meta', 'key': 'fine_label_names', 'md5': '7973b15100ade9c7d40fb424638fde48', } cls_num = 100
[ "noreply@github.com" ]
CoffeeCatt.noreply@github.com
4471091d4589d819e31f2d4fadfc1864059dd955
5826560b3680c25dc72ee9ad6c70ce808484f05c
/.pycharm_helpers/python_stubs/cache/bbe9cdf40be5fc89fec7c7e8fe7f757f3cd30c63b3e6c0e2af3b4c8f99eaf30b/_lsprof.py
b217b871a4e9ba0722ced166fb29ac963a450be4
[]
no_license
yangzsc/Pancake_test
c98e8caacd1e82c80fdfeb1e94fbf84783100864
22bd0bbcdbd04dc4201057696eaeaf27117e1dcc
refs/heads/master
2020-12-27T18:46:15.112829
2020-02-29T03:57:18
2020-02-29T03:57:18
238,009,308
0
0
null
null
null
null
UTF-8
Python
false
false
6,025
py
# encoding: utf-8 # module _lsprof # from /usr/lib/python3.6/lib-dynload/_lsprof.cpython-36m-x86_64-linux-gnu.so # by generator 1.147 """ Fast profiler """ # no imports # no functions # classes class Profiler(object): """ Profiler(timer=None, timeunit=None, subcalls=True, builtins=True) Builds a profiler object using the specified timer function. The default timer is a fast built-in one based on real time. For custom timer functions returning integers, timeunit can be a float specifying a scale (i.e. how long each integer unit is, in seconds). """ def clear(self): # real signature unknown; restored from __doc__ """ clear() Clear all profiling information collected so far. """ pass def disable(self): # real signature unknown; restored from __doc__ """ disable() Stop collecting profiling information. """ pass def enable(self, subcalls=True, builtins=True): # real signature unknown; restored from __doc__ """ enable(subcalls=True, builtins=True) Start collecting profiling information. If 'subcalls' is True, also records for each function statistics separated according to its current caller. If 'builtins' is True, records the time spent in built-in functions separately from their caller. """ pass def getstats(self): # real signature unknown; restored from __doc__ """ getstats() -> list of profiler_entry objects Return all information collected by the profiler. Each profiler_entry is a tuple-like object with the following attributes: code code object callcount how many times this was called reccallcount how many times called recursively totaltime total time in this entry inlinetime inline time in this entry (not in subcalls) calls details of the calls The calls attribute is either None or a list of profiler_subentry objects: code called code object callcount how many times this is called reccallcount how many times this is called recursively totaltime total time spent in this call inlinetime inline time (not in further subcalls) """ return [] def __init__(self, timer=None, timeunit=None, subcalls=True, builtins=True): # real signature unknown; restored from __doc__ pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass class profiler_entry(tuple): # no doc def __init__(self, *args, **kwargs): # real signature unknown pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __reduce__(self, *args, **kwargs): # real signature unknown pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass callcount = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """how many times this was called""" calls = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """details of the calls""" code = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """code object or built-in function name""" inlinetime = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """inline time in this entry (not in subcalls)""" reccallcount = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """how many times called recursively""" totaltime = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """total time in this entry""" n_fields = 6 n_sequence_fields = 6 n_unnamed_fields = 0 class profiler_subentry(tuple): # no doc def __init__(self, *args, **kwargs): # real signature unknown pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __reduce__(self, *args, **kwargs): # real signature unknown pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass callcount = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """how many times this is called""" code = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """called code object or built-in function name""" inlinetime = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """inline time (not in further subcalls)""" reccallcount = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """how many times this is called recursively""" totaltime = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """total time spent in this call""" n_fields = 5 n_sequence_fields = 5 n_unnamed_fields = 0 # variables with complex values __loader__ = None # (!) real value is '<_frozen_importlib_external.ExtensionFileLoader object at 0x7efebc83f160>' __spec__ = None # (!) real value is "ModuleSpec(name='_lsprof', loader=<_frozen_importlib_external.ExtensionFileLoader object at 0x7efebc83f160>, origin='/usr/lib/python3.6/lib-dynload/_lsprof.cpython-36m-x86_64-linux-gnu.so')"
[ "zhaoshuchen2018@gmail.com" ]
zhaoshuchen2018@gmail.com
077045edcf59aa7ef113bd1399cbe9bd53983c6c
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03545/s422953786.py
4b254d999870e05b7d54322e2f1ab097c008b7a3
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
413
py
def operation(a,ops): ans = a[0] for i in range(3): if ops[i]=='+': ans += a[i+1] else: ans -= a[i+1] return ans s = list(input()) a = [int(i) for i in s] op = ['+','-'] for i in range(1<<3): ops = [op[1&(i>>j)] for j in range(3)] if operation(a,ops)==7: print("{}{}{}{}{}{}{}=7".format(a[0],ops[0],a[1],ops[1],a[2],ops[2],a[3])) break
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
394aa06e303e9a3f66b8704e72eb6643cca902d9
fd9146d123bc208967dae58116e0c6826a022b14
/test.py
82b7f57aa2ad03f152a50a6f9e9080dd84923aeb
[]
no_license
TaseerH/Python-DB-Practice
8c51f63367e4ae4a67509a166824fb0814f6942c
076eba31b18753e0091178d549f7a2ab124a399e
refs/heads/main
2023-07-21T12:27:08.467436
2021-08-23T09:44:28
2021-08-23T09:44:28
394,566,019
0
0
null
null
null
null
UTF-8
Python
false
false
1,095
py
from sqlalchemy import create_engine import mysql.connector import pandas as pd import matplotlib.pyplot as plt import numpy as np #db_connection_str = 'mysql+pymysql://root:@localhost:3307/movies1' mydb = mysql.connector.connect(host= 'localhost', user= 'root', port= '3307', password= None, database='movies1') mycursor = mydb.cursor() mycursor.execute("select title, budget, revenue from movie limit 25") title = [] budget = [] revenue = [] for i in mycursor: title.append(i[0]) budget.append(i[1]/1000000) revenue.append(i[2]/1000000) print ("Titles:", title) print("Budget:", budget) print("Revenue", revenue) plt.figure(figsize=(100, 100)) plt.scatter(title, budget) plt.scatter(title, revenue) plt.plot(title, budget) plt.plot(title, revenue) plt.ylim(0, 1100) plt.xlim(0, 25) plt.xlabel("Titles") plt.ylabel("Budgets per 1000000/ Revenue per 1000000") plt.xticks(rotation = 85) plt.subplots_adjust(bottom=0.424) plt.show() mydb.close()
[ "73301847+TaseerH@users.noreply.github.com" ]
73301847+TaseerH@users.noreply.github.com
40544f9a4149ed4de40111270434f7a75411b62c
6d08a33780364ef81a4d5d7889546495aeaa0375
/usuario/models.py
b22e84a2440807707cefce63196afddf7408ac95
[]
no_license
DevHoodChiquinquira/AsdicalSAS
5e7ec4e7c39cfaf49fa2834e598640cd13eda8b7
2516c432a08b7e1f8e1672966c1bc4cdcc3ecf72
refs/heads/master
2021-05-07T16:32:20.280790
2018-03-13T23:22:16
2018-03-13T23:22:16
108,570,787
0
0
null
null
null
null
UTF-8
Python
false
false
838
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from phonenumber_field.modelfields import PhoneNumberField # Create your models here. class Perfil(models.Model): numeroDocumento = models.CharField(max_length=15, unique=True, verbose_name="Número de Documento") telefono = PhoneNumberField(default='+573001234567', null=True, verbose_name="Télefono") direccion = models.CharField(max_length=15, null=True, verbose_name="Dirección") user = models.OneToOneField(User, verbose_name= "Usario") imagen = models.ImageField(blank=True, null=True, upload_to="perfil") def __unicode__(self): return self.user.username
[ "romarovin11@gmail.com" ]
romarovin11@gmail.com
1ad4295854a4e9a16f126f62d4b03887d6619a89
dc7d8521472189945d4d7afb8b65319683453f74
/Instacopy/Instacopy/urls.py
460c6935811c45def4c3e0d13f242e3279194793
[]
no_license
rohanraarora/Instacopy
fdcbcdf20f6ca830981fe3e76bf0a2c25cbd2306
c8dadfe635dc87fd4a574f9edf2cb8b5edd53207
refs/heads/master
2020-06-02T06:19:41.541082
2016-12-10T19:46:51
2016-12-10T19:46:51
39,625,770
0
0
null
null
null
null
UTF-8
Python
false
false
929
py
"""Instacopy URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url, static from django.contrib import admin from django.conf import settings urlpatterns = [ url(r'^account/',include('account.urls')), url(r'^admin/', include(admin.site.urls)), ] + static.static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT)
[ "rohanraarora@gmail.com" ]
rohanraarora@gmail.com
b771191e3d536e036c6705fd9ea3ce57b4d3db46
10f620f96fb5876c9dfd88cbe99897b06489dae9
/you/vlc.py
9ae7f6e44149a198b67acc579f1c39c12e1170ed
[]
no_license
diegocrzt/you
f7a320a35ec49dfae9d02f584a3215e0e85ec5dc
e613a8009f01be2ca2013ea823c8754ad2809859
refs/heads/master
2020-02-26T14:11:00.236002
2014-02-14T20:48:19
2014-02-14T20:48:19
null
0
0
null
null
null
null
UTF-8
Python
false
false
256,209
py
#! /usr/bin/python # Python ctypes bindings for VLC # # Copyright (C) 2009-2012 the VideoLAN team # $Id: $ # # Authors: Olivier Aubert <olivier.aubert at liris.cnrs.fr> # Jean Brouwers <MrJean1 at gmail.com> # Geoff Salmon <geoff.salmon at gmail.com> # # This library is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation; either version 2.1 of the # License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA """This module provides bindings for the LibVLC public API, see U{http://wiki.videolan.org/LibVLC}. You can find the documentation and a README file with some examples at U{http://www.advene.org/download/python-ctypes/}. Basically, the most important class is L{Instance}, which is used to create a libvlc instance. From this instance, you then create L{MediaPlayer} and L{MediaListPlayer} instances. Alternatively, you may create instances of the L{MediaPlayer} and L{MediaListPlayer} class directly and an instance of L{Instance} will be implicitly created. The latter can be obtained using the C{get_instance} method of L{MediaPlayer} and L{MediaListPlayer}. """ import ctypes from ctypes.util import find_library import os import sys # Used by EventManager in override.py from inspect import getargspec __version__ = "N/A" build_date = "Tue Jul 2 10:35:53 2013" if sys.version_info[0] > 2: str = str unicode = str bytes = bytes basestring = (str, bytes) PYTHON3 = True def str_to_bytes(s): """Translate string or bytes to bytes. """ if isinstance(s, str): return bytes(s, sys.getfilesystemencoding()) else: return s def bytes_to_str(b): """Translate bytes to string. """ if isinstance(b, bytes): return b.decode(sys.getfilesystemencoding()) else: return b else: str = str unicode = unicode bytes = str basestring = basestring PYTHON3 = False def str_to_bytes(s): """Translate string or bytes to bytes. """ if isinstance(s, unicode): return s.encode(sys.getfilesystemencoding()) else: return s def bytes_to_str(b): """Translate bytes to unicode string. """ if isinstance(b, str): return unicode(b, sys.getfilesystemencoding()) else: return b # Internal guard to prevent internal classes to be directly # instanciated. _internal_guard = object() def find_lib(): dll = None plugin_path = None if sys.platform.startswith('linux'): p = find_library('vlc') try: dll = ctypes.CDLL(p) except OSError: # may fail dll = ctypes.CDLL('libvlc.so.5') elif sys.platform.startswith('win'): p = find_library('libvlc.dll') if p is None: try: # some registry settings import _winreg as w # leaner than win32api, win32con for r in w.HKEY_LOCAL_MACHINE, w.HKEY_CURRENT_USER: try: r = w.OpenKey(r, 'Software\\VideoLAN\\VLC') plugin_path, _ = w.QueryValueEx(r, 'InstallDir') w.CloseKey(r) break except w.error: pass except ImportError: # no PyWin32 pass if plugin_path is None: # try some standard locations. for p in ('Program Files\\VideoLan\\', 'VideoLan\\', 'Program Files\\', ''): p = 'C:\\' + p + 'VLC\\libvlc.dll' if os.path.exists(p): plugin_path = os.path.dirname(p) break if plugin_path is not None: # try loading p = os.getcwd() os.chdir(plugin_path) # if chdir failed, this will raise an exception dll = ctypes.CDLL('libvlc.dll') # restore cwd after dll has been loaded os.chdir(p) else: # may fail dll = ctypes.CDLL('libvlc.dll') else: plugin_path = os.path.dirname(p) dll = ctypes.CDLL(p) elif sys.platform.startswith('darwin'): # FIXME: should find a means to configure path d = '/Applications/VLC.app/Contents/MacOS/' p = d + 'lib/libvlc.dylib' if os.path.exists(p): dll = ctypes.CDLL(p) d += 'modules' if os.path.isdir(d): plugin_path = d else: # hope, some PATH is set... dll = ctypes.CDLL('libvlc.dylib') else: raise NotImplementedError('%s: %s not supported' % (sys.argv[0], sys.platform)) return (dll, plugin_path) # plugin_path used on win32 and MacOS in override.py dll, plugin_path = find_lib() class VLCException(Exception): """Exception raised by libvlc methods. """ pass try: _Ints = (int, long) except NameError: # no long in Python 3+ _Ints = int _Seqs = (list, tuple) # Default instance. It is used to instanciate classes directly in the # OO-wrapper. _default_instance = None def get_default_instance(): """Return the default VLC.Instance. """ global _default_instance if _default_instance is None: _default_instance = Instance() return _default_instance _Cfunctions = {} # from LibVLC __version__ _Globals = globals() # sys.modules[__name__].__dict__ def _Cfunction(name, flags, errcheck, *types): """(INTERNAL) New ctypes function binding. """ if hasattr(dll, name) and name in _Globals: p = ctypes.CFUNCTYPE(*types) f = p((name, dll), flags) if errcheck is not None: f.errcheck = errcheck # replace the Python function # in this module, but only when # running as python -O or -OO if __debug__: _Cfunctions[name] = f else: _Globals[name] = f return f raise NameError('no function %r' % (name,)) def _Cobject(cls, ctype): """(INTERNAL) New instance from ctypes. """ o = object.__new__(cls) o._as_parameter_ = ctype return o def _Constructor(cls, ptr=_internal_guard): """(INTERNAL) New wrapper from ctypes. """ if ptr == _internal_guard: raise VLCException("(INTERNAL) ctypes class. You should get references for this class through methods of the LibVLC API.") if ptr is None or ptr == 0: return None return _Cobject(cls, ctypes.c_void_p(ptr)) class _Cstruct(ctypes.Structure): """(INTERNAL) Base class for ctypes structures. """ _fields_ = [] # list of 2-tuples ('name', ctyptes.<type>) def __str__(self): l = [' %s:\t%s' % (n, getattr(self, n)) for n, _ in self._fields_] return '\n'.join([self.__class__.__name__] + l) def __repr__(self): return '%s.%s' % (self.__class__.__module__, self) class _Ctype(object): """(INTERNAL) Base class for ctypes. """ @staticmethod def from_param(this): # not self """(INTERNAL) ctypes parameter conversion method. """ if this is None: return None return this._as_parameter_ class ListPOINTER(object): """Just like a POINTER but accept a list of ctype as an argument. """ def __init__(self, etype): self.etype = etype def from_param(self, param): if isinstance(param, _Seqs): return (self.etype * len(param))(*param) # errcheck functions for some native functions. def string_result(result, func, arguments): """Errcheck function. Returns a string and frees the original pointer. It assumes the result is a char *. """ if result: # make a python string copy s = bytes_to_str(ctypes.string_at(result)) # free original string ptr libvlc_free(result) return s return None def class_result(classname): """Errcheck function. Returns a function that creates the specified class. """ def wrap_errcheck(result, func, arguments): if result is None: return None return classname(result) return wrap_errcheck # Wrapper for the opaque struct libvlc_log_t class Log(ctypes.Structure): pass Log_ptr = ctypes.POINTER(Log) # FILE* ctypes wrapper, copied from # http://svn.python.org/projects/ctypes/trunk/ctypeslib/ctypeslib/contrib/pythonhdr.py class FILE(ctypes.Structure): pass FILE_ptr = ctypes.POINTER(FILE) if PYTHON3: PyFile_FromFd = ctypes.pythonapi.PyFile_FromFd PyFile_FromFd.restype = ctypes.py_object PyFile_FromFd.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int ] PyFile_AsFd = ctypes.pythonapi.PyObject_AsFileDescriptor PyFile_AsFd.restype = ctypes.c_int PyFile_AsFd.argtypes = [ctypes.py_object] else: PyFile_FromFile = ctypes.pythonapi.PyFile_FromFile PyFile_FromFile.restype = ctypes.py_object PyFile_FromFile.argtypes = [FILE_ptr, ctypes.c_char_p, ctypes.c_char_p, ctypes.CFUNCTYPE(ctypes.c_int, FILE_ptr)] PyFile_AsFile = ctypes.pythonapi.PyFile_AsFile PyFile_AsFile.restype = FILE_ptr PyFile_AsFile.argtypes = [ctypes.py_object] # Generated enum types # class _Enum(ctypes.c_uint): '''(INTERNAL) Base class ''' _enum_names_ = {} def __str__(self): n = self._enum_names_.get(self.value, '') or ('FIXME_(%r)' % (self.value,)) return '.'.join((self.__class__.__name__, n)) def __hash__(self): return self.value def __repr__(self): return '.'.join((self.__class__.__module__, self.__str__())) def __eq__(self, other): return ( (isinstance(other, _Enum) and self.value == other.value) or (isinstance(other, _Ints) and self.value == other) ) def __ne__(self, other): return not self.__eq__(other) class LogLevel(_Enum): '''Logging messages level. \note future libvlc versions may define new levels. ''' _enum_names_ = { 0: 'DEBUG', 2: 'NOTICE', 3: 'WARNING', 4: 'ERROR', } LogLevel.DEBUG = LogLevel(0) LogLevel.ERROR = LogLevel(4) LogLevel.NOTICE = LogLevel(2) LogLevel.WARNING = LogLevel(3) class EventType(_Enum): '''Event types. ''' _enum_names_ = { 0: 'MediaMetaChanged', 1: 'MediaSubItemAdded', 2: 'MediaDurationChanged', 3: 'MediaParsedChanged', 4: 'MediaFreed', 5: 'MediaStateChanged', 0x100: 'MediaPlayerMediaChanged', 257: 'MediaPlayerNothingSpecial', 258: 'MediaPlayerOpening', 259: 'MediaPlayerBuffering', 260: 'MediaPlayerPlaying', 261: 'MediaPlayerPaused', 262: 'MediaPlayerStopped', 263: 'MediaPlayerForward', 264: 'MediaPlayerBackward', 265: 'MediaPlayerEndReached', 266: 'MediaPlayerEncounteredError', 267: 'MediaPlayerTimeChanged', 268: 'MediaPlayerPositionChanged', 269: 'MediaPlayerSeekableChanged', 270: 'MediaPlayerPausableChanged', 271: 'MediaPlayerTitleChanged', 272: 'MediaPlayerSnapshotTaken', 273: 'MediaPlayerLengthChanged', 274: 'MediaPlayerVout', 0x200: 'MediaListItemAdded', 513: 'MediaListWillAddItem', 514: 'MediaListItemDeleted', 515: 'MediaListWillDeleteItem', 0x300: 'MediaListViewItemAdded', 769: 'MediaListViewWillAddItem', 770: 'MediaListViewItemDeleted', 771: 'MediaListViewWillDeleteItem', 0x400: 'MediaListPlayerPlayed', 1025: 'MediaListPlayerNextItemSet', 1026: 'MediaListPlayerStopped', 0x500: 'MediaDiscovererStarted', 1281: 'MediaDiscovererEnded', 0x600: 'VlmMediaAdded', 1537: 'VlmMediaRemoved', 1538: 'VlmMediaChanged', 1539: 'VlmMediaInstanceStarted', 1540: 'VlmMediaInstanceStopped', 1541: 'VlmMediaInstanceStatusInit', 1542: 'VlmMediaInstanceStatusOpening', 1543: 'VlmMediaInstanceStatusPlaying', 1544: 'VlmMediaInstanceStatusPause', 1545: 'VlmMediaInstanceStatusEnd', 1546: 'VlmMediaInstanceStatusError', } EventType.MediaDiscovererEnded = EventType(1281) EventType.MediaDiscovererStarted = EventType(0x500) EventType.MediaDurationChanged = EventType(2) EventType.MediaFreed = EventType(4) EventType.MediaListItemAdded = EventType(0x200) EventType.MediaListItemDeleted = EventType(514) EventType.MediaListPlayerNextItemSet = EventType(1025) EventType.MediaListPlayerPlayed = EventType(0x400) EventType.MediaListPlayerStopped = EventType(1026) EventType.MediaListViewItemAdded = EventType(0x300) EventType.MediaListViewItemDeleted = EventType(770) EventType.MediaListViewWillAddItem = EventType(769) EventType.MediaListViewWillDeleteItem = EventType(771) EventType.MediaListWillAddItem = EventType(513) EventType.MediaListWillDeleteItem = EventType(515) EventType.MediaMetaChanged = EventType(0) EventType.MediaParsedChanged = EventType(3) EventType.MediaPlayerBackward = EventType(264) EventType.MediaPlayerBuffering = EventType(259) EventType.MediaPlayerEncounteredError = EventType(266) EventType.MediaPlayerEndReached = EventType(265) EventType.MediaPlayerForward = EventType(263) EventType.MediaPlayerLengthChanged = EventType(273) EventType.MediaPlayerMediaChanged = EventType(0x100) EventType.MediaPlayerNothingSpecial = EventType(257) EventType.MediaPlayerOpening = EventType(258) EventType.MediaPlayerPausableChanged = EventType(270) EventType.MediaPlayerPaused = EventType(261) EventType.MediaPlayerPlaying = EventType(260) EventType.MediaPlayerPositionChanged = EventType(268) EventType.MediaPlayerSeekableChanged = EventType(269) EventType.MediaPlayerSnapshotTaken = EventType(272) EventType.MediaPlayerStopped = EventType(262) EventType.MediaPlayerTimeChanged = EventType(267) EventType.MediaPlayerTitleChanged = EventType(271) EventType.MediaPlayerVout = EventType(274) EventType.MediaStateChanged = EventType(5) EventType.MediaSubItemAdded = EventType(1) EventType.VlmMediaAdded = EventType(0x600) EventType.VlmMediaChanged = EventType(1538) EventType.VlmMediaInstanceStarted = EventType(1539) EventType.VlmMediaInstanceStatusEnd = EventType(1545) EventType.VlmMediaInstanceStatusError = EventType(1546) EventType.VlmMediaInstanceStatusInit = EventType(1541) EventType.VlmMediaInstanceStatusOpening = EventType(1542) EventType.VlmMediaInstanceStatusPause = EventType(1544) EventType.VlmMediaInstanceStatusPlaying = EventType(1543) EventType.VlmMediaInstanceStopped = EventType(1540) EventType.VlmMediaRemoved = EventType(1537) class Meta(_Enum): '''Meta data types. ''' _enum_names_ = { 0: 'Title', 1: 'Artist', 2: 'Genre', 3: 'Copyright', 4: 'Album', 5: 'TrackNumber', 6: 'Description', 7: 'Rating', 8: 'Date', 9: 'Setting', 10: 'URL', 11: 'Language', 12: 'NowPlaying', 13: 'Publisher', 14: 'EncodedBy', 15: 'ArtworkURL', 16: 'TrackID', } Meta.Album = Meta(4) Meta.Artist = Meta(1) Meta.ArtworkURL = Meta(15) Meta.Copyright = Meta(3) Meta.Date = Meta(8) Meta.Description = Meta(6) Meta.EncodedBy = Meta(14) Meta.Genre = Meta(2) Meta.Language = Meta(11) Meta.NowPlaying = Meta(12) Meta.Publisher = Meta(13) Meta.Rating = Meta(7) Meta.Setting = Meta(9) Meta.Title = Meta(0) Meta.TrackID = Meta(16) Meta.TrackNumber = Meta(5) Meta.URL = Meta(10) class State(_Enum): '''Note the order of libvlc_state_t enum must match exactly the order of See mediacontrol_playerstatus, See input_state_e enums, and videolan.libvlc.state (at bindings/cil/src/media.cs). expected states by web plugins are: idle/close=0, opening=1, buffering=2, playing=3, paused=4, stopping=5, ended=6, error=7. ''' _enum_names_ = { 0: 'NothingSpecial', 1: 'Opening', 2: 'Buffering', 3: 'Playing', 4: 'Paused', 5: 'Stopped', 6: 'Ended', 7: 'Error', } State.Buffering = State(2) State.Ended = State(6) State.Error = State(7) State.NothingSpecial = State(0) State.Opening = State(1) State.Paused = State(4) State.Playing = State(3) State.Stopped = State(5) class TrackType(_Enum): '''N/A ''' _enum_names_ = { -1: 'unknown', 0: 'audio', 1: 'video', 2: 'text', } TrackType.audio = TrackType(0) TrackType.text = TrackType(2) TrackType.unknown = TrackType(-1) TrackType.video = TrackType(1) class PlaybackMode(_Enum): '''Defines playback modes for playlist. ''' _enum_names_ = { 0: 'default', 1: 'loop', 2: 'repeat', } PlaybackMode.default = PlaybackMode(0) PlaybackMode.loop = PlaybackMode(1) PlaybackMode.repeat = PlaybackMode(2) class VideoMarqueeOption(_Enum): '''Marq options definition. ''' _enum_names_ = { 0: 'Enable', 1: 'Text', 2: 'Color', 3: 'Opacity', 4: 'Position', 5: 'Refresh', 6: 'Size', 7: 'Timeout', 8: 'marquee_X', 9: 'marquee_Y', } VideoMarqueeOption.Color = VideoMarqueeOption(2) VideoMarqueeOption.Enable = VideoMarqueeOption(0) VideoMarqueeOption.Opacity = VideoMarqueeOption(3) VideoMarqueeOption.Position = VideoMarqueeOption(4) VideoMarqueeOption.Refresh = VideoMarqueeOption(5) VideoMarqueeOption.Size = VideoMarqueeOption(6) VideoMarqueeOption.Text = VideoMarqueeOption(1) VideoMarqueeOption.Timeout = VideoMarqueeOption(7) VideoMarqueeOption.marquee_X = VideoMarqueeOption(8) VideoMarqueeOption.marquee_Y = VideoMarqueeOption(9) class NavigateMode(_Enum): '''Navigation mode. ''' _enum_names_ = { 0: 'activate', 1: 'up', 2: 'down', 3: 'left', 4: 'right', } NavigateMode.activate = NavigateMode(0) NavigateMode.down = NavigateMode(2) NavigateMode.left = NavigateMode(3) NavigateMode.right = NavigateMode(4) NavigateMode.up = NavigateMode(1) class VideoLogoOption(_Enum): '''Option values for libvlc_video_{get,set}_logo_{int,string}. ''' _enum_names_ = { 0: 'enable', 1: 'file', 2: 'logo_x', 3: 'logo_y', 4: 'delay', 5: 'repeat', 6: 'opacity', 7: 'position', } VideoLogoOption.delay = VideoLogoOption(4) VideoLogoOption.enable = VideoLogoOption(0) VideoLogoOption.file = VideoLogoOption(1) VideoLogoOption.logo_x = VideoLogoOption(2) VideoLogoOption.logo_y = VideoLogoOption(3) VideoLogoOption.opacity = VideoLogoOption(6) VideoLogoOption.position = VideoLogoOption(7) VideoLogoOption.repeat = VideoLogoOption(5) class VideoAdjustOption(_Enum): '''Option values for libvlc_video_{get,set}_adjust_{int,float,bool}. ''' _enum_names_ = { 0: 'Enable', 1: 'Contrast', 2: 'Brightness', 3: 'Hue', 4: 'Saturation', 5: 'Gamma', } VideoAdjustOption.Brightness = VideoAdjustOption(2) VideoAdjustOption.Contrast = VideoAdjustOption(1) VideoAdjustOption.Enable = VideoAdjustOption(0) VideoAdjustOption.Gamma = VideoAdjustOption(5) VideoAdjustOption.Hue = VideoAdjustOption(3) VideoAdjustOption.Saturation = VideoAdjustOption(4) class AudioOutputDeviceTypes(_Enum): '''Audio device types. ''' _enum_names_ = { -1: 'Error', 1: 'Mono', 2: 'Stereo', 4: '_2F2R', 5: '_3F2R', 6: '_5_1', 7: '_6_1', 8: '_7_1', 10: 'SPDIF', } AudioOutputDeviceTypes.Error = AudioOutputDeviceTypes(-1) AudioOutputDeviceTypes.Mono = AudioOutputDeviceTypes(1) AudioOutputDeviceTypes.SPDIF = AudioOutputDeviceTypes(10) AudioOutputDeviceTypes.Stereo = AudioOutputDeviceTypes(2) AudioOutputDeviceTypes._2F2R = AudioOutputDeviceTypes(4) AudioOutputDeviceTypes._3F2R = AudioOutputDeviceTypes(5) AudioOutputDeviceTypes._5_1 = AudioOutputDeviceTypes(6) AudioOutputDeviceTypes._6_1 = AudioOutputDeviceTypes(7) AudioOutputDeviceTypes._7_1 = AudioOutputDeviceTypes(8) class AudioOutputChannel(_Enum): '''Audio channels. ''' _enum_names_ = { -1: 'Error', 1: 'Stereo', 2: 'RStereo', 3: 'Left', 4: 'Right', 5: 'Dolbys', } AudioOutputChannel.Dolbys = AudioOutputChannel(5) AudioOutputChannel.Error = AudioOutputChannel(-1) AudioOutputChannel.Left = AudioOutputChannel(3) AudioOutputChannel.RStereo = AudioOutputChannel(2) AudioOutputChannel.Right = AudioOutputChannel(4) AudioOutputChannel.Stereo = AudioOutputChannel(1) class Callback(ctypes.c_void_p): """Callback function notification \param p_event the event triggering the callback """ pass class LogCb(ctypes.c_void_p): """Callback prototype for LibVLC log message handler. \param data data pointer as given to L{libvlc_log_set}() \param level message level (@ref enum libvlc_log_level) \param ctx message context (meta-informations about the message) \param fmt printf() format string (as defined by ISO C11) \param args variable argument list for the format \note Log message handlers <b>must</b> be thread-safe. \warning The message context pointer, the format string parameters and the variable arguments are only valid until the callback returns. """ pass class VideoLockCb(ctypes.c_void_p): """Callback prototype to allocate and lock a picture buffer. Whenever a new video frame needs to be decoded, the lock callback is invoked. Depending on the video chroma, one or three pixel planes of adequate dimensions must be returned via the second parameter. Those planes must be aligned on 32-bytes boundaries. \param opaque private pointer as passed to L{libvlc_video_set_callbacks}() [IN] \param planes start address of the pixel planes (LibVLC allocates the array of void pointers, this callback must initialize the array) [OUT] \return a private pointer for the display and unlock callbacks to identify the picture buffers """ pass class VideoUnlockCb(ctypes.c_void_p): """Callback prototype to unlock a picture buffer. When the video frame decoding is complete, the unlock callback is invoked. This callback might not be needed at all. It is only an indication that the application can now read the pixel values if it needs to. \warning A picture buffer is unlocked after the picture is decoded, but before the picture is displayed. \param opaque private pointer as passed to L{libvlc_video_set_callbacks}() [IN] \param picture private pointer returned from the @ref libvlc_video_lock_cb callback [IN] \param planes pixel planes as defined by the @ref libvlc_video_lock_cb callback (this parameter is only for convenience) [IN] """ pass class VideoDisplayCb(ctypes.c_void_p): """Callback prototype to display a picture. When the video frame needs to be shown, as determined by the media playback clock, the display callback is invoked. \param opaque private pointer as passed to L{libvlc_video_set_callbacks}() [IN] \param picture private pointer returned from the @ref libvlc_video_lock_cb callback [IN] """ pass class VideoFormatCb(ctypes.c_void_p): """Callback prototype to configure picture buffers format. This callback gets the format of the video as output by the video decoder and the chain of video filters (if any). It can opt to change any parameter as it needs. In that case, LibVLC will attempt to convert the video format (rescaling and chroma conversion) but these operations can be CPU intensive. \param opaque pointer to the private pointer passed to L{libvlc_video_set_callbacks}() [IN/OUT] \param chroma pointer to the 4 bytes video format identifier [IN/OUT] \param width pointer to the pixel width [IN/OUT] \param height pointer to the pixel height [IN/OUT] \param pitches table of scanline pitches in bytes for each pixel plane (the table is allocated by LibVLC) [OUT] \param lines table of scanlines count for each plane [OUT] \return the number of picture buffers allocated, 0 indicates failure \note For each pixels plane, the scanline pitch must be bigger than or equal to the number of bytes per pixel multiplied by the pixel width. Similarly, the number of scanlines must be bigger than of equal to the pixel height. Furthermore, we recommend that pitches and lines be multiple of 32 to not break assumption that might be made by various optimizations in the video decoders, video filters and/or video converters. """ pass class VideoCleanupCb(ctypes.c_void_p): """Callback prototype to configure picture buffers format. \param opaque private pointer as passed to L{libvlc_video_set_callbacks}() (and possibly modified by @ref libvlc_video_format_cb) [IN] """ pass class AudioPlayCb(ctypes.c_void_p): """Callback prototype for audio playback. \param data data pointer as passed to L{libvlc_audio_set_callbacks}() [IN] \param samples pointer to the first audio sample to play back [IN] \param count number of audio samples to play back \param pts expected play time stamp (see libvlc_delay()) """ pass class AudioPauseCb(ctypes.c_void_p): """Callback prototype for audio pause. \note The pause callback is never called if the audio is already paused. \param data data pointer as passed to L{libvlc_audio_set_callbacks}() [IN] \param pts time stamp of the pause request (should be elapsed already) """ pass class AudioResumeCb(ctypes.c_void_p): """Callback prototype for audio resumption (i.e. restart from pause). \note The resume callback is never called if the audio is not paused. \param data data pointer as passed to L{libvlc_audio_set_callbacks}() [IN] \param pts time stamp of the resumption request (should be elapsed already) """ pass class AudioFlushCb(ctypes.c_void_p): """Callback prototype for audio buffer flush (i.e. discard all pending buffers and stop playback as soon as possible). \param data data pointer as passed to L{libvlc_audio_set_callbacks}() [IN] """ pass class AudioDrainCb(ctypes.c_void_p): """Callback prototype for audio buffer drain (i.e. wait for pending buffers to be played). \param data data pointer as passed to L{libvlc_audio_set_callbacks}() [IN] """ pass class AudioSetVolumeCb(ctypes.c_void_p): """Callback prototype for audio volume change. \param data data pointer as passed to L{libvlc_audio_set_callbacks}() [IN] \param volume software volume (1. = nominal, 0. = mute) \param mute muted flag """ pass class AudioSetupCb(ctypes.c_void_p): """Callback prototype to setup the audio playback. This is called when the media player needs to create a new audio output. \param opaque pointer to the data pointer passed to L{libvlc_audio_set_callbacks}() [IN/OUT] \param format 4 bytes sample format [IN/OUT] \param rate sample rate [IN/OUT] \param channels channels count [IN/OUT] \return 0 on success, anything else to skip audio playback """ pass class AudioCleanupCb(ctypes.c_void_p): """Callback prototype for audio playback cleanup. This is called when the media player no longer needs an audio output. \param opaque data pointer as passed to L{libvlc_audio_set_callbacks}() [IN] """ pass class CallbackDecorators(object): "Class holding various method decorators for callback functions." Callback = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p) Callback.__doc__ = '''Callback function notification \param p_event the event triggering the callback ''' LogCb = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, Log_ptr, ctypes.c_char_p, ctypes.c_void_p) LogCb.__doc__ = '''Callback prototype for LibVLC log message handler. \param data data pointer as given to L{libvlc_log_set}() \param level message level (@ref enum libvlc_log_level) \param ctx message context (meta-informations about the message) \param fmt printf() format string (as defined by ISO C11) \param args variable argument list for the format \note Log message handlers <b>must</b> be thread-safe. \warning The message context pointer, the format string parameters and the variable arguments are only valid until the callback returns. ''' VideoLockCb = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p, ListPOINTER(ctypes.c_void_p)) VideoLockCb.__doc__ = '''Callback prototype to allocate and lock a picture buffer. Whenever a new video frame needs to be decoded, the lock callback is invoked. Depending on the video chroma, one or three pixel planes of adequate dimensions must be returned via the second parameter. Those planes must be aligned on 32-bytes boundaries. \param opaque private pointer as passed to L{libvlc_video_set_callbacks}() [IN] \param planes start address of the pixel planes (LibVLC allocates the array of void pointers, this callback must initialize the array) [OUT] \return a private pointer for the display and unlock callbacks to identify the picture buffers ''' VideoUnlockCb = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ListPOINTER(ctypes.c_void_p)) VideoUnlockCb.__doc__ = '''Callback prototype to unlock a picture buffer. When the video frame decoding is complete, the unlock callback is invoked. This callback might not be needed at all. It is only an indication that the application can now read the pixel values if it needs to. \warning A picture buffer is unlocked after the picture is decoded, but before the picture is displayed. \param opaque private pointer as passed to L{libvlc_video_set_callbacks}() [IN] \param picture private pointer returned from the @ref libvlc_video_lock_cb callback [IN] \param planes pixel planes as defined by the @ref libvlc_video_lock_cb callback (this parameter is only for convenience) [IN] ''' VideoDisplayCb = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p) VideoDisplayCb.__doc__ = '''Callback prototype to display a picture. When the video frame needs to be shown, as determined by the media playback clock, the display callback is invoked. \param opaque private pointer as passed to L{libvlc_video_set_callbacks}() [IN] \param picture private pointer returned from the @ref libvlc_video_lock_cb callback [IN] ''' VideoFormatCb = ctypes.CFUNCTYPE(ctypes.POINTER(ctypes.c_uint), ListPOINTER(ctypes.c_void_p), ctypes.c_char_p, ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint)) VideoFormatCb.__doc__ = '''Callback prototype to configure picture buffers format. This callback gets the format of the video as output by the video decoder and the chain of video filters (if any). It can opt to change any parameter as it needs. In that case, LibVLC will attempt to convert the video format (rescaling and chroma conversion) but these operations can be CPU intensive. \param opaque pointer to the private pointer passed to L{libvlc_video_set_callbacks}() [IN/OUT] \param chroma pointer to the 4 bytes video format identifier [IN/OUT] \param width pointer to the pixel width [IN/OUT] \param height pointer to the pixel height [IN/OUT] \param pitches table of scanline pitches in bytes for each pixel plane (the table is allocated by LibVLC) [OUT] \param lines table of scanlines count for each plane [OUT] \return the number of picture buffers allocated, 0 indicates failure \note For each pixels plane, the scanline pitch must be bigger than or equal to the number of bytes per pixel multiplied by the pixel width. Similarly, the number of scanlines must be bigger than of equal to the pixel height. Furthermore, we recommend that pitches and lines be multiple of 32 to not break assumption that might be made by various optimizations in the video decoders, video filters and/or video converters. ''' VideoCleanupCb = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p) VideoCleanupCb.__doc__ = '''Callback prototype to configure picture buffers format. \param opaque private pointer as passed to L{libvlc_video_set_callbacks}() (and possibly modified by @ref libvlc_video_format_cb) [IN] ''' AudioPlayCb = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint, ctypes.c_int64) AudioPlayCb.__doc__ = '''Callback prototype for audio playback. \param data data pointer as passed to L{libvlc_audio_set_callbacks}() [IN] \param samples pointer to the first audio sample to play back [IN] \param count number of audio samples to play back \param pts expected play time stamp (see libvlc_delay()) ''' AudioPauseCb = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int64) AudioPauseCb.__doc__ = '''Callback prototype for audio pause. \note The pause callback is never called if the audio is already paused. \param data data pointer as passed to L{libvlc_audio_set_callbacks}() [IN] \param pts time stamp of the pause request (should be elapsed already) ''' AudioResumeCb = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int64) AudioResumeCb.__doc__ = '''Callback prototype for audio resumption (i.e. restart from pause). \note The resume callback is never called if the audio is not paused. \param data data pointer as passed to L{libvlc_audio_set_callbacks}() [IN] \param pts time stamp of the resumption request (should be elapsed already) ''' AudioFlushCb = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int64) AudioFlushCb.__doc__ = '''Callback prototype for audio buffer flush (i.e. discard all pending buffers and stop playback as soon as possible). \param data data pointer as passed to L{libvlc_audio_set_callbacks}() [IN] ''' AudioDrainCb = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p) AudioDrainCb.__doc__ = '''Callback prototype for audio buffer drain (i.e. wait for pending buffers to be played). \param data data pointer as passed to L{libvlc_audio_set_callbacks}() [IN] ''' AudioSetVolumeCb = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p, ctypes.c_float, ctypes.c_bool) AudioSetVolumeCb.__doc__ = '''Callback prototype for audio volume change. \param data data pointer as passed to L{libvlc_audio_set_callbacks}() [IN] \param volume software volume (1. = nominal, 0. = mute) \param mute muted flag ''' AudioSetupCb = ctypes.CFUNCTYPE(ctypes.POINTER(ctypes.c_int), ListPOINTER(ctypes.c_void_p), ctypes.c_char_p, ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint)) AudioSetupCb.__doc__ = '''Callback prototype to setup the audio playback. This is called when the media player needs to create a new audio output. \param opaque pointer to the data pointer passed to L{libvlc_audio_set_callbacks}() [IN/OUT] \param format 4 bytes sample format [IN/OUT] \param rate sample rate [IN/OUT] \param channels channels count [IN/OUT] \return 0 on success, anything else to skip audio playback ''' AudioCleanupCb = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p) AudioCleanupCb.__doc__ = '''Callback prototype for audio playback cleanup. This is called when the media player no longer needs an audio output. \param opaque data pointer as passed to L{libvlc_audio_set_callbacks}() [IN] ''' cb = CallbackDecorators # End of generated enum types # # From libvlc_structures.h class AudioOutput(_Cstruct): def __str__(self): return '%s(%s:%s)' % (self.__class__.__name__, self.name, self.description) AudioOutput._fields_ = [ # recursive struct ('name', ctypes.c_char_p), ('description', ctypes.c_char_p), ('next', ctypes.POINTER(AudioOutput)), ] class LogMessage(_Cstruct): _fields_ = [ ('size', ctypes.c_uint ), ('severity', ctypes.c_int ), ('type', ctypes.c_char_p), ('name', ctypes.c_char_p), ('header', ctypes.c_char_p), ('message', ctypes.c_char_p), ] def __init__(self): super(LogMessage, self).__init__() self.size = ctypes.sizeof(self) def __str__(self): return '%s(%d:%s): %s' % (self.__class__.__name__, self.severity, self.type, self.message) class MediaEvent(_Cstruct): _fields_ = [ ('media_name', ctypes.c_char_p), ('instance_name', ctypes.c_char_p), ] class MediaStats(_Cstruct): _fields_ = [ ('read_bytes', ctypes.c_int ), ('input_bitrate', ctypes.c_float), ('demux_read_bytes', ctypes.c_int ), ('demux_bitrate', ctypes.c_float), ('demux_corrupted', ctypes.c_int ), ('demux_discontinuity', ctypes.c_int ), ('decoded_video', ctypes.c_int ), ('decoded_audio', ctypes.c_int ), ('displayed_pictures', ctypes.c_int ), ('lost_pictures', ctypes.c_int ), ('played_abuffers', ctypes.c_int ), ('lost_abuffers', ctypes.c_int ), ('sent_packets', ctypes.c_int ), ('sent_bytes', ctypes.c_int ), ('send_bitrate', ctypes.c_float), ] class MediaTrackInfo(_Cstruct): _fields_ = [ ('codec', ctypes.c_uint32), ('id', ctypes.c_int ), ('type', TrackType ), ('profile', ctypes.c_int ), ('level', ctypes.c_int ), ('channels_or_height', ctypes.c_uint ), ('rate_or_width', ctypes.c_uint ), ] class AudioTrack(_Cstruct): _fields_ = [ ('channels', ctypes.c_uint), ('rate', ctypes.c_uint), ] class VideoTrack(_Cstruct): _fields_ = [ ('height', ctypes.c_uint), ('width', ctypes.c_uint), ('sar_num', ctypes.c_uint), ('sar_den', ctypes.c_uint), ('frame_rate_num', ctypes.c_uint), ('frame_rate_den', ctypes.c_uint), ] class SubtitleTrack(_Cstruct): _fields_ = [ ('encoding', ctypes.c_char_p), ] class MediaTrackTracks(ctypes.Union): _fields_ = [ ('audio', ctypes.POINTER(AudioTrack)), ('video', ctypes.POINTER(VideoTrack)), ('subtitle', ctypes.POINTER(SubtitleTrack)), ] class MediaTrack(_Cstruct): _anonymous_ = ("u",) _fields_ = [ ('codec', ctypes.c_uint32), ('original_fourcc', ctypes.c_uint32), ('id', ctypes.c_int ), ('type', TrackType ), ('profile', ctypes.c_int ), ('level', ctypes.c_int ), ('u', MediaTrackTracks), ('bitrate', ctypes.c_uint), ('language', ctypes.c_char_p), ('description', ctypes.c_char_p), ] class PlaylistItem(_Cstruct): _fields_ = [ ('id', ctypes.c_int ), ('uri', ctypes.c_char_p), ('name', ctypes.c_char_p), ] def __str__(self): return '%s #%d %s (uri %s)' % (self.__class__.__name__, self.id, self.name, self.uri) class Position(object): """Enum-like, immutable window position constants. See e.g. VideoMarqueeOption.Position. """ Center = 0 Left = 1 CenterLeft = 1 Right = 2 CenterRight = 2 Top = 4 TopCenter = 4 TopLeft = 5 TopRight = 6 Bottom = 8 BottomCenter = 8 BottomLeft = 9 BottomRight = 10 def __init__(self, *unused): raise TypeError('constants only') def __setattr__(self, *unused): #PYCHOK expected raise TypeError('immutable constants') class Rectangle(_Cstruct): _fields_ = [ ('top', ctypes.c_int), ('left', ctypes.c_int), ('bottom', ctypes.c_int), ('right', ctypes.c_int), ] class TrackDescription(_Cstruct): def __str__(self): return '%s(%d:%s)' % (self.__class__.__name__, self.id, self.name) TrackDescription._fields_ = [ # recursive struct ('id', ctypes.c_int ), ('name', ctypes.c_char_p), ('next', ctypes.POINTER(TrackDescription)), ] def track_description_list(head): """Convert a TrackDescription linked list to a Python list (and release the former). """ r = [] if head: item = head while item: item = item.contents r.append((item.id, item.name)) item = item.next try: libvlc_track_description_release(head) except NameError: libvlc_track_description_list_release(head) return r class EventUnion(ctypes.Union): _fields_ = [ ('meta_type', ctypes.c_uint ), ('new_child', ctypes.c_uint ), ('new_duration', ctypes.c_longlong), ('new_status', ctypes.c_int ), ('media', ctypes.c_void_p ), ('new_state', ctypes.c_uint ), # Media instance ('new_position', ctypes.c_float ), ('new_time', ctypes.c_longlong), ('new_title', ctypes.c_int ), ('new_seekable', ctypes.c_longlong), ('new_pausable', ctypes.c_longlong), # FIXME: Skipped MediaList and MediaListView... ('filename', ctypes.c_char_p ), ('new_length', ctypes.c_longlong), ('media_event', MediaEvent ), ] class Event(_Cstruct): _fields_ = [ ('type', EventType ), ('object', ctypes.c_void_p), ('u', EventUnion ), ] class ModuleDescription(_Cstruct): def __str__(self): return '%s %s (%s)' % (self.__class__.__name__, self.shortname, self.name) ModuleDescription._fields_ = [ # recursive struct ('name', ctypes.c_char_p), ('shortname', ctypes.c_char_p), ('longname', ctypes.c_char_p), ('help', ctypes.c_char_p), ('next', ctypes.POINTER(ModuleDescription)), ] def module_description_list(head): """Convert a ModuleDescription linked list to a Python list (and release the former). """ r = [] if head: item = head while item: item = item.contents r.append((item.name, item.shortname, item.longname, item.help)) item = item.next libvlc_module_description_list_release(head) return r class AudioOutputDevice(_Cstruct): def __str__(self): return '%s(%d:%s)' % (self.__class__.__name__, self.id, self.name) AudioOutputDevice._fields_ = [ # recursive struct ('next', ctypes.POINTER(AudioOutputDevice)), ('device', ctypes.c_char_p ), ('description', ctypes.c_char_p), ] # End of header.py # class EventManager(_Ctype): '''Create an event manager with callback handler. This class interposes the registration and handling of event notifications in order to (a) remove the need for decorating each callback functions with the decorator '@callbackmethod', (b) allow any number of positional and/or keyword arguments to the callback (in addition to the Event instance) and (c) to preserve the Python objects such that the callback and argument objects remain alive (i.e. are not garbage collected) until B{after} the notification has been unregistered. @note: Only a single notification can be registered for each event type in an EventManager instance. ''' _callback_handler = None _callbacks = {} def __new__(cls, ptr=_internal_guard): if ptr == _internal_guard: raise VLCException("(INTERNAL) ctypes class.\nYou should get a reference to EventManager through the MediaPlayer.event_manager() method.") return _Constructor(cls, ptr) def event_attach(self, eventtype, callback, *args, **kwds): """Register an event notification. @param eventtype: the desired event type to be notified about. @param callback: the function to call when the event occurs. @param args: optional positional arguments for the callback. @param kwds: optional keyword arguments for the callback. @return: 0 on success, ENOMEM on error. @note: The callback function must have at least one argument, an Event instance. Any other, optional positional and keyword arguments are in B{addition} to the first one. """ if not isinstance(eventtype, EventType): raise VLCException("%s required: %r" % ('EventType', eventtype)) if not hasattr(callback, '__call__'): # callable() raise VLCException("%s required: %r" % ('callable', callback)) # check that the callback expects arguments if not any(getargspec(callback)[:2]): # list(...) raise VLCException("%s required: %r" % ('argument', callback)) if self._callback_handler is None: _called_from_ctypes = ctypes.CFUNCTYPE(None, ctypes.POINTER(Event), ctypes.c_void_p) @_called_from_ctypes def _callback_handler(event, k): """(INTERNAL) handle callback call from ctypes. @note: We cannot simply make this an EventManager method since ctypes does not prepend self as the first parameter, hence this closure. """ try: # retrieve Python callback and arguments call, args, kwds = self._callbacks[k] # deref event.contents to simplify callback code call(event.contents, *args, **kwds) except KeyError: # detached? pass self._callback_handler = _callback_handler self._callbacks = {} k = eventtype.value r = libvlc_event_attach(self, k, self._callback_handler, k) if not r: self._callbacks[k] = (callback, args, kwds) return r def event_detach(self, eventtype): """Unregister an event notification. @param eventtype: the event type notification to be removed. """ if not isinstance(eventtype, EventType): raise VLCException("%s required: %r" % ('EventType', eventtype)) k = eventtype.value if k in self._callbacks: del self._callbacks[k] # remove, regardless of libvlc return value libvlc_event_detach(self, k, self._callback_handler, k) class Instance(_Ctype): '''Create a new Instance instance. It may take as parameter either: - a string - a list of strings as first parameters - the parameters given as the constructor parameters (must be strings) ''' def __new__(cls, *args): if len(args) == 1: # Only 1 arg. It is either a C pointer, or an arg string, # or a tuple. i = args[0] if isinstance(i, _Ints): return _Constructor(cls, i) elif isinstance(i, basestring): args = i.strip().split() elif isinstance(i, _Seqs): args = i else: raise VLCException('Instance %r' % (args,)) if not args and plugin_path is not None: # no parameters passed, for win32 and MacOS, # specify the plugin_path if detected earlier args = ['vlc', '--plugin-path=' + plugin_path] if PYTHON3: args = [ str_to_bytes(a) for a in args ] return libvlc_new(len(args), args) def media_player_new(self, uri=None): """Create a new MediaPlayer instance. @param uri: an optional URI to play in the player. """ p = libvlc_media_player_new(self) if uri: p.set_media(self.media_new(uri)) p._instance = self return p def media_list_player_new(self): """Create a new MediaListPlayer instance. """ p = libvlc_media_list_player_new(self) p._instance = self return p def media_new(self, mrl, *options): """Create a new Media instance. If mrl contains a colon (:) preceded by more than 1 letter, it will be treated as a URL. Else, it will be considered as a local path. If you need more control, directly use media_new_location/media_new_path methods. Options can be specified as supplementary string parameters, e.g. C{m = i.media_new('foo.avi', 'sub-filter=marq{marquee=Hello}', 'vout-filter=invert')} Alternatively, the options can be added to the media using the Media.add_options method: C{m.add_options('foo.avi', 'sub-filter=marq@test{marquee=Hello}', 'video-filter=invert')} @param options: optional media option=value strings """ if ':' in mrl and mrl.index(':') > 1: # Assume it is a URL m = libvlc_media_new_location(self, str_to_bytes(mrl)) else: # Else it should be a local path. m = libvlc_media_new_path(self, str_to_bytes(os.path.normpath(mrl))) for o in options: libvlc_media_add_option(m, str_to_bytes(o)) m._instance = self return m def media_list_new(self, mrls=None): """Create a new MediaList instance. @param mrls: optional list of MRL strings """ l = libvlc_media_list_new(self) # We should take the lock, but since we did not leak the # reference, nobody else can access it. if mrls: for m in mrls: l.add_media(m) l._instance = self return l def audio_output_enumerate_devices(self): """Enumerate the defined audio output devices. @return: list of dicts {name:, description:, devices:} """ r = [] head = libvlc_audio_output_list_get(self) if head: i = head while i: i = i.contents d = [{'id': libvlc_audio_output_device_id (self, i.name, d), 'longname': libvlc_audio_output_device_longname(self, i.name, d)} for d in range(libvlc_audio_output_device_count (self, i.name))] r.append({'name': i.name, 'description': i.description, 'devices': d}) i = i.next libvlc_audio_output_list_release(head) return r def audio_filter_list_get(self): """Returns a list of available audio filters. """ return module_description_list(libvlc_audio_filter_list_get(self)) def video_filter_list_get(self): """Returns a list of available video filters. """ return module_description_list(libvlc_video_filter_list_get(self)) def release(self): '''Decrement the reference count of a libvlc instance, and destroy it if it reaches zero. ''' return libvlc_release(self) def retain(self): '''Increments the reference count of a libvlc instance. The initial reference count is 1 after L{new}() returns. ''' return libvlc_retain(self) def add_intf(self, name): '''Try to start a user interface for the libvlc instance. @param name: interface name, or NULL for default. @return: 0 on success, -1 on error. ''' return libvlc_add_intf(self, str_to_bytes(name)) def set_user_agent(self, name, http): '''Sets the application name. LibVLC passes this as the user agent string when a protocol requires it. @param name: human-readable application name, e.g. "FooBar player 1.2.3". @param http: HTTP User Agent, e.g. "FooBar/1.2.3 Python/2.6.0". @version: LibVLC 1.1.1 or later. ''' return libvlc_set_user_agent(self, str_to_bytes(name), str_to_bytes(http)) def log_unset(self): '''Unsets the logging callback for a LibVLC instance. This is rarely needed: the callback is implicitly unset when the instance is destroyed. This function will wait for any pending callbacks invocation to complete (causing a deadlock if called from within the callback). @version: LibVLC 2.1.0 or later. ''' return libvlc_log_unset(self) def log_set(self, data, p_instance): '''Sets the logging callback for a LibVLC instance. This function is thread-safe: it will wait for any pending callbacks invocation to complete. @param data: opaque data pointer for the callback function @note Some log messages (especially debug) are emitted by LibVLC while is being initialized. These messages cannot be captured with this interface. @warning A deadlock may occur if this function is called from the callback. @param p_instance: libvlc instance. @version: LibVLC 2.1.0 or later. ''' return libvlc_log_set(self, data, p_instance) def log_set_file(self, stream): '''Sets up logging to a file. @param stream: FILE pointer opened for writing (the FILE pointer must remain valid until L{log_unset}()). @version: LibVLC 2.1.0 or later. ''' return libvlc_log_set_file(self, stream) def media_new_location(self, psz_mrl): '''Create a media with a certain given media resource location, for instance a valid URL. @note: To refer to a local file with this function, the file://... URI syntax B{must} be used (see IETF RFC3986). We recommend using L{media_new_path}() instead when dealing with local files. See L{media_release}. @param psz_mrl: the media location. @return: the newly created media or NULL on error. ''' return libvlc_media_new_location(self, str_to_bytes(psz_mrl)) def media_new_path(self, path): '''Create a media for a certain file path. See L{media_release}. @param path: local filesystem path. @return: the newly created media or NULL on error. ''' return libvlc_media_new_path(self, str_to_bytes(path)) def media_new_fd(self, fd): '''Create a media for an already open file descriptor. The file descriptor shall be open for reading (or reading and writing). Regular file descriptors, pipe read descriptors and character device descriptors (including TTYs) are supported on all platforms. Block device descriptors are supported where available. Directory descriptors are supported on systems that provide fdopendir(). Sockets are supported on all platforms where they are file descriptors, i.e. all except Windows. @note: This library will B{not} automatically close the file descriptor under any circumstance. Nevertheless, a file descriptor can usually only be rendered once in a media player. To render it a second time, the file descriptor should probably be rewound to the beginning with lseek(). See L{media_release}. @param fd: open file descriptor. @return: the newly created media or NULL on error. @version: LibVLC 1.1.5 and later. ''' return libvlc_media_new_fd(self, fd) def media_new_as_node(self, psz_name): '''Create a media as an empty node with a given name. See L{media_release}. @param psz_name: the name of the node. @return: the new empty media or NULL on error. ''' return libvlc_media_new_as_node(self, str_to_bytes(psz_name)) def media_discoverer_new_from_name(self, psz_name): '''Discover media service by name. @param psz_name: service name. @return: media discover object or NULL in case of error. ''' return libvlc_media_discoverer_new_from_name(self, str_to_bytes(psz_name)) def media_library_new(self): '''Create an new Media Library object. @return: a new object or NULL on error. ''' return libvlc_media_library_new(self) def audio_output_list_get(self): '''Gets the list of available audio outputs. @return: list of available audio outputs. It must be freed it with In case of error, NULL is returned. ''' return libvlc_audio_output_list_get(self) def audio_output_device_list_get(self, aout): '''Gets a list of audio output devices for a given audio output. See L{audio_output_device_set}(). @note: Not all audio outputs support this. In particular, an empty (NULL) list of devices does B{not} imply that the specified audio output does not work. @note: The list might not be exhaustive. @warning: Some audio output devices in the list might not actually work in some circumstances. By default, it is recommended to not specify any explicit audio device. @param psz_aout: audio output name (as returned by L{audio_output_list_get}()). @return: A NULL-terminated linked list of potential audio output devices. It must be freed it with L{audio_output_device_list_release}(). @version: LibVLC 2.1.0 or later. ''' return libvlc_audio_output_device_list_get(self, str_to_bytes(aout)) def vlm_release(self): '''Release the vlm instance related to the given L{Instance}. ''' return libvlc_vlm_release(self) def vlm_add_broadcast(self, psz_name, psz_input, psz_output, i_options, ppsz_options, b_enabled, b_loop): '''Add a broadcast, with one input. @param psz_name: the name of the new broadcast. @param psz_input: the input MRL. @param psz_output: the output MRL (the parameter to the "sout" variable). @param i_options: number of additional options. @param ppsz_options: additional options. @param b_enabled: boolean for enabling the new broadcast. @param b_loop: Should this broadcast be played in loop ? @return: 0 on success, -1 on error. ''' return libvlc_vlm_add_broadcast(self, str_to_bytes(psz_name), str_to_bytes(psz_input), str_to_bytes(psz_output), i_options, ppsz_options, b_enabled, b_loop) def vlm_add_vod(self, psz_name, psz_input, i_options, ppsz_options, b_enabled, psz_mux): '''Add a vod, with one input. @param psz_name: the name of the new vod media. @param psz_input: the input MRL. @param i_options: number of additional options. @param ppsz_options: additional options. @param b_enabled: boolean for enabling the new vod. @param psz_mux: the muxer of the vod media. @return: 0 on success, -1 on error. ''' return libvlc_vlm_add_vod(self, str_to_bytes(psz_name), str_to_bytes(psz_input), i_options, ppsz_options, b_enabled, str_to_bytes(psz_mux)) def vlm_del_media(self, psz_name): '''Delete a media (VOD or broadcast). @param psz_name: the media to delete. @return: 0 on success, -1 on error. ''' return libvlc_vlm_del_media(self, str_to_bytes(psz_name)) def vlm_set_enabled(self, psz_name, b_enabled): '''Enable or disable a media (VOD or broadcast). @param psz_name: the media to work on. @param b_enabled: the new status. @return: 0 on success, -1 on error. ''' return libvlc_vlm_set_enabled(self, str_to_bytes(psz_name), b_enabled) def vlm_set_output(self, psz_name, psz_output): '''Set the output for a media. @param psz_name: the media to work on. @param psz_output: the output MRL (the parameter to the "sout" variable). @return: 0 on success, -1 on error. ''' return libvlc_vlm_set_output(self, str_to_bytes(psz_name), str_to_bytes(psz_output)) def vlm_set_input(self, psz_name, psz_input): '''Set a media's input MRL. This will delete all existing inputs and add the specified one. @param psz_name: the media to work on. @param psz_input: the input MRL. @return: 0 on success, -1 on error. ''' return libvlc_vlm_set_input(self, str_to_bytes(psz_name), str_to_bytes(psz_input)) def vlm_add_input(self, psz_name, psz_input): '''Add a media's input MRL. This will add the specified one. @param psz_name: the media to work on. @param psz_input: the input MRL. @return: 0 on success, -1 on error. ''' return libvlc_vlm_add_input(self, str_to_bytes(psz_name), str_to_bytes(psz_input)) def vlm_set_loop(self, psz_name, b_loop): '''Set a media's loop status. @param psz_name: the media to work on. @param b_loop: the new status. @return: 0 on success, -1 on error. ''' return libvlc_vlm_set_loop(self, str_to_bytes(psz_name), b_loop) def vlm_set_mux(self, psz_name, psz_mux): '''Set a media's vod muxer. @param psz_name: the media to work on. @param psz_mux: the new muxer. @return: 0 on success, -1 on error. ''' return libvlc_vlm_set_mux(self, str_to_bytes(psz_name), str_to_bytes(psz_mux)) def vlm_change_media(self, psz_name, psz_input, psz_output, i_options, ppsz_options, b_enabled, b_loop): '''Edit the parameters of a media. This will delete all existing inputs and add the specified one. @param psz_name: the name of the new broadcast. @param psz_input: the input MRL. @param psz_output: the output MRL (the parameter to the "sout" variable). @param i_options: number of additional options. @param ppsz_options: additional options. @param b_enabled: boolean for enabling the new broadcast. @param b_loop: Should this broadcast be played in loop ? @return: 0 on success, -1 on error. ''' return libvlc_vlm_change_media(self, str_to_bytes(psz_name), str_to_bytes(psz_input), str_to_bytes(psz_output), i_options, ppsz_options, b_enabled, b_loop) def vlm_play_media(self, psz_name): '''Play the named broadcast. @param psz_name: the name of the broadcast. @return: 0 on success, -1 on error. ''' return libvlc_vlm_play_media(self, str_to_bytes(psz_name)) def vlm_stop_media(self, psz_name): '''Stop the named broadcast. @param psz_name: the name of the broadcast. @return: 0 on success, -1 on error. ''' return libvlc_vlm_stop_media(self, str_to_bytes(psz_name)) def vlm_pause_media(self, psz_name): '''Pause the named broadcast. @param psz_name: the name of the broadcast. @return: 0 on success, -1 on error. ''' return libvlc_vlm_pause_media(self, str_to_bytes(psz_name)) def vlm_seek_media(self, psz_name, f_percentage): '''Seek in the named broadcast. @param psz_name: the name of the broadcast. @param f_percentage: the percentage to seek to. @return: 0 on success, -1 on error. ''' return libvlc_vlm_seek_media(self, str_to_bytes(psz_name), f_percentage) def vlm_show_media(self, psz_name): '''Return information about the named media as a JSON string representation. This function is mainly intended for debugging use, if you want programmatic access to the state of a vlm_media_instance_t, please use the corresponding libvlc_vlm_get_media_instance_xxx -functions. Currently there are no such functions available for vlm_media_t though. @param psz_name: the name of the media, if the name is an empty string, all media is described. @return: string with information about named media, or NULL on error. ''' return libvlc_vlm_show_media(self, str_to_bytes(psz_name)) def vlm_get_media_instance_position(self, psz_name, i_instance): '''Get vlm_media instance position by name or instance id. @param psz_name: name of vlm media instance. @param i_instance: instance id. @return: position as float or -1. on error. ''' return libvlc_vlm_get_media_instance_position(self, str_to_bytes(psz_name), i_instance) def vlm_get_media_instance_time(self, psz_name, i_instance): '''Get vlm_media instance time by name or instance id. @param psz_name: name of vlm media instance. @param i_instance: instance id. @return: time as integer or -1 on error. ''' return libvlc_vlm_get_media_instance_time(self, str_to_bytes(psz_name), i_instance) def vlm_get_media_instance_length(self, psz_name, i_instance): '''Get vlm_media instance length by name or instance id. @param psz_name: name of vlm media instance. @param i_instance: instance id. @return: length of media item or -1 on error. ''' return libvlc_vlm_get_media_instance_length(self, str_to_bytes(psz_name), i_instance) def vlm_get_media_instance_rate(self, psz_name, i_instance): '''Get vlm_media instance playback rate by name or instance id. @param psz_name: name of vlm media instance. @param i_instance: instance id. @return: playback rate or -1 on error. ''' return libvlc_vlm_get_media_instance_rate(self, str_to_bytes(psz_name), i_instance) def vlm_get_media_instance_title(self, psz_name, i_instance): '''Get vlm_media instance title number by name or instance id. @param psz_name: name of vlm media instance. @param i_instance: instance id. @return: title as number or -1 on error. @bug: will always return 0. ''' return libvlc_vlm_get_media_instance_title(self, str_to_bytes(psz_name), i_instance) def vlm_get_media_instance_chapter(self, psz_name, i_instance): '''Get vlm_media instance chapter number by name or instance id. @param psz_name: name of vlm media instance. @param i_instance: instance id. @return: chapter as number or -1 on error. @bug: will always return 0. ''' return libvlc_vlm_get_media_instance_chapter(self, str_to_bytes(psz_name), i_instance) def vlm_get_media_instance_seekable(self, psz_name, i_instance): '''Is libvlc instance seekable ? @param psz_name: name of vlm media instance. @param i_instance: instance id. @return: 1 if seekable, 0 if not, -1 if media does not exist. @bug: will always return 0. ''' return libvlc_vlm_get_media_instance_seekable(self, str_to_bytes(psz_name), i_instance) def vlm_get_event_manager(self): '''Get libvlc_event_manager from a vlm media. The p_event_manager is immutable, so you don't have to hold the lock. @return: libvlc_event_manager. ''' return libvlc_vlm_get_event_manager(self) class Media(_Ctype): '''Create a new Media instance. Usage: Media(MRL, *options) See vlc.Instance.media_new documentation for details. ''' def __new__(cls, *args): if args: i = args[0] if isinstance(i, _Ints): return _Constructor(cls, i) if isinstance(i, Instance): return i.media_new(*args[1:]) o = get_default_instance().media_new(*args) return o def get_instance(self): return getattr(self, '_instance', None) def add_options(self, *options): """Add a list of options to the media. Options must be written without the double-dash, e.g.: C{m.add_options('sub-filter=marq@test{marquee=Hello}', 'video-filter=invert')} Alternatively, the options can directly be passed in the Instance.media_new method: C{m = instance.media_new('foo.avi', 'sub-filter=marq@test{marquee=Hello}', 'video-filter=invert')} @param options: optional media option=value strings """ for o in options: self.add_option(o) def add_option(self, psz_options): '''Add an option to the media. This option will be used to determine how the media_player will read the media. This allows to use VLC's advanced reading/streaming options on a per-media basis. @note: The options are listed in 'vlc --long-help' from the command line, e.g. "-sout-all". Keep in mind that available options and their semantics vary across LibVLC versions and builds. @warning: Not all options affects L{Media} objects: Specifically, due to architectural issues most audio and video options, such as text renderer options, have no effects on an individual media. These options must be set through L{new}() instead. @param psz_options: the options (as a string). ''' return libvlc_media_add_option(self, str_to_bytes(psz_options)) def add_option_flag(self, psz_options, i_flags): '''Add an option to the media with configurable flags. This option will be used to determine how the media_player will read the media. This allows to use VLC's advanced reading/streaming options on a per-media basis. The options are detailed in vlc --long-help, for instance "--sout-all". Note that all options are not usable on medias: specifically, due to architectural issues, video-related options such as text renderer options cannot be set on a single media. They must be set on the whole libvlc instance instead. @param psz_options: the options (as a string). @param i_flags: the flags for this option. ''' return libvlc_media_add_option_flag(self, str_to_bytes(psz_options), i_flags) def retain(self): '''Retain a reference to a media descriptor object (libvlc_media_t). Use L{release}() to decrement the reference count of a media descriptor object. ''' return libvlc_media_retain(self) def release(self): '''Decrement the reference count of a media descriptor object. If the reference count is 0, then L{release}() will release the media descriptor object. It will send out an libvlc_MediaFreed event to all listeners. If the media descriptor object has been released it should not be used again. ''' return libvlc_media_release(self) def get_mrl(self): '''Get the media resource locator (mrl) from a media descriptor object. @return: string with mrl of media descriptor object. ''' return libvlc_media_get_mrl(self) def duplicate(self): '''Duplicate a media descriptor object. ''' return libvlc_media_duplicate(self) def get_meta(self, e_meta): '''Read the meta of the media. If the media has not yet been parsed this will return NULL. This methods automatically calls L{parse_async}(), so after calling it you may receive a libvlc_MediaMetaChanged event. If you prefer a synchronous version ensure that you call L{parse}() before get_meta(). See L{parse} See L{parse_async} See libvlc_MediaMetaChanged. @param e_meta: the meta to read. @return: the media's meta. ''' return libvlc_media_get_meta(self, e_meta) def set_meta(self, e_meta, psz_value): '''Set the meta of the media (this function will not save the meta, call L{save_meta} in order to save the meta). @param e_meta: the meta to write. @param psz_value: the media's meta. ''' return libvlc_media_set_meta(self, e_meta, str_to_bytes(psz_value)) def save_meta(self): '''Save the meta previously set. @return: true if the write operation was successful. ''' return libvlc_media_save_meta(self) def get_state(self): '''Get current state of media descriptor object. Possible media states are defined in libvlc_structures.c ( libvlc_NothingSpecial=0, libvlc_Opening, libvlc_Buffering, libvlc_Playing, libvlc_Paused, libvlc_Stopped, libvlc_Ended, libvlc_Error). See libvlc_state_t. @return: state of media descriptor object. ''' return libvlc_media_get_state(self) def get_stats(self, p_stats): '''Get the current statistics about the media. @param p_stats:: structure that contain the statistics about the media (this structure must be allocated by the caller). @return: true if the statistics are available, false otherwise \libvlc_return_bool. ''' return libvlc_media_get_stats(self, p_stats) def subitems(self): '''Get subitems of media descriptor object. This will increment the reference count of supplied media descriptor object. Use L{list_release}() to decrement the reference counting. @return: list of media descriptor subitems or NULL. ''' return libvlc_media_subitems(self) def event_manager(self): '''Get event manager from media descriptor object. NOTE: this function doesn't increment reference counting. @return: event manager object. ''' return libvlc_media_event_manager(self) def get_duration(self): '''Get duration (in ms) of media descriptor object item. @return: duration of media item or -1 on error. ''' return libvlc_media_get_duration(self) def parse(self): '''Parse a media. This fetches (local) meta data and tracks information. The method is synchronous. See L{parse_async} See L{get_meta} See libvlc_media_get_tracks_info. ''' return libvlc_media_parse(self) def parse_async(self): '''Parse a media. This fetches (local) meta data and tracks information. The method is the asynchronous of L{parse}(). To track when this is over you can listen to libvlc_MediaParsedChanged event. However if the media was already parsed you will not receive this event. See L{parse} See libvlc_MediaParsedChanged See L{get_meta} See libvlc_media_get_tracks_info. ''' return libvlc_media_parse_async(self) def is_parsed(self): '''Get Parsed status for media descriptor object. See libvlc_MediaParsedChanged. @return: true if media object has been parsed otherwise it returns false \libvlc_return_bool. ''' return libvlc_media_is_parsed(self) def set_user_data(self, p_new_user_data): '''Sets media descriptor's user_data. user_data is specialized data accessed by the host application, VLC.framework uses it as a pointer to an native object that references a L{Media} pointer. @param p_new_user_data: pointer to user data. ''' return libvlc_media_set_user_data(self, p_new_user_data) def get_user_data(self): '''Get media descriptor's user_data. user_data is specialized data accessed by the host application, VLC.framework uses it as a pointer to an native object that references a L{Media} pointer. ''' return libvlc_media_get_user_data(self) def tracks_get(self, tracks): '''Get media descriptor's elementary streams description Note, you need to call L{parse}() or play the media at least once before calling this function. Not doing this will result in an empty array. @param tracks: address to store an allocated array of Elementary Streams descriptions (must be freed with L{tracks_release}. @return: the number of Elementary Streams (zero on error). @version: LibVLC 2.1.0 and later. ''' return libvlc_media_tracks_get(self, tracks) def player_new_from_media(self): '''Create a Media Player object from a Media. @return: a new media player object, or NULL on error. ''' return libvlc_media_player_new_from_media(self) class MediaDiscoverer(_Ctype): '''N/A ''' def __new__(cls, ptr=_internal_guard): '''(INTERNAL) ctypes wrapper constructor. ''' return _Constructor(cls, ptr) def release(self): '''Release media discover object. If the reference count reaches 0, then the object will be released. ''' return libvlc_media_discoverer_release(self) def localized_name(self): '''Get media service discover object its localized name. @return: localized name. ''' return libvlc_media_discoverer_localized_name(self) def media_list(self): '''Get media service discover media list. @return: list of media items. ''' return libvlc_media_discoverer_media_list(self) def event_manager(self): '''Get event manager from media service discover object. @return: event manager object. ''' return libvlc_media_discoverer_event_manager(self) def is_running(self): '''Query if media service discover object is running. @return: true if running, false if not \libvlc_return_bool. ''' return libvlc_media_discoverer_is_running(self) class MediaLibrary(_Ctype): '''N/A ''' def __new__(cls, ptr=_internal_guard): '''(INTERNAL) ctypes wrapper constructor. ''' return _Constructor(cls, ptr) def release(self): '''Release media library object. This functions decrements the reference count of the media library object. If it reaches 0, then the object will be released. ''' return libvlc_media_library_release(self) def retain(self): '''Retain a reference to a media library object. This function will increment the reference counting for this object. Use L{release}() to decrement the reference count. ''' return libvlc_media_library_retain(self) def load(self): '''Load media library. @return: 0 on success, -1 on error. ''' return libvlc_media_library_load(self) def media_list(self): '''Get media library subitems. @return: media list subitems. ''' return libvlc_media_library_media_list(self) class MediaList(_Ctype): '''Create a new MediaList instance. Usage: MediaList(list_of_MRLs) See vlc.Instance.media_list_new documentation for details. ''' def __new__(cls, *args): if args: i = args[0] if isinstance(i, _Ints): return _Constructor(cls, i) if isinstance(i, Instance): return i.media_list_new(*args[1:]) o = get_default_instance().media_list_new(*args) return o def get_instance(self): return getattr(self, '_instance', None) def add_media(self, mrl): """Add media instance to media list. The L{lock} should be held upon entering this function. @param mrl: a media instance or a MRL. @return: 0 on success, -1 if the media list is read-only. """ if isinstance(mrl, basestring): mrl = (self.get_instance() or get_default_instance()).media_new(mrl) return libvlc_media_list_add_media(self, mrl) def release(self): '''Release media list created with L{new}(). ''' return libvlc_media_list_release(self) def retain(self): '''Retain reference to a media list. ''' return libvlc_media_list_retain(self) def set_media(self, p_md): '''Associate media instance with this media list instance. If another media instance was present it will be released. The L{lock} should NOT be held upon entering this function. @param p_md: media instance to add. ''' return libvlc_media_list_set_media(self, p_md) def media(self): '''Get media instance from this media list instance. This action will increase the refcount on the media instance. The L{lock} should NOT be held upon entering this function. @return: media instance. ''' return libvlc_media_list_media(self) def insert_media(self, p_md, i_pos): '''Insert media instance in media list on a position The L{lock} should be held upon entering this function. @param p_md: a media instance. @param i_pos: position in array where to insert. @return: 0 on success, -1 if the media list is read-only. ''' return libvlc_media_list_insert_media(self, p_md, i_pos) def remove_index(self, i_pos): '''Remove media instance from media list on a position The L{lock} should be held upon entering this function. @param i_pos: position in array where to insert. @return: 0 on success, -1 if the list is read-only or the item was not found. ''' return libvlc_media_list_remove_index(self, i_pos) def count(self): '''Get count on media list items The L{lock} should be held upon entering this function. @return: number of items in media list. ''' return libvlc_media_list_count(self) def __len__(self): return libvlc_media_list_count(self) def item_at_index(self, i_pos): '''List media instance in media list at a position The L{lock} should be held upon entering this function. @param i_pos: position in array where to insert. @return: media instance at position i_pos, or NULL if not found. In case of success, L{media_retain}() is called to increase the refcount on the media. ''' return libvlc_media_list_item_at_index(self, i_pos) def __getitem__(self, i): return libvlc_media_list_item_at_index(self, i) def __iter__(self): for i in range(len(self)): yield self[i] def index_of_item(self, p_md): '''Find index position of List media instance in media list. Warning: the function will return the first matched position. The L{lock} should be held upon entering this function. @param p_md: media instance. @return: position of media instance or -1 if media not found. ''' return libvlc_media_list_index_of_item(self, p_md) def is_readonly(self): '''This indicates if this media list is read-only from a user point of view. @return: 1 on readonly, 0 on readwrite \libvlc_return_bool. ''' return libvlc_media_list_is_readonly(self) def lock(self): '''Get lock on media list items. ''' return libvlc_media_list_lock(self) def unlock(self): '''Release lock on media list items The L{lock} should be held upon entering this function. ''' return libvlc_media_list_unlock(self) def event_manager(self): '''Get libvlc_event_manager from this media list instance. The p_event_manager is immutable, so you don't have to hold the lock. @return: libvlc_event_manager. ''' return libvlc_media_list_event_manager(self) class MediaListPlayer(_Ctype): '''Create a new MediaListPlayer instance. It may take as parameter either: - a vlc.Instance - nothing ''' def __new__(cls, arg=None): if arg is None: i = get_default_instance() elif isinstance(arg, Instance): i = arg elif isinstance(arg, _Ints): return _Constructor(cls, arg) else: raise TypeError('MediaListPlayer %r' % (arg,)) return i.media_list_player_new() def get_instance(self): """Return the associated Instance. """ return self._instance #PYCHOK expected def release(self): '''Release a media_list_player after use Decrement the reference count of a media player object. If the reference count is 0, then L{release}() will release the media player object. If the media player object has been released, then it should not be used again. ''' return libvlc_media_list_player_release(self) def retain(self): '''Retain a reference to a media player list object. Use L{release}() to decrement reference count. ''' return libvlc_media_list_player_retain(self) def event_manager(self): '''Return the event manager of this media_list_player. @return: the event manager. ''' return libvlc_media_list_player_event_manager(self) def set_media_player(self, p_mi): '''Replace media player in media_list_player with this instance. @param p_mi: media player instance. ''' return libvlc_media_list_player_set_media_player(self, p_mi) def set_media_list(self, p_mlist): '''Set the media list associated with the player. @param p_mlist: list of media. ''' return libvlc_media_list_player_set_media_list(self, p_mlist) def play(self): '''Play media list. ''' return libvlc_media_list_player_play(self) def pause(self): '''Toggle pause (or resume) media list. ''' return libvlc_media_list_player_pause(self) def is_playing(self): '''Is media list playing? @return: true for playing and false for not playing \libvlc_return_bool. ''' return libvlc_media_list_player_is_playing(self) def get_state(self): '''Get current libvlc_state of media list player. @return: libvlc_state_t for media list player. ''' return libvlc_media_list_player_get_state(self) def play_item_at_index(self, i_index): '''Play media list item at position index. @param i_index: index in media list to play. @return: 0 upon success -1 if the item wasn't found. ''' return libvlc_media_list_player_play_item_at_index(self, i_index) def __getitem__(self, i): return libvlc_media_list_player_play_item_at_index(self, i) def __iter__(self): for i in range(len(self)): yield self[i] def play_item(self, p_md): '''Play the given media item. @param p_md: the media instance. @return: 0 upon success, -1 if the media is not part of the media list. ''' return libvlc_media_list_player_play_item(self, p_md) def stop(self): '''Stop playing media list. ''' return libvlc_media_list_player_stop(self) def next(self): '''Play next item from media list. @return: 0 upon success -1 if there is no next item. ''' return libvlc_media_list_player_next(self) def previous(self): '''Play previous item from media list. @return: 0 upon success -1 if there is no previous item. ''' return libvlc_media_list_player_previous(self) def set_playback_mode(self, e_mode): '''Sets the playback mode for the playlist. @param e_mode: playback mode specification. ''' return libvlc_media_list_player_set_playback_mode(self, e_mode) class MediaPlayer(_Ctype): '''Create a new MediaPlayer instance. It may take as parameter either: - a string (media URI), options... In this case, a vlc.Instance will be created. - a vlc.Instance, a string (media URI), options... ''' def __new__(cls, *args): if len(args) == 1 and isinstance(args[0], _Ints): return _Constructor(cls, args[0]) if args and isinstance(args[0], Instance): instance = args[0] args = args[1:] else: instance = get_default_instance() o = instance.media_player_new() if args: o.set_media(instance.media_new(*args)) return o def get_instance(self): """Return the associated Instance. """ return self._instance #PYCHOK expected def set_mrl(self, mrl, *options): """Set the MRL to play. @param mrl: The MRL @param options: optional media option=value strings @return: the Media object """ m = self.get_instance().media_new(mrl, *options) self.set_media(m) return m def video_get_spu_description(self): """Get the description of available video subtitles. """ return track_description_list(libvlc_video_get_spu_description(self)) def video_get_title_description(self): """Get the description of available titles. """ return track_description_list(libvlc_video_get_title_description(self)) def video_get_chapter_description(self, title): """Get the description of available chapters for specific title. @param title: selected title (int) """ return track_description_list(libvlc_video_get_chapter_description(self, title)) def video_get_track_description(self): """Get the description of available video tracks. """ return track_description_list(libvlc_video_get_track_description(self)) def audio_get_track_description(self): """Get the description of available audio tracks. """ return track_description_list(libvlc_audio_get_track_description(self)) def video_get_size(self, num=0): """Get the video size in pixels as 2-tuple (width, height). @param num: video number (default 0). """ r = libvlc_video_get_size(self, num) if isinstance(r, tuple) and len(r) == 2: return r else: raise VLCException('invalid video number (%s)' % (num,)) def set_hwnd(self, drawable): """Set a Win32/Win64 API window handle (HWND). Specify where the media player should render its video output. If LibVLC was built without Win32/Win64 API output support, then this has no effects. @param drawable: windows handle of the drawable. """ if not isinstance(drawable, ctypes.c_void_p): drawable = ctypes.c_void_p(int(drawable)) libvlc_media_player_set_hwnd(self, drawable) def video_get_width(self, num=0): """Get the width of a video in pixels. @param num: video number (default 0). """ return self.video_get_size(num)[0] def video_get_height(self, num=0): """Get the height of a video in pixels. @param num: video number (default 0). """ return self.video_get_size(num)[1] def video_get_cursor(self, num=0): """Get the mouse pointer coordinates over a video as 2-tuple (x, y). Coordinates are expressed in terms of the decoded video resolution, B{not} in terms of pixels on the screen/viewport. To get the latter, you must query your windowing system directly. Either coordinate may be negative or larger than the corresponding size of the video, if the cursor is outside the rendering area. @warning: The coordinates may be out-of-date if the pointer is not located on the video rendering area. LibVLC does not track the mouse pointer if the latter is outside the video widget. @note: LibVLC does not support multiple mouse pointers (but does support multiple input devices sharing the same pointer). @param num: video number (default 0). """ r = libvlc_video_get_cursor(self, num) if isinstance(r, tuple) and len(r) == 2: return r raise VLCException('invalid video number (%s)' % (num,)) def release(self): '''Release a media_player after use Decrement the reference count of a media player object. If the reference count is 0, then L{release}() will release the media player object. If the media player object has been released, then it should not be used again. ''' return libvlc_media_player_release(self) def retain(self): '''Retain a reference to a media player object. Use L{release}() to decrement reference count. ''' return libvlc_media_player_retain(self) def set_media(self, p_md): '''Set the media that will be used by the media_player. If any, previous md will be released. @param p_md: the Media. Afterwards the p_md can be safely destroyed. ''' return libvlc_media_player_set_media(self, p_md) def get_media(self): '''Get the media used by the media_player. @return: the media associated with p_mi, or NULL if no media is associated. ''' return libvlc_media_player_get_media(self) def event_manager(self): '''Get the Event Manager from which the media player send event. @return: the event manager associated with p_mi. ''' return libvlc_media_player_event_manager(self) def is_playing(self): '''is_playing. @return: 1 if the media player is playing, 0 otherwise \libvlc_return_bool. ''' return libvlc_media_player_is_playing(self) def play(self): '''Play. @return: 0 if playback started (and was already started), or -1 on error. ''' return libvlc_media_player_play(self) def set_pause(self, do_pause): '''Pause or resume (no effect if there is no media). @param do_pause: play/resume if zero, pause if non-zero. @version: LibVLC 1.1.1 or later. ''' return libvlc_media_player_set_pause(self, do_pause) def pause(self): '''Toggle pause (no effect if there is no media). ''' return libvlc_media_player_pause(self) def stop(self): '''Stop (no effect if there is no media). ''' return libvlc_media_player_stop(self) def video_set_callbacks(self, lock, unlock, display, opaque): '''Set callbacks and private data to render decoded video to a custom area in memory. Use L{video_set_format}() or L{video_set_format_callbacks}() to configure the decoded format. @param lock: callback to lock video memory (must not be NULL). @param unlock: callback to unlock video memory (or NULL if not needed). @param display: callback to display video (or NULL if not needed). @param opaque: private pointer for the three callbacks (as first parameter). @version: LibVLC 1.1.1 or later. ''' return libvlc_video_set_callbacks(self, lock, unlock, display, opaque) def video_set_format(self, chroma, width, height, pitch): '''Set decoded video chroma and dimensions. This only works in combination with L{video_set_callbacks}(), and is mutually exclusive with L{video_set_format_callbacks}(). @param chroma: a four-characters string identifying the chroma (e.g. "RV32" or "YUYV"). @param width: pixel width. @param height: pixel height. @param pitch: line pitch (in bytes). @version: LibVLC 1.1.1 or later. @bug: All pixel planes are expected to have the same pitch. To use the YCbCr color space with chrominance subsampling, consider using L{video_set_format_callbacks}() instead. ''' return libvlc_video_set_format(self, str_to_bytes(chroma), width, height, pitch) def video_set_format_callbacks(self, setup, cleanup): '''Set decoded video chroma and dimensions. This only works in combination with L{video_set_callbacks}(). @param setup: callback to select the video format (cannot be NULL). @param cleanup: callback to release any allocated resources (or NULL). @version: LibVLC 2.0.0 or later. ''' return libvlc_video_set_format_callbacks(self, setup, cleanup) def set_nsobject(self, drawable): '''Set the NSView handler where the media player should render its video output. Use the vout called "macosx". The drawable is an NSObject that follow the VLCOpenGLVideoViewEmbedding protocol: @begincode \@protocol VLCOpenGLVideoViewEmbedding <NSObject> - (void)addVoutSubview:(NSView *)view; - (void)removeVoutSubview:(NSView *)view; \@end @endcode Or it can be an NSView object. If you want to use it along with Qt4 see the QMacCocoaViewContainer. Then the following code should work: @begincode NSView *video = [[NSView alloc] init]; QMacCocoaViewContainer *container = new QMacCocoaViewContainer(video, parent); L{set_nsobject}(mp, video); [video release]; @endcode You can find a live example in VLCVideoView in VLCKit.framework. @param drawable: the drawable that is either an NSView or an object following the VLCOpenGLVideoViewEmbedding protocol. ''' return libvlc_media_player_set_nsobject(self, drawable) def get_nsobject(self): '''Get the NSView handler previously set with L{set_nsobject}(). @return: the NSView handler or 0 if none where set. ''' return libvlc_media_player_get_nsobject(self) def set_agl(self, drawable): '''Set the agl handler where the media player should render its video output. @param drawable: the agl handler. ''' return libvlc_media_player_set_agl(self, drawable) def get_agl(self): '''Get the agl handler previously set with L{set_agl}(). @return: the agl handler or 0 if none where set. ''' return libvlc_media_player_get_agl(self) def set_xwindow(self, drawable): '''Set an X Window System drawable where the media player should render its video output. If LibVLC was built without X11 output support, then this has no effects. The specified identifier must correspond to an existing Input/Output class X11 window. Pixmaps are B{not} supported. The caller shall ensure that the X11 server is the same as the one the VLC instance has been configured with. This function must be called before video playback is started; otherwise it will only take effect after playback stop and restart. @param drawable: the ID of the X window. ''' return libvlc_media_player_set_xwindow(self, drawable) def get_xwindow(self): '''Get the X Window System window identifier previously set with L{set_xwindow}(). Note that this will return the identifier even if VLC is not currently using it (for instance if it is playing an audio-only input). @return: an X window ID, or 0 if none where set. ''' return libvlc_media_player_get_xwindow(self) def get_hwnd(self): '''Get the Windows API window handle (HWND) previously set with L{set_hwnd}(). The handle will be returned even if LibVLC is not currently outputting any video to it. @return: a window handle or NULL if there are none. ''' return libvlc_media_player_get_hwnd(self) def audio_set_callbacks(self, play, pause, resume, flush, drain, opaque): '''Set callbacks and private data for decoded audio. Use L{audio_set_format}() or L{audio_set_format_callbacks}() to configure the decoded audio format. @param play: callback to play audio samples (must not be NULL). @param pause: callback to pause playback (or NULL to ignore). @param resume: callback to resume playback (or NULL to ignore). @param flush: callback to flush audio buffers (or NULL to ignore). @param drain: callback to drain audio buffers (or NULL to ignore). @param opaque: private pointer for the audio callbacks (as first parameter). @version: LibVLC 2.0.0 or later. ''' return libvlc_audio_set_callbacks(self, play, pause, resume, flush, drain, opaque) def audio_set_volume_callback(self, set_volume): '''Set callbacks and private data for decoded audio. Use L{audio_set_format}() or L{audio_set_format_callbacks}() to configure the decoded audio format. @param set_volume: callback to apply audio volume, or NULL to apply volume in software. @version: LibVLC 2.0.0 or later. ''' return libvlc_audio_set_volume_callback(self, set_volume) def audio_set_format_callbacks(self, setup, cleanup): '''Set decoded audio format. This only works in combination with L{audio_set_callbacks}(). @param setup: callback to select the audio format (cannot be NULL). @param cleanup: callback to release any allocated resources (or NULL). @version: LibVLC 2.0.0 or later. ''' return libvlc_audio_set_format_callbacks(self, setup, cleanup) def audio_set_format(self, format, rate, channels): '''Set decoded audio format. This only works in combination with L{audio_set_callbacks}(), and is mutually exclusive with L{audio_set_format_callbacks}(). @param format: a four-characters string identifying the sample format (e.g. "S16N" or "FL32"). @param rate: sample rate (expressed in Hz). @param channels: channels count. @version: LibVLC 2.0.0 or later. ''' return libvlc_audio_set_format(self, str_to_bytes(format), rate, channels) def get_length(self): '''Get the current movie length (in ms). @return: the movie length (in ms), or -1 if there is no media. ''' return libvlc_media_player_get_length(self) def get_time(self): '''Get the current movie time (in ms). @return: the movie time (in ms), or -1 if there is no media. ''' return libvlc_media_player_get_time(self) def set_time(self, i_time): '''Set the movie time (in ms). This has no effect if no media is being played. Not all formats and protocols support this. @param i_time: the movie time (in ms). ''' return libvlc_media_player_set_time(self, i_time) def get_position(self): '''Get movie position as percentage between 0.0 and 1.0. @return: movie position, or -1. in case of error. ''' return libvlc_media_player_get_position(self) def set_position(self, f_pos): '''Set movie position as percentage between 0.0 and 1.0. This has no effect if playback is not enabled. This might not work depending on the underlying input format and protocol. @param f_pos: the position. ''' return libvlc_media_player_set_position(self, f_pos) def set_chapter(self, i_chapter): '''Set movie chapter (if applicable). @param i_chapter: chapter number to play. ''' return libvlc_media_player_set_chapter(self, i_chapter) def get_chapter(self): '''Get movie chapter. @return: chapter number currently playing, or -1 if there is no media. ''' return libvlc_media_player_get_chapter(self) def get_chapter_count(self): '''Get movie chapter count. @return: number of chapters in movie, or -1. ''' return libvlc_media_player_get_chapter_count(self) def will_play(self): '''Is the player able to play. @return: boolean \libvlc_return_bool. ''' return libvlc_media_player_will_play(self) def get_chapter_count_for_title(self, i_title): '''Get title chapter count. @param i_title: title. @return: number of chapters in title, or -1. ''' return libvlc_media_player_get_chapter_count_for_title(self, i_title) def set_title(self, i_title): '''Set movie title. @param i_title: title number to play. ''' return libvlc_media_player_set_title(self, i_title) def get_title(self): '''Get movie title. @return: title number currently playing, or -1. ''' return libvlc_media_player_get_title(self) def get_title_count(self): '''Get movie title count. @return: title number count, or -1. ''' return libvlc_media_player_get_title_count(self) def previous_chapter(self): '''Set previous chapter (if applicable). ''' return libvlc_media_player_previous_chapter(self) def next_chapter(self): '''Set next chapter (if applicable). ''' return libvlc_media_player_next_chapter(self) def get_rate(self): '''Get the requested movie play rate. @warning: Depending on the underlying media, the requested rate may be different from the real playback rate. @return: movie play rate. ''' return libvlc_media_player_get_rate(self) def set_rate(self, rate): '''Set movie play rate. @param rate: movie play rate to set. @return: -1 if an error was detected, 0 otherwise (but even then, it might not actually work depending on the underlying media protocol). ''' return libvlc_media_player_set_rate(self, rate) def get_state(self): '''Get current movie state. @return: the current state of the media player (playing, paused, ...) See libvlc_state_t. ''' return libvlc_media_player_get_state(self) def get_fps(self): '''Get movie fps rate. @return: frames per second (fps) for this playing movie, or 0 if unspecified. ''' return libvlc_media_player_get_fps(self) def has_vout(self): '''How many video outputs does this media player have? @return: the number of video outputs. ''' return libvlc_media_player_has_vout(self) def is_seekable(self): '''Is this media player seekable? @return: true if the media player can seek \libvlc_return_bool. ''' return libvlc_media_player_is_seekable(self) def can_pause(self): '''Can this media player be paused? @return: true if the media player can pause \libvlc_return_bool. ''' return libvlc_media_player_can_pause(self) def next_frame(self): '''Display the next frame (if supported). ''' return libvlc_media_player_next_frame(self) def navigate(self, navigate): '''Navigate through DVD Menu. @param navigate: the Navigation mode. @version: libVLC 2.0.0 or later. ''' return libvlc_media_player_navigate(self, navigate) def toggle_fullscreen(self): '''Toggle fullscreen status on non-embedded video outputs. @warning: The same limitations applies to this function as to L{set_fullscreen}(). ''' return libvlc_toggle_fullscreen(self) def set_fullscreen(self, b_fullscreen): '''Enable or disable fullscreen. @warning: With most window managers, only a top-level windows can be in full-screen mode. Hence, this function will not operate properly if L{set_xwindow}() was used to embed the video in a non-top-level window. In that case, the embedding window must be reparented to the root window B{before} fullscreen mode is enabled. You will want to reparent it back to its normal parent when disabling fullscreen. @param b_fullscreen: boolean for fullscreen status. ''' return libvlc_set_fullscreen(self, b_fullscreen) def get_fullscreen(self): '''Get current fullscreen status. @return: the fullscreen status (boolean) \libvlc_return_bool. ''' return libvlc_get_fullscreen(self) def video_set_key_input(self, on): '''Enable or disable key press events handling, according to the LibVLC hotkeys configuration. By default and for historical reasons, keyboard events are handled by the LibVLC video widget. @note: On X11, there can be only one subscriber for key press and mouse click events per window. If your application has subscribed to those events for the X window ID of the video widget, then LibVLC will not be able to handle key presses and mouse clicks in any case. @warning: This function is only implemented for X11 and Win32 at the moment. @param on: true to handle key press events, false to ignore them. ''' return libvlc_video_set_key_input(self, on) def video_set_mouse_input(self, on): '''Enable or disable mouse click events handling. By default, those events are handled. This is needed for DVD menus to work, as well as a few video filters such as "puzzle". See L{video_set_key_input}(). @warning: This function is only implemented for X11 and Win32 at the moment. @param on: true to handle mouse click events, false to ignore them. ''' return libvlc_video_set_mouse_input(self, on) def video_get_scale(self): '''Get the current video scaling factor. See also L{video_set_scale}(). @return: the currently configured zoom factor, or 0. if the video is set to fit to the output window/drawable automatically. ''' return libvlc_video_get_scale(self) def video_set_scale(self, f_factor): '''Set the video scaling factor. That is the ratio of the number of pixels on screen to the number of pixels in the original decoded video in each dimension. Zero is a special value; it will adjust the video to the output window/drawable (in windowed mode) or the entire screen. Note that not all video outputs support scaling. @param f_factor: the scaling factor, or zero. ''' return libvlc_video_set_scale(self, f_factor) def video_get_aspect_ratio(self): '''Get current video aspect ratio. @return: the video aspect ratio or NULL if unspecified (the result must be released with free() or L{free}()). ''' return libvlc_video_get_aspect_ratio(self) def video_set_aspect_ratio(self, psz_aspect): '''Set new video aspect ratio. @param psz_aspect: new video aspect-ratio or NULL to reset to default @note Invalid aspect ratios are ignored. ''' return libvlc_video_set_aspect_ratio(self, str_to_bytes(psz_aspect)) def video_get_spu(self): '''Get current video subtitle. @return: the video subtitle selected, or -1 if none. ''' return libvlc_video_get_spu(self) def video_get_spu_count(self): '''Get the number of available video subtitles. @return: the number of available video subtitles. ''' return libvlc_video_get_spu_count(self) def video_set_spu(self, i_spu): '''Set new video subtitle. @param i_spu: video subtitle track to select (i_id from track description). @return: 0 on success, -1 if out of range. ''' return libvlc_video_set_spu(self, i_spu) def video_set_subtitle_file(self, psz_subtitle): '''Set new video subtitle file. @param psz_subtitle: new video subtitle file. @return: the success status (boolean). ''' return libvlc_video_set_subtitle_file(self, str_to_bytes(psz_subtitle)) def video_get_spu_delay(self): '''Get the current subtitle delay. Positive values means subtitles are being displayed later, negative values earlier. @return: time (in microseconds) the display of subtitles is being delayed. @version: LibVLC 2.0.0 or later. ''' return libvlc_video_get_spu_delay(self) def video_set_spu_delay(self, i_delay): '''Set the subtitle delay. This affects the timing of when the subtitle will be displayed. Positive values result in subtitles being displayed later, while negative values will result in subtitles being displayed earlier. The subtitle delay will be reset to zero each time the media changes. @param i_delay: time (in microseconds) the display of subtitles should be delayed. @return: 0 on success, -1 on error. @version: LibVLC 2.0.0 or later. ''' return libvlc_video_set_spu_delay(self, i_delay) def video_get_crop_geometry(self): '''Get current crop filter geometry. @return: the crop filter geometry or NULL if unset. ''' return libvlc_video_get_crop_geometry(self) def video_set_crop_geometry(self, psz_geometry): '''Set new crop filter geometry. @param psz_geometry: new crop filter geometry (NULL to unset). ''' return libvlc_video_set_crop_geometry(self, str_to_bytes(psz_geometry)) def video_get_teletext(self): '''Get current teletext page requested. @return: the current teletext page requested. ''' return libvlc_video_get_teletext(self) def video_set_teletext(self, i_page): '''Set new teletext page to retrieve. @param i_page: teletex page number requested. ''' return libvlc_video_set_teletext(self, i_page) def toggle_teletext(self): '''Toggle teletext transparent status on video output. ''' return libvlc_toggle_teletext(self) def video_get_track_count(self): '''Get number of available video tracks. @return: the number of available video tracks (int). ''' return libvlc_video_get_track_count(self) def video_get_track(self): '''Get current video track. @return: the video track ID (int) or -1 if no active input. ''' return libvlc_video_get_track(self) def video_set_track(self, i_track): '''Set video track. @param i_track: the track ID (i_id field from track description). @return: 0 on success, -1 if out of range. ''' return libvlc_video_set_track(self, i_track) def video_take_snapshot(self, num, psz_filepath, i_width, i_height): '''Take a snapshot of the current video window. If i_width AND i_height is 0, original size is used. If i_width XOR i_height is 0, original aspect-ratio is preserved. @param num: number of video output (typically 0 for the first/only one). @param psz_filepath: the path where to save the screenshot to. @param i_width: the snapshot's width. @param i_height: the snapshot's height. @return: 0 on success, -1 if the video was not found. ''' return libvlc_video_take_snapshot(self, num, str_to_bytes(psz_filepath), i_width, i_height) def video_set_deinterlace(self, psz_mode): '''Enable or disable deinterlace filter. @param psz_mode: type of deinterlace filter, NULL to disable. ''' return libvlc_video_set_deinterlace(self, str_to_bytes(psz_mode)) def video_get_marquee_int(self, option): '''Get an integer marquee option value. @param option: marq option to get See libvlc_video_marquee_int_option_t. ''' return libvlc_video_get_marquee_int(self, option) def video_get_marquee_string(self, option): '''Get a string marquee option value. @param option: marq option to get See libvlc_video_marquee_string_option_t. ''' return libvlc_video_get_marquee_string(self, option) def video_set_marquee_int(self, option, i_val): '''Enable, disable or set an integer marquee option Setting libvlc_marquee_Enable has the side effect of enabling (arg !0) or disabling (arg 0) the marq filter. @param option: marq option to set See libvlc_video_marquee_int_option_t. @param i_val: marq option value. ''' return libvlc_video_set_marquee_int(self, option, i_val) def video_set_marquee_string(self, option, psz_text): '''Set a marquee string option. @param option: marq option to set See libvlc_video_marquee_string_option_t. @param psz_text: marq option value. ''' return libvlc_video_set_marquee_string(self, option, str_to_bytes(psz_text)) def video_get_logo_int(self, option): '''Get integer logo option. @param option: logo option to get, values of libvlc_video_logo_option_t. ''' return libvlc_video_get_logo_int(self, option) def video_set_logo_int(self, option, value): '''Set logo option as integer. Options that take a different type value are ignored. Passing libvlc_logo_enable as option value has the side effect of starting (arg !0) or stopping (arg 0) the logo filter. @param option: logo option to set, values of libvlc_video_logo_option_t. @param value: logo option value. ''' return libvlc_video_set_logo_int(self, option, value) def video_set_logo_string(self, option, psz_value): '''Set logo option as string. Options that take a different type value are ignored. @param option: logo option to set, values of libvlc_video_logo_option_t. @param psz_value: logo option value. ''' return libvlc_video_set_logo_string(self, option, str_to_bytes(psz_value)) def video_get_adjust_int(self, option): '''Get integer adjust option. @param option: adjust option to get, values of libvlc_video_adjust_option_t. @version: LibVLC 1.1.1 and later. ''' return libvlc_video_get_adjust_int(self, option) def video_set_adjust_int(self, option, value): '''Set adjust option as integer. Options that take a different type value are ignored. Passing libvlc_adjust_enable as option value has the side effect of starting (arg !0) or stopping (arg 0) the adjust filter. @param option: adust option to set, values of libvlc_video_adjust_option_t. @param value: adjust option value. @version: LibVLC 1.1.1 and later. ''' return libvlc_video_set_adjust_int(self, option, value) def video_get_adjust_float(self, option): '''Get float adjust option. @param option: adjust option to get, values of libvlc_video_adjust_option_t. @version: LibVLC 1.1.1 and later. ''' return libvlc_video_get_adjust_float(self, option) def video_set_adjust_float(self, option, value): '''Set adjust option as float. Options that take a different type value are ignored. @param option: adust option to set, values of libvlc_video_adjust_option_t. @param value: adjust option value. @version: LibVLC 1.1.1 and later. ''' return libvlc_video_set_adjust_float(self, option, value) def audio_output_set(self, psz_name): '''Sets the audio output. @note: Any change will take be effect only after playback is stopped and restarted. Audio output cannot be changed while playing. @param psz_name: name of audio output, use psz_name of See L{AudioOutput}. @return: 0 if function succeded, -1 on error. ''' return libvlc_audio_output_set(self, str_to_bytes(psz_name)) def audio_output_device_set(self, psz_audio_output, psz_device_id): '''Configures an explicit audio output device for a given audio output plugin. A list of possible devices can be obtained with L{audio_output_device_list_get}(). @note: This function does not select the specified audio output plugin. L{audio_output_set}() is used for that purpose. @warning: The syntax for the device parameter depends on the audio output. This is not portable. Only use this function if you know what you are doing. Some audio outputs do not support this function (e.g. PulseAudio, WASAPI). Some audio outputs require further parameters (e.g. ALSA: channels map). @param psz_audio_output: - name of audio output, See L{AudioOutput}. @param psz_device_id: device. @return: Nothing. Errors are ignored. ''' return libvlc_audio_output_device_set(self, str_to_bytes(psz_audio_output), str_to_bytes(psz_device_id)) def audio_toggle_mute(self): '''Toggle mute status. ''' return libvlc_audio_toggle_mute(self) def audio_get_mute(self): '''Get current mute status. @return: the mute status (boolean) if defined, -1 if undefined/unapplicable. ''' return libvlc_audio_get_mute(self) def audio_set_mute(self, status): '''Set mute status. @param status: If status is true then mute, otherwise unmute @warning This function does not always work. If there are no active audio playback stream, the mute status might not be available. If digital pass-through (S/PDIF, HDMI...) is in use, muting may be unapplicable. Also some audio output plugins do not support muting at all. @note To force silent playback, disable all audio tracks. This is more efficient and reliable than mute. ''' return libvlc_audio_set_mute(self, status) def audio_get_volume(self): '''Get current software audio volume. @return: the software volume in percents (0 = mute, 100 = nominal / 0dB). ''' return libvlc_audio_get_volume(self) def audio_set_volume(self, i_volume): '''Set current software audio volume. @param i_volume: the volume in percents (0 = mute, 100 = 0dB). @return: 0 if the volume was set, -1 if it was out of range. ''' return libvlc_audio_set_volume(self, i_volume) def audio_get_track_count(self): '''Get number of available audio tracks. @return: the number of available audio tracks (int), or -1 if unavailable. ''' return libvlc_audio_get_track_count(self) def audio_get_track(self): '''Get current audio track. @return: the audio track ID or -1 if no active input. ''' return libvlc_audio_get_track(self) def audio_set_track(self, i_track): '''Set current audio track. @param i_track: the track ID (i_id field from track description). @return: 0 on success, -1 on error. ''' return libvlc_audio_set_track(self, i_track) def audio_get_channel(self): '''Get current audio channel. @return: the audio channel See libvlc_audio_output_channel_t. ''' return libvlc_audio_get_channel(self) def audio_set_channel(self, channel): '''Set current audio channel. @param channel: the audio channel, See libvlc_audio_output_channel_t. @return: 0 on success, -1 on error. ''' return libvlc_audio_set_channel(self, channel) def audio_get_delay(self): '''Get current audio delay. @return: the audio delay (microseconds). @version: LibVLC 1.1.1 or later. ''' return libvlc_audio_get_delay(self) def audio_set_delay(self, i_delay): '''Set current audio delay. The audio delay will be reset to zero each time the media changes. @param i_delay: the audio delay (microseconds). @return: 0 on success, -1 on error. @version: LibVLC 1.1.1 or later. ''' return libvlc_audio_set_delay(self, i_delay) # LibVLC __version__ functions # def libvlc_errmsg(): '''A human-readable error message for the last LibVLC error in the calling thread. The resulting string is valid until another error occurs (at least until the next LibVLC call). @warning This will be NULL if there was no error. ''' f = _Cfunctions.get('libvlc_errmsg', None) or \ _Cfunction('libvlc_errmsg', (), None, ctypes.c_char_p) return f() def libvlc_clearerr(): '''Clears the LibVLC error status for the current thread. This is optional. By default, the error status is automatically overridden when a new error occurs, and destroyed when the thread exits. ''' f = _Cfunctions.get('libvlc_clearerr', None) or \ _Cfunction('libvlc_clearerr', (), None, None) return f() def libvlc_vprinterr(fmt, ap): '''Sets the LibVLC error status and message for the current thread. Any previous error is overridden. @param fmt: the format string. @param ap: the arguments. @return: a nul terminated string in any case. ''' f = _Cfunctions.get('libvlc_vprinterr', None) or \ _Cfunction('libvlc_vprinterr', ((1,), (1,),), None, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_void_p) return f(fmt, ap) def libvlc_new(argc, argv): '''Create and initialize a libvlc instance. This functions accept a list of "command line" arguments similar to the main(). These arguments affect the LibVLC instance default configuration. @param argc: the number of arguments (should be 0). @param argv: list of arguments (should be NULL). @return: the libvlc instance or NULL in case of error. @version Arguments are meant to be passed from the command line to LibVLC, just like VLC media player does. The list of valid arguments depends on the LibVLC version, the operating system and platform, and set of available LibVLC plugins. Invalid or unsupported arguments will cause the function to fail (i.e. return NULL). Also, some arguments may alter the behaviour or otherwise interfere with other LibVLC functions. @warning There is absolutely no warranty or promise of forward, backward and cross-platform compatibility with regards to L{libvlc_new}() arguments. We recommend that you do not use them, other than when debugging. ''' f = _Cfunctions.get('libvlc_new', None) or \ _Cfunction('libvlc_new', ((1,), (1,),), class_result(Instance), ctypes.c_void_p, ctypes.c_int, ListPOINTER(ctypes.c_char_p)) return f(argc, argv) def libvlc_release(p_instance): '''Decrement the reference count of a libvlc instance, and destroy it if it reaches zero. @param p_instance: the instance to destroy. ''' f = _Cfunctions.get('libvlc_release', None) or \ _Cfunction('libvlc_release', ((1,),), None, None, Instance) return f(p_instance) def libvlc_retain(p_instance): '''Increments the reference count of a libvlc instance. The initial reference count is 1 after L{libvlc_new}() returns. @param p_instance: the instance to reference. ''' f = _Cfunctions.get('libvlc_retain', None) or \ _Cfunction('libvlc_retain', ((1,),), None, None, Instance) return f(p_instance) def libvlc_add_intf(p_instance, name): '''Try to start a user interface for the libvlc instance. @param p_instance: the instance. @param name: interface name, or NULL for default. @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_add_intf', None) or \ _Cfunction('libvlc_add_intf', ((1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p) return f(p_instance, name) def libvlc_set_user_agent(p_instance, name, http): '''Sets the application name. LibVLC passes this as the user agent string when a protocol requires it. @param p_instance: LibVLC instance. @param name: human-readable application name, e.g. "FooBar player 1.2.3". @param http: HTTP User Agent, e.g. "FooBar/1.2.3 Python/2.6.0". @version: LibVLC 1.1.1 or later. ''' f = _Cfunctions.get('libvlc_set_user_agent', None) or \ _Cfunction('libvlc_set_user_agent', ((1,), (1,), (1,),), None, None, Instance, ctypes.c_char_p, ctypes.c_char_p) return f(p_instance, name, http) def libvlc_get_version(): '''Retrieve libvlc version. Example: "1.1.0-git The Luggage". @return: a string containing the libvlc version. ''' f = _Cfunctions.get('libvlc_get_version', None) or \ _Cfunction('libvlc_get_version', (), None, ctypes.c_char_p) return f() def libvlc_get_compiler(): '''Retrieve libvlc compiler version. Example: "gcc version 4.2.3 (Ubuntu 4.2.3-2ubuntu6)". @return: a string containing the libvlc compiler version. ''' f = _Cfunctions.get('libvlc_get_compiler', None) or \ _Cfunction('libvlc_get_compiler', (), None, ctypes.c_char_p) return f() def libvlc_get_changeset(): '''Retrieve libvlc changeset. Example: "aa9bce0bc4". @return: a string containing the libvlc changeset. ''' f = _Cfunctions.get('libvlc_get_changeset', None) or \ _Cfunction('libvlc_get_changeset', (), None, ctypes.c_char_p) return f() def libvlc_free(ptr): '''Frees an heap allocation returned by a LibVLC function. If you know you're using the same underlying C run-time as the LibVLC implementation, then you can call ANSI C free() directly instead. @param ptr: the pointer. ''' f = _Cfunctions.get('libvlc_free', None) or \ _Cfunction('libvlc_free', ((1,),), None, None, ctypes.c_void_p) return f(ptr) def libvlc_event_attach(p_event_manager, i_event_type, f_callback, user_data): '''Register for an event notification. @param p_event_manager: the event manager to which you want to attach to. Generally it is obtained by vlc_my_object_event_manager() where my_object is the object you want to listen to. @param i_event_type: the desired event to which we want to listen. @param f_callback: the function to call when i_event_type occurs. @param user_data: user provided data to carry with the event. @return: 0 on success, ENOMEM on error. ''' f = _Cfunctions.get('libvlc_event_attach', None) or \ _Cfunction('libvlc_event_attach', ((1,), (1,), (1,), (1,),), None, ctypes.c_int, EventManager, ctypes.c_uint, Callback, ctypes.c_void_p) return f(p_event_manager, i_event_type, f_callback, user_data) def libvlc_event_detach(p_event_manager, i_event_type, f_callback, p_user_data): '''Unregister an event notification. @param p_event_manager: the event manager. @param i_event_type: the desired event to which we want to unregister. @param f_callback: the function to call when i_event_type occurs. @param p_user_data: user provided data to carry with the event. ''' f = _Cfunctions.get('libvlc_event_detach', None) or \ _Cfunction('libvlc_event_detach', ((1,), (1,), (1,), (1,),), None, None, EventManager, ctypes.c_uint, Callback, ctypes.c_void_p) return f(p_event_manager, i_event_type, f_callback, p_user_data) def libvlc_event_type_name(event_type): '''Get an event's type name. @param event_type: the desired event. ''' f = _Cfunctions.get('libvlc_event_type_name', None) or \ _Cfunction('libvlc_event_type_name', ((1,),), None, ctypes.c_char_p, ctypes.c_uint) return f(event_type) def libvlc_log_get_context(ctx): '''Gets debugging informations about a log message: the name of the VLC module emitting the message and the message location within the source code. The returned module name and file name will be NULL if unknown. The returned line number will similarly be zero if unknown. @param ctx: message context (as passed to the @ref libvlc_log_cb callback). @return: module module name storage (or NULL), file source code file name storage (or NULL), line source code file line number storage (or NULL). @version: LibVLC 2.1.0 or later. ''' f = _Cfunctions.get('libvlc_log_get_context', None) or \ _Cfunction('libvlc_log_get_context', ((1,), (2,), (2,), (2,),), None, None, Log_ptr, ListPOINTER(ctypes.c_char_p), ListPOINTER(ctypes.c_char_p), ctypes.POINTER(ctypes.c_uint)) return f(ctx) def libvlc_log_get_object(ctx, id): '''Gets VLC object informations about a log message: the type name of the VLC object emitting the message, the object header if any and a temporaly-unique object identifier. These informations are mainly meant for B{manual} troubleshooting. The returned type name may be "generic" if unknown, but it cannot be NULL. The returned header will be NULL if unset; in current versions, the header is used to distinguish for VLM inputs. The returned object ID will be zero if the message is not associated with any VLC object. @param ctx: message context (as passed to the @ref libvlc_log_cb callback). @return: name object name storage (or NULL), header object header (or NULL), line source code file line number storage (or NULL). @version: LibVLC 2.1.0 or later. ''' f = _Cfunctions.get('libvlc_log_get_object', None) or \ _Cfunction('libvlc_log_get_object', ((1,), (2,), (2,), (1,),), None, None, Log_ptr, ListPOINTER(ctypes.c_char_p), ListPOINTER(ctypes.c_char_p), ctypes.POINTER(ctypes.c_uint)) return f(ctx, id) def libvlc_log_unset(p_instance): '''Unsets the logging callback for a LibVLC instance. This is rarely needed: the callback is implicitly unset when the instance is destroyed. This function will wait for any pending callbacks invocation to complete (causing a deadlock if called from within the callback). @param p_instance: libvlc instance. @version: LibVLC 2.1.0 or later. ''' f = _Cfunctions.get('libvlc_log_unset', None) or \ _Cfunction('libvlc_log_unset', ((1,),), None, None, Instance) return f(p_instance) def libvlc_log_set(cb, data, p_instance): '''Sets the logging callback for a LibVLC instance. This function is thread-safe: it will wait for any pending callbacks invocation to complete. @param cb: callback function pointer. @param data: opaque data pointer for the callback function @note Some log messages (especially debug) are emitted by LibVLC while is being initialized. These messages cannot be captured with this interface. @warning A deadlock may occur if this function is called from the callback. @param p_instance: libvlc instance. @version: LibVLC 2.1.0 or later. ''' f = _Cfunctions.get('libvlc_log_set', None) or \ _Cfunction('libvlc_log_set', ((1,), (1,), (1,),), None, None, Instance, LogCb, ctypes.c_void_p) return f(cb, data, p_instance) def libvlc_log_set_file(p_instance, stream): '''Sets up logging to a file. @param p_instance: libvlc instance. @param stream: FILE pointer opened for writing (the FILE pointer must remain valid until L{libvlc_log_unset}()). @version: LibVLC 2.1.0 or later. ''' f = _Cfunctions.get('libvlc_log_set_file', None) or \ _Cfunction('libvlc_log_set_file', ((1,), (1,),), None, None, Instance, FILE_ptr) return f(p_instance, stream) def libvlc_module_description_list_release(p_list): '''Release a list of module descriptions. @param p_list: the list to be released. ''' f = _Cfunctions.get('libvlc_module_description_list_release', None) or \ _Cfunction('libvlc_module_description_list_release', ((1,),), None, None, ctypes.POINTER(ModuleDescription)) return f(p_list) def libvlc_audio_filter_list_get(p_instance): '''Returns a list of audio filters that are available. @param p_instance: libvlc instance. @return: a list of module descriptions. It should be freed with L{libvlc_module_description_list_release}(). In case of an error, NULL is returned. See L{ModuleDescription} See L{libvlc_module_description_list_release}. ''' f = _Cfunctions.get('libvlc_audio_filter_list_get', None) or \ _Cfunction('libvlc_audio_filter_list_get', ((1,),), None, ctypes.POINTER(ModuleDescription), Instance) return f(p_instance) def libvlc_video_filter_list_get(p_instance): '''Returns a list of video filters that are available. @param p_instance: libvlc instance. @return: a list of module descriptions. It should be freed with L{libvlc_module_description_list_release}(). In case of an error, NULL is returned. See L{ModuleDescription} See L{libvlc_module_description_list_release}. ''' f = _Cfunctions.get('libvlc_video_filter_list_get', None) or \ _Cfunction('libvlc_video_filter_list_get', ((1,),), None, ctypes.POINTER(ModuleDescription), Instance) return f(p_instance) def libvlc_clock(): '''Return the current time as defined by LibVLC. The unit is the microsecond. Time increases monotonically (regardless of time zone changes and RTC adjustements). The origin is arbitrary but consistent across the whole system (e.g. the system uptim, the time since the system was booted). @note: On systems that support it, the POSIX monotonic clock is used. ''' f = _Cfunctions.get('libvlc_clock', None) or \ _Cfunction('libvlc_clock', (), None, ctypes.c_int64) return f() def libvlc_media_new_location(p_instance, psz_mrl): '''Create a media with a certain given media resource location, for instance a valid URL. @note: To refer to a local file with this function, the file://... URI syntax B{must} be used (see IETF RFC3986). We recommend using L{libvlc_media_new_path}() instead when dealing with local files. See L{libvlc_media_release}. @param p_instance: the instance. @param psz_mrl: the media location. @return: the newly created media or NULL on error. ''' f = _Cfunctions.get('libvlc_media_new_location', None) or \ _Cfunction('libvlc_media_new_location', ((1,), (1,),), class_result(Media), ctypes.c_void_p, Instance, ctypes.c_char_p) return f(p_instance, psz_mrl) def libvlc_media_new_path(p_instance, path): '''Create a media for a certain file path. See L{libvlc_media_release}. @param p_instance: the instance. @param path: local filesystem path. @return: the newly created media or NULL on error. ''' f = _Cfunctions.get('libvlc_media_new_path', None) or \ _Cfunction('libvlc_media_new_path', ((1,), (1,),), class_result(Media), ctypes.c_void_p, Instance, ctypes.c_char_p) return f(p_instance, path) def libvlc_media_new_fd(p_instance, fd): '''Create a media for an already open file descriptor. The file descriptor shall be open for reading (or reading and writing). Regular file descriptors, pipe read descriptors and character device descriptors (including TTYs) are supported on all platforms. Block device descriptors are supported where available. Directory descriptors are supported on systems that provide fdopendir(). Sockets are supported on all platforms where they are file descriptors, i.e. all except Windows. @note: This library will B{not} automatically close the file descriptor under any circumstance. Nevertheless, a file descriptor can usually only be rendered once in a media player. To render it a second time, the file descriptor should probably be rewound to the beginning with lseek(). See L{libvlc_media_release}. @param p_instance: the instance. @param fd: open file descriptor. @return: the newly created media or NULL on error. @version: LibVLC 1.1.5 and later. ''' f = _Cfunctions.get('libvlc_media_new_fd', None) or \ _Cfunction('libvlc_media_new_fd', ((1,), (1,),), class_result(Media), ctypes.c_void_p, Instance, ctypes.c_int) return f(p_instance, fd) def libvlc_media_new_as_node(p_instance, psz_name): '''Create a media as an empty node with a given name. See L{libvlc_media_release}. @param p_instance: the instance. @param psz_name: the name of the node. @return: the new empty media or NULL on error. ''' f = _Cfunctions.get('libvlc_media_new_as_node', None) or \ _Cfunction('libvlc_media_new_as_node', ((1,), (1,),), class_result(Media), ctypes.c_void_p, Instance, ctypes.c_char_p) return f(p_instance, psz_name) def libvlc_media_add_option(p_md, psz_options): '''Add an option to the media. This option will be used to determine how the media_player will read the media. This allows to use VLC's advanced reading/streaming options on a per-media basis. @note: The options are listed in 'vlc --long-help' from the command line, e.g. "-sout-all". Keep in mind that available options and their semantics vary across LibVLC versions and builds. @warning: Not all options affects L{Media} objects: Specifically, due to architectural issues most audio and video options, such as text renderer options, have no effects on an individual media. These options must be set through L{libvlc_new}() instead. @param p_md: the media descriptor. @param psz_options: the options (as a string). ''' f = _Cfunctions.get('libvlc_media_add_option', None) or \ _Cfunction('libvlc_media_add_option', ((1,), (1,),), None, None, Media, ctypes.c_char_p) return f(p_md, psz_options) def libvlc_media_add_option_flag(p_md, psz_options, i_flags): '''Add an option to the media with configurable flags. This option will be used to determine how the media_player will read the media. This allows to use VLC's advanced reading/streaming options on a per-media basis. The options are detailed in vlc --long-help, for instance "--sout-all". Note that all options are not usable on medias: specifically, due to architectural issues, video-related options such as text renderer options cannot be set on a single media. They must be set on the whole libvlc instance instead. @param p_md: the media descriptor. @param psz_options: the options (as a string). @param i_flags: the flags for this option. ''' f = _Cfunctions.get('libvlc_media_add_option_flag', None) or \ _Cfunction('libvlc_media_add_option_flag', ((1,), (1,), (1,),), None, None, Media, ctypes.c_char_p, ctypes.c_uint) return f(p_md, psz_options, i_flags) def libvlc_media_retain(p_md): '''Retain a reference to a media descriptor object (libvlc_media_t). Use L{libvlc_media_release}() to decrement the reference count of a media descriptor object. @param p_md: the media descriptor. ''' f = _Cfunctions.get('libvlc_media_retain', None) or \ _Cfunction('libvlc_media_retain', ((1,),), None, None, Media) return f(p_md) def libvlc_media_release(p_md): '''Decrement the reference count of a media descriptor object. If the reference count is 0, then L{libvlc_media_release}() will release the media descriptor object. It will send out an libvlc_MediaFreed event to all listeners. If the media descriptor object has been released it should not be used again. @param p_md: the media descriptor. ''' f = _Cfunctions.get('libvlc_media_release', None) or \ _Cfunction('libvlc_media_release', ((1,),), None, None, Media) return f(p_md) def libvlc_media_get_mrl(p_md): '''Get the media resource locator (mrl) from a media descriptor object. @param p_md: a media descriptor object. @return: string with mrl of media descriptor object. ''' f = _Cfunctions.get('libvlc_media_get_mrl', None) or \ _Cfunction('libvlc_media_get_mrl', ((1,),), string_result, ctypes.c_void_p, Media) return f(p_md) def libvlc_media_duplicate(p_md): '''Duplicate a media descriptor object. @param p_md: a media descriptor object. ''' f = _Cfunctions.get('libvlc_media_duplicate', None) or \ _Cfunction('libvlc_media_duplicate', ((1,),), class_result(Media), ctypes.c_void_p, Media) return f(p_md) def libvlc_media_get_meta(p_md, e_meta): '''Read the meta of the media. If the media has not yet been parsed this will return NULL. This methods automatically calls L{libvlc_media_parse_async}(), so after calling it you may receive a libvlc_MediaMetaChanged event. If you prefer a synchronous version ensure that you call L{libvlc_media_parse}() before get_meta(). See L{libvlc_media_parse} See L{libvlc_media_parse_async} See libvlc_MediaMetaChanged. @param p_md: the media descriptor. @param e_meta: the meta to read. @return: the media's meta. ''' f = _Cfunctions.get('libvlc_media_get_meta', None) or \ _Cfunction('libvlc_media_get_meta', ((1,), (1,),), string_result, ctypes.c_void_p, Media, Meta) return f(p_md, e_meta) def libvlc_media_set_meta(p_md, e_meta, psz_value): '''Set the meta of the media (this function will not save the meta, call L{libvlc_media_save_meta} in order to save the meta). @param p_md: the media descriptor. @param e_meta: the meta to write. @param psz_value: the media's meta. ''' f = _Cfunctions.get('libvlc_media_set_meta', None) or \ _Cfunction('libvlc_media_set_meta', ((1,), (1,), (1,),), None, None, Media, Meta, ctypes.c_char_p) return f(p_md, e_meta, psz_value) def libvlc_media_save_meta(p_md): '''Save the meta previously set. @param p_md: the media desriptor. @return: true if the write operation was successful. ''' f = _Cfunctions.get('libvlc_media_save_meta', None) or \ _Cfunction('libvlc_media_save_meta', ((1,),), None, ctypes.c_int, Media) return f(p_md) def libvlc_media_get_state(p_md): '''Get current state of media descriptor object. Possible media states are defined in libvlc_structures.c ( libvlc_NothingSpecial=0, libvlc_Opening, libvlc_Buffering, libvlc_Playing, libvlc_Paused, libvlc_Stopped, libvlc_Ended, libvlc_Error). See libvlc_state_t. @param p_md: a media descriptor object. @return: state of media descriptor object. ''' f = _Cfunctions.get('libvlc_media_get_state', None) or \ _Cfunction('libvlc_media_get_state', ((1,),), None, State, Media) return f(p_md) def libvlc_media_get_stats(p_md, p_stats): '''Get the current statistics about the media. @param p_md:: media descriptor object. @param p_stats:: structure that contain the statistics about the media (this structure must be allocated by the caller). @return: true if the statistics are available, false otherwise \libvlc_return_bool. ''' f = _Cfunctions.get('libvlc_media_get_stats', None) or \ _Cfunction('libvlc_media_get_stats', ((1,), (1,),), None, ctypes.c_int, Media, ctypes.POINTER(MediaStats)) return f(p_md, p_stats) def libvlc_media_subitems(p_md): '''Get subitems of media descriptor object. This will increment the reference count of supplied media descriptor object. Use L{libvlc_media_list_release}() to decrement the reference counting. @param p_md: media descriptor object. @return: list of media descriptor subitems or NULL. ''' f = _Cfunctions.get('libvlc_media_subitems', None) or \ _Cfunction('libvlc_media_subitems', ((1,),), class_result(MediaList), ctypes.c_void_p, Media) return f(p_md) def libvlc_media_event_manager(p_md): '''Get event manager from media descriptor object. NOTE: this function doesn't increment reference counting. @param p_md: a media descriptor object. @return: event manager object. ''' f = _Cfunctions.get('libvlc_media_event_manager', None) or \ _Cfunction('libvlc_media_event_manager', ((1,),), class_result(EventManager), ctypes.c_void_p, Media) return f(p_md) def libvlc_media_get_duration(p_md): '''Get duration (in ms) of media descriptor object item. @param p_md: media descriptor object. @return: duration of media item or -1 on error. ''' f = _Cfunctions.get('libvlc_media_get_duration', None) or \ _Cfunction('libvlc_media_get_duration', ((1,),), None, ctypes.c_longlong, Media) return f(p_md) def libvlc_media_parse(p_md): '''Parse a media. This fetches (local) meta data and tracks information. The method is synchronous. See L{libvlc_media_parse_async} See L{libvlc_media_get_meta} See libvlc_media_get_tracks_info. @param p_md: media descriptor object. ''' f = _Cfunctions.get('libvlc_media_parse', None) or \ _Cfunction('libvlc_media_parse', ((1,),), None, None, Media) return f(p_md) def libvlc_media_parse_async(p_md): '''Parse a media. This fetches (local) meta data and tracks information. The method is the asynchronous of L{libvlc_media_parse}(). To track when this is over you can listen to libvlc_MediaParsedChanged event. However if the media was already parsed you will not receive this event. See L{libvlc_media_parse} See libvlc_MediaParsedChanged See L{libvlc_media_get_meta} See libvlc_media_get_tracks_info. @param p_md: media descriptor object. ''' f = _Cfunctions.get('libvlc_media_parse_async', None) or \ _Cfunction('libvlc_media_parse_async', ((1,),), None, None, Media) return f(p_md) def libvlc_media_is_parsed(p_md): '''Get Parsed status for media descriptor object. See libvlc_MediaParsedChanged. @param p_md: media descriptor object. @return: true if media object has been parsed otherwise it returns false \libvlc_return_bool. ''' f = _Cfunctions.get('libvlc_media_is_parsed', None) or \ _Cfunction('libvlc_media_is_parsed', ((1,),), None, ctypes.c_int, Media) return f(p_md) def libvlc_media_set_user_data(p_md, p_new_user_data): '''Sets media descriptor's user_data. user_data is specialized data accessed by the host application, VLC.framework uses it as a pointer to an native object that references a L{Media} pointer. @param p_md: media descriptor object. @param p_new_user_data: pointer to user data. ''' f = _Cfunctions.get('libvlc_media_set_user_data', None) or \ _Cfunction('libvlc_media_set_user_data', ((1,), (1,),), None, None, Media, ctypes.c_void_p) return f(p_md, p_new_user_data) def libvlc_media_get_user_data(p_md): '''Get media descriptor's user_data. user_data is specialized data accessed by the host application, VLC.framework uses it as a pointer to an native object that references a L{Media} pointer. @param p_md: media descriptor object. ''' f = _Cfunctions.get('libvlc_media_get_user_data', None) or \ _Cfunction('libvlc_media_get_user_data', ((1,),), None, ctypes.c_void_p, Media) return f(p_md) def libvlc_media_tracks_get(p_md, tracks): '''Get media descriptor's elementary streams description Note, you need to call L{libvlc_media_parse}() or play the media at least once before calling this function. Not doing this will result in an empty array. @param p_md: media descriptor object. @param tracks: address to store an allocated array of Elementary Streams descriptions (must be freed with L{libvlc_media_tracks_release}. @return: the number of Elementary Streams (zero on error). @version: LibVLC 2.1.0 and later. ''' f = _Cfunctions.get('libvlc_media_tracks_get', None) or \ _Cfunction('libvlc_media_tracks_get', ((1,), (1,),), None, ctypes.c_uint, Media, ctypes.POINTER(ctypes.POINTER(MediaTrack))) return f(p_md, tracks) def libvlc_media_tracks_release(p_tracks, i_count): '''Release media descriptor's elementary streams description array. @param p_tracks: tracks info array to release. @param i_count: number of elements in the array. @version: LibVLC 2.1.0 and later. ''' f = _Cfunctions.get('libvlc_media_tracks_release', None) or \ _Cfunction('libvlc_media_tracks_release', ((1,), (1,),), None, None, ctypes.POINTER(MediaTrack), ctypes.c_uint) return f(p_tracks, i_count) def libvlc_media_discoverer_new_from_name(p_inst, psz_name): '''Discover media service by name. @param p_inst: libvlc instance. @param psz_name: service name. @return: media discover object or NULL in case of error. ''' f = _Cfunctions.get('libvlc_media_discoverer_new_from_name', None) or \ _Cfunction('libvlc_media_discoverer_new_from_name', ((1,), (1,),), class_result(MediaDiscoverer), ctypes.c_void_p, Instance, ctypes.c_char_p) return f(p_inst, psz_name) def libvlc_media_discoverer_release(p_mdis): '''Release media discover object. If the reference count reaches 0, then the object will be released. @param p_mdis: media service discover object. ''' f = _Cfunctions.get('libvlc_media_discoverer_release', None) or \ _Cfunction('libvlc_media_discoverer_release', ((1,),), None, None, MediaDiscoverer) return f(p_mdis) def libvlc_media_discoverer_localized_name(p_mdis): '''Get media service discover object its localized name. @param p_mdis: media discover object. @return: localized name. ''' f = _Cfunctions.get('libvlc_media_discoverer_localized_name', None) or \ _Cfunction('libvlc_media_discoverer_localized_name', ((1,),), string_result, ctypes.c_void_p, MediaDiscoverer) return f(p_mdis) def libvlc_media_discoverer_media_list(p_mdis): '''Get media service discover media list. @param p_mdis: media service discover object. @return: list of media items. ''' f = _Cfunctions.get('libvlc_media_discoverer_media_list', None) or \ _Cfunction('libvlc_media_discoverer_media_list', ((1,),), class_result(MediaList), ctypes.c_void_p, MediaDiscoverer) return f(p_mdis) def libvlc_media_discoverer_event_manager(p_mdis): '''Get event manager from media service discover object. @param p_mdis: media service discover object. @return: event manager object. ''' f = _Cfunctions.get('libvlc_media_discoverer_event_manager', None) or \ _Cfunction('libvlc_media_discoverer_event_manager', ((1,),), class_result(EventManager), ctypes.c_void_p, MediaDiscoverer) return f(p_mdis) def libvlc_media_discoverer_is_running(p_mdis): '''Query if media service discover object is running. @param p_mdis: media service discover object. @return: true if running, false if not \libvlc_return_bool. ''' f = _Cfunctions.get('libvlc_media_discoverer_is_running', None) or \ _Cfunction('libvlc_media_discoverer_is_running', ((1,),), None, ctypes.c_int, MediaDiscoverer) return f(p_mdis) def libvlc_media_library_new(p_instance): '''Create an new Media Library object. @param p_instance: the libvlc instance. @return: a new object or NULL on error. ''' f = _Cfunctions.get('libvlc_media_library_new', None) or \ _Cfunction('libvlc_media_library_new', ((1,),), class_result(MediaLibrary), ctypes.c_void_p, Instance) return f(p_instance) def libvlc_media_library_release(p_mlib): '''Release media library object. This functions decrements the reference count of the media library object. If it reaches 0, then the object will be released. @param p_mlib: media library object. ''' f = _Cfunctions.get('libvlc_media_library_release', None) or \ _Cfunction('libvlc_media_library_release', ((1,),), None, None, MediaLibrary) return f(p_mlib) def libvlc_media_library_retain(p_mlib): '''Retain a reference to a media library object. This function will increment the reference counting for this object. Use L{libvlc_media_library_release}() to decrement the reference count. @param p_mlib: media library object. ''' f = _Cfunctions.get('libvlc_media_library_retain', None) or \ _Cfunction('libvlc_media_library_retain', ((1,),), None, None, MediaLibrary) return f(p_mlib) def libvlc_media_library_load(p_mlib): '''Load media library. @param p_mlib: media library object. @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_media_library_load', None) or \ _Cfunction('libvlc_media_library_load', ((1,),), None, ctypes.c_int, MediaLibrary) return f(p_mlib) def libvlc_media_library_media_list(p_mlib): '''Get media library subitems. @param p_mlib: media library object. @return: media list subitems. ''' f = _Cfunctions.get('libvlc_media_library_media_list', None) or \ _Cfunction('libvlc_media_library_media_list', ((1,),), class_result(MediaList), ctypes.c_void_p, MediaLibrary) return f(p_mlib) def libvlc_media_list_new(p_instance): '''Create an empty media list. @param p_instance: libvlc instance. @return: empty media list, or NULL on error. ''' f = _Cfunctions.get('libvlc_media_list_new', None) or \ _Cfunction('libvlc_media_list_new', ((1,),), class_result(MediaList), ctypes.c_void_p, Instance) return f(p_instance) def libvlc_media_list_release(p_ml): '''Release media list created with L{libvlc_media_list_new}(). @param p_ml: a media list created with L{libvlc_media_list_new}(). ''' f = _Cfunctions.get('libvlc_media_list_release', None) or \ _Cfunction('libvlc_media_list_release', ((1,),), None, None, MediaList) return f(p_ml) def libvlc_media_list_retain(p_ml): '''Retain reference to a media list. @param p_ml: a media list created with L{libvlc_media_list_new}(). ''' f = _Cfunctions.get('libvlc_media_list_retain', None) or \ _Cfunction('libvlc_media_list_retain', ((1,),), None, None, MediaList) return f(p_ml) def libvlc_media_list_set_media(p_ml, p_md): '''Associate media instance with this media list instance. If another media instance was present it will be released. The L{libvlc_media_list_lock} should NOT be held upon entering this function. @param p_ml: a media list instance. @param p_md: media instance to add. ''' f = _Cfunctions.get('libvlc_media_list_set_media', None) or \ _Cfunction('libvlc_media_list_set_media', ((1,), (1,),), None, None, MediaList, Media) return f(p_ml, p_md) def libvlc_media_list_media(p_ml): '''Get media instance from this media list instance. This action will increase the refcount on the media instance. The L{libvlc_media_list_lock} should NOT be held upon entering this function. @param p_ml: a media list instance. @return: media instance. ''' f = _Cfunctions.get('libvlc_media_list_media', None) or \ _Cfunction('libvlc_media_list_media', ((1,),), class_result(Media), ctypes.c_void_p, MediaList) return f(p_ml) def libvlc_media_list_add_media(p_ml, p_md): '''Add media instance to media list The L{libvlc_media_list_lock} should be held upon entering this function. @param p_ml: a media list instance. @param p_md: a media instance. @return: 0 on success, -1 if the media list is read-only. ''' f = _Cfunctions.get('libvlc_media_list_add_media', None) or \ _Cfunction('libvlc_media_list_add_media', ((1,), (1,),), None, ctypes.c_int, MediaList, Media) return f(p_ml, p_md) def libvlc_media_list_insert_media(p_ml, p_md, i_pos): '''Insert media instance in media list on a position The L{libvlc_media_list_lock} should be held upon entering this function. @param p_ml: a media list instance. @param p_md: a media instance. @param i_pos: position in array where to insert. @return: 0 on success, -1 if the media list is read-only. ''' f = _Cfunctions.get('libvlc_media_list_insert_media', None) or \ _Cfunction('libvlc_media_list_insert_media', ((1,), (1,), (1,),), None, ctypes.c_int, MediaList, Media, ctypes.c_int) return f(p_ml, p_md, i_pos) def libvlc_media_list_remove_index(p_ml, i_pos): '''Remove media instance from media list on a position The L{libvlc_media_list_lock} should be held upon entering this function. @param p_ml: a media list instance. @param i_pos: position in array where to insert. @return: 0 on success, -1 if the list is read-only or the item was not found. ''' f = _Cfunctions.get('libvlc_media_list_remove_index', None) or \ _Cfunction('libvlc_media_list_remove_index', ((1,), (1,),), None, ctypes.c_int, MediaList, ctypes.c_int) return f(p_ml, i_pos) def libvlc_media_list_count(p_ml): '''Get count on media list items The L{libvlc_media_list_lock} should be held upon entering this function. @param p_ml: a media list instance. @return: number of items in media list. ''' f = _Cfunctions.get('libvlc_media_list_count', None) or \ _Cfunction('libvlc_media_list_count', ((1,),), None, ctypes.c_int, MediaList) return f(p_ml) def libvlc_media_list_item_at_index(p_ml, i_pos): '''List media instance in media list at a position The L{libvlc_media_list_lock} should be held upon entering this function. @param p_ml: a media list instance. @param i_pos: position in array where to insert. @return: media instance at position i_pos, or NULL if not found. In case of success, L{libvlc_media_retain}() is called to increase the refcount on the media. ''' f = _Cfunctions.get('libvlc_media_list_item_at_index', None) or \ _Cfunction('libvlc_media_list_item_at_index', ((1,), (1,),), class_result(Media), ctypes.c_void_p, MediaList, ctypes.c_int) return f(p_ml, i_pos) def libvlc_media_list_index_of_item(p_ml, p_md): '''Find index position of List media instance in media list. Warning: the function will return the first matched position. The L{libvlc_media_list_lock} should be held upon entering this function. @param p_ml: a media list instance. @param p_md: media instance. @return: position of media instance or -1 if media not found. ''' f = _Cfunctions.get('libvlc_media_list_index_of_item', None) or \ _Cfunction('libvlc_media_list_index_of_item', ((1,), (1,),), None, ctypes.c_int, MediaList, Media) return f(p_ml, p_md) def libvlc_media_list_is_readonly(p_ml): '''This indicates if this media list is read-only from a user point of view. @param p_ml: media list instance. @return: 1 on readonly, 0 on readwrite \libvlc_return_bool. ''' f = _Cfunctions.get('libvlc_media_list_is_readonly', None) or \ _Cfunction('libvlc_media_list_is_readonly', ((1,),), None, ctypes.c_int, MediaList) return f(p_ml) def libvlc_media_list_lock(p_ml): '''Get lock on media list items. @param p_ml: a media list instance. ''' f = _Cfunctions.get('libvlc_media_list_lock', None) or \ _Cfunction('libvlc_media_list_lock', ((1,),), None, None, MediaList) return f(p_ml) def libvlc_media_list_unlock(p_ml): '''Release lock on media list items The L{libvlc_media_list_lock} should be held upon entering this function. @param p_ml: a media list instance. ''' f = _Cfunctions.get('libvlc_media_list_unlock', None) or \ _Cfunction('libvlc_media_list_unlock', ((1,),), None, None, MediaList) return f(p_ml) def libvlc_media_list_event_manager(p_ml): '''Get libvlc_event_manager from this media list instance. The p_event_manager is immutable, so you don't have to hold the lock. @param p_ml: a media list instance. @return: libvlc_event_manager. ''' f = _Cfunctions.get('libvlc_media_list_event_manager', None) or \ _Cfunction('libvlc_media_list_event_manager', ((1,),), class_result(EventManager), ctypes.c_void_p, MediaList) return f(p_ml) def libvlc_media_list_player_new(p_instance): '''Create new media_list_player. @param p_instance: libvlc instance. @return: media list player instance or NULL on error. ''' f = _Cfunctions.get('libvlc_media_list_player_new', None) or \ _Cfunction('libvlc_media_list_player_new', ((1,),), class_result(MediaListPlayer), ctypes.c_void_p, Instance) return f(p_instance) def libvlc_media_list_player_release(p_mlp): '''Release a media_list_player after use Decrement the reference count of a media player object. If the reference count is 0, then L{libvlc_media_list_player_release}() will release the media player object. If the media player object has been released, then it should not be used again. @param p_mlp: media list player instance. ''' f = _Cfunctions.get('libvlc_media_list_player_release', None) or \ _Cfunction('libvlc_media_list_player_release', ((1,),), None, None, MediaListPlayer) return f(p_mlp) def libvlc_media_list_player_retain(p_mlp): '''Retain a reference to a media player list object. Use L{libvlc_media_list_player_release}() to decrement reference count. @param p_mlp: media player list object. ''' f = _Cfunctions.get('libvlc_media_list_player_retain', None) or \ _Cfunction('libvlc_media_list_player_retain', ((1,),), None, None, MediaListPlayer) return f(p_mlp) def libvlc_media_list_player_event_manager(p_mlp): '''Return the event manager of this media_list_player. @param p_mlp: media list player instance. @return: the event manager. ''' f = _Cfunctions.get('libvlc_media_list_player_event_manager', None) or \ _Cfunction('libvlc_media_list_player_event_manager', ((1,),), class_result(EventManager), ctypes.c_void_p, MediaListPlayer) return f(p_mlp) def libvlc_media_list_player_set_media_player(p_mlp, p_mi): '''Replace media player in media_list_player with this instance. @param p_mlp: media list player instance. @param p_mi: media player instance. ''' f = _Cfunctions.get('libvlc_media_list_player_set_media_player', None) or \ _Cfunction('libvlc_media_list_player_set_media_player', ((1,), (1,),), None, None, MediaListPlayer, MediaPlayer) return f(p_mlp, p_mi) def libvlc_media_list_player_set_media_list(p_mlp, p_mlist): '''Set the media list associated with the player. @param p_mlp: media list player instance. @param p_mlist: list of media. ''' f = _Cfunctions.get('libvlc_media_list_player_set_media_list', None) or \ _Cfunction('libvlc_media_list_player_set_media_list', ((1,), (1,),), None, None, MediaListPlayer, MediaList) return f(p_mlp, p_mlist) def libvlc_media_list_player_play(p_mlp): '''Play media list. @param p_mlp: media list player instance. ''' f = _Cfunctions.get('libvlc_media_list_player_play', None) or \ _Cfunction('libvlc_media_list_player_play', ((1,),), None, None, MediaListPlayer) return f(p_mlp) def libvlc_media_list_player_pause(p_mlp): '''Toggle pause (or resume) media list. @param p_mlp: media list player instance. ''' f = _Cfunctions.get('libvlc_media_list_player_pause', None) or \ _Cfunction('libvlc_media_list_player_pause', ((1,),), None, None, MediaListPlayer) return f(p_mlp) def libvlc_media_list_player_is_playing(p_mlp): '''Is media list playing? @param p_mlp: media list player instance. @return: true for playing and false for not playing \libvlc_return_bool. ''' f = _Cfunctions.get('libvlc_media_list_player_is_playing', None) or \ _Cfunction('libvlc_media_list_player_is_playing', ((1,),), None, ctypes.c_int, MediaListPlayer) return f(p_mlp) def libvlc_media_list_player_get_state(p_mlp): '''Get current libvlc_state of media list player. @param p_mlp: media list player instance. @return: libvlc_state_t for media list player. ''' f = _Cfunctions.get('libvlc_media_list_player_get_state', None) or \ _Cfunction('libvlc_media_list_player_get_state', ((1,),), None, State, MediaListPlayer) return f(p_mlp) def libvlc_media_list_player_play_item_at_index(p_mlp, i_index): '''Play media list item at position index. @param p_mlp: media list player instance. @param i_index: index in media list to play. @return: 0 upon success -1 if the item wasn't found. ''' f = _Cfunctions.get('libvlc_media_list_player_play_item_at_index', None) or \ _Cfunction('libvlc_media_list_player_play_item_at_index', ((1,), (1,),), None, ctypes.c_int, MediaListPlayer, ctypes.c_int) return f(p_mlp, i_index) def libvlc_media_list_player_play_item(p_mlp, p_md): '''Play the given media item. @param p_mlp: media list player instance. @param p_md: the media instance. @return: 0 upon success, -1 if the media is not part of the media list. ''' f = _Cfunctions.get('libvlc_media_list_player_play_item', None) or \ _Cfunction('libvlc_media_list_player_play_item', ((1,), (1,),), None, ctypes.c_int, MediaListPlayer, Media) return f(p_mlp, p_md) def libvlc_media_list_player_stop(p_mlp): '''Stop playing media list. @param p_mlp: media list player instance. ''' f = _Cfunctions.get('libvlc_media_list_player_stop', None) or \ _Cfunction('libvlc_media_list_player_stop', ((1,),), None, None, MediaListPlayer) return f(p_mlp) def libvlc_media_list_player_next(p_mlp): '''Play next item from media list. @param p_mlp: media list player instance. @return: 0 upon success -1 if there is no next item. ''' f = _Cfunctions.get('libvlc_media_list_player_next', None) or \ _Cfunction('libvlc_media_list_player_next', ((1,),), None, ctypes.c_int, MediaListPlayer) return f(p_mlp) def libvlc_media_list_player_previous(p_mlp): '''Play previous item from media list. @param p_mlp: media list player instance. @return: 0 upon success -1 if there is no previous item. ''' f = _Cfunctions.get('libvlc_media_list_player_previous', None) or \ _Cfunction('libvlc_media_list_player_previous', ((1,),), None, ctypes.c_int, MediaListPlayer) return f(p_mlp) def libvlc_media_list_player_set_playback_mode(p_mlp, e_mode): '''Sets the playback mode for the playlist. @param p_mlp: media list player instance. @param e_mode: playback mode specification. ''' f = _Cfunctions.get('libvlc_media_list_player_set_playback_mode', None) or \ _Cfunction('libvlc_media_list_player_set_playback_mode', ((1,), (1,),), None, None, MediaListPlayer, PlaybackMode) return f(p_mlp, e_mode) def libvlc_media_player_new(p_libvlc_instance): '''Create an empty Media Player object. @param p_libvlc_instance: the libvlc instance in which the Media Player should be created. @return: a new media player object, or NULL on error. ''' f = _Cfunctions.get('libvlc_media_player_new', None) or \ _Cfunction('libvlc_media_player_new', ((1,),), class_result(MediaPlayer), ctypes.c_void_p, Instance) return f(p_libvlc_instance) def libvlc_media_player_new_from_media(p_md): '''Create a Media Player object from a Media. @param p_md: the media. Afterwards the p_md can be safely destroyed. @return: a new media player object, or NULL on error. ''' f = _Cfunctions.get('libvlc_media_player_new_from_media', None) or \ _Cfunction('libvlc_media_player_new_from_media', ((1,),), class_result(MediaPlayer), ctypes.c_void_p, Media) return f(p_md) def libvlc_media_player_release(p_mi): '''Release a media_player after use Decrement the reference count of a media player object. If the reference count is 0, then L{libvlc_media_player_release}() will release the media player object. If the media player object has been released, then it should not be used again. @param p_mi: the Media Player to free. ''' f = _Cfunctions.get('libvlc_media_player_release', None) or \ _Cfunction('libvlc_media_player_release', ((1,),), None, None, MediaPlayer) return f(p_mi) def libvlc_media_player_retain(p_mi): '''Retain a reference to a media player object. Use L{libvlc_media_player_release}() to decrement reference count. @param p_mi: media player object. ''' f = _Cfunctions.get('libvlc_media_player_retain', None) or \ _Cfunction('libvlc_media_player_retain', ((1,),), None, None, MediaPlayer) return f(p_mi) def libvlc_media_player_set_media(p_mi, p_md): '''Set the media that will be used by the media_player. If any, previous md will be released. @param p_mi: the Media Player. @param p_md: the Media. Afterwards the p_md can be safely destroyed. ''' f = _Cfunctions.get('libvlc_media_player_set_media', None) or \ _Cfunction('libvlc_media_player_set_media', ((1,), (1,),), None, None, MediaPlayer, Media) return f(p_mi, p_md) def libvlc_media_player_get_media(p_mi): '''Get the media used by the media_player. @param p_mi: the Media Player. @return: the media associated with p_mi, or NULL if no media is associated. ''' f = _Cfunctions.get('libvlc_media_player_get_media', None) or \ _Cfunction('libvlc_media_player_get_media', ((1,),), class_result(Media), ctypes.c_void_p, MediaPlayer) return f(p_mi) def libvlc_media_player_event_manager(p_mi): '''Get the Event Manager from which the media player send event. @param p_mi: the Media Player. @return: the event manager associated with p_mi. ''' f = _Cfunctions.get('libvlc_media_player_event_manager', None) or \ _Cfunction('libvlc_media_player_event_manager', ((1,),), class_result(EventManager), ctypes.c_void_p, MediaPlayer) return f(p_mi) def libvlc_media_player_is_playing(p_mi): '''is_playing. @param p_mi: the Media Player. @return: 1 if the media player is playing, 0 otherwise \libvlc_return_bool. ''' f = _Cfunctions.get('libvlc_media_player_is_playing', None) or \ _Cfunction('libvlc_media_player_is_playing', ((1,),), None, ctypes.c_int, MediaPlayer) return f(p_mi) def libvlc_media_player_play(p_mi): '''Play. @param p_mi: the Media Player. @return: 0 if playback started (and was already started), or -1 on error. ''' f = _Cfunctions.get('libvlc_media_player_play', None) or \ _Cfunction('libvlc_media_player_play', ((1,),), None, ctypes.c_int, MediaPlayer) return f(p_mi) def libvlc_media_player_set_pause(mp, do_pause): '''Pause or resume (no effect if there is no media). @param mp: the Media Player. @param do_pause: play/resume if zero, pause if non-zero. @version: LibVLC 1.1.1 or later. ''' f = _Cfunctions.get('libvlc_media_player_set_pause', None) or \ _Cfunction('libvlc_media_player_set_pause', ((1,), (1,),), None, None, MediaPlayer, ctypes.c_int) return f(mp, do_pause) def libvlc_media_player_pause(p_mi): '''Toggle pause (no effect if there is no media). @param p_mi: the Media Player. ''' f = _Cfunctions.get('libvlc_media_player_pause', None) or \ _Cfunction('libvlc_media_player_pause', ((1,),), None, None, MediaPlayer) return f(p_mi) def libvlc_media_player_stop(p_mi): '''Stop (no effect if there is no media). @param p_mi: the Media Player. ''' f = _Cfunctions.get('libvlc_media_player_stop', None) or \ _Cfunction('libvlc_media_player_stop', ((1,),), None, None, MediaPlayer) return f(p_mi) def libvlc_video_set_callbacks(mp, lock, unlock, display, opaque): '''Set callbacks and private data to render decoded video to a custom area in memory. Use L{libvlc_video_set_format}() or L{libvlc_video_set_format_callbacks}() to configure the decoded format. @param mp: the media player. @param lock: callback to lock video memory (must not be NULL). @param unlock: callback to unlock video memory (or NULL if not needed). @param display: callback to display video (or NULL if not needed). @param opaque: private pointer for the three callbacks (as first parameter). @version: LibVLC 1.1.1 or later. ''' f = _Cfunctions.get('libvlc_video_set_callbacks', None) or \ _Cfunction('libvlc_video_set_callbacks', ((1,), (1,), (1,), (1,), (1,),), None, None, MediaPlayer, VideoLockCb, VideoUnlockCb, VideoDisplayCb, ctypes.c_void_p) return f(mp, lock, unlock, display, opaque) def libvlc_video_set_format(mp, chroma, width, height, pitch): '''Set decoded video chroma and dimensions. This only works in combination with L{libvlc_video_set_callbacks}(), and is mutually exclusive with L{libvlc_video_set_format_callbacks}(). @param mp: the media player. @param chroma: a four-characters string identifying the chroma (e.g. "RV32" or "YUYV"). @param width: pixel width. @param height: pixel height. @param pitch: line pitch (in bytes). @version: LibVLC 1.1.1 or later. @bug: All pixel planes are expected to have the same pitch. To use the YCbCr color space with chrominance subsampling, consider using L{libvlc_video_set_format_callbacks}() instead. ''' f = _Cfunctions.get('libvlc_video_set_format', None) or \ _Cfunction('libvlc_video_set_format', ((1,), (1,), (1,), (1,), (1,),), None, None, MediaPlayer, ctypes.c_char_p, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint) return f(mp, chroma, width, height, pitch) def libvlc_video_set_format_callbacks(mp, setup, cleanup): '''Set decoded video chroma and dimensions. This only works in combination with L{libvlc_video_set_callbacks}(). @param mp: the media player. @param setup: callback to select the video format (cannot be NULL). @param cleanup: callback to release any allocated resources (or NULL). @version: LibVLC 2.0.0 or later. ''' f = _Cfunctions.get('libvlc_video_set_format_callbacks', None) or \ _Cfunction('libvlc_video_set_format_callbacks', ((1,), (1,), (1,),), None, None, MediaPlayer, VideoFormatCb, VideoCleanupCb) return f(mp, setup, cleanup) def libvlc_media_player_set_nsobject(p_mi, drawable): '''Set the NSView handler where the media player should render its video output. Use the vout called "macosx". The drawable is an NSObject that follow the VLCOpenGLVideoViewEmbedding protocol: @begincode \@protocol VLCOpenGLVideoViewEmbedding <NSObject> - (void)addVoutSubview:(NSView *)view; - (void)removeVoutSubview:(NSView *)view; \@end @endcode Or it can be an NSView object. If you want to use it along with Qt4 see the QMacCocoaViewContainer. Then the following code should work: @begincode NSView *video = [[NSView alloc] init]; QMacCocoaViewContainer *container = new QMacCocoaViewContainer(video, parent); L{libvlc_media_player_set_nsobject}(mp, video); [video release]; @endcode You can find a live example in VLCVideoView in VLCKit.framework. @param p_mi: the Media Player. @param drawable: the drawable that is either an NSView or an object following the VLCOpenGLVideoViewEmbedding protocol. ''' f = _Cfunctions.get('libvlc_media_player_set_nsobject', None) or \ _Cfunction('libvlc_media_player_set_nsobject', ((1,), (1,),), None, None, MediaPlayer, ctypes.c_void_p) return f(p_mi, drawable) def libvlc_media_player_get_nsobject(p_mi): '''Get the NSView handler previously set with L{libvlc_media_player_set_nsobject}(). @param p_mi: the Media Player. @return: the NSView handler or 0 if none where set. ''' f = _Cfunctions.get('libvlc_media_player_get_nsobject', None) or \ _Cfunction('libvlc_media_player_get_nsobject', ((1,),), None, ctypes.c_void_p, MediaPlayer) return f(p_mi) def libvlc_media_player_set_agl(p_mi, drawable): '''Set the agl handler where the media player should render its video output. @param p_mi: the Media Player. @param drawable: the agl handler. ''' f = _Cfunctions.get('libvlc_media_player_set_agl', None) or \ _Cfunction('libvlc_media_player_set_agl', ((1,), (1,),), None, None, MediaPlayer, ctypes.c_uint32) return f(p_mi, drawable) def libvlc_media_player_get_agl(p_mi): '''Get the agl handler previously set with L{libvlc_media_player_set_agl}(). @param p_mi: the Media Player. @return: the agl handler or 0 if none where set. ''' f = _Cfunctions.get('libvlc_media_player_get_agl', None) or \ _Cfunction('libvlc_media_player_get_agl', ((1,),), None, ctypes.c_uint32, MediaPlayer) return f(p_mi) def libvlc_media_player_set_xwindow(p_mi, drawable): '''Set an X Window System drawable where the media player should render its video output. If LibVLC was built without X11 output support, then this has no effects. The specified identifier must correspond to an existing Input/Output class X11 window. Pixmaps are B{not} supported. The caller shall ensure that the X11 server is the same as the one the VLC instance has been configured with. This function must be called before video playback is started; otherwise it will only take effect after playback stop and restart. @param p_mi: the Media Player. @param drawable: the ID of the X window. ''' f = _Cfunctions.get('libvlc_media_player_set_xwindow', None) or \ _Cfunction('libvlc_media_player_set_xwindow', ((1,), (1,),), None, None, MediaPlayer, ctypes.c_uint32) return f(p_mi, drawable) def libvlc_media_player_get_xwindow(p_mi): '''Get the X Window System window identifier previously set with L{libvlc_media_player_set_xwindow}(). Note that this will return the identifier even if VLC is not currently using it (for instance if it is playing an audio-only input). @param p_mi: the Media Player. @return: an X window ID, or 0 if none where set. ''' f = _Cfunctions.get('libvlc_media_player_get_xwindow', None) or \ _Cfunction('libvlc_media_player_get_xwindow', ((1,),), None, ctypes.c_uint32, MediaPlayer) return f(p_mi) def libvlc_media_player_set_hwnd(p_mi, drawable): '''Set a Win32/Win64 API window handle (HWND) where the media player should render its video output. If LibVLC was built without Win32/Win64 API output support, then this has no effects. @param p_mi: the Media Player. @param drawable: windows handle of the drawable. ''' f = _Cfunctions.get('libvlc_media_player_set_hwnd', None) or \ _Cfunction('libvlc_media_player_set_hwnd', ((1,), (1,),), None, None, MediaPlayer, ctypes.c_void_p) return f(p_mi, drawable) def libvlc_media_player_get_hwnd(p_mi): '''Get the Windows API window handle (HWND) previously set with L{libvlc_media_player_set_hwnd}(). The handle will be returned even if LibVLC is not currently outputting any video to it. @param p_mi: the Media Player. @return: a window handle or NULL if there are none. ''' f = _Cfunctions.get('libvlc_media_player_get_hwnd', None) or \ _Cfunction('libvlc_media_player_get_hwnd', ((1,),), None, ctypes.c_void_p, MediaPlayer) return f(p_mi) def libvlc_audio_set_callbacks(mp, play, pause, resume, flush, drain, opaque): '''Set callbacks and private data for decoded audio. Use L{libvlc_audio_set_format}() or L{libvlc_audio_set_format_callbacks}() to configure the decoded audio format. @param mp: the media player. @param play: callback to play audio samples (must not be NULL). @param pause: callback to pause playback (or NULL to ignore). @param resume: callback to resume playback (or NULL to ignore). @param flush: callback to flush audio buffers (or NULL to ignore). @param drain: callback to drain audio buffers (or NULL to ignore). @param opaque: private pointer for the audio callbacks (as first parameter). @version: LibVLC 2.0.0 or later. ''' f = _Cfunctions.get('libvlc_audio_set_callbacks', None) or \ _Cfunction('libvlc_audio_set_callbacks', ((1,), (1,), (1,), (1,), (1,), (1,), (1,),), None, None, MediaPlayer, AudioPlayCb, AudioPauseCb, AudioResumeCb, AudioFlushCb, AudioDrainCb, ctypes.c_void_p) return f(mp, play, pause, resume, flush, drain, opaque) def libvlc_audio_set_volume_callback(mp, set_volume): '''Set callbacks and private data for decoded audio. Use L{libvlc_audio_set_format}() or L{libvlc_audio_set_format_callbacks}() to configure the decoded audio format. @param mp: the media player. @param set_volume: callback to apply audio volume, or NULL to apply volume in software. @version: LibVLC 2.0.0 or later. ''' f = _Cfunctions.get('libvlc_audio_set_volume_callback', None) or \ _Cfunction('libvlc_audio_set_volume_callback', ((1,), (1,),), None, None, MediaPlayer, AudioSetVolumeCb) return f(mp, set_volume) def libvlc_audio_set_format_callbacks(mp, setup, cleanup): '''Set decoded audio format. This only works in combination with L{libvlc_audio_set_callbacks}(). @param mp: the media player. @param setup: callback to select the audio format (cannot be NULL). @param cleanup: callback to release any allocated resources (or NULL). @version: LibVLC 2.0.0 or later. ''' f = _Cfunctions.get('libvlc_audio_set_format_callbacks', None) or \ _Cfunction('libvlc_audio_set_format_callbacks', ((1,), (1,), (1,),), None, None, MediaPlayer, AudioSetupCb, AudioCleanupCb) return f(mp, setup, cleanup) def libvlc_audio_set_format(mp, format, rate, channels): '''Set decoded audio format. This only works in combination with L{libvlc_audio_set_callbacks}(), and is mutually exclusive with L{libvlc_audio_set_format_callbacks}(). @param mp: the media player. @param format: a four-characters string identifying the sample format (e.g. "S16N" or "FL32"). @param rate: sample rate (expressed in Hz). @param channels: channels count. @version: LibVLC 2.0.0 or later. ''' f = _Cfunctions.get('libvlc_audio_set_format', None) or \ _Cfunction('libvlc_audio_set_format', ((1,), (1,), (1,), (1,),), None, None, MediaPlayer, ctypes.c_char_p, ctypes.c_uint, ctypes.c_uint) return f(mp, format, rate, channels) def libvlc_media_player_get_length(p_mi): '''Get the current movie length (in ms). @param p_mi: the Media Player. @return: the movie length (in ms), or -1 if there is no media. ''' f = _Cfunctions.get('libvlc_media_player_get_length', None) or \ _Cfunction('libvlc_media_player_get_length', ((1,),), None, ctypes.c_longlong, MediaPlayer) return f(p_mi) def libvlc_media_player_get_time(p_mi): '''Get the current movie time (in ms). @param p_mi: the Media Player. @return: the movie time (in ms), or -1 if there is no media. ''' f = _Cfunctions.get('libvlc_media_player_get_time', None) or \ _Cfunction('libvlc_media_player_get_time', ((1,),), None, ctypes.c_longlong, MediaPlayer) return f(p_mi) def libvlc_media_player_set_time(p_mi, i_time): '''Set the movie time (in ms). This has no effect if no media is being played. Not all formats and protocols support this. @param p_mi: the Media Player. @param i_time: the movie time (in ms). ''' f = _Cfunctions.get('libvlc_media_player_set_time', None) or \ _Cfunction('libvlc_media_player_set_time', ((1,), (1,),), None, None, MediaPlayer, ctypes.c_longlong) return f(p_mi, i_time) def libvlc_media_player_get_position(p_mi): '''Get movie position as percentage between 0.0 and 1.0. @param p_mi: the Media Player. @return: movie position, or -1. in case of error. ''' f = _Cfunctions.get('libvlc_media_player_get_position', None) or \ _Cfunction('libvlc_media_player_get_position', ((1,),), None, ctypes.c_float, MediaPlayer) return f(p_mi) def libvlc_media_player_set_position(p_mi, f_pos): '''Set movie position as percentage between 0.0 and 1.0. This has no effect if playback is not enabled. This might not work depending on the underlying input format and protocol. @param p_mi: the Media Player. @param f_pos: the position. ''' f = _Cfunctions.get('libvlc_media_player_set_position', None) or \ _Cfunction('libvlc_media_player_set_position', ((1,), (1,),), None, None, MediaPlayer, ctypes.c_float) return f(p_mi, f_pos) def libvlc_media_player_set_chapter(p_mi, i_chapter): '''Set movie chapter (if applicable). @param p_mi: the Media Player. @param i_chapter: chapter number to play. ''' f = _Cfunctions.get('libvlc_media_player_set_chapter', None) or \ _Cfunction('libvlc_media_player_set_chapter', ((1,), (1,),), None, None, MediaPlayer, ctypes.c_int) return f(p_mi, i_chapter) def libvlc_media_player_get_chapter(p_mi): '''Get movie chapter. @param p_mi: the Media Player. @return: chapter number currently playing, or -1 if there is no media. ''' f = _Cfunctions.get('libvlc_media_player_get_chapter', None) or \ _Cfunction('libvlc_media_player_get_chapter', ((1,),), None, ctypes.c_int, MediaPlayer) return f(p_mi) def libvlc_media_player_get_chapter_count(p_mi): '''Get movie chapter count. @param p_mi: the Media Player. @return: number of chapters in movie, or -1. ''' f = _Cfunctions.get('libvlc_media_player_get_chapter_count', None) or \ _Cfunction('libvlc_media_player_get_chapter_count', ((1,),), None, ctypes.c_int, MediaPlayer) return f(p_mi) def libvlc_media_player_will_play(p_mi): '''Is the player able to play. @param p_mi: the Media Player. @return: boolean \libvlc_return_bool. ''' f = _Cfunctions.get('libvlc_media_player_will_play', None) or \ _Cfunction('libvlc_media_player_will_play', ((1,),), None, ctypes.c_int, MediaPlayer) return f(p_mi) def libvlc_media_player_get_chapter_count_for_title(p_mi, i_title): '''Get title chapter count. @param p_mi: the Media Player. @param i_title: title. @return: number of chapters in title, or -1. ''' f = _Cfunctions.get('libvlc_media_player_get_chapter_count_for_title', None) or \ _Cfunction('libvlc_media_player_get_chapter_count_for_title', ((1,), (1,),), None, ctypes.c_int, MediaPlayer, ctypes.c_int) return f(p_mi, i_title) def libvlc_media_player_set_title(p_mi, i_title): '''Set movie title. @param p_mi: the Media Player. @param i_title: title number to play. ''' f = _Cfunctions.get('libvlc_media_player_set_title', None) or \ _Cfunction('libvlc_media_player_set_title', ((1,), (1,),), None, None, MediaPlayer, ctypes.c_int) return f(p_mi, i_title) def libvlc_media_player_get_title(p_mi): '''Get movie title. @param p_mi: the Media Player. @return: title number currently playing, or -1. ''' f = _Cfunctions.get('libvlc_media_player_get_title', None) or \ _Cfunction('libvlc_media_player_get_title', ((1,),), None, ctypes.c_int, MediaPlayer) return f(p_mi) def libvlc_media_player_get_title_count(p_mi): '''Get movie title count. @param p_mi: the Media Player. @return: title number count, or -1. ''' f = _Cfunctions.get('libvlc_media_player_get_title_count', None) or \ _Cfunction('libvlc_media_player_get_title_count', ((1,),), None, ctypes.c_int, MediaPlayer) return f(p_mi) def libvlc_media_player_previous_chapter(p_mi): '''Set previous chapter (if applicable). @param p_mi: the Media Player. ''' f = _Cfunctions.get('libvlc_media_player_previous_chapter', None) or \ _Cfunction('libvlc_media_player_previous_chapter', ((1,),), None, None, MediaPlayer) return f(p_mi) def libvlc_media_player_next_chapter(p_mi): '''Set next chapter (if applicable). @param p_mi: the Media Player. ''' f = _Cfunctions.get('libvlc_media_player_next_chapter', None) or \ _Cfunction('libvlc_media_player_next_chapter', ((1,),), None, None, MediaPlayer) return f(p_mi) def libvlc_media_player_get_rate(p_mi): '''Get the requested movie play rate. @warning: Depending on the underlying media, the requested rate may be different from the real playback rate. @param p_mi: the Media Player. @return: movie play rate. ''' f = _Cfunctions.get('libvlc_media_player_get_rate', None) or \ _Cfunction('libvlc_media_player_get_rate', ((1,),), None, ctypes.c_float, MediaPlayer) return f(p_mi) def libvlc_media_player_set_rate(p_mi, rate): '''Set movie play rate. @param p_mi: the Media Player. @param rate: movie play rate to set. @return: -1 if an error was detected, 0 otherwise (but even then, it might not actually work depending on the underlying media protocol). ''' f = _Cfunctions.get('libvlc_media_player_set_rate', None) or \ _Cfunction('libvlc_media_player_set_rate', ((1,), (1,),), None, ctypes.c_int, MediaPlayer, ctypes.c_float) return f(p_mi, rate) def libvlc_media_player_get_state(p_mi): '''Get current movie state. @param p_mi: the Media Player. @return: the current state of the media player (playing, paused, ...) See libvlc_state_t. ''' f = _Cfunctions.get('libvlc_media_player_get_state', None) or \ _Cfunction('libvlc_media_player_get_state', ((1,),), None, State, MediaPlayer) return f(p_mi) def libvlc_media_player_get_fps(p_mi): '''Get movie fps rate. @param p_mi: the Media Player. @return: frames per second (fps) for this playing movie, or 0 if unspecified. ''' f = _Cfunctions.get('libvlc_media_player_get_fps', None) or \ _Cfunction('libvlc_media_player_get_fps', ((1,),), None, ctypes.c_float, MediaPlayer) return f(p_mi) def libvlc_media_player_has_vout(p_mi): '''How many video outputs does this media player have? @param p_mi: the media player. @return: the number of video outputs. ''' f = _Cfunctions.get('libvlc_media_player_has_vout', None) or \ _Cfunction('libvlc_media_player_has_vout', ((1,),), None, ctypes.c_uint, MediaPlayer) return f(p_mi) def libvlc_media_player_is_seekable(p_mi): '''Is this media player seekable? @param p_mi: the media player. @return: true if the media player can seek \libvlc_return_bool. ''' f = _Cfunctions.get('libvlc_media_player_is_seekable', None) or \ _Cfunction('libvlc_media_player_is_seekable', ((1,),), None, ctypes.c_int, MediaPlayer) return f(p_mi) def libvlc_media_player_can_pause(p_mi): '''Can this media player be paused? @param p_mi: the media player. @return: true if the media player can pause \libvlc_return_bool. ''' f = _Cfunctions.get('libvlc_media_player_can_pause', None) or \ _Cfunction('libvlc_media_player_can_pause', ((1,),), None, ctypes.c_int, MediaPlayer) return f(p_mi) def libvlc_media_player_next_frame(p_mi): '''Display the next frame (if supported). @param p_mi: the media player. ''' f = _Cfunctions.get('libvlc_media_player_next_frame', None) or \ _Cfunction('libvlc_media_player_next_frame', ((1,),), None, None, MediaPlayer) return f(p_mi) def libvlc_media_player_navigate(p_mi, navigate): '''Navigate through DVD Menu. @param p_mi: the Media Player. @param navigate: the Navigation mode. @version: libVLC 2.0.0 or later. ''' f = _Cfunctions.get('libvlc_media_player_navigate', None) or \ _Cfunction('libvlc_media_player_navigate', ((1,), (1,),), None, None, MediaPlayer, ctypes.c_uint) return f(p_mi, navigate) def libvlc_track_description_list_release(p_track_description): '''Release (free) L{TrackDescription}. @param p_track_description: the structure to release. ''' f = _Cfunctions.get('libvlc_track_description_list_release', None) or \ _Cfunction('libvlc_track_description_list_release', ((1,),), None, None, ctypes.POINTER(TrackDescription)) return f(p_track_description) def libvlc_toggle_fullscreen(p_mi): '''Toggle fullscreen status on non-embedded video outputs. @warning: The same limitations applies to this function as to L{libvlc_set_fullscreen}(). @param p_mi: the media player. ''' f = _Cfunctions.get('libvlc_toggle_fullscreen', None) or \ _Cfunction('libvlc_toggle_fullscreen', ((1,),), None, None, MediaPlayer) return f(p_mi) def libvlc_set_fullscreen(p_mi, b_fullscreen): '''Enable or disable fullscreen. @warning: With most window managers, only a top-level windows can be in full-screen mode. Hence, this function will not operate properly if L{libvlc_media_player_set_xwindow}() was used to embed the video in a non-top-level window. In that case, the embedding window must be reparented to the root window B{before} fullscreen mode is enabled. You will want to reparent it back to its normal parent when disabling fullscreen. @param p_mi: the media player. @param b_fullscreen: boolean for fullscreen status. ''' f = _Cfunctions.get('libvlc_set_fullscreen', None) or \ _Cfunction('libvlc_set_fullscreen', ((1,), (1,),), None, None, MediaPlayer, ctypes.c_int) return f(p_mi, b_fullscreen) def libvlc_get_fullscreen(p_mi): '''Get current fullscreen status. @param p_mi: the media player. @return: the fullscreen status (boolean) \libvlc_return_bool. ''' f = _Cfunctions.get('libvlc_get_fullscreen', None) or \ _Cfunction('libvlc_get_fullscreen', ((1,),), None, ctypes.c_int, MediaPlayer) return f(p_mi) def libvlc_video_set_key_input(p_mi, on): '''Enable or disable key press events handling, according to the LibVLC hotkeys configuration. By default and for historical reasons, keyboard events are handled by the LibVLC video widget. @note: On X11, there can be only one subscriber for key press and mouse click events per window. If your application has subscribed to those events for the X window ID of the video widget, then LibVLC will not be able to handle key presses and mouse clicks in any case. @warning: This function is only implemented for X11 and Win32 at the moment. @param p_mi: the media player. @param on: true to handle key press events, false to ignore them. ''' f = _Cfunctions.get('libvlc_video_set_key_input', None) or \ _Cfunction('libvlc_video_set_key_input', ((1,), (1,),), None, None, MediaPlayer, ctypes.c_uint) return f(p_mi, on) def libvlc_video_set_mouse_input(p_mi, on): '''Enable or disable mouse click events handling. By default, those events are handled. This is needed for DVD menus to work, as well as a few video filters such as "puzzle". See L{libvlc_video_set_key_input}(). @warning: This function is only implemented for X11 and Win32 at the moment. @param p_mi: the media player. @param on: true to handle mouse click events, false to ignore them. ''' f = _Cfunctions.get('libvlc_video_set_mouse_input', None) or \ _Cfunction('libvlc_video_set_mouse_input', ((1,), (1,),), None, None, MediaPlayer, ctypes.c_uint) return f(p_mi, on) def libvlc_video_get_size(p_mi, num): '''Get the pixel dimensions of a video. @param p_mi: media player. @param num: number of the video (starting from, and most commonly 0). @return: px pixel width, py pixel height. ''' f = _Cfunctions.get('libvlc_video_get_size', None) or \ _Cfunction('libvlc_video_get_size', ((1,), (1,), (2,), (2,),), None, ctypes.c_int, MediaPlayer, ctypes.c_uint, ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint)) return f(p_mi, num) def libvlc_video_get_cursor(p_mi, num): '''Get the mouse pointer coordinates over a video. Coordinates are expressed in terms of the decoded video resolution, B{not} in terms of pixels on the screen/viewport (to get the latter, you can query your windowing system directly). Either of the coordinates may be negative or larger than the corresponding dimension of the video, if the cursor is outside the rendering area. @warning: The coordinates may be out-of-date if the pointer is not located on the video rendering area. LibVLC does not track the pointer if it is outside of the video widget. @note: LibVLC does not support multiple pointers (it does of course support multiple input devices sharing the same pointer) at the moment. @param p_mi: media player. @param num: number of the video (starting from, and most commonly 0). @return: px abscissa, py ordinate. ''' f = _Cfunctions.get('libvlc_video_get_cursor', None) or \ _Cfunction('libvlc_video_get_cursor', ((1,), (1,), (2,), (2,),), None, ctypes.c_int, MediaPlayer, ctypes.c_uint, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)) return f(p_mi, num) def libvlc_video_get_scale(p_mi): '''Get the current video scaling factor. See also L{libvlc_video_set_scale}(). @param p_mi: the media player. @return: the currently configured zoom factor, or 0. if the video is set to fit to the output window/drawable automatically. ''' f = _Cfunctions.get('libvlc_video_get_scale', None) or \ _Cfunction('libvlc_video_get_scale', ((1,),), None, ctypes.c_float, MediaPlayer) return f(p_mi) def libvlc_video_set_scale(p_mi, f_factor): '''Set the video scaling factor. That is the ratio of the number of pixels on screen to the number of pixels in the original decoded video in each dimension. Zero is a special value; it will adjust the video to the output window/drawable (in windowed mode) or the entire screen. Note that not all video outputs support scaling. @param p_mi: the media player. @param f_factor: the scaling factor, or zero. ''' f = _Cfunctions.get('libvlc_video_set_scale', None) or \ _Cfunction('libvlc_video_set_scale', ((1,), (1,),), None, None, MediaPlayer, ctypes.c_float) return f(p_mi, f_factor) def libvlc_video_get_aspect_ratio(p_mi): '''Get current video aspect ratio. @param p_mi: the media player. @return: the video aspect ratio or NULL if unspecified (the result must be released with free() or L{libvlc_free}()). ''' f = _Cfunctions.get('libvlc_video_get_aspect_ratio', None) or \ _Cfunction('libvlc_video_get_aspect_ratio', ((1,),), string_result, ctypes.c_void_p, MediaPlayer) return f(p_mi) def libvlc_video_set_aspect_ratio(p_mi, psz_aspect): '''Set new video aspect ratio. @param p_mi: the media player. @param psz_aspect: new video aspect-ratio or NULL to reset to default @note Invalid aspect ratios are ignored. ''' f = _Cfunctions.get('libvlc_video_set_aspect_ratio', None) or \ _Cfunction('libvlc_video_set_aspect_ratio', ((1,), (1,),), None, None, MediaPlayer, ctypes.c_char_p) return f(p_mi, psz_aspect) def libvlc_video_get_spu(p_mi): '''Get current video subtitle. @param p_mi: the media player. @return: the video subtitle selected, or -1 if none. ''' f = _Cfunctions.get('libvlc_video_get_spu', None) or \ _Cfunction('libvlc_video_get_spu', ((1,),), None, ctypes.c_int, MediaPlayer) return f(p_mi) def libvlc_video_get_spu_count(p_mi): '''Get the number of available video subtitles. @param p_mi: the media player. @return: the number of available video subtitles. ''' f = _Cfunctions.get('libvlc_video_get_spu_count', None) or \ _Cfunction('libvlc_video_get_spu_count', ((1,),), None, ctypes.c_int, MediaPlayer) return f(p_mi) def libvlc_video_get_spu_description(p_mi): '''Get the description of available video subtitles. @param p_mi: the media player. @return: list containing description of available video subtitles. ''' f = _Cfunctions.get('libvlc_video_get_spu_description', None) or \ _Cfunction('libvlc_video_get_spu_description', ((1,),), None, ctypes.POINTER(TrackDescription), MediaPlayer) return f(p_mi) def libvlc_video_set_spu(p_mi, i_spu): '''Set new video subtitle. @param p_mi: the media player. @param i_spu: video subtitle track to select (i_id from track description). @return: 0 on success, -1 if out of range. ''' f = _Cfunctions.get('libvlc_video_set_spu', None) or \ _Cfunction('libvlc_video_set_spu', ((1,), (1,),), None, ctypes.c_int, MediaPlayer, ctypes.c_int) return f(p_mi, i_spu) def libvlc_video_set_subtitle_file(p_mi, psz_subtitle): '''Set new video subtitle file. @param p_mi: the media player. @param psz_subtitle: new video subtitle file. @return: the success status (boolean). ''' f = _Cfunctions.get('libvlc_video_set_subtitle_file', None) or \ _Cfunction('libvlc_video_set_subtitle_file', ((1,), (1,),), None, ctypes.c_int, MediaPlayer, ctypes.c_char_p) return f(p_mi, psz_subtitle) def libvlc_video_get_spu_delay(p_mi): '''Get the current subtitle delay. Positive values means subtitles are being displayed later, negative values earlier. @param p_mi: media player. @return: time (in microseconds) the display of subtitles is being delayed. @version: LibVLC 2.0.0 or later. ''' f = _Cfunctions.get('libvlc_video_get_spu_delay', None) or \ _Cfunction('libvlc_video_get_spu_delay', ((1,),), None, ctypes.c_int64, MediaPlayer) return f(p_mi) def libvlc_video_set_spu_delay(p_mi, i_delay): '''Set the subtitle delay. This affects the timing of when the subtitle will be displayed. Positive values result in subtitles being displayed later, while negative values will result in subtitles being displayed earlier. The subtitle delay will be reset to zero each time the media changes. @param p_mi: media player. @param i_delay: time (in microseconds) the display of subtitles should be delayed. @return: 0 on success, -1 on error. @version: LibVLC 2.0.0 or later. ''' f = _Cfunctions.get('libvlc_video_set_spu_delay', None) or \ _Cfunction('libvlc_video_set_spu_delay', ((1,), (1,),), None, ctypes.c_int, MediaPlayer, ctypes.c_int64) return f(p_mi, i_delay) def libvlc_video_get_title_description(p_mi): '''Get the description of available titles. @param p_mi: the media player. @return: list containing description of available titles. ''' f = _Cfunctions.get('libvlc_video_get_title_description', None) or \ _Cfunction('libvlc_video_get_title_description', ((1,),), None, ctypes.POINTER(TrackDescription), MediaPlayer) return f(p_mi) def libvlc_video_get_chapter_description(p_mi, i_title): '''Get the description of available chapters for specific title. @param p_mi: the media player. @param i_title: selected title. @return: list containing description of available chapter for title i_title. ''' f = _Cfunctions.get('libvlc_video_get_chapter_description', None) or \ _Cfunction('libvlc_video_get_chapter_description', ((1,), (1,),), None, ctypes.POINTER(TrackDescription), MediaPlayer, ctypes.c_int) return f(p_mi, i_title) def libvlc_video_get_crop_geometry(p_mi): '''Get current crop filter geometry. @param p_mi: the media player. @return: the crop filter geometry or NULL if unset. ''' f = _Cfunctions.get('libvlc_video_get_crop_geometry', None) or \ _Cfunction('libvlc_video_get_crop_geometry', ((1,),), string_result, ctypes.c_void_p, MediaPlayer) return f(p_mi) def libvlc_video_set_crop_geometry(p_mi, psz_geometry): '''Set new crop filter geometry. @param p_mi: the media player. @param psz_geometry: new crop filter geometry (NULL to unset). ''' f = _Cfunctions.get('libvlc_video_set_crop_geometry', None) or \ _Cfunction('libvlc_video_set_crop_geometry', ((1,), (1,),), None, None, MediaPlayer, ctypes.c_char_p) return f(p_mi, psz_geometry) def libvlc_video_get_teletext(p_mi): '''Get current teletext page requested. @param p_mi: the media player. @return: the current teletext page requested. ''' f = _Cfunctions.get('libvlc_video_get_teletext', None) or \ _Cfunction('libvlc_video_get_teletext', ((1,),), None, ctypes.c_int, MediaPlayer) return f(p_mi) def libvlc_video_set_teletext(p_mi, i_page): '''Set new teletext page to retrieve. @param p_mi: the media player. @param i_page: teletex page number requested. ''' f = _Cfunctions.get('libvlc_video_set_teletext', None) or \ _Cfunction('libvlc_video_set_teletext', ((1,), (1,),), None, None, MediaPlayer, ctypes.c_int) return f(p_mi, i_page) def libvlc_toggle_teletext(p_mi): '''Toggle teletext transparent status on video output. @param p_mi: the media player. ''' f = _Cfunctions.get('libvlc_toggle_teletext', None) or \ _Cfunction('libvlc_toggle_teletext', ((1,),), None, None, MediaPlayer) return f(p_mi) def libvlc_video_get_track_count(p_mi): '''Get number of available video tracks. @param p_mi: media player. @return: the number of available video tracks (int). ''' f = _Cfunctions.get('libvlc_video_get_track_count', None) or \ _Cfunction('libvlc_video_get_track_count', ((1,),), None, ctypes.c_int, MediaPlayer) return f(p_mi) def libvlc_video_get_track_description(p_mi): '''Get the description of available video tracks. @param p_mi: media player. @return: list with description of available video tracks, or NULL on error. ''' f = _Cfunctions.get('libvlc_video_get_track_description', None) or \ _Cfunction('libvlc_video_get_track_description', ((1,),), None, ctypes.POINTER(TrackDescription), MediaPlayer) return f(p_mi) def libvlc_video_get_track(p_mi): '''Get current video track. @param p_mi: media player. @return: the video track ID (int) or -1 if no active input. ''' f = _Cfunctions.get('libvlc_video_get_track', None) or \ _Cfunction('libvlc_video_get_track', ((1,),), None, ctypes.c_int, MediaPlayer) return f(p_mi) def libvlc_video_set_track(p_mi, i_track): '''Set video track. @param p_mi: media player. @param i_track: the track ID (i_id field from track description). @return: 0 on success, -1 if out of range. ''' f = _Cfunctions.get('libvlc_video_set_track', None) or \ _Cfunction('libvlc_video_set_track', ((1,), (1,),), None, ctypes.c_int, MediaPlayer, ctypes.c_int) return f(p_mi, i_track) def libvlc_video_take_snapshot(p_mi, num, psz_filepath, i_width, i_height): '''Take a snapshot of the current video window. If i_width AND i_height is 0, original size is used. If i_width XOR i_height is 0, original aspect-ratio is preserved. @param p_mi: media player instance. @param num: number of video output (typically 0 for the first/only one). @param psz_filepath: the path where to save the screenshot to. @param i_width: the snapshot's width. @param i_height: the snapshot's height. @return: 0 on success, -1 if the video was not found. ''' f = _Cfunctions.get('libvlc_video_take_snapshot', None) or \ _Cfunction('libvlc_video_take_snapshot', ((1,), (1,), (1,), (1,), (1,),), None, ctypes.c_int, MediaPlayer, ctypes.c_uint, ctypes.c_char_p, ctypes.c_int, ctypes.c_int) return f(p_mi, num, psz_filepath, i_width, i_height) def libvlc_video_set_deinterlace(p_mi, psz_mode): '''Enable or disable deinterlace filter. @param p_mi: libvlc media player. @param psz_mode: type of deinterlace filter, NULL to disable. ''' f = _Cfunctions.get('libvlc_video_set_deinterlace', None) or \ _Cfunction('libvlc_video_set_deinterlace', ((1,), (1,),), None, None, MediaPlayer, ctypes.c_char_p) return f(p_mi, psz_mode) def libvlc_video_get_marquee_int(p_mi, option): '''Get an integer marquee option value. @param p_mi: libvlc media player. @param option: marq option to get See libvlc_video_marquee_int_option_t. ''' f = _Cfunctions.get('libvlc_video_get_marquee_int', None) or \ _Cfunction('libvlc_video_get_marquee_int', ((1,), (1,),), None, ctypes.c_int, MediaPlayer, ctypes.c_uint) return f(p_mi, option) def libvlc_video_get_marquee_string(p_mi, option): '''Get a string marquee option value. @param p_mi: libvlc media player. @param option: marq option to get See libvlc_video_marquee_string_option_t. ''' f = _Cfunctions.get('libvlc_video_get_marquee_string', None) or \ _Cfunction('libvlc_video_get_marquee_string', ((1,), (1,),), string_result, ctypes.c_void_p, MediaPlayer, ctypes.c_uint) return f(p_mi, option) def libvlc_video_set_marquee_int(p_mi, option, i_val): '''Enable, disable or set an integer marquee option Setting libvlc_marquee_Enable has the side effect of enabling (arg !0) or disabling (arg 0) the marq filter. @param p_mi: libvlc media player. @param option: marq option to set See libvlc_video_marquee_int_option_t. @param i_val: marq option value. ''' f = _Cfunctions.get('libvlc_video_set_marquee_int', None) or \ _Cfunction('libvlc_video_set_marquee_int', ((1,), (1,), (1,),), None, None, MediaPlayer, ctypes.c_uint, ctypes.c_int) return f(p_mi, option, i_val) def libvlc_video_set_marquee_string(p_mi, option, psz_text): '''Set a marquee string option. @param p_mi: libvlc media player. @param option: marq option to set See libvlc_video_marquee_string_option_t. @param psz_text: marq option value. ''' f = _Cfunctions.get('libvlc_video_set_marquee_string', None) or \ _Cfunction('libvlc_video_set_marquee_string', ((1,), (1,), (1,),), None, None, MediaPlayer, ctypes.c_uint, ctypes.c_char_p) return f(p_mi, option, psz_text) def libvlc_video_get_logo_int(p_mi, option): '''Get integer logo option. @param p_mi: libvlc media player instance. @param option: logo option to get, values of libvlc_video_logo_option_t. ''' f = _Cfunctions.get('libvlc_video_get_logo_int', None) or \ _Cfunction('libvlc_video_get_logo_int', ((1,), (1,),), None, ctypes.c_int, MediaPlayer, ctypes.c_uint) return f(p_mi, option) def libvlc_video_set_logo_int(p_mi, option, value): '''Set logo option as integer. Options that take a different type value are ignored. Passing libvlc_logo_enable as option value has the side effect of starting (arg !0) or stopping (arg 0) the logo filter. @param p_mi: libvlc media player instance. @param option: logo option to set, values of libvlc_video_logo_option_t. @param value: logo option value. ''' f = _Cfunctions.get('libvlc_video_set_logo_int', None) or \ _Cfunction('libvlc_video_set_logo_int', ((1,), (1,), (1,),), None, None, MediaPlayer, ctypes.c_uint, ctypes.c_int) return f(p_mi, option, value) def libvlc_video_set_logo_string(p_mi, option, psz_value): '''Set logo option as string. Options that take a different type value are ignored. @param p_mi: libvlc media player instance. @param option: logo option to set, values of libvlc_video_logo_option_t. @param psz_value: logo option value. ''' f = _Cfunctions.get('libvlc_video_set_logo_string', None) or \ _Cfunction('libvlc_video_set_logo_string', ((1,), (1,), (1,),), None, None, MediaPlayer, ctypes.c_uint, ctypes.c_char_p) return f(p_mi, option, psz_value) def libvlc_video_get_adjust_int(p_mi, option): '''Get integer adjust option. @param p_mi: libvlc media player instance. @param option: adjust option to get, values of libvlc_video_adjust_option_t. @version: LibVLC 1.1.1 and later. ''' f = _Cfunctions.get('libvlc_video_get_adjust_int', None) or \ _Cfunction('libvlc_video_get_adjust_int', ((1,), (1,),), None, ctypes.c_int, MediaPlayer, ctypes.c_uint) return f(p_mi, option) def libvlc_video_set_adjust_int(p_mi, option, value): '''Set adjust option as integer. Options that take a different type value are ignored. Passing libvlc_adjust_enable as option value has the side effect of starting (arg !0) or stopping (arg 0) the adjust filter. @param p_mi: libvlc media player instance. @param option: adust option to set, values of libvlc_video_adjust_option_t. @param value: adjust option value. @version: LibVLC 1.1.1 and later. ''' f = _Cfunctions.get('libvlc_video_set_adjust_int', None) or \ _Cfunction('libvlc_video_set_adjust_int', ((1,), (1,), (1,),), None, None, MediaPlayer, ctypes.c_uint, ctypes.c_int) return f(p_mi, option, value) def libvlc_video_get_adjust_float(p_mi, option): '''Get float adjust option. @param p_mi: libvlc media player instance. @param option: adjust option to get, values of libvlc_video_adjust_option_t. @version: LibVLC 1.1.1 and later. ''' f = _Cfunctions.get('libvlc_video_get_adjust_float', None) or \ _Cfunction('libvlc_video_get_adjust_float', ((1,), (1,),), None, ctypes.c_float, MediaPlayer, ctypes.c_uint) return f(p_mi, option) def libvlc_video_set_adjust_float(p_mi, option, value): '''Set adjust option as float. Options that take a different type value are ignored. @param p_mi: libvlc media player instance. @param option: adust option to set, values of libvlc_video_adjust_option_t. @param value: adjust option value. @version: LibVLC 1.1.1 and later. ''' f = _Cfunctions.get('libvlc_video_set_adjust_float', None) or \ _Cfunction('libvlc_video_set_adjust_float', ((1,), (1,), (1,),), None, None, MediaPlayer, ctypes.c_uint, ctypes.c_float) return f(p_mi, option, value) def libvlc_audio_output_list_get(p_instance): '''Gets the list of available audio outputs. @param p_instance: libvlc instance. @return: list of available audio outputs. It must be freed it with In case of error, NULL is returned. ''' f = _Cfunctions.get('libvlc_audio_output_list_get', None) or \ _Cfunction('libvlc_audio_output_list_get', ((1,),), None, ctypes.POINTER(AudioOutput), Instance) return f(p_instance) def libvlc_audio_output_list_release(p_list): '''Frees the list of available audio outputs. @param p_list: list with audio outputs for release. ''' f = _Cfunctions.get('libvlc_audio_output_list_release', None) or \ _Cfunction('libvlc_audio_output_list_release', ((1,),), None, None, ctypes.POINTER(AudioOutput)) return f(p_list) def libvlc_audio_output_set(p_mi, psz_name): '''Sets the audio output. @note: Any change will take be effect only after playback is stopped and restarted. Audio output cannot be changed while playing. @param p_mi: media player. @param psz_name: name of audio output, use psz_name of See L{AudioOutput}. @return: 0 if function succeded, -1 on error. ''' f = _Cfunctions.get('libvlc_audio_output_set', None) or \ _Cfunction('libvlc_audio_output_set', ((1,), (1,),), None, ctypes.c_int, MediaPlayer, ctypes.c_char_p) return f(p_mi, psz_name) def libvlc_audio_output_device_list_get(p_instance, aout): '''Gets a list of audio output devices for a given audio output. See L{libvlc_audio_output_device_set}(). @note: Not all audio outputs support this. In particular, an empty (NULL) list of devices does B{not} imply that the specified audio output does not work. @note: The list might not be exhaustive. @warning: Some audio output devices in the list might not actually work in some circumstances. By default, it is recommended to not specify any explicit audio device. @param p_instance: libvlc instance. @param psz_aout: audio output name (as returned by L{libvlc_audio_output_list_get}()). @return: A NULL-terminated linked list of potential audio output devices. It must be freed it with L{libvlc_audio_output_device_list_release}(). @version: LibVLC 2.1.0 or later. ''' f = _Cfunctions.get('libvlc_audio_output_device_list_get', None) or \ _Cfunction('libvlc_audio_output_device_list_get', ((1,), (1,),), None, ctypes.POINTER(AudioOutputDevice), Instance, ctypes.c_char_p) return f(p_instance, aout) def libvlc_audio_output_device_list_release(p_list): '''Frees a list of available audio output devices. @param p_list: list with audio outputs for release. @version: LibVLC 2.1.0 or later. ''' f = _Cfunctions.get('libvlc_audio_output_device_list_release', None) or \ _Cfunction('libvlc_audio_output_device_list_release', ((1,),), None, None, ctypes.POINTER(AudioOutputDevice)) return f(p_list) def libvlc_audio_output_device_set(p_mi, psz_audio_output, psz_device_id): '''Configures an explicit audio output device for a given audio output plugin. A list of possible devices can be obtained with L{libvlc_audio_output_device_list_get}(). @note: This function does not select the specified audio output plugin. L{libvlc_audio_output_set}() is used for that purpose. @warning: The syntax for the device parameter depends on the audio output. This is not portable. Only use this function if you know what you are doing. Some audio outputs do not support this function (e.g. PulseAudio, WASAPI). Some audio outputs require further parameters (e.g. ALSA: channels map). @param p_mi: media player. @param psz_audio_output: - name of audio output, See L{AudioOutput}. @param psz_device_id: device. @return: Nothing. Errors are ignored. ''' f = _Cfunctions.get('libvlc_audio_output_device_set', None) or \ _Cfunction('libvlc_audio_output_device_set', ((1,), (1,), (1,),), None, None, MediaPlayer, ctypes.c_char_p, ctypes.c_char_p) return f(p_mi, psz_audio_output, psz_device_id) def libvlc_audio_toggle_mute(p_mi): '''Toggle mute status. @param p_mi: media player @warning Toggling mute atomically is not always possible: On some platforms, other processes can mute the VLC audio playback stream asynchronously. Thus, there is a small race condition where toggling will not work. See also the limitations of L{libvlc_audio_set_mute}(). ''' f = _Cfunctions.get('libvlc_audio_toggle_mute', None) or \ _Cfunction('libvlc_audio_toggle_mute', ((1,),), None, None, MediaPlayer) return f(p_mi) def libvlc_audio_get_mute(p_mi): '''Get current mute status. @param p_mi: media player. @return: the mute status (boolean) if defined, -1 if undefined/unapplicable. ''' f = _Cfunctions.get('libvlc_audio_get_mute', None) or \ _Cfunction('libvlc_audio_get_mute', ((1,),), None, ctypes.c_int, MediaPlayer) return f(p_mi) def libvlc_audio_set_mute(p_mi, status): '''Set mute status. @param p_mi: media player. @param status: If status is true then mute, otherwise unmute @warning This function does not always work. If there are no active audio playback stream, the mute status might not be available. If digital pass-through (S/PDIF, HDMI...) is in use, muting may be unapplicable. Also some audio output plugins do not support muting at all. @note To force silent playback, disable all audio tracks. This is more efficient and reliable than mute. ''' f = _Cfunctions.get('libvlc_audio_set_mute', None) or \ _Cfunction('libvlc_audio_set_mute', ((1,), (1,),), None, None, MediaPlayer, ctypes.c_int) return f(p_mi, status) def libvlc_audio_get_volume(p_mi): '''Get current software audio volume. @param p_mi: media player. @return: the software volume in percents (0 = mute, 100 = nominal / 0dB). ''' f = _Cfunctions.get('libvlc_audio_get_volume', None) or \ _Cfunction('libvlc_audio_get_volume', ((1,),), None, ctypes.c_int, MediaPlayer) return f(p_mi) def libvlc_audio_set_volume(p_mi, i_volume): '''Set current software audio volume. @param p_mi: media player. @param i_volume: the volume in percents (0 = mute, 100 = 0dB). @return: 0 if the volume was set, -1 if it was out of range. ''' f = _Cfunctions.get('libvlc_audio_set_volume', None) or \ _Cfunction('libvlc_audio_set_volume', ((1,), (1,),), None, ctypes.c_int, MediaPlayer, ctypes.c_int) return f(p_mi, i_volume) def libvlc_audio_get_track_count(p_mi): '''Get number of available audio tracks. @param p_mi: media player. @return: the number of available audio tracks (int), or -1 if unavailable. ''' f = _Cfunctions.get('libvlc_audio_get_track_count', None) or \ _Cfunction('libvlc_audio_get_track_count', ((1,),), None, ctypes.c_int, MediaPlayer) return f(p_mi) def libvlc_audio_get_track_description(p_mi): '''Get the description of available audio tracks. @param p_mi: media player. @return: list with description of available audio tracks, or NULL. ''' f = _Cfunctions.get('libvlc_audio_get_track_description', None) or \ _Cfunction('libvlc_audio_get_track_description', ((1,),), None, ctypes.POINTER(TrackDescription), MediaPlayer) return f(p_mi) def libvlc_audio_get_track(p_mi): '''Get current audio track. @param p_mi: media player. @return: the audio track ID or -1 if no active input. ''' f = _Cfunctions.get('libvlc_audio_get_track', None) or \ _Cfunction('libvlc_audio_get_track', ((1,),), None, ctypes.c_int, MediaPlayer) return f(p_mi) def libvlc_audio_set_track(p_mi, i_track): '''Set current audio track. @param p_mi: media player. @param i_track: the track ID (i_id field from track description). @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_audio_set_track', None) or \ _Cfunction('libvlc_audio_set_track', ((1,), (1,),), None, ctypes.c_int, MediaPlayer, ctypes.c_int) return f(p_mi, i_track) def libvlc_audio_get_channel(p_mi): '''Get current audio channel. @param p_mi: media player. @return: the audio channel See libvlc_audio_output_channel_t. ''' f = _Cfunctions.get('libvlc_audio_get_channel', None) or \ _Cfunction('libvlc_audio_get_channel', ((1,),), None, ctypes.c_int, MediaPlayer) return f(p_mi) def libvlc_audio_set_channel(p_mi, channel): '''Set current audio channel. @param p_mi: media player. @param channel: the audio channel, See libvlc_audio_output_channel_t. @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_audio_set_channel', None) or \ _Cfunction('libvlc_audio_set_channel', ((1,), (1,),), None, ctypes.c_int, MediaPlayer, ctypes.c_int) return f(p_mi, channel) def libvlc_audio_get_delay(p_mi): '''Get current audio delay. @param p_mi: media player. @return: the audio delay (microseconds). @version: LibVLC 1.1.1 or later. ''' f = _Cfunctions.get('libvlc_audio_get_delay', None) or \ _Cfunction('libvlc_audio_get_delay', ((1,),), None, ctypes.c_int64, MediaPlayer) return f(p_mi) def libvlc_audio_set_delay(p_mi, i_delay): '''Set current audio delay. The audio delay will be reset to zero each time the media changes. @param p_mi: media player. @param i_delay: the audio delay (microseconds). @return: 0 on success, -1 on error. @version: LibVLC 1.1.1 or later. ''' f = _Cfunctions.get('libvlc_audio_set_delay', None) or \ _Cfunction('libvlc_audio_set_delay', ((1,), (1,),), None, ctypes.c_int, MediaPlayer, ctypes.c_int64) return f(p_mi, i_delay) def libvlc_vlm_release(p_instance): '''Release the vlm instance related to the given L{Instance}. @param p_instance: the instance. ''' f = _Cfunctions.get('libvlc_vlm_release', None) or \ _Cfunction('libvlc_vlm_release', ((1,),), None, None, Instance) return f(p_instance) def libvlc_vlm_add_broadcast(p_instance, psz_name, psz_input, psz_output, i_options, ppsz_options, b_enabled, b_loop): '''Add a broadcast, with one input. @param p_instance: the instance. @param psz_name: the name of the new broadcast. @param psz_input: the input MRL. @param psz_output: the output MRL (the parameter to the "sout" variable). @param i_options: number of additional options. @param ppsz_options: additional options. @param b_enabled: boolean for enabling the new broadcast. @param b_loop: Should this broadcast be played in loop ? @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_add_broadcast', None) or \ _Cfunction('libvlc_vlm_add_broadcast', ((1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int, ListPOINTER(ctypes.c_char_p), ctypes.c_int, ctypes.c_int) return f(p_instance, psz_name, psz_input, psz_output, i_options, ppsz_options, b_enabled, b_loop) def libvlc_vlm_add_vod(p_instance, psz_name, psz_input, i_options, ppsz_options, b_enabled, psz_mux): '''Add a vod, with one input. @param p_instance: the instance. @param psz_name: the name of the new vod media. @param psz_input: the input MRL. @param i_options: number of additional options. @param ppsz_options: additional options. @param b_enabled: boolean for enabling the new vod. @param psz_mux: the muxer of the vod media. @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_add_vod', None) or \ _Cfunction('libvlc_vlm_add_vod', ((1,), (1,), (1,), (1,), (1,), (1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int, ListPOINTER(ctypes.c_char_p), ctypes.c_int, ctypes.c_char_p) return f(p_instance, psz_name, psz_input, i_options, ppsz_options, b_enabled, psz_mux) def libvlc_vlm_del_media(p_instance, psz_name): '''Delete a media (VOD or broadcast). @param p_instance: the instance. @param psz_name: the media to delete. @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_del_media', None) or \ _Cfunction('libvlc_vlm_del_media', ((1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p) return f(p_instance, psz_name) def libvlc_vlm_set_enabled(p_instance, psz_name, b_enabled): '''Enable or disable a media (VOD or broadcast). @param p_instance: the instance. @param psz_name: the media to work on. @param b_enabled: the new status. @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_set_enabled', None) or \ _Cfunction('libvlc_vlm_set_enabled', ((1,), (1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_int) return f(p_instance, psz_name, b_enabled) def libvlc_vlm_set_output(p_instance, psz_name, psz_output): '''Set the output for a media. @param p_instance: the instance. @param psz_name: the media to work on. @param psz_output: the output MRL (the parameter to the "sout" variable). @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_set_output', None) or \ _Cfunction('libvlc_vlm_set_output', ((1,), (1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_char_p) return f(p_instance, psz_name, psz_output) def libvlc_vlm_set_input(p_instance, psz_name, psz_input): '''Set a media's input MRL. This will delete all existing inputs and add the specified one. @param p_instance: the instance. @param psz_name: the media to work on. @param psz_input: the input MRL. @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_set_input', None) or \ _Cfunction('libvlc_vlm_set_input', ((1,), (1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_char_p) return f(p_instance, psz_name, psz_input) def libvlc_vlm_add_input(p_instance, psz_name, psz_input): '''Add a media's input MRL. This will add the specified one. @param p_instance: the instance. @param psz_name: the media to work on. @param psz_input: the input MRL. @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_add_input', None) or \ _Cfunction('libvlc_vlm_add_input', ((1,), (1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_char_p) return f(p_instance, psz_name, psz_input) def libvlc_vlm_set_loop(p_instance, psz_name, b_loop): '''Set a media's loop status. @param p_instance: the instance. @param psz_name: the media to work on. @param b_loop: the new status. @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_set_loop', None) or \ _Cfunction('libvlc_vlm_set_loop', ((1,), (1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_int) return f(p_instance, psz_name, b_loop) def libvlc_vlm_set_mux(p_instance, psz_name, psz_mux): '''Set a media's vod muxer. @param p_instance: the instance. @param psz_name: the media to work on. @param psz_mux: the new muxer. @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_set_mux', None) or \ _Cfunction('libvlc_vlm_set_mux', ((1,), (1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_char_p) return f(p_instance, psz_name, psz_mux) def libvlc_vlm_change_media(p_instance, psz_name, psz_input, psz_output, i_options, ppsz_options, b_enabled, b_loop): '''Edit the parameters of a media. This will delete all existing inputs and add the specified one. @param p_instance: the instance. @param psz_name: the name of the new broadcast. @param psz_input: the input MRL. @param psz_output: the output MRL (the parameter to the "sout" variable). @param i_options: number of additional options. @param ppsz_options: additional options. @param b_enabled: boolean for enabling the new broadcast. @param b_loop: Should this broadcast be played in loop ? @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_change_media', None) or \ _Cfunction('libvlc_vlm_change_media', ((1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int, ListPOINTER(ctypes.c_char_p), ctypes.c_int, ctypes.c_int) return f(p_instance, psz_name, psz_input, psz_output, i_options, ppsz_options, b_enabled, b_loop) def libvlc_vlm_play_media(p_instance, psz_name): '''Play the named broadcast. @param p_instance: the instance. @param psz_name: the name of the broadcast. @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_play_media', None) or \ _Cfunction('libvlc_vlm_play_media', ((1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p) return f(p_instance, psz_name) def libvlc_vlm_stop_media(p_instance, psz_name): '''Stop the named broadcast. @param p_instance: the instance. @param psz_name: the name of the broadcast. @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_stop_media', None) or \ _Cfunction('libvlc_vlm_stop_media', ((1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p) return f(p_instance, psz_name) def libvlc_vlm_pause_media(p_instance, psz_name): '''Pause the named broadcast. @param p_instance: the instance. @param psz_name: the name of the broadcast. @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_pause_media', None) or \ _Cfunction('libvlc_vlm_pause_media', ((1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p) return f(p_instance, psz_name) def libvlc_vlm_seek_media(p_instance, psz_name, f_percentage): '''Seek in the named broadcast. @param p_instance: the instance. @param psz_name: the name of the broadcast. @param f_percentage: the percentage to seek to. @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_seek_media', None) or \ _Cfunction('libvlc_vlm_seek_media', ((1,), (1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_float) return f(p_instance, psz_name, f_percentage) def libvlc_vlm_show_media(p_instance, psz_name): '''Return information about the named media as a JSON string representation. This function is mainly intended for debugging use, if you want programmatic access to the state of a vlm_media_instance_t, please use the corresponding libvlc_vlm_get_media_instance_xxx -functions. Currently there are no such functions available for vlm_media_t though. @param p_instance: the instance. @param psz_name: the name of the media, if the name is an empty string, all media is described. @return: string with information about named media, or NULL on error. ''' f = _Cfunctions.get('libvlc_vlm_show_media', None) or \ _Cfunction('libvlc_vlm_show_media', ((1,), (1,),), string_result, ctypes.c_void_p, Instance, ctypes.c_char_p) return f(p_instance, psz_name) def libvlc_vlm_get_media_instance_position(p_instance, psz_name, i_instance): '''Get vlm_media instance position by name or instance id. @param p_instance: a libvlc instance. @param psz_name: name of vlm media instance. @param i_instance: instance id. @return: position as float or -1. on error. ''' f = _Cfunctions.get('libvlc_vlm_get_media_instance_position', None) or \ _Cfunction('libvlc_vlm_get_media_instance_position', ((1,), (1,), (1,),), None, ctypes.c_float, Instance, ctypes.c_char_p, ctypes.c_int) return f(p_instance, psz_name, i_instance) def libvlc_vlm_get_media_instance_time(p_instance, psz_name, i_instance): '''Get vlm_media instance time by name or instance id. @param p_instance: a libvlc instance. @param psz_name: name of vlm media instance. @param i_instance: instance id. @return: time as integer or -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_get_media_instance_time', None) or \ _Cfunction('libvlc_vlm_get_media_instance_time', ((1,), (1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_int) return f(p_instance, psz_name, i_instance) def libvlc_vlm_get_media_instance_length(p_instance, psz_name, i_instance): '''Get vlm_media instance length by name or instance id. @param p_instance: a libvlc instance. @param psz_name: name of vlm media instance. @param i_instance: instance id. @return: length of media item or -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_get_media_instance_length', None) or \ _Cfunction('libvlc_vlm_get_media_instance_length', ((1,), (1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_int) return f(p_instance, psz_name, i_instance) def libvlc_vlm_get_media_instance_rate(p_instance, psz_name, i_instance): '''Get vlm_media instance playback rate by name or instance id. @param p_instance: a libvlc instance. @param psz_name: name of vlm media instance. @param i_instance: instance id. @return: playback rate or -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_get_media_instance_rate', None) or \ _Cfunction('libvlc_vlm_get_media_instance_rate', ((1,), (1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_int) return f(p_instance, psz_name, i_instance) def libvlc_vlm_get_media_instance_title(p_instance, psz_name, i_instance): '''Get vlm_media instance title number by name or instance id. @param p_instance: a libvlc instance. @param psz_name: name of vlm media instance. @param i_instance: instance id. @return: title as number or -1 on error. @bug: will always return 0. ''' f = _Cfunctions.get('libvlc_vlm_get_media_instance_title', None) or \ _Cfunction('libvlc_vlm_get_media_instance_title', ((1,), (1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_int) return f(p_instance, psz_name, i_instance) def libvlc_vlm_get_media_instance_chapter(p_instance, psz_name, i_instance): '''Get vlm_media instance chapter number by name or instance id. @param p_instance: a libvlc instance. @param psz_name: name of vlm media instance. @param i_instance: instance id. @return: chapter as number or -1 on error. @bug: will always return 0. ''' f = _Cfunctions.get('libvlc_vlm_get_media_instance_chapter', None) or \ _Cfunction('libvlc_vlm_get_media_instance_chapter', ((1,), (1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_int) return f(p_instance, psz_name, i_instance) def libvlc_vlm_get_media_instance_seekable(p_instance, psz_name, i_instance): '''Is libvlc instance seekable ? @param p_instance: a libvlc instance. @param psz_name: name of vlm media instance. @param i_instance: instance id. @return: 1 if seekable, 0 if not, -1 if media does not exist. @bug: will always return 0. ''' f = _Cfunctions.get('libvlc_vlm_get_media_instance_seekable', None) or \ _Cfunction('libvlc_vlm_get_media_instance_seekable', ((1,), (1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_int) return f(p_instance, psz_name, i_instance) def libvlc_vlm_get_event_manager(p_instance): '''Get libvlc_event_manager from a vlm media. The p_event_manager is immutable, so you don't have to hold the lock. @param p_instance: a libvlc instance. @return: libvlc_event_manager. ''' f = _Cfunctions.get('libvlc_vlm_get_event_manager', None) or \ _Cfunction('libvlc_vlm_get_event_manager', ((1,),), class_result(EventManager), ctypes.c_void_p, Instance) return f(p_instance) # 4 function(s) blacklisted: # libvlc_audio_output_get_device_type # libvlc_audio_output_set_device_type # libvlc_printerr # libvlc_set_exit_handler # 17 function(s) not wrapped as methods: # libvlc_audio_output_device_list_release # libvlc_audio_output_list_release # libvlc_clearerr # libvlc_clock # libvlc_errmsg # libvlc_event_type_name # libvlc_free # libvlc_get_changeset # libvlc_get_compiler # libvlc_get_version # libvlc_log_get_context # libvlc_log_get_object # libvlc_media_tracks_release # libvlc_module_description_list_release # libvlc_new # libvlc_track_description_list_release # libvlc_vprinterr # Start of footer.py # # Backward compatibility def callbackmethod(callback): """Now obsolete @callbackmethod decorator.""" return callback # libvlc_free is not present in some versions of libvlc. If it is not # in the library, then emulate it by calling libc.free if not hasattr(dll, 'libvlc_free'): # need to find the free function in the C runtime. This is # platform specific. # For Linux and MacOSX libc_path = find_library('c') if libc_path: libc = ctypes.CDLL(libc_path) libvlc_free = libc.free else: # On win32, it is impossible to guess the proper lib to call # (msvcrt, mingw...). Just ignore the call: it will memleak, # but not prevent to run the application. def libvlc_free(p): pass # ensure argtypes is right, because default type of int won't work # on 64-bit systems libvlc_free.argtypes = [ ctypes.c_void_p ] # Version functions def _dot2int(v): '''(INTERNAL) Convert 'i.i.i[.i]' str to int. ''' t = [int(i) for i in v.split('.')] if len(t) == 3: t.append(0) elif len(t) != 4: raise ValueError('"i.i.i[.i]": %r' % (v,)) if min(t) < 0 or max(t) > 255: raise ValueError('[0..255]: %r' % (v,)) i = t.pop(0) while t: i = (i << 8) + t.pop(0) return i def hex_version(): """Return the version of these bindings in hex or 0 if unavailable. """ try: return _dot2int(__version__.split('-')[-1]) except (NameError, ValueError): return 0 def libvlc_hex_version(): """Return the libvlc version in hex or 0 if unavailable. """ try: return _dot2int(bytes_to_str(libvlc_get_version()).split()[0]) except ValueError: return 0 def debug_callback(event, *args, **kwds): '''Example callback, useful for debugging. ''' l = ['event %s' % (event.type,)] if args: l.extend(map(str, args)) if kwds: l.extend(sorted('%s=%s' % t for t in kwds.items())) print('Debug callback (%s)' % ', '.join(l)) if __name__ == '__main__': try: from msvcrt import getch except ImportError: import termios import tty def getch(): # getchar(), getc(stdin) #PYCHOK flake fd = sys.stdin.fileno() old = termios.tcgetattr(fd) try: tty.setraw(fd) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old) return ch def end_callback(event): print('End of media stream (event %s)' % event.type) sys.exit(0) echo_position = False def pos_callback(event, player): if echo_position: sys.stdout.write('\r%s to %.2f%% (%.2f%%)' % (event.type, event.u.new_position * 100, player.get_position() * 100)) sys.stdout.flush() def print_version(): """Print libvlc version""" try: print('Build date: %s (%#x)' % (build_date, hex_version())) print('LibVLC version: %s (%#x)' % (bytes_to_str(libvlc_get_version()), libvlc_hex_version())) print('LibVLC compiler: %s' % bytes_to_str(libvlc_get_compiler())) if plugin_path: print('Plugin path: %s' % plugin_path) except: print('Error: %s' % sys.exc_info()[1]) if sys.argv[1:] and sys.argv[1] not in ('-h', '--help'): movie = sys.argv[1] # if not os.access(movie, os.R_OK): # print('Error: %s file not readable' % movie) # sys.exit(1) instance = Instance("--sub-source marq") try: media = instance.media_new(movie) except NameError: print('NameError: %s (%s vs LibVLC %s)' % (sys.exc_info()[1], __version__, libvlc_get_version())) sys.exit(1) player = instance.media_player_new() player.set_media(media) player.play() # Some marquee examples. Marquee requires '--sub-source marq' in the # Instance() call above. See <http://www.videolan.org/doc/play-howto/en/ch04.html> player.video_set_marquee_int(VideoMarqueeOption.Enable, 1) player.video_set_marquee_int(VideoMarqueeOption.Size, 24) # pixels player.video_set_marquee_int(VideoMarqueeOption.Position, Position.Bottom) if False: # only one marquee can be specified player.video_set_marquee_int(VideoMarqueeOption.Timeout, 5000) # millisec, 0==forever t = media.get_mrl() # movie else: # update marquee text periodically player.video_set_marquee_int(VideoMarqueeOption.Timeout, 0) # millisec, 0==forever player.video_set_marquee_int(VideoMarqueeOption.Refresh, 1000) # millisec (or sec?) ##t = '$L / $D or $P at $T' t = '%Y-%m-%d %H:%M:%S' player.video_set_marquee_string(VideoMarqueeOption.Text, str_to_bytes(t)) # Some event manager examples. Note, the callback can be any Python # callable and does not need to be decorated. Optionally, specify # any number of positional and/or keyword arguments to be passed # to the callback (in addition to the first one, an Event instance). event_manager = player.event_manager() event_manager.event_attach(EventType.MediaPlayerEndReached, end_callback) event_manager.event_attach(EventType.MediaPlayerPositionChanged, pos_callback, player) def mspf(): """Milliseconds per frame.""" return int(1000 // (player.get_fps() or 25)) def print_info(): """Print information about the media""" try: print_version() media = player.get_media() print('State: %s' % player.get_state()) print('Media: %s' % bytes_to_str(media.get_mrl())) print('Track: %s/%s' % (player.video_get_track(), player.video_get_track_count())) print('Current time: %s/%s' % (player.get_time(), media.get_duration())) print('Position: %s' % player.get_position()) print('FPS: %s (%d ms)' % (player.get_fps(), mspf())) print('Rate: %s' % player.get_rate()) print('Video size: %s' % str(player.video_get_size(0))) # num=0 print('Scale: %s' % player.video_get_scale()) print('Aspect ratio: %s' % player.video_get_aspect_ratio()) #print('Window:' % player.get_hwnd() except Exception: print('Error: %s' % sys.exc_info()[1]) def sec_forward(): """Go forward one sec""" player.set_time(player.get_time() + 1000) def sec_backward(): """Go backward one sec""" player.set_time(player.get_time() - 1000) def frame_forward(): """Go forward one frame""" player.set_time(player.get_time() + mspf()) def frame_backward(): """Go backward one frame""" player.set_time(player.get_time() - mspf()) def print_help(): """Print help""" print('Single-character commands:') for k, m in sorted(keybindings.items()): m = (m.__doc__ or m.__name__).splitlines()[0] print(' %s: %s.' % (k, m.rstrip('.'))) print('0-9: go to that fraction of the movie') def quit_app(): """Stop and exit""" sys.exit(0) def toggle_echo_position(): """Toggle echoing of media position""" global echo_position echo_position = not echo_position keybindings = { ' ': player.pause, '+': sec_forward, '-': sec_backward, '.': frame_forward, ',': frame_backward, 'f': player.toggle_fullscreen, 'i': print_info, 'p': toggle_echo_position, 'q': quit_app, '?': print_help, } print('Press q to quit, ? to get help.%s' % os.linesep) while True: k = getch() print('> %s' % k) if k in keybindings: keybindings[k]() elif k.isdigit(): # jump to fraction of the movie. player.set_position(float('0.'+k)) else: print('Usage: %s <movie_filename>' % sys.argv[0]) print('Once launched, type ? for help.') print('') print_version()
[ "dh@xix.org" ]
dh@xix.org
47512859c702be0adafb042dec3b9966bc0918d6
c9558831ad86603f0efc27b25b05706984a3338e
/add_string.py
06a2f819b52c286e75fcd061816f38d0282e85b7
[]
no_license
ygohil2350/infytq-Python_Fandamentals-
b7c3bcf3cfbfb9041fafe824454329d5ed3ecd96
82d69aecf479ea62139095f74cea56ed6f07989a
refs/heads/main
2023-03-26T04:19:26.405065
2021-03-19T08:01:27
2021-03-19T08:01:27
346,596,252
0
0
null
null
null
null
UTF-8
Python
false
false
260
py
#lex_auth_0127135739583692801137 def add_string(str1): #start writing your code here length = len(str1) if length > 2: if str1[-3:] == 'ing': str1 += 'ly' else: str1 += 'ing' return str1 str1="com" print(add_string(str1))
[ "noreply@github.com" ]
ygohil2350.noreply@github.com
6e0bd2a7b073204b5855fcc552b1b35eba61c4aa
92fa526d5ca2e31f5908f17bb95c529b09ac9995
/Models/venv/bin/easy_install
1bbeee32f98b0e29d87d1b21f5b35ec837e06a94
[]
no_license
KevinLongkk/IFit
55e1f7f872dbdd28e23066c9b96465315061ca2a
438fbdbd63d7cf4059038623e2739fc0a860c26b
refs/heads/master
2020-03-21T02:08:49.538064
2018-06-20T04:53:56
2018-06-20T04:53:56
137,982,728
0
0
null
null
null
null
UTF-8
Python
false
false
427
#!/home/kevin/IFit/Models/venv/bin/python # EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==28.8.0','console_scripts','easy_install' __requires__ = 'setuptools==28.8.0' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit( load_entry_point('setuptools==28.8.0', 'console_scripts', 'easy_install')() )
[ "1247594945@qq.com" ]
1247594945@qq.com
6e5da171791c50723cfa6449c4572065bd55ecb0
96619fa4155335e98670a52fa94cf1ba3402de69
/Spider_Tanks.py
79a9854e2f38ce5744de6e937f9478e0ec9ef230
[]
no_license
Konstlang/Yandex_Pygame_Project
3e57d4b9b88bf8989180105108a5f45729345c45
e347f617042886abe6155af24408533e800b8870
refs/heads/master
2023-03-08T20:35:21.240717
2021-02-25T10:40:18
2021-02-25T10:40:18
342,208,734
0
0
null
null
null
null
UTF-8
Python
false
false
9,276
py
import pygame pygame.init() win = pygame.display.set_mode((500, 480)) pygame.display.set_caption("Spider_Tanks") image_loader = pygame.image.load walkRight = [image_loader('Player_1.0R.png'), image_loader('Player_1.1R.png'), image_loader('Player_1.2R.png'), image_loader('Player_1.3R.png')] walkLeft = [image_loader('Player_1.0L.png'), image_loader('Player_1.1L.png'), image_loader('Player_1.2L.png'), image_loader('Player_1.3L.png')] bg = pygame.image.load('BG.png') fps = 20 clock = pygame.time.Clock() class player(pygame.sprite.Sprite): def __init__(self, x, y, width, height, walkLeft, walkRight): self.x = x self.y = y self.start_pos = (x, y) self.width = width self.height = height self.vel = 9 self.isCollide = False self.isJump = False self.left = False self.right = False self.walkCount = 0 self.y_vel = 0 self.walkLeft = walkLeft self.walkRight = walkRight self.hitbox = (self.x, self.y, 48, 35) self.health = 3 self.wins = 0 self.image = walkLeft[0] self.rect = self.image.get_rect() self.rect.x = self.x self.rect.y = self.y def draw(self, win, level): if self.isJump: self.y_vel -= 1 if self.y <= 20: self.y_vel = -4 for i in level.platform_list: if i.colliderect(self.rect.x, self.rect.y - self.y_vel, self.width, self.height): self.isCollide = True break else: self.isCollide = False if i.colliderect(self.rect.x - self.vel, self.rect.y, self.width, self.height): self.x += 10 if i.colliderect(self.rect.x + self.vel, self.rect.y, self.width, self.height): self.x -= 10 if self.isCollide: if self.y_vel < 0: self.y_vel = 0 self.isJump = False if self.y_vel > 0: self.y_vel = -4 else: self.isJump = True self.y -= self.y_vel if self.walkCount >= fps and not self.isJump: self.walkCount = 0 if self.left and not self.isJump: self.image = self.walkLeft[self.walkCount // (fps // len(walkLeft))] self.walkCount += 1 elif self.right and not self.isJump: self.image = self.walkRight[self.walkCount // (fps // len(walkRight))] self.walkCount += 1 else: if self.right: self.image = self.walkRight[0] else: self.image = self.walkLeft[0] win.blit(self.image, (self.x, self.y)) self.rect = self.image.get_rect() self.rect.x = self.x self.rect.y = self.y self.hitbox = (self.x, self.y, 48, 35) if self.y >= 440 + self.y_vel: self.isJump = False self.y_vel = 0 def hit(self): self.health -= 1 def to_start(self): self.health = 3 self.x = self.start_pos[0] self.y = self.start_pos[1] class Level(): def __init__(self, coords): self.coords = coords self.platform_list = [] self.image = image_loader('Platform.png') for i in self.coords: rect = self.image.get_rect() rect.x = i[0] rect.y = i[1] self.platform_list.append(rect) def draw(self, win): for i in self.platform_list: win.blit(self.image, (i.x, i.y)) class Bullet(object): def __init__(self, x, y, radius, color, facing): self.x = x self.y = y self.radius = radius self.color = color self.facing = facing self.vel = 10 * facing def draw(self, win): pygame.draw.circle(win, self.color, (self.x, self.y), self.radius) def redrawGameWindow(level): win.blit(bg, (0, 0)) player_2.draw(win, level) player_1.draw(win, level) health_bar_1 = font.render(f'Player 1: {player_1.health}', 1, 'yellow') health_bar_2 = font.render(f'Player 2: {player_2.health}', 1, 'blue') rounds_1 = font.render(str(player_1.wins), 1, 'yellow') rounds_2 = font.render(str(player_2.wins), 1, 'blue') dots = font.render(':', 1, 'black') number_1 = font.render('1', 1, 'yellow') number_2 = font.render('2', 1, 'blue') win.blit(health_bar_1, (10, 10)) win.blit(health_bar_2, (370, 10)) win.blit(rounds_1, (220, 10)) win.blit(dots, (240, 10)) win.blit(rounds_2, (260, 10)) win.blit(number_1, (player_1.x + 19, player_1.y - 17)) win.blit(number_2, (player_2.x + 19, player_2.y - 17)) level.draw(win) for bullet in bullets_2: bullet.draw(win) for bullet in bullets_1: bullet.draw(win) pygame.display.update() def change_level(): global current_level global levels global level_count if level_count < 1: level_count += 1 current_level = levels[level_count] else: current_level = levels[0] level_count = 0 player_2.to_start() player_1.to_start() level_count = 0 font = pygame.font.SysFont('comicsans', 30, True, True) run = True player_2 = player(429, 440, 48, 35, walkLeft, walkRight) player_1 = player(21, 440, 48, 35, walkLeft, walkRight) Level_1 = Level(([50, 250], [200, 400], [350, 250], [200, 100])) Level_2 = Level(([70, 400], [200, 250], [330, 400], [70, 100], [330, 100])) levels = [Level_1, Level_2] current_level = Level_1 shootLoop_1 = 0 shootLoop_2 = 0 bullets_2 = [] bullets_1 = [] player_1.right = True player_2.left = True redrawGameWindow(current_level) while run: clock.tick(fps) if shootLoop_1 > 0: shootLoop_1 += 1 if shootLoop_1 > 10: shootLoop_1 = 0 if shootLoop_2 > 0: shootLoop_2 += 1 if shootLoop_2 > 10: shootLoop_2 = 0 for event in pygame.event.get(): if event.type == pygame.QUIT: run = False for bullet in bullets_2: if bullet.y - bullet.radius < player_1.hitbox[1] + player_1.hitbox[3] \ and bullet.y + bullet.radius > player_1.hitbox[1]: if bullet.x + bullet.radius > player_1.hitbox[0] \ and bullet.x - bullet.radius < player_1.hitbox[0] + player_1.hitbox[2]: player_1.hit() bullets_2.pop(bullets_2.index(bullet)) if 500 > bullet.x > 0: bullet.x += bullet.vel else: bullets_2.pop(bullets_2.index(bullet)) for bullet in bullets_1: if bullet.y - bullet.radius < player_2.hitbox[1] + player_2.hitbox[3] \ and bullet.y + bullet.radius > player_2.hitbox[1]: if bullet.x + bullet.radius > player_2.hitbox[0] \ and bullet.x - bullet.radius < player_2.hitbox[0] + player_2.hitbox[2]: player_2.hit() bullets_1.pop(bullets_1.index(bullet)) if 500 > bullet.x > 0: bullet.x += bullet.vel else: bullets_1.pop(bullets_1.index(bullet)) keys = pygame.key.get_pressed() if keys[pygame.K_DOWN] and shootLoop_1 == 0: if player_2.left: facing = -1 else: facing = 1 if len(bullets_2) < 5: bullets_2.append( Bullet(round(player_2.x + (player_2.width // 2 + 7) * facing + 24), round(player_2.y + player_2.height // 2 - 5) , 6, (50, 50, 50), facing)) shootLoop_1 = 1 if keys[pygame.K_LEFT] and player_2.x > player_2.vel: player_2.x -= player_2.vel player_2.left = True player_2.right = False elif keys[pygame.K_RIGHT] and player_2.x < 500 - player_2.width - player_2.vel: player_2.x += player_2.vel player_2.right = True player_2.left = False else: player_2.walkCount = 0 if not player_2.isJump: if keys[pygame.K_UP]: player_2.isJump = True player_2.walkCount = 0 player_2.y_vel = 20 if keys[pygame.K_s] and shootLoop_2 == 0: if player_1.left: facing_2 = -1 else: facing_2 = 1 if len(bullets_1) < 5: bullets_1.append( Bullet(round(player_1.x + (player_1.width // 2 + 7) * facing_2 + 24), round(player_1.y + player_1.height // 2 - 5) , 6, (50, 50, 50), facing_2)) shootLoop_2 = 1 if keys[pygame.K_a] and player_1.x > player_1.vel: player_1.x -= player_1.vel player_1.left = True player_1.right = False elif keys[pygame.K_d] and player_1.x < 500 - player_1.width - player_1.vel: player_1.x += player_1.vel player_1.right = True player_1.left = False else: player_1.walkCount = 0 if not player_1.isJump: if keys[pygame.K_w]: player_1.isJump = True player_1.walkCount = 0 player_1.y_vel = 20 if player_1.health <= 0: player_2.wins += 1 change_level() elif player_2.health <= 0: player_1.wins += 1 change_level() redrawGameWindow(current_level) pygame.quit()
[ "konstlang@gmail.com" ]
konstlang@gmail.com
c74cdcb4343ed06233a14d71ba0593c0f5429b86
ee21ac3f25a719d7bc04c14adf6ccd9d3354f69c
/ninth.py
b93836bbedf68f22f01baf28937d23d1aa07734c
[]
no_license
AnushaSatram/guvi
f145f7535133354b5f1f7735e3bb95ae09a3df09
8f73ba671a9f2bd3ef17f1fd40574f19a71cb62d
refs/heads/master
2020-06-15T00:17:34.065646
2019-07-23T14:46:32
2019-07-23T14:46:32
195,162,159
0
1
null
null
null
null
UTF-8
Python
false
false
161
py
lt=[] nun=int(input()) kin=int(input()) added=0 for a in range(nun): ssm=int(input()) lt.append(ssm) for d in range(0,kin): added=added+lt[d] print(added)
[ "noreply@github.com" ]
AnushaSatram.noreply@github.com
f7ad1f7ae4e202aef51426d06ced0698403c716e
c82b36298061a64b741a6ca93698e90ec430e1df
/Contents/Code/__init__.py
63903c5503007f2ec9d7142202b4d86c048e41c1
[]
no_license
plex-unofficial/Firefly-Media-Server.bundle
d984b9a7f262def5627f42a0d6b7721510492e91
494cb2413486619dbb37849cccbed430c75e1f45
refs/heads/master
2020-03-29T22:43:43.828605
2011-04-19T00:59:07
2011-04-19T00:59:07
1,633,434
0
0
null
null
null
null
UTF-8
Python
false
false
8,245
py
import re, string, os, socket from PMS import * from PMS.Objects import * from PMS.Shortcuts import * REQUIRED_TAGS = { "str":[ "dmap.itemname", "daap.songalbum", "daap.songartist", "daap.songgenre" ], "int":[ "daap.songcompilation", "daap.songdiscnumber", "daap.songsize", "daap.songtime", "daap.songtracknumber", "daap.songyear", "daap.songuserrating" ]} class ArtistItem(XMLObject): def __init__(self, key, artist, thumb=None, **kwargs): XMLObject.__init__(self, key=key, artist=artist, thumb=thumb, **kwargs) self.tagName = "Artist" class AlbumItem(XMLObject): def __init__(self, key, label, album=None, artist=None, genre=None, year=None, **kwargs): XMLObject.__init__(self, key=key, label=label, album=album, artist=artist, genre=genre, year=year, **kwargs) self.tagName = "Album" def Start(): Plugin.AddPrefixHandler("/music/firefly", ServerMenu, "Firefly Media Server", "icon-default.png") Plugin.AddViewGroup("Songs", mediaType="songs", viewMode="Songs") Prefs.Add("pref_host", "text", "0.0.0.0", "Host/IP") Prefs.Add("pref_port", "text", "3689", "Port") MediaContainer.title1 = "Firefly Media Server" MediaContainer.content = "Objects" def ServerMenu(): global ff_host, ff_port, server_name dir = MediaContainer() ff_host = Prefs.Get("pref_host") ff_port = int(Prefs.Get("pref_port")) if ff_host != "0.0.0.0" and isValidHost(ff_host, ff_port): url = "http://%s:%d/server-info?output=xml" % (ff_host, ff_port) server_name = XML.ElementFromURL(url, errors="ignore").xpath("//dmap.itemname")[0].text dir.Append(Function(DirectoryItem(MainMenu, title=server_name))) dir.Append(PrefsItem(title="Preferences")) else: dir.Append(PrefsItem(title="Add a server")) return dir def MainMenu(sender): dir = MediaContainer(title1=server_name) total_songs, total_playlists = Populate() if total_songs: dir.Append(Function(DirectoryItem(GetArtists, title="Artists"))) dir.Append(Function(DirectoryItem(GetAlbums, title="Albums"))) dir.Append(Function(DirectoryItem(GetGenres, title="Genres"))) if total_playlists: dir.Append(Function(DirectoryItem(GetPlaylists, title="Playlists"))) dir.Append(Function(DirectoryItem(GetAlbums, title="Compilations"), title="Compilations", compilations=True)) return dir def isValidHost(host, port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.settimeout(3) s.connect((host, port)) s.shutdown(2) return True except: return False def GetXML(uri, fill=False): url = "http://%s:%d" % (ff_host, ff_port) query = url + uri results = [] for item in XML.ElementFromURL(query, errors='ignore').xpath('//dmap.listingitem'): row = {} for index in item: row[index.tag] = index.text if fill: for field in REQUIRED_TAGS: for tag in REQUIRED_TAGS[field]: if tag not in row: row[tag] = 0 if field == "int" else None results.append(row) return results def Populate(): global song_db, playlist_db song_db = GetXML('/databases/1/items?output=xml&meta=dmap.itemname,dmap.itemid,daap.songalbum,daap.songartist,daap.songcompilation,daap.songdiscnumber,daap.songgenre,daap.songsize,daap.songtime,daap.songtracknumber,daap.songyear,daap.songuserrating', True) playlist_db = GetXML('/databases/1/containers?output=xml') return len(song_db), len(playlist_db) def UniqueList(seq, idfun=None): if idfun is None: def idfun(x): return x seen = {} result = [] for item in seq: marker = idfun(item) if marker in seen: continue seen[marker] = 1 result.append(item) return result def GetArtists(sender, start=None, end=None): dir = MediaContainer(title1=server_name, title2="Artists") artists = [] for index in song_db: if not index['daap.songcompilation']: artists.append(index['daap.songartist']) artists = UniqueList(artists, lambda x: x.lower()) if start is not None and end is not None: artists = artists[start:end] for artist in artists: first_word = artist.split(" ", 2)[0] title = "%s, %s" % (artist[len(first_word) + 1:len(artist)], first_word) if first_word.lower() in ["a", "an", "the"] else artist dir.Append(Function(ArtistItem(GetAlbums, artist=title), title=artist, artist=artist)) del artists dir.Sort("artist") return dir def GetAlbums(sender, title="Albums", artist=None, genre=None, container=1, compilations=False): dir = MediaContainer(title1=server_name, title2=title) albums = [] if container <= 1: for index in song_db: row = None if not compilations: if not index['daap.songcompilation'] and index['daap.songalbum'] is not None: if (genre is None and artist and artist.lower() == index['daap.songartist'].lower()) or \ (artist is None and genre and index['daap.songgenre'] and genre.lower() == index['daap.songgenre'].lower() or \ (artist is None and genre is None)): row = {'daap.songalbum': index['daap.songalbum'], 'daap.songartist': index['daap.songartist'], 'daap.songcompilation': index['daap.songcompilation']} elif index['daap.songalbum'] is not None and index['daap.songcompilation']: row = {'daap.songalbum': index['daap.songalbum'], 'daap.songartist': index['daap.songartist'], 'daap.songcompilation': index['daap.songcompilation']} if row is not None and row not in albums: albums.append(row) else: container_db = GetXML('/databases/1/containers/%d/items?output=xml&meta=dmap.itemname,dmap.itemid,daap.songalbum,daap.songartist,daap.songcompilation,daap.songsize,daap.songtime,daap.songyear' % container, True) for index in container_db: if index['daap.songalbum'] is not None: row = {'daap.songalbum': index['daap.songalbum'], 'daap.songartist': index['daap.songartist'], 'daap.songcompilation': index['daap.songcompilation']} if row not in albums: albums.append(row) del container_db albums = UniqueList(albums, lambda x: x['daap.songalbum'].lower()) # Sorting routine. Hopefully this can be removed when correct AlbumItem hooks are implemented in a future version of Plex. albums = [(x['daap.songalbum'], x) for x in albums] albums.sort() albums = [y for (x,y) in albums] for album in albums: title = "%s - %s" % (album['daap.songalbum'], album['daap.songartist']) if not artist and not album['daap.songcompilation'] else album['daap.songalbum'] dir.Append(Function(AlbumItem(GetSongs, artist=album['daap.songartist'], album=album['daap.songalbum'], year=album['daap.songyear']), album=['daap.songalbum'], artist=album['daap.songartist'])) # dir.Append(Function(DirectoryItem(GetSongs, title=title), album=album['daap.songalbum'], artist=album['daap.songartist'])) del albums return dir def GetPlaylists(sender): dir = MediaContainer(title1=server_name, title2="Playlists") for index in playlist_db: if index['dmap.itemname'] != 'Library': dir.Append(Function(DirectoryItem(GetAlbums, title=index['dmap.itemname']), title=index['dmap.itemname'], container=int(index['dmap.itemid']))) return dir def GetSongs(sender, album, artist=None): dir = MediaContainer(title1=server_name, title2="Songs", viewGroup="Songs") songs = [] for index in song_db: if index['daap.songalbum'] is not None and album.lower() == index['daap.songalbum'].lower() and \ ((artist and artist.lower() == index['daap.songartist'].lower()) or not artist): url = "http://%s:%s/databases/1/items/%d.mp3" % (ff_host, ff_port, int(index['dmap.itemid'])) dir.Append(TrackItem(url, title=index['dmap.itemname'], artist=index['daap.songartist'], album=index['daap.songalbum'], \ index=int(index['daap.songtracknumber']), rating=int(index['daap.songuserrating']), duration=int(index['daap.songtime']), \ size=int(index['daap.songsize']), year=int(index['daap.songyear']), \ sort=int("%d%02d" % (int(index['daap.songdiscnumber']), int(index['daap.songtracknumber']))))) del songs dir.Sort("sort") return dir def GetGenres(sender): dir = MediaContainer(title1=server_name, title2="Genres") genres = [] for index in song_db: if index['daap.songgenre'] and index['daap.songgenre'] not in genres and not index['daap.songcompilation']: genres.append(index['daap.songgenre']) genres.sort() for genre in genres: dir.Append(Function(DirectoryItem(GetAlbums, title=genre), title=genre, genre=genre)) del genres return dir
[ "ryan@Mac-Pro.local" ]
ryan@Mac-Pro.local
6b1970ceea76c3cad3edb8e479f28e5abdca6d09
ef243d91a1826b490e935fa3f3e6c29c3cc547d0
/PyQt5/QtCore/QModelIndex.py
d9b013cff9817d045dc57732ff44a7728aa0723d
[]
no_license
VentiFang/Python_local_module
6b3d0b22399e817057dfd15d647a14bb1e41980e
c44f55379eca2818b29732c2815480ee755ae3fb
refs/heads/master
2020-11-29T11:24:54.932967
2019-12-25T12:57:14
2019-12-25T12:57:14
230,101,875
0
0
null
null
null
null
UTF-8
Python
false
false
3,319
py
# encoding: utf-8 # module PyQt5.QtCore # from F:\Python\Python36\lib\site-packages\PyQt5\QtCore.pyd # by generator 1.147 # no doc # imports import enum as __enum import sip as __sip class QModelIndex(__sip.simplewrapper): """ QModelIndex() QModelIndex(QModelIndex) QModelIndex(QPersistentModelIndex) """ def child(self, p_int, p_int_1): # real signature unknown; restored from __doc__ """ child(self, int, int) -> QModelIndex """ return QModelIndex def column(self): # real signature unknown; restored from __doc__ """ column(self) -> int """ return 0 def data(self, role=None): # real signature unknown; restored from __doc__ """ data(self, role: int = Qt.DisplayRole) -> Any """ pass def flags(self): # real signature unknown; restored from __doc__ """ flags(self) -> Qt.ItemFlags """ pass def internalId(self): # real signature unknown; restored from __doc__ """ internalId(self) -> int """ return 0 def internalPointer(self): # real signature unknown; restored from __doc__ """ internalPointer(self) -> object """ return object() def isValid(self): # real signature unknown; restored from __doc__ """ isValid(self) -> bool """ return False def model(self): # real signature unknown; restored from __doc__ """ model(self) -> QAbstractItemModel """ return QAbstractItemModel def parent(self): # real signature unknown; restored from __doc__ """ parent(self) -> QModelIndex """ return QModelIndex def row(self): # real signature unknown; restored from __doc__ """ row(self) -> int """ return 0 def sibling(self, p_int, p_int_1): # real signature unknown; restored from __doc__ """ sibling(self, int, int) -> QModelIndex """ return QModelIndex def siblingAtColumn(self, p_int): # real signature unknown; restored from __doc__ """ siblingAtColumn(self, int) -> QModelIndex """ return QModelIndex def siblingAtRow(self, p_int): # real signature unknown; restored from __doc__ """ siblingAtRow(self, int) -> QModelIndex """ return QModelIndex def __eq__(self, *args, **kwargs): # real signature unknown """ Return self==value. """ pass def __ge__(self, *args, **kwargs): # real signature unknown """ Return self>=value. """ pass def __gt__(self, *args, **kwargs): # real signature unknown """ Return self>value. """ pass def __hash__(self, *args, **kwargs): # real signature unknown """ Return hash(self). """ pass def __init__(self, *__args): # real signature unknown; restored from __doc__ with multiple overloads pass def __le__(self, *args, **kwargs): # real signature unknown """ Return self<=value. """ pass def __lt__(self, *args, **kwargs): # real signature unknown """ Return self<value. """ pass def __ne__(self, *args, **kwargs): # real signature unknown """ Return self!=value. """ pass __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """list of weak references to the object (if defined)"""
[ "5149528+ventifang@user.noreply.gitee.com" ]
5149528+ventifang@user.noreply.gitee.com
0b5e6a672d8db74b848555e5a59e928e5aa043e3
60da3d5a9c3957ddbaaf481fea19691f87d682b0
/frec/image.py
bb9fbb7a9a1cad9ac45b1b3772cd6d5fb512fec8
[]
no_license
heynemann/frec
59d46740ee86c7f3fc68fe0e0d14d98c043c8a31
bb23732f1c367f4c8167adeeefad93cc153851a2
refs/heads/master
2020-05-16T23:17:42.826305
2012-08-13T13:35:25
2012-08-13T13:35:25
4,644,976
1
0
null
null
null
null
UTF-8
Python
false
false
1,755
py
#!/usr/bin/python # -*- coding: utf-8 -*- # frec face recognition service # https://github.com/heynemann/frec # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2012 Bernardo Heynemann heynemann@gmail.com # code adapted from remotecv's image module # (http://github.com/globocom/remotecv) import cv2 import numpy as np class Image: @classmethod def create_from_buffer(cls, image_buffer): if isinstance(image_buffer, Image): return image_buffer instance = cls() if not instance.is_valid(image_buffer): return None instance.set_image_buffer(image_buffer) return instance @property def size(self): return (self.image.shape[1], self.image.shape[0]) @property def color_channels(self): if len(self.image.shape) > 2: return self.image.shape[2] return 1 def is_valid(self, image_buffer): return len(image_buffer) > 4 and image_buffer[:4] != 'GIF8' def set_image_buffer(self, image_buffer): self.mode = "BGR" buffer_array = np.fromstring(image_buffer, dtype=np.uint8) self.image = cv2.imdecode(buffer_array, 1) def grayscale(self): if len(self.image.shape) == 2: return self convert_mode = getattr(cv2, 'COLOR_%s2GRAY' % self.mode) self.image = cv2.cvtColor(self.image, convert_mode) self.image = cv2.equalizeHist(self.image) return self def resize(self, size): self.image = cv2.resize(self.image, size) return self def to_array(self): return np.array(self.image, dtype=np.uint8) def save(self, path): cv2.imwrite(path, self.image)
[ "heynemann@gmail.com" ]
heynemann@gmail.com
2e0e001960ba1f8f3bb725c5130f182b56c8df7a
2399b7fe82493359d19257b85baac4959214c641
/setup.py
a2ac0c1e05671a90bf95db90b7074e4addfaf3ec
[ "Apache-2.0" ]
permissive
bradder555/easy_arg_parse
80cd4a9ccac34a2491a4782ee02b81e7b38dd2d5
b56c586d8f76f00c0978868e1dba65b2af5e64ae
refs/heads/master
2021-01-11T17:07:34.371016
2017-01-23T12:56:24
2017-01-23T12:56:24
79,727,679
0
1
null
null
null
null
UTF-8
Python
false
false
495
py
from distutils.core import setup setup( name = 'easy_arg_parse', packages = ['easy_arg_parse'], version = '0.1', description = 'Returns a dict of the arguments and values, guesses datatypes', author = 'Bradley Phillips', author_email = 'brad.phillips@exemail.com.au', url = 'https://github.com/bradder555/easy_arg_parse', download_url = 'https://github.com/bradder555/easy_arg_parse/tarball/0.1', keywords = ['arg', 'argument', 'sys.argv'], classifiers = [], )
[ "brad.phillips@exemail.com.au" ]
brad.phillips@exemail.com.au
5d5477fbc6b6ee7ca326ea4d194bceb880852bd8
48ff999aabac44e14fabfc78fd55ebc04b3804ae
/homework8/Action.py
566457c3e6ac422b3859d18ed7d1885c364b8e7d
[]
no_license
stevenacalhoun/ai-homeworks
65907b50f5fdccddef3951c9a14387dce7e764ea
07adf770b5e417d4b20303ea13d58d3507a72fdd
refs/heads/master
2021-03-30T17:28:26.563401
2017-04-18T17:26:32
2017-04-18T17:26:32
78,664,594
0
0
null
null
null
null
UTF-8
Python
false
false
133
py
import sys class Action: actionValue = -1 def __init__(self, value=None): if value != None: self.actionValue = value
[ "stevenacalhoun@gmail.com" ]
stevenacalhoun@gmail.com
1824863c5831b3cc9aea20701a6eb2c9676f3cdc
c8d7c4ba5e949b0af2f5aa234c3ae594b1a49950
/Python接口自动化/GWE_test/common/scripts/parama.py
9745460a9442a29e9a2d5ebc140a385bf346c524
[]
no_license
chase001/chase_learning
00b7396a6775fb6e2fd80950f8acf3f1737b162e
c5ee2473e49923c781212eb3f9f50341c0bc80c8
refs/heads/master
2022-12-12T00:08:08.407671
2020-03-06T14:17:39
2020-03-06T14:17:39
221,268,073
0
0
null
2022-12-08T05:26:49
2019-11-12T16:56:34
Python
UTF-8
Python
false
false
2,985
py
# def bubbleSort(arr): # n = len(arr) # # # 遍历所有数组元素 # for i in range(n): # # # Last i elements are already in place # for j in range(0, n - i - 1): # # if arr[j] > arr[j + 1]: # arr[j], arr[j + 1] = arr[j + 1], arr[j] # # # arr = [64, 34, -20,25, 12, 22, 90,11] # # bubbleSort(arr) # # print("排序后的数组:") # for i in range(len(arr)): # print("%d" % arr[i]) # # 入门,这是装饰器函数,参数 func 是被装饰的函数 # def logger(func): # def wrapper(*args, **kw): # print('主人,我准备开始执行:{} 函数了:'.format(func.__name__)) # # # 真正执行的是这行。 # func(*args, **kw) # # print('主人,我执行完啦。') # return wrapper # # @logger # def add(x, y): # print('{} + {} = {}'.format(x, y, x+y)) # # # add(12142,1245151) # # #带参数的函数装饰器 # def say_hello(contry): # def wrappe(func): # def deco(*args,**kwargs): # if contry =="china": # print("您好,北京.") # if contry == "english": # print("hello paris.") # else: # return print('hello world.') # #真正执行函数的地方 # func(*args,**kwargs) # # return deco # return wrappe # # # 小明,中国人 # @say_hello("china") # def xiaoming(): # pass # # # jack,美国人 # @say_hello("america") # def jack(): # pass # # xiaoming() # #不带参数的类装饰器 # class logger(object): # def __init__(self, func): # self.func = func # # def __call__(self, *args, **kwargs): # print("[INFO]: the function {func}() is running..." # .format(func=self.func.__name__)) # return self.func(*args, **kwargs) # # @logger # def say(something): # print("say {}!".format(something)) # # say("hello") #当前时间 import datetime def now(days= 0, minutes = 0, seconds = 0, format = "%Y-%m-%d %H:%M:%S"): """ 根据传参以当前时间为基准计算前后时间 例如 今天是2019-11-2 00:00:00 delay_time = now(days=1, format="%Y-%m-%d") 此时得到2019-11-3 :return: """ time_result = (datetime.datetime.now()+datetime.timedelta(days=days,minutes=minutes,seconds=seconds)).strftime(format) return time_result #高阶:带参数的类装饰器 class logger(object): def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): print("[INFO]{now}: the function {func}() is running..." .format(now=now(),func=self.func.__name__)) return self.func(*args, **kwargs) # @logger # def paomao(list): # ll = len(list) # for i in range(0,ll): # for m in range(0,ll-i-1): # if list[m] > list[m+1]: # list[m],list[m+1] = list[m+1],list[m] # return list # # a=paomao(list=[1026,99,-22,37,66,102,896,-300]) # print(a)
[ "chenyuliang@globalegrow.com" ]
chenyuliang@globalegrow.com
b3c6a0714eb2f269e604dddc30b6309035ccebe1
dd493bc6b105eec60e07c80cdea2528365dc0600
/scrapers/fantasy_scraper.py
d5e665ce3feacaa538b2515041636dd43f4402ec
[]
no_license
Arhuan/superteam
717cd05f2ccf6468c4395ed670ef81bb3d05c6ff
81ee469146d2a7a005a2a0bf04cca67efe8500a1
refs/heads/master
2022-11-15T12:56:44.988217
2020-06-20T07:00:04
2020-06-20T07:00:04
267,916,055
1
1
null
null
null
null
UTF-8
Python
false
false
3,384
py
import json import pathlib import re from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.chrome.options import Options from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from unidecode import unidecode DRIVER_PATH = "/usr/local/share/chromedriver" fantasy_pages = [ "https://fantasydata.com/nba/fantasy-basketball-leaders?scope=1&season=2019&seasontype=1&conference=1&date=03-11-2020", "https://fantasydata.com/nba/fantasy-basketball-leaders?scope=1&season=2018&seasontype=1&conference=1&date=03-11-2020", "https://fantasydata.com/nba/fantasy-basketball-leaders?scope=1&season=2017&seasontype=1&conference=1&date=03-11-2020", "https://fantasydata.com/nba/fantasy-basketball-leaders?scope=1&season=2016&seasontype=1&conference=1&date=03-11-2020" ] fantasy_filenames = [ "fantasy-2019", "fantasy-2018", "fantasy-2017", "fantasy-2016" ] def get_data(pages, filenames): pathlib.Path("../data").mkdir(parents=True, exist_ok=True) options = Options() driver = webdriver.Chrome(options=options, executable_path=DRIVER_PATH) driver.implicitly_wait(10) try: for i, page in enumerate(pages): with open(f"../data/{fantasy_filenames[i]}.json", "w") as f: driver.get(page) driver.find_element_by_xpath("//a[@ng-click='SetPageSize(300);']").click() wait_for_table_data(driver) hide_popups(driver) load_all_rows(driver) # TODO: bit of a hack, revisit and fix later wait_for_table_data(driver) data = parse_html(driver.page_source) json.dump(data, f) finally: driver.quit() def hide_popups(driver): try: driver.find_element_by_xpath("//button[@class='fs-close-button']").click() except: print("Ad popup not visible") try: driver.find_element_by_xpath("//div[@class='cookieinfo-close']").click() except: print("Cookies popup not visible") def wait_for_table_data(driver): wait = WebDriverWait(driver, 10) wait.until(EC.presence_of_all_elements_located((By.XPATH, "//td"))) def load_all_rows(driver): # TODO: implement a function that checks to see if the table has loaded all possible new data so we can exit earlier for i in range(3): load_more_button = driver.find_element_by_xpath("//div[@ng-app='fantasydata']//a[@ng-hide='LoadingMore']") actions = ActionChains(driver) actions.move_to_element(load_more_button).click(load_more_button).perform() wait_for_table_data(driver) def parse_html(html): soup = BeautifulSoup(html, "html.parser") data = [] rows = soup.select("div[class='k-grid-content-locked'] tbody tr") for row in rows: player = dict() player["rank"] = float(row.select_one("span[ng-bind='dataItem.Rank']").text) player["name"] = re.sub(r"\W+", "", unidecode(row.select_one("a").text)).lower() print(player) data.append(player) return data def main(): get_data(fantasy_pages, fantasy_filenames) if __name__ == "__main__": main()
[ "aaronhuangwork@gmail.com" ]
aaronhuangwork@gmail.com
6caaa6f1a44cbde4d6d152d045b2892ff6b3ffc1
f28cd1e2e8796fbb812be389cd529c6d07833d7d
/vendor/urls.py
0d102f28a5c2a014b1f7a241b7ae1d091606001c
[]
no_license
nn-nagar/Project_management
76f75098bcc50f64b949ad62f0a38c51e96953bb
9e9caf131d99044698d577017ffd777cbbc50301
refs/heads/main
2023-05-12T21:45:31.458093
2021-06-05T14:34:01
2021-06-05T14:34:01
374,134,185
0
0
null
null
null
null
UTF-8
Python
false
false
892
py
"""vendor URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from django.views.generic import RedirectView urlpatterns = [ path('admin/', admin.site.urls), path('', include("budget.urls")), path('', RedirectView.as_view(url='vendor/')), ]
[ "narendra@verificient.com" ]
narendra@verificient.com
66af14b5202dcf4218d2741fd417060f218040aa
0afae00fa81305c0a5a335a524a3b4930a2d3fed
/inheritance 16.py
ad13ade3fabd0bad5bd2acf59fc4faba1ae939f8
[]
no_license
shubham22121998/python-oop
a116926e1a2b7b51d1b267e569fea642191ed0e9
9ddc1a23a84b1908d8fa3741b0dba1aaa3c0f424
refs/heads/master
2023-03-15T06:28:07.299469
2021-03-12T12:56:21
2021-03-12T12:56:21
347,065,846
0
0
null
null
null
null
UTF-8
Python
false
false
359
py
#single inheritance class phone: def __init__(self,brand,price,color): self.brand=brand self.price=price self.color=color def buy(self): print("customer by the phone") def return_phone(self): print("customer return the phone") class smart_phone(phone): pass s=smart_phone("appel",12000,"red") s.buy()
[ "shubhammorchhale204@gmail.com" ]
shubhammorchhale204@gmail.com
51237d14d1b60dd28aeb3adaef135d6a6afe2e83
a31695feb0cfd97610829510693c9c8759a845d7
/src/extract_forenames.py
2be56aeb5f8ee3026b664d9ca967e90a518297bd
[]
no_license
jsnajder/socmwe
79474149a7f6c82d8d262089515d224360695bdd
5ee594a1951e1d2ac460b7735ccc5c03221943b8
refs/heads/master
2021-01-20T19:05:56.516662
2016-08-24T06:17:18
2016-08-24T06:17:18
63,913,201
0
0
null
null
null
null
UTF-8
Python
false
false
741
py
import sys import codecs def main(): fname = sys.argv[1] f = codecs.open(fname, encoding='utf8') d = {} for line in f: try: xs = line.split('\t') userid = xs[1] names = [s for s in xs[2].rstrip().split() if s.isalpha()] if len(names) <= 1 or len(names[0]) < 3: continue if userid not in d: d[userid] = set() d[userid].add(names[0].lower()) except: continue for userid, forenames in d.iteritems(): sys.stdout.write(('%s\t%s\n' % (userid, ' '.join(forenames))).encode('utf-8')) # sys.stdout.write(('%s\t%s\n' % (userid, forenames)).encode('utf-8')) if __name__ == "__main__": main()
[ "jan.snajder@fer.hr" ]
jan.snajder@fer.hr
0d8116be768c9d283aefa13c43d45fd131abb114
f71d67025b732e66e1a37c02c05392c3dd116d65
/vol/vol.0-3/vol_00/a059.py
7cf7b5e872d7c000f66f5664150d9f7b44424573
[]
no_license
clarinet758/aoj
2829f92137dd1a93734445e1e92513f8e3e0b5c0
21787ffee1a6dd60c717d7b880b63107187e4710
refs/heads/main
2023-06-25T12:04:40.127040
2023-06-19T16:36:38
2023-06-19T16:36:38
34,978,951
0
0
null
null
null
null
UTF-8
Python
false
false
836
py
#!/usr/bin/env python # -*- coding: UTF-8 -*- import time import sys import io import re import math import itertools import collections #sys.stdin=file('input.txt') #sys.stdout=file('output.txt','w') #10**9+7 mod=1000000007 #mod=1777777777 pi=3.141592653589 xy=[(1,0),(-1,0),(0,1),(0,-1)] bs=[(-1,-1),(-1,1),(1,1),(1,-1)] def gcd(a,b): return a if b==0 else gcd(b,a%b) def lcm(a,b): return a*b/gcd(a,b) def choco(xa,ya,xb,yb,xc,yc,xd,yd): return 1 if abs((yb-ya)*(yd-yc)+(xb-xa)*(xd-xc))<1.e-10 else 0 #memo roiti 886942 while 1: try: xa,ya,xb,yb,xc,yc,xd,yd=map(float,raw_input().split()) print 'NO' if (xd<xa or xb<xc or yd<ya or yb<yc) else 'YES' except: break exit() n=int(raw_input()) n,k=map(int,raw_input().split()) l=map(int,raw_input().split()) ans=chk=0 #end = time.clock() #print end - start
[ "clarinet758@gmail.com" ]
clarinet758@gmail.com
8bb6e6857e69710a41987e95615c5c3e4ef53fa8
008ffa5d2f7f519ef27bd53ec3003cf9170aa40a
/src/tools/utils.py
445f66da0d80e82068bce67722b0fc4342a6fa68
[ "BSD-3-Clause" ]
permissive
oist-cnru/VCBot
ada50b7b1cd77f83842d5e9551af8ec723f0c0f0
52edc41244659a4175e537575b3c4434da441998
refs/heads/master
2023-02-15T06:43:50.033259
2021-01-14T21:06:34
2021-01-14T21:06:34
276,042,234
2
0
null
null
null
null
UTF-8
Python
false
false
22,836
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ BSD 3-Clause License Copyright (c) 2020 Okinawa Institute of Science and Technology (OIST). All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Willow Garage, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Author: Hendry F. Chame <hendryfchame@gmail.com> Publication: Chame, H. F., Ahmadi, A., & Tani, J. (2020). A hybrid human-neurorobotics approach to primary intersubjectivity via active inference. Frontiers in psychology, 11. Okinawa Institute of Science and Technology Graduate University (OIST) Cognitive Neurorobotics Research Unit (CNRU) 1919-1, Tancha, Onna, Kunigami District, Okinawa 904-0495, Japan """ import os import time import shutil import numpy as np from datetime import datetime import csv from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA import pandas as pd import parse class Utils(): def __init__(self, _pwd): self.pwd = _pwd self.modelFilePrefix = "properties_" self.trainingFileName = 'training.txt' self.modelFileSufix = ".d" self.datasetFileName = "dataset.d" self.experimentFileName = "experiment.d" self.primFilePrefix = "primitive_" self.primFileSufix = ".csv" self.delimiter = ',' self.modelKeys = ['datapath',\ 'modelpath', 'network', 'robot', 'activejoints', 'nsamples', 'w1', 'w', 'd', 'z', 't', 'epochs', 'alpha', 'beta1', 'beta2', 'shuffle', 'retrain', 'greedy', 'dsoft', 'sigma'] self.datasetKeys = ['samplingperiod',\ 'numbertimes', 'numberprims'] self.experimentKeys = ['datetime',\ 'model', 'dataset', 'numbertimes', 'samplingperiod', 'primitiveid', 'windowSize', 'w', 'postdiction', 'epochs', 'alpha', 'beta1', 'beta2', 'motorcompliance'] self.experimentExportKeys = ['cur_pos',\ 'tgt_pos', 'hum_pos', 'hum_int', 'states', 'elbo'] def pcaFromList(self,_Xs, _nComp=2): nComp = _nComp lColumns = [] for c in range(1, nComp+1): lColumns.append("PC{}".format(c)) VZ = np.vstack(_Xs) AllHidden_std = StandardScaler().fit_transform(VZ) pca = PCA(n_components=nComp) pcaAnalysis = pca.fit_transform(AllHidden_std) principalDf = pd.DataFrame(data = pcaAnalysis, columns = lColumns) pcs = principalDf.loc[:,lColumns]; pcsArrayZ = np.array(pcs); return pcsArrayZ def pcaFromDatabase(self,_Xs, _XdbPath, _nComp=2): sizeBuffer = [] v_list = [] for x in _Xs: sizeBuffer.append(x.shape) v_list.append(x) for p in _XdbPath: v = np.load(p) sizeBuffer.append(v.shape) v_list.append(v); nComp = _nComp lColumns = [] for c in range(1, nComp+1): lColumns.append("PC{}".format(c)) VZ = np.vstack(v_list) AllHidden_std = StandardScaler().fit_transform(VZ) pca = PCA(n_components=nComp) pcaAnalysis = pca.fit_transform(AllHidden_std) principalDf = pd.DataFrame(data = pcaAnalysis, columns = lColumns) pcs = principalDf.loc[:,lColumns]; pcsArrayZ = np.array(pcs); X = [] idx = 0 for i in range(len(_Xs)): X.append(pcsArrayZ[idx:sizeBuffer[i][0],:]) idx += sizeBuffer[i][0] return X, sizeBuffer def parseTrainingData(self,_fname): fname = _fname + '/' + self.trainingFileName if not self.fileExists(fname): return None list_train_data = [] try: format_string = 'Epoch [{}] - Time [{}ms] - RE_Q [{}] - RE_P [{}] - Regulation [{}] - loss [{}]' with open(fname) as f: for line in f: parsed = parse.parse(format_string, line) if not parsed == None: l_par = [] for i in range (6): l_par.append(float(parsed[i])) list_train_data.append(np.array(l_par)) except IOError: print("IOError file \'{}\'".format(_fname)) if len(list_train_data) > 0 : return np.vstack(list_train_data) return None def trimString(self, _str, _sep=' '): str_strip = _str.strip().split(_sep) str_rem = '' for s in str_strip: str_rem = str_rem + s return str_rem def getModelList(self,_dir): mList = [] try: model_list = os.listdir(_dir) format_string = 'properties_{}.d' if len(model_list) > 0: for s in model_list: parsed = parse.parse(format_string, s) if not parsed == None: mList.append(parsed[0]) except IOError: print("IOError dir \'{}\'".format(_dir)) return None return mList def parseModel(self,_fname): m = self.modelFactory() li = 0 fullName = self.pwd + '/' + _fname if not self.fileExists(fullName.replace('/',os.sep)): print('The model \'{}\' no longer exists !'.format(_fname.split('/')[-1])) return None try: with open(_fname) as f: for line in f: if '#' in line or len(line) <= 1: continue k = self.modelKeys[li] i = len(k)+1 if (line[:i]) == k + '=': m[k] = line[i:-1] li = li + 1 if li < len(self.modelKeys): m = None else: m['name'] = m['modelpath'].split(os.sep)[-1] m['dsname'] = m['datapath'].split(os.sep)[-1] m['nlayers'] = len(m['d'].split(self.delimiter)) prevTrain = self.parseTrainingData(m['modelpath']) m['train'] = not prevTrain is None except IOError: print("IOError file \'{}\'".format(_fname)) m = None except: print("Something went wrong with the file \'{}\'".format(_fname)) m = None return m def getCurrentTimeMS(self): return int(round(time.time() * 1000)) def modelPathString(self,_bDir, _cName): return _bDir + '/' + self.modelFilePrefix + _cName + self.modelFileSufix def fileExists(self,_fname): return os.path.isfile(_fname) def modelFactory(self): m = {} for k in self.modelKeys: m[k] = '' # default initialization m['activejoints'] = '1' + self.delimiter+ '1' + self.delimiter + '0' m['dsoft'] = '10' m['sigma'] = '0.2' m['beta1'] = '0.9' m['beta2'] = '0.999' m['alpha'] = '0.001' m['retrain'] = 'false' m['greedy'] = 'false' m['name'] = '' m['dsname'] = '' m['train'] = False m['robot'] = 'cartesian' m['shuffle'] = 'false' return m def saveModel(self,_fname, _m, _new=True): data = '' mPath= _m['modelpath'] if _new: _m['datapath'] = self.pwd + os.sep + _m['datapath'] for k in self.modelKeys: data = data + k + '=' + _m[k] + os.linesep try: f = open(_fname,"w") f.write(data) f.close() if not self.isDir(mPath): self.createDir(mPath) return True except IOError: print("IOError file \'{}\'".format(_fname)) return False def datasetFactory(self): d = {} for k in self.datasetKeys: d[k] = '' # default initialization d['name'] = '' d['data'] = [] d['samplingpriod'] = '100' d['numbertimes'] = '0' d['numberprims'] = '0' return d def getDirList(self,_dir): dList = [] try: dList = os.listdir(_dir+"/.") except IOError: print("IOError dir \'{}\'".format(_dir)) return None return dList def parseDataset(self,_fname): d = self.datasetFactory() li = 0 fname = _fname + '/' + self.datasetFileName fullName = self.pwd + '/' + fname if not self.fileExists(fullName.replace('/',os.sep)): print('The dataset \'{}\' no longer exists !'.format(_fname.split('/')[-1])) return None try: with open(fname) as f: for line in f: if '#' in line or len(line) <= 1: continue k = self.datasetKeys[li] i = len(k)+1 if (line[:i]) == k + '=': d[k] = line[i:-1] li = li + 1 if li < len(self.datasetKeys): d = None else: d['name'] = _fname.split('/')[-1] pList = [] for i in range(int(d['numberprims'])): pfname = '{}/{}{}_0{}'.format(_fname, self.primFilePrefix, i, self.primFileSufix) vDat = self.readData(pfname, _delimiter=self.delimiter) pList.append(vDat) d['data'] = pList except IOError: print("IOError file \'{}\'".format(fname)) d = None except: print("Something went wrong with the file \'{}\'".format(fname)) d = None return d def datasetPathString(self,_bDir, _cName): return _bDir + '/' + self.datasetFilePrefix + _cName + self.datasetFileSufix def saveDataset(self,_dir, _d): flag = True dsName = _d['name'] dsDir = _dir + '/' + dsName if not self.isDir('./'+dsDir): flag = self.createDir(dsDir) else: #clear previous files for f in os.listdir(dsDir): self.removeFile(f) data = '' for k in self.datasetKeys: data = data + k + '=' + _d[k] + os.linesep try: fName = dsDir + '/' + self.datasetFileName f = open(fName,"w") f.write(data) f.close() dList = _d['data'] for i in range(len(dList)): pName = '{}/{}{}_0{}'.format(dsDir, self.primFilePrefix, i, self.primFileSufix) self.saveData(pName, dList[i]) except IOError: self.removeDir(dsDir) print("IOError file \'{}\'".format(dsName)) flag = False return flag def saveExperiment(self,_dir, _e): flag = True exDir = '' try: now = datetime.now() dt_string = now.strftime("date[%Y_%m_%d]_time[%H_%M_%S]") exDir = _dir + '/' + dt_string if self.createDir(exDir): data = '' _e['datetime']=dt_string for k in self.experimentKeys: data = data + k + '=' + _e[k] + os.linesep fName = exDir + '/' + self.experimentFileName f = open(fName,"w") f.write(data) f.close() np.save(exDir + '/cur_pos.npy', _e['cur_pos']) np.save(exDir + '/tgt_pos.npy', _e['tgt_pos']) np.save(exDir + '/hum_pos.npy', _e['hum_pos']) np.save(exDir + '/hum_int.npy', _e['hum_int']) np.save(exDir + '/states.npy', _e['states']) np.save(exDir + '/elbo.npy', _e['elbo']) else: flag = False except IOError: self.removeDir(exDir) print("IOError file \'{}\'".format(exDir)) flag = False return flag def parseExperiment(self,_path): e_ = {} li = 0 fname = _path + '/' + self.experimentFileName #print(fname) try: with open(fname) as f: for line in f: if '#' in line or len(line) <= 1: continue k = self.experimentKeys[li] i = len(k)+1 if (line[:i]) == k + '=': e_[k] = line[i:-1] li = li + 1 if li < len(self.experimentKeys): e_ = None else: e_['cur_pos'] = np.load(_path + '/cur_pos.npy') e_['tgt_pos'] = np.load(_path + '/tgt_pos.npy') e_['hum_pos'] = np.load(_path + '/hum_pos.npy') e_['hum_int'] = np.load(_path + '/hum_int.npy') e_['states'] = np.load(_path + '/states.npy') e_['elbo'] = np.load(_path + '/elbo.npy') except IOError: print("IOError dir \'{}\'".format(_path)) return None return e_ def exportExperimentCsv(self,_expPath, _savePath): if not self.isDir(_savePath): return False e_ = self.parseExperiment(_expPath) if not e_ is None: for k in self.experimentExportKeys: if not self.saveData(_savePath + '/{}.csv'.format(k), e_[k]): return False else: return False return True def datasetExists(self, _dir, _dname): return self.isDir('./'+ _dir + '/' + _dname) def removeFile(self,_fname): try: if self.fileExists(_fname): os.remove(_fname) return True except IOError: print("IOError file \'{}\'".format(_fname)) return False def isDir(self,_dir): return os.path.isdir(_dir) def createDir(self,_dir): flag = True try: if not self.isDir(_dir): os.mkdir(_dir) except OSError: print ("Dir \'%s\' creation failed" % _dir) flag = False return flag def removeDir(self,_dir): flag = True try: if self.isDir(_dir): shutil.rmtree(_dir) except IOError: print("IOError dir \'{}\'".format(_dir)) flag = False return flag def removeDataset(self,_cDir): return self.removeDir(_cDir) def saveData(self,_fname, _X): flag = True try: with open(_fname, 'w') as writeFile: writer = csv.writer(writeFile, delimiter=self.delimiter) for i in range(_X.shape[0]): line = [] x_i = _X[i,:] for j in range(_X.shape[1]): line.append(str(x_i[j])) writer.writerow(line) writeFile.close() except IOError: flag = False print("IOError file \'{}\'".format(_fname)) return flag def parseString(self, _string, _dtype='float', _delim=' '): list_ = [] try: if (_dtype=='float'): list_ = [float(i) for i in _string.split(_delim)] elif (_dtype=='bool'): list_ = [bool(i) for i in _string.split(_delim)] elif (_dtype=='int'): list_ = [int(i) for i in _string.split(_delim)] else: print("Error unknown data type \'{}\' for parsing".format(_dtype)) except ValueError: print("Cannot parse string=\'{}\', dtype=\'{}\', delimiter=\'{}\'!".format(_string,_dtype, _delim)) return list_ def readData(self,_fname, _type="float", _delimiter=' '): def toFloat(_v): return float(_v) def toBool(_v): return _v == "1" try: ifile = open(_fname, "r") reader = csv.reader(ifile, delimiter=_delimiter) data = [] func = toFloat if _type == "bool": func = toBool for row in reader: coord = [] for col in row: coord.append(func(col)) data.append(coord) ifile.close() X = np.array(data) return X except IOError: print("IOError file \'{}\'".format(_fname)) return None def str2Int(self, _str): i = None try: i = int(_str) except ValueError: print("ValueError converting to int \'{}\'".format(_str)) return i def readDataRobust(self,_fname, _type="float", _delimiter=' '): def toFloat(_v): return float(_v) def toBool(_v): return _v == "1" try: ifile = open(_fname, "r") reader = csv.reader(ifile, delimiter=_delimiter) data = [] func = toFloat if _type == "bool": func = toBool count = 0 for row in reader: if count == 0: count = 1 continue coord = [] for col in row: try: coord.append(func(col)) except ValueError: pass # print('NaN') #coord.append(float(col)) data.append(coord) ifile.close() X = np.array(data) return X except IOError: print("IOError file \'{}\'".format(_fname)) return None
[ "hendryf@gmail.com" ]
hendryf@gmail.com
9703d7734b6c8cfc45c33b04bbc7ced4d80f58da
926621c29eb55046f9f59750db09bdb24ed3078e
/lib/surface/meta/render_markdown.py
a3a1b3c9051c98b815672f60f889d20ccfcdd062
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
bopopescu/SDK
525d9b29fb2e901aa79697c9dcdf5ddd852859ab
e6d9aaee2456f706d1d86e8ec2a41d146e33550d
refs/heads/master
2022-11-22T18:24:13.464605
2016-05-18T16:53:30
2016-05-18T16:53:30
282,322,505
0
0
NOASSERTION
2020-07-24T21:52:25
2020-07-24T21:52:24
null
UTF-8
Python
false
false
1,267
py
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A command that generates all DevSite and manpage documents.""" import sys from googlecloudsdk.calliope import base from googlecloudsdk.core.document_renderers import render_document class GenerateHelpDocs(base.Command): """Uses gcloud's markdown renderer to render the given markdown file.""" @staticmethod def Args(parser): parser.add_argument( 'md_file', help='The path to a file containing markdown to render.') parser.add_argument( '--style', default='text', help='The output format of the renderer.') def Run(self, args): with open(args.md_file, 'r') as f: render_document.RenderDocument(args.style, f, sys.stdout)
[ "richarddewalhalla@gmail.com" ]
richarddewalhalla@gmail.com
4cd4265cad19035feb5bf220096223233b1d0b58
ddb6e57f89baecd33eaf5313c8d6f83f64408097
/test.py
3f1ab868ab1602bd40ec28868d6541031f528881
[]
no_license
handesome/OPENCV
f182eef21e8da89a9ff206f454a959d634358411
f5bb5dd08f039e9794dcc38cf6fcafe8fdada964
refs/heads/main
2023-01-31T17:19:30.364424
2020-12-20T02:36:30
2020-12-20T02:36:30
322,884,011
2
0
null
null
null
null
UTF-8
Python
false
false
1,759
py
""" opencv 基础入门 """ # 1. 环境搭配 ## win10 + python3.5/3.6 + opencv3.3/或者更高 + pycharm2017 ## pip install opencv-python ## pip install openc-contrib_python ## pip install pytesseract # 2. 课程内容与目标 ## opencv 图像读写模块 ## opencv 图像处理模块 ## opencv 各种编程技巧 ## 有用案例 ## Tesseract-OCR + opencv ## 解决项目中实际问题 # 创建窗口, 窗口可以调整大小, 但是标签改成cv2.WINDOW_NORMAL,也可调整窗口大小。 # 当图像维度太大, 或者要添加轨迹条时,调整窗口大小将会很有用 # cv.namedWindow("Crystal Liu") # cv.destroyAllWindows() # 关闭所有窗口 # cv2.waitKey() 是一个键盘绑定函数。需要指出的是它的时间尺度是毫 秒级。 # 函数等待特定的几毫秒,看是否有键盘输入。 # 特定的几毫秒之内,如果 按下任意键,这个函数会返回按键的 ASCII 码值,程序将会继续运行。 # 如果没 有键盘输入,返回值为 -1,如果我们设置这个函数的参数为 0,那它将会无限 期的等待键盘输入。 # 它也可以被用来检测特定键是否被按下, # cv2.destroyAllWindows() 可以轻易删除任何我们建立的窗口。 # 如果 你想删除特定的窗口可以使用 cv2.destroyWindow(),在括号内输入你想删 除的窗口名。 import cv2 as cv def test(): # src = cv.imread(r"images/lena.jpg") # 读入图片放进src中 src = cv.imread("../images/lena.jpg") cv.imshow("Crystal", src) # 将src图片放入该创建的窗口中 cv.waitKey(1000) # 等有键输入或者1000ms后自动将窗口消除,0表示只用键输入结束窗口 if __name__ == '__main__': test()
[ "noreply@github.com" ]
handesome.noreply@github.com
ab7705221dcf015493c4a0f3bf3914fb49bfe4e6
9399332ae342cb445f1d627857f6a729852dc2e6
/stockExperiments/instances.py
aea7cb51c549f15a4cbe7ebe2d2b3e97580e36fa
[]
no_license
rhlobo/stockExperiments
9fd2eb711f24152a3433d760d33603c7c8d9ac31
dc39f5ac10c31f43162520bb9d8aa58225dfed02
refs/heads/master
2022-11-18T05:16:16.644617
2013-09-24T12:23:56
2013-09-24T12:23:56
5,346,188
4
2
null
2022-11-04T19:05:35
2012-08-08T19:14:02
Python
UTF-8
Python
false
false
96
py
# -*- coding: utf-8 -*- import bigtempo.core data_engine = bigtempo.core.DatasourceEngine()
[ "rhlobo+github@gmail.com" ]
rhlobo+github@gmail.com
e7c5a6940023090081ef2337e06aa152c7e3d894
8cfef2c907b332f4b9442702d8b5d057929275b6
/gen-readme.py
4bf7f09052f10bf4a5e6e157d8835f8141406e71
[ "CC-BY-4.0" ]
permissive
CipherHe/MarineHydromaster
da77506981b9474717d73a7811cd4ed922c194e1
f97e2f03cf8652919eff4f144e4d5921d88288f8
refs/heads/master
2020-12-24T15:05:35.137102
2015-05-09T16:35:48
2015-05-09T16:35:48
35,335,816
1
1
null
null
null
null
UTF-8
Python
false
false
1,433
py
#!/usr/bin/env python2 from glob import glob from urllib import quote import re header = ''' ## Aerodynamics-Hydrodynamics with Python "Aerodynamics-Hydrodynamics" (MAE 6226) is taught at the George Washington University by Prof. Lorena Barba for the first time in Spring 2014. These IPython Notebooks are being prepared for this class, with assistance from Barba-group PhD student Olivier Mesnard. The materials are distributed publicly and openly under a Creative Commons Attribution license, [CC-BY 4.0](https://creativecommons.org/licenses/by/4.0/) ### List of notebooks: ''' format_item = '* [{name}]({url})'.format bb_url = 'github.com/barbagroup/AeroPython/blob/master/{}'.format def notebooks(): return glob('lessons/*.ipynb') def lesson_id(filename): return int(re.search('[0-9]+', filename).group()) def lesson_name(filename): return filename.split('/')[1].split('.')[0].split('_')[2] def nb_url(filename): raw_url = bb_url(quote(quote(filename))) return 'http://nbviewer.ipython.org/urls/{}'.format(raw_url) def write_readme(nblist, fo): fo.write('{}\n'.format(header)) for nb in nblist: name = lesson_name(nb) url = nb_url(nb) fo.write('{}\n'.format(format_item(name=name, url=url))) def main(): nblist = sorted(notebooks(), key=lesson_id) with open('README.md', 'w') as fo: write_readme(nblist, fo) if __name__ == '__main__': main()
[ "he_huimin@yahoo.com" ]
he_huimin@yahoo.com
35226f445ccc9b98390bbababafb794059653a52
79e66cea6612693d7a8e67aae6379d241e12bf4d
/basic/mimic.py
4814a5368cf2a1f9d623fbf335bf551e7f517bd9
[ "Apache-2.0" ]
permissive
floresgfelipeal/google-python-course
ec42de1cea061f73f30b3a1e4946234724742702
a8f681b6c40030f4e67f4b29d67b3d25832186f8
refs/heads/master
2020-07-19T12:39:31.008451
2019-09-05T02:24:30
2019-09-05T02:24:30
206,450,023
0
0
null
null
null
null
UTF-8
Python
false
false
2,684
py
#!/usr/bin/python -tt # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ """Mimic pyquick exercise -- optional extra exercise. Google's Python Class Read in the file specified on the command line. Do a simple split() on whitespace to obtain all the words in the file. Rather than read the file line by line, it's easier to read it into one giant string and split it once. Build a "mimic" dict that maps each word that appears in the file to a list of all the words that immediately follow that word in the file. The list of words can be be in any order and should include duplicates. So for example the key "and" might have the list ["then", "best", "then", "after", ...] listing all the words which came after "and" in the text. We'll say that the empty string is what comes before the first word in the file. With the mimic dict, it's fairly easy to emit random text that mimics the original. Print a word, then look up what words might come next and pick one at random as the next work. Use the empty string as the first word to prime things. If we ever get stuck with a word that is not in the dict, go back to the empty string to keep things moving. Note: the standard python module 'random' includes a random.choice(list) method which picks a random element from a non-empty list. For fun, feed your program to itself as input. Could work on getting it to put in linebreaks around 70 columns, so the output looks better. """ import random import sys def mimic_dict(filename): f = open(filename, 'r') s = f.read() words = s.split() dict = {} prev = '' for w in words: if not prev in dict: dict[prev] = [w] else: dict[prev].append(w) prev = w return dict def build_mimic(mimic_dict, mimic_str, word, w_count): if w_count < 200: list_next = mimic_dict.get(word) new_str = word if w_count == 0 else mimic_str + ' ' + word if not list_next: return build_mimic(mimic_dict, new_str, random.choice(mimic_dict.get('')), w_count + 1) else: return build_mimic(mimic_dict, new_str, random.choice(list_next), w_count + 1) else: return mimic_str def print_mimic(mimic_dict, word): print(build_mimic(mimic_dict, '', word, 0)) # Provided main(), calls mimic_dict() and mimic() def main(): if len(sys.argv) != 2: print('usage: ./mimic.py file-to-read') sys.exit(1) dict = mimic_dict(sys.argv[1]) print_mimic(dict, '') if __name__ == '__main__': main()
[ "floresgfelipeal@gmail.com" ]
floresgfelipeal@gmail.com
994933abafed5a041b46978eb87f6ccb992ed10b
066e0b1e42f9e3c898f16b3f0cac401fd0f59b2a
/bye.py
1a6f5468159e1f1e7ce108ca62100219bd0749e7
[]
no_license
alexkassil/CircuitSimulator
98d2a1b3e9344b2e901c271b11c401f64b16a1c0
95c27a20154d36fac381a4f551d1404444eb1aa1
refs/heads/master
2021-08-30T19:57:21.734175
2017-12-19T07:41:19
2017-12-19T07:41:19
110,922,020
0
0
null
null
null
null
UTF-8
Python
false
false
3,403
py
def bye(): print(""" _ _ _ _ _____ _____ | | | | /\ | \ | || __ \ / ____| | |__| | / \ | \| || | | || (___ | __ | / /\ \ | . ` || | | | \___ \ | | | | / ____ \ | |\ || |__| | ____) | |_| |_|/_/ \_\|_| \_||_____/ |_____/ ____ _ _ / __ \ | \ | | | | | || \| | | | | || . ` | | |__| || |\ | \____/ |_| \_| _____ _____ _____ _______ _____ _____ _ | __ \ | __ \ /\ / ____||__ __||_ _|/ ____| /\ | | | |__) || |__) | / \ | | | | | | | | / \ | | | ___/ | _ / / /\ \ | | | | | | | | / /\ \ | | | | | | \ \ / ____ \| |____ | | _| |_| |____ / ____ \ | |____ |_| |_| \_\/_/ \_\\\_____| |_| |_____|\_____|/_/ \_\|______| ______ _ ______ _____ _______ _____ ____ _ _ _____ _____ _____ | ____|| | | ____|/ ____||__ __|| __ \ / __ \ | \ | ||_ _|/ ____| / ____| | |__ | | | |__ | | | | | |__) || | | || \| | | | | | | (___ | __| | | | __| | | | | | _ / | | | || . ` | | | | | \___ \ | |____ | |____ | |____| |____ | | | | \ \ | |__| || |\ | _| |_| |____ ____) | |______||______||______|\_____| |_| |_| \_\ \____/ |_| \_||_____|\_____||_____/ ______ _ _ ___ ___ __ ______ | ____|/\ | | | | |__ \ / _ \/_ ||____ | | |__ / \ | | | | ) || | | || | / / | __|/ /\ \ | | | | / / | | | || | / / | | / ____ \ | |____ | |____ / /_ | |_| || | / / |_| /_/ \_\|______||______| |____| \___/ |_| /_/ _ ______ __ __ _____ _ _ ____ ______ _ _ /\ | | | ____|\ \ / / _ | __ \ | | | || _ \ | ____|| \ | | / \ | | | |__ \ V / _| |_ | |__) || | | || |_) || |__ | \| | / /\ \ | | | __| > < |_ _| | _ / | | | || _ < | __| | . ` | / ____ \ | |____ | |____ / . \ |_| | | \ \ | |__| || |_) || |____ | |\ | /_/ \_\|______||______|/_/ \_\ |_| \_\ \____/ |____/ |______||_| \_| """) print()
[ "alexkassil@sbcglobal.net" ]
alexkassil@sbcglobal.net
420bc1b632fdf987b0488093fe043140f0cdea5f
46629ff6f29ff095ce42a3ff943f664055cb571e
/desafio91.py
a6b9c552e221bddbcd34d76a99b59f6afce1b6dd
[]
no_license
alex-gsantos/cursos_em_video
4640defb2a4467d0a76c09c62cc32354f14dd9be
7dbd75300c66789239d51d6f063a06ed28c11f0f
refs/heads/main
2023-06-23T11:11:57.627219
2021-07-09T19:13:59
2021-07-09T19:13:59
384,485,497
0
0
null
null
null
null
UTF-8
Python
false
false
1,609
py
''' Crie um programa onde 4 jogadores joguem um dado e tenham resultados aleatórios. Guarde esses resultados em um dicionario. No final, coloque esse dicionario em ordem, sabendo que o vencedor tirou o maior numero no dado. ''' import random lista = {} l_nome = list() l_num = list() n1 = 0 while n1 < 4: aux = random.randint(1, 6) l_nome.append(f'Jogador {n1}') l_num.append(aux) n1 += 1 lista = {'Nome:': l_nome, 'Dado:': l_num} print(lista) ''' n1 = 0 while n1 < 3: n2 = 0 aux1 = l_num[n2] nom1 = l_nome[n2] aux2 = l_num[n2 + 1] nom2 = l_nome[n2 + 1] if aux1 > aux2: while aux1 > aux2: l_num.append(aux1) l_num.remove(aux1) l_nome.append(nom1) l_nome.remove(nom1) n2 += 1 n1 += 1 lista = {'Nome:': l_nome, 'Dado:': l_num} print(lista) n1 = 0 n2 = 0 while n1 < 4: print(f'Nome: {lista["Nome:"][n1]}') print(f'Dado: {lista["Dado:"][n1]}') n1 += 1 #l_nome.clear() #l_num.clear() l_num_aux = l_num[:] l_nome_aux = list() n1 = 0 while n1 < 4: n2 = 0 aux1 = l_num[n1] aux2 = l_num_aux[n2] while n2 < 4: if aux1 > aux2: aux3 = aux2 l_num_aux[n2] = aux1 l_num_aux[n1] = aux3 n2 += 1 n1 += 1 print(l_num) #fazer uma lista ao contrário, onde os números tem um conteúdo, que é os Jogadores. #sortear de modo reverso os números print(l_nome) print(l_num) print(lista) lista = {'Jogador': l_nomes, 'Numero': } '''
[ "noreply@github.com" ]
alex-gsantos.noreply@github.com
ee5cf6ef026fe9f008bc6c85ef2e4492318ef9b4
2cc051c804f8b46c9e376de2f213c8721dd6c5bf
/eventlog/ext/feeds/instagram.py
4c707923ca28d96172d022559e48d107dd8457b0
[]
no_license
stevebirk/eventlog
96e665e1b5f882e57c24a1d9a58d6400fe3cd0b1
719a99133aabc4727ac810eb9d6988f48a965aeb
refs/heads/master
2021-06-18T18:03:57.532733
2021-03-04T02:46:35
2021-03-04T02:46:35
30,161,205
1
0
null
null
null
null
UTF-8
Python
false
false
1,541
py
import datetime from eventlog.lib.feeds import Feed from eventlog.lib.events import Event, Fields class Instagram(Feed): def __init__(self, config, **kwargs): Feed.__init__(self, config, **kwargs) self.url = 'https://api.instagram.com/v1/users/self/media/recent' # OAuth self._CLIENT_ID = self.config['oauth2_client_id'] self._CLIENT_SECRET = self.config['oauth2_client_secret'] self._ACCESS_TOKEN = self.config['oauth2_access_token'] def to_event(self, raw): e = Event() e.feed = self.dict() if raw['caption']: e.title = raw['caption']['text'] e.link = raw["images"]["standard_resolution"]["url"] e.occurred = datetime.datetime.utcfromtimestamp( float(raw['created_time']) ) e.thumbnail_url = e.link e.original_url = e.link e.raw = raw return e def _make_url(self, next_max_id=None): url = self.url + ("?access_token=%s" % (self._ACCESS_TOKEN)) if next_max_id: url += ("&max_id=%s" % (str(next_max_id))) return url def init_parse_params(self, **kwargs): return self._make_url(), None def parse(self, data): events = [self.to_event(photo) for photo in data['data']] next_max_id = data['pagination'].get('next_max_id') next_url = None next_headers = None if next_max_id: next_url = self._make_url(next_max_id) return events, next_url, next_headers
[ "stevebirk@gmail.com" ]
stevebirk@gmail.com
a25416f90ae3e05a24d5a1875ddb153609080649
d7eb6761760ad1a11e617d68d1b06de48c20744d
/bot.py
c4cf198789ebd3b89acad972dec641bc0a4a4cd1
[ "MIT" ]
permissive
Timidger/AutoWikiaBot
32b30a5bed5744a5965627a15a95fab8a9ec3cbd
0117afc509817be0e134851120cd9aa12f8b053b
refs/heads/master
2021-01-16T17:46:09.758094
2015-03-28T04:50:26
2015-03-28T04:50:26
31,488,820
0
0
null
null
null
null
UTF-8
Python
false
false
2,468
py
#! /usr/bin/env python3 import sys import praw import utils from wikia import wikia BOT = praw.Reddit("autowikiabot by /u/timidger at /r/autowikiabot") BOT.login("autowikiabot", "I lke JSON") # The sub reddit that the bot scans on, usually /r/all SUB_REDDIT = str(sys.argv[1]) # The template for the main header of the post, which contains the tile & url POST_HEADER = "\n".join(("#####&#009;", "######&#009;", "####&#009;", "[**{title}**]({link}):\n", "---\n")) # The basic footer of a post, which contain info about the bot POST_FOOTER = ("\n\n---\n" "^(Parent commenter can) [^toggle ^NSFW](http://www.np.reddit.com/message/" "compose?to=autowikiabot&subject=AutoWikibot NSFW toggle&message=%2Btoggle-" "nsfw+cj4ck5b) ^or [^delete](http://www.np.reddit.com/message/compos" "e?to=autowikiabot&subject=AutoWikibot Deletion&message=%2Bdelete+cj4ck5b)" "^(. Will also delete on comment score of -1 or less. |) [^(FAQs)]" "(http://www.np.reddit.com/r/autowikiabot/wiki/index) ^| [^Source](https:/" "/github.com/Timidger/autowikiabot-py)") def make_reply(page): """Constructs a reply summary using the given page""" header = POST_HEADER.format(title=page.title, link=page.url) # Get the basic body body = utils.summarize(page) # Make the first occurence of the title bolded body = body.replace(page.title, "__" + page.title + "__", 1) # Add the quote tags around everything (including each paragraph) body = ">\n" + body.replace("\n", "\n>") return header + body + POST_FOOTER if __name__ == "__main__": while True: try: for post in praw.helpers.comment_stream(BOT, SUB_REDDIT, verbosity=0): # Search for a wikia link in the post link = utils.find_link(post.body) if not link or "wikia.com" not in link: continue # Get the sub-wikia and article name sub_wikia = utils.find_sub_wikia(link) article = utils.find_article(link) # Construct the page using that data page = wikia.page(sub_wikia, article) # Get the summary of the page to post reply = make_reply(page) print("Replied with {} from {}".format(page.title, page.sub_wikia).encode("ascii", "ignore")) post.reply(reply) except Exception as e: print("ERROR: ", e)
[ "APragmaticPlace@gmail.com" ]
APragmaticPlace@gmail.com
36ff1c0007eda9541b243ff82e0b44688245125d
e6bbb4b0930c7d5fa28de6562e8f881ec1715129
/Problem Set 3/inverse_function.py
09d8d53690ab0aa663fd1b267a8041ca02fc9990
[]
no_license
LanQikun/Udacity-CS212
1ed2170eca8f6ade7d38f778265d67828bccdb1e
e5340f7c5e079155209414ea80b8de07abbce6f3
refs/heads/master
2021-06-07T06:45:00.870435
2021-02-02T10:32:17
2021-02-02T10:32:17
147,186,775
0
0
null
null
null
null
UTF-8
Python
false
false
2,101
py
# -------------- # User Instructions # # Write a function, inverse, which takes as input a monotonically # increasing (always increasing) function that is defined on the # non-negative numbers. The runtime of your program should be # proportional to the LOGARITHM of the input. You may want to # do some research into binary search and Newton's method to # help you out. # # This function should return another function which computes the # inverse of the input function. # # Your inverse function should also take an optional parameter, # delta, as input so that the computed value of the inverse will # be within delta of the true value. # ------------- # Grading Notes # # Your function will be called with three test cases. The # input numbers will be large enough that your submission # will only terminate in the allotted time if it is # efficient enough. def slow_inverse(f, delta=1 / 128.): """Given a function y = f(x) that is a monotonically increasing function on non-negatve numbers, return the function x = f_1(y) that is an approximate inverse, picking the closest value to the inverse, within delta.""" def f_1(y): x = 0 while f(x) < y: x += delta # Now x is too big, x-delta is too small; pick the closest to y return x if (f(x) - y < y - f(x - delta)) else x - delta return f_1 def inverse(f, delta=1 / 128.): """Given a function y = f(x) that is a monotonically increasing function on non-negatve numbers, return the function x = f_1(y) that is an approximate inverse, picking the closest value to the inverse, within delta.""" def f_1(y): x = delta while f(x) < y: x *= 2 low = x / 2 high = x ok = (y - delta, y + delta) while True: mid = (low + high) / 2 if f(mid) <= ok[0]: low = mid elif f(mid) >= ok[1]: high = mid else: return mid return f_1 def square(x): return x * x sqrt = slow_inverse(square) print (sqrt(1000000000))
[ "lanqikun@hotmai.com" ]
lanqikun@hotmai.com
8044405df35b03963cce1ff6f1ecad088d23825b
f82a567e59c16319d3282d162b052426dbe79b47
/yahootest/1.py
5a0db0307ae9291265f585450584fd44433bdd20
[]
no_license
mk668a/python_aoj
c399191c8f3f514590983e50e09680626841114a
a8394ee9f9fe8d80272209665afa5898fec921fd
refs/heads/master
2020-06-09T23:37:32.957497
2020-01-28T11:47:48
2020-01-28T11:47:48
193,528,013
0
0
null
null
null
null
UTF-8
Python
false
false
115
py
A = list(map(int, input().split())) B = [] for a in A: if a != 0 and a not in B: B.append(a) print(*B)
[ "msftoaa@gmail.com" ]
msftoaa@gmail.com
bb6967f42e912a205b3fa4e6acc87a4de0e7e700
aae7b8484ef985a5b56feb28a9715cc8b2dde826
/app/urls.py
7e05ef62fb7493d513f833364b42cda9a7b30b85
[]
no_license
paligit/django
fa48cebcab60d119f632ca5d68d7037039d99484
cbd6b25d7bbfa5df40519ff2c37ebf01a52ce931
refs/heads/master
2016-09-06T11:26:50.754028
2015-03-25T22:01:47
2015-03-25T22:01:47
32,892,882
0
0
null
null
null
null
UTF-8
Python
false
false
663
py
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns( url (r'^$/','app.views.crear',name="crearArticulo"), #url (r'^ventas/$','app.views.crear',name='crear'), # Examples: # url(r'^$', 'ventas.views.home', name='home'), # url(r'^ventas/', include('ventas.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), )
[ "pablo@debian.debian" ]
pablo@debian.debian
65335f45499cb075ed3818997d7b956fd726a8bf
b5169b07690f58741639ccafb1f2782c9e0bdb10
/Flask-RestPlus/app.py
929b51724d7e547fd9405944d0592981e8f51e65
[]
no_license
akeyi2018/FlaskStudy
d5b2085a9be8f524fb409648bc5165a60bdf1705
cc78a6167277c3dbefad6a144f3e75cc365f5d40
refs/heads/master
2023-07-10T01:34:40.564013
2023-06-27T09:19:48
2023-06-27T09:19:48
249,384,132
0
1
null
2023-05-01T22:15:38
2020-03-23T09:13:53
Python
UTF-8
Python
false
false
568
py
from flask import Flask, jsonify from flask_restx import Api, Resource, fields, model app = Flask(__name__) api = Api(app) a_language = api.model('Language', {'language' : fields.String('The language.')}) languages = [] python = {'language': 'Python'} languages.append(python) @app.route('/language') class Language(Resource): def get(self): return 'OK',200 @api.expect(a_language) def post(self): languages.append(api.payload) return {'result' : 'Language added'}, 201 if __name__ == '__main__': app.run(debug=True)
[ "akeyi2016@gmail.com" ]
akeyi2016@gmail.com
b9ef7a029f6dea3d4b4c85f87f8a68e71e3d9096
45ea532e3f3457cd3f5e1b3203287c07238157e9
/util/writer_util.py
af9bca69635912758edbcb552d0a392baa30ff93
[ "MIT" ]
permissive
EccRiley/DynamicPlacementGenerator
7f0e2f04eb418c3bf7ba997631be1aa59d2c7847
60c0e3f1892c702ae46db78a89ff5e64f472a1b7
refs/heads/master
2022-04-18T01:27:39.062874
2020-04-16T18:41:23
2020-04-16T18:41:23
260,022,209
1
0
MIT
2020-04-29T19:24:35
2020-04-29T19:24:35
null
UTF-8
Python
false
false
1,049
py
import csv def export_all_possible_removal_situations(engine_subtype, all_possible_removal_situations): with open(filepath, 'w') as file: writer = csv.writer(file) rows_to_write = [] for row in all_possible_removal_situations: rows_to_write.append(row) writer.writerows(rows_to_write) def export_all_possible_states(all_states): with open('data_to_read/all_possible_states.csv', 'w') as file: writer = csv.writer(file) rows_to_write = [] for num_engines, states in all_states.items(): for state in states: row_to_write = [num_engines] row_to_write.extend(state) rows_to_write.append(row_to_write) writer.writerows(rows_to_write) def export_all_possible_actions(num, all_actions): with open('data_to_read/' + str(num) + '_engines_all_possible_actions.csv', 'w') as file: writer = csv.writer(file) rows_to_write = [] for action in all_actions: row_to_write = [] for row in action: for i in row: row_to_write.append(i) rows_to_write.append(row_to_write) writer.writerows(rows_to_write)
[ "meredithmurfin@gmail.com" ]
meredithmurfin@gmail.com
61c97ccfb5080fc8c5285ff5fbfafae1b4b5d6e3
f1265dfe151d65fe0cc99159bc9db8e57785cc95
/devel/lib/python2.7/dist-packages/vrep_common/__init__.py
c95e2b0d85475339e97012f922e3e2dc0fca0c15
[]
no_license
rodrigogarces/catkin_ws
5679e0bcd88f0920409c989ea75b5a174b270e5e
df570450d57bfeb579495d1bb94837df2e72e150
refs/heads/master
2020-05-16T08:35:03.899207
2019-01-22T16:28:02
2019-01-22T16:28:02
null
0
0
null
null
null
null
UTF-8
Python
false
false
102
py
/home/raphael/catkin_ws/devel/.private/vrep_common/lib/python2.7/dist-packages/vrep_common/__init__.py
[ "raphaelgoms@gmail.com" ]
raphaelgoms@gmail.com
b36e16cd6bee314d0c10f4c19ce3272dbad7f47a
3908a4e4cc597c1a1b4f6d9740c0b1af2e3f8af0
/mine/models.py
517fb81307b5d16889108906a5e0da5843520699
[]
no_license
0xE232FE/ogamebot-1
317bc2e431ac8974f2752aa69ee1390d299a8b30
8aa8b06244977fdb486509c44cd15da2a1677b10
refs/heads/master
2020-09-17T22:26:34.079851
2019-06-26T16:00:50
2019-06-26T16:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
770
py
# Create your models here. from django.db import models from planet.models import Planet class Mine(models.Model): planet = models.ForeignKey(Planet, related_name='mines', on_delete=models.CASCADE) level = models.IntegerField(default=0) upgradeable = models.BooleanField(default=False) name = models.CharField(default="", max_length=24) def __str__(self): return self.name class MetalMine(Mine): Mine.name = "MetalMine" class CrystalMine(Mine): Mine.name = "CrystalMine" class DeuteriumMine(Mine): Mine.name = "DeuteriumMine" class SolarPowerstation(Mine): Mine.name = "SolarPowerstation" class FusionReactor(Mine): Mine.name = "FusionReactor" class SolarSatellite(Mine): Mine.name = "SolarSatellite"
[ "vinh-ngu@hotmail.com" ]
vinh-ngu@hotmail.com
45ff54197bd2efca8b935fafc218b7c4a05a96f2
4f40b4ac50117892c2466afdaad774eb685a00e9
/ApachelogsAnalyser.py
d15c93faf23a512b7414527c3f8f20b9265097e2
[]
no_license
PIR-Botnet/LogAnalysis
a83b9057a3faf837b255b4cb15337ba20c8f790d
9b7eaf6903580f1599c6221e3a3aed4d2e9e8719
refs/heads/master
2020-12-25T13:44:33.105614
2016-06-25T00:00:51
2016-06-25T00:00:51
61,878,264
0
0
null
null
null
null
UTF-8
Python
false
false
10,886
py
import time import re import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator import pylab as pl import datetime class Apache(object): filename = 'final.log' botmasterResource = ['/abc','/cca','/bac/acb/abc/?abc=2','/cba/abc/abc/?bca=0','/presentations/','/blog','/twitter/login/botmaster'] botIP = [] totalBotNumber = 0 botDictionary = {} botActivity = {} totalActivity = {} bots = [] botsactivity = [] botsNumberIn30Minutes = {} botsNumber = [] def analysis(self): linedata = [] with open(self.filename) as file: for line in file: linedata = line.split(' ') ip = linedata[0] str1 = re.split('[[:/]',linedata[3]) temps = str1[3] + '-' + str(self.getMonth(str1[2])).zfill(2) + '-' + str1[1] + ' ' + str1[4] + ':' minute = int(str1[5]) temps = self.getTemps(temps,minute) temps = time.mktime(time.strptime(temps,'%Y-%m-%d %H:%M')) if (temps in self.totalActivity): self.totalActivity[temps] += 1 else: self.totalActivity[temps] = 1 if (ip in self.botIP): str1 = re.split('[[:/]',linedata[3]) temps = str1[3] + '-' + str(self.getMonth(str1[2])).zfill(2) + '-' + str1[1] + ' ' + str1[4] + ':' minute = int(str1[5]) temps = self.getTemps(temps,minute) temps = time.mktime(time.strptime(temps,'%Y-%m-%d %H:%M')) if (temps in self.botActivity): self.botActivity[temps] += 1 else: self.botActivity[temps] = 1 try: if (self.rightResource(linedata[6]) and ip not in self.botIP): self.totalBotNumber += 1 self.botIP.append(ip) self.botIP.append(linedata[0]) str1 = re.split('[[:/]',linedata[3]) temps = str1[3]+ '-' + str(self.getMonth(str1[2])).zfill(2)+ '-'+ str1[1]+ ' ' +str1[4]+':' minute = int(str1[5]) temps = self.getTemps(temps,minute) temps = time.mktime(time.strptime(temps,'%Y-%m-%d %H:%M')) if (temps in self.botDictionary): self.botDictionary[temps] += 1 else: self.botDictionary[temps] = 1 if (temps in self.botActivity): self.botActivity[temps] += 1 else: self.botActivity[temps] = 1 except IndexError: continue if (ip in self.botIP): str1 = re.split('[[:/]',linedata[3]) temps = str1[3]+ '-' + str(self.getMonth(str1[2])).zfill(2)+ '-'+ str1[1]+ ' ' +str1[4]+':' minute = int(str1[5]) temps30Minutes = self.getTemps30Minutes(temps,minute) temps30Minutes = time.mktime(time.strptime(temps30Minutes,'%Y-%m-%d %H:%M')) if (temps30Minutes not in self.botsNumberIn30Minutes): self.botsNumberIn30Minutes[temps30Minutes] = [] if(ip not in self.botsNumberIn30Minutes[temps30Minutes]): self.botsNumberIn30Minutes[temps30Minutes].append(ip) print ("total bots number = ",self.totalBotNumber) lastnum = 0 firstStamp = sorted(self.botDictionary.keys())[0] lastStamp = sorted(self.botDictionary.keys())[-1] stamp = firstStamp while(stamp <= lastStamp): if stamp not in self.botDictionary: self.botDictionary[stamp] = 0 stamp = time.strftime('%Y-%m-%d %H:%M',time.localtime(stamp)) stamp = datetime.datetime.strptime(stamp,'%Y-%m-%d %H:%M') stamp += datetime.timedelta(minutes = 5) stamp = time.mktime(stamp.timetuple()) firstStamp = sorted(self.botActivity.keys())[0] lastStamp = sorted(self.botActivity.keys())[-1] stamp = firstStamp while(stamp <= lastStamp): if stamp not in self.botActivity: self.botActivity[stamp] = 0 if stamp not in self.totalActivity: self.totalActivity[stamp] = 0 #print (self.botActivity[stamp]) stamp = time.strftime('%Y-%m-%d %H:%M',time.localtime(stamp)) stamp = datetime.datetime.strptime(stamp,'%Y-%m-%d %H:%M') stamp += datetime.timedelta(minutes = 5) stamp = time.mktime(stamp.timetuple()) firstStamp = sorted(self.botsNumberIn30Minutes.keys())[0] lastStamp = sorted(self.botsNumberIn30Minutes.keys())[-1] stamp = firstStamp while(stamp <= lastStamp): if stamp not in self.botsNumberIn30Minutes: self.botsNumberIn30Minutes[stamp] = [] stamp = time.strftime('%Y-%m-%d %H:%M',time.localtime(stamp)) stamp = datetime.datetime.strptime(stamp,'%Y-%m-%d %H:%M') stamp += datetime.timedelta(minutes = 30) stamp = time.mktime(stamp.timetuple()) timelist = [] anothertimelist = [] justanothertimelist = [] for k in sorted(self.botDictionary.keys()): self.botDictionary[k] += lastnum timelist.append(time.strftime('%Y-%m-%d %H:%M',time.localtime(k))) print (time.strftime('%Y-%m-%d %H:%M',time.localtime(k))+'------ %d' % self.botDictionary[k]) lastnum = self.botDictionary[k] self.bots.append(self.botDictionary[k]) for k in sorted(self.botActivity.keys()): justanothertimelist.append(time.strftime('%Y-%m-%d %H:%M',time.localtime(k))) print (time.strftime('%Y-%m-%d %H:%M',time.localtime(k))+'------Activities------ %d' % self.botActivity[k]) self.botsactivity.append(self.botActivity[k]) for k in sorted(self.botsNumberIn30Minutes.keys()): anothertimelist.append(time.strftime('%Y-%m-%d %H:%M',time.localtime(k))) print (time.strftime('%Y-%m-%d %H:%M',time.localtime(k))+'------30minutes------ %d' % len(self.botsNumberIn30Minutes[k])) self.botsNumber.append(len(self.botsNumberIn30Minutes[k])) totalactivity = [] for k in sorted(self.totalActivity.keys()): totalactivity.append(self.totalActivity[k]) #print (self.botActivity[sorted(self.botActivity.keys())[-2]]) x1 = [] x2 = [] x3 = [] #print(justanothertimelist) for stringTime in timelist: x1.append(datetime.datetime.strptime(stringTime, "%Y-%m-%d %H:%M")) for stringTime in anothertimelist: x2.append(datetime.datetime.strptime(stringTime, "%Y-%m-%d %H:%M")) for stringTime in justanothertimelist: x3.append(datetime.datetime.strptime(stringTime, "%Y-%m-%d %H:%M")) self.paint(self.bots,self.botsactivity,self.botsNumber,totalactivity,timelist,anothertimelist,x1,x2,x3) def rightResource(self,string): for resource in self.botmasterResource: if (string.startswith(resource)): return True return False def getTemps(self,temps,minute): if(minute < 5): temps += '00' elif(minute <10): temps += '05' elif(minute <15): temps += '10' elif(minute <20): temps += '15' elif(minute <25): temps += '20' elif(minute <30): temps += '25' elif(minute <35): temps += '30' elif(minute <40): temps += '35' elif(minute <45): temps += '40' elif(minute <50): temps += '45' elif(minute <55): temps += '50' else: temps += '55' return temps def getTemps30Minutes(self,temps,minute): if(minute <= 30): temps += '00' else: temps += '30' return temps def getMonth(self,monthstr): months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] if (monthstr in months): month = months.index(monthstr) + 1 else: month = 0 return month def paint(self,bots,botsactivity,botsNumber,totalactivity,temps,temps30minutes,x1,x2,x3): plt.figure('number of bots') plt.xlabel(u'time/5minute') plt.ylabel(u'number of bots') plt.plot(x1,bots) plt.gcf().autofmt_xdate() plt.figure('number of bots activity') plt.xlabel(u'time/5minute') plt.ylabel(u'number of bot activities') plt.plot(x3,totalactivity,label = "total activity") plt.plot(x3,botsactivity,label = "bot activity") plt.gcf().autofmt_xdate() pl.legend() plt.figure('number of bots within 30 minutes') plt.xlabel(u'time/30minute') plt.ylabel(u'number of bots within 30 minutes') plt.plot(x2,botsNumber) plt.gcf().autofmt_xdate() plt.show() if __name__ == '__main__': apache = Apache() apache.analysis() #尽量真实地模拟出一个apache日志,每个bot和非bot独立运行 #30分钟的图像横坐标以时间输出 ''' presentation: 更多的讲讲自己干了啥 用了什么语言 python,怎么做的 代码流程用流程图简要描述一遍,bot和notBot的行为方式 流程给你用summary,log,simulation,analyse,result,amelioration 概率分布的介绍 注意时间,这次用了12分钟 server anaysis? 更详细的标题 botnet log 流量分析。。。 --------------------- propo: 逻辑连贯 client 和 bot分开 log 加在twitter 上 介绍log format 太长了 botmaster和bot在twitter上做了什么 说明我知道bot怎么运行 simulation更靠后 analyse 然后 evaluation 概率分布 删除总bot数量 概率分布曲线和traffic一起,证明我detect bien 30000bots + 所有人整个projet的conclusion '''
[ "noreply@github.com" ]
PIR-Botnet.noreply@github.com
aff051d98734021f3f4523d83bf58848091ad511
53fab060fa262e5d5026e0807d93c75fb81e67b9
/gaussiana/ch3_2020_03_02_19_40_45_184657.py
388976c4229562ed4c3f1e6b54c6758644c0ce7d
[]
no_license
gabriellaec/desoft-analise-exercicios
b77c6999424c5ce7e44086a12589a0ad43d6adca
01940ab0897aa6005764fc220b900e4d6161d36b
refs/heads/main
2023-01-31T17:19:42.050628
2020-12-16T05:21:31
2020-12-16T05:21:31
306,735,108
0
0
null
null
null
null
UTF-8
Python
false
false
164
py
import math def calcula_gaussiana(x,mi,sigma): parte1 = 1 / (sigma * 2 * math.pi ** 1/2) parte2 = math.exp(-0.5*((x-mi)/sigma)**2) return parte1*parte2
[ "you@example.com" ]
you@example.com
efca18ab1d7c9619edf492d0475c54151b784848
2497210cc7e914be160450d8e00ce102820b1bc2
/sdpy/calibrate_map_scans.py
4566cde43ec6eb9a89c91d5822a25486d5112787
[]
no_license
adamginsburg/sdpy
a67640f17d76e09d6854e560c990bd0863c9a9cd
193ab2cb38741f088addc3952ae46b7591f92e60
refs/heads/master
2021-01-21T08:51:43.658918
2015-02-13T07:40:54
2015-02-13T07:40:54
29,185,295
0
0
null
2015-01-13T10:41:13
2015-01-13T10:41:13
null
UTF-8
Python
false
false
19,127
py
import astropy.io.fits as pyfits import numpy as np import warnings from .timer import print_timing def load_data_file(filename, extension=1, dataarr=None, filepyfits=None, datapfits=None): """ Load the series of spectra from a raw SDFITS file """ if filepyfits is not None: datapyfits = filepyfits[extension].data else: try: print "Treating file as an open FITS HDU... ", datapyfits = filename[extension].data except AttributeError: print "File is not an HDU. Reading file from disk using pyfits...", if isinstance(filename,str): filepyfits = pyfits.open(filename,memmap=True) datapyfits = filepyfits[extension].data else: print "Assuming file is a FITS BinaryTableHDU" datapyfits = filename if dataarr is None: dataarr = datapyfits['DATA'] print "Data successfully read" namelist = datapyfits.names data = datapyfits # Don't do this any more; reads whole thing into memory #if dataarr.sum() == 0 or dataarr[-1,:].sum() == 0: # print "Reading file using pfits because pyfits didn't read any values!" # import pfits # if datapfits is not None: # data = datapfits # else: # data = pfits.FITS(filename).get_hdus()[1].get_data() # dataarr = np.reshape(data['DATA'],data['DATA'].shape[::-1]) # namelist = data.keys() return data, dataarr, namelist, filepyfits @print_timing def calibrate_cube_data(filename, outfilename, scanrange=[], sourcename=None, feednum=1, sampler=0, return_data=False, datapfits=None, dataarr=None, clobber=True, tau=0.0, obsmode=None, refscans=None, tauz=0.0, off_template=None, filepyfits=None, refscan1=None, refscan2=None, exclude_spectral_ends=10., extension=1, min_scale_reference=False, verbose=1, tsysmethod='perscan', tatm=273.0, trec=None, airmass_method='maddalena', scale_airmass=True, ): """ The calibration process in pseudocode: # Create a "reference spectrum" on blank sky refspec = mean(refspec_calon,refspec_caloff) # Determine TSYS, the total atmospheric + astrophysical + receiver noise # temperature tsys = tcal * mean_continuum(cal_off) / (mean_continuum(cal_on - cal_off)) + tcal/2.0 # for "TOTAL POWER" mode # Remove the atmospheric and receiver contribution tsource = tsys - (np.exp(tau*airmass)-1)*tatm - trec tsource_star = tsource * np.exp(tau*airmass) # for SIG-REF mode (signal + reference; on/off nod) calSpec = (spec-specRef)/specRef * tsys How does GBTIDL do it? in dcmeantsys.pro_, the +/-10% edge channels are excluded, and mean_tsys = mean(cal_off) / (mean(cal_on-cal_off)) * tcal + tcal/2.0 in dototalpower.pro_, the data is set to tp_data = (cal_on + cal_off) / 2.0 in dofullsigref.pro_, tsys is corrected with airmass=1/sin(elev) in dosigref.pro_, sigrefdata = (tpdata - refdata)/refdata * tsys .. dofullsigref.pro_: http://www.gb.nrao.edu/GBT/DA/gbtidl/release/user/toolbox/dofullsigref.html Parameters ---------- filename : str input file name outfilename : str output file name scanrange : 2-tuple *DATA SELECTION PARAMETER* Range of scans to include when creating off positions sourcename : str or None *DATA SELECTION PARAMETER* Name of source to include feednum : int *DATA SELECTION PARAMETER* Feed number to use (1 for single-feed systems) sampler : str *DATA SELECTION PARAMETER* Sampler to create the off for (e.g., 'A9') obsmode : str *DATA SELECTION PARAMETER* Observation Mode to include (e.g., DecLatMap) dataarr : None or np.ndarray OPTIONAL input of data array. If it has already been read, this param saves time tau : float Zenith optical depth [Deprecated, use tauz] tauz : float Zenith optical depth off_template : np.ndarray A spectrum representing the 'off' position generated by make_off (normalized!) refscans: list Reference scans at beginning & end of observation (probably). These are used as a spectroscopic off template unless off_template is specified, but they are always used to determine the continuum "zero-point" exclude_spectral_ends: float PERCENT (range [0,100]) of the spectrum to exclude at either end when computing TSYS etc. min_scale_reference: False or float EXPERIMENTAL: rescale the "reference" to be the scan of lowest TSYS, then use the value of min_scale_reference as a percentile to determine the integration to use from that scan. Try 10. WARNING: Can cause major problems if obserations occur at highly variable airmass! tsysmethod: 'perscan' or 'perint' Compute tsys for each scan or for each integration? verbose: int Level of verbosity. 0 is none, 1 is some, 2 is very, 3 is very lots tatm: float The atmospheric temperature. Will be subtracted from TSYS using the provided optical depth and assuming a plane-parallel atmosphere, which is good down to 8 degrees (http://www.gb.nrao.edu/~rmaddale/GBT/HighPrecisionCalibrationFromSingleDishTelescopes.pdf) trec: float Not presently used airmass_method: float Method of airmass determination, either csc(elev) or Ron Maddalena's version scale_airmass: bool If the min_scale_reference method is used, try to re-scale the off position mean by the airmass """ if tau != 0: if tauz != 0: raise ValueError("Only use tauz, not both tau and tauz") else: tauz = tau warnings.warn("Use tauz instead of tau", DeprecationWarning) if refscan1 is not None or refscan2 is not None: warnings.warn("Use refscans (a list of scans) rather than ref1,ref2", DeprecationWarning) if (type(refscans) == list and not (len(refscans) ==2 and refscans[0] == refscan1 and refscans[1] == refscan2)): raise ValueError('refscans does not match refscan1,2') elif refscans is None: refscans = refscan1,refscan2 data, dataarr, namelist, filepyfits = load_data_file(filename, extension=extension, dataarr=dataarr, datapfits=datapfits, filepyfits=filepyfits) newdatadict = dict([(n,[]) for n in namelist]) formatdict = dict([(t.name,t.format) for t in filepyfits[extension].columns]) samplers = np.unique(data['SAMPLER']) if isinstance(sampler,int): sampler = samplers[sampler] OK = data['SAMPLER'] == sampler OK *= data['FEED'] == feednum OK *= np.isfinite(data['DATA'].sum(axis=1)) OKsource = OK.copy() if sourcename is not None: OKsource *= (data['OBJECT'] == sourcename) if scanrange is not []: OKsource *= (scanrange[0] < data['SCAN'])*(data['SCAN'] < scanrange[1]) if obsmode is not None: OKsource *= ((obsmode == data.OBSMODE) + ((obsmode+":NONE:TPWCAL") == data.OBSMODE)) if sourcename is None and scanrange is None: raise IndexError("Must specify a source name and/or a scan range") if verbose: print "Beginning scan selection and calibration for sampler %s and feed %s" % (sampler,feednum) CalOff = (data['CAL']=='F') CalOn = (data['CAL']=='T') speclen = dataarr.shape[1] # Fraction of ends to exclude. exslice = "Exclusion Slice" exfrac = exclude_spectral_ends/100. exslice = slice(speclen*exfrac,-speclen*exfrac) # reference scans define the "background continuum" if type(refscans) == list: # split into two steps for readability temp_ref = get_reference(data, refscans, CalOn=CalOn, CalOff=CalOff, exslice=exslice, OK=OK) LSTrefs, refarray, ref_cntstoK, tsysref = temp_ref else: raise TypeError("Must specify reference scans as a list of scan numbers.") if verbose: print "Beginning calibration of %i scans." % ((OKsource*CalOn).sum()) if ((OKsource*CalOn).sum()) == 0: import pdb; pdb.set_trace() raise ValueError("There are no locations where the source was observed" " with the calibration diode on. That can't be right.") compute_tsys(data, tsysmethod=tsysmethod, OKsource=OKsource, CalOn=CalOn, CalOff=CalOff, exslice=exslice, verbose=verbose) # experimental: try to rescale the "reference" scan to be the minimum if min_scale_reference: ref_scale,ref_airmass = get_min_scale_reference(data, min_scale_reference, OKsource=OKsource, CalOn=CalOn, CalOff=CalOff, exslice=exslice, airmass_method=airmass_method) if verbose: print "EXPERIMENTAL: min_scale_reference = ",ref_scale for specindOn,specindOff in zip(np.where(OKsource*CalOn)[0], np.where(OKsource*CalOff)[0]): for K in namelist: if K != 'DATA': newdatadict[K].append(data[K][specindOn]) else: # should this be speclen or 4096? Changing to speclen... newdatadict['DATA'].append(np.zeros(speclen)) # http://www.gb.nrao.edu/~rmaddale/Weather/ elev = data['ELEVATIO'][specindOn] airmass = elev_to_airmass(elev, method=airmass_method) specOn = dataarr[specindOn,:] specOff = dataarr[specindOff,:] spec = (specOn + specOff)/2.0 LSTspec = data['LST'][specindOn] # this "if" test is no longer necessary if refscans is not None: # find the reference scan closest to the current scan # (LSTspec is a number, LSTrefs is an array, probably length 2) refscannumber = np.argmin(np.abs(LSTspec-LSTrefs)) # if the closest reference scan is the last or it is after the spectrum... # the earlier reference scan has index self-1 if refscannumber == len(refscans) - 1 or LSTrefs[refscannumber] > LSTspec: r1 = refscannumber - 1 r2 = refscannumber elif LSTrefs[refscannumber] < LSTspec: r1 = refscannumber r2 = refscannumber + 1 LSTref1 = LSTrefs[r1] LSTref2 = LSTrefs[r2] specref1 = refarray[r1,:] specref2 = refarray[r2,:] LSTspread = LSTref2-LSTref1 # LINEAR interpolation between the reference scans specRef = (specref2-specref1)/LSTspread*(LSTspec-LSTref1) + specref1 # EXPERIMENTAL if min_scale_reference: if verbose > 2: print "Rescaling specRef from ",specRef[exslice].mean()," to ",ref_scale specRef = specRef/specRef[exslice].mean() * ref_scale if scale_airmass: specRef += tatm/ref_cntstoK*(np.exp(-tauz*ref_airmass)-np.exp(-tauz*airmass)) # use a templated OFF spectrum # (e.g., one that has had spectral lines interpolated over) if off_template is not None: if off_template.shape != specRef.shape: raise ValueError("Off template shape does not match spectral shape") # exclude spectral ends when ratio-ing specRef = off_template * specRef[exslice].mean() / off_template[exslice].mean() tsys = data['TSYS'][specindOn] # I don't think this is right... the correct way is to make sure specRef moves with Spec #tsys_eff = tsys * np.exp(tau*airmass) - (np.exp(tau*airmass)-1)*tatm tsys_eff = tsys * np.exp(tauz*airmass) calSpec = (spec-specRef)/specRef * tsys_eff if calSpec.sum() == 0: raise ValueError("All values in calibrated spectrum are zero") newdatadict['TSYS'][-1] = tsys newdatadict['DATA'][-1] = calSpec # how do I get the "Format" for the column definitions? # Make Table cols = [pyfits.Column(name=key,format=formatdict[key],array=value) for key,value in newdatadict.iteritems()] colsP = pyfits.ColDefs(cols) #tablehdu = copy.copy(filepyfits[extension]) #tablehdu.data = colsP # this lies and claims corrupted tablehdu = pyfits.new_table(colsP, header=filepyfits[extension].header) phdu = pyfits.PrimaryHDU(header=filepyfits[0].header) hdulist = pyfits.HDUList([phdu,tablehdu]) hdulist.writeto(outfilename,clobber=clobber) #tablehdu.writeto(outfilename,clobber=clobber) if return_data: return filepyfits,data,colsP def compute_tsys(data, tsysmethod='perscan', OKsource=None, CalOn=None, CalOff=None, verbose=False, exslice=slice(None)): """ Calculate the TSYS vector for a set of scans from GBTIDL's dcmeantsys.py ; mean_tsys = tcal * mean(nocal) / (mean(withcal-nocal)) + tcal/2.0 """ if CalOn is None: CalOn = (data['CAL']=='T') if CalOff is None: CalOff = (data['CAL']=='F') dataarr = data['DATA'] if OKsource is None: OKsource = np.ones(dataarr.shape[0], dtype='bool') if tsysmethod == 'perscan': # compute TSYS on a scan-by-scan basis to avoid problems with saturated # TSYS. scannumbers = np.unique(data['SCAN'][OKsource]) for scanid in scannumbers: whscan = data['SCAN'] == scanid on_data = dataarr[whscan & CalOn,exslice] off_data = dataarr[whscan & CalOff,exslice] tcal = np.median(data['TCAL'][whscan]) offmean = np.median(off_data,axis=0).mean() onmean = np.median(on_data,axis=0).mean() diffmean = onmean-offmean tsys = (offmean / diffmean * tcal + tcal/2.0) if verbose > 1: print "Scan %4i: TSYS=%12.3f" % (scanid,tsys) data['TSYS'][whscan] = tsys elif tsysmethod == 'perint': on_data = dataarr[CalOn & OKsource,exslice] off_data = dataarr[CalOff & OKsource,exslice] tcal = data['TCAL'][CalOn & OKsource] offmean = np.mean(off_data,axis=1) onmean = np.mean(on_data,axis=1) diffmean = onmean-offmean # K / count = tcal / diffmean tsys = (offmean / diffmean * tcal + tcal/2.0) data['TSYS'][CalOn & OKsource] = tsys data['TSYS'][CalOff & OKsource] = tsys return data['TSYS'] def elev_to_airmass(elev, method='maddalena'): """ Calculate the airmass with np.csc(elev) or Ron Maddalena's improved method for low elevations http://www.gb.nrao.edu/~rmaddale/GBT/HighPrecisionCalibrationFromSingleDishTelescopes.pdf """ if method != 'maddalena': return 1/np.sin(elev/180*np.pi) else: # http://www.gb.nrao.edu/~rmaddale/GBT/HighPrecisionCalibrationFromSingleDishTelescopes.pdf return -0.0234+1.014/np.sin((elev+5.18/(elev+3.35))*np.pi/180.) def get_min_scale_reference(data, min_scale_reference, OKsource=None, CalOn=None, CalOff=None, verbose=False, exslice=slice(None), airmass_method='maddalena'): if CalOn is None: CalOn = (data['CAL']=='T') if CalOff is None: CalOff = (data['CAL']=='F') min_tsys = np.argmin(data['TSYS'][OKsource]) whmin = data['SCAN'][OKsource][min_tsys] whscan = data['SCAN'] == whmin dataarr = data['DATA'] r1 = np.percentile(dataarr[whscan*OKsource*CalOn,exslice], min_scale_reference, axis=0) r2 = np.percentile(dataarr[whscan*OKsource*CalOff,exslice], min_scale_reference, axis=0) ref_scale = np.median((r1+r2)/2.0) ref_airmass = elev_to_airmass(data['ELEVATIO'][OKsource][min_tsys], method=airmass_method) return ref_scale,ref_airmass def get_reference(data, refscans, CalOn=None, CalOff=None, exslice=slice(None), OK=None): """ Extract the reference scans from the data. Parameters ---------- data: FITS table Table of the data and associated metadata refscans: list List of scan numbers CalOn/CalOff: boolean arrays Optional; if not specified they will be recomputed. Boolean arrays identified the on/off regions of the data exslice: slice Slice along the spectral axis for computing means OK: boolean array Mandatory. All valid spectra for the specified feed and sampler """ if CalOn is None: CalOn = (data['CAL']=='T') if CalOff is None: CalOff = (data['CAL']=='F') dataarr = data['DATA'] speclen = dataarr.shape[1] refarray = np.zeros([len(refscans),speclen]) LSTrefs = np.zeros([len(refscans)]) for II,refscan in enumerate(refscans): OKref = OK & (refscan == data['SCAN']) # use "where" in case that reduces amount of stuff read in... CalOnRef = np.nonzero(OKref & CalOn)[0] CalOffRef = np.nonzero(OKref & CalOff)[0] specrefon = np.median(dataarr[CalOnRef,:],axis=0) specrefoff = np.median(dataarr[CalOffRef,:],axis=0) tcalref = np.median(data['TCAL'][OKref]) ref_cntstoK = tcalref/np.mean((specrefon-specrefoff)[exslice]) #tsysref = ( np.mean(specrefoff[exslice]) / # (np.mean((specrefon-specrefoff)[exslice])) * # tcalref + tcalref/2.0 ) tsysref = np.mean(specrefoff[exslice]) * ref_cntstoK + tcalref/2.0 refarray[II] = (specrefon + specrefoff)/2.0 LSTrefs[II] = np.mean(data['LST'][OKref]) if specrefon.sum() == 0 or specrefoff.sum() == 0: raise ValueError("All values in reference scan %i are zero" % refscan) elif np.isnan(specrefon).sum() > 0 or np.isnan(specrefoff).sum() > 0: raise ValueError("Reference scan %i contains a NAN" % refscan) return LSTrefs, refarray, ref_cntstoK, tsysref
[ "keflavich@gmail.com" ]
keflavich@gmail.com
36911a42ddb3beaf4d335d095a98af9da930b3f1
e2247e3bda886b9af82f1a246cc1eafa7cb08067
/experiments/llc2160_01/diag/utils.py
9a26d67f0c0f1b2ecd132befef03e86e205aa9a7
[]
no_license
joernc/NA
b9f15e7fa2653f630ed3fe5c5596f867215a74ad
77c22886ff8a2610ff60977c6aa28bee9737e99d
refs/heads/master
2023-08-09T06:09:58.126443
2021-09-13T21:47:07
2021-09-13T21:47:07
141,634,628
0
0
null
null
null
null
UTF-8
Python
false
false
2,181
py
import sys import os sys.path.append(os.path.abspath("/home/joernc/MITgcm/utils/python/MITgcmutils/MITgcmutils")) from mds import rdmds import numpy as np nx = 1080 ny = 540 nz = 55 # diag levels # model levels with diagnostics (data.diagnostics, converted to 0-based index) diag_lev = np.array([1,2,3,4,5,6,7,8,9,10,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95,97,99])-1 def rearrange(a): a1 = np.reshape(a[:nx,:], (ny,nx)) a5 = np.reshape(a[nx:,:], (nx,ny)) a = np.concatenate((a5[:,::-1].T, a1), axis=1) a[a==0.] = np.nan return a def rearrange3d(a): a1 = np.reshape(a[:,:nx,:], (nz,ny,nx)) a5 = np.reshape(a[:,nx:,:], (nz,nx,ny)) a = np.concatenate((np.swapaxes(a5[:,:,::-1], 1, 2), a1), axis=2) a[a==0.] = np.nan return a def rearrange_grid_spacing(dx, dy): dx1 = np.reshape(dx[:nx,:], (ny,nx)) dy1 = np.reshape(dy[:nx,:], (ny,nx)) dx5 = np.reshape(dy[nx:,:], (nx,ny)) dy5 = np.reshape(dx[nx:,:], (nx,ny)) dx = np.concatenate((dx5[:,::-1].T, dx1), axis=1) dy = np.concatenate((dy5[:,::-1].T, dy1), axis=1) dx[dx==0.] = np.nan dy[dy==0.] = np.nan return dx, dy def rearrange_velocities(u, v): u1 = np.reshape(u[:nx,:], (ny,nx)) v1 = np.reshape(v[:nx,:], (ny,nx)) u5 = np.reshape(v[nx:,:], (nx,ny)) v5 = np.roll(np.reshape(-u[nx:,:], (nx,ny)), -1, axis=1) u = np.concatenate((u5[:,::-1].T, u1), axis=1) v = np.concatenate((v5[:,::-1].T, v1), axis=1) u[u==0.] = np.nan v[v==0.] = np.nan return u,v def get_x_y(folder, do_rearrange=True): XC = rdmds(folder+"XC") XG = rdmds(folder+"XG") YC = rdmds(folder+"YC") YG = rdmds(folder+"YG") if do_rearrange: XC = rearrange(XC) XG = rearrange(XG) YC = rearrange(YC) YG = rearrange(YG) return XC, YC, XG, YG def get_dx_dy(folder): DXC = rdmds(folder+"DXC") DYC = rdmds(folder+"DYC") DXG = rdmds(folder+"DXG") DYG = rdmds(folder+"DYG") DXC, DYC = rearrange_grid_spacing(DXC, DYC) DXG, DYG = rearrange_grid_spacing(DXG, DYG) return DXC, DYC, DXG, DYG
[ "joernc@mit.edu" ]
joernc@mit.edu
8aac69bd60087f310596326b480b94339be3e5ef
f9d0def0e4a91388f5af9054461c66333abb8430
/kitti_evaluate.py
32ad0fadd2450a419ae75d0beb646020d2254158
[ "MIT" ]
permissive
michaelala25/prednet
aa1b66d33647ddb17479924c55845872cfbf710d
ae09ebf77ab3b6f0d80faf490bb246972de2ddc2
refs/heads/master
2022-08-21T16:53:28.916058
2018-09-25T18:01:02
2018-09-25T18:01:02
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,478
py
''' Evaluate trained PredNet on KITTI sequences. Calculates mean-squared error and plots predictions. ''' import os import numpy as np from six.moves import cPickle import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from keras import backend as K from keras.models import Model, model_from_json from keras.layers import Input, Dense, Flatten from prednet import PredNet from data_utils import SequenceGenerator from kitti_settings import * n_plot = 40 batch_size = 10 nt = 10 weights_file = os.path.join(WEIGHTS_DIR, 'prednet_kitti_weights.hdf5') json_file = os.path.join(WEIGHTS_DIR, 'prednet_kitti_model.json') test_file = os.path.join(DATA_DIR, 'X_test.hkl') test_sources = os.path.join(DATA_DIR, 'sources_test.hkl') # Load trained model f = open(json_file, 'r') json_string = f.read() f.close() train_model = model_from_json(json_string, custom_objects = {'PredNet': PredNet}) train_model.load_weights(weights_file) # Create testing model (to output predictions) layer_config = train_model.layers[1].get_config() layer_config['output_mode'] = 'prediction' data_format = layer_config['data_format'] if 'data_format' in layer_config else layer_config['dim_ordering'] test_prednet = PredNet(weights=train_model.layers[1].get_weights(), **layer_config) input_shape = list(train_model.layers[0].batch_input_shape[1:]) input_shape[0] = nt inputs = Input(shape=tuple(input_shape)) predictions = test_prednet(inputs) test_model = Model(inputs=inputs, outputs=predictions) test_generator = SequenceGenerator(test_file, test_sources, nt, sequence_start_mode='unique', data_format=data_format) X_test = test_generator.create_all() X_hat = test_model.predict(X_test, batch_size) if data_format == 'channels_first': X_test = np.transpose(X_test, (0, 1, 3, 4, 2)) X_hat = np.transpose(X_hat, (0, 1, 3, 4, 2)) # Compare MSE of PredNet predictions vs. using last frame. Write results to prediction_scores.txt mse_model = np.mean( (X_test[:, 1:] - X_hat[:, 1:])**2 ) # look at all timesteps except the first mse_prev = np.mean( (X_test[:, :-1] - X_test[:, 1:])**2 ) if not os.path.exists(RESULTS_SAVE_DIR): os.mkdir(RESULTS_SAVE_DIR) f = open(RESULTS_SAVE_DIR + 'prediction_scores.txt', 'w') f.write("Model MSE: %f\n" % mse_model) f.write("Previous Frame MSE: %f" % mse_prev) f.close() # Plot some predictions aspect_ratio = float(X_hat.shape[2]) / X_hat.shape[3] plt.figure(figsize = (nt, 2*aspect_ratio)) gs = gridspec.GridSpec(2, nt) gs.update(wspace=0., hspace=0.) plot_save_dir = os.path.join(RESULTS_SAVE_DIR, 'prediction_plots/') if not os.path.exists(plot_save_dir): os.mkdir(plot_save_dir) plot_idx = np.random.permutation(X_test.shape[0])[:n_plot] for i in plot_idx: for t in range(nt): plt.subplot(gs[t]) plt.imshow(X_test[i,t], interpolation='none') plt.tick_params(axis='both', which='both', bottom='off', top='off', left='off', right='off', labelbottom='off', labelleft='off') if t==0: plt.ylabel('Actual', fontsize=10) plt.subplot(gs[t + nt]) plt.imshow(X_hat[i,t], interpolation='none') plt.tick_params(axis='both', which='both', bottom='off', top='off', left='off', right='off', labelbottom='off', labelleft='off') if t==0: plt.ylabel('Predicted', fontsize=10) plt.savefig(plot_save_dir + 'plot_' + str(i) + '.png') plt.clf()
[ "mfala@edu.uwaterloo.ca" ]
mfala@edu.uwaterloo.ca
37fda34ea2332d382151e6afefbe696b94d10882
347fd3e01f338fe9c4b2ccaf398c758a0f226824
/venv/lib/python3.6/site-packages/django/views/__init__.py
220c4e57a013db1f3b629f2df592e943988ce7f3
[]
no_license
shohruhodilov/forms_tut
a26ad23bc3afcc6d7e1e49731dc0baecb6d84043
629cd97b5b6f94afdf24ed69af77ee8e9a7550d0
refs/heads/master
2021-09-27T15:07:06.044797
2020-03-25T09:34:55
2020-03-25T09:34:55
247,538,042
0
0
null
2021-06-10T18:41:28
2020-03-15T19:36:45
Python
UTF-8
Python
false
false
92
py
from django.views.generic.base import View __all__ = ['View'] def home(): return None
[ "shohruh.odilov@mailru" ]
shohruh.odilov@mailru
69db2cad29759665413e860575b1d9bd3dfb6c4c
388d49ac53ba59f8862048939798379d33b82609
/ipython-dev/Qiime/qiime/compare_distance_matrices.py
c0853c5226b2dcf83dd41dbf874fed2192ef0579
[]
no_license
andrewmagis/docker
973a467dc6bec6f7b182992677a725f3d0964515
46bd6f69c4f5fd61d08ab728caebb7e77d1cc6eb
refs/heads/master
2021-05-29T11:58:01.290201
2015-02-18T01:27:25
2015-02-18T01:27:25
30,884,223
0
0
null
null
null
null
UTF-8
Python
false
false
11,851
py
#!/usr/bin/env python from __future__ import division __author__ = "Jai Ram Rideout" __copyright__ = "Copyright 2012, The QIIME project" __credits__ = ["Jai Ram Rideout", "Michael Dwan", "Logan Knecht", "Damien Coy", "Levi McCracken", "Greg Caporaso"] __license__ = "GPL" __version__ = "1.8.0-dev" __maintainer__ = "Jai Ram Rideout" __email__ = "jai.rideout@gmail.com" from os import path from skbio.stats.distance import DistanceMatrix from qiime.format import format_p_value_for_num_iters from qiime.util import make_compatible_distance_matrices from qiime.stats import Mantel, MantelCorrelogram, PartialMantel def run_mantel_test(method, fps, distmats, num_perms, tail_type, comment, control_dm_fp=None, control_dm=None, sample_id_map=None): """Runs a Mantel test on all pairs of distance matrices. Returns a string suitable for writing out to a file containing the results of the test. WARNING: Only symmetric, hollow distance matrices may be used as input. Asymmetric distance matrices, such as those obtained by the UniFrac Gain metric (i.e. beta_diversity.py -m unifrac_g), should not be used as input. Arguments: method - which Mantel test to run (either 'mantel' or 'partial_mantel') fps - list of filepaths of the distance matrices distmats - list of tuples containing dm labels and dm data (i.e. the output of parse_distmat) num_perms - the number of permutations to use to calculate the p-value(s) tail_type - the type of tail test to use when calculating the p-value(s). Can be 'two sided', 'greater', or 'less'. Only applies when method is mantel comment - comment string to add to the beginning of the results string control_dm_fp - filepath of the control distance matrix. Only applies when method is partial_mantel (it is required then) control_dm - tuple containing control distance matrix labels and matrix data. Only applies when method is partial_mantel (it is required then) sample_id_map - dict mapping sample IDs (i.e. what is expected by make_compatible_distance_matrices) """ if len(fps) != len(distmats): raise ValueError("Must provide the same number of filepaths as there " "are distance matrices.") if comment is None: comment = '' result = comment if method == 'mantel': result += 'DM1\tDM2\tNumber of entries\tMantel r statistic\t' + \ 'p-value\tNumber of permutations\tTail type\n' elif method == 'partial_mantel': if not control_dm_fp or not control_dm: raise ValueError("You must provide a control matrix filepath and " "control matrix when running the partial Mantel " "test.") result += 'DM1\tDM2\tCDM\tNumber of entries\t' + \ 'Mantel r statistic\tp-value\tNumber of permutations\t' +\ 'Tail type\n' else: raise ValueError("Invalid method '%s'. Must be either 'mantel' or " "'partial_mantel'." % method) # Loop over all pairs of dms. for i, (fp1, (dm1_labels, dm1_data)) in enumerate(zip(fps, distmats)): for fp2, (dm2_labels, dm2_data) in zip(fps, distmats)[i + 1:]: # Make the current pair of distance matrices compatible by only # keeping samples that match between them, and ordering them by # the same sample IDs. (dm1_labels, dm1_data), (dm2_labels, dm2_data) = \ make_compatible_distance_matrices((dm1_labels, dm1_data), (dm2_labels, dm2_data), lookup=sample_id_map) if method == 'partial_mantel': # We need to intersect three sets (three matrices). (dm1_labels, dm1_data), (cdm_labels, cdm_data) = \ make_compatible_distance_matrices( (dm1_labels, dm1_data), control_dm, lookup=sample_id_map) (dm1_labels, dm1_data), (dm2_labels, dm2_data) = \ make_compatible_distance_matrices( (dm1_labels, dm1_data), (dm2_labels, dm2_data), lookup=sample_id_map) if len(dm1_labels) < 3: result += '%s\t%s\t%s\t%d\tToo few samples\n' % (fp1, fp2, control_dm_fp, len(dm1_labels)) continue elif len(dm1_labels) < 3: result += '%s\t%s\t%d\tToo few samples\n' % (fp1, fp2, len(dm1_labels)) continue dm1 = DistanceMatrix(dm1_data, dm1_labels) dm2 = DistanceMatrix(dm2_data, dm2_labels) # Create an instance of our correlation test and run it with # the specified number of permutations. if method == 'mantel': results = Mantel(dm1, dm2, tail_type)(num_perms) p_str = format_p_value_for_num_iters(results['p_value'], num_perms) result += "%s\t%s\t%d\t%.5f\t%s\t%d\t%s\n" % (fp1, fp2, len(dm1_labels), results[ 'r_value'], p_str, num_perms, tail_type) elif method == 'partial_mantel': cdm = DistanceMatrix(cdm_data, cdm_labels) results = PartialMantel(dm1, dm2, cdm)(num_perms) p_str = format_p_value_for_num_iters(results['mantel_p'], num_perms) result += "%s\t%s\t%s\t%d\t%.5f\t%s\t%d\t%s\n" % (fp1, fp2, control_dm_fp, len( dm1_labels), results['mantel_r'], p_str, num_perms, 'greater') return result def run_mantel_correlogram(fps, distmats, num_perms, comment, alpha, sample_id_map=None, variable_size_distance_classes=False): """Runs a Mantel correlogram analysis on all pairs of distance matrices. Returns a string suitable for writing out to a file containing the results of the test, a list of correlogram filepath names, and a list of matplotlib Figure objects representing each correlogram. The correlogram filepaths can have an extension string appended to the end of them and then be used to save each of the correlogram Figures to a file. Each correlogram filepath will be a combination of the two distance matrix filepaths that were used to create it. WARNING: Only symmetric, hollow distance matrices may be used as input. Asymmetric distance matrices, such as those obtained by the UniFrac Gain metric (i.e. beta_diversity.py -m unifrac_g), should not be used as input. Arguments: fps - list of filepaths of the distance matrices distmats - list of tuples containing dm labels and dm data (i.e. the output of parse_distmat) num_perms - the number of permutations to use to calculate the p-value(s) comment - comment string to add to the beginning of the results string alpha - the alpha value to use to determine significance in the correlogram plots sample_id_map - dict mapping sample IDs (i.e. what is expected by make_compatible_distance_matrices) variable_size_distance_classes - create distance classes that vary in size (i.e. width) but have the same number of distances in each class """ if len(fps) != len(distmats): raise ValueError("Must provide the same number of filepaths as there " "are distance matrices.") if comment is None: comment = '' result = comment + 'DM1\tDM2\tNumber of entries\t' + \ 'Number of permutations\tClass index\t' + \ 'Number of distances\tMantel r statistic\t' + \ 'p-value\tp-value (Bonferroni corrected)\tTail type\n' correlogram_fps = [] correlograms = [] # Loop over all pairs of dms. for i, (fp1, (dm1_labels, dm1_data)) in enumerate(zip(fps, distmats)): for fp2, (dm2_labels, dm2_data) in zip(fps, distmats)[i + 1:]: # Make the current pair of distance matrices compatible by only # keeping samples that match between them, and ordering them by # the same sample IDs. (dm1_labels, dm1_data), (dm2_labels, dm2_data) = \ make_compatible_distance_matrices((dm1_labels, dm1_data), (dm2_labels, dm2_data), lookup=sample_id_map) if len(dm1_labels) < 3: result += '%s\t%s\t%d\tToo few samples\n' % (fp1, fp2, len(dm1_labels)) continue dm1 = DistanceMatrix(dm1_data, dm1_labels) dm2 = DistanceMatrix(dm2_data, dm2_labels) # Create an instance of our Mantel correlogram test and run it with # the specified number of permutations. mc = MantelCorrelogram(dm1, dm2, alpha=alpha, variable_size_distance_classes=variable_size_distance_classes) results = mc(num_perms) # Generate a name for the current correlogram and save it and the # correlogram itself. dm1_name = path.basename(fp1) dm2_name = path.basename(fp2) correlogram_fps.append('_'.join((dm1_name, 'AND', dm2_name, 'mantel_correlogram')) + '.') correlograms.append(results['correlogram_plot']) # Iterate over the results and write them to the text file. first_time = True for class_idx, num_dist, r, p, p_corr in zip( results['class_index'], results['num_dist'], results['mantel_r'], results['mantel_p'], results['mantel_p_corr']): # Format p-values and figure out which tail type we have based # on the sign of r. p_str = None if p is not None: p_str = format_p_value_for_num_iters(p, num_perms) p_corr_str = None if p_corr is not None: p_corr_str = format_p_value_for_num_iters(p_corr, num_perms) if r is None: tail_type = None elif r < 0: tail_type = 'less' else: tail_type = 'greater' if first_time: result += '%s\t%s\t%d\t%d\t%s\t%d\t%s\t%s\t%s\t%s\n' % ( fp1, fp2, len(dm1_labels), num_perms, class_idx, num_dist, r, p_str, p_corr_str, tail_type) first_time = False else: result += '\t\t\t\t%s\t%d\t%s\t%s\t%s\t%s\n' % (class_idx, num_dist, r, p_str, p_corr_str, tail_type) return result, correlogram_fps, correlograms
[ "johncearls@gmail.com" ]
johncearls@gmail.com