max_stars_repo_path
stringlengths
4
286
max_stars_repo_name
stringlengths
5
119
max_stars_count
int64
0
191k
id
stringlengths
1
7
content
stringlengths
6
1.03M
content_cleaned
stringlengths
6
1.03M
language
stringclasses
111 values
language_score
float64
0.03
1
comments
stringlengths
0
556k
edu_score
float64
0.32
5.03
edu_int_score
int64
0
5
fourierflow/builders/kolmogorov.py
alasdairtran/fourierflow
42
6619551
import logging import time from functools import partial from typing import Callable, Dict, List, Optional import jax import jax.numpy as jnp import numpy as np import xarray as xr from hydra.utils import instantiate from jax_cfd.base.boundaries import periodic_boundary_conditions from jax_cfd.base.finite_differences import curl_2d from jax_cfd.base.funcutils import repeated, trajectory from jax_cfd.base.grids import Grid from jax_cfd.base.initial_conditions import (filtered_velocity_field, wrap_velocities) from jax_cfd.base.resize import downsample_staggered_velocity from jax_cfd.spectral.utils import vorticity_to_velocity from torch.utils.data import DataLoader, Dataset from fourierflow.utils import downsample_vorticity_hat, import_string from .base import Builder logger = logging.getLogger(__name__) KEYS = ['vx', 'vy', 'vz'] class KolmogorovBuilder(Builder): name = 'kolmogorov' def __init__(self, train_dataset, valid_dataset, test_dataset, loader_target: str = 'torch.utils.data.DataLoader', **kwargs): super().__init__() self.kwargs = kwargs self.train_dataset = train_dataset self.valid_dataset = valid_dataset self.test_dataset = test_dataset self.DataLoader = import_string(loader_target) def train_dataloader(self) -> DataLoader: loader = self.DataLoader(self.train_dataset, shuffle=True, **self.kwargs) return loader def val_dataloader(self) -> DataLoader: loader = self.DataLoader(self.valid_dataset, shuffle=False, **self.kwargs) return loader def test_dataloader(self) -> DataLoader: loader = self.DataLoader(self.test_dataset, shuffle=False, **self.kwargs) return loader def inference_data(self): k = self.test_dataset.k ds = self.test_dataset.ds.isel(time=slice(None, None, k)) data = { 'data': ds.vorticity.data, 'vx': ds.vx.data, 'vy': ds.vy.data, } return data class KolmogorovJAXDataset(Dataset): def __init__(self, path, k, unroll_length, in_memory=False): self.ds = xr.open_dataset(path, engine='h5netcdf') self.k = k self.B = len(self.ds.sample) self.L = unroll_length self.T = len(self.ds.time) - self.k * self.L if in_memory: logger.info('Loading dataset into memory...') self.ds.load() def __len__(self): return self.B * self.T def __getitem__(self, idx): b = idx // self.T t = idx % self.T k = self.k L = self.L ds = self.ds.isel(sample=b, time=slice(t, t+L*k+1, k)) in_ds = ds.isel(time=0) out_ds = ds.isel(time=slice(1, None, None)).transpose('x', 'y', 'time') inputs = { 'vx': in_ds.vx.data, 'vy': in_ds.vy.data, # 'vorticity': in_ds.vorticity, } outputs = { 'vx': out_ds.vx.data, 'vy': out_ds.vy.data, # 'vorticity': out_ds.vorticity, } return inputs, outputs class KolmogorovTorchDataset(Dataset): def __init__(self, path, k, in_memory=False): self.ds = xr.open_dataset(path, engine='h5netcdf') self.k = k self.B = len(self.ds.sample) self.T = len(self.ds.time) - self.k if in_memory: logger.info('Loading dataset into memory...') self.ds.load() def __len__(self): return self.B * self.T def __getitem__(self, idx): b = idx // self.T t = idx % self.T k = self.k ds = self.ds.isel(sample=b, time=slice(t, t+k+1, k)) in_ds = ds.isel(time=slice(0, 1)).transpose('x', 'y', 'time') out_ds = ds.isel(time=slice(1, 2)).transpose('x', 'y', 'time') return { 'x': in_ds.vorticity.data, 'vx': in_ds.vx.data, 'vy': in_ds.vy.data, 'y': out_ds.vorticity.data, } class KolmogorovMultiTorchDataset(Dataset): def __init__(self, paths, k, batch_size): self.dss = [xr.open_dataset(path, engine='h5netcdf') for path in paths] self.k = k self.B = len(self.dss[0].sample) self.T = len(self.dss[0].time) - self.k self.counter = 0 self.batch_size = batch_size self.ds_index = 0 def __len__(self): return self.B * self.T def __getitem__(self, idx): b = idx // self.T t = idx % self.T k = self.k ds = self.dss[self.ds_index] ds = ds.isel(sample=b, time=slice(t, t+k+1, k)) in_ds = ds.isel(time=slice(0, 1)).transpose('x', 'y', 'time') out_ds = ds.isel(time=slice(1, 2)).transpose('x', 'y', 'time') self.update_counter() return { 'x': in_ds.vorticity.data, 'y': out_ds.vorticity.data, } def update_counter(self): self.counter += 1 if self.counter % self.batch_size == 0: self.ds_index = (self.ds_index + 1) % len(self.dss) class KolmogorovTrajectoryDataset(Dataset): def __init__(self, init_path, path, corr_path, k, end=None, in_memory=False): ds = xr.open_dataset(path, engine='h5netcdf') init_ds = xr.open_dataset(init_path, engine='h5netcdf') init_ds = init_ds.expand_dims(dim={'time': [0.0]}) ds = xr.concat([init_ds, ds], dim='time') self.ds = ds.transpose('sample', 'x', 'y', 'time') corr_ds = xr.open_dataset(corr_path, engine='h5netcdf') self.corr_ds = corr_ds.transpose('sample', 'x', 'y', 'time') self.k = k self.B = len(self.ds.sample) self.end = end if in_memory: logger.info('Loading datasets into memory...') self.ds.load() self.corr_ds.load() def __len__(self): return self.B def __getitem__(self, b): time_slice = slice(None, self.end, self.k) ds = self.ds.isel(sample=b, time=time_slice) corr_ds = self.corr_ds.isel(sample=b, time=time_slice) out = { 'times': ds.time.data, 'data': ds.vorticity.data, 'vx': ds.vx.data, 'vy': ds.vy.data, 'corr_data': corr_ds.vorticity.data, } return out class KolmogorovJAXTrajectoryDataset(Dataset): def __init__(self, init_path, path, corr_path, k, end=None, inner_steps=1, outer_steps=100, in_memory=False): ds = xr.open_dataset(path, engine='h5netcdf') init_ds = xr.open_dataset(init_path, engine='h5netcdf') init_ds = init_ds.expand_dims(dim={'time': [0.0]}) ds = xr.concat([init_ds, ds], dim='time') self.ds = ds.transpose('sample', 'x', 'y', 'time') corr_ds = xr.open_dataset(corr_path, engine='h5netcdf') self.corr_ds = corr_ds.transpose('sample', 'x', 'y', 'time') self.k = k self.B = len(self.ds.sample) self.end = end self.inner_steps = inner_steps self.outer_steps = outer_steps if in_memory: logger.info('Loading datasets into memory...') self.ds.load() self.corr_ds.load() def __len__(self): return self.B def __getitem__(self, b): time_slice = slice(None, self.end, self.k) ds = self.ds.isel(sample=b, time=time_slice) corr_ds = self.corr_ds.isel(sample=b, time=time_slice) s = self.inner_steps e = s + self.outer_steps * s out = { 'times': corr_ds.time.data[..., s:e:s], 'vx': ds.vx.data[..., 0], 'vy': ds.vy.data[..., 0], 'targets': corr_ds.vorticity.data[..., s:e:s], } return out def get_learned_interpolation_step_fn(grid): from functools import partial import elegy import haiku as hk from jax_cfd.base.funcutils import init_context from jax_cfd.base.grids import GridArray, GridVariable from jax_cfd.ml.advections import modular_self_advection, self_advection from jax_cfd.ml.equations import modular_navier_stokes_model from jax_cfd.ml.forcings import kolmogorov_forcing from jax_cfd.ml.interpolations import FusedLearnedInterpolation from jax_cfd.ml.physics_specifications import NavierStokesPhysicsSpecs dt = 0.007012483601762931 forcing_module = partial(kolmogorov_forcing, scale=1.0, wavenumber=4, linear_coefficient=-0.1, ) interpolation_module = partial(FusedLearnedInterpolation, tags=['u', 'c'] ) advection_module = partial(modular_self_advection, interpolation_module=interpolation_module, ) convection_module = partial(self_advection, advection_module=advection_module, ) physics_specs = NavierStokesPhysicsSpecs( density=1.0, viscosity=1e-3, forcing_module=forcing_module, ) def step_fwd(x): model = modular_navier_stokes_model( grid=grid, dt=dt, physics_specs=physics_specs, convection_module=convection_module, ) return model(x) step_model = hk.without_apply_rng(hk.transform(step_fwd)) model = elegy.load( "./experiments/kolmogorov/re_1000/learned_interpolation/x128/checkpoints/weights.06-0.99") params = hk.data_structures.to_immutable_dict(model.module.params_) # inputs = [] # for seed, offset in enumerate(grid.cell_faces): # rng_key = jax.random.PRNGKey(seed) # data = jax.random.uniform(rng_key, grid.shape, jnp.float32) # variable = GridVariable( # array=GridArray(data, offset, grid), # bc=periodic_boundary_conditions(grid.ndim)) # inputs.append(variable) # inputs = tuple(inputs) # rng = jax.random.PRNGKey(42) # with init_context(): # params = step_model.init(rng, inputs) def step_fn(inputs): return step_model.apply(params, inputs) return step_fn def generate_kolmogorov(sim_grid: Grid, out_sizes: List[Dict[str, int]], method: str, step_fn: Callable, downsample_fn: Callable, seed: jax.random.KeyArray, initial_field: Optional[xr.Dataset] = None, peak_wavenumber: float = 4.0, max_velocity: float = 7.0, inner_steps: int = 25, outer_steps: int = 200, warmup_steps: int = 40, out_vorticity: bool = True): """Generate 2D Kolmogorov flows, similar to Kochkov et al (2021). Adapted from https://github.com/google/jax-cfd/blob/main/notebooks/demo.ipynb """ # Seems that there is some memory leak, especially when generating # re_1000/short_trajectories jax.lib.xla_bridge.get_backend.cache_clear() # Define the physical dimensions of the simulation. velocity_solve = vorticity_to_velocity( sim_grid) if sim_grid.ndim == 2 else None out_grids = {} for o in out_sizes: grid = Grid(shape=[o['size']] * sim_grid.ndim, domain=sim_grid.domain) out_grids[(o['size'], o['k'])] = grid downsample = partial(downsample_fn, sim_grid, out_grids, velocity_solve, out_vorticity) if initial_field is None: # Construct a random initial velocity. The `filtered_velocity_field` # function ensures that the initial velocity is divergence free and it # filters out high frequency fluctuations. v0 = filtered_velocity_field( seed, sim_grid, max_velocity, peak_wavenumber) if method == 'pseudo_spectral': # Compute the fft of the vorticity. The spectral code assumes an fft'd # vorticity for an initial state. vorticity0 = curl_2d(v0).data else: u, bcs = [], [] for i in range(sim_grid.ndim): u.append(initial_field[KEYS[i]].data) bcs.append(periodic_boundary_conditions(sim_grid.ndim)) v0 = wrap_velocities(u, sim_grid, bcs) if method == 'pseudo_spectral': vorticity0 = initial_field.vorticity.values if method == 'pseudo_spectral': state = jnp.fft.rfftn(vorticity0, axes=(0, 1)) else: state = v0 step_fn = instantiate(step_fn) # step_fn = get_learned_interpolation_step_fn(sim_grid) outer_step_fn = repeated(step_fn, inner_steps) # During warming up, we ignore intermediate results and just return # the final field if warmup_steps > 0: def ignore(_): return None trajectory_fn = trajectory(outer_step_fn, warmup_steps, ignore) start = time.time() state, _ = trajectory_fn(state) elapsed = np.float32(time.time() - start) outs = downsample(state) return outs, elapsed if outer_steps > 0: start = time.time() trajectory_fn = trajectory(outer_step_fn, outer_steps, downsample) _, trajs = trajectory_fn(state) elapsed = np.float32(time.time() - start) return trajs, elapsed def downsample_vorticity(sim_grid, out_grids, velocity_solve, out_vorticity, vorticity_hat): outs = {} for key, out_grid in out_grids.items(): size = key[0] if size == sim_grid.shape[0]: vxhat, vyhat = velocity_solve(vorticity_hat) out = { 'vx': jnp.fft.irfftn(vxhat, axes=(0, 1)), 'vy': jnp.fft.irfftn(vyhat, axes=(0, 1)), 'vorticity': jnp.fft.irfftn(vorticity_hat, axes=(0, 1)), } else: out = downsample_vorticity_hat( vorticity_hat, velocity_solve, sim_grid, out_grid) if not out_vorticity: del out['vorticity'] outs[key] = out # cpu = jax.devices('cpu')[0] # outs = {k: jax.device_put(v, cpu) for k, v in outs.items()} return outs def downsample_velocity(sim_grid, out_grids, velocity_solve, out_vorticity, u): outs = {} for key, out_grid in out_grids.items(): size = key[0] out = {} if size == sim_grid.shape[0]: for i in range(sim_grid.ndim): out[KEYS[i]] = u[i].data if sim_grid.ndim == 2 and out_vorticity: out['vorticity'] = curl_2d(u).data else: u_new = downsample_staggered_velocity( sim_grid, out_grid, u) for i in range(sim_grid.ndim): out[KEYS[i]] = u_new[i].data if sim_grid.ndim == 2 and out_vorticity: out['vorticity'] = curl_2d(u_new).data outs[key] = out # cpu = jax.devices('cpu')[0] # outs = {k: jax.device_put(v, cpu) for k, v in outs.items()} return outs
import logging import time from functools import partial from typing import Callable, Dict, List, Optional import jax import jax.numpy as jnp import numpy as np import xarray as xr from hydra.utils import instantiate from jax_cfd.base.boundaries import periodic_boundary_conditions from jax_cfd.base.finite_differences import curl_2d from jax_cfd.base.funcutils import repeated, trajectory from jax_cfd.base.grids import Grid from jax_cfd.base.initial_conditions import (filtered_velocity_field, wrap_velocities) from jax_cfd.base.resize import downsample_staggered_velocity from jax_cfd.spectral.utils import vorticity_to_velocity from torch.utils.data import DataLoader, Dataset from fourierflow.utils import downsample_vorticity_hat, import_string from .base import Builder logger = logging.getLogger(__name__) KEYS = ['vx', 'vy', 'vz'] class KolmogorovBuilder(Builder): name = 'kolmogorov' def __init__(self, train_dataset, valid_dataset, test_dataset, loader_target: str = 'torch.utils.data.DataLoader', **kwargs): super().__init__() self.kwargs = kwargs self.train_dataset = train_dataset self.valid_dataset = valid_dataset self.test_dataset = test_dataset self.DataLoader = import_string(loader_target) def train_dataloader(self) -> DataLoader: loader = self.DataLoader(self.train_dataset, shuffle=True, **self.kwargs) return loader def val_dataloader(self) -> DataLoader: loader = self.DataLoader(self.valid_dataset, shuffle=False, **self.kwargs) return loader def test_dataloader(self) -> DataLoader: loader = self.DataLoader(self.test_dataset, shuffle=False, **self.kwargs) return loader def inference_data(self): k = self.test_dataset.k ds = self.test_dataset.ds.isel(time=slice(None, None, k)) data = { 'data': ds.vorticity.data, 'vx': ds.vx.data, 'vy': ds.vy.data, } return data class KolmogorovJAXDataset(Dataset): def __init__(self, path, k, unroll_length, in_memory=False): self.ds = xr.open_dataset(path, engine='h5netcdf') self.k = k self.B = len(self.ds.sample) self.L = unroll_length self.T = len(self.ds.time) - self.k * self.L if in_memory: logger.info('Loading dataset into memory...') self.ds.load() def __len__(self): return self.B * self.T def __getitem__(self, idx): b = idx // self.T t = idx % self.T k = self.k L = self.L ds = self.ds.isel(sample=b, time=slice(t, t+L*k+1, k)) in_ds = ds.isel(time=0) out_ds = ds.isel(time=slice(1, None, None)).transpose('x', 'y', 'time') inputs = { 'vx': in_ds.vx.data, 'vy': in_ds.vy.data, # 'vorticity': in_ds.vorticity, } outputs = { 'vx': out_ds.vx.data, 'vy': out_ds.vy.data, # 'vorticity': out_ds.vorticity, } return inputs, outputs class KolmogorovTorchDataset(Dataset): def __init__(self, path, k, in_memory=False): self.ds = xr.open_dataset(path, engine='h5netcdf') self.k = k self.B = len(self.ds.sample) self.T = len(self.ds.time) - self.k if in_memory: logger.info('Loading dataset into memory...') self.ds.load() def __len__(self): return self.B * self.T def __getitem__(self, idx): b = idx // self.T t = idx % self.T k = self.k ds = self.ds.isel(sample=b, time=slice(t, t+k+1, k)) in_ds = ds.isel(time=slice(0, 1)).transpose('x', 'y', 'time') out_ds = ds.isel(time=slice(1, 2)).transpose('x', 'y', 'time') return { 'x': in_ds.vorticity.data, 'vx': in_ds.vx.data, 'vy': in_ds.vy.data, 'y': out_ds.vorticity.data, } class KolmogorovMultiTorchDataset(Dataset): def __init__(self, paths, k, batch_size): self.dss = [xr.open_dataset(path, engine='h5netcdf') for path in paths] self.k = k self.B = len(self.dss[0].sample) self.T = len(self.dss[0].time) - self.k self.counter = 0 self.batch_size = batch_size self.ds_index = 0 def __len__(self): return self.B * self.T def __getitem__(self, idx): b = idx // self.T t = idx % self.T k = self.k ds = self.dss[self.ds_index] ds = ds.isel(sample=b, time=slice(t, t+k+1, k)) in_ds = ds.isel(time=slice(0, 1)).transpose('x', 'y', 'time') out_ds = ds.isel(time=slice(1, 2)).transpose('x', 'y', 'time') self.update_counter() return { 'x': in_ds.vorticity.data, 'y': out_ds.vorticity.data, } def update_counter(self): self.counter += 1 if self.counter % self.batch_size == 0: self.ds_index = (self.ds_index + 1) % len(self.dss) class KolmogorovTrajectoryDataset(Dataset): def __init__(self, init_path, path, corr_path, k, end=None, in_memory=False): ds = xr.open_dataset(path, engine='h5netcdf') init_ds = xr.open_dataset(init_path, engine='h5netcdf') init_ds = init_ds.expand_dims(dim={'time': [0.0]}) ds = xr.concat([init_ds, ds], dim='time') self.ds = ds.transpose('sample', 'x', 'y', 'time') corr_ds = xr.open_dataset(corr_path, engine='h5netcdf') self.corr_ds = corr_ds.transpose('sample', 'x', 'y', 'time') self.k = k self.B = len(self.ds.sample) self.end = end if in_memory: logger.info('Loading datasets into memory...') self.ds.load() self.corr_ds.load() def __len__(self): return self.B def __getitem__(self, b): time_slice = slice(None, self.end, self.k) ds = self.ds.isel(sample=b, time=time_slice) corr_ds = self.corr_ds.isel(sample=b, time=time_slice) out = { 'times': ds.time.data, 'data': ds.vorticity.data, 'vx': ds.vx.data, 'vy': ds.vy.data, 'corr_data': corr_ds.vorticity.data, } return out class KolmogorovJAXTrajectoryDataset(Dataset): def __init__(self, init_path, path, corr_path, k, end=None, inner_steps=1, outer_steps=100, in_memory=False): ds = xr.open_dataset(path, engine='h5netcdf') init_ds = xr.open_dataset(init_path, engine='h5netcdf') init_ds = init_ds.expand_dims(dim={'time': [0.0]}) ds = xr.concat([init_ds, ds], dim='time') self.ds = ds.transpose('sample', 'x', 'y', 'time') corr_ds = xr.open_dataset(corr_path, engine='h5netcdf') self.corr_ds = corr_ds.transpose('sample', 'x', 'y', 'time') self.k = k self.B = len(self.ds.sample) self.end = end self.inner_steps = inner_steps self.outer_steps = outer_steps if in_memory: logger.info('Loading datasets into memory...') self.ds.load() self.corr_ds.load() def __len__(self): return self.B def __getitem__(self, b): time_slice = slice(None, self.end, self.k) ds = self.ds.isel(sample=b, time=time_slice) corr_ds = self.corr_ds.isel(sample=b, time=time_slice) s = self.inner_steps e = s + self.outer_steps * s out = { 'times': corr_ds.time.data[..., s:e:s], 'vx': ds.vx.data[..., 0], 'vy': ds.vy.data[..., 0], 'targets': corr_ds.vorticity.data[..., s:e:s], } return out def get_learned_interpolation_step_fn(grid): from functools import partial import elegy import haiku as hk from jax_cfd.base.funcutils import init_context from jax_cfd.base.grids import GridArray, GridVariable from jax_cfd.ml.advections import modular_self_advection, self_advection from jax_cfd.ml.equations import modular_navier_stokes_model from jax_cfd.ml.forcings import kolmogorov_forcing from jax_cfd.ml.interpolations import FusedLearnedInterpolation from jax_cfd.ml.physics_specifications import NavierStokesPhysicsSpecs dt = 0.007012483601762931 forcing_module = partial(kolmogorov_forcing, scale=1.0, wavenumber=4, linear_coefficient=-0.1, ) interpolation_module = partial(FusedLearnedInterpolation, tags=['u', 'c'] ) advection_module = partial(modular_self_advection, interpolation_module=interpolation_module, ) convection_module = partial(self_advection, advection_module=advection_module, ) physics_specs = NavierStokesPhysicsSpecs( density=1.0, viscosity=1e-3, forcing_module=forcing_module, ) def step_fwd(x): model = modular_navier_stokes_model( grid=grid, dt=dt, physics_specs=physics_specs, convection_module=convection_module, ) return model(x) step_model = hk.without_apply_rng(hk.transform(step_fwd)) model = elegy.load( "./experiments/kolmogorov/re_1000/learned_interpolation/x128/checkpoints/weights.06-0.99") params = hk.data_structures.to_immutable_dict(model.module.params_) # inputs = [] # for seed, offset in enumerate(grid.cell_faces): # rng_key = jax.random.PRNGKey(seed) # data = jax.random.uniform(rng_key, grid.shape, jnp.float32) # variable = GridVariable( # array=GridArray(data, offset, grid), # bc=periodic_boundary_conditions(grid.ndim)) # inputs.append(variable) # inputs = tuple(inputs) # rng = jax.random.PRNGKey(42) # with init_context(): # params = step_model.init(rng, inputs) def step_fn(inputs): return step_model.apply(params, inputs) return step_fn def generate_kolmogorov(sim_grid: Grid, out_sizes: List[Dict[str, int]], method: str, step_fn: Callable, downsample_fn: Callable, seed: jax.random.KeyArray, initial_field: Optional[xr.Dataset] = None, peak_wavenumber: float = 4.0, max_velocity: float = 7.0, inner_steps: int = 25, outer_steps: int = 200, warmup_steps: int = 40, out_vorticity: bool = True): """Generate 2D Kolmogorov flows, similar to Kochkov et al (2021). Adapted from https://github.com/google/jax-cfd/blob/main/notebooks/demo.ipynb """ # Seems that there is some memory leak, especially when generating # re_1000/short_trajectories jax.lib.xla_bridge.get_backend.cache_clear() # Define the physical dimensions of the simulation. velocity_solve = vorticity_to_velocity( sim_grid) if sim_grid.ndim == 2 else None out_grids = {} for o in out_sizes: grid = Grid(shape=[o['size']] * sim_grid.ndim, domain=sim_grid.domain) out_grids[(o['size'], o['k'])] = grid downsample = partial(downsample_fn, sim_grid, out_grids, velocity_solve, out_vorticity) if initial_field is None: # Construct a random initial velocity. The `filtered_velocity_field` # function ensures that the initial velocity is divergence free and it # filters out high frequency fluctuations. v0 = filtered_velocity_field( seed, sim_grid, max_velocity, peak_wavenumber) if method == 'pseudo_spectral': # Compute the fft of the vorticity. The spectral code assumes an fft'd # vorticity for an initial state. vorticity0 = curl_2d(v0).data else: u, bcs = [], [] for i in range(sim_grid.ndim): u.append(initial_field[KEYS[i]].data) bcs.append(periodic_boundary_conditions(sim_grid.ndim)) v0 = wrap_velocities(u, sim_grid, bcs) if method == 'pseudo_spectral': vorticity0 = initial_field.vorticity.values if method == 'pseudo_spectral': state = jnp.fft.rfftn(vorticity0, axes=(0, 1)) else: state = v0 step_fn = instantiate(step_fn) # step_fn = get_learned_interpolation_step_fn(sim_grid) outer_step_fn = repeated(step_fn, inner_steps) # During warming up, we ignore intermediate results and just return # the final field if warmup_steps > 0: def ignore(_): return None trajectory_fn = trajectory(outer_step_fn, warmup_steps, ignore) start = time.time() state, _ = trajectory_fn(state) elapsed = np.float32(time.time() - start) outs = downsample(state) return outs, elapsed if outer_steps > 0: start = time.time() trajectory_fn = trajectory(outer_step_fn, outer_steps, downsample) _, trajs = trajectory_fn(state) elapsed = np.float32(time.time() - start) return trajs, elapsed def downsample_vorticity(sim_grid, out_grids, velocity_solve, out_vorticity, vorticity_hat): outs = {} for key, out_grid in out_grids.items(): size = key[0] if size == sim_grid.shape[0]: vxhat, vyhat = velocity_solve(vorticity_hat) out = { 'vx': jnp.fft.irfftn(vxhat, axes=(0, 1)), 'vy': jnp.fft.irfftn(vyhat, axes=(0, 1)), 'vorticity': jnp.fft.irfftn(vorticity_hat, axes=(0, 1)), } else: out = downsample_vorticity_hat( vorticity_hat, velocity_solve, sim_grid, out_grid) if not out_vorticity: del out['vorticity'] outs[key] = out # cpu = jax.devices('cpu')[0] # outs = {k: jax.device_put(v, cpu) for k, v in outs.items()} return outs def downsample_velocity(sim_grid, out_grids, velocity_solve, out_vorticity, u): outs = {} for key, out_grid in out_grids.items(): size = key[0] out = {} if size == sim_grid.shape[0]: for i in range(sim_grid.ndim): out[KEYS[i]] = u[i].data if sim_grid.ndim == 2 and out_vorticity: out['vorticity'] = curl_2d(u).data else: u_new = downsample_staggered_velocity( sim_grid, out_grid, u) for i in range(sim_grid.ndim): out[KEYS[i]] = u_new[i].data if sim_grid.ndim == 2 and out_vorticity: out['vorticity'] = curl_2d(u_new).data outs[key] = out # cpu = jax.devices('cpu')[0] # outs = {k: jax.device_put(v, cpu) for k, v in outs.items()} return outs
en
0.659661
# 'vorticity': in_ds.vorticity, # 'vorticity': out_ds.vorticity, # inputs = [] # for seed, offset in enumerate(grid.cell_faces): # rng_key = jax.random.PRNGKey(seed) # data = jax.random.uniform(rng_key, grid.shape, jnp.float32) # variable = GridVariable( # array=GridArray(data, offset, grid), # bc=periodic_boundary_conditions(grid.ndim)) # inputs.append(variable) # inputs = tuple(inputs) # rng = jax.random.PRNGKey(42) # with init_context(): # params = step_model.init(rng, inputs) Generate 2D Kolmogorov flows, similar to Kochkov et al (2021). Adapted from https://github.com/google/jax-cfd/blob/main/notebooks/demo.ipynb # Seems that there is some memory leak, especially when generating # re_1000/short_trajectories # Define the physical dimensions of the simulation. # Construct a random initial velocity. The `filtered_velocity_field` # function ensures that the initial velocity is divergence free and it # filters out high frequency fluctuations. # Compute the fft of the vorticity. The spectral code assumes an fft'd # vorticity for an initial state. # step_fn = get_learned_interpolation_step_fn(sim_grid) # During warming up, we ignore intermediate results and just return # the final field # cpu = jax.devices('cpu')[0] # outs = {k: jax.device_put(v, cpu) for k, v in outs.items()} # cpu = jax.devices('cpu')[0] # outs = {k: jax.device_put(v, cpu) for k, v in outs.items()}
1.908962
2
sms/telerivet_backend.py
Audakel/Haedrian_Website
0
6619552
<gh_stars>0 __author__ = 'audakel' from rapidsms.backends.http.views import GenericHttpBackendView class TelerivetBackendView(GenericHttpBackendView): params = { 'identity_name': 'phone', 'text_name': 'message', }
__author__ = 'audakel' from rapidsms.backends.http.views import GenericHttpBackendView class TelerivetBackendView(GenericHttpBackendView): params = { 'identity_name': 'phone', 'text_name': 'message', }
none
1
1.696023
2
Enemy/__init__.py
henryboisdequin/Tower-Defense-Game
0
6619553
<gh_stars>0 """ Python package for abstract class of enemies and all the enemies in the game. """
""" Python package for abstract class of enemies and all the enemies in the game. """
en
0.786797
Python package for abstract class of enemies and all the enemies in the game.
1.316775
1
purls/algorithms/q_network.py
ollema/purl
10
6619554
<gh_stars>1-10 import time import matplotlib import matplotlib.pyplot as plt import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from gym.spaces.discrete import Discrete from scipy.signal import savgol_filter from gym_minigrid.envs import MiniGridEnv from gym_minigrid.wrappers import FullyObsWrapper from purls.algorithms.base import ReinforcementLearningAlgorithm from purls.utils.logs import debug, info, success # import adabound - if you want to experiment with (https://github.com/Luolc/AdaBound) DIRECTIONS = 4 device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def preprocess_obs(obs, in_features, discrete=False): """ Very similar to the preprocess_obs method in q_table. Main difference is that we want to return a onehot encoded vector here instead of an int. """ onehot = torch.zeros(in_features, dtype=torch.float, device=device) # for other gym environments like FrozenLake-v0 if discrete: state = obs # for MiniGrid environments else: obs = obs.flatten() i = np.nonzero(obs == 255)[0][0] position = i // 3 direction = obs[i + 1] state = position + in_features // DIRECTIONS * direction onehot[state] = 1 return onehot class Net(nn.Module): def __init__(self, in_features, action_space): super(Net, self).__init__() self.fully_connected = nn.Linear(in_features, action_space.n, bias=False) def forward(self, x): x = self.fully_connected(x) return x class q_network(ReinforcementLearningAlgorithm): def __init__(self, env, args): super().__init__( env, args, # default values for this algorithm default_learning_rate=0.1, default_discount_factor=0.99, default_start_eps=0.5, default_end_eps=0.05, default_annealing_steps=2500, default_num_updates=4000, ) try: # for MiniGrid environments self.env: MiniGridEnv = FullyObsWrapper(self.env) width, height = self.env.observation_space.shape[0:2] self.in_features = width * height * DIRECTIONS # really Discrete(7) for this env but we don't need the pick up, drop... actions self.env.action_space = Discrete(3) self.discrete_obs_space = False except Exception: # for other gym environments like FrozenLake-v0 if isinstance(self.env.observation_space, Discrete): self.in_features = self.env.observation_space.n self.discrete_obs_space = True # for other enviroments, we don't know how in_features is calculated from the obs space else: raise RuntimeError( f"Don't know how to handle this observation space{self.env.obeservation_space}" ) self.model = {"q_network": Net(self.in_features, self.env.action_space).to(device)} def train(self): q_net = self.model["q_network"] q_net.train() # loss function, could experiment with alternatives like Huber loss (F.smooth_l1_loss) too criterion = F.mse_loss # optimizer, could experiment with alternatives like AdaBound (adabound.AdaBound) too optimizer = optim.SGD(q_net.parameters(), lr=self.lr) eps = self.start_eps rewards = [] for i in range(1, self.max_num_updates + 1): # reduce chance for random action if eps > self.end_eps: eps -= self.eps_decay if self.seed: self.env.seed(self.seed) obs = self.env.reset() obs = preprocess_obs(obs, self.in_features, self.discrete_obs_space) current_reward = 0 done = False while True: # get q values q = q_net(obs.unsqueeze(0)) # greedy-epsilon if np.random.rand(1) < eps: # sample random action from action space a = self.env.action_space.sample() else: with torch.no_grad(): # choose action with highest Q value a = q.argmax().item() # get next observation, reward and done from environment next_obs, reward, done, _ = self.env.step(a) next_obs = preprocess_obs(next_obs, self.in_features, self.discrete_obs_space) # construct a target (compare this to a label in supervised learning) by taking # our current q values and replacing the q value for the action chosen with: # the max q value in the next observation * discount factor + the reward next_q = q_net(next_obs.unsqueeze(0)) next_q_max = next_q.max().item() target_q = q.detach().clone() # clone an independant target_q[0, a] = next_q_max * self.y + reward # compute loss loss = criterion(q, target_q) # optimize: backprop and update weights optimizer.zero_grad() loss.backward() optimizer.step() # update variables for next iteration current_reward += reward obs = next_obs if self.render_interval != 0 and i % self.render_interval == 0: self.env.render() time.sleep(1 / self.fps) if done: break rewards.append(current_reward) if i % 100 == 0: debug(f"episode {i:5d} finished - avg. reward: {np.average(rewards[-100:-1]):2f}") if self.save_interval != 0 and i % self.save_interval == 0: self.save() success(f"all {self.max_num_updates:5d} episodes finished!") info(f"reward for the final episode: {rewards[-1]:2f}") if self.save_interval != 0: self.save() debug("plotting reward over episodes") matplotlib.rcParams["figure.dpi"] = 200 plt.plot(rewards) plt.plot(savgol_filter(rewards, 23, 3), "-r", linewidth=2.0) plt.title(self.model_name) plt.xlabel("episode") plt.ylabel("reward") plt.show() def visualize(self): self.model = self.load() q_net = self.model["q_network"] q_net.eval() for i in range(self.max_num_updates + 1): if self.seed: self.env.seed(self.seed) obs = self.env.reset() obs = preprocess_obs(obs, self.in_features, self.discrete_obs_space) self.env.render() done = False time.sleep(0.5) while True: a = q_net(obs.unsqueeze(0)).argmax().item() next_obs, reward, done, _ = self.env.step(a) next_obs = preprocess_obs(next_obs, self.in_features, self.discrete_obs_space) obs = next_obs self.env.render() time.sleep(1 / self.fps) if done: break time.sleep(0.5)
import time import matplotlib import matplotlib.pyplot as plt import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from gym.spaces.discrete import Discrete from scipy.signal import savgol_filter from gym_minigrid.envs import MiniGridEnv from gym_minigrid.wrappers import FullyObsWrapper from purls.algorithms.base import ReinforcementLearningAlgorithm from purls.utils.logs import debug, info, success # import adabound - if you want to experiment with (https://github.com/Luolc/AdaBound) DIRECTIONS = 4 device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def preprocess_obs(obs, in_features, discrete=False): """ Very similar to the preprocess_obs method in q_table. Main difference is that we want to return a onehot encoded vector here instead of an int. """ onehot = torch.zeros(in_features, dtype=torch.float, device=device) # for other gym environments like FrozenLake-v0 if discrete: state = obs # for MiniGrid environments else: obs = obs.flatten() i = np.nonzero(obs == 255)[0][0] position = i // 3 direction = obs[i + 1] state = position + in_features // DIRECTIONS * direction onehot[state] = 1 return onehot class Net(nn.Module): def __init__(self, in_features, action_space): super(Net, self).__init__() self.fully_connected = nn.Linear(in_features, action_space.n, bias=False) def forward(self, x): x = self.fully_connected(x) return x class q_network(ReinforcementLearningAlgorithm): def __init__(self, env, args): super().__init__( env, args, # default values for this algorithm default_learning_rate=0.1, default_discount_factor=0.99, default_start_eps=0.5, default_end_eps=0.05, default_annealing_steps=2500, default_num_updates=4000, ) try: # for MiniGrid environments self.env: MiniGridEnv = FullyObsWrapper(self.env) width, height = self.env.observation_space.shape[0:2] self.in_features = width * height * DIRECTIONS # really Discrete(7) for this env but we don't need the pick up, drop... actions self.env.action_space = Discrete(3) self.discrete_obs_space = False except Exception: # for other gym environments like FrozenLake-v0 if isinstance(self.env.observation_space, Discrete): self.in_features = self.env.observation_space.n self.discrete_obs_space = True # for other enviroments, we don't know how in_features is calculated from the obs space else: raise RuntimeError( f"Don't know how to handle this observation space{self.env.obeservation_space}" ) self.model = {"q_network": Net(self.in_features, self.env.action_space).to(device)} def train(self): q_net = self.model["q_network"] q_net.train() # loss function, could experiment with alternatives like Huber loss (F.smooth_l1_loss) too criterion = F.mse_loss # optimizer, could experiment with alternatives like AdaBound (adabound.AdaBound) too optimizer = optim.SGD(q_net.parameters(), lr=self.lr) eps = self.start_eps rewards = [] for i in range(1, self.max_num_updates + 1): # reduce chance for random action if eps > self.end_eps: eps -= self.eps_decay if self.seed: self.env.seed(self.seed) obs = self.env.reset() obs = preprocess_obs(obs, self.in_features, self.discrete_obs_space) current_reward = 0 done = False while True: # get q values q = q_net(obs.unsqueeze(0)) # greedy-epsilon if np.random.rand(1) < eps: # sample random action from action space a = self.env.action_space.sample() else: with torch.no_grad(): # choose action with highest Q value a = q.argmax().item() # get next observation, reward and done from environment next_obs, reward, done, _ = self.env.step(a) next_obs = preprocess_obs(next_obs, self.in_features, self.discrete_obs_space) # construct a target (compare this to a label in supervised learning) by taking # our current q values and replacing the q value for the action chosen with: # the max q value in the next observation * discount factor + the reward next_q = q_net(next_obs.unsqueeze(0)) next_q_max = next_q.max().item() target_q = q.detach().clone() # clone an independant target_q[0, a] = next_q_max * self.y + reward # compute loss loss = criterion(q, target_q) # optimize: backprop and update weights optimizer.zero_grad() loss.backward() optimizer.step() # update variables for next iteration current_reward += reward obs = next_obs if self.render_interval != 0 and i % self.render_interval == 0: self.env.render() time.sleep(1 / self.fps) if done: break rewards.append(current_reward) if i % 100 == 0: debug(f"episode {i:5d} finished - avg. reward: {np.average(rewards[-100:-1]):2f}") if self.save_interval != 0 and i % self.save_interval == 0: self.save() success(f"all {self.max_num_updates:5d} episodes finished!") info(f"reward for the final episode: {rewards[-1]:2f}") if self.save_interval != 0: self.save() debug("plotting reward over episodes") matplotlib.rcParams["figure.dpi"] = 200 plt.plot(rewards) plt.plot(savgol_filter(rewards, 23, 3), "-r", linewidth=2.0) plt.title(self.model_name) plt.xlabel("episode") plt.ylabel("reward") plt.show() def visualize(self): self.model = self.load() q_net = self.model["q_network"] q_net.eval() for i in range(self.max_num_updates + 1): if self.seed: self.env.seed(self.seed) obs = self.env.reset() obs = preprocess_obs(obs, self.in_features, self.discrete_obs_space) self.env.render() done = False time.sleep(0.5) while True: a = q_net(obs.unsqueeze(0)).argmax().item() next_obs, reward, done, _ = self.env.step(a) next_obs = preprocess_obs(next_obs, self.in_features, self.discrete_obs_space) obs = next_obs self.env.render() time.sleep(1 / self.fps) if done: break time.sleep(0.5)
en
0.868465
# import adabound - if you want to experiment with (https://github.com/Luolc/AdaBound) Very similar to the preprocess_obs method in q_table. Main difference is that we want to return a onehot encoded vector here instead of an int. # for other gym environments like FrozenLake-v0 # for MiniGrid environments # default values for this algorithm # for MiniGrid environments # really Discrete(7) for this env but we don't need the pick up, drop... actions # for other gym environments like FrozenLake-v0 # for other enviroments, we don't know how in_features is calculated from the obs space # loss function, could experiment with alternatives like Huber loss (F.smooth_l1_loss) too # optimizer, could experiment with alternatives like AdaBound (adabound.AdaBound) too # reduce chance for random action # get q values # greedy-epsilon # sample random action from action space # choose action with highest Q value # get next observation, reward and done from environment # construct a target (compare this to a label in supervised learning) by taking # our current q values and replacing the q value for the action chosen with: # the max q value in the next observation * discount factor + the reward # clone an independant # compute loss # optimize: backprop and update weights # update variables for next iteration
2.454668
2
ssrtt.py
CylonicRaider/ssrtt
0
6619555
<filename>ssrtt.py #!/usr/bin/env python3 # -*- coding: ascii -*- import sys, os, re, inspect import cgi import weakref, contextlib import threading import websocket_server try: from Queue import Queue except ImportError: from queue import Queue THIS_DIR = os.path.dirname(os.path.abspath(inspect.getfile(lambda: None))) class Stream: def __init__(self, code, data=''): self.code = code self.data = data self.locked = False self.onevent = None self.cond = threading.Condition() def __enter__(self): return self.cond.__enter__() def __exit__(self, *args): return self.cond.__exit__(*args) def __iter__(self): return iter(self.iter()) def __call__(self, data): self.update(data) def iter(self, timeout=None): while 1: with self: yield (self.data, self.locked) self.cond.wait(timeout) def lock(self): with self: if self.locked: return False self.locked = True self.cond.notifyAll() if self.onevent: self.onevent('lock') return True def unlock(self): with self: self.locked = False self.cond.notifyAll() if self.onevent: self.onevent('unlock') def update(self, data): with self: self.data = data self.cond.notifyAll() if self.onevent: self.onevent('update', data) def set_onevent(self, handler): with self: self.onevent = handler def cas_onevent(self, check, handler): with self: if self.onevent is check: self.onevent = handler def spawn_thread(func, *args, **kwds): thr = threading.Thread(target=func, args=args, kwargs=kwds) thr.setDaemon(True) thr.start() return thr class SSRTTRequestHandler( websocket_server.quick.RoutingWebSocketRequestHandler): CACHE = websocket_server.httpserver.FileCache(THIS_DIR) STREAMS = weakref.WeakValueDictionary() LOCK = threading.RLock() @classmethod def get_stream(cls, code, data=''): with cls.LOCK: try: ret = cls.STREAMS[code] except KeyError: ret = Stream(code, data) cls.STREAMS[code] = ret return ret def run_read(self, code): self.send_response(200) self.send_header('Content-Type', 'text/event-stream') self.end_headers() old_data, old_locked = None, False for data, locked in self.get_stream(code).iter(60): if locked != old_locked: if locked: self.wfile.write(b'data: s:active\n\n') else: self.wfile.write(b'data: s:hangup\n\n') if data != old_data: cdata = data.encode('utf-8') event = (b'data: t:' + cdata.replace(b'\n', b'\ndata: ') + b'\n\n') self.wfile.write(event) self.wfile.flush() old_data, old_locked = data, locked def run_write(self, code, readcode=None): def handle_event(name, data=None): if name == 'lock': conn.write_text_frame('s:active') elif name == 'unlock': conn.write_text_frame('s:hangup') elif name == 'update': conn.write_text_frame('t:' + data) stream = self.get_stream(code) if not stream.lock(): self.send_code(409, 'Stream is already being written') return readstream = None if readcode is None else self.get_stream(readcode) try: conn = self.handshake() if readstream: with readstream: readstream.set_onevent(handle_event) if readstream.locked: handle_event('lock') else: handle_event('unlock') handle_event('update', readstream.data) conn.write_text_frame('e:' + stream.data) while 1: msg = conn.read_frame() if not msg: break if msg.msgtype != websocket_server.OP_TEXT: continue cnt = msg.content if cnt.startswith('T:'): stream(cnt[2:]) finally: if readstream: readstream.cas_onevent(handle_event, None) stream.unlock() def do_GET(self): path, sep, query = self.path.partition('?') query = sep + query parts = re.sub('^/|/$', '', path).split('/') static = None try: if path == '/': # Landing page static = 'index.html' elif '' in parts: # Sanitize path self.send_400() return elif len(parts) == 1: if parts[0] == 'favicon.ico' and not path.endswith('/'): # Special case for favicon static = 'favicon.ico' elif not path.endswith('/'): # Ensure streams have a canonical URL self.send_redirect(301, parts[0] + '/' + query) return else: # HTML page reading the stream static = 'static/index.html' elif len(parts) == 2: code = parts[0] if path.endswith('/'): # No directories on this level self.send_redirect(301, '../' + parts[-1] + query) return elif parts[1] == 'ws': # WebSocket writing the stream self.run_write(code) return elif parts[1] == 'get': # Actual stream self.run_read(code) return elif parts[1] not in ('.', '..'): # Random static files if '.' in parts[1]: static = 'static/' + parts[1] else: static = 'static/' + parts[1] + '.html' elif len(parts) == 3: code = parts[0] + '/' + parts[2] flipcode = parts[2] + '/' + parts[0] if path.endswith('/'): # No directories here, too self.send_redirect(301, '../' + parts[-1] + query) return elif parts[1] == 'chat': # HTML page for the chat static = 'static/chat.html' elif parts[1] == 'ws': # Writing the chat stream self.run_write(code, flipcode) return self.send_cache(static and self.CACHE.get(static)) except IOError: pass def main(): websocket_server.quick.run(SSRTTRequestHandler) if __name__ == '__main__': main()
<filename>ssrtt.py #!/usr/bin/env python3 # -*- coding: ascii -*- import sys, os, re, inspect import cgi import weakref, contextlib import threading import websocket_server try: from Queue import Queue except ImportError: from queue import Queue THIS_DIR = os.path.dirname(os.path.abspath(inspect.getfile(lambda: None))) class Stream: def __init__(self, code, data=''): self.code = code self.data = data self.locked = False self.onevent = None self.cond = threading.Condition() def __enter__(self): return self.cond.__enter__() def __exit__(self, *args): return self.cond.__exit__(*args) def __iter__(self): return iter(self.iter()) def __call__(self, data): self.update(data) def iter(self, timeout=None): while 1: with self: yield (self.data, self.locked) self.cond.wait(timeout) def lock(self): with self: if self.locked: return False self.locked = True self.cond.notifyAll() if self.onevent: self.onevent('lock') return True def unlock(self): with self: self.locked = False self.cond.notifyAll() if self.onevent: self.onevent('unlock') def update(self, data): with self: self.data = data self.cond.notifyAll() if self.onevent: self.onevent('update', data) def set_onevent(self, handler): with self: self.onevent = handler def cas_onevent(self, check, handler): with self: if self.onevent is check: self.onevent = handler def spawn_thread(func, *args, **kwds): thr = threading.Thread(target=func, args=args, kwargs=kwds) thr.setDaemon(True) thr.start() return thr class SSRTTRequestHandler( websocket_server.quick.RoutingWebSocketRequestHandler): CACHE = websocket_server.httpserver.FileCache(THIS_DIR) STREAMS = weakref.WeakValueDictionary() LOCK = threading.RLock() @classmethod def get_stream(cls, code, data=''): with cls.LOCK: try: ret = cls.STREAMS[code] except KeyError: ret = Stream(code, data) cls.STREAMS[code] = ret return ret def run_read(self, code): self.send_response(200) self.send_header('Content-Type', 'text/event-stream') self.end_headers() old_data, old_locked = None, False for data, locked in self.get_stream(code).iter(60): if locked != old_locked: if locked: self.wfile.write(b'data: s:active\n\n') else: self.wfile.write(b'data: s:hangup\n\n') if data != old_data: cdata = data.encode('utf-8') event = (b'data: t:' + cdata.replace(b'\n', b'\ndata: ') + b'\n\n') self.wfile.write(event) self.wfile.flush() old_data, old_locked = data, locked def run_write(self, code, readcode=None): def handle_event(name, data=None): if name == 'lock': conn.write_text_frame('s:active') elif name == 'unlock': conn.write_text_frame('s:hangup') elif name == 'update': conn.write_text_frame('t:' + data) stream = self.get_stream(code) if not stream.lock(): self.send_code(409, 'Stream is already being written') return readstream = None if readcode is None else self.get_stream(readcode) try: conn = self.handshake() if readstream: with readstream: readstream.set_onevent(handle_event) if readstream.locked: handle_event('lock') else: handle_event('unlock') handle_event('update', readstream.data) conn.write_text_frame('e:' + stream.data) while 1: msg = conn.read_frame() if not msg: break if msg.msgtype != websocket_server.OP_TEXT: continue cnt = msg.content if cnt.startswith('T:'): stream(cnt[2:]) finally: if readstream: readstream.cas_onevent(handle_event, None) stream.unlock() def do_GET(self): path, sep, query = self.path.partition('?') query = sep + query parts = re.sub('^/|/$', '', path).split('/') static = None try: if path == '/': # Landing page static = 'index.html' elif '' in parts: # Sanitize path self.send_400() return elif len(parts) == 1: if parts[0] == 'favicon.ico' and not path.endswith('/'): # Special case for favicon static = 'favicon.ico' elif not path.endswith('/'): # Ensure streams have a canonical URL self.send_redirect(301, parts[0] + '/' + query) return else: # HTML page reading the stream static = 'static/index.html' elif len(parts) == 2: code = parts[0] if path.endswith('/'): # No directories on this level self.send_redirect(301, '../' + parts[-1] + query) return elif parts[1] == 'ws': # WebSocket writing the stream self.run_write(code) return elif parts[1] == 'get': # Actual stream self.run_read(code) return elif parts[1] not in ('.', '..'): # Random static files if '.' in parts[1]: static = 'static/' + parts[1] else: static = 'static/' + parts[1] + '.html' elif len(parts) == 3: code = parts[0] + '/' + parts[2] flipcode = parts[2] + '/' + parts[0] if path.endswith('/'): # No directories here, too self.send_redirect(301, '../' + parts[-1] + query) return elif parts[1] == 'chat': # HTML page for the chat static = 'static/chat.html' elif parts[1] == 'ws': # Writing the chat stream self.run_write(code, flipcode) return self.send_cache(static and self.CACHE.get(static)) except IOError: pass def main(): websocket_server.quick.run(SSRTTRequestHandler) if __name__ == '__main__': main()
en
0.603578
#!/usr/bin/env python3 # -*- coding: ascii -*- # Landing page # Sanitize path # Special case for favicon # Ensure streams have a canonical URL # HTML page reading the stream # No directories on this level # WebSocket writing the stream # Actual stream # Random static files # No directories here, too # HTML page for the chat # Writing the chat stream
2.489291
2
utils/messaging.py
City-of-Helsinki/berth-reservations
3
6619556
<filename>utils/messaging.py from django.utils.translation import gettext_lazy as _ def get_email_subject(notification_type): from applications.notifications import ( NotificationType as ApplicationsNotificationType, ) from payments.notifications import NotificationType as PaymentsNotificationType if ( notification_type == PaymentsNotificationType.NEW_BERTH_ORDER_APPROVED or notification_type == PaymentsNotificationType.RENEW_BERTH_ORDER_APPROVED ): return _("Boat berth invoice") elif notification_type == PaymentsNotificationType.ORDER_CANCELLED: return _("Confirmation") elif notification_type == PaymentsNotificationType.ORDER_REFUNDED: return _("Refund confirmation") elif notification_type == ApplicationsNotificationType.BERTH_APPLICATION_REJECTED: return _("Berth application processed") return notification_type.label
<filename>utils/messaging.py from django.utils.translation import gettext_lazy as _ def get_email_subject(notification_type): from applications.notifications import ( NotificationType as ApplicationsNotificationType, ) from payments.notifications import NotificationType as PaymentsNotificationType if ( notification_type == PaymentsNotificationType.NEW_BERTH_ORDER_APPROVED or notification_type == PaymentsNotificationType.RENEW_BERTH_ORDER_APPROVED ): return _("Boat berth invoice") elif notification_type == PaymentsNotificationType.ORDER_CANCELLED: return _("Confirmation") elif notification_type == PaymentsNotificationType.ORDER_REFUNDED: return _("Refund confirmation") elif notification_type == ApplicationsNotificationType.BERTH_APPLICATION_REJECTED: return _("Berth application processed") return notification_type.label
none
1
1.996863
2
src/tests/basic_deployment.py
coreycb/charm-keystone-ldap
0
6619557
# # Copyright 2017 Canonical Ltd # # 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. import charmhelpers.contrib.openstack.amulet.deployment as amulet_deployment import charmhelpers.contrib.openstack.amulet.utils as os_amulet_utils # Use DEBUG to turn on debug logging u = os_amulet_utils.OpenStackAmuletUtils(os_amulet_utils.DEBUG) ldap_config_flags = "\ {user_id_attribute: uid,\ user_name_attribute: uid,\ user_tree_dn: 'ou=users,dc=test,dc=com',\ user_objectclass: inetOrgPerson,\ group_tree_dn: 'ou=groups,dc=test,dc=com',\ group_id_attribute: cn,\ group_name_attribute: cn,\ group_member_attribute: memberUid,\ group_objectclass: posixGroup}" class KeystoneLDAPCharmDeployment(amulet_deployment.OpenStackAmuletDeployment): """Amulet tests on a basic sdn_charm deployment.""" def __init__(self, series, openstack=None, source=None, stable=False): """Deploy the entire test environment.""" super(KeystoneLDAPCharmDeployment, self).__init__(series, openstack, source, stable) self._add_services() self._add_relations() self._deploy() # Run the configure post-deploy to get the ldap-server's IP # for use by keystone-ldap self._configure_services() u.log.info('Waiting on extended status checks...') exclude_services = ['mysql', 'mongodb'] self._auto_wait_for_status(exclude_services=exclude_services) self._initialize_tests() def _add_services(self): """Add services Add the services that we're testing, where sdn_charm is local, and the rest of the service are from lp branches that are compatible with the local charm (e.g. stable or next). """ this_service = {'name': 'keystone-ldap'} other_services = [ {'name': 'keystone'}, {'name': 'percona-cluster'}, {'name': 'ldap-server', 'location': '/home/ubuntu/charms/bionic/ldap-test-fixture'}, ] super(KeystoneLDAPCharmDeployment, self)._add_services( this_service, other_services, no_origin=['keystone-ldap', 'ldap-server'] ) def _add_relations(self): """Add all of the relations for the services.""" relations = { 'keystone:domain-backend': 'keystone-ldap:domain-backend', 'keystone:shared-db': 'percona-cluster:shared-db', } super(KeystoneLDAPCharmDeployment, self)._add_relations(relations) def _configure_services(self): """Configure all of the services.""" keystone_config = { 'admin-password': '<PASSWORD>', 'admin-token': '<PASSWORD>', 'preferred-api-version': 3, } keystone_ldap_config = self._get_ldap_config() pxc_config = { 'max-connections': 1000, } configs = {'keystone': keystone_config, 'keystone-ldap': keystone_ldap_config, 'percona-cluster': pxc_config} super(KeystoneLDAPCharmDeployment, self)._configure_services(configs) def _get_ldap_config(self): self.ldap_server_sentry = self.d.sentry['ldap-server'][0] self.ldap_server_ip = self.ldap_server_sentry.info['public-address'] #group_objectclass = groupOfNames #group_id_attribute = gidnumber #group_members_are_ids = False #user_tree_dn = ou=users,dc=test,dc=com keystone_ldap_config = { 'ldap-server': "ldap://{}".format(self.ldap_server_ip), 'ldap-user': 'cn=admin,dc=test,dc=com', 'ldap-password': '<PASSWORD>', 'ldap-suffix': 'dc=test,dc=com', 'domain-name': 'userdomain', 'ldap-config-flags': ldap_config_flags } if all(keystone_ldap_config.values()): self.ldap_configured = True return keystone_ldap_config else: # NOTE(jamespage): Use mock values to check deployment only # as no test fixture has been supplied self.ldap_configured = False return { 'ldap-server': 'myserver', 'ldap-user': 'myuser', 'ldap-password': '<PASSWORD>', 'ldap-suffix': 'mysuffix', 'domain-name': 'userdomain', } def _get_token(self): return self.keystone.service_catalog.catalog['token']['id'] def _initialize_tests(self): """Perform final initialization before tests get run.""" # Access the sentries for inspecting service units self.keystone_ldap = self.d.sentry['keystone-ldap'][0] self.mysql_sentry = self.d.sentry['percona-cluster'][0] self.keystone_sentry = self.d.sentry['keystone'][0] self.keystone_ip = self.keystone_sentry.relation( 'shared-db', 'percona-cluster:shared-db')['private-address'] # Authenticate admin with keystone self.keystone_session, self.keystone = u.get_default_keystone_session( self.keystone_sentry, openstack_release=self._get_openstack_release(), api_version=3) def find_keystone_v3_user(self, client, username, domain): """Find a user within a specified keystone v3 domain""" domain_users = client.users.list( domain=client.domains.find(name=domain).id ) usernames = [] for user in domain_users: usernames.append(user.name) if username.lower() == user.name.lower(): return user u.log.debug("The user {} was not in these users: {}. Returning None." "".format(username, usernames)) return None def find_keystone_v3_group(self, client, groupname, domain, user=None): """Find a group within a specified keystone v3 domain""" domain_groups = client.groups.list( domain=client.domains.find(name=domain).id, user=user ) groupnames = [] for group in domain_groups: groupsnames.append(group.name) if groupname.lower() == group.name.lower(): return group u.log.debug("The group {} was not in these groups: {}. Returning None." "".format(groupname, groupnames)) return None def test_100_keystone_ldap_users(self): """Validate basic functionality of keystone API""" if not self.ldap_configured: msg = 'Skipping API tests as no LDAP test fixture' u.log.info(msg) return # NOTE(jamespage): Test fixture should have johndoe and janedoe # accounts johndoe = self.find_keystone_v3_user(self.keystone, 'johndoe', 'userdomain') print("CCB johndoe={}".format(johndoe)) assert johndoe is not None janedoe = self.find_keystone_v3_user(self.keystone, 'janedoe', 'userdomain') print("CCB janedoe={}".format(janedoe)) assert janedoe is not None janedoe = self.find_keystone_v3_user(self.keystone, 'johndoe', 'userdomain', group='admin') print("CCB johndoe={}".format(johndoe)) assert johndoe is not None def test_101_keystone_ldap_groups(self): """Validate basic functionality of keystone API""" if not self.ldap_configured: msg = 'Skipping API tests as no LDAP test fixture' u.log.info(msg) return # NOTE(jamespage): Test fixture should have johndoe and janedoe # accounts admin = self.find_keystone_v3_group(self.keystone, 'admin', 'userdomain') print("CCB admin={}".format(admin)) assert admin is not None admin = self.find_keystone_v3_group(self.keystone, 'admin', 'userdomain', user='johndoe') print("CCB admin={}".format(admin)) assert admin is not None
# # Copyright 2017 Canonical Ltd # # 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. import charmhelpers.contrib.openstack.amulet.deployment as amulet_deployment import charmhelpers.contrib.openstack.amulet.utils as os_amulet_utils # Use DEBUG to turn on debug logging u = os_amulet_utils.OpenStackAmuletUtils(os_amulet_utils.DEBUG) ldap_config_flags = "\ {user_id_attribute: uid,\ user_name_attribute: uid,\ user_tree_dn: 'ou=users,dc=test,dc=com',\ user_objectclass: inetOrgPerson,\ group_tree_dn: 'ou=groups,dc=test,dc=com',\ group_id_attribute: cn,\ group_name_attribute: cn,\ group_member_attribute: memberUid,\ group_objectclass: posixGroup}" class KeystoneLDAPCharmDeployment(amulet_deployment.OpenStackAmuletDeployment): """Amulet tests on a basic sdn_charm deployment.""" def __init__(self, series, openstack=None, source=None, stable=False): """Deploy the entire test environment.""" super(KeystoneLDAPCharmDeployment, self).__init__(series, openstack, source, stable) self._add_services() self._add_relations() self._deploy() # Run the configure post-deploy to get the ldap-server's IP # for use by keystone-ldap self._configure_services() u.log.info('Waiting on extended status checks...') exclude_services = ['mysql', 'mongodb'] self._auto_wait_for_status(exclude_services=exclude_services) self._initialize_tests() def _add_services(self): """Add services Add the services that we're testing, where sdn_charm is local, and the rest of the service are from lp branches that are compatible with the local charm (e.g. stable or next). """ this_service = {'name': 'keystone-ldap'} other_services = [ {'name': 'keystone'}, {'name': 'percona-cluster'}, {'name': 'ldap-server', 'location': '/home/ubuntu/charms/bionic/ldap-test-fixture'}, ] super(KeystoneLDAPCharmDeployment, self)._add_services( this_service, other_services, no_origin=['keystone-ldap', 'ldap-server'] ) def _add_relations(self): """Add all of the relations for the services.""" relations = { 'keystone:domain-backend': 'keystone-ldap:domain-backend', 'keystone:shared-db': 'percona-cluster:shared-db', } super(KeystoneLDAPCharmDeployment, self)._add_relations(relations) def _configure_services(self): """Configure all of the services.""" keystone_config = { 'admin-password': '<PASSWORD>', 'admin-token': '<PASSWORD>', 'preferred-api-version': 3, } keystone_ldap_config = self._get_ldap_config() pxc_config = { 'max-connections': 1000, } configs = {'keystone': keystone_config, 'keystone-ldap': keystone_ldap_config, 'percona-cluster': pxc_config} super(KeystoneLDAPCharmDeployment, self)._configure_services(configs) def _get_ldap_config(self): self.ldap_server_sentry = self.d.sentry['ldap-server'][0] self.ldap_server_ip = self.ldap_server_sentry.info['public-address'] #group_objectclass = groupOfNames #group_id_attribute = gidnumber #group_members_are_ids = False #user_tree_dn = ou=users,dc=test,dc=com keystone_ldap_config = { 'ldap-server': "ldap://{}".format(self.ldap_server_ip), 'ldap-user': 'cn=admin,dc=test,dc=com', 'ldap-password': '<PASSWORD>', 'ldap-suffix': 'dc=test,dc=com', 'domain-name': 'userdomain', 'ldap-config-flags': ldap_config_flags } if all(keystone_ldap_config.values()): self.ldap_configured = True return keystone_ldap_config else: # NOTE(jamespage): Use mock values to check deployment only # as no test fixture has been supplied self.ldap_configured = False return { 'ldap-server': 'myserver', 'ldap-user': 'myuser', 'ldap-password': '<PASSWORD>', 'ldap-suffix': 'mysuffix', 'domain-name': 'userdomain', } def _get_token(self): return self.keystone.service_catalog.catalog['token']['id'] def _initialize_tests(self): """Perform final initialization before tests get run.""" # Access the sentries for inspecting service units self.keystone_ldap = self.d.sentry['keystone-ldap'][0] self.mysql_sentry = self.d.sentry['percona-cluster'][0] self.keystone_sentry = self.d.sentry['keystone'][0] self.keystone_ip = self.keystone_sentry.relation( 'shared-db', 'percona-cluster:shared-db')['private-address'] # Authenticate admin with keystone self.keystone_session, self.keystone = u.get_default_keystone_session( self.keystone_sentry, openstack_release=self._get_openstack_release(), api_version=3) def find_keystone_v3_user(self, client, username, domain): """Find a user within a specified keystone v3 domain""" domain_users = client.users.list( domain=client.domains.find(name=domain).id ) usernames = [] for user in domain_users: usernames.append(user.name) if username.lower() == user.name.lower(): return user u.log.debug("The user {} was not in these users: {}. Returning None." "".format(username, usernames)) return None def find_keystone_v3_group(self, client, groupname, domain, user=None): """Find a group within a specified keystone v3 domain""" domain_groups = client.groups.list( domain=client.domains.find(name=domain).id, user=user ) groupnames = [] for group in domain_groups: groupsnames.append(group.name) if groupname.lower() == group.name.lower(): return group u.log.debug("The group {} was not in these groups: {}. Returning None." "".format(groupname, groupnames)) return None def test_100_keystone_ldap_users(self): """Validate basic functionality of keystone API""" if not self.ldap_configured: msg = 'Skipping API tests as no LDAP test fixture' u.log.info(msg) return # NOTE(jamespage): Test fixture should have johndoe and janedoe # accounts johndoe = self.find_keystone_v3_user(self.keystone, 'johndoe', 'userdomain') print("CCB johndoe={}".format(johndoe)) assert johndoe is not None janedoe = self.find_keystone_v3_user(self.keystone, 'janedoe', 'userdomain') print("CCB janedoe={}".format(janedoe)) assert janedoe is not None janedoe = self.find_keystone_v3_user(self.keystone, 'johndoe', 'userdomain', group='admin') print("CCB johndoe={}".format(johndoe)) assert johndoe is not None def test_101_keystone_ldap_groups(self): """Validate basic functionality of keystone API""" if not self.ldap_configured: msg = 'Skipping API tests as no LDAP test fixture' u.log.info(msg) return # NOTE(jamespage): Test fixture should have johndoe and janedoe # accounts admin = self.find_keystone_v3_group(self.keystone, 'admin', 'userdomain') print("CCB admin={}".format(admin)) assert admin is not None admin = self.find_keystone_v3_group(self.keystone, 'admin', 'userdomain', user='johndoe') print("CCB admin={}".format(admin)) assert admin is not None
en
0.814981
# # Copyright 2017 Canonical Ltd # # 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. # Use DEBUG to turn on debug logging Amulet tests on a basic sdn_charm deployment. Deploy the entire test environment. # Run the configure post-deploy to get the ldap-server's IP # for use by keystone-ldap Add services Add the services that we're testing, where sdn_charm is local, and the rest of the service are from lp branches that are compatible with the local charm (e.g. stable or next). Add all of the relations for the services. Configure all of the services. #group_objectclass = groupOfNames #group_id_attribute = gidnumber #group_members_are_ids = False #user_tree_dn = ou=users,dc=test,dc=com # NOTE(jamespage): Use mock values to check deployment only # as no test fixture has been supplied Perform final initialization before tests get run. # Access the sentries for inspecting service units # Authenticate admin with keystone Find a user within a specified keystone v3 domain Find a group within a specified keystone v3 domain Validate basic functionality of keystone API # NOTE(jamespage): Test fixture should have johndoe and janedoe # accounts Validate basic functionality of keystone API # NOTE(jamespage): Test fixture should have johndoe and janedoe # accounts
1.605805
2
Etap 2/Logia18/Zad2.py
aszokalski/Logia
0
6619558
<filename>Etap 2/Logia18/Zad2.py def neon(n): wynik = 0 for i in range(len(n)): for j in range(len(n)): if i is j: continue ocena = max(i - j, j - i) * 2 + n[j] + n[i] if ocena > wynik: wynik = ocena return wynik
<filename>Etap 2/Logia18/Zad2.py def neon(n): wynik = 0 for i in range(len(n)): for j in range(len(n)): if i is j: continue ocena = max(i - j, j - i) * 2 + n[j] + n[i] if ocena > wynik: wynik = ocena return wynik
none
1
2.712894
3
apps/blog/migrations/0003_remove_aparatmedia_script.py
mehrbodjavadi79/AIC21-Backend
3
6619559
# Generated by Django 3.1.5 on 2021-03-06 14:39 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('blog', '0002_aparatmedia'), ] operations = [ migrations.RemoveField( model_name='aparatmedia', name='script', ), ]
# Generated by Django 3.1.5 on 2021-03-06 14:39 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('blog', '0002_aparatmedia'), ] operations = [ migrations.RemoveField( model_name='aparatmedia', name='script', ), ]
en
0.788293
# Generated by Django 3.1.5 on 2021-03-06 14:39
1.366045
1
demos/concat.cast.py
project-faros/resources
1
6619560
#!/usr/bin/env python3 import sys import json cast_files = sys.argv[1:] t_offset = 0 t_last = 0 entry = [0] max_idle = 5 for idx, cast_file in enumerate(cast_files): lines = open(cast_file, 'r').read().split('\n') meta = lines[0] data = lines[1:] if idx == 0: print(meta) for entry_raw in data: if entry_raw: # read entry and offset time stamp entry = json.loads(entry_raw) entry[0] += t_offset # check for long idles if entry[0] > t_last + max_idle: idle_delta = entry[0] - t_last - max_idle entry[0] -= idle_delta t_offset -= idle_delta t_last = entry[0] print(json.dumps(entry)) t_offset = entry[0] + 3
#!/usr/bin/env python3 import sys import json cast_files = sys.argv[1:] t_offset = 0 t_last = 0 entry = [0] max_idle = 5 for idx, cast_file in enumerate(cast_files): lines = open(cast_file, 'r').read().split('\n') meta = lines[0] data = lines[1:] if idx == 0: print(meta) for entry_raw in data: if entry_raw: # read entry and offset time stamp entry = json.loads(entry_raw) entry[0] += t_offset # check for long idles if entry[0] > t_last + max_idle: idle_delta = entry[0] - t_last - max_idle entry[0] -= idle_delta t_offset -= idle_delta t_last = entry[0] print(json.dumps(entry)) t_offset = entry[0] + 3
en
0.551585
#!/usr/bin/env python3 # read entry and offset time stamp # check for long idles
2.399998
2
lab5/alpha_beta.py
Lucassass/kunstigIntelligenceF21
0
6619561
def alpha_beta_decision(state): infinity = float('inf') def max_value(state, alpha, beta): if is_terminal(state): return utility_of(state) v = -infinity for successor in successors_of(state): v = max(v, min_value(successor, alpha, beta)) if v >= beta: return v alpha = min(alpha, v) return v def min_value(state, alpha, beta): if is_terminal(state): return utility_of(state) v = infinity for successor in successors_of(state): v = min(v, max_value(successor, alpha, beta)) if v <= alpha: return v beta = max(beta, v) return v state = argmax( successors_of(state), lambda a: min_value(a, infinity, -infinity) ) return state def is_terminal(state): pass def utility_of(state): pass def successors_of(state): pass def argmax(iterable, func): return max(iterable, key=func) def computer_select_pile(state): new_state = alpha_beta_decision(state) return new_state def user_select_pile(list_of_piles): ''' Given a list of piles, asks the user to select a pile and then a split. Then returns the new list of piles. ''' print("\n Current piles: {}".format(list_of_piles)) i = -1 while i < 0 or i >= len(list_of_piles) or list_of_piles[i] < 3: print("Which pile (from 1 to {}, must be > 2)?".format(len(list_of_piles))) i = -1 + int(input()) print("Selected pile {}".format(list_of_piles[i])) max_split = list_of_piles[i] - 1 j = 0 while j < 1 or j > max_split or j == list_of_piles[i] - j: if list_of_piles[i] % 2 == 0: print( 'How much is the first split (from 1 to {}, but not {})?'.format( max_split, list_of_piles[i] // 2 ) ) else: print( 'How much is the first split (from 1 to {})?'.format(max_split) ) j = int(input()) k = list_of_piles[i] - j new_list_of_piles = list_of_piles[:i] + [j, k] + list_of_piles[i + 1:] print(" New piles: {}".format(new_list_of_piles)) return new_list_of_piles def main(): state = [7] while not is_terminal(state): state = user_select_pile(state) if not is_terminal(state): state = computer_select_pile(state) print(" Final state is {}".format(state)) if __name__ == '__main__': main()
def alpha_beta_decision(state): infinity = float('inf') def max_value(state, alpha, beta): if is_terminal(state): return utility_of(state) v = -infinity for successor in successors_of(state): v = max(v, min_value(successor, alpha, beta)) if v >= beta: return v alpha = min(alpha, v) return v def min_value(state, alpha, beta): if is_terminal(state): return utility_of(state) v = infinity for successor in successors_of(state): v = min(v, max_value(successor, alpha, beta)) if v <= alpha: return v beta = max(beta, v) return v state = argmax( successors_of(state), lambda a: min_value(a, infinity, -infinity) ) return state def is_terminal(state): pass def utility_of(state): pass def successors_of(state): pass def argmax(iterable, func): return max(iterable, key=func) def computer_select_pile(state): new_state = alpha_beta_decision(state) return new_state def user_select_pile(list_of_piles): ''' Given a list of piles, asks the user to select a pile and then a split. Then returns the new list of piles. ''' print("\n Current piles: {}".format(list_of_piles)) i = -1 while i < 0 or i >= len(list_of_piles) or list_of_piles[i] < 3: print("Which pile (from 1 to {}, must be > 2)?".format(len(list_of_piles))) i = -1 + int(input()) print("Selected pile {}".format(list_of_piles[i])) max_split = list_of_piles[i] - 1 j = 0 while j < 1 or j > max_split or j == list_of_piles[i] - j: if list_of_piles[i] % 2 == 0: print( 'How much is the first split (from 1 to {}, but not {})?'.format( max_split, list_of_piles[i] // 2 ) ) else: print( 'How much is the first split (from 1 to {})?'.format(max_split) ) j = int(input()) k = list_of_piles[i] - j new_list_of_piles = list_of_piles[:i] + [j, k] + list_of_piles[i + 1:] print(" New piles: {}".format(new_list_of_piles)) return new_list_of_piles def main(): state = [7] while not is_terminal(state): state = user_select_pile(state) if not is_terminal(state): state = computer_select_pile(state) print(" Final state is {}".format(state)) if __name__ == '__main__': main()
en
0.734493
Given a list of piles, asks the user to select a pile and then a split. Then returns the new list of piles.
3.890704
4
test/application/test_views.py
Ashaba/API-Monitor
0
6619562
<reponame>Ashaba/API-Monitor<filename>test/application/test_views.py<gh_stars>0 from test.base import BaseTestCase, user_payload import json from application.models import db, Collection, Header, Request, RequestAssertion, Team from application.auth.models import User class TestApplication(BaseTestCase): checks = [ { "method":"GET", "id":"", "url":"https://lmap-staging-test.andela.com/api/v1/careers", "headers":[ { "key":"Token", "value":"someToken", "id":"" } ], "assertions":[ { "assertion_type":"Status Code", "comparison":"equal (number)", "value":"200", "id":"" } ] } ] def setUp(self): db.drop_all() db.create_all() self.user = User(name=user_payload['fullName'], email=user_payload['email'], image_url=user_payload['imageUrl']) self.user.save() self.team = Team(name="Test team", user_id=self.user.id) self.team.save() self.collection_one = Collection(name="collection one", user_id=self.user.id, team_id=self.team.id) self.collection_one.save() self.collection_two = Collection(name="collection two", user_id=self.user.id) self.collection_two.save() def test_get_dashboard(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') response = self.client.get('/dashboard') self.assert_template_used('dashboard.html') self.assert200(response) def test_get_dashboard_unauthenticated(self): response = self.client.get('/dashboard') self.assertEqual(response.status_code, 302) def test_get_team_view(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') response = self.client.get('/team') self.assert_template_used('team.html') self.assert200(response) def test_get_team_unauthorized(self): response = self.client.get('/team') self.assertEqual(response.status_code, 302) def test_get_collection_view(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') response = self.client.get('/collections') self.assert_template_used('collections.html') self.assert200(response) def test_get_collection_unauthorized(self): response = self.client.get('/collections') self.assertEqual(response.status_code, 302) def test_get_collections_correct_user_successful(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') response = self.client.get('/collections') self.assertEqual(response.status_code, 200) self.assertTrue(self.get_context_variable('context')['collections']) self.assertListEqual(self.get_context_variable('context')['collections'], [self.collection_one, self.collection_two]) def test_get_collections_different_user_no_result(self): another_user_payload = { "fullName": "<NAME>", "email": "<EMAIL>", "imageUrl": "another_image_random" } self.client.post('/auth', data=json.dumps(another_user_payload), content_type='application/json') response = self.client.get('/collections') self.assertEqual(response.status_code, 200) self.assertFalse(self.get_context_variable('context')['collections']) self.assertListEqual(self.get_context_variable('context')['collections'], []) def test_post_collections_unauthorized(self): response = self.client.post('/collections') self.assertEqual(response.status_code, 302) def test_post_collection_no_team_successful(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') response = self.client.post('/collections', data=dict(team="none", collection="this is a test collection")) self.assertEqual(response.status_code, 200) self.assertTrue(self.get_context_variable('context')['collections']) self.assertEqual(len(self.get_context_variable('context')['collections']), 3) def test_post_collection_with_team_successful(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') response = self.client.post('/collections', data=dict(team=self.team.name, collection="this is a test collection")) self.assertEqual(response.status_code, 200) self.assertTrue(self.get_context_variable('context')['collections']) self.assertEqual(len(self.get_context_variable('context')['collections']), 3) def test_post_collection_duplicate_name_with_team(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') response = self.client.post('/collections', data=dict(team=self.team.name, collection="collection one")) self.assertEqual(response.status_code, 200) self.assertEqual(response.data, b'duplicate_collection') def test_post_collection_duplicate_name_no_team(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') response = self.client.post('/collections', data=dict(team="none", collection="collection one")) self.assertEqual(response.status_code, 200) self.assertEqual(response.data, b'duplicate_collection') def test_delete_collection_unauthorized(self): response = self.client.delete('/collections') self.assertEqual(response.status_code, 302) def test_delete_collection_successful(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') response = self.client.delete('/collections?id={}'.format(self.collection_one.id)) self.assertEqual(response.status_code, 200) self.assertTrue(self.get_context_variable('context')['collections']) self.assertEqual(len(self.get_context_variable('context')['collections']), 1) self.assertListEqual(self.get_context_variable('context')['collections'], [self.collection_two]) def test_post_check(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') collection = Collection(name='Test Collection', user_id=self.user.id) collection.save() old_number_of_checks = len(collection.requests) self.checks[0]['id'] = "" response = self.client.post( f'/collection-details/{collection.id}/update', data=json.dumps(self.checks), content_type='application/json') self.assertEqual(response.status_code, 200) new_number_of_checks = len(collection.requests) self.assertEqual(new_number_of_checks, old_number_of_checks + 1) def test_update_check(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') collection = Collection(name='Test Collection', user_id=self.user.id) collection.save() request = Request( collection_id=collection.id, method='GET', url='https://test.com', ) request.save() old_number_of_headers = len(request.headers) self.checks[0]['id'] = f"{request.id}" response = self.client.post( f'/collection-details/{collection.id}/update', data=json.dumps(self.checks), content_type='application/json') self.assertEqual(response.status_code, 200) new_number_of_headers = len(request.headers) self.assertEqual(new_number_of_headers, old_number_of_headers + 1) def test_fetch_collection_details(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') collection = Collection(name='Test Collection', user_id=self.user.id) collection.save() response = self.client.get(f'/collection-details/{collection.id}') self.assertEqual(response.status_code, 200) self.assertTrue('checks' in self.get_context_variable('context')) self.assertTrue('results' in self.get_context_variable('context')) self.assertEqual(self.get_context_variable('context')['collection_name'], collection.name) def test_post_check_with_duplicate_method_and_url(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') collection = Collection(name='Test Collection', user_id=self.user.id) collection.save() request = Request( collection_id=collection.id, method='GET', url='https://test.com', ) request.save() old_number_of_checks = len(collection.requests) self.checks[0][''] = f"{request.id}" self.checks[0]['method'] = 'GET' self.checks[0]['url'] = 'https://test.com' response = self.client.post( f'/collection-details/{collection.id}/update', data=json.dumps(self.checks), content_type='application/json') self.assertEqual(response.status_code, 200) new_number_of_checks = len(collection.requests) self.assertEqual(old_number_of_checks, new_number_of_checks) self.assertTrue((json.loads(response.data))['errors']) def test_post_duplicate_header(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') collection = Collection(name='Test Collection', user_id=self.user.id) collection.save() request = Request( collection_id=collection.id, method='GET', url='https://lmap-staging-test.andela.com/api/v1/careers', ) request.save() header = Header(key="Token", value="<PASSWORD>Token", request_id=request.id) header.save() old_number_of_headers = len(request.headers) self.checks[0]['id'] = f"{request.id}" response = self.client.post( f'/collection-details/{collection.id}/update', data=json.dumps(self.checks), content_type='application/json') self.assertEqual(response.status_code, 200) new_number_of_headers = len(request.headers) self.assertEqual(old_number_of_headers, new_number_of_headers) self.assertTrue((json.loads(response.data))['errors']) def test_post_duplicate_assertion(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') collection = Collection(name='Test Collection', user_id=self.user.id) collection.save() request = Request( collection_id=collection.id, method='GET', url='https://lmap-staging-test.andela.com/api/v1/careers', ) request.save() assertion = RequestAssertion( assertion_type='Status Code', comparison='equal (number)', value=200, request_id=request.id ) assertion.save() old_number_of_assertions = len(request.assertions) self.checks[0]['id'] = f"{request.id}" response = self.client.post( f'/collection-details/{collection.id}/update', data=json.dumps(self.checks), content_type='application/json') self.assertEqual(response.status_code, 200) new_number_of_assertions = len(request.assertions) self.assertEqual(old_number_of_assertions, new_number_of_assertions) self.assertTrue((json.loads(response.data))['errors'])
from test.base import BaseTestCase, user_payload import json from application.models import db, Collection, Header, Request, RequestAssertion, Team from application.auth.models import User class TestApplication(BaseTestCase): checks = [ { "method":"GET", "id":"", "url":"https://lmap-staging-test.andela.com/api/v1/careers", "headers":[ { "key":"Token", "value":"someToken", "id":"" } ], "assertions":[ { "assertion_type":"Status Code", "comparison":"equal (number)", "value":"200", "id":"" } ] } ] def setUp(self): db.drop_all() db.create_all() self.user = User(name=user_payload['fullName'], email=user_payload['email'], image_url=user_payload['imageUrl']) self.user.save() self.team = Team(name="Test team", user_id=self.user.id) self.team.save() self.collection_one = Collection(name="collection one", user_id=self.user.id, team_id=self.team.id) self.collection_one.save() self.collection_two = Collection(name="collection two", user_id=self.user.id) self.collection_two.save() def test_get_dashboard(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') response = self.client.get('/dashboard') self.assert_template_used('dashboard.html') self.assert200(response) def test_get_dashboard_unauthenticated(self): response = self.client.get('/dashboard') self.assertEqual(response.status_code, 302) def test_get_team_view(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') response = self.client.get('/team') self.assert_template_used('team.html') self.assert200(response) def test_get_team_unauthorized(self): response = self.client.get('/team') self.assertEqual(response.status_code, 302) def test_get_collection_view(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') response = self.client.get('/collections') self.assert_template_used('collections.html') self.assert200(response) def test_get_collection_unauthorized(self): response = self.client.get('/collections') self.assertEqual(response.status_code, 302) def test_get_collections_correct_user_successful(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') response = self.client.get('/collections') self.assertEqual(response.status_code, 200) self.assertTrue(self.get_context_variable('context')['collections']) self.assertListEqual(self.get_context_variable('context')['collections'], [self.collection_one, self.collection_two]) def test_get_collections_different_user_no_result(self): another_user_payload = { "fullName": "<NAME>", "email": "<EMAIL>", "imageUrl": "another_image_random" } self.client.post('/auth', data=json.dumps(another_user_payload), content_type='application/json') response = self.client.get('/collections') self.assertEqual(response.status_code, 200) self.assertFalse(self.get_context_variable('context')['collections']) self.assertListEqual(self.get_context_variable('context')['collections'], []) def test_post_collections_unauthorized(self): response = self.client.post('/collections') self.assertEqual(response.status_code, 302) def test_post_collection_no_team_successful(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') response = self.client.post('/collections', data=dict(team="none", collection="this is a test collection")) self.assertEqual(response.status_code, 200) self.assertTrue(self.get_context_variable('context')['collections']) self.assertEqual(len(self.get_context_variable('context')['collections']), 3) def test_post_collection_with_team_successful(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') response = self.client.post('/collections', data=dict(team=self.team.name, collection="this is a test collection")) self.assertEqual(response.status_code, 200) self.assertTrue(self.get_context_variable('context')['collections']) self.assertEqual(len(self.get_context_variable('context')['collections']), 3) def test_post_collection_duplicate_name_with_team(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') response = self.client.post('/collections', data=dict(team=self.team.name, collection="collection one")) self.assertEqual(response.status_code, 200) self.assertEqual(response.data, b'duplicate_collection') def test_post_collection_duplicate_name_no_team(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') response = self.client.post('/collections', data=dict(team="none", collection="collection one")) self.assertEqual(response.status_code, 200) self.assertEqual(response.data, b'duplicate_collection') def test_delete_collection_unauthorized(self): response = self.client.delete('/collections') self.assertEqual(response.status_code, 302) def test_delete_collection_successful(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') response = self.client.delete('/collections?id={}'.format(self.collection_one.id)) self.assertEqual(response.status_code, 200) self.assertTrue(self.get_context_variable('context')['collections']) self.assertEqual(len(self.get_context_variable('context')['collections']), 1) self.assertListEqual(self.get_context_variable('context')['collections'], [self.collection_two]) def test_post_check(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') collection = Collection(name='Test Collection', user_id=self.user.id) collection.save() old_number_of_checks = len(collection.requests) self.checks[0]['id'] = "" response = self.client.post( f'/collection-details/{collection.id}/update', data=json.dumps(self.checks), content_type='application/json') self.assertEqual(response.status_code, 200) new_number_of_checks = len(collection.requests) self.assertEqual(new_number_of_checks, old_number_of_checks + 1) def test_update_check(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') collection = Collection(name='Test Collection', user_id=self.user.id) collection.save() request = Request( collection_id=collection.id, method='GET', url='https://test.com', ) request.save() old_number_of_headers = len(request.headers) self.checks[0]['id'] = f"{request.id}" response = self.client.post( f'/collection-details/{collection.id}/update', data=json.dumps(self.checks), content_type='application/json') self.assertEqual(response.status_code, 200) new_number_of_headers = len(request.headers) self.assertEqual(new_number_of_headers, old_number_of_headers + 1) def test_fetch_collection_details(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') collection = Collection(name='Test Collection', user_id=self.user.id) collection.save() response = self.client.get(f'/collection-details/{collection.id}') self.assertEqual(response.status_code, 200) self.assertTrue('checks' in self.get_context_variable('context')) self.assertTrue('results' in self.get_context_variable('context')) self.assertEqual(self.get_context_variable('context')['collection_name'], collection.name) def test_post_check_with_duplicate_method_and_url(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') collection = Collection(name='Test Collection', user_id=self.user.id) collection.save() request = Request( collection_id=collection.id, method='GET', url='https://test.com', ) request.save() old_number_of_checks = len(collection.requests) self.checks[0][''] = f"{request.id}" self.checks[0]['method'] = 'GET' self.checks[0]['url'] = 'https://test.com' response = self.client.post( f'/collection-details/{collection.id}/update', data=json.dumps(self.checks), content_type='application/json') self.assertEqual(response.status_code, 200) new_number_of_checks = len(collection.requests) self.assertEqual(old_number_of_checks, new_number_of_checks) self.assertTrue((json.loads(response.data))['errors']) def test_post_duplicate_header(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') collection = Collection(name='Test Collection', user_id=self.user.id) collection.save() request = Request( collection_id=collection.id, method='GET', url='https://lmap-staging-test.andela.com/api/v1/careers', ) request.save() header = Header(key="Token", value="<PASSWORD>Token", request_id=request.id) header.save() old_number_of_headers = len(request.headers) self.checks[0]['id'] = f"{request.id}" response = self.client.post( f'/collection-details/{collection.id}/update', data=json.dumps(self.checks), content_type='application/json') self.assertEqual(response.status_code, 200) new_number_of_headers = len(request.headers) self.assertEqual(old_number_of_headers, new_number_of_headers) self.assertTrue((json.loads(response.data))['errors']) def test_post_duplicate_assertion(self): self.client.post('/auth', data=json.dumps(user_payload), content_type='application/json') collection = Collection(name='Test Collection', user_id=self.user.id) collection.save() request = Request( collection_id=collection.id, method='GET', url='https://lmap-staging-test.andela.com/api/v1/careers', ) request.save() assertion = RequestAssertion( assertion_type='Status Code', comparison='equal (number)', value=200, request_id=request.id ) assertion.save() old_number_of_assertions = len(request.assertions) self.checks[0]['id'] = f"{request.id}" response = self.client.post( f'/collection-details/{collection.id}/update', data=json.dumps(self.checks), content_type='application/json') self.assertEqual(response.status_code, 200) new_number_of_assertions = len(request.assertions) self.assertEqual(old_number_of_assertions, new_number_of_assertions) self.assertTrue((json.loads(response.data))['errors'])
none
1
2.439548
2
lib/pytan/exceptions.py
netsec/pytan
1
6619563
# -*- mode: Python; tab-width: 4; indent-tabs-mode: nil; -*- # ex: set tabstop=4 # Please do not change the two lines above. See PEP 8, PEP 263. """Provides exceptions for the :mod:`pytan` module.""" import sys # disable python from creating .pyc files everywhere sys.dont_write_bytecode = True class HandlerError(Exception): """Exception thrown for errors in :mod:`pytan.handler`""" pass class HumanParserError(Exception): """Exception thrown for errors while parsing human strings from :mod:`pytan.handler`""" pass class DefinitionParserError(Exception): """Exception thrown for errors while parsing definitions from :mod:`pytan.handler`""" pass class RunFalse(Exception): """Exception thrown when run=False from :func:`pytan.handler.Handler.deploy_action`""" pass class PytanHelp(Exception): """Exception thrown when printing out help""" pass class PollingError(Exception): """Exception thrown for errors in :mod:`pytan.polling`""" pass class TimeoutException(Exception): """Exception thrown for timeout errors in :mod:`pytan.polling`""" pass class HttpError(Exception): """Exception thrown for HTTP errors in :mod:`pytan.sessions`""" pass class AuthorizationError(Exception): """Exception thrown for authorization errors in :mod:`pytan.sessions`""" pass class BadResponseError(Exception): """Exception thrown for BadResponse messages from Tanium in :mod:`pytan.sessions`""" pass class NotFoundError(Exception): """Exception thrown for Not Found messages from Tanium in :mod:`pytan.handler`""" pass class VersionMismatchError(Exception): """Exception thrown for version_check in :mod:`pytan.utils`""" pass class UnsupportedVersionError(Exception): """Exception thrown for version checks in :mod:`pytan.handler`""" pass class ServerSideExportError(Exception): """Exception thrown for server side export errors in :mod:`pytan.handler`""" pass class VersionParseError(Exception): """Exception thrown for server version parsing errors in :mod:`pytan.handler`""" pass class ServerParseError(Exception): """Exception thrown for server parsing errors in :mod:`pytan.handler`""" pass class PickerError(Exception): """Exception thrown for picker errors in :mod:`pytan.handler`""" pass
# -*- mode: Python; tab-width: 4; indent-tabs-mode: nil; -*- # ex: set tabstop=4 # Please do not change the two lines above. See PEP 8, PEP 263. """Provides exceptions for the :mod:`pytan` module.""" import sys # disable python from creating .pyc files everywhere sys.dont_write_bytecode = True class HandlerError(Exception): """Exception thrown for errors in :mod:`pytan.handler`""" pass class HumanParserError(Exception): """Exception thrown for errors while parsing human strings from :mod:`pytan.handler`""" pass class DefinitionParserError(Exception): """Exception thrown for errors while parsing definitions from :mod:`pytan.handler`""" pass class RunFalse(Exception): """Exception thrown when run=False from :func:`pytan.handler.Handler.deploy_action`""" pass class PytanHelp(Exception): """Exception thrown when printing out help""" pass class PollingError(Exception): """Exception thrown for errors in :mod:`pytan.polling`""" pass class TimeoutException(Exception): """Exception thrown for timeout errors in :mod:`pytan.polling`""" pass class HttpError(Exception): """Exception thrown for HTTP errors in :mod:`pytan.sessions`""" pass class AuthorizationError(Exception): """Exception thrown for authorization errors in :mod:`pytan.sessions`""" pass class BadResponseError(Exception): """Exception thrown for BadResponse messages from Tanium in :mod:`pytan.sessions`""" pass class NotFoundError(Exception): """Exception thrown for Not Found messages from Tanium in :mod:`pytan.handler`""" pass class VersionMismatchError(Exception): """Exception thrown for version_check in :mod:`pytan.utils`""" pass class UnsupportedVersionError(Exception): """Exception thrown for version checks in :mod:`pytan.handler`""" pass class ServerSideExportError(Exception): """Exception thrown for server side export errors in :mod:`pytan.handler`""" pass class VersionParseError(Exception): """Exception thrown for server version parsing errors in :mod:`pytan.handler`""" pass class ServerParseError(Exception): """Exception thrown for server parsing errors in :mod:`pytan.handler`""" pass class PickerError(Exception): """Exception thrown for picker errors in :mod:`pytan.handler`""" pass
en
0.501491
# -*- mode: Python; tab-width: 4; indent-tabs-mode: nil; -*- # ex: set tabstop=4 # Please do not change the two lines above. See PEP 8, PEP 263. Provides exceptions for the :mod:`pytan` module. # disable python from creating .pyc files everywhere Exception thrown for errors in :mod:`pytan.handler` Exception thrown for errors while parsing human strings from :mod:`pytan.handler` Exception thrown for errors while parsing definitions from :mod:`pytan.handler` Exception thrown when run=False from :func:`pytan.handler.Handler.deploy_action` Exception thrown when printing out help Exception thrown for errors in :mod:`pytan.polling` Exception thrown for timeout errors in :mod:`pytan.polling` Exception thrown for HTTP errors in :mod:`pytan.sessions` Exception thrown for authorization errors in :mod:`pytan.sessions` Exception thrown for BadResponse messages from Tanium in :mod:`pytan.sessions` Exception thrown for Not Found messages from Tanium in :mod:`pytan.handler` Exception thrown for version_check in :mod:`pytan.utils` Exception thrown for version checks in :mod:`pytan.handler` Exception thrown for server side export errors in :mod:`pytan.handler` Exception thrown for server version parsing errors in :mod:`pytan.handler` Exception thrown for server parsing errors in :mod:`pytan.handler` Exception thrown for picker errors in :mod:`pytan.handler`
2.467365
2
test_project/settings.py
haavikko/django-trans-history
0
6619564
# -*- coding: utf-8 -*- # Settings for running the test application testcases from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from future import standard_library standard_library.install_aliases() from builtins import * import os import sys DEBUG = True TEMPLATE_DEBUG = DEBUG PROJECT_ROOT = os.path.normpath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(PROJECT_ROOT, '..')) ADMINS = ( # ('<NAME>', '<EMAIL>'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'personnel', # Or path to database file if using sqlite3. 'USER': 'personnel', # Not used with sqlite3. 'PASSWORD': '<PASSWORD>', # Not used with sqlite3. 'PORT': '5432', 'HOST': 'localhost', } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'Europe/Helsinki' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = PROJECT_ROOT + '/media/' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = '/media/' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/media/admin/' # Make this unique, and don't share it with anybody. SECRET_KEY = '<KEY>' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'personnel.urls' ''' TEMPLATE_DIRS = ( PROJECT_ROOT + "/personnel/templates/" ) ''' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'DIRS': [ os.path.join(PROJECT_ROOT, '/personnel/templates/'), ], 'OPTIONS': { # 'debug': DEBUG, 'context_processors': ( 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.i18n', 'django.template.context_processors.media', # not needed? 'django.template.context_processors.static', # not needed? 'django.template.context_processors.tz', # not needed? 'django.template.context_processors.csrf', 'django.contrib.messages.context_processors.messages', 'ws.dws.context_processors.django_conf_settings', ) } }, ] INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'personnel', 'transhistory', 'cli_query', # for querying objects from command line 'django_nose', # testing nose test runner ) TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.auth', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.request', ) LOGIN_URL = "/login" # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'postgres':{ 'level':'DEBUG', 'class':'transhistory.db_log_util.PostgresLogHandler', 'formatter': 'simple' }, 'console':{ 'level':'DEBUG', 'class':'logging.StreamHandler', 'formatter': 'simple' }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, 'personnel': { 'handlers': ['console', 'postgres'], # change in real use 'level': 'DEBUG', 'propagate': True, }, 'transhistory': { 'handlers': ['console', 'postgres'], # change in real use 'level': 'DEBUG', 'propagate': True, }, } }
# -*- coding: utf-8 -*- # Settings for running the test application testcases from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from future import standard_library standard_library.install_aliases() from builtins import * import os import sys DEBUG = True TEMPLATE_DEBUG = DEBUG PROJECT_ROOT = os.path.normpath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(PROJECT_ROOT, '..')) ADMINS = ( # ('<NAME>', '<EMAIL>'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'personnel', # Or path to database file if using sqlite3. 'USER': 'personnel', # Not used with sqlite3. 'PASSWORD': '<PASSWORD>', # Not used with sqlite3. 'PORT': '5432', 'HOST': 'localhost', } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'Europe/Helsinki' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = PROJECT_ROOT + '/media/' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = '/media/' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/media/admin/' # Make this unique, and don't share it with anybody. SECRET_KEY = '<KEY>' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'personnel.urls' ''' TEMPLATE_DIRS = ( PROJECT_ROOT + "/personnel/templates/" ) ''' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'DIRS': [ os.path.join(PROJECT_ROOT, '/personnel/templates/'), ], 'OPTIONS': { # 'debug': DEBUG, 'context_processors': ( 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.i18n', 'django.template.context_processors.media', # not needed? 'django.template.context_processors.static', # not needed? 'django.template.context_processors.tz', # not needed? 'django.template.context_processors.csrf', 'django.contrib.messages.context_processors.messages', 'ws.dws.context_processors.django_conf_settings', ) } }, ] INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'personnel', 'transhistory', 'cli_query', # for querying objects from command line 'django_nose', # testing nose test runner ) TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.auth', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.request', ) LOGIN_URL = "/login" # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'postgres':{ 'level':'DEBUG', 'class':'transhistory.db_log_util.PostgresLogHandler', 'formatter': 'simple' }, 'console':{ 'level':'DEBUG', 'class':'logging.StreamHandler', 'formatter': 'simple' }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, 'personnel': { 'handlers': ['console', 'postgres'], # change in real use 'level': 'DEBUG', 'propagate': True, }, 'transhistory': { 'handlers': ['console', 'postgres'], # change in real use 'level': 'DEBUG', 'propagate': True, }, } }
en
0.726219
# -*- coding: utf-8 -*- # Settings for running the test application testcases # ('<NAME>', '<EMAIL>'), # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. # Or path to database file if using sqlite3. # Not used with sqlite3. # Not used with sqlite3. # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". # Make this unique, and don't share it with anybody. # List of callables that know how to import templates from various sources. TEMPLATE_DIRS = ( PROJECT_ROOT + "/personnel/templates/" ) # 'debug': DEBUG, # not needed? 'django.template.context_processors.static', # not needed? 'django.template.context_processors.tz', # not needed? 'django.template.context_processors.csrf', # for querying objects from command line # testing nose test runner # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. # change in real use # change in real use
1.869959
2
assignments/p2/src/create_wordlength_eval_data.py
stanford-cs324/winter2022
8
6619565
from pathlib import Path import numpy as np import json if __name__ == "__main__": num_examples = 50 max_words = 30 for seed in range(5): np.random.seed(seed) num_words_ls = np.random.randint(low=2, high=max_words+1, size=num_examples) with open(f'wordlength_eval_data/wordlength_eval_data_{seed}.json', 'w') as f: for i in range(num_examples): num_words = num_words_ls[i] prefix = f"<len> {num_words} <text>" line = json.dumps({'text': prefix, 'num_words': str(num_words)}) if i < num_examples: line += '\n' f.write(line)
from pathlib import Path import numpy as np import json if __name__ == "__main__": num_examples = 50 max_words = 30 for seed in range(5): np.random.seed(seed) num_words_ls = np.random.randint(low=2, high=max_words+1, size=num_examples) with open(f'wordlength_eval_data/wordlength_eval_data_{seed}.json', 'w') as f: for i in range(num_examples): num_words = num_words_ls[i] prefix = f"<len> {num_words} <text>" line = json.dumps({'text': prefix, 'num_words': str(num_words)}) if i < num_examples: line += '\n' f.write(line)
none
1
2.877708
3
app/main/views.py
CheboiDerrick/flask-blog-app
0
6619566
<reponame>CheboiDerrick/flask-blog-app from flask import render_template, redirect, url_for,abort,request from . import main from flask_login import login_required,current_user from ..models import User,Blog,Comment,Upvote,Downvote from .forms import UpdateProfile,BlogForm,CommentForm from .. import db,photos from sqlalchemy import desc from app.request import get_quotes @main.route('/') def index(): blogs = Blog.query.order_by(desc(Blog.time)).all() categories = Blog.query.with_entities(Blog.category) categories = [r for (r,) in categories] quote=get_quotes() title='Blogs | Home' return render_template('index.html', blogs = blogs, categories=categories, title=title, quote=quote) @main.route('/blogs/<category_name>') def category(category_name): category = Blog.query.filter_by(category=category_name).all() categories = Blog.query.with_entities(Blog.category) categories = [r for (r,) in categories] title=f'{category_name}' return render_template('category.html', category = category, title=title, categories=categories, category_name=category_name) @main.route('/new/blogpost', methods = ['POST','GET']) @login_required def new_blog(): form = BlogForm() categories = Blog.query.with_entities(Blog.category) categories = [r for (r,) in categories] if form.validate_on_submit(): title = form.title.data post = form.post.data category = form.category.data user_id = current_user new_blog_object = Blog(post=post,user_id=current_user._get_current_object().id,category=category,title=title) new_blog_object.save_blog () return redirect(url_for('main.index')) return render_template('new_blog.html', categories=categories,form = form) @main.route('/comment/<int:blog_id>', methods = ['POST','GET']) @login_required def comment(blog_id): form = CommentForm() blog = Blog.query.get(blog_id) all_comments = Comment.query.filter_by(blog_id = blog_id).all() categories = Blog.query.with_entities(Blog.category) categories = [r for (r,) in categories] if form.validate_on_submit(): comment = form.comment.data blog_id = blog_id user_id = current_user._get_current_object().id new_comment = Comment(comment = comment,user_id = user_id,blog_id = blog_id) new_comment.save_c() return redirect(url_for('.comment', blog_id = blog_id)) return render_template('comment.html', form =form, blog = blog,all_comments=all_comments, categories=categories) @main.route('/user/<name>') def profile(name): user = User.query.filter_by(username = name).first() user_id = current_user._get_current_object().id posts = Blog.query.filter_by(user_id = user_id).all() categories = Blog.query.with_entities(Blog.category) categories = [r for (r,) in categories] if user is None: abort(404) return render_template("profile/profile.html", user = user,posts=posts, categories=categories) @main.route('/user/<name>/updateprofile', methods = ['POST','GET']) @login_required def updateprofile(name): form = UpdateProfile() user = User.query.filter_by(username = name).first() categories = Blog.query.with_entities(Blog.category) categories = [r for (r,) in categories] if user == None: abort(404) if form.validate_on_submit(): user.bio = form.bio.data user.save_u() return redirect(url_for('.profile',name = name)) return render_template('profile/update.html',form =form, categories=categories) @main.route('/user/<name>/update/pic',methods= ['POST']) @login_required def update_pic(name): categories = Blog.query.with_entities(Blog.category) categories = [r for (r,) in categories] user = User.query.filter_by(username = name).first() if 'photo' in request.files: filename = photos.save(request.files['photo']) path = f'photos/{filename}' user.profile_pic_path = path db.session.commit() return redirect(url_for('main.profile',name=name, categories=categories)) @main.route('/like/<int:id>',methods = ['POST','GET']) @login_required def like(id): get_blogs = Upvote.get_upvotes(id) valid_string = f'{current_user.id}:{id}' for blog in get_blogs: to_str = f'{blog}' print(valid_string+" "+to_str) if valid_string == to_str: return redirect(url_for('main.index',id=id)) else: continue new_vote = Upvote(user = current_user, blog_id=id) new_vote.save() return redirect(url_for('main.index',id=id)) @main.route('/dislike/<int:id>',methods = ['POST','GET']) @login_required def dislike(id): blog = Downvote.get_downvotes(id) valid_string = f'{current_user.id}:{id}' for p in blog: to_str = f'{p}' print(valid_string+" "+to_str) if valid_string == to_str: return redirect(url_for('main.index',id=id)) else: continue new_downvote = Downvote(user = current_user, blog_id=id) new_downvote.save() return redirect(url_for('main.index',id = id))
from flask import render_template, redirect, url_for,abort,request from . import main from flask_login import login_required,current_user from ..models import User,Blog,Comment,Upvote,Downvote from .forms import UpdateProfile,BlogForm,CommentForm from .. import db,photos from sqlalchemy import desc from app.request import get_quotes @main.route('/') def index(): blogs = Blog.query.order_by(desc(Blog.time)).all() categories = Blog.query.with_entities(Blog.category) categories = [r for (r,) in categories] quote=get_quotes() title='Blogs | Home' return render_template('index.html', blogs = blogs, categories=categories, title=title, quote=quote) @main.route('/blogs/<category_name>') def category(category_name): category = Blog.query.filter_by(category=category_name).all() categories = Blog.query.with_entities(Blog.category) categories = [r for (r,) in categories] title=f'{category_name}' return render_template('category.html', category = category, title=title, categories=categories, category_name=category_name) @main.route('/new/blogpost', methods = ['POST','GET']) @login_required def new_blog(): form = BlogForm() categories = Blog.query.with_entities(Blog.category) categories = [r for (r,) in categories] if form.validate_on_submit(): title = form.title.data post = form.post.data category = form.category.data user_id = current_user new_blog_object = Blog(post=post,user_id=current_user._get_current_object().id,category=category,title=title) new_blog_object.save_blog () return redirect(url_for('main.index')) return render_template('new_blog.html', categories=categories,form = form) @main.route('/comment/<int:blog_id>', methods = ['POST','GET']) @login_required def comment(blog_id): form = CommentForm() blog = Blog.query.get(blog_id) all_comments = Comment.query.filter_by(blog_id = blog_id).all() categories = Blog.query.with_entities(Blog.category) categories = [r for (r,) in categories] if form.validate_on_submit(): comment = form.comment.data blog_id = blog_id user_id = current_user._get_current_object().id new_comment = Comment(comment = comment,user_id = user_id,blog_id = blog_id) new_comment.save_c() return redirect(url_for('.comment', blog_id = blog_id)) return render_template('comment.html', form =form, blog = blog,all_comments=all_comments, categories=categories) @main.route('/user/<name>') def profile(name): user = User.query.filter_by(username = name).first() user_id = current_user._get_current_object().id posts = Blog.query.filter_by(user_id = user_id).all() categories = Blog.query.with_entities(Blog.category) categories = [r for (r,) in categories] if user is None: abort(404) return render_template("profile/profile.html", user = user,posts=posts, categories=categories) @main.route('/user/<name>/updateprofile', methods = ['POST','GET']) @login_required def updateprofile(name): form = UpdateProfile() user = User.query.filter_by(username = name).first() categories = Blog.query.with_entities(Blog.category) categories = [r for (r,) in categories] if user == None: abort(404) if form.validate_on_submit(): user.bio = form.bio.data user.save_u() return redirect(url_for('.profile',name = name)) return render_template('profile/update.html',form =form, categories=categories) @main.route('/user/<name>/update/pic',methods= ['POST']) @login_required def update_pic(name): categories = Blog.query.with_entities(Blog.category) categories = [r for (r,) in categories] user = User.query.filter_by(username = name).first() if 'photo' in request.files: filename = photos.save(request.files['photo']) path = f'photos/{filename}' user.profile_pic_path = path db.session.commit() return redirect(url_for('main.profile',name=name, categories=categories)) @main.route('/like/<int:id>',methods = ['POST','GET']) @login_required def like(id): get_blogs = Upvote.get_upvotes(id) valid_string = f'{current_user.id}:{id}' for blog in get_blogs: to_str = f'{blog}' print(valid_string+" "+to_str) if valid_string == to_str: return redirect(url_for('main.index',id=id)) else: continue new_vote = Upvote(user = current_user, blog_id=id) new_vote.save() return redirect(url_for('main.index',id=id)) @main.route('/dislike/<int:id>',methods = ['POST','GET']) @login_required def dislike(id): blog = Downvote.get_downvotes(id) valid_string = f'{current_user.id}:{id}' for p in blog: to_str = f'{p}' print(valid_string+" "+to_str) if valid_string == to_str: return redirect(url_for('main.index',id=id)) else: continue new_downvote = Downvote(user = current_user, blog_id=id) new_downvote.save() return redirect(url_for('main.index',id = id))
none
1
2.4979
2
proxydek/web/sketch_view.py
tpott/pub_musings
0
6619567
# sketch_view.py # <NAME> # Sun Jan 10 16:05:30 PST 2016 from base import BaseCardHandler class SketchCardHandler(BaseCardHandler): def renderCard(self, card): # TODO copy card into a temp variable, and add values to that if card['pt_divider'] != '': card['power_float'] = """ <div id="powerFloat" class="bordered" > <span class="innerText" style="float: right; font-size: 9pt; margin-right: 3px;">%(power)s%(pt_divider)s%(toughness)s</span> </div> """ % card elif 'loyalty' in card and card['loyalty'] is not None: card['power_float'] = """ <div id="powerFloat" class="bordered" > <span class="innerText" style="float: right; font-size: 9pt; margin-right: 3px;">%(loyalty)d</span> </div> """ % card else: card['power_float'] = '' if len(card['text']) + len(card['flavor']) > 340: card['text_section'] = """ <div class="bordered inner" style="top: 4px; height: 87px;"> <span class="innerText" style="float: left; font-size: 6pt"><div>%(text)s</div></span> <span class="innerText" style="float: left; font-style: italic; font-size: 5pt;">%(flavor)s</span> </div> """ % card elif len(card['text']) + len(card['flavor']) > 230: card['text_section'] = """ <div class="bordered inner" style="top: 4px; height: 87px;"> <span class="innerText" style="float: left; font-size: 7pt"><div>%(text)s</div></span> <span class="innerText" style="float: left; font-style: italic; font-size: 6pt;">%(flavor)s</span> </div> """ % card else: card['text_section'] = """ <div class="bordered inner" style="top: 4px; height: 87px;"> <span class="innerText" style="float: left; font-size: 8pt"><div>%(text)s</div></span> <span class="innerText" style="float: left; font-style: italic; font-size: 7pt;">%(flavor)s</span> </div> """ % card # Passes in card via `%` return """ <!-- 2.50" ==> 223px, 3.50" ==> 311px --> <!-- actual ==> 203px, 291px --> <div class="bordered" style="width: 203px; height: 291px; clear: left; float: left;"> <!-- name and cost --> <div class="bordered inner" style="top: 5px; height: 18px; font-size: 9pt;"> <span class="innerText" style="float: left; font-size: 9pt;">%(name)s</span> <span class="innerText" style="float: right; font-size: 8pt;">%(manaCost)s</span> </div> <!-- photo, top relative to previous div --> <div class="bordered inner" style="top: 2px; height: 135px;"> <!--<img src="%%(art_url)s" />--> </div> <!-- type bar --> <div class="bordered inner" style="top: 3px; height: 17px; font-size: 8pt;"> <span class="innerText" style="float: left;">%(originalType)s</span> <span class="innerText" style="float: right; margin-right: 3px;">%(set_id)s</span> </div> <!-- text section --> %(text_section)s <!-- why does the `top` attribute need to keep increasing? --> <!-- copyright, index, power + toughness --> <div class="bordered inner" style="top: 5px; height: 12px;"> <span class="innerText" style="margin: 3px; float: left; font-size: 5pt;">%(set_id)s-%(card_id)s %(artist)s</span> </div> %(power_float)s </div> """ % card def renderFooterLinks(self, card): # Passes in card via `%` return """ <br> <div style="float: left;"> <a href="%(prev_sketch_url)s">Previous</a> </div> <!-- the destination page may not exist --> <div style="padding-left: 180px;"> <a href="%(next_sketch_url)s">Next</a> </div> """ % card def renderWizardsCard(self, card): # TODO width and height should be unified return """<img style="width: 203px; height: 291px;" src="%(url)s" />""" % card #return """<img style="padding-left: 5px;" src="%(url)s" />""" % card def renderPageCSS(self): return """ <style> tr, td, table { padding: 0px; border-spacing: 0px; } .bordered { border: 1px solid black; color: black; } .inner { position: relative; left: 5px; width: 193px; } .innerText { margin-left: 5px; } #powerFloat { position: relative; width: 24px; height: 15px; float: right; right: 3px; bottom: 20px; background: white; } </style> """ def get(self, set_id, card_id, card_sub_id): if card_sub_id is None: # Does this make sense as the default sub ID? card_sub_id = '0' try: card_index = int(card_id) except Exception: self.fourOhFour("\"%d\" not an int, in set %s" % (index, set_id)) return if set_id not in self.db['cards']: self.fourOhFour("\"%s\" not a valid set code name" % (set_id)) return if card_index not in self.db['cards'][set_id]: self.fourOhFour( "\"%d\" not a valid index in set %s" % (card_index, set_id) ) return if card_sub_id not in self.db['cards'][set_id][card_index]: self.fourOhFour( "\"%s\" not a valid sub index in set %s-%d" % (card_sub_id, set_id, card_index) ) return print("200 GET %s %s" % (self.request.path, "SketchCardHandler")) # This is terrible HTML self.write(self.renderPageCSS()) card = self.fetchCard(set_id, card_index, card_sub_id) if card is None: self.fourOhFour("Unexpected None from %s-%s" % (set_id, card_id)) return self.write(self.renderCard(card)) self.write(self.renderWizardsCard(card)) self.write(self.renderFooterLinks(card)) # return get
# sketch_view.py # <NAME> # Sun Jan 10 16:05:30 PST 2016 from base import BaseCardHandler class SketchCardHandler(BaseCardHandler): def renderCard(self, card): # TODO copy card into a temp variable, and add values to that if card['pt_divider'] != '': card['power_float'] = """ <div id="powerFloat" class="bordered" > <span class="innerText" style="float: right; font-size: 9pt; margin-right: 3px;">%(power)s%(pt_divider)s%(toughness)s</span> </div> """ % card elif 'loyalty' in card and card['loyalty'] is not None: card['power_float'] = """ <div id="powerFloat" class="bordered" > <span class="innerText" style="float: right; font-size: 9pt; margin-right: 3px;">%(loyalty)d</span> </div> """ % card else: card['power_float'] = '' if len(card['text']) + len(card['flavor']) > 340: card['text_section'] = """ <div class="bordered inner" style="top: 4px; height: 87px;"> <span class="innerText" style="float: left; font-size: 6pt"><div>%(text)s</div></span> <span class="innerText" style="float: left; font-style: italic; font-size: 5pt;">%(flavor)s</span> </div> """ % card elif len(card['text']) + len(card['flavor']) > 230: card['text_section'] = """ <div class="bordered inner" style="top: 4px; height: 87px;"> <span class="innerText" style="float: left; font-size: 7pt"><div>%(text)s</div></span> <span class="innerText" style="float: left; font-style: italic; font-size: 6pt;">%(flavor)s</span> </div> """ % card else: card['text_section'] = """ <div class="bordered inner" style="top: 4px; height: 87px;"> <span class="innerText" style="float: left; font-size: 8pt"><div>%(text)s</div></span> <span class="innerText" style="float: left; font-style: italic; font-size: 7pt;">%(flavor)s</span> </div> """ % card # Passes in card via `%` return """ <!-- 2.50" ==> 223px, 3.50" ==> 311px --> <!-- actual ==> 203px, 291px --> <div class="bordered" style="width: 203px; height: 291px; clear: left; float: left;"> <!-- name and cost --> <div class="bordered inner" style="top: 5px; height: 18px; font-size: 9pt;"> <span class="innerText" style="float: left; font-size: 9pt;">%(name)s</span> <span class="innerText" style="float: right; font-size: 8pt;">%(manaCost)s</span> </div> <!-- photo, top relative to previous div --> <div class="bordered inner" style="top: 2px; height: 135px;"> <!--<img src="%%(art_url)s" />--> </div> <!-- type bar --> <div class="bordered inner" style="top: 3px; height: 17px; font-size: 8pt;"> <span class="innerText" style="float: left;">%(originalType)s</span> <span class="innerText" style="float: right; margin-right: 3px;">%(set_id)s</span> </div> <!-- text section --> %(text_section)s <!-- why does the `top` attribute need to keep increasing? --> <!-- copyright, index, power + toughness --> <div class="bordered inner" style="top: 5px; height: 12px;"> <span class="innerText" style="margin: 3px; float: left; font-size: 5pt;">%(set_id)s-%(card_id)s %(artist)s</span> </div> %(power_float)s </div> """ % card def renderFooterLinks(self, card): # Passes in card via `%` return """ <br> <div style="float: left;"> <a href="%(prev_sketch_url)s">Previous</a> </div> <!-- the destination page may not exist --> <div style="padding-left: 180px;"> <a href="%(next_sketch_url)s">Next</a> </div> """ % card def renderWizardsCard(self, card): # TODO width and height should be unified return """<img style="width: 203px; height: 291px;" src="%(url)s" />""" % card #return """<img style="padding-left: 5px;" src="%(url)s" />""" % card def renderPageCSS(self): return """ <style> tr, td, table { padding: 0px; border-spacing: 0px; } .bordered { border: 1px solid black; color: black; } .inner { position: relative; left: 5px; width: 193px; } .innerText { margin-left: 5px; } #powerFloat { position: relative; width: 24px; height: 15px; float: right; right: 3px; bottom: 20px; background: white; } </style> """ def get(self, set_id, card_id, card_sub_id): if card_sub_id is None: # Does this make sense as the default sub ID? card_sub_id = '0' try: card_index = int(card_id) except Exception: self.fourOhFour("\"%d\" not an int, in set %s" % (index, set_id)) return if set_id not in self.db['cards']: self.fourOhFour("\"%s\" not a valid set code name" % (set_id)) return if card_index not in self.db['cards'][set_id]: self.fourOhFour( "\"%d\" not a valid index in set %s" % (card_index, set_id) ) return if card_sub_id not in self.db['cards'][set_id][card_index]: self.fourOhFour( "\"%s\" not a valid sub index in set %s-%d" % (card_sub_id, set_id, card_index) ) return print("200 GET %s %s" % (self.request.path, "SketchCardHandler")) # This is terrible HTML self.write(self.renderPageCSS()) card = self.fetchCard(set_id, card_index, card_sub_id) if card is None: self.fourOhFour("Unexpected None from %s-%s" % (set_id, card_id)) return self.write(self.renderCard(card)) self.write(self.renderWizardsCard(card)) self.write(self.renderFooterLinks(card)) # return get
en
0.258211
# sketch_view.py # <NAME> # Sun Jan 10 16:05:30 PST 2016 # TODO copy card into a temp variable, and add values to that <div id="powerFloat" class="bordered" > <span class="innerText" style="float: right; font-size: 9pt; margin-right: 3px;">%(power)s%(pt_divider)s%(toughness)s</span> </div> <div id="powerFloat" class="bordered" > <span class="innerText" style="float: right; font-size: 9pt; margin-right: 3px;">%(loyalty)d</span> </div> <div class="bordered inner" style="top: 4px; height: 87px;"> <span class="innerText" style="float: left; font-size: 6pt"><div>%(text)s</div></span> <span class="innerText" style="float: left; font-style: italic; font-size: 5pt;">%(flavor)s</span> </div> <div class="bordered inner" style="top: 4px; height: 87px;"> <span class="innerText" style="float: left; font-size: 7pt"><div>%(text)s</div></span> <span class="innerText" style="float: left; font-style: italic; font-size: 6pt;">%(flavor)s</span> </div> <div class="bordered inner" style="top: 4px; height: 87px;"> <span class="innerText" style="float: left; font-size: 8pt"><div>%(text)s</div></span> <span class="innerText" style="float: left; font-style: italic; font-size: 7pt;">%(flavor)s</span> </div> # Passes in card via `%` <!-- 2.50" ==> 223px, 3.50" ==> 311px --> <!-- actual ==> 203px, 291px --> <div class="bordered" style="width: 203px; height: 291px; clear: left; float: left;"> <!-- name and cost --> <div class="bordered inner" style="top: 5px; height: 18px; font-size: 9pt;"> <span class="innerText" style="float: left; font-size: 9pt;">%(name)s</span> <span class="innerText" style="float: right; font-size: 8pt;">%(manaCost)s</span> </div> <!-- photo, top relative to previous div --> <div class="bordered inner" style="top: 2px; height: 135px;"> <!--<img src="%%(art_url)s" />--> </div> <!-- type bar --> <div class="bordered inner" style="top: 3px; height: 17px; font-size: 8pt;"> <span class="innerText" style="float: left;">%(originalType)s</span> <span class="innerText" style="float: right; margin-right: 3px;">%(set_id)s</span> </div> <!-- text section --> %(text_section)s <!-- why does the `top` attribute need to keep increasing? --> <!-- copyright, index, power + toughness --> <div class="bordered inner" style="top: 5px; height: 12px;"> <span class="innerText" style="margin: 3px; float: left; font-size: 5pt;">%(set_id)s-%(card_id)s %(artist)s</span> </div> %(power_float)s </div> # Passes in card via `%` <br> <div style="float: left;"> <a href="%(prev_sketch_url)s">Previous</a> </div> <!-- the destination page may not exist --> <div style="padding-left: 180px;"> <a href="%(next_sketch_url)s">Next</a> </div> # TODO width and height should be unified <img style="width: 203px; height: 291px;" src="%(url)s" /> #return """<img style="padding-left: 5px;" src="%(url)s" />""" % card <style> tr, td, table { padding: 0px; border-spacing: 0px; } .bordered { border: 1px solid black; color: black; } .inner { position: relative; left: 5px; width: 193px; } .innerText { margin-left: 5px; } #powerFloat { position: relative; width: 24px; height: 15px; float: right; right: 3px; bottom: 20px; background: white; } </style> # Does this make sense as the default sub ID? # This is terrible HTML # return get
2.739467
3
f1_2020_db/receiver.py
alastairgarner/f1-2020-db
0
6619568
#! /usr/bin/env python3 import threading import socket import time import datetime from queue import Queue from collections import namedtuple from f1_2020_telemetry.packets import unpack_udp_packet from .utils.packet import PacketParser class PacketReceiver(threading.Thread): """ Docstring """ def __init__(self, port:int = 20777, queue=None, session=None): """Doc""" super().__init__() self.parser = PacketParser(queue=queue, session=session) self._quitflag = True self.socket = None def connect(self, port:int = 20777): """Docstring""" self.socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM) self.socket.bind(("", port)) print(f'Connected on port: {port}') def close(self): """Stop the thread""" if self._quitflag: self._quitflag = True print('PacketReceiver stopped') def run(self): """ Doc """ self._quitflag = False if self.socket is None: self.connect() count = 0 elapsed = 0 timer = time.time() while not self._quitflag: udp_packet = self.socket.recv(2048) packet = unpack_udp_packet(udp_packet) start = time.time() self.parser.parse_packet(packet) elapsed += time.time() - start count += 1 # Print progress once per second duration = time.time() - timer if duration > 1: print(f'Parsed {count} packets in {elapsed} seconds') count = 0; elapsed = 0; timer = time.time()
#! /usr/bin/env python3 import threading import socket import time import datetime from queue import Queue from collections import namedtuple from f1_2020_telemetry.packets import unpack_udp_packet from .utils.packet import PacketParser class PacketReceiver(threading.Thread): """ Docstring """ def __init__(self, port:int = 20777, queue=None, session=None): """Doc""" super().__init__() self.parser = PacketParser(queue=queue, session=session) self._quitflag = True self.socket = None def connect(self, port:int = 20777): """Docstring""" self.socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM) self.socket.bind(("", port)) print(f'Connected on port: {port}') def close(self): """Stop the thread""" if self._quitflag: self._quitflag = True print('PacketReceiver stopped') def run(self): """ Doc """ self._quitflag = False if self.socket is None: self.connect() count = 0 elapsed = 0 timer = time.time() while not self._quitflag: udp_packet = self.socket.recv(2048) packet = unpack_udp_packet(udp_packet) start = time.time() self.parser.parse_packet(packet) elapsed += time.time() - start count += 1 # Print progress once per second duration = time.time() - timer if duration > 1: print(f'Parsed {count} packets in {elapsed} seconds') count = 0; elapsed = 0; timer = time.time()
en
0.466832
#! /usr/bin/env python3 Docstring Doc Docstring Stop the thread Doc # Print progress once per second
2.794266
3
src/apps/core/migrations/0006_add_cloned_lesson_derived_fields.py
HydroLearn/HydroLearn
0
6619569
<reponame>HydroLearn/HydroLearn # -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-12-06 20:16 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('core', '0005_collaboration_table_addition'), ] operations = [ migrations.AddField( model_name='lesson', name='derived_date', field=models.DateTimeField(null=True), ), migrations.AddField( model_name='lesson', name='derived_lesson_creator', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='inspired_lessons', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='lesson', name='derived_lesson_slug', field=models.CharField(default=None, editable=False, max_length=8, null=True), ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-12-06 20:16 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('core', '0005_collaboration_table_addition'), ] operations = [ migrations.AddField( model_name='lesson', name='derived_date', field=models.DateTimeField(null=True), ), migrations.AddField( model_name='lesson', name='derived_lesson_creator', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='inspired_lessons', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='lesson', name='derived_lesson_slug', field=models.CharField(default=None, editable=False, max_length=8, null=True), ), ]
en
0.735056
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-12-06 20:16
1.56242
2
code/distributions.py
JosepLeder/Lekai-Reinforcement-Learning-Notes
2
6619570
<filename>code/distributions.py import torch import torch.nn as nn from utils import init class DiagGaussianDistribution(nn.Module): def __init__(self, num_inputs, num_outputs): super(DiagGaussianDistribution, self).__init__() init_ = lambda m: init(m, nn.init.orthogonal_, lambda x: nn.init. constant_(x, 0)) self.fc_mean = init_(nn.Linear(num_inputs, num_outputs)) self._bias = nn.Parameter(torch.zeros(num_outputs).unsqueeze(1)) def forward(self, x): action_mean = self.fc_mean(x) # An ugly hack for my KFAC implementation. zeros = torch.zeros(action_mean.size()) if zeros.dim() == 2: bias = self._bias.t().view(1, -1) else: bias = self._bias.t().view(1, -1, 1, 1) action_logstd = zeros + bias return FixedNormal(action_mean, action_logstd.exp()) # Normal class FixedNormal(torch.distributions.Normal): def log_probs(self, actions): return super().log_prob(actions).sum(-1, keepdim=True) def entrop(self): return super.entropy().sum(-1) def mode(self): return self.mean
<filename>code/distributions.py import torch import torch.nn as nn from utils import init class DiagGaussianDistribution(nn.Module): def __init__(self, num_inputs, num_outputs): super(DiagGaussianDistribution, self).__init__() init_ = lambda m: init(m, nn.init.orthogonal_, lambda x: nn.init. constant_(x, 0)) self.fc_mean = init_(nn.Linear(num_inputs, num_outputs)) self._bias = nn.Parameter(torch.zeros(num_outputs).unsqueeze(1)) def forward(self, x): action_mean = self.fc_mean(x) # An ugly hack for my KFAC implementation. zeros = torch.zeros(action_mean.size()) if zeros.dim() == 2: bias = self._bias.t().view(1, -1) else: bias = self._bias.t().view(1, -1, 1, 1) action_logstd = zeros + bias return FixedNormal(action_mean, action_logstd.exp()) # Normal class FixedNormal(torch.distributions.Normal): def log_probs(self, actions): return super().log_prob(actions).sum(-1, keepdim=True) def entrop(self): return super.entropy().sum(-1) def mode(self): return self.mean
en
0.721375
# An ugly hack for my KFAC implementation. # Normal
2.462319
2
nesta/core/orms/nih_orm.py
anniyanvr/nesta
13
6619571
''' NIH schema ============== The schema for the World RePORTER data. ''' from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.types import INTEGER, JSON, DATETIME, FLOAT from sqlalchemy import Column, Table, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.ext.associationproxy import association_proxy from nesta.core.orms.types import VARCHAR, TEXT def getattr_(entity, attribute): """Either unpack the attribute from every item in the entity if the entity is a list, otherwise just return the attribute from the entity. Returns None if the entity is either None or empty.""" if entity in (None, []): return None if isinstance(entity, list): return [getattr(item, attribute) for item in entity] return getattr(entity, attribute) Base = declarative_base() class Projects(Base): __tablename__ = 'nih_projects' application_id = Column(INTEGER, primary_key=True, autoincrement=False) activity = Column(VARCHAR(3)) administering_ic = Column(VARCHAR(2)) application_type = Column(INTEGER) arra_funded = Column(VARCHAR(1)) award_notice_date = Column(DATETIME) base_core_project_num = Column(VARCHAR(50), index=True) budget_start = Column(DATETIME) budget_end = Column(DATETIME) cfda_code = Column(TEXT) core_project_num = Column(VARCHAR(50), index=True) ed_inst_type = Column(TEXT) foa_number = Column(TEXT) full_project_num = Column(VARCHAR(50), index=True) funding_ics = Column(JSON) funding_mechanism = Column(TEXT) fy = Column(INTEGER, index=True) ic_name = Column(VARCHAR(100), index=True) org_city = Column(VARCHAR(50), index=True) org_country = Column(VARCHAR(50), index=True) org_dept = Column(VARCHAR(100), index=True) org_district = Column(INTEGER) org_duns = Column(JSON) org_fips = Column(VARCHAR(2), index=True) org_ipf_code = Column(INTEGER) org_name = Column(VARCHAR(100), index=True) org_state = Column(VARCHAR(2), index=True) org_zipcode = Column(VARCHAR(10)) phr = Column(TEXT) pi_ids = Column(JSON) pi_names = Column(JSON) program_officer_name = Column(TEXT) project_start = Column(DATETIME, index=True) project_end = Column(DATETIME, index=True) project_terms = Column(JSON) project_title = Column(TEXT) serial_number = Column(VARCHAR(6)) study_section = Column(VARCHAR(4)) study_section_name = Column(TEXT) suffix = Column(VARCHAR(6)) support_year = Column(VARCHAR(2)) direct_cost_amt = Column(INTEGER) indirect_cost_amt = Column(INTEGER) total_cost = Column(INTEGER) subproject_id = Column(INTEGER, index=True) total_cost_sub_project = Column(INTEGER) nih_spending_cats = Column(JSON) # Pseudo-FKs abstract = relationship("Abstracts", uselist=False, foreign_keys=[application_id], primaryjoin=("Projects.application_id==" "Abstracts.application_id")) publications = relationship("LinkTables", uselist=True, foreign_keys=[core_project_num], primaryjoin=("Projects.core_project_num==" "LinkTables.project_number")) patents = relationship("Patents", uselist=True, foreign_keys=[core_project_num], primaryjoin=("Projects.core_project_num==" "Patents.project_id")) clinicalstudies = relationship("ClinicalStudies", uselist=True, foreign_keys=[core_project_num], primaryjoin=("Projects.core_project_num==" "ClinicalStudies.core_project_number")) # Pseudo-fields (populated from relationships) @property def abstract_text(self): return getattr_(self.abstract, "abstract_text") @property def patent_ids(self): return getattr_(self.patents, "patent_id") @property def patent_titles(self): return getattr_(self.patents, "patent_title") @property def pmids(self): return getattr_(self.publications, "pmid") @property def clinicaltrial_ids(self): return getattr_(self.clinicalstudies, "clinicaltrials_gov_id") @property def clinicaltrial_titles(self): return getattr_(self.clinicalstudies, "study") class Abstracts(Base): __tablename__ = 'nih_abstracts' application_id = Column(INTEGER, primary_key=True, autoincrement=False) abstract_text = Column(TEXT) class Publications(Base): __tablename__ = 'nih_publications' pmid = Column(INTEGER, primary_key=True, autoincrement=False) author_name = Column(TEXT) affiliation = Column(TEXT) author_list = Column(JSON) country = Column(VARCHAR(50), index=True) issn = Column(VARCHAR(9)) journal_issue = Column(VARCHAR(75)) journal_title = Column(VARCHAR(400), index=True) journal_title_abbr = Column(VARCHAR(200)) journal_volume = Column(VARCHAR(100)) lang = Column(VARCHAR(3)) page_number = Column(VARCHAR(200)) pub_date = Column(DATETIME) pub_title = Column(VARCHAR(400), index=True) pub_year = Column(INTEGER, index=True) pmc_id = Column(INTEGER, index=True) class Patents(Base): __tablename__ = 'nih_patents' patent_id = Column(VARCHAR(20), primary_key=True) patent_title = Column(TEXT) project_id = Column(VARCHAR(50), index=True) patent_org_name = Column(TEXT) class LinkTables(Base): __tablename__ = 'nih_linktables' pmid = Column(INTEGER, primary_key=True, autoincrement=False) project_number = Column(VARCHAR(50), index=True) class ClinicalStudies(Base): __tablename__ = "nih_clinicalstudies" clinicaltrials_gov_id = Column(VARCHAR(20), primary_key=True) core_project_number = Column(VARCHAR(50), index=True) study = Column(TEXT) study_status = Column(VARCHAR(30), index=True) class PhrVector(Base): """Document vectors for NiH Public Health Relevance (PHR) statements.""" __tablename__ = 'nih_phr_vectors' application_id = Column(INTEGER, ForeignKey(Projects.application_id), autoincrement=False, primary_key=True) vector = Column(JSON) class AbstractVector(Base): """Document vectors for NiH abstracts.""" __tablename__ = 'nih_abstract_vectors' application_id = Column(INTEGER, ForeignKey(Abstracts.application_id), autoincrement=False, primary_key=True) vector = Column(JSON) class TextDuplicate(Base): """Link table to describe for NiH text-field duplicates, which probably imply that projects are related, either formally (if weight > 0.8 they are normally almost exact duplicates of each other) or contextually (if weight > 0.5 it is normally in the same general subject area). The cut-off for inclusion in this table is a weight of 0.5, because the core interest for using this method is to identify texts which are near duplicates, since texts which are contextually similar can also be found by other metrics (topic modelling, etc) and there can be some weird side-effects of using BERT for this; e.g. finding texts with a similar writing style rather than topic. """ __tablename__ = 'nih_duplicates' application_id_1 = Column(INTEGER, ForeignKey(Projects.application_id), autoincrement=False, primary_key=True) application_id_2 = Column(INTEGER, ForeignKey(Projects.application_id), autoincrement=False, primary_key=True) text_field = Column(VARCHAR(8), primary_key=True, index=True) # Either "phr" or "abstract" weight = Column(FLOAT, index=True)
''' NIH schema ============== The schema for the World RePORTER data. ''' from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.types import INTEGER, JSON, DATETIME, FLOAT from sqlalchemy import Column, Table, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.ext.associationproxy import association_proxy from nesta.core.orms.types import VARCHAR, TEXT def getattr_(entity, attribute): """Either unpack the attribute from every item in the entity if the entity is a list, otherwise just return the attribute from the entity. Returns None if the entity is either None or empty.""" if entity in (None, []): return None if isinstance(entity, list): return [getattr(item, attribute) for item in entity] return getattr(entity, attribute) Base = declarative_base() class Projects(Base): __tablename__ = 'nih_projects' application_id = Column(INTEGER, primary_key=True, autoincrement=False) activity = Column(VARCHAR(3)) administering_ic = Column(VARCHAR(2)) application_type = Column(INTEGER) arra_funded = Column(VARCHAR(1)) award_notice_date = Column(DATETIME) base_core_project_num = Column(VARCHAR(50), index=True) budget_start = Column(DATETIME) budget_end = Column(DATETIME) cfda_code = Column(TEXT) core_project_num = Column(VARCHAR(50), index=True) ed_inst_type = Column(TEXT) foa_number = Column(TEXT) full_project_num = Column(VARCHAR(50), index=True) funding_ics = Column(JSON) funding_mechanism = Column(TEXT) fy = Column(INTEGER, index=True) ic_name = Column(VARCHAR(100), index=True) org_city = Column(VARCHAR(50), index=True) org_country = Column(VARCHAR(50), index=True) org_dept = Column(VARCHAR(100), index=True) org_district = Column(INTEGER) org_duns = Column(JSON) org_fips = Column(VARCHAR(2), index=True) org_ipf_code = Column(INTEGER) org_name = Column(VARCHAR(100), index=True) org_state = Column(VARCHAR(2), index=True) org_zipcode = Column(VARCHAR(10)) phr = Column(TEXT) pi_ids = Column(JSON) pi_names = Column(JSON) program_officer_name = Column(TEXT) project_start = Column(DATETIME, index=True) project_end = Column(DATETIME, index=True) project_terms = Column(JSON) project_title = Column(TEXT) serial_number = Column(VARCHAR(6)) study_section = Column(VARCHAR(4)) study_section_name = Column(TEXT) suffix = Column(VARCHAR(6)) support_year = Column(VARCHAR(2)) direct_cost_amt = Column(INTEGER) indirect_cost_amt = Column(INTEGER) total_cost = Column(INTEGER) subproject_id = Column(INTEGER, index=True) total_cost_sub_project = Column(INTEGER) nih_spending_cats = Column(JSON) # Pseudo-FKs abstract = relationship("Abstracts", uselist=False, foreign_keys=[application_id], primaryjoin=("Projects.application_id==" "Abstracts.application_id")) publications = relationship("LinkTables", uselist=True, foreign_keys=[core_project_num], primaryjoin=("Projects.core_project_num==" "LinkTables.project_number")) patents = relationship("Patents", uselist=True, foreign_keys=[core_project_num], primaryjoin=("Projects.core_project_num==" "Patents.project_id")) clinicalstudies = relationship("ClinicalStudies", uselist=True, foreign_keys=[core_project_num], primaryjoin=("Projects.core_project_num==" "ClinicalStudies.core_project_number")) # Pseudo-fields (populated from relationships) @property def abstract_text(self): return getattr_(self.abstract, "abstract_text") @property def patent_ids(self): return getattr_(self.patents, "patent_id") @property def patent_titles(self): return getattr_(self.patents, "patent_title") @property def pmids(self): return getattr_(self.publications, "pmid") @property def clinicaltrial_ids(self): return getattr_(self.clinicalstudies, "clinicaltrials_gov_id") @property def clinicaltrial_titles(self): return getattr_(self.clinicalstudies, "study") class Abstracts(Base): __tablename__ = 'nih_abstracts' application_id = Column(INTEGER, primary_key=True, autoincrement=False) abstract_text = Column(TEXT) class Publications(Base): __tablename__ = 'nih_publications' pmid = Column(INTEGER, primary_key=True, autoincrement=False) author_name = Column(TEXT) affiliation = Column(TEXT) author_list = Column(JSON) country = Column(VARCHAR(50), index=True) issn = Column(VARCHAR(9)) journal_issue = Column(VARCHAR(75)) journal_title = Column(VARCHAR(400), index=True) journal_title_abbr = Column(VARCHAR(200)) journal_volume = Column(VARCHAR(100)) lang = Column(VARCHAR(3)) page_number = Column(VARCHAR(200)) pub_date = Column(DATETIME) pub_title = Column(VARCHAR(400), index=True) pub_year = Column(INTEGER, index=True) pmc_id = Column(INTEGER, index=True) class Patents(Base): __tablename__ = 'nih_patents' patent_id = Column(VARCHAR(20), primary_key=True) patent_title = Column(TEXT) project_id = Column(VARCHAR(50), index=True) patent_org_name = Column(TEXT) class LinkTables(Base): __tablename__ = 'nih_linktables' pmid = Column(INTEGER, primary_key=True, autoincrement=False) project_number = Column(VARCHAR(50), index=True) class ClinicalStudies(Base): __tablename__ = "nih_clinicalstudies" clinicaltrials_gov_id = Column(VARCHAR(20), primary_key=True) core_project_number = Column(VARCHAR(50), index=True) study = Column(TEXT) study_status = Column(VARCHAR(30), index=True) class PhrVector(Base): """Document vectors for NiH Public Health Relevance (PHR) statements.""" __tablename__ = 'nih_phr_vectors' application_id = Column(INTEGER, ForeignKey(Projects.application_id), autoincrement=False, primary_key=True) vector = Column(JSON) class AbstractVector(Base): """Document vectors for NiH abstracts.""" __tablename__ = 'nih_abstract_vectors' application_id = Column(INTEGER, ForeignKey(Abstracts.application_id), autoincrement=False, primary_key=True) vector = Column(JSON) class TextDuplicate(Base): """Link table to describe for NiH text-field duplicates, which probably imply that projects are related, either formally (if weight > 0.8 they are normally almost exact duplicates of each other) or contextually (if weight > 0.5 it is normally in the same general subject area). The cut-off for inclusion in this table is a weight of 0.5, because the core interest for using this method is to identify texts which are near duplicates, since texts which are contextually similar can also be found by other metrics (topic modelling, etc) and there can be some weird side-effects of using BERT for this; e.g. finding texts with a similar writing style rather than topic. """ __tablename__ = 'nih_duplicates' application_id_1 = Column(INTEGER, ForeignKey(Projects.application_id), autoincrement=False, primary_key=True) application_id_2 = Column(INTEGER, ForeignKey(Projects.application_id), autoincrement=False, primary_key=True) text_field = Column(VARCHAR(8), primary_key=True, index=True) # Either "phr" or "abstract" weight = Column(FLOAT, index=True)
en
0.887825
NIH schema ============== The schema for the World RePORTER data. Either unpack the attribute from every item in the entity if the entity is a list, otherwise just return the attribute from the entity. Returns None if the entity is either None or empty. # Pseudo-FKs # Pseudo-fields (populated from relationships) Document vectors for NiH Public Health Relevance (PHR) statements. Document vectors for NiH abstracts. Link table to describe for NiH text-field duplicates, which probably imply that projects are related, either formally (if weight > 0.8 they are normally almost exact duplicates of each other) or contextually (if weight > 0.5 it is normally in the same general subject area). The cut-off for inclusion in this table is a weight of 0.5, because the core interest for using this method is to identify texts which are near duplicates, since texts which are contextually similar can also be found by other metrics (topic modelling, etc) and there can be some weird side-effects of using BERT for this; e.g. finding texts with a similar writing style rather than topic. # Either "phr" or "abstract"
2.235978
2
step_to_stl.py
jdlubrano/cad_volume
9
6619572
import getopt import os import sys from OCC.StlAPI import StlAPI_Writer from OCC.STEPControl import STEPControl_Reader from OCC.IFSelect import IFSelect_RetDone, IFSelect_ItemsByEntity def usage(): print('step_to_stl.py -i source -o dest') sys.exit(2) def convert(source, dest): step_reader = STEPControl_Reader() status = step_reader.ReadFile(source) if status == IFSelect_RetDone: i = 1 ok = False number_of_roots = step_reader.NbRootsForTransfer() while i <= number_of_roots and not ok: ok = step_reader.TransferRoot(i) i += 1 if (not ok): return { 'error': 'Failed to find a suitable root for the STEP file' } shape = step_reader.Shape(1) output = os.path.abspath(dest) stl_ascii = False stl_writer = StlAPI_Writer() stl_writer.SetASCIIMode(stl_ascii) stl_writer.Write(shape, output) print "STL FILE: %s" % output else: print "Error, can't read file: %s" % './demo.stp' def main(argv): try: opts, args = getopt.getopt(argv, "hi:o:", ["infile=", "outfile="]) except getopt.GetoptError: usage() source = None dest = None for opt, arg in opts: if opt in ("-i", "--infile"): source = arg if opt in ("-o", "--outfile"): dest = arg if source != None and dest != None: convert(source, dest) else: usage() sys.exit(0) if __name__ == '__main__': main(sys.argv[1:])
import getopt import os import sys from OCC.StlAPI import StlAPI_Writer from OCC.STEPControl import STEPControl_Reader from OCC.IFSelect import IFSelect_RetDone, IFSelect_ItemsByEntity def usage(): print('step_to_stl.py -i source -o dest') sys.exit(2) def convert(source, dest): step_reader = STEPControl_Reader() status = step_reader.ReadFile(source) if status == IFSelect_RetDone: i = 1 ok = False number_of_roots = step_reader.NbRootsForTransfer() while i <= number_of_roots and not ok: ok = step_reader.TransferRoot(i) i += 1 if (not ok): return { 'error': 'Failed to find a suitable root for the STEP file' } shape = step_reader.Shape(1) output = os.path.abspath(dest) stl_ascii = False stl_writer = StlAPI_Writer() stl_writer.SetASCIIMode(stl_ascii) stl_writer.Write(shape, output) print "STL FILE: %s" % output else: print "Error, can't read file: %s" % './demo.stp' def main(argv): try: opts, args = getopt.getopt(argv, "hi:o:", ["infile=", "outfile="]) except getopt.GetoptError: usage() source = None dest = None for opt, arg in opts: if opt in ("-i", "--infile"): source = arg if opt in ("-o", "--outfile"): dest = arg if source != None and dest != None: convert(source, dest) else: usage() sys.exit(0) if __name__ == '__main__': main(sys.argv[1:])
none
1
2.343881
2
SE/check-srm-iplementations.py
frmichel/vo-support-tools
0
6619573
#!/usr/bin/python # Retrieve the number and size of storage elements available for a VO (defaults to biomed), # sorted by SRM implementation and version. Cumulative values of used and total sizes are # calculated per SRM flavour and version. # # ChangeLog: # 1.0: initial version # 1.1: fix issue in LDAP attributes parsing: AttributeName: value, where the value sometimes # also contains a ':' import sys import os import commands import re from optparse import OptionParser DEFAULT_TOPBDII = "cclcgtopbdii01.in2p3.fr:2170" optParser = OptionParser(version="%prog 1.1", description="""Retrieve the number and size of storage elements available for a VO (defaults to biomed), sorted by SRM implementation and version""") optParser.add_option("--vo", action="store", dest="vo", default="biomed", help="Virtual Organisation to query. Defaults to \"biomed\"") optParser.add_option("--bdii", action="store", dest="bdii", default=DEFAULT_TOPBDII, help="top BDII hostname and port. Defaults to " + DEFAULT_TOPBDII) optParser.add_option("--limit", action="store", dest="limit", default=9999, help="Max number of SE to check. Defaults to all (9999)") # ------------------------------------------------------------------------- # Definitions, global variables # ------------------------------------------------------------------------- (options, args) = optParser.parse_args() VO = options.vo TOPBDII = options.bdii MAX_SE = int(options.limit) # LDAP Request to get the Storage Element info ldapSE = "ldapsearch -x -L -s sub -H ldap://%(TOPBDII)s -b mds-vo-name=local,o=grid \"(&(ObjectClass=GlueSE)(GlueSEUniqueID=%(HOST)s))\" | egrep \"GlueSEImplementationName|GlueSEImplementationVersion\"" # LDAP Request to get the Storage Area info ldapSA = "ldapsearch -x -L -s sub -H ldap://%(TOPBDII)s -b mds-vo-name=local,o=grid \"(&(ObjectClass=GlueSA)(GlueChunkKey=GlueSEUniqueID=%(HOST)s)(|(GlueSAAccessControlBaseRule=VO:%(VO)s*)(GlueSAAccessControlBaseRule=%(VO)s*)))\" | egrep \"GlueSATotalOnlineSize|GlueSAUsedOnlineSize\"" # ------------------------------------------------------------------------- # Program main body # ------------------------------------------------------------------------- # Get the list of SEs from the BDII status, output = commands.getstatusoutput("lcg-infosites --vo " + VO + " space") if status <> 0: print "lcg-infosites error: ", output sys.exit(1) # Build the list of SEs: filter out header lines, and keep only hostnames listSE = [] nbSE = 0 for line in output.splitlines(): if ("Reserved" not in line) and ("Nearline" not in line) and ("----------" not in line): listSE.append(line.split()[-1]) if nbSE > MAX_SE: break; nbSE += 1 # The result is a multidimensional dictionary: # SRM name # 'total': total available size for that SRM implementation, whatever the version # 'used': space used by the VO for that SRM implementation, whatever the version # 'nbOcc': number of SEs with that SRM iplem, whatever the version # SRM implem version # 'total': total available size # 'used': space used by the VO # 'nbOcc': number of SEs with that SRM iplem and version result = {} # Regexp to limit the version number to 3 numbers matchVer = re.compile("^(\w+.\w+.\w+)") # Regexp to match one line of the result of an LDAP request formatted as: "Attribute: value" matchLdapResp = re.compile("^(\w+): (.+)$") # ------------------------------------------------------------------------- # For each SE, run an ldap request to get implementation names/versions and storage sizes for host in listSE: print "Checking SE " + host + "..." statusSE, outputSE = commands.getstatusoutput(ldapSE % {'TOPBDII': TOPBDII, 'HOST': host}) statusSA, outputSA = commands.getstatusoutput(ldapSA % {'TOPBDII': TOPBDII, 'HOST': host, 'VO': VO}) if statusSE <> 0 or statusSA <> 0: print "ldapsearch error for SE", host, ":", outputSE, outputSA continue; # Parse the result lines output = outputSE + "\n" + outputSA totalSE = usedSE = 0 for line in output.splitlines(): match = matchLdapResp.match(line) if match <> None: attrib = match.group(1) value = match.group(2) else: attrib, value = line.split(":") if attrib == "GlueSEImplementationName": implemName = value.strip() if attrib == "GlueSEImplementationVersion": implemVer = value.strip() if attrib == "GlueSATotalOnlineSize": totalSE += int(value.strip()) if attrib == "GlueSAUsedOnlineSize": usedSE += int(value.strip()) # Consistency checks: ignore 0 of negative values if totalSE <= 0 or usedSE < 0: print "Skipping " + host + " due to inconsistent data." continue # Limit the version number to only 2 figures, like 1.8 instead of 1.8.2-1 implemVerCut = implemVer match = matchVer.match(implemVer) if match <> None: implemVerCut = match.group(1) if implemName in result: if implemVerCut in result[implemName]: # Add SRM implem/version data to the existing entry total = result[implemName][implemVerCut]['total'] used = result[implemName][implemVerCut]['used'] nbOcc = result[implemName][implemVerCut]['nbOcc'] result[implemName][implemVerCut] = {'total': total + totalSE, 'used': used + usedSE, 'nbOcc': nbOcc + 1} else: # Create a new entry for that version result[implemName][implemVerCut] = {'total': totalSE, 'used': usedSE, 'nbOcc': 1} # Update artial results for this implementation name (whatever the version) result[implemName]['total'] += totalSE result[implemName]['used'] += usedSE result[implemName]['nbOcc'] += 1 else: # Create a new entry for that implementation and version result[implemName] = { implemVerCut: {'total': totalSE, 'used': usedSE, 'nbOcc': 1}, 'total': totalSE, 'used': usedSE, 'nbOcc': 1 } # End of loop on SE hostnames # ------------------------------------------------------------------------- # Display the results # Prepare the finla counts: calculate the total number of SE and storage space (to compute percentages) nbSETotal = totalTotal = totalUsed = 0 for implemName, implemDetail in result.iteritems(): nbSETotal += implemDetail['nbOcc'] totalTotal += implemDetail['total'] totalUsed += implemDetail['used'] print "Implementation Version NbOcc Total space Used space" print "===================================================================================" format = "%(implname)-16s%(implver)-8s%(nbOcc)6i%(nbOccPercent)7s%(total)16i%(totalPercent)7s%(used)16i%(usedPercent)7s\n" for implemName, implemDetail in result.iteritems(): if implemName <> 'total' and implemName <> 'used' and implemName <> 'nbOcc': sys.stdout.write(format % {'implname': implemName, 'implver': "", 'nbOcc': implemDetail['nbOcc'], 'nbOccPercent': "(" + str(implemDetail['nbOcc']*100/nbSETotal) + "%)", 'total': implemDetail['total'], 'totalPercent': "(" + str(implemDetail['total']*100/totalTotal) + "%)", 'used': implemDetail['used'], 'usedPercent': "(" + str(implemDetail['used']*100/totalUsed) + "%)"}) print "-----------------------------------------------------------------------------------" for implemVer, implemVerDetail in implemDetail.iteritems(): if implemVer <> 'total' and implemVer <> 'used' and implemVer <> 'nbOcc': sys.stdout.write(format % {'implname': "", 'implver': implemVer, 'nbOcc': implemVerDetail['nbOcc'], 'nbOccPercent': "", 'total': implemVerDetail['total'], 'totalPercent': "", 'used': implemVerDetail['used'], 'usedPercent': ""}) print "==================================================================================="
#!/usr/bin/python # Retrieve the number and size of storage elements available for a VO (defaults to biomed), # sorted by SRM implementation and version. Cumulative values of used and total sizes are # calculated per SRM flavour and version. # # ChangeLog: # 1.0: initial version # 1.1: fix issue in LDAP attributes parsing: AttributeName: value, where the value sometimes # also contains a ':' import sys import os import commands import re from optparse import OptionParser DEFAULT_TOPBDII = "cclcgtopbdii01.in2p3.fr:2170" optParser = OptionParser(version="%prog 1.1", description="""Retrieve the number and size of storage elements available for a VO (defaults to biomed), sorted by SRM implementation and version""") optParser.add_option("--vo", action="store", dest="vo", default="biomed", help="Virtual Organisation to query. Defaults to \"biomed\"") optParser.add_option("--bdii", action="store", dest="bdii", default=DEFAULT_TOPBDII, help="top BDII hostname and port. Defaults to " + DEFAULT_TOPBDII) optParser.add_option("--limit", action="store", dest="limit", default=9999, help="Max number of SE to check. Defaults to all (9999)") # ------------------------------------------------------------------------- # Definitions, global variables # ------------------------------------------------------------------------- (options, args) = optParser.parse_args() VO = options.vo TOPBDII = options.bdii MAX_SE = int(options.limit) # LDAP Request to get the Storage Element info ldapSE = "ldapsearch -x -L -s sub -H ldap://%(TOPBDII)s -b mds-vo-name=local,o=grid \"(&(ObjectClass=GlueSE)(GlueSEUniqueID=%(HOST)s))\" | egrep \"GlueSEImplementationName|GlueSEImplementationVersion\"" # LDAP Request to get the Storage Area info ldapSA = "ldapsearch -x -L -s sub -H ldap://%(TOPBDII)s -b mds-vo-name=local,o=grid \"(&(ObjectClass=GlueSA)(GlueChunkKey=GlueSEUniqueID=%(HOST)s)(|(GlueSAAccessControlBaseRule=VO:%(VO)s*)(GlueSAAccessControlBaseRule=%(VO)s*)))\" | egrep \"GlueSATotalOnlineSize|GlueSAUsedOnlineSize\"" # ------------------------------------------------------------------------- # Program main body # ------------------------------------------------------------------------- # Get the list of SEs from the BDII status, output = commands.getstatusoutput("lcg-infosites --vo " + VO + " space") if status <> 0: print "lcg-infosites error: ", output sys.exit(1) # Build the list of SEs: filter out header lines, and keep only hostnames listSE = [] nbSE = 0 for line in output.splitlines(): if ("Reserved" not in line) and ("Nearline" not in line) and ("----------" not in line): listSE.append(line.split()[-1]) if nbSE > MAX_SE: break; nbSE += 1 # The result is a multidimensional dictionary: # SRM name # 'total': total available size for that SRM implementation, whatever the version # 'used': space used by the VO for that SRM implementation, whatever the version # 'nbOcc': number of SEs with that SRM iplem, whatever the version # SRM implem version # 'total': total available size # 'used': space used by the VO # 'nbOcc': number of SEs with that SRM iplem and version result = {} # Regexp to limit the version number to 3 numbers matchVer = re.compile("^(\w+.\w+.\w+)") # Regexp to match one line of the result of an LDAP request formatted as: "Attribute: value" matchLdapResp = re.compile("^(\w+): (.+)$") # ------------------------------------------------------------------------- # For each SE, run an ldap request to get implementation names/versions and storage sizes for host in listSE: print "Checking SE " + host + "..." statusSE, outputSE = commands.getstatusoutput(ldapSE % {'TOPBDII': TOPBDII, 'HOST': host}) statusSA, outputSA = commands.getstatusoutput(ldapSA % {'TOPBDII': TOPBDII, 'HOST': host, 'VO': VO}) if statusSE <> 0 or statusSA <> 0: print "ldapsearch error for SE", host, ":", outputSE, outputSA continue; # Parse the result lines output = outputSE + "\n" + outputSA totalSE = usedSE = 0 for line in output.splitlines(): match = matchLdapResp.match(line) if match <> None: attrib = match.group(1) value = match.group(2) else: attrib, value = line.split(":") if attrib == "GlueSEImplementationName": implemName = value.strip() if attrib == "GlueSEImplementationVersion": implemVer = value.strip() if attrib == "GlueSATotalOnlineSize": totalSE += int(value.strip()) if attrib == "GlueSAUsedOnlineSize": usedSE += int(value.strip()) # Consistency checks: ignore 0 of negative values if totalSE <= 0 or usedSE < 0: print "Skipping " + host + " due to inconsistent data." continue # Limit the version number to only 2 figures, like 1.8 instead of 1.8.2-1 implemVerCut = implemVer match = matchVer.match(implemVer) if match <> None: implemVerCut = match.group(1) if implemName in result: if implemVerCut in result[implemName]: # Add SRM implem/version data to the existing entry total = result[implemName][implemVerCut]['total'] used = result[implemName][implemVerCut]['used'] nbOcc = result[implemName][implemVerCut]['nbOcc'] result[implemName][implemVerCut] = {'total': total + totalSE, 'used': used + usedSE, 'nbOcc': nbOcc + 1} else: # Create a new entry for that version result[implemName][implemVerCut] = {'total': totalSE, 'used': usedSE, 'nbOcc': 1} # Update artial results for this implementation name (whatever the version) result[implemName]['total'] += totalSE result[implemName]['used'] += usedSE result[implemName]['nbOcc'] += 1 else: # Create a new entry for that implementation and version result[implemName] = { implemVerCut: {'total': totalSE, 'used': usedSE, 'nbOcc': 1}, 'total': totalSE, 'used': usedSE, 'nbOcc': 1 } # End of loop on SE hostnames # ------------------------------------------------------------------------- # Display the results # Prepare the finla counts: calculate the total number of SE and storage space (to compute percentages) nbSETotal = totalTotal = totalUsed = 0 for implemName, implemDetail in result.iteritems(): nbSETotal += implemDetail['nbOcc'] totalTotal += implemDetail['total'] totalUsed += implemDetail['used'] print "Implementation Version NbOcc Total space Used space" print "===================================================================================" format = "%(implname)-16s%(implver)-8s%(nbOcc)6i%(nbOccPercent)7s%(total)16i%(totalPercent)7s%(used)16i%(usedPercent)7s\n" for implemName, implemDetail in result.iteritems(): if implemName <> 'total' and implemName <> 'used' and implemName <> 'nbOcc': sys.stdout.write(format % {'implname': implemName, 'implver': "", 'nbOcc': implemDetail['nbOcc'], 'nbOccPercent': "(" + str(implemDetail['nbOcc']*100/nbSETotal) + "%)", 'total': implemDetail['total'], 'totalPercent': "(" + str(implemDetail['total']*100/totalTotal) + "%)", 'used': implemDetail['used'], 'usedPercent': "(" + str(implemDetail['used']*100/totalUsed) + "%)"}) print "-----------------------------------------------------------------------------------" for implemVer, implemVerDetail in implemDetail.iteritems(): if implemVer <> 'total' and implemVer <> 'used' and implemVer <> 'nbOcc': sys.stdout.write(format % {'implname': "", 'implver': implemVer, 'nbOcc': implemVerDetail['nbOcc'], 'nbOccPercent': "", 'total': implemVerDetail['total'], 'totalPercent': "", 'used': implemVerDetail['used'], 'usedPercent': ""}) print "==================================================================================="
en
0.634061
#!/usr/bin/python # Retrieve the number and size of storage elements available for a VO (defaults to biomed), # sorted by SRM implementation and version. Cumulative values of used and total sizes are # calculated per SRM flavour and version. # # ChangeLog: # 1.0: initial version # 1.1: fix issue in LDAP attributes parsing: AttributeName: value, where the value sometimes # also contains a ':' Retrieve the number and size of storage elements available for a VO (defaults to biomed), sorted by SRM implementation and version # ------------------------------------------------------------------------- # Definitions, global variables # ------------------------------------------------------------------------- # LDAP Request to get the Storage Element info # LDAP Request to get the Storage Area info # ------------------------------------------------------------------------- # Program main body # ------------------------------------------------------------------------- # Get the list of SEs from the BDII # Build the list of SEs: filter out header lines, and keep only hostnames # The result is a multidimensional dictionary: # SRM name # 'total': total available size for that SRM implementation, whatever the version # 'used': space used by the VO for that SRM implementation, whatever the version # 'nbOcc': number of SEs with that SRM iplem, whatever the version # SRM implem version # 'total': total available size # 'used': space used by the VO # 'nbOcc': number of SEs with that SRM iplem and version # Regexp to limit the version number to 3 numbers # Regexp to match one line of the result of an LDAP request formatted as: "Attribute: value" # ------------------------------------------------------------------------- # For each SE, run an ldap request to get implementation names/versions and storage sizes # Parse the result lines # Consistency checks: ignore 0 of negative values # Limit the version number to only 2 figures, like 1.8 instead of 1.8.2-1 # Add SRM implem/version data to the existing entry # Create a new entry for that version # Update artial results for this implementation name (whatever the version) # Create a new entry for that implementation and version # End of loop on SE hostnames # ------------------------------------------------------------------------- # Display the results # Prepare the finla counts: calculate the total number of SE and storage space (to compute percentages)
2.146313
2
pyalp/apps/tournaments/utils.py
Mause/pyalp
0
6619574
""" aka include/touraments/_tournament_functions.php """ from tournaments.models import Tournament, Moderator def get_what_teams_called(tournament, plural=True): if tournament.per_team == 1 or (tournament.random and not tournament.lockstart): return 'competitor' + ('s' if plural else '') else: return 'team' + ('s' if plural else '') def get_num_teams(tournament, random_as_competitors=1): q = dbc->database_query('SELECT per_team, random, lockstart FROM tournaments WHERE tourneyid='.(int)tourneyid) if (dbc->database_num_rows(q)) { tournament = dbc->database_fetch_assoc(q) if (tournament['per_team'] == 1 or (tournament['random'] and !tournament['lockstart'])) { if (tournament['per_team'] == 1 or (tournament['random'] and !tournament['lockstart'] and random_as_competitors)) { teams = dbc->database_num_rows(dbc->database_query('SELECT * FROM tournament_players WHERE tourneyid='.(int)tourneyid)) else: teams = ceil(dbc->database_num_rows(dbc->database_query('SELECT * FROM tournament_players WHERE tourneyid='.(int)tournament['tourneyid'])) / tournament['per_team']) else: teams = dbc->database_num_rows(dbc->database_query('SELECT * FROM tournament_teams WHERE tourneyid='.(int)tourneyid)) if teams: return teams else: return 0 else: return 0 def is_under_max_teams(tournament): q = dbc->database_query('SELECT max_teams FROM tournaments WHERE tourneyid='.(int)tourneyid) if (dbc->database_num_rows(q)) { tournament = dbc->database_fetch_assoc(q) teams = get_num_teams(tourneyid) if (tournament['max_teams'] > 0) { return (teams < tournament['max_teams']) return True return False def make_tournament_link(tourneyid): if (current_security_level() < 2 and file_exists('_tournament_'.tourneyid.'.html')) { return '_tournament_'.tourneyid.'.html' else: return 'disp_tournament.php?id='.tourneyid def tournament_is_secure(request, tourney): moderator = tourney.moderator return (current_security_level() >= 2 or (current_security_level() >= 1 and moderator == request.user): def display_tournament_menu(tourneyid, double_br=1, extra_admin=0): context = { 'txt': get_what_teams_called(tourney), 'link': make_tournament_link(tourney) } return render_to_string( 'tournament_menu.html', context )
""" aka include/touraments/_tournament_functions.php """ from tournaments.models import Tournament, Moderator def get_what_teams_called(tournament, plural=True): if tournament.per_team == 1 or (tournament.random and not tournament.lockstart): return 'competitor' + ('s' if plural else '') else: return 'team' + ('s' if plural else '') def get_num_teams(tournament, random_as_competitors=1): q = dbc->database_query('SELECT per_team, random, lockstart FROM tournaments WHERE tourneyid='.(int)tourneyid) if (dbc->database_num_rows(q)) { tournament = dbc->database_fetch_assoc(q) if (tournament['per_team'] == 1 or (tournament['random'] and !tournament['lockstart'])) { if (tournament['per_team'] == 1 or (tournament['random'] and !tournament['lockstart'] and random_as_competitors)) { teams = dbc->database_num_rows(dbc->database_query('SELECT * FROM tournament_players WHERE tourneyid='.(int)tourneyid)) else: teams = ceil(dbc->database_num_rows(dbc->database_query('SELECT * FROM tournament_players WHERE tourneyid='.(int)tournament['tourneyid'])) / tournament['per_team']) else: teams = dbc->database_num_rows(dbc->database_query('SELECT * FROM tournament_teams WHERE tourneyid='.(int)tourneyid)) if teams: return teams else: return 0 else: return 0 def is_under_max_teams(tournament): q = dbc->database_query('SELECT max_teams FROM tournaments WHERE tourneyid='.(int)tourneyid) if (dbc->database_num_rows(q)) { tournament = dbc->database_fetch_assoc(q) teams = get_num_teams(tourneyid) if (tournament['max_teams'] > 0) { return (teams < tournament['max_teams']) return True return False def make_tournament_link(tourneyid): if (current_security_level() < 2 and file_exists('_tournament_'.tourneyid.'.html')) { return '_tournament_'.tourneyid.'.html' else: return 'disp_tournament.php?id='.tourneyid def tournament_is_secure(request, tourney): moderator = tourney.moderator return (current_security_level() >= 2 or (current_security_level() >= 1 and moderator == request.user): def display_tournament_menu(tourneyid, double_br=1, extra_admin=0): context = { 'txt': get_what_teams_called(tourney), 'link': make_tournament_link(tourney) } return render_to_string( 'tournament_menu.html', context )
en
0.591593
aka include/touraments/_tournament_functions.php
2.755
3
deep-rl/lib/python2.7/site-packages/OpenGL/raw/GLX/ARB/create_context_profile.py
ShujaKhalid/deep-rl
210
6619575
<filename>deep-rl/lib/python2.7/site-packages/OpenGL/raw/GLX/ARB/create_context_profile.py<gh_stars>100-1000 '''Autogenerated by xml_generate script, do not edit!''' from OpenGL import platform as _p, arrays # Code generation uses this from OpenGL.raw.GLX import _types as _cs # End users want this... from OpenGL.raw.GLX._types import * from OpenGL.raw.GLX import _errors from OpenGL.constant import Constant as _C import ctypes _EXTENSION_NAME = 'GLX_ARB_create_context_profile' def _f( function ): return _p.createFunction( function,_p.PLATFORM.GLX,'GLX_ARB_create_context_profile',error_checker=_errors._error_checker) GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB=_C('GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB',0x00000002) GLX_CONTEXT_CORE_PROFILE_BIT_ARB=_C('GLX_CONTEXT_CORE_PROFILE_BIT_ARB',0x00000001) GLX_CONTEXT_PROFILE_MASK_ARB=_C('GLX_CONTEXT_PROFILE_MASK_ARB',0x9126)
<filename>deep-rl/lib/python2.7/site-packages/OpenGL/raw/GLX/ARB/create_context_profile.py<gh_stars>100-1000 '''Autogenerated by xml_generate script, do not edit!''' from OpenGL import platform as _p, arrays # Code generation uses this from OpenGL.raw.GLX import _types as _cs # End users want this... from OpenGL.raw.GLX._types import * from OpenGL.raw.GLX import _errors from OpenGL.constant import Constant as _C import ctypes _EXTENSION_NAME = 'GLX_ARB_create_context_profile' def _f( function ): return _p.createFunction( function,_p.PLATFORM.GLX,'GLX_ARB_create_context_profile',error_checker=_errors._error_checker) GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB=_C('GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB',0x00000002) GLX_CONTEXT_CORE_PROFILE_BIT_ARB=_C('GLX_CONTEXT_CORE_PROFILE_BIT_ARB',0x00000001) GLX_CONTEXT_PROFILE_MASK_ARB=_C('GLX_CONTEXT_PROFILE_MASK_ARB',0x9126)
en
0.743726
Autogenerated by xml_generate script, do not edit! # Code generation uses this # End users want this...
1.725867
2
modules/opcodes.py
Atlas8008/chip8-emulator
0
6619576
OP_0NNN = 0 OP_00E0 = 1 OP_00EE = 2 OP_1NNN = 3 OP_2NNN = 4 OP_3XNN = 5 OP_4XNN = 6 OP_5XY0 = 7 OP_6XNN = 8 OP_7XNN = 9 OP_8XY0 = 10 OP_8XY1 = 11 OP_8XY2 = 12 OP_8XY3 = 13 OP_8XY4 = 14 OP_8XY5 = 15 OP_8XY6 = 16 OP_8XY7 = 17 OP_8XYE = 18 OP_9XY0 = 19 OP_ANNN = 20 OP_BNNN = 21 OP_CXNN = 22 OP_DXYN = 23 OP_EX9E = 24 OP_EXA1 = 25 OP_FX07 = 26 OP_FX0A = 27 OP_FX15 = 28 OP_FX18 = 29 OP_FX1E = 30 OP_FX29 = 31 OP_FX33 = 32 OP_FX55 = 33 OP_FX65 = 34
OP_0NNN = 0 OP_00E0 = 1 OP_00EE = 2 OP_1NNN = 3 OP_2NNN = 4 OP_3XNN = 5 OP_4XNN = 6 OP_5XY0 = 7 OP_6XNN = 8 OP_7XNN = 9 OP_8XY0 = 10 OP_8XY1 = 11 OP_8XY2 = 12 OP_8XY3 = 13 OP_8XY4 = 14 OP_8XY5 = 15 OP_8XY6 = 16 OP_8XY7 = 17 OP_8XYE = 18 OP_9XY0 = 19 OP_ANNN = 20 OP_BNNN = 21 OP_CXNN = 22 OP_DXYN = 23 OP_EX9E = 24 OP_EXA1 = 25 OP_FX07 = 26 OP_FX0A = 27 OP_FX15 = 28 OP_FX18 = 29 OP_FX1E = 30 OP_FX29 = 31 OP_FX33 = 32 OP_FX55 = 33 OP_FX65 = 34
none
1
1.072913
1
examples/example1.py
IhorNehrutsa/micropyserver
0
6619577
""" Example 1 Needed ESP8266 or ESP32 board @see https://github.com/troublegum/micropyserver """ import esp import network from micropyserver import MicroPyServer from machine import Pin PIN_NUMBER = 2 wlan_id = "your wi-fi" wlan_pass = "<PASSWORD>" wlan = network.WLAN(network.STA_IF) # wlan.active(True) # if not wlan.isconnected(): # wlan.connect(wlan_id, wlan_pass) print("wlan.ifconfig():", wlan.ifconfig()) print("wlan.isconnected():", wlan.isconnected()) pin = Pin(PIN_NUMBER, Pin.OUT, value=0) def show_index_page(request): server.send("THIS IS INDEX PAGE") def show_info_page(request): server.send("THIS IS INFO PAGE") def show_pin_page(request): if request.startswith("GET /on HTTP"): pin.value(1) elif request.startswith("GET /off HTTP"): pin.value(0) server.send("PIN IS " + ("ON" if pin.value() == 1 else "OFF")) server = MicroPyServer() server.add_route("/info", show_info_page) server.add_route("/", show_index_page) server.add_route("/on", show_pin_page) server.add_route("/off", show_pin_page) server.start()
""" Example 1 Needed ESP8266 or ESP32 board @see https://github.com/troublegum/micropyserver """ import esp import network from micropyserver import MicroPyServer from machine import Pin PIN_NUMBER = 2 wlan_id = "your wi-fi" wlan_pass = "<PASSWORD>" wlan = network.WLAN(network.STA_IF) # wlan.active(True) # if not wlan.isconnected(): # wlan.connect(wlan_id, wlan_pass) print("wlan.ifconfig():", wlan.ifconfig()) print("wlan.isconnected():", wlan.isconnected()) pin = Pin(PIN_NUMBER, Pin.OUT, value=0) def show_index_page(request): server.send("THIS IS INDEX PAGE") def show_info_page(request): server.send("THIS IS INFO PAGE") def show_pin_page(request): if request.startswith("GET /on HTTP"): pin.value(1) elif request.startswith("GET /off HTTP"): pin.value(0) server.send("PIN IS " + ("ON" if pin.value() == 1 else "OFF")) server = MicroPyServer() server.add_route("/info", show_info_page) server.add_route("/", show_index_page) server.add_route("/on", show_pin_page) server.add_route("/off", show_pin_page) server.start()
en
0.490672
Example 1 Needed ESP8266 or ESP32 board @see https://github.com/troublegum/micropyserver # wlan.active(True) # if not wlan.isconnected(): # wlan.connect(wlan_id, wlan_pass)
3.60876
4
data_loader.py
1048727525/fnm_pytorch
2
6619578
<reponame>1048727525/fnm_pytorch import os import scipy import numpy as np from util import * from PIL import Image from torchvision import transforms from torch.utils.data import Dataset, DataLoader class sample_dataset(Dataset): def __init__(self, list_path, img_root_path, crop_size, image_size, mode="train"): self.img_name_list = read_txt_file(list_path) self.img_root_path = img_root_path transform = [] if mode == "train": transform.append(transforms.ColorJitter(brightness=0.5, contrast=0, saturation=0, hue=0)) transform.append(transforms.RandomHorizontalFlip()) transform.append(transforms.CenterCrop(crop_size)) transform.append(transforms.Resize(image_size)) transform.append(transforms.ToTensor()) transform.append(transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))) self.transform = transforms.Compose(transform) transform_112 = [] if mode == "train": transform_112.append(transforms.ColorJitter(brightness=0.5, contrast=0, saturation=0, hue=0)) transform_112.append(transforms.RandomHorizontalFlip()) transform_112.append(transforms.CenterCrop(crop_size)) transform_112.append(transforms.Resize(112)) transform_112.append(transforms.ToTensor()) transform_112.append(transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))) self.transform_112 = transforms.Compose(transform_112) def __len__(self): return len(self.img_name_list) def __getitem__(self, idx): img_path = os.path.join(self.img_root_path, self.img_name_list[idx]) img = Image.open(img_path).convert('RGB') return self.transform(img), self.transform_112(img) def get_loader(list_path, img_root_path, crop_size=224, image_size=224, batch_size=16, mode="train", num_workers=8): dataset = sample_dataset(list_path, img_root_path, crop_size, image_size) data_loader = DataLoader(dataset=dataset, batch_size=batch_size, shuffle=(mode=='train'), num_workers=num_workers) return data_loader if __name__ == '__main__': import cv2 profile_list_path = "../fnm/mpie/casia_gt.txt" front_list_path = "../fnm/mpie/session01_front_demo.txt" profile_path = "../../datasets/casia_aligned_250_250_jpg" front_path = "../../datasets/session01_align" crop_size = 224 image_size = 224 #dataset = sample_dataset(profile_list_path, profile_path, crop_size, image_size) ''' for i, sample in enumerate(dataset): cv2.imwrite("profile.jpg", tensor2im(sample["profile"])) cv2.imwrite("front.jpg", tensor2im(sample["front"])) if i==1: break ''' data_loader = get_loader(front_list_path, front_path, crop_size=224, image_size=224, batch_size=16, mode="train", num_workers=8) for i, sample in data_loader: print(sample.shape) ''' for i, sample in enumerate(data_loader): cv2.imwrite("profile.jpg", cv2.cvtColor(tensor2im(sample["profile"]), cv2.COLOR_BGR2RGB)) cv2.imwrite("front.jpg", cv2.cvtColor(tensor2im(sample["front"]), cv2.COLOR_BGR2RGB)) if i==1: break '''
import os import scipy import numpy as np from util import * from PIL import Image from torchvision import transforms from torch.utils.data import Dataset, DataLoader class sample_dataset(Dataset): def __init__(self, list_path, img_root_path, crop_size, image_size, mode="train"): self.img_name_list = read_txt_file(list_path) self.img_root_path = img_root_path transform = [] if mode == "train": transform.append(transforms.ColorJitter(brightness=0.5, contrast=0, saturation=0, hue=0)) transform.append(transforms.RandomHorizontalFlip()) transform.append(transforms.CenterCrop(crop_size)) transform.append(transforms.Resize(image_size)) transform.append(transforms.ToTensor()) transform.append(transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))) self.transform = transforms.Compose(transform) transform_112 = [] if mode == "train": transform_112.append(transforms.ColorJitter(brightness=0.5, contrast=0, saturation=0, hue=0)) transform_112.append(transforms.RandomHorizontalFlip()) transform_112.append(transforms.CenterCrop(crop_size)) transform_112.append(transforms.Resize(112)) transform_112.append(transforms.ToTensor()) transform_112.append(transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))) self.transform_112 = transforms.Compose(transform_112) def __len__(self): return len(self.img_name_list) def __getitem__(self, idx): img_path = os.path.join(self.img_root_path, self.img_name_list[idx]) img = Image.open(img_path).convert('RGB') return self.transform(img), self.transform_112(img) def get_loader(list_path, img_root_path, crop_size=224, image_size=224, batch_size=16, mode="train", num_workers=8): dataset = sample_dataset(list_path, img_root_path, crop_size, image_size) data_loader = DataLoader(dataset=dataset, batch_size=batch_size, shuffle=(mode=='train'), num_workers=num_workers) return data_loader if __name__ == '__main__': import cv2 profile_list_path = "../fnm/mpie/casia_gt.txt" front_list_path = "../fnm/mpie/session01_front_demo.txt" profile_path = "../../datasets/casia_aligned_250_250_jpg" front_path = "../../datasets/session01_align" crop_size = 224 image_size = 224 #dataset = sample_dataset(profile_list_path, profile_path, crop_size, image_size) ''' for i, sample in enumerate(dataset): cv2.imwrite("profile.jpg", tensor2im(sample["profile"])) cv2.imwrite("front.jpg", tensor2im(sample["front"])) if i==1: break ''' data_loader = get_loader(front_list_path, front_path, crop_size=224, image_size=224, batch_size=16, mode="train", num_workers=8) for i, sample in data_loader: print(sample.shape) ''' for i, sample in enumerate(data_loader): cv2.imwrite("profile.jpg", cv2.cvtColor(tensor2im(sample["profile"]), cv2.COLOR_BGR2RGB)) cv2.imwrite("front.jpg", cv2.cvtColor(tensor2im(sample["front"]), cv2.COLOR_BGR2RGB)) if i==1: break '''
en
0.206066
#dataset = sample_dataset(profile_list_path, profile_path, crop_size, image_size) for i, sample in enumerate(dataset): cv2.imwrite("profile.jpg", tensor2im(sample["profile"])) cv2.imwrite("front.jpg", tensor2im(sample["front"])) if i==1: break for i, sample in enumerate(data_loader): cv2.imwrite("profile.jpg", cv2.cvtColor(tensor2im(sample["profile"]), cv2.COLOR_BGR2RGB)) cv2.imwrite("front.jpg", cv2.cvtColor(tensor2im(sample["front"]), cv2.COLOR_BGR2RGB)) if i==1: break
2.55656
3
Datasets/lfw.py
whkwls2653/Pytorch_Face_Recognition-
62
6619579
from torch.utils.data import Dataset, DataLoader import torchvision.transforms as transforms import numpy as np import cv2 import os def image_loader(image_path): try: image = cv2.imread(image_path) if len(image.shape) == 2: image = np.stack([image]*3, 2) return image except IOError: print('fail to load image:' + image_path) transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(mean = (0.5, 0.5, 0.5), std = (0.5, 0.5, 0.5)) ]) class LFW(Dataset): def __init__(self, dataset_path, file_list): self.dataset_path = dataset_path self.file_list = file_list self.left_images = [] self.right_images = [] self.folds = [] self.labels = [] with open(file_list) as f: pairs = f.read().splitlines()[1:] for i, p in enumerate(pairs): p = p.split('\t') if len(p) == 3: left_image = p[0] + '/' + p[0] + '_' + '{:04}.jpg'.format(int(p[1])) right_image = p[0] + '/' + p[0] + '_' + '{:04}.jpg'.format(int(p[2])) fold = i // 600 label = 1 elif len(p) == 4: left_image = p[0] + '/' + p[0] + '_' + '{:04}.jpg'.format(int(p[1])) right_image = p[2] + '/' + p[2] + '_' + '{:04}.jpg'.format(int(p[3])) fold = i // 600 label = -1 self.left_images.append(left_image) self.right_images.append(right_image) self.folds.append(fold) self.labels.append(label) def __getitem__(self, index): image_left = image_loader(os.path.join(self.dataset_path, self.left_images[index])) image_right = image_loader(os.path.join(self.dataset_path, self.right_images[index])) image_list = [image_left, cv2.flip(image_left, 1), image_right, cv2.flip(image_right, 1)] for i in range(len(image_list)): image_list[i] = transform(image_list[i]) return image_list def __len__(self): return len(self.left_images) if __name__ == '__main__': dataset_path = '/home/CaiMao/Face_Pytorch-master/dataset/lfw-112x112/lfw-112x112' file_list = '/home/CaiMao/Face_Pytorch-master/dataset/lfw-112x112/pairs.txt' lfw_dataset = LFW(dataset_path, file_list) lfw_dataloader = DataLoader(lfw_dataset, batch_size=128, shuffle=False, num_workers=4, drop_last=False) print(len(lfw_dataset)) print(len(lfw_dataloader)) for data in lfw_dataloader: print(len(data))
from torch.utils.data import Dataset, DataLoader import torchvision.transforms as transforms import numpy as np import cv2 import os def image_loader(image_path): try: image = cv2.imread(image_path) if len(image.shape) == 2: image = np.stack([image]*3, 2) return image except IOError: print('fail to load image:' + image_path) transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(mean = (0.5, 0.5, 0.5), std = (0.5, 0.5, 0.5)) ]) class LFW(Dataset): def __init__(self, dataset_path, file_list): self.dataset_path = dataset_path self.file_list = file_list self.left_images = [] self.right_images = [] self.folds = [] self.labels = [] with open(file_list) as f: pairs = f.read().splitlines()[1:] for i, p in enumerate(pairs): p = p.split('\t') if len(p) == 3: left_image = p[0] + '/' + p[0] + '_' + '{:04}.jpg'.format(int(p[1])) right_image = p[0] + '/' + p[0] + '_' + '{:04}.jpg'.format(int(p[2])) fold = i // 600 label = 1 elif len(p) == 4: left_image = p[0] + '/' + p[0] + '_' + '{:04}.jpg'.format(int(p[1])) right_image = p[2] + '/' + p[2] + '_' + '{:04}.jpg'.format(int(p[3])) fold = i // 600 label = -1 self.left_images.append(left_image) self.right_images.append(right_image) self.folds.append(fold) self.labels.append(label) def __getitem__(self, index): image_left = image_loader(os.path.join(self.dataset_path, self.left_images[index])) image_right = image_loader(os.path.join(self.dataset_path, self.right_images[index])) image_list = [image_left, cv2.flip(image_left, 1), image_right, cv2.flip(image_right, 1)] for i in range(len(image_list)): image_list[i] = transform(image_list[i]) return image_list def __len__(self): return len(self.left_images) if __name__ == '__main__': dataset_path = '/home/CaiMao/Face_Pytorch-master/dataset/lfw-112x112/lfw-112x112' file_list = '/home/CaiMao/Face_Pytorch-master/dataset/lfw-112x112/pairs.txt' lfw_dataset = LFW(dataset_path, file_list) lfw_dataloader = DataLoader(lfw_dataset, batch_size=128, shuffle=False, num_workers=4, drop_last=False) print(len(lfw_dataset)) print(len(lfw_dataloader)) for data in lfw_dataloader: print(len(data))
none
1
2.804934
3
nappy/get_msd_from_akr.py
ryokbys/nap
27
6619580
#!/bin/env python # u""" Get mean square displacements (MSDs) of given atoms (see ids below) from the akr files in the arguments. This utility assumes that the cell is fixed during the simulation. Staggered measuring of MSD for for the statistical purpose. """ from __future__ import print_function import os,sys,glob,time import numpy as np import optparse from nappy.napsys import NAPSystem usage= '%prog [options] akr0001 akr0002 akr0003 ...' parser= optparse.OptionParser(usage=usage) parser.add_option("--id",dest="id",type="int",default=1, help="id of an atom whose path is to be traced.") parser.add_option("-m","--measure",dest="measure",type="int",default=1, help="num of measuring lane. In case of 1, it is identical to non-staggered measuring.") parser.add_option("-s","--shift",dest="shift",type="int",default=20, help="shift of each staggered lane.") (options,args)= parser.parse_args() #...atom IDs whose trajectories are tracked. #ids=(55,) id= options.id #...num of measuring lane, in case of 1, it is identical to non-staggered measuring #nmeasure= 10 nmeasure= options.measure #...shift of each staggered lane #nshift= 50 nshift= options.shift # print id # print nmeasure # print nshift # print args # exit() def anint(x): if x >= 0.5: return 1.0 elif x < -0.5: return -1.0 else: return 0.0 if len(args) < 1: print(' [Error] number of arguments wrong.') print(usage) sys.exit() #...parse arguments infiles= [] #print os.getcwd() for file in args: infiles.append(file) #...compute sampling time-window from nmeasure and nshift ntwindow= len(infiles) -(nmeasure-1)*nshift if ntwindow <= 0: print(' [Error] ntwindow <= 0 !!!') print(' Chech the parameters nmeasure and nshift, and input files.') sys.exit() #...make output data files outfname='dat.msd-{0}'.format(id) outfile= open(outfname,'w') p0= np.zeros((nmeasure,3)) pp= np.zeros(3) msd= np.zeros((len(infiles),nmeasure,3)) npbc= np.zeros((3,),dtype=int) hmat= np.zeros((3,3)) for ifile in range(len(infiles)): file= infiles[ifile] system= NAPSystem() system.read_akr(file) hmat[0]= system.a1 *system.alc hmat[1]= system.a2 *system.alc hmat[2]= system.a3 *system.alc #...human-readable ID to computer-oriented ID i= id-1 pi= system.get_atom_attr(i,'pos') if ifile == 0: pp= pi else: #...correct periodic motion dev= pi -pp if dev[0] > 0.5: npbc[0] += -1 elif dev[0] < -0.5: npbc[0] += 1 if dev[1] > 0.5: npbc[1] += -1 elif dev[1] < -0.5: npbc[1] += 1 if dev[2] > 0.5: npbc[2] += -1 elif dev[2] < -0.5: npbc[2] += 1 # print npbc #...store current position pp= pi for nm in range(nmeasure): if ifile == nm*nshift: p0[nm,0]= pi[0] +float(npbc[0]) p0[nm,1]= pi[1] +float(npbc[1]) p0[nm,2]= pi[2] +float(npbc[2]) if nm*nshift < ifile: #...normalized to absolute dev[0]= pi[0] -p0[nm,0] +float(npbc[0]) dev[1]= pi[1] -p0[nm,1] +float(npbc[1]) dev[2]= pi[2] -p0[nm,2] +float(npbc[2]) dev= np.dot(hmat.T,dev) msd[ifile-nm*nshift,nm,0] = dev[0]**2 msd[ifile-nm*nshift,nm,1] = dev[1]**2 msd[ifile-nm*nshift,nm,2] = dev[2]**2 for ifile in range(len(infiles)-(nmeasure-1)*nshift): if ifile == 0: outfile.write(' {:10d}'.format(ifile) +' {:15.7f} {:15.7f}'.format(0.0,0.0) +' {:15.7f} {:15.7f}\n'.format(0.0,0.0)) else: dev= np.zeros((3,)) for nm in range(nmeasure): dev += msd[ifile,nm] dev /= nmeasure outfile.write(' {:10d}'.format(ifile) +' {:15.7f}'.format(dev[0]) +' {:15.7f}'.format(dev[1]) +' {:15.7f}'.format(dev[2]) +' {:15.7f}'.format((dev[0]+dev[1]+dev[2])/3) +' \n')
#!/bin/env python # u""" Get mean square displacements (MSDs) of given atoms (see ids below) from the akr files in the arguments. This utility assumes that the cell is fixed during the simulation. Staggered measuring of MSD for for the statistical purpose. """ from __future__ import print_function import os,sys,glob,time import numpy as np import optparse from nappy.napsys import NAPSystem usage= '%prog [options] akr0001 akr0002 akr0003 ...' parser= optparse.OptionParser(usage=usage) parser.add_option("--id",dest="id",type="int",default=1, help="id of an atom whose path is to be traced.") parser.add_option("-m","--measure",dest="measure",type="int",default=1, help="num of measuring lane. In case of 1, it is identical to non-staggered measuring.") parser.add_option("-s","--shift",dest="shift",type="int",default=20, help="shift of each staggered lane.") (options,args)= parser.parse_args() #...atom IDs whose trajectories are tracked. #ids=(55,) id= options.id #...num of measuring lane, in case of 1, it is identical to non-staggered measuring #nmeasure= 10 nmeasure= options.measure #...shift of each staggered lane #nshift= 50 nshift= options.shift # print id # print nmeasure # print nshift # print args # exit() def anint(x): if x >= 0.5: return 1.0 elif x < -0.5: return -1.0 else: return 0.0 if len(args) < 1: print(' [Error] number of arguments wrong.') print(usage) sys.exit() #...parse arguments infiles= [] #print os.getcwd() for file in args: infiles.append(file) #...compute sampling time-window from nmeasure and nshift ntwindow= len(infiles) -(nmeasure-1)*nshift if ntwindow <= 0: print(' [Error] ntwindow <= 0 !!!') print(' Chech the parameters nmeasure and nshift, and input files.') sys.exit() #...make output data files outfname='dat.msd-{0}'.format(id) outfile= open(outfname,'w') p0= np.zeros((nmeasure,3)) pp= np.zeros(3) msd= np.zeros((len(infiles),nmeasure,3)) npbc= np.zeros((3,),dtype=int) hmat= np.zeros((3,3)) for ifile in range(len(infiles)): file= infiles[ifile] system= NAPSystem() system.read_akr(file) hmat[0]= system.a1 *system.alc hmat[1]= system.a2 *system.alc hmat[2]= system.a3 *system.alc #...human-readable ID to computer-oriented ID i= id-1 pi= system.get_atom_attr(i,'pos') if ifile == 0: pp= pi else: #...correct periodic motion dev= pi -pp if dev[0] > 0.5: npbc[0] += -1 elif dev[0] < -0.5: npbc[0] += 1 if dev[1] > 0.5: npbc[1] += -1 elif dev[1] < -0.5: npbc[1] += 1 if dev[2] > 0.5: npbc[2] += -1 elif dev[2] < -0.5: npbc[2] += 1 # print npbc #...store current position pp= pi for nm in range(nmeasure): if ifile == nm*nshift: p0[nm,0]= pi[0] +float(npbc[0]) p0[nm,1]= pi[1] +float(npbc[1]) p0[nm,2]= pi[2] +float(npbc[2]) if nm*nshift < ifile: #...normalized to absolute dev[0]= pi[0] -p0[nm,0] +float(npbc[0]) dev[1]= pi[1] -p0[nm,1] +float(npbc[1]) dev[2]= pi[2] -p0[nm,2] +float(npbc[2]) dev= np.dot(hmat.T,dev) msd[ifile-nm*nshift,nm,0] = dev[0]**2 msd[ifile-nm*nshift,nm,1] = dev[1]**2 msd[ifile-nm*nshift,nm,2] = dev[2]**2 for ifile in range(len(infiles)-(nmeasure-1)*nshift): if ifile == 0: outfile.write(' {:10d}'.format(ifile) +' {:15.7f} {:15.7f}'.format(0.0,0.0) +' {:15.7f} {:15.7f}\n'.format(0.0,0.0)) else: dev= np.zeros((3,)) for nm in range(nmeasure): dev += msd[ifile,nm] dev /= nmeasure outfile.write(' {:10d}'.format(ifile) +' {:15.7f}'.format(dev[0]) +' {:15.7f}'.format(dev[1]) +' {:15.7f}'.format(dev[2]) +' {:15.7f}'.format((dev[0]+dev[1]+dev[2])/3) +' \n')
en
0.735942
#!/bin/env python # Get mean square displacements (MSDs) of given atoms (see ids below) from the akr files in the arguments. This utility assumes that the cell is fixed during the simulation. Staggered measuring of MSD for for the statistical purpose. #...atom IDs whose trajectories are tracked. #ids=(55,) #...num of measuring lane, in case of 1, it is identical to non-staggered measuring #nmeasure= 10 #...shift of each staggered lane #nshift= 50 # print id # print nmeasure # print nshift # print args # exit() #...parse arguments #print os.getcwd() #...compute sampling time-window from nmeasure and nshift #...make output data files #...human-readable ID to computer-oriented ID #...correct periodic motion # print npbc #...store current position #...normalized to absolute
2.790165
3
otherDotFiles/powerline/weightless.py
serious-scribbler/WeightlessTheme
0
6619581
class DefaultColor(object): """ This class should have the default colors for every segment. Please test every new segment with this theme first. """ # RESET is not a real color code. It is used as in indicator # within the code that any foreground / background color should # be cleared RESET = -1 USERNAME_FG = 0 # white USERNAME_BG = 214 # weightless grey USERNAME_ROOT_BG = 88 # weightless dark red HOSTNAME_FG = 214 # weightless orange HOSTNAME_BG = 240 # grey HOME_SPECIAL_DISPLAY = True HOME_BG = 33 # weightless dark red HOME_FG = 0 # white PATH_BG = 0 # 250 medium grey PATH_FG = 33 # light grey CWD_FG = 15 # 254 nearly-white grey SEPARATOR_FG = 160 READONLY_BG = 88 READONLY_FG = 254 SSH_BG = 61 #not in use, orange SSH_FG = 0 REPO_CLEAN_BG = 149 # light green REPO_CLEAN_FG = 0 # black REPO_DIRTY_BG = 160 # /red REPO_DIRTY_FG = 15 # white JOBS_FG = 99 # replaces 39, light purple JOBS_BG = 235 CMD_PASSED_BG = 235 CMD_PASSED_FG = 15 CMD_FAILED_BG = 160 CMD_FAILED_FG = 15 SVN_CHANGES_BG = 235 # not in use SVN_CHANGES_FG = 112 # dark green GIT_AHEAD_BG = 235 GIT_AHEAD_FG = 15 GIT_BEHIND_BG = 235 GIT_BEHIND_FG = 15 GIT_STAGED_BG = 112 GIT_STAGED_FG = 15 GIT_NOTSTAGED_BG = 61 GIT_NOTSTAGED_FG = 15 GIT_UNTRACKED_BG = 52 GIT_UNTRACKED_FG = 15 GIT_CONFLICTED_BG = 9 GIT_CONFLICTED_FG = 15 GIT_STASH_BG = 221 GIT_STASH_FG = 0 VIRTUAL_ENV_BG = 112 VIRTUAL_ENV_FG = 00 BATTERY_NORMAL_BG = 112 BATTERY_NORMAL_FG = 0 BATTERY_LOW_BG = 160 BATTERY_LOW_FG = 0 AWS_PROFILE_FG = 45 AWS_PROFILE_BG = 235 TIME_FG = 15 TIME_BG = 235 class Color(DefaultColor): """ This subclass is required when the user chooses to use 'default' theme. Because the segments require a 'Color' class for every theme. """ pass
class DefaultColor(object): """ This class should have the default colors for every segment. Please test every new segment with this theme first. """ # RESET is not a real color code. It is used as in indicator # within the code that any foreground / background color should # be cleared RESET = -1 USERNAME_FG = 0 # white USERNAME_BG = 214 # weightless grey USERNAME_ROOT_BG = 88 # weightless dark red HOSTNAME_FG = 214 # weightless orange HOSTNAME_BG = 240 # grey HOME_SPECIAL_DISPLAY = True HOME_BG = 33 # weightless dark red HOME_FG = 0 # white PATH_BG = 0 # 250 medium grey PATH_FG = 33 # light grey CWD_FG = 15 # 254 nearly-white grey SEPARATOR_FG = 160 READONLY_BG = 88 READONLY_FG = 254 SSH_BG = 61 #not in use, orange SSH_FG = 0 REPO_CLEAN_BG = 149 # light green REPO_CLEAN_FG = 0 # black REPO_DIRTY_BG = 160 # /red REPO_DIRTY_FG = 15 # white JOBS_FG = 99 # replaces 39, light purple JOBS_BG = 235 CMD_PASSED_BG = 235 CMD_PASSED_FG = 15 CMD_FAILED_BG = 160 CMD_FAILED_FG = 15 SVN_CHANGES_BG = 235 # not in use SVN_CHANGES_FG = 112 # dark green GIT_AHEAD_BG = 235 GIT_AHEAD_FG = 15 GIT_BEHIND_BG = 235 GIT_BEHIND_FG = 15 GIT_STAGED_BG = 112 GIT_STAGED_FG = 15 GIT_NOTSTAGED_BG = 61 GIT_NOTSTAGED_FG = 15 GIT_UNTRACKED_BG = 52 GIT_UNTRACKED_FG = 15 GIT_CONFLICTED_BG = 9 GIT_CONFLICTED_FG = 15 GIT_STASH_BG = 221 GIT_STASH_FG = 0 VIRTUAL_ENV_BG = 112 VIRTUAL_ENV_FG = 00 BATTERY_NORMAL_BG = 112 BATTERY_NORMAL_FG = 0 BATTERY_LOW_BG = 160 BATTERY_LOW_FG = 0 AWS_PROFILE_FG = 45 AWS_PROFILE_BG = 235 TIME_FG = 15 TIME_BG = 235 class Color(DefaultColor): """ This subclass is required when the user chooses to use 'default' theme. Because the segments require a 'Color' class for every theme. """ pass
en
0.803611
This class should have the default colors for every segment. Please test every new segment with this theme first. # RESET is not a real color code. It is used as in indicator # within the code that any foreground / background color should # be cleared # white # weightless grey # weightless dark red # weightless orange # grey # weightless dark red # white # 250 medium grey # light grey # 254 nearly-white grey #not in use, orange # light green # black # /red # white # replaces 39, light purple # not in use # dark green This subclass is required when the user chooses to use 'default' theme. Because the segments require a 'Color' class for every theme.
2.022716
2
book/src/ch06/src/descriptors_cpython_2.py
zangyuchen2008/Clean-Code-in-Python-Second-Edition
133
6619582
"""Clean Code in Python - Chapter 6: Descriptors > How Python uses descriptors internally: __slots__ """ from dataclasses import dataclass @dataclass class Coordinate2D: """Example of a class that uses __slots__.""" __slots__ = ("lat", "long") lat: float long: float def __repr__(self): return f"{self.__class__.__name__}({self.lat}, {self.long})"
"""Clean Code in Python - Chapter 6: Descriptors > How Python uses descriptors internally: __slots__ """ from dataclasses import dataclass @dataclass class Coordinate2D: """Example of a class that uses __slots__.""" __slots__ = ("lat", "long") lat: float long: float def __repr__(self): return f"{self.__class__.__name__}({self.lat}, {self.long})"
en
0.577572
Clean Code in Python - Chapter 6: Descriptors > How Python uses descriptors internally: __slots__ Example of a class that uses __slots__.
3.422835
3
dist/Lib/site-packages/neo4jrestclient/traversals.py
nelmiux/CS347-Data_Management
1
6619583
# -*- coding: utf-8 -*- # From https://gist.github.com/1865786 by @aventurella # http://docs.neo4j.org/chunked/snapshot/rest-api-traverse.html # #rest-api-traversal-returning-nodes-below-a-certain-depth from neo4jrestclient import constants from neo4jrestclient.iterable import Iterable from neo4jrestclient.request import Request from neo4jrestclient.exceptions import NotFoundError, StatusException from neo4jrestclient.utils import string_types class GraphTraversal(object): types = None order = None stop = None returnable = None uniqueness = None paginated = None page_size = None time_out = None returns = None is_returnable = None isReturnable = None is_stop_node = None isStopNode = None def __init__(self, start_node=None): self.start_node = start_node is_returnable = self.is_returnable or self.isReturnable is_stop_node = self.is_stop_node or self.isStopNode results = self.start_node.traverse(types=self.types, order=self.order, stop=self.stop, returnable=self.returnable, uniqueness=self.uniqueness, is_stop_node=is_stop_node, is_returnable=is_returnable, paginated=self.paginated, page_size=self.page_size, time_out=self.time_out, returns=self.returns) self._items = results self._index = len(results) def __iter__(self): return self def __next__(self): if self._index == 0: raise StopIteration self._index = self._index - 1 return self._items[self._index] def next(self): return self.__next__() class Order(object): BREADTH_FIRST = constants.BREADTH_FIRST DEPTH_FIRST = constants.DEPTH_FIRST class Uniqueness(object): NODE_GLOBAL = constants.NODE_GLOBAL NONE = constants.NONE RELATIONSHIP_GLOBAL = constants.RELATIONSHIP_GLOBAL NODE_PATH = constants.NODE_PATH RELATIONSHIP_PATH = constants.RELATIONSHIP_PATH class RelationshipDirection(object): ANY = constants.RELATIONSHIPS_ALL ALL = constants.RELATIONSHIPS_ALL INCOMING = constants.RELATIONSHIPS_IN OUTGOING = constants.RELATIONSHIPS_OUT class Filters(object): """Filters answer the question (return true/false) Evaluation.INCLUDE_AND_CONTINUE Evaluation.EXCLUDE_AND_CONTINUE """ ALL = {"language": "builtin", "name": constants.RETURN_ALL_NODES} ALL_BUT_START_NODE = { "language": "builtin", "name": constants.RETURN_ALL_BUT_START_NODE, } class PruneEvaluators(object): """PruneEvaluators answer the question (return true/false) Evaluation.INCLUDE_AND_PRUNE Evaluation.EXCLUDE_AND_PRUNE """ pass class Traverser(object): NODE = constants.NODE RELATIONSHIP = constants.RELATIONSHIP PATH = constants.PATH FULLPATH = constants.FULLPATH def __init__(self, start_node, data, auth=None, cypher=None): self._auth = auth or {} self._cypher = cypher self._data = data self._endpoint = start_node._dic["traverse"] self._cache = {} def request(self, return_type): try: return self._cache[return_type] except KeyError: url = self._endpoint.replace("{returnType}", return_type) response = Request(**self._auth).post(url, data=self._data) if response.status_code == 200: results_list = response.json() self._cache[return_type] = results_list return results_list elif response.status_code == 404: raise NotFoundError(response.status_code, "Node or relationship not found") raise StatusException(response.status_code, "Invalid data sent") @property def nodes(self): from neo4jrestclient.client import Node results = self.request(Traverser.NODE) return Iterable(Node, results, "self", cypher=self._cypher) @property def relationships(self): from neo4jrestclient.client import Relationship results = self.request(Traverser.RELATIONSHIP) return Iterable(Relationship, results, "self") @property def fullpaths(self): raise NotImplementedError() def __iter__(self): from neo4jrestclient.client import Path results = self.request(Traverser.PATH) return Iterable(Path, results, auth=self._auth) class TraversalDescription(object): """https://github.com/neo4j/community/blob/master/kernel/src/main /java/org/neo4j/graphdb/traversal/TraversalDescription.java""" def __init__(self, auth=None, cypher=None): self._auth = auth or {} self._cypher = cypher self._data = {} self.uniqueness(Uniqueness.NODE_GLOBAL) # self.max_depth(1) def uniqueness(self, value): self._data["uniqueness"] = value return self def filter(self, value): try: value["language"] self._data["return_filter"] = value except KeyError: self._data["return_filter"] = { "language": "javascript", "body": value, } return self def prune(self, value, language="javascript"): try: value["language"] self._data["prune_evaluator"] = value except KeyError: self._data["prune_evaluator"] = {"language": language, "body": value} return self def order(self, value): self._data["order"] = value return self def depthFirst(self, value=None): self.order(Order.DEPTH_FIRST) return self def breadthFirst(self, value=None): self.order(Order.BREADTH_FIRST) return self def relationships(self, name, direction=RelationshipDirection.ALL): self._data["relationships"] = [] if (not isinstance(name, string_types) and hasattr(name, "type") and hasattr(name, "direction")): direction = name.direction name = name.type self.relationships_append(name, direction) self.relationships = self.relationships_append return self def relationships_append(self, name, direction=RelationshipDirection.ALL): if (not isinstance(name, string_types) and hasattr(name, "type") and hasattr(name, "direction")): direction = name.direction name = name.type self._data["relationships"].append({ "direction": direction, "type": name, }) return self def max_depth(self, value): self._data["max_depth"] = value def traverse(self, start_node): try: self._data['prune_evaluator'] del self._data["max_depth"] except KeyError: pass return Traverser(start_node, self._data, auth=self._auth, cypher=self._cypher) class Traversal(object): def __init__(self, start_node): self._description = Traversal.description() self._start_node = start_node @property def description(self): return self._description def __iter__(self): return self._description.traverse(self._start_node)
# -*- coding: utf-8 -*- # From https://gist.github.com/1865786 by @aventurella # http://docs.neo4j.org/chunked/snapshot/rest-api-traverse.html # #rest-api-traversal-returning-nodes-below-a-certain-depth from neo4jrestclient import constants from neo4jrestclient.iterable import Iterable from neo4jrestclient.request import Request from neo4jrestclient.exceptions import NotFoundError, StatusException from neo4jrestclient.utils import string_types class GraphTraversal(object): types = None order = None stop = None returnable = None uniqueness = None paginated = None page_size = None time_out = None returns = None is_returnable = None isReturnable = None is_stop_node = None isStopNode = None def __init__(self, start_node=None): self.start_node = start_node is_returnable = self.is_returnable or self.isReturnable is_stop_node = self.is_stop_node or self.isStopNode results = self.start_node.traverse(types=self.types, order=self.order, stop=self.stop, returnable=self.returnable, uniqueness=self.uniqueness, is_stop_node=is_stop_node, is_returnable=is_returnable, paginated=self.paginated, page_size=self.page_size, time_out=self.time_out, returns=self.returns) self._items = results self._index = len(results) def __iter__(self): return self def __next__(self): if self._index == 0: raise StopIteration self._index = self._index - 1 return self._items[self._index] def next(self): return self.__next__() class Order(object): BREADTH_FIRST = constants.BREADTH_FIRST DEPTH_FIRST = constants.DEPTH_FIRST class Uniqueness(object): NODE_GLOBAL = constants.NODE_GLOBAL NONE = constants.NONE RELATIONSHIP_GLOBAL = constants.RELATIONSHIP_GLOBAL NODE_PATH = constants.NODE_PATH RELATIONSHIP_PATH = constants.RELATIONSHIP_PATH class RelationshipDirection(object): ANY = constants.RELATIONSHIPS_ALL ALL = constants.RELATIONSHIPS_ALL INCOMING = constants.RELATIONSHIPS_IN OUTGOING = constants.RELATIONSHIPS_OUT class Filters(object): """Filters answer the question (return true/false) Evaluation.INCLUDE_AND_CONTINUE Evaluation.EXCLUDE_AND_CONTINUE """ ALL = {"language": "builtin", "name": constants.RETURN_ALL_NODES} ALL_BUT_START_NODE = { "language": "builtin", "name": constants.RETURN_ALL_BUT_START_NODE, } class PruneEvaluators(object): """PruneEvaluators answer the question (return true/false) Evaluation.INCLUDE_AND_PRUNE Evaluation.EXCLUDE_AND_PRUNE """ pass class Traverser(object): NODE = constants.NODE RELATIONSHIP = constants.RELATIONSHIP PATH = constants.PATH FULLPATH = constants.FULLPATH def __init__(self, start_node, data, auth=None, cypher=None): self._auth = auth or {} self._cypher = cypher self._data = data self._endpoint = start_node._dic["traverse"] self._cache = {} def request(self, return_type): try: return self._cache[return_type] except KeyError: url = self._endpoint.replace("{returnType}", return_type) response = Request(**self._auth).post(url, data=self._data) if response.status_code == 200: results_list = response.json() self._cache[return_type] = results_list return results_list elif response.status_code == 404: raise NotFoundError(response.status_code, "Node or relationship not found") raise StatusException(response.status_code, "Invalid data sent") @property def nodes(self): from neo4jrestclient.client import Node results = self.request(Traverser.NODE) return Iterable(Node, results, "self", cypher=self._cypher) @property def relationships(self): from neo4jrestclient.client import Relationship results = self.request(Traverser.RELATIONSHIP) return Iterable(Relationship, results, "self") @property def fullpaths(self): raise NotImplementedError() def __iter__(self): from neo4jrestclient.client import Path results = self.request(Traverser.PATH) return Iterable(Path, results, auth=self._auth) class TraversalDescription(object): """https://github.com/neo4j/community/blob/master/kernel/src/main /java/org/neo4j/graphdb/traversal/TraversalDescription.java""" def __init__(self, auth=None, cypher=None): self._auth = auth or {} self._cypher = cypher self._data = {} self.uniqueness(Uniqueness.NODE_GLOBAL) # self.max_depth(1) def uniqueness(self, value): self._data["uniqueness"] = value return self def filter(self, value): try: value["language"] self._data["return_filter"] = value except KeyError: self._data["return_filter"] = { "language": "javascript", "body": value, } return self def prune(self, value, language="javascript"): try: value["language"] self._data["prune_evaluator"] = value except KeyError: self._data["prune_evaluator"] = {"language": language, "body": value} return self def order(self, value): self._data["order"] = value return self def depthFirst(self, value=None): self.order(Order.DEPTH_FIRST) return self def breadthFirst(self, value=None): self.order(Order.BREADTH_FIRST) return self def relationships(self, name, direction=RelationshipDirection.ALL): self._data["relationships"] = [] if (not isinstance(name, string_types) and hasattr(name, "type") and hasattr(name, "direction")): direction = name.direction name = name.type self.relationships_append(name, direction) self.relationships = self.relationships_append return self def relationships_append(self, name, direction=RelationshipDirection.ALL): if (not isinstance(name, string_types) and hasattr(name, "type") and hasattr(name, "direction")): direction = name.direction name = name.type self._data["relationships"].append({ "direction": direction, "type": name, }) return self def max_depth(self, value): self._data["max_depth"] = value def traverse(self, start_node): try: self._data['prune_evaluator'] del self._data["max_depth"] except KeyError: pass return Traverser(start_node, self._data, auth=self._auth, cypher=self._cypher) class Traversal(object): def __init__(self, start_node): self._description = Traversal.description() self._start_node = start_node @property def description(self): return self._description def __iter__(self): return self._description.traverse(self._start_node)
en
0.594099
# -*- coding: utf-8 -*- # From https://gist.github.com/1865786 by @aventurella # http://docs.neo4j.org/chunked/snapshot/rest-api-traverse.html # #rest-api-traversal-returning-nodes-below-a-certain-depth Filters answer the question (return true/false) Evaluation.INCLUDE_AND_CONTINUE Evaluation.EXCLUDE_AND_CONTINUE PruneEvaluators answer the question (return true/false) Evaluation.INCLUDE_AND_PRUNE Evaluation.EXCLUDE_AND_PRUNE https://github.com/neo4j/community/blob/master/kernel/src/main /java/org/neo4j/graphdb/traversal/TraversalDescription.java # self.max_depth(1)
2.523059
3
tests/test_site/__init__.py
granduke/python-django
0
6619584
from __future__ import absolute_import from . import test_middleware
from __future__ import absolute_import from . import test_middleware
none
1
1.055879
1
basxconnect/core/wizards/add_person.py
weblate/basxconnect
1
6619585
<filename>basxconnect/core/wizards/add_person.py<gh_stars>1-10 import htmlgenerator as hg from bread import layout from bread.forms.forms import breadmodelform_factory from bread.utils import pretty_modelname from bread.utils.urls import reverse_model from django import forms from django.apps import apps from django.contrib.auth.mixins import PermissionRequiredMixin from django.shortcuts import redirect from django.urls import reverse, reverse_lazy from django.utils.translation import gettext_lazy as _ from formtools.wizard.views import NamedUrlSessionWizardView from ..models import LegalPerson, NaturalPerson, Person, PersonAssociation, Postal, Term ADD_FORM_LAYOUTS = { NaturalPerson: hg.BaseElement( layout.grid.Row( layout.grid.Col(layout.form.FormField("first_name")), layout.grid.Col(layout.form.FormField("last_name")), ), layout.grid.Row( layout.grid.Col(layout.form.FormField("salutation")), layout.grid.Col(layout.form.FormField("gender")), ), ), LegalPerson: hg.DIV( layout.form.FormField("name"), layout.form.FormField("name_addition") ), PersonAssociation: hg.DIV(layout.form.FormField("name")), } ADD_ADDRESS_LAYOUT = layout.grid.Grid( layout.grid.Row( layout.grid.Col(_("Address"), style="font-weight: 700; margin-bottom: 2rem") ), layout.grid.Row(layout.grid.Col(layout.form.FormField("address"))), layout.grid.Row( layout.grid.Col( layout.form.FormField("postcode"), ), layout.grid.Col(layout.form.FormField("city")), ), layout.grid.Row(layout.grid.Col(layout.form.FormField("country"))), ) def generate_wizard_form(formlayout): # needs to be rendered in view of type NamedUrlSessionWizardView in order to work correctly def go_back_url(context, element): url = reverse( context["request"].resolver_match.view_name, kwargs={"step": context["wizard"]["steps"].prev}, ) return f"document.location='{url}'" return layout.form.Form( hg.C("wizard.form"), layout.form.Form( hg.C("wizard.management_form"), layout.form.FormField("current_step"), standalone=False, ), formlayout, hg.DIV( hg.DIV( hg.If( hg.C("wizard.steps.prev"), layout.button.Button( _("Back"), buttontype="secondary", onclick=hg.F(go_back_url), ), ), hg.If( hg.F( lambda c, e: c["wizard"]["steps"].last == c["wizard"]["steps"].current ), layout.button.Button( _("Complete"), type="submit", style="margin-left: 1rem" ), layout.button.Button( _("Continue"), type="submit", style="margin-left: 1rem" ), ), ), style="align-items: flex-end", _class="bx--form-item", ), ) class SearchForm(forms.Form): name_of_existing_person = forms.CharField( label=_("Check for existing people before continuing"), max_length=255, required=False, ) searchbutton = layout.search.Search( widgetattributes={ "placeholder": _("Start typing to search for a person..."), "hx_get": reverse_lazy("basxconnect.core.views.searchperson"), "hx_trigger": "changed, keyup changed delay:100ms", "hx_target": "#search-results", "name": "q", }, ) # clear search field when search box is emptied searchbutton[3].attributes[ "onclick" ] = "this.parentElement.nextElementSibling.innerHTML = ''" title = _("Search person") _layout = hg.DIV( hg.DIV( _( "Before a new person can be added it must be confirmed that the person does not exists yet." ), style="margin-bottom: 2rem", ), searchbutton, hg.DIV(id="search-results", style="margin-bottom: 2rem;"), ) class ChooseType(forms.Form): PERSON_TYPES = { "core.NaturalPerson": pretty_modelname(NaturalPerson), "core.LegalPerson": pretty_modelname(LegalPerson), "core.PersonAssociation": pretty_modelname(PersonAssociation), } persontype = forms.TypedChoiceField( label=_("Type of person"), choices=tuple(PERSON_TYPES.items()), coerce=lambda a: apps.get_model(a), empty_value=None, ) title = _("Choose person main type") _layout = hg.BaseElement( hg.DIV( _("Please choose what type of person you want to add:"), style="margin-bottom: 2rem", ), layout.form.FormField("persontype"), ) class ChooseSubType(forms.Form): ALLOWED_SUBTYPE_CATEGORY = { Person: None, NaturalPerson: "naturaltype", LegalPerson: "legaltype", PersonAssociation: "associationtype", } subtype = forms.ModelChoiceField( label=_("Subtype of person"), queryset=Term.objects.all(), required=False ) def __init__(self, persontype, *args, **kwargs): super().__init__(*args, **kwargs) subtype_category = ChooseSubType.ALLOWED_SUBTYPE_CATEGORY.get(persontype) if subtype_category is None: self.fields = {} else: self.fields["subtype"].queryset = Term.objects.filter( category__slug=subtype_category ) title = _("Choose person type") _layout = layout.form.FormField("subtype") class AddPersonInformation(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) title = _("Add person") _layout = hg.DIV("Please select a person type first") class ConfirmNewPerson(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) title = _("Finish") _layout = hg.DIV("Please select a person type first") def generate_add_form_for(model, request, data, files, initial=None): form = breadmodelform_factory( request=request, model=model, layout=ADD_FORM_LAYOUTS[model] )(data, files, initial=initial) for fieldname, field in breadmodelform_factory( request, Postal, ADD_ADDRESS_LAYOUT )().fields.items(): form.fields[fieldname] = field formlayout = hg.BaseElement( layout.grid.Grid(ADD_FORM_LAYOUTS[model].copy(), style="margin-bottom: 2rem"), ADD_ADDRESS_LAYOUT.copy(), ) form._layout = formlayout return form # The WizardView contains mostly control-flow logic and some configuration class AddPersonWizard(PermissionRequiredMixin, NamedUrlSessionWizardView): kwargs = {"url_name": "core:person:add_wizard", "urlparams": {"step": "str"}} urlparams = (("step", str),) permission_required = "core.add_person" form_list = [ ("Search", SearchForm), ("Type", ChooseType), ("Subtype", ChooseSubType), ("Information", AddPersonInformation), ("Confirmation", ConfirmNewPerson), ] # translation detection _("Search") _("Type") _("Subtype") _("Information") _("Confirmation") template_name = "core/wizards/add_person.html" condition_dict = { "Subtype": lambda wizard: ChooseSubType.ALLOWED_SUBTYPE_CATEGORY.get( (wizard.get_cleaned_data_for_step("Type") or {}).get("persontype") ) } def get_person_type(self): return (self.get_cleaned_data_for_step("Type") or {}).get("persontype") def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) steps = [] for i, step in enumerate(self.get_form_list().keys()): status = "incomplete" if i < self.steps.index: status = "complete" if step == self.steps.current: status = "current" steps.append((_(step), status)) context["layout"] = lambda request: hg.BaseElement( hg.H3(_("Add new person")), hg.H4(self.get_form().title), layout.progress_indicator.ProgressIndicator( steps, style="margin-bottom: 2rem", ), generate_wizard_form(self.get_form()._layout), ) return context def get_form_kwargs(self, step): ret = super().get_form_kwargs() if step == "Subtype": ret.update({"persontype": self.get_person_type()}) return ret def get_form(self, step=None, data=None, files=None): form = super().get_form(step, data, files) if step is None: step = self.steps.current # step 3 and 4 depend on the select type, so we generate the forms dynamically if step in ("Information", "Confirmation"): persontype = self.get_person_type() if persontype: if step == "Information": form = generate_add_form_for( persontype, self.request, data, files, ) else: form = generate_add_form_for( persontype, self.request, data, files, self.get_cleaned_data_for_step("Information"), ) form._layout.insert( 0, layout.notification.InlineNotification( "", _("Review and confirm the entered information"), lowcontrast=True, hideclosebutton=True, ), ) for fieldname in form.fields: form.fields[fieldname].disabled = True form.fields[fieldname].widget.attrs["style"] = "color: #000" form.title = _("Add %s") % pretty_modelname(persontype) return form def done(self, form_list, **kwargs): # in case the new person had a subtype set, we need to set the attribute here subtype = (self.get_cleaned_data_for_step("Subtype") or {}).get("subtype") if subtype: list(form_list)[-1].instance.type = subtype newperson = list(form_list)[-1].save() newperson.core_postal_list.create( **{ k: v for k, v in list(form_list)[-1].cleaned_data.items() if k in ("address", "city", "postcode", "country") } ) return redirect( reverse_model( newperson._meta.model, "read", kwargs={"pk": newperson.pk}, ) )
<filename>basxconnect/core/wizards/add_person.py<gh_stars>1-10 import htmlgenerator as hg from bread import layout from bread.forms.forms import breadmodelform_factory from bread.utils import pretty_modelname from bread.utils.urls import reverse_model from django import forms from django.apps import apps from django.contrib.auth.mixins import PermissionRequiredMixin from django.shortcuts import redirect from django.urls import reverse, reverse_lazy from django.utils.translation import gettext_lazy as _ from formtools.wizard.views import NamedUrlSessionWizardView from ..models import LegalPerson, NaturalPerson, Person, PersonAssociation, Postal, Term ADD_FORM_LAYOUTS = { NaturalPerson: hg.BaseElement( layout.grid.Row( layout.grid.Col(layout.form.FormField("first_name")), layout.grid.Col(layout.form.FormField("last_name")), ), layout.grid.Row( layout.grid.Col(layout.form.FormField("salutation")), layout.grid.Col(layout.form.FormField("gender")), ), ), LegalPerson: hg.DIV( layout.form.FormField("name"), layout.form.FormField("name_addition") ), PersonAssociation: hg.DIV(layout.form.FormField("name")), } ADD_ADDRESS_LAYOUT = layout.grid.Grid( layout.grid.Row( layout.grid.Col(_("Address"), style="font-weight: 700; margin-bottom: 2rem") ), layout.grid.Row(layout.grid.Col(layout.form.FormField("address"))), layout.grid.Row( layout.grid.Col( layout.form.FormField("postcode"), ), layout.grid.Col(layout.form.FormField("city")), ), layout.grid.Row(layout.grid.Col(layout.form.FormField("country"))), ) def generate_wizard_form(formlayout): # needs to be rendered in view of type NamedUrlSessionWizardView in order to work correctly def go_back_url(context, element): url = reverse( context["request"].resolver_match.view_name, kwargs={"step": context["wizard"]["steps"].prev}, ) return f"document.location='{url}'" return layout.form.Form( hg.C("wizard.form"), layout.form.Form( hg.C("wizard.management_form"), layout.form.FormField("current_step"), standalone=False, ), formlayout, hg.DIV( hg.DIV( hg.If( hg.C("wizard.steps.prev"), layout.button.Button( _("Back"), buttontype="secondary", onclick=hg.F(go_back_url), ), ), hg.If( hg.F( lambda c, e: c["wizard"]["steps"].last == c["wizard"]["steps"].current ), layout.button.Button( _("Complete"), type="submit", style="margin-left: 1rem" ), layout.button.Button( _("Continue"), type="submit", style="margin-left: 1rem" ), ), ), style="align-items: flex-end", _class="bx--form-item", ), ) class SearchForm(forms.Form): name_of_existing_person = forms.CharField( label=_("Check for existing people before continuing"), max_length=255, required=False, ) searchbutton = layout.search.Search( widgetattributes={ "placeholder": _("Start typing to search for a person..."), "hx_get": reverse_lazy("basxconnect.core.views.searchperson"), "hx_trigger": "changed, keyup changed delay:100ms", "hx_target": "#search-results", "name": "q", }, ) # clear search field when search box is emptied searchbutton[3].attributes[ "onclick" ] = "this.parentElement.nextElementSibling.innerHTML = ''" title = _("Search person") _layout = hg.DIV( hg.DIV( _( "Before a new person can be added it must be confirmed that the person does not exists yet." ), style="margin-bottom: 2rem", ), searchbutton, hg.DIV(id="search-results", style="margin-bottom: 2rem;"), ) class ChooseType(forms.Form): PERSON_TYPES = { "core.NaturalPerson": pretty_modelname(NaturalPerson), "core.LegalPerson": pretty_modelname(LegalPerson), "core.PersonAssociation": pretty_modelname(PersonAssociation), } persontype = forms.TypedChoiceField( label=_("Type of person"), choices=tuple(PERSON_TYPES.items()), coerce=lambda a: apps.get_model(a), empty_value=None, ) title = _("Choose person main type") _layout = hg.BaseElement( hg.DIV( _("Please choose what type of person you want to add:"), style="margin-bottom: 2rem", ), layout.form.FormField("persontype"), ) class ChooseSubType(forms.Form): ALLOWED_SUBTYPE_CATEGORY = { Person: None, NaturalPerson: "naturaltype", LegalPerson: "legaltype", PersonAssociation: "associationtype", } subtype = forms.ModelChoiceField( label=_("Subtype of person"), queryset=Term.objects.all(), required=False ) def __init__(self, persontype, *args, **kwargs): super().__init__(*args, **kwargs) subtype_category = ChooseSubType.ALLOWED_SUBTYPE_CATEGORY.get(persontype) if subtype_category is None: self.fields = {} else: self.fields["subtype"].queryset = Term.objects.filter( category__slug=subtype_category ) title = _("Choose person type") _layout = layout.form.FormField("subtype") class AddPersonInformation(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) title = _("Add person") _layout = hg.DIV("Please select a person type first") class ConfirmNewPerson(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) title = _("Finish") _layout = hg.DIV("Please select a person type first") def generate_add_form_for(model, request, data, files, initial=None): form = breadmodelform_factory( request=request, model=model, layout=ADD_FORM_LAYOUTS[model] )(data, files, initial=initial) for fieldname, field in breadmodelform_factory( request, Postal, ADD_ADDRESS_LAYOUT )().fields.items(): form.fields[fieldname] = field formlayout = hg.BaseElement( layout.grid.Grid(ADD_FORM_LAYOUTS[model].copy(), style="margin-bottom: 2rem"), ADD_ADDRESS_LAYOUT.copy(), ) form._layout = formlayout return form # The WizardView contains mostly control-flow logic and some configuration class AddPersonWizard(PermissionRequiredMixin, NamedUrlSessionWizardView): kwargs = {"url_name": "core:person:add_wizard", "urlparams": {"step": "str"}} urlparams = (("step", str),) permission_required = "core.add_person" form_list = [ ("Search", SearchForm), ("Type", ChooseType), ("Subtype", ChooseSubType), ("Information", AddPersonInformation), ("Confirmation", ConfirmNewPerson), ] # translation detection _("Search") _("Type") _("Subtype") _("Information") _("Confirmation") template_name = "core/wizards/add_person.html" condition_dict = { "Subtype": lambda wizard: ChooseSubType.ALLOWED_SUBTYPE_CATEGORY.get( (wizard.get_cleaned_data_for_step("Type") or {}).get("persontype") ) } def get_person_type(self): return (self.get_cleaned_data_for_step("Type") or {}).get("persontype") def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) steps = [] for i, step in enumerate(self.get_form_list().keys()): status = "incomplete" if i < self.steps.index: status = "complete" if step == self.steps.current: status = "current" steps.append((_(step), status)) context["layout"] = lambda request: hg.BaseElement( hg.H3(_("Add new person")), hg.H4(self.get_form().title), layout.progress_indicator.ProgressIndicator( steps, style="margin-bottom: 2rem", ), generate_wizard_form(self.get_form()._layout), ) return context def get_form_kwargs(self, step): ret = super().get_form_kwargs() if step == "Subtype": ret.update({"persontype": self.get_person_type()}) return ret def get_form(self, step=None, data=None, files=None): form = super().get_form(step, data, files) if step is None: step = self.steps.current # step 3 and 4 depend on the select type, so we generate the forms dynamically if step in ("Information", "Confirmation"): persontype = self.get_person_type() if persontype: if step == "Information": form = generate_add_form_for( persontype, self.request, data, files, ) else: form = generate_add_form_for( persontype, self.request, data, files, self.get_cleaned_data_for_step("Information"), ) form._layout.insert( 0, layout.notification.InlineNotification( "", _("Review and confirm the entered information"), lowcontrast=True, hideclosebutton=True, ), ) for fieldname in form.fields: form.fields[fieldname].disabled = True form.fields[fieldname].widget.attrs["style"] = "color: #000" form.title = _("Add %s") % pretty_modelname(persontype) return form def done(self, form_list, **kwargs): # in case the new person had a subtype set, we need to set the attribute here subtype = (self.get_cleaned_data_for_step("Subtype") or {}).get("subtype") if subtype: list(form_list)[-1].instance.type = subtype newperson = list(form_list)[-1].save() newperson.core_postal_list.create( **{ k: v for k, v in list(form_list)[-1].cleaned_data.items() if k in ("address", "city", "postcode", "country") } ) return redirect( reverse_model( newperson._meta.model, "read", kwargs={"pk": newperson.pk}, ) )
en
0.852296
# needs to be rendered in view of type NamedUrlSessionWizardView in order to work correctly # clear search field when search box is emptied # The WizardView contains mostly control-flow logic and some configuration # translation detection # step 3 and 4 depend on the select type, so we generate the forms dynamically #000" # in case the new person had a subtype set, we need to set the attribute here
1.818164
2
plaso/parsers/winreg_plugins/mrulistex.py
Defense-Cyber-Crime-Center/plaso
2
6619586
# -*- coding: utf-8 -*- """This file contains MRUListEx Windows Registry plugins.""" import abc import logging import construct from plaso.events import windows_events from plaso.lib import binary from plaso.parsers import winreg from plaso.parsers.shared import shell_items from plaso.parsers.winreg_plugins import interface # A mixin class is used here to not to have the duplicate functionality # to parse the MRUListEx Registry values. However multiple inheritance # and thus mixins are to be used sparsely in this codebase, hence we need # to find a better solution in not needing to distinguish between key and # value plugins. # TODO: refactor Registry key and value plugin to rid ourselves of the mixin. class MRUListExPluginMixin(object): """Class for common MRUListEx Windows Registry plugin functionality.""" _MRULISTEX_STRUCT = construct.Range( 1, 500, construct.ULInt32(u'entry_number')) @abc.abstractmethod def _ParseMRUListExEntryValue( self, parser_mediator, key, entry_index, entry_number, **kwargs): """Parses the MRUListEx entry value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: the Registry key (instance of winreg.WinRegKey) that contains the MRUListEx value. entry_index: integer value representing the MRUListEx entry index. entry_number: integer value representing the entry number. Returns: A string containing the value. """ def _ParseMRUListExValue(self, key): """Parses the MRUListEx value in a given Registry key. Args: key: the Registry key (instance of winreg.WinRegKey) that contains the MRUListEx value. Returns: A MRUListEx value generator, which returns the MRU index number and entry value. """ mru_list_value = key.GetValue(u'MRUListEx') # The key exists but does not contain a value named "MRUListEx". if not mru_list_value: return enumerate([]) try: mru_list = self._MRULISTEX_STRUCT.parse(mru_list_value.data) except construct.FieldError: logging.warning(u'[{0:s}] Unable to parse the MRU key: {1:s}'.format( self.NAME, key.path)) return enumerate([]) return enumerate(mru_list) def _ParseMRUListExKey( self, parser_mediator, key, registry_file_type=None, codepage=u'cp1252'): """Extract event objects from a MRUListEx Registry key. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: the Registry key (instance of winreg.WinRegKey). registry_file_type: Optional string containing the Windows Registry file type, e.g. NTUSER, SOFTWARE. The default is None. codepage: Optional extended ASCII string codepage. The default is cp1252. """ text_dict = {} for entry_index, entry_number in self._ParseMRUListExValue(key): # TODO: detect if list ends prematurely. # MRU lists are terminated with 0xffffffff (-1). if entry_number == 0xffffffff: break value_string = self._ParseMRUListExEntryValue( parser_mediator, key, entry_index, entry_number, codepage=codepage) value_text = u'Index: {0:d} [MRU Value {1:d}]'.format( entry_index + 1, entry_number) text_dict[value_text] = value_string event_object = windows_events.WindowsRegistryEvent( key.last_written_timestamp, key.path, text_dict, offset=key.offset, registry_file_type=registry_file_type, source_append=u': MRUListEx') parser_mediator.ProduceEvent(event_object) class MRUListExStringPlugin(interface.ValuePlugin, MRUListExPluginMixin): """Windows Registry plugin to parse a string MRUListEx.""" NAME = u'mrulistex_string' DESCRIPTION = u'Parser for Most Recently Used (MRU) Registry data.' REG_TYPE = u'any' REG_VALUES = frozenset([u'MRUListEx', u'0']) URLS = [ u'http://forensicartifacts.com/2011/02/recentdocs/', u'https://github.com/libyal/winreg-kb/wiki/MRU-keys'] _STRING_STRUCT = construct.Struct( u'string_and_shell_item', construct.RepeatUntil( lambda obj, ctx: obj == b'\x00\x00', construct.Field(u'string', 2))) def _ParseMRUListExEntryValue( self, parser_mediator, key, entry_index, entry_number, **unused_kwargs): """Parses the MRUListEx entry value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: the Registry key (instance of winreg.WinRegKey) that contains the MRUListEx value. entry_index: integer value representing the MRUListEx entry index. entry_number: integer value representing the entry number. Returns: A string containing the value. """ value_string = u'' value = key.GetValue(u'{0:d}'.format(entry_number)) if value is None: logging.debug( u'[{0:s}] Missing MRUListEx entry value: {1:d} in key: {2:s}.'.format( self.NAME, entry_number, key.path)) elif value.DataIsString(): value_string = value.data elif value.DataIsBinaryData(): logging.debug(( u'[{0:s}] Non-string MRUListEx entry value: {1:d} parsed as string ' u'in key: {2:s}.').format(self.NAME, entry_number, key.path)) utf16_stream = binary.ByteStreamCopyToUtf16Stream(value.data) try: value_string = utf16_stream.decode(u'utf-16-le') except UnicodeDecodeError as exception: value_string = binary.HexifyBuffer(utf16_stream) logging.warning(( u'[{0:s}] Unable to decode UTF-16 stream: {1:s} in MRUListEx entry ' u'value: {2:d} in key: {3:s} with error: {4:s}').format( self.NAME, value_string, entry_number, key.path, exception)) return value_string def GetEntries( self, parser_mediator, key=None, registry_file_type=None, codepage=u'cp1252', **kwargs): """Extract event objects from a Registry key containing a MRUListEx value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: Optional Registry key (instance of winreg.WinRegKey). The default is None. registry_file_type: Optional string containing the Windows Registry file type, e.g. NTUSER, SOFTWARE. The default is None. codepage: Optional extended ASCII string codepage. The default is cp1252. """ self._ParseMRUListExKey( parser_mediator, key, registry_file_type=registry_file_type, codepage=codepage) def Process(self, parser_mediator, key=None, codepage=u'cp1252', **kwargs): """Determine if we can process this Registry key or not. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: Optional Windows Registry key (instance of WinRegKey). The default is None. codepage: Optional extended ASCII string codepage. The default is cp1252. """ # Prevent this plugin triggering on sub paths of non-string MRUListEx # values. if (u'BagMRU' in key.path or u'Explorer\\StreamMRU' in key.path or u'\\Explorer\\ComDlg32\\OpenSavePidlMRU' in key.path): return super(MRUListExStringPlugin, self).Process( parser_mediator, key=key, codepage=codepage) class MRUListExShellItemListPlugin(interface.KeyPlugin, MRUListExPluginMixin): """Windows Registry plugin to parse a shell item list MRUListEx.""" NAME = u'mrulistex_shell_item_list' DESCRIPTION = u'Parser for Most Recently Used (MRU) Registry data.' REG_TYPE = u'any' REG_KEYS = frozenset([ # The regular expression indicated a file extension (.jpg) or '*'. (u'\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\' u'OpenSavePidlMRU'), u'\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StreamMRU']) def _ParseMRUListExEntryValue( self, parser_mediator, key, entry_index, entry_number, codepage=u'cp1252', **unused_kwargs): """Parses the MRUListEx entry value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: the Registry key (instance of winreg.WinRegKey) that contains the MRUListEx value. entry_index: integer value representing the MRUListEx entry index. entry_number: integer value representing the entry number. codepage: Optional extended ASCII string codepage. The default is cp1252. Returns: A string containing the value. """ value_string = u'' value = key.GetValue(u'{0:d}'.format(entry_number)) if value is None: logging.debug( u'[{0:s}] Missing MRUListEx entry value: {1:d} in key: {2:s}.'.format( self.NAME, entry_number, key.path)) elif not value.DataIsBinaryData(): logging.debug(( u'[{0:s}] Non-binary MRUListEx entry value: {1:d} in key: ' u'{2:s}.').format(self.NAME, entry_number, key.path)) elif value.data: shell_items_parser = shell_items.ShellItemsParser(key.path) shell_items_parser.UpdateChainAndParse( parser_mediator, value.data, None, codepage=codepage) value_string = u'Shell item path: {0:s}'.format( shell_items_parser.CopyToPath()) return value_string def GetEntries( self, parser_mediator, key=None, registry_file_type=None, codepage=u'cp1252', **kwargs): """Extract event objects from a Registry key containing a MRUListEx value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: Optional Registry key (instance of winreg.WinRegKey). The default is None. registry_file_type: Optional string containing the Windows Registry file type, e.g. NTUSER, SOFTWARE. The default is None. codepage: Optional extended ASCII string codepage. The default is cp1252. """ if key.name != u'OpenSavePidlMRU': self._ParseMRUListExKey( parser_mediator, key, registry_file_type=registry_file_type, codepage=codepage) if key.name == u'OpenSavePidlMRU': # For the OpenSavePidlMRU MRUListEx we also need to parse its subkeys # since the Registry key path does not support wildcards yet. for subkey in key.GetSubkeys(): self._ParseMRUListExKey( parser_mediator, subkey, registry_file_type=registry_file_type, codepage=codepage) class MRUListExStringAndShellItemPlugin( interface.KeyPlugin, MRUListExPluginMixin): """Windows Registry plugin to parse a string and shell item MRUListEx.""" NAME = u'mrulistex_string_and_shell_item' DESCRIPTION = u'Parser for Most Recently Used (MRU) Registry data.' REG_TYPE = u'any' REG_KEYS = frozenset([ u'\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RecentDocs']) _STRING_AND_SHELL_ITEM_STRUCT = construct.Struct( u'string_and_shell_item', construct.RepeatUntil( lambda obj, ctx: obj == b'\x00\x00', construct.Field(u'string', 2)), construct.Anchor(u'shell_item')) def _ParseMRUListExEntryValue( self, parser_mediator, key, entry_index, entry_number, codepage=u'cp1252', **unused_kwargs): """Parses the MRUListEx entry value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: the Registry key (instance of winreg.WinRegKey) that contains the MRUListEx value. entry_index: integer value representing the MRUListEx entry index. entry_number: integer value representing the entry number. codepage: Optional extended ASCII string codepage. The default is cp1252. Returns: A string containing the value. """ value_string = u'' value = key.GetValue(u'{0:d}'.format(entry_number)) if value is None: logging.debug( u'[{0:s}] Missing MRUListEx entry value: {1:d} in key: {2:s}.'.format( self.NAME, entry_number, key.path)) elif not value.DataIsBinaryData(): logging.debug(( u'[{0:s}] Non-binary MRUListEx entry value: {1:d} in key: ' u'{2:s}.').format(self.NAME, entry_number, key.path)) elif value.data: value_struct = self._STRING_AND_SHELL_ITEM_STRUCT.parse(value.data) try: # The struct includes the end-of-string character that we need # to strip off. path = b''.join(value_struct.string).decode(u'utf16')[:-1] except UnicodeDecodeError as exception: logging.warning(( u'[{0:s}] Unable to decode string MRUListEx entry value: {1:d} ' u'in key: {2:s} with error: {3:s}').format( self.NAME, entry_number, key.path, exception)) path = u'' if path: shell_item_list_data = value.data[value_struct.shell_item:] if not shell_item_list_data: logging.debug(( u'[{0:s}] Missing shell item in MRUListEx entry value: {1:d}' u'in key: {2:s}').format(self.NAME, entry_number, key.path)) value_string = u'Path: {0:s}'.format(path) else: shell_items_parser = shell_items.ShellItemsParser(key.path) shell_items_parser.UpdateChainAndParse( parser_mediator, shell_item_list_data, None, codepage=codepage) value_string = u'Path: {0:s}, Shell item: [{1:s}]'.format( path, shell_items_parser.CopyToPath()) return value_string def GetEntries( self, parser_mediator, key=None, registry_file_type=None, codepage=u'cp1252', **kwargs): """Extract event objects from a Registry key containing a MRUListEx value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: Optional Registry key (instance of winreg.WinRegKey). The default is None. registry_file_type: Optional string containing the Windows Registry file type, e.g. NTUSER, SOFTWARE. The default is None. codepage: Optional extended ASCII string codepage. The default is cp1252. """ self._ParseMRUListExKey( parser_mediator, key, registry_file_type=registry_file_type, codepage=codepage) if key.name == u'RecentDocs': # For the RecentDocs MRUListEx we also need to parse its subkeys # since the Registry key path does not support wildcards yet. for subkey in key.GetSubkeys(): self._ParseMRUListExKey( parser_mediator, subkey, registry_file_type=registry_file_type, codepage=codepage) class MRUListExStringAndShellItemListPlugin( interface.KeyPlugin, MRUListExPluginMixin): """Windows Registry plugin to parse a string and shell item list MRUListEx.""" NAME = u'mrulistex_string_and_shell_item_list' DESCRIPTION = u'Parser for Most Recently Used (MRU) Registry data.' REG_TYPE = u'any' REG_KEYS = frozenset([ (u'\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\' u'LastVisitedPidlMRU')]) _STRING_AND_SHELL_ITEM_LIST_STRUCT = construct.Struct( u'string_and_shell_item', construct.RepeatUntil( lambda obj, ctx: obj == b'\x00\x00', construct.Field(u'string', 2)), construct.Anchor(u'shell_item_list')) def _ParseMRUListExEntryValue( self, parser_mediator, key, entry_index, entry_number, codepage=u'cp1252', **unused_kwargs): """Parses the MRUListEx entry value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: the Registry key (instance of winreg.WinRegKey) that contains the MRUListEx value. entry_index: integer value representing the MRUListEx entry index. entry_number: integer value representing the entry number. codepage: Optional extended ASCII string codepage. The default is cp1252. Returns: A string containing the value. """ value_string = u'' value = key.GetValue(u'{0:d}'.format(entry_number)) if value is None: logging.debug( u'[{0:s}] Missing MRUListEx entry value: {1:d} in key: {2:s}.'.format( self.NAME, entry_number, key.path)) elif not value.DataIsBinaryData(): logging.debug(( u'[{0:s}] Non-binary MRUListEx entry value: {1:d} in key: ' u'{2:s}.').format(self.NAME, entry_number, key.path)) elif value.data: value_struct = self._STRING_AND_SHELL_ITEM_LIST_STRUCT.parse(value.data) try: # The struct includes the end-of-string character that we need # to strip off. path = b''.join(value_struct.string).decode(u'utf16')[:-1] except UnicodeDecodeError as exception: logging.warning(( u'[{0:s}] Unable to decode string MRUListEx entry value: {1:d} ' u'in key: {2:s} with error: {3:s}').format( self.NAME, entry_number, key.path, exception)) path = u'' if path: shell_item_list_data = value.data[value_struct.shell_item_list:] if not shell_item_list_data: logging.debug(( u'[{0:s}] Missing shell item in MRUListEx entry value: {1:d}' u'in key: {2:s}').format(self.NAME, entry_number, key.path)) value_string = u'Path: {0:s}'.format(path) else: shell_items_parser = shell_items.ShellItemsParser(key.path) shell_items_parser.UpdateChainAndParse( parser_mediator, shell_item_list_data, None, codepage=codepage) value_string = u'Path: {0:s}, Shell item path: {1:s}'.format( path, shell_items_parser.CopyToPath()) return value_string def GetEntries( self, parser_mediator, key=None, registry_file_type=None, codepage=u'cp1252', **kwargs): """Extract event objects from a Registry key containing a MRUListEx value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: Optional Registry key (instance of winreg.WinRegKey). The default is None. registry_file_type: Optional string containing the Windows Registry file type, e.g. NTUSER, SOFTWARE. The default is None. codepage: Optional extended ASCII string codepage. The default is cp1252. """ self._ParseMRUListExKey( parser_mediator, key, registry_file_type=registry_file_type, codepage=codepage) winreg.WinRegistryParser.RegisterPlugins([ MRUListExStringPlugin, MRUListExShellItemListPlugin, MRUListExStringAndShellItemPlugin, MRUListExStringAndShellItemListPlugin])
# -*- coding: utf-8 -*- """This file contains MRUListEx Windows Registry plugins.""" import abc import logging import construct from plaso.events import windows_events from plaso.lib import binary from plaso.parsers import winreg from plaso.parsers.shared import shell_items from plaso.parsers.winreg_plugins import interface # A mixin class is used here to not to have the duplicate functionality # to parse the MRUListEx Registry values. However multiple inheritance # and thus mixins are to be used sparsely in this codebase, hence we need # to find a better solution in not needing to distinguish between key and # value plugins. # TODO: refactor Registry key and value plugin to rid ourselves of the mixin. class MRUListExPluginMixin(object): """Class for common MRUListEx Windows Registry plugin functionality.""" _MRULISTEX_STRUCT = construct.Range( 1, 500, construct.ULInt32(u'entry_number')) @abc.abstractmethod def _ParseMRUListExEntryValue( self, parser_mediator, key, entry_index, entry_number, **kwargs): """Parses the MRUListEx entry value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: the Registry key (instance of winreg.WinRegKey) that contains the MRUListEx value. entry_index: integer value representing the MRUListEx entry index. entry_number: integer value representing the entry number. Returns: A string containing the value. """ def _ParseMRUListExValue(self, key): """Parses the MRUListEx value in a given Registry key. Args: key: the Registry key (instance of winreg.WinRegKey) that contains the MRUListEx value. Returns: A MRUListEx value generator, which returns the MRU index number and entry value. """ mru_list_value = key.GetValue(u'MRUListEx') # The key exists but does not contain a value named "MRUListEx". if not mru_list_value: return enumerate([]) try: mru_list = self._MRULISTEX_STRUCT.parse(mru_list_value.data) except construct.FieldError: logging.warning(u'[{0:s}] Unable to parse the MRU key: {1:s}'.format( self.NAME, key.path)) return enumerate([]) return enumerate(mru_list) def _ParseMRUListExKey( self, parser_mediator, key, registry_file_type=None, codepage=u'cp1252'): """Extract event objects from a MRUListEx Registry key. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: the Registry key (instance of winreg.WinRegKey). registry_file_type: Optional string containing the Windows Registry file type, e.g. NTUSER, SOFTWARE. The default is None. codepage: Optional extended ASCII string codepage. The default is cp1252. """ text_dict = {} for entry_index, entry_number in self._ParseMRUListExValue(key): # TODO: detect if list ends prematurely. # MRU lists are terminated with 0xffffffff (-1). if entry_number == 0xffffffff: break value_string = self._ParseMRUListExEntryValue( parser_mediator, key, entry_index, entry_number, codepage=codepage) value_text = u'Index: {0:d} [MRU Value {1:d}]'.format( entry_index + 1, entry_number) text_dict[value_text] = value_string event_object = windows_events.WindowsRegistryEvent( key.last_written_timestamp, key.path, text_dict, offset=key.offset, registry_file_type=registry_file_type, source_append=u': MRUListEx') parser_mediator.ProduceEvent(event_object) class MRUListExStringPlugin(interface.ValuePlugin, MRUListExPluginMixin): """Windows Registry plugin to parse a string MRUListEx.""" NAME = u'mrulistex_string' DESCRIPTION = u'Parser for Most Recently Used (MRU) Registry data.' REG_TYPE = u'any' REG_VALUES = frozenset([u'MRUListEx', u'0']) URLS = [ u'http://forensicartifacts.com/2011/02/recentdocs/', u'https://github.com/libyal/winreg-kb/wiki/MRU-keys'] _STRING_STRUCT = construct.Struct( u'string_and_shell_item', construct.RepeatUntil( lambda obj, ctx: obj == b'\x00\x00', construct.Field(u'string', 2))) def _ParseMRUListExEntryValue( self, parser_mediator, key, entry_index, entry_number, **unused_kwargs): """Parses the MRUListEx entry value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: the Registry key (instance of winreg.WinRegKey) that contains the MRUListEx value. entry_index: integer value representing the MRUListEx entry index. entry_number: integer value representing the entry number. Returns: A string containing the value. """ value_string = u'' value = key.GetValue(u'{0:d}'.format(entry_number)) if value is None: logging.debug( u'[{0:s}] Missing MRUListEx entry value: {1:d} in key: {2:s}.'.format( self.NAME, entry_number, key.path)) elif value.DataIsString(): value_string = value.data elif value.DataIsBinaryData(): logging.debug(( u'[{0:s}] Non-string MRUListEx entry value: {1:d} parsed as string ' u'in key: {2:s}.').format(self.NAME, entry_number, key.path)) utf16_stream = binary.ByteStreamCopyToUtf16Stream(value.data) try: value_string = utf16_stream.decode(u'utf-16-le') except UnicodeDecodeError as exception: value_string = binary.HexifyBuffer(utf16_stream) logging.warning(( u'[{0:s}] Unable to decode UTF-16 stream: {1:s} in MRUListEx entry ' u'value: {2:d} in key: {3:s} with error: {4:s}').format( self.NAME, value_string, entry_number, key.path, exception)) return value_string def GetEntries( self, parser_mediator, key=None, registry_file_type=None, codepage=u'cp1252', **kwargs): """Extract event objects from a Registry key containing a MRUListEx value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: Optional Registry key (instance of winreg.WinRegKey). The default is None. registry_file_type: Optional string containing the Windows Registry file type, e.g. NTUSER, SOFTWARE. The default is None. codepage: Optional extended ASCII string codepage. The default is cp1252. """ self._ParseMRUListExKey( parser_mediator, key, registry_file_type=registry_file_type, codepage=codepage) def Process(self, parser_mediator, key=None, codepage=u'cp1252', **kwargs): """Determine if we can process this Registry key or not. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: Optional Windows Registry key (instance of WinRegKey). The default is None. codepage: Optional extended ASCII string codepage. The default is cp1252. """ # Prevent this plugin triggering on sub paths of non-string MRUListEx # values. if (u'BagMRU' in key.path or u'Explorer\\StreamMRU' in key.path or u'\\Explorer\\ComDlg32\\OpenSavePidlMRU' in key.path): return super(MRUListExStringPlugin, self).Process( parser_mediator, key=key, codepage=codepage) class MRUListExShellItemListPlugin(interface.KeyPlugin, MRUListExPluginMixin): """Windows Registry plugin to parse a shell item list MRUListEx.""" NAME = u'mrulistex_shell_item_list' DESCRIPTION = u'Parser for Most Recently Used (MRU) Registry data.' REG_TYPE = u'any' REG_KEYS = frozenset([ # The regular expression indicated a file extension (.jpg) or '*'. (u'\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\' u'OpenSavePidlMRU'), u'\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StreamMRU']) def _ParseMRUListExEntryValue( self, parser_mediator, key, entry_index, entry_number, codepage=u'cp1252', **unused_kwargs): """Parses the MRUListEx entry value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: the Registry key (instance of winreg.WinRegKey) that contains the MRUListEx value. entry_index: integer value representing the MRUListEx entry index. entry_number: integer value representing the entry number. codepage: Optional extended ASCII string codepage. The default is cp1252. Returns: A string containing the value. """ value_string = u'' value = key.GetValue(u'{0:d}'.format(entry_number)) if value is None: logging.debug( u'[{0:s}] Missing MRUListEx entry value: {1:d} in key: {2:s}.'.format( self.NAME, entry_number, key.path)) elif not value.DataIsBinaryData(): logging.debug(( u'[{0:s}] Non-binary MRUListEx entry value: {1:d} in key: ' u'{2:s}.').format(self.NAME, entry_number, key.path)) elif value.data: shell_items_parser = shell_items.ShellItemsParser(key.path) shell_items_parser.UpdateChainAndParse( parser_mediator, value.data, None, codepage=codepage) value_string = u'Shell item path: {0:s}'.format( shell_items_parser.CopyToPath()) return value_string def GetEntries( self, parser_mediator, key=None, registry_file_type=None, codepage=u'cp1252', **kwargs): """Extract event objects from a Registry key containing a MRUListEx value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: Optional Registry key (instance of winreg.WinRegKey). The default is None. registry_file_type: Optional string containing the Windows Registry file type, e.g. NTUSER, SOFTWARE. The default is None. codepage: Optional extended ASCII string codepage. The default is cp1252. """ if key.name != u'OpenSavePidlMRU': self._ParseMRUListExKey( parser_mediator, key, registry_file_type=registry_file_type, codepage=codepage) if key.name == u'OpenSavePidlMRU': # For the OpenSavePidlMRU MRUListEx we also need to parse its subkeys # since the Registry key path does not support wildcards yet. for subkey in key.GetSubkeys(): self._ParseMRUListExKey( parser_mediator, subkey, registry_file_type=registry_file_type, codepage=codepage) class MRUListExStringAndShellItemPlugin( interface.KeyPlugin, MRUListExPluginMixin): """Windows Registry plugin to parse a string and shell item MRUListEx.""" NAME = u'mrulistex_string_and_shell_item' DESCRIPTION = u'Parser for Most Recently Used (MRU) Registry data.' REG_TYPE = u'any' REG_KEYS = frozenset([ u'\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RecentDocs']) _STRING_AND_SHELL_ITEM_STRUCT = construct.Struct( u'string_and_shell_item', construct.RepeatUntil( lambda obj, ctx: obj == b'\x00\x00', construct.Field(u'string', 2)), construct.Anchor(u'shell_item')) def _ParseMRUListExEntryValue( self, parser_mediator, key, entry_index, entry_number, codepage=u'cp1252', **unused_kwargs): """Parses the MRUListEx entry value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: the Registry key (instance of winreg.WinRegKey) that contains the MRUListEx value. entry_index: integer value representing the MRUListEx entry index. entry_number: integer value representing the entry number. codepage: Optional extended ASCII string codepage. The default is cp1252. Returns: A string containing the value. """ value_string = u'' value = key.GetValue(u'{0:d}'.format(entry_number)) if value is None: logging.debug( u'[{0:s}] Missing MRUListEx entry value: {1:d} in key: {2:s}.'.format( self.NAME, entry_number, key.path)) elif not value.DataIsBinaryData(): logging.debug(( u'[{0:s}] Non-binary MRUListEx entry value: {1:d} in key: ' u'{2:s}.').format(self.NAME, entry_number, key.path)) elif value.data: value_struct = self._STRING_AND_SHELL_ITEM_STRUCT.parse(value.data) try: # The struct includes the end-of-string character that we need # to strip off. path = b''.join(value_struct.string).decode(u'utf16')[:-1] except UnicodeDecodeError as exception: logging.warning(( u'[{0:s}] Unable to decode string MRUListEx entry value: {1:d} ' u'in key: {2:s} with error: {3:s}').format( self.NAME, entry_number, key.path, exception)) path = u'' if path: shell_item_list_data = value.data[value_struct.shell_item:] if not shell_item_list_data: logging.debug(( u'[{0:s}] Missing shell item in MRUListEx entry value: {1:d}' u'in key: {2:s}').format(self.NAME, entry_number, key.path)) value_string = u'Path: {0:s}'.format(path) else: shell_items_parser = shell_items.ShellItemsParser(key.path) shell_items_parser.UpdateChainAndParse( parser_mediator, shell_item_list_data, None, codepage=codepage) value_string = u'Path: {0:s}, Shell item: [{1:s}]'.format( path, shell_items_parser.CopyToPath()) return value_string def GetEntries( self, parser_mediator, key=None, registry_file_type=None, codepage=u'cp1252', **kwargs): """Extract event objects from a Registry key containing a MRUListEx value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: Optional Registry key (instance of winreg.WinRegKey). The default is None. registry_file_type: Optional string containing the Windows Registry file type, e.g. NTUSER, SOFTWARE. The default is None. codepage: Optional extended ASCII string codepage. The default is cp1252. """ self._ParseMRUListExKey( parser_mediator, key, registry_file_type=registry_file_type, codepage=codepage) if key.name == u'RecentDocs': # For the RecentDocs MRUListEx we also need to parse its subkeys # since the Registry key path does not support wildcards yet. for subkey in key.GetSubkeys(): self._ParseMRUListExKey( parser_mediator, subkey, registry_file_type=registry_file_type, codepage=codepage) class MRUListExStringAndShellItemListPlugin( interface.KeyPlugin, MRUListExPluginMixin): """Windows Registry plugin to parse a string and shell item list MRUListEx.""" NAME = u'mrulistex_string_and_shell_item_list' DESCRIPTION = u'Parser for Most Recently Used (MRU) Registry data.' REG_TYPE = u'any' REG_KEYS = frozenset([ (u'\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\' u'LastVisitedPidlMRU')]) _STRING_AND_SHELL_ITEM_LIST_STRUCT = construct.Struct( u'string_and_shell_item', construct.RepeatUntil( lambda obj, ctx: obj == b'\x00\x00', construct.Field(u'string', 2)), construct.Anchor(u'shell_item_list')) def _ParseMRUListExEntryValue( self, parser_mediator, key, entry_index, entry_number, codepage=u'cp1252', **unused_kwargs): """Parses the MRUListEx entry value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: the Registry key (instance of winreg.WinRegKey) that contains the MRUListEx value. entry_index: integer value representing the MRUListEx entry index. entry_number: integer value representing the entry number. codepage: Optional extended ASCII string codepage. The default is cp1252. Returns: A string containing the value. """ value_string = u'' value = key.GetValue(u'{0:d}'.format(entry_number)) if value is None: logging.debug( u'[{0:s}] Missing MRUListEx entry value: {1:d} in key: {2:s}.'.format( self.NAME, entry_number, key.path)) elif not value.DataIsBinaryData(): logging.debug(( u'[{0:s}] Non-binary MRUListEx entry value: {1:d} in key: ' u'{2:s}.').format(self.NAME, entry_number, key.path)) elif value.data: value_struct = self._STRING_AND_SHELL_ITEM_LIST_STRUCT.parse(value.data) try: # The struct includes the end-of-string character that we need # to strip off. path = b''.join(value_struct.string).decode(u'utf16')[:-1] except UnicodeDecodeError as exception: logging.warning(( u'[{0:s}] Unable to decode string MRUListEx entry value: {1:d} ' u'in key: {2:s} with error: {3:s}').format( self.NAME, entry_number, key.path, exception)) path = u'' if path: shell_item_list_data = value.data[value_struct.shell_item_list:] if not shell_item_list_data: logging.debug(( u'[{0:s}] Missing shell item in MRUListEx entry value: {1:d}' u'in key: {2:s}').format(self.NAME, entry_number, key.path)) value_string = u'Path: {0:s}'.format(path) else: shell_items_parser = shell_items.ShellItemsParser(key.path) shell_items_parser.UpdateChainAndParse( parser_mediator, shell_item_list_data, None, codepage=codepage) value_string = u'Path: {0:s}, Shell item path: {1:s}'.format( path, shell_items_parser.CopyToPath()) return value_string def GetEntries( self, parser_mediator, key=None, registry_file_type=None, codepage=u'cp1252', **kwargs): """Extract event objects from a Registry key containing a MRUListEx value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: Optional Registry key (instance of winreg.WinRegKey). The default is None. registry_file_type: Optional string containing the Windows Registry file type, e.g. NTUSER, SOFTWARE. The default is None. codepage: Optional extended ASCII string codepage. The default is cp1252. """ self._ParseMRUListExKey( parser_mediator, key, registry_file_type=registry_file_type, codepage=codepage) winreg.WinRegistryParser.RegisterPlugins([ MRUListExStringPlugin, MRUListExShellItemListPlugin, MRUListExStringAndShellItemPlugin, MRUListExStringAndShellItemListPlugin])
en
0.586225
# -*- coding: utf-8 -*- This file contains MRUListEx Windows Registry plugins. # A mixin class is used here to not to have the duplicate functionality # to parse the MRUListEx Registry values. However multiple inheritance # and thus mixins are to be used sparsely in this codebase, hence we need # to find a better solution in not needing to distinguish between key and # value plugins. # TODO: refactor Registry key and value plugin to rid ourselves of the mixin. Class for common MRUListEx Windows Registry plugin functionality. Parses the MRUListEx entry value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: the Registry key (instance of winreg.WinRegKey) that contains the MRUListEx value. entry_index: integer value representing the MRUListEx entry index. entry_number: integer value representing the entry number. Returns: A string containing the value. Parses the MRUListEx value in a given Registry key. Args: key: the Registry key (instance of winreg.WinRegKey) that contains the MRUListEx value. Returns: A MRUListEx value generator, which returns the MRU index number and entry value. # The key exists but does not contain a value named "MRUListEx". Extract event objects from a MRUListEx Registry key. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: the Registry key (instance of winreg.WinRegKey). registry_file_type: Optional string containing the Windows Registry file type, e.g. NTUSER, SOFTWARE. The default is None. codepage: Optional extended ASCII string codepage. The default is cp1252. # TODO: detect if list ends prematurely. # MRU lists are terminated with 0xffffffff (-1). Windows Registry plugin to parse a string MRUListEx. Parses the MRUListEx entry value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: the Registry key (instance of winreg.WinRegKey) that contains the MRUListEx value. entry_index: integer value representing the MRUListEx entry index. entry_number: integer value representing the entry number. Returns: A string containing the value. Extract event objects from a Registry key containing a MRUListEx value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: Optional Registry key (instance of winreg.WinRegKey). The default is None. registry_file_type: Optional string containing the Windows Registry file type, e.g. NTUSER, SOFTWARE. The default is None. codepage: Optional extended ASCII string codepage. The default is cp1252. Determine if we can process this Registry key or not. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: Optional Windows Registry key (instance of WinRegKey). The default is None. codepage: Optional extended ASCII string codepage. The default is cp1252. # Prevent this plugin triggering on sub paths of non-string MRUListEx # values. Windows Registry plugin to parse a shell item list MRUListEx. # The regular expression indicated a file extension (.jpg) or '*'. Parses the MRUListEx entry value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: the Registry key (instance of winreg.WinRegKey) that contains the MRUListEx value. entry_index: integer value representing the MRUListEx entry index. entry_number: integer value representing the entry number. codepage: Optional extended ASCII string codepage. The default is cp1252. Returns: A string containing the value. Extract event objects from a Registry key containing a MRUListEx value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: Optional Registry key (instance of winreg.WinRegKey). The default is None. registry_file_type: Optional string containing the Windows Registry file type, e.g. NTUSER, SOFTWARE. The default is None. codepage: Optional extended ASCII string codepage. The default is cp1252. # For the OpenSavePidlMRU MRUListEx we also need to parse its subkeys # since the Registry key path does not support wildcards yet. Windows Registry plugin to parse a string and shell item MRUListEx. Parses the MRUListEx entry value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: the Registry key (instance of winreg.WinRegKey) that contains the MRUListEx value. entry_index: integer value representing the MRUListEx entry index. entry_number: integer value representing the entry number. codepage: Optional extended ASCII string codepage. The default is cp1252. Returns: A string containing the value. # The struct includes the end-of-string character that we need # to strip off. Extract event objects from a Registry key containing a MRUListEx value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: Optional Registry key (instance of winreg.WinRegKey). The default is None. registry_file_type: Optional string containing the Windows Registry file type, e.g. NTUSER, SOFTWARE. The default is None. codepage: Optional extended ASCII string codepage. The default is cp1252. # For the RecentDocs MRUListEx we also need to parse its subkeys # since the Registry key path does not support wildcards yet. Windows Registry plugin to parse a string and shell item list MRUListEx. Parses the MRUListEx entry value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: the Registry key (instance of winreg.WinRegKey) that contains the MRUListEx value. entry_index: integer value representing the MRUListEx entry index. entry_number: integer value representing the entry number. codepage: Optional extended ASCII string codepage. The default is cp1252. Returns: A string containing the value. # The struct includes the end-of-string character that we need # to strip off. Extract event objects from a Registry key containing a MRUListEx value. Args: parser_mediator: A parser mediator object (instance of ParserMediator). key: Optional Registry key (instance of winreg.WinRegKey). The default is None. registry_file_type: Optional string containing the Windows Registry file type, e.g. NTUSER, SOFTWARE. The default is None. codepage: Optional extended ASCII string codepage. The default is cp1252.
2.296541
2
dlkit/json_/authentication_process/objects.py
UOC/dlkit
2
6619587
"""JSON implementations of authentication.process objects.""" # pylint: disable=no-init # Numerous classes don't require __init__. # pylint: disable=too-many-public-methods,too-few-public-methods # Number of methods are defined in specification # pylint: disable=protected-access # Access to protected methods allowed in package json package scope # pylint: disable=too-many-ancestors # Inheritance defined in specification from .. import utilities from ..authentication.objects import Agent from ..id.objects import IdList from ..osid import objects as osid_objects from ..primitives import Id from ..utilities import get_registry from dlkit.abstract_osid.authentication_process import objects as abc_authentication_process_objects from dlkit.abstract_osid.osid import errors class Authentication(abc_authentication_process_objects.Authentication, osid_objects.OsidObject): """``Authentication`` represents an authentication credential which contains set of ``bytes`` and a format Type. Once an ``Authentication`` is created from the ``AuthenticationValidationSession,`` the credential data can be extracted and sent to the remote peer for validation. The remote peer gets another ``Authentication`` object as a result of validating the serialized credential data. An ``Authentication`` may or may not be valid. ``is_valid()`` should be checked before acting upon the ``Agent`` identity to which the credential is mapped. """ def __init__(self): self._django_user = None self._credential = None def get_agent_id(self): """Gets the ``Id`` of the ``Agent`` identified in this authentication credential. return: (osid.id.Id) - the ``Agent Id`` *compliance: mandatory -- This method must be implemented.* *implementation notes*: The Agent should be determined at the time this credential is created. """ if self._django_user is not None: return Id(identifier=self._django_user.get_username(), namespace='osid.agent.Agent', authority='MIT-OEIT') else: return Id(identifier='<EMAIL>', namespace='osid.agent.Agent', authority='MIT-OEIT') agent_id = property(fget=get_agent_id) def get_agent(self): """Gets the ``Agent`` identified in this authentication credential. return: (osid.authentication.Agent) - the ``Agent`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ raise errors.Unimplemented agent = property(fget=get_agent) def is_valid(self): """Tests whether or not the credential represented by this ``Authentication`` is currently valid. A credential may be invalid because it has been destroyed, expired, or is somehow no longer able to be used. return: (boolean) - ``true`` if this authentication credential is valid, ``false`` otherwise *compliance: mandatory -- This method must be implemented.* *implementation notes*: Any problem in determining the validity of this credential should result in ``false``. """ if self._django_user is not None: return self._django_user.is_authenticated() else: return False def has_expiration(self): """Tests if this authentication has an expiration. return: (boolean) - ``true`` if this authentication has an expiration, ``false`` otherwise *compliance: mandatory -- This method must be implemented.* """ return False def get_expiration(self): """Gets the expiration date associated with this authentication credential. Consumers should check for the existence of a an expiration mechanism via ``hasExpiration()``. return: (timestamp) - the expiration date of this authentication credential raise: IllegalState - ``has_expiration()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ if not self.has_expiration(): raise errors.IllegalState() else: raise errors.Unimplemented() expiration = property(fget=get_expiration) def has_credential(self): """Tests if this authentication has a credential for export. return: (boolean) - ``true`` if this authentication has a credential, ``false`` otherwise *compliance: mandatory -- This method must be implemented.* """ if self._credential is None: return False else: return True @utilities.arguments_not_none def get_credential(self, credential_type): """Gets the credential represented by the given ``Type`` for transport to a remote service. arg: credential_type (osid.type.Type): the credential format ``Type`` return: (object) - the credential raise: IllegalState - ``has_credential()`` is ``false`` raise: NullArgument - ``credential_type`` is ``null`` raise: Unsupported - the given ``credential_type`` is not supported *compliance: mandatory -- This method must be implemented.* *implementation notes*: A provider may support multiple credential formats for a variety of applications. """ if self.has_credential(): return self._credential else: raise errors.IllegalState() @utilities.arguments_not_none def get_authentication_record(self, authentication_record_type): """Gets the authentication record corresponding to the given authentication record ``Type``. This method is used to retrieve an object implementing the requested record. The ``authentication_record_type`` may be the ``Type`` returned in ``get_record_types()`` or any of its parents in a ``Type`` hierarchy where ``has_record_type(authentication_record_type)`` is ``true`` . arg: authentication_record_type (osid.type.Type): the type of authentication record to retrieve return: (osid.authentication.process.records.AuthenticationRecor d) - the authentication record raise: NullArgument - ``authentication_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure occurred raise: Unsupported - ``has_record_type(authenticaton_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ raise errors.Unsupported() def set_django_user(self, django_user): """Special method that excepts a django user. Should be a record.""" self._django_user = django_user
"""JSON implementations of authentication.process objects.""" # pylint: disable=no-init # Numerous classes don't require __init__. # pylint: disable=too-many-public-methods,too-few-public-methods # Number of methods are defined in specification # pylint: disable=protected-access # Access to protected methods allowed in package json package scope # pylint: disable=too-many-ancestors # Inheritance defined in specification from .. import utilities from ..authentication.objects import Agent from ..id.objects import IdList from ..osid import objects as osid_objects from ..primitives import Id from ..utilities import get_registry from dlkit.abstract_osid.authentication_process import objects as abc_authentication_process_objects from dlkit.abstract_osid.osid import errors class Authentication(abc_authentication_process_objects.Authentication, osid_objects.OsidObject): """``Authentication`` represents an authentication credential which contains set of ``bytes`` and a format Type. Once an ``Authentication`` is created from the ``AuthenticationValidationSession,`` the credential data can be extracted and sent to the remote peer for validation. The remote peer gets another ``Authentication`` object as a result of validating the serialized credential data. An ``Authentication`` may or may not be valid. ``is_valid()`` should be checked before acting upon the ``Agent`` identity to which the credential is mapped. """ def __init__(self): self._django_user = None self._credential = None def get_agent_id(self): """Gets the ``Id`` of the ``Agent`` identified in this authentication credential. return: (osid.id.Id) - the ``Agent Id`` *compliance: mandatory -- This method must be implemented.* *implementation notes*: The Agent should be determined at the time this credential is created. """ if self._django_user is not None: return Id(identifier=self._django_user.get_username(), namespace='osid.agent.Agent', authority='MIT-OEIT') else: return Id(identifier='<EMAIL>', namespace='osid.agent.Agent', authority='MIT-OEIT') agent_id = property(fget=get_agent_id) def get_agent(self): """Gets the ``Agent`` identified in this authentication credential. return: (osid.authentication.Agent) - the ``Agent`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ raise errors.Unimplemented agent = property(fget=get_agent) def is_valid(self): """Tests whether or not the credential represented by this ``Authentication`` is currently valid. A credential may be invalid because it has been destroyed, expired, or is somehow no longer able to be used. return: (boolean) - ``true`` if this authentication credential is valid, ``false`` otherwise *compliance: mandatory -- This method must be implemented.* *implementation notes*: Any problem in determining the validity of this credential should result in ``false``. """ if self._django_user is not None: return self._django_user.is_authenticated() else: return False def has_expiration(self): """Tests if this authentication has an expiration. return: (boolean) - ``true`` if this authentication has an expiration, ``false`` otherwise *compliance: mandatory -- This method must be implemented.* """ return False def get_expiration(self): """Gets the expiration date associated with this authentication credential. Consumers should check for the existence of a an expiration mechanism via ``hasExpiration()``. return: (timestamp) - the expiration date of this authentication credential raise: IllegalState - ``has_expiration()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ if not self.has_expiration(): raise errors.IllegalState() else: raise errors.Unimplemented() expiration = property(fget=get_expiration) def has_credential(self): """Tests if this authentication has a credential for export. return: (boolean) - ``true`` if this authentication has a credential, ``false`` otherwise *compliance: mandatory -- This method must be implemented.* """ if self._credential is None: return False else: return True @utilities.arguments_not_none def get_credential(self, credential_type): """Gets the credential represented by the given ``Type`` for transport to a remote service. arg: credential_type (osid.type.Type): the credential format ``Type`` return: (object) - the credential raise: IllegalState - ``has_credential()`` is ``false`` raise: NullArgument - ``credential_type`` is ``null`` raise: Unsupported - the given ``credential_type`` is not supported *compliance: mandatory -- This method must be implemented.* *implementation notes*: A provider may support multiple credential formats for a variety of applications. """ if self.has_credential(): return self._credential else: raise errors.IllegalState() @utilities.arguments_not_none def get_authentication_record(self, authentication_record_type): """Gets the authentication record corresponding to the given authentication record ``Type``. This method is used to retrieve an object implementing the requested record. The ``authentication_record_type`` may be the ``Type`` returned in ``get_record_types()`` or any of its parents in a ``Type`` hierarchy where ``has_record_type(authentication_record_type)`` is ``true`` . arg: authentication_record_type (osid.type.Type): the type of authentication record to retrieve return: (osid.authentication.process.records.AuthenticationRecor d) - the authentication record raise: NullArgument - ``authentication_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure occurred raise: Unsupported - ``has_record_type(authenticaton_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ raise errors.Unsupported() def set_django_user(self, django_user): """Special method that excepts a django user. Should be a record.""" self._django_user = django_user
en
0.729488
JSON implementations of authentication.process objects. # pylint: disable=no-init # Numerous classes don't require __init__. # pylint: disable=too-many-public-methods,too-few-public-methods # Number of methods are defined in specification # pylint: disable=protected-access # Access to protected methods allowed in package json package scope # pylint: disable=too-many-ancestors # Inheritance defined in specification ``Authentication`` represents an authentication credential which contains set of ``bytes`` and a format Type. Once an ``Authentication`` is created from the ``AuthenticationValidationSession,`` the credential data can be extracted and sent to the remote peer for validation. The remote peer gets another ``Authentication`` object as a result of validating the serialized credential data. An ``Authentication`` may or may not be valid. ``is_valid()`` should be checked before acting upon the ``Agent`` identity to which the credential is mapped. Gets the ``Id`` of the ``Agent`` identified in this authentication credential. return: (osid.id.Id) - the ``Agent Id`` *compliance: mandatory -- This method must be implemented.* *implementation notes*: The Agent should be determined at the time this credential is created. Gets the ``Agent`` identified in this authentication credential. return: (osid.authentication.Agent) - the ``Agent`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* Tests whether or not the credential represented by this ``Authentication`` is currently valid. A credential may be invalid because it has been destroyed, expired, or is somehow no longer able to be used. return: (boolean) - ``true`` if this authentication credential is valid, ``false`` otherwise *compliance: mandatory -- This method must be implemented.* *implementation notes*: Any problem in determining the validity of this credential should result in ``false``. Tests if this authentication has an expiration. return: (boolean) - ``true`` if this authentication has an expiration, ``false`` otherwise *compliance: mandatory -- This method must be implemented.* Gets the expiration date associated with this authentication credential. Consumers should check for the existence of a an expiration mechanism via ``hasExpiration()``. return: (timestamp) - the expiration date of this authentication credential raise: IllegalState - ``has_expiration()`` is ``false`` *compliance: mandatory -- This method must be implemented.* Tests if this authentication has a credential for export. return: (boolean) - ``true`` if this authentication has a credential, ``false`` otherwise *compliance: mandatory -- This method must be implemented.* Gets the credential represented by the given ``Type`` for transport to a remote service. arg: credential_type (osid.type.Type): the credential format ``Type`` return: (object) - the credential raise: IllegalState - ``has_credential()`` is ``false`` raise: NullArgument - ``credential_type`` is ``null`` raise: Unsupported - the given ``credential_type`` is not supported *compliance: mandatory -- This method must be implemented.* *implementation notes*: A provider may support multiple credential formats for a variety of applications. Gets the authentication record corresponding to the given authentication record ``Type``. This method is used to retrieve an object implementing the requested record. The ``authentication_record_type`` may be the ``Type`` returned in ``get_record_types()`` or any of its parents in a ``Type`` hierarchy where ``has_record_type(authentication_record_type)`` is ``true`` . arg: authentication_record_type (osid.type.Type): the type of authentication record to retrieve return: (osid.authentication.process.records.AuthenticationRecor d) - the authentication record raise: NullArgument - ``authentication_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure occurred raise: Unsupported - ``has_record_type(authenticaton_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* Special method that excepts a django user. Should be a record.
2.670836
3
plot_accuracies.py
Summer0328/DeeplabforRS
3
6619588
<filename>plot_accuracies.py #!/usr/bin/env python # Filename: plot_accuracies """ introduction: plot accuracies of the results, including Receiver Operating Characteristic (ROC), and Precision-Recall authors: <NAME> email:<EMAIL> add time: 31 Dec, 2018 """ import os, sys from optparse import OptionParser import matplotlib.pyplot as plt import numpy as np # import vector_features import vector_features from vector_features import shape_opeation import parameters import basic_src.io_function as io_function import basic_src.basic as basic from sklearn.metrics import f1_score from sklearn.metrics import precision_recall_fscore_support # plt.rc('xtick',labelsize=20) # plt.rc('ytick',labelsize=20) def get_iou_scores(result_shp, ground_truth_shp): """ get IoU scores of all the polygons in result_shp Args: result_shp: the path of result file ground_truth_shp: the path of ground truth file Returns: IoU values """ IoUs = vector_features.calculate_IoU_scores(result_shp, ground_truth_shp) return IoUs def get_y_true_prediction(input_shp,groud_truth_shp,iou_threshold): """ get ground truth and prediction array of polygons based on IoU values Args: input_shp: shape file of mapped polygons groud_truth_shp: shape file of ground truth polygons iou_threshold: iou threshold Returns: y_true,y_prediction ( numpy array) """ # calculate the IoU of each predicted polygons iou_pre = np.array(get_iou_scores(input_shp, groud_truth_shp)) # calculate the IoU of each ground truth, for false negative iou_GT = np.array(get_iou_scores(groud_truth_shp, input_shp)) count_pre = len(iou_pre) y_pred = np.ones(count_pre) # all the predicted output are considered as targets (1) # set true positive and false positve y_true = np.zeros(count_pre) y_true[np.where(iou_pre > iou_threshold)] = 1 # modify y_true based on iou_GT for false negative count_false_neg = len(iou_GT[np.where(iou_GT < iou_threshold)]) print(count_false_neg) # idx = 0 # while (count_false_neg>0): # print(idx) # if y_true[idx]==0 and y_pred[idx] == 1: # all y_pred are 1 # y_true[idx] = 1 # y_pred[idx] = 0 # count_false_neg -= 1 # idx += 1 # add false negatives y_true = np.append(y_true, np.ones(count_false_neg)) y_pred = np.append(y_pred, np.zeros(count_false_neg)) # tp = np.where(y_true==1 and y_pred==1) tp = 0 fp = 0 fn = 0 for y_t, y_p in zip(y_true, y_pred): if y_p == 1 and y_t == 1: tp += 1 elif y_p == 1 and y_t == 0: fp += 1 elif y_p == 0 and y_t == 1: fn += 1 else: pass print('tp=%d, fp=%d, fn=%d' % (tp, fp, fn)) return y_true,y_pred def get_y_true_and_scores(input_shp,groud_truth_shp): """ get ground truth and the scores (IoU values) array of polygons Args: input_shp: shape file of mapped polygons groud_truth_shp: shape file of ground truth polygons Returns: y_true,y_scores ( numpy array) """ # calculate the IoU of each predicted polygons iou_pre = np.array(get_iou_scores(input_shp, groud_truth_shp)) # it seems unable to get it 1 Jan 2019 # return y_true,y_pred def calculate_f1_score(input_shp,groud_truth_shp,threshold): y_true, y_pred = get_y_true_prediction(input_shp,groud_truth_shp,threshold) # score = f1_score(y_true, y_pred) #, default average='binary' p_r_f1 =precision_recall_fscore_support(y_true, y_pred,average='binary') print(p_r_f1) return True def calculate_precision_recall_iou(IoU_prediction,IoU_ground_truth,iou_threshold): """ calculate precision, recall based on IoU values Args: IoU_prediction: IoU of each mapped polygons, should be 1d numpy array IoU_ground_truth: IoU of each ground truth polygons: for count false negatives, should be 1d numpy array iou_threshold: IoU threshold Returns: precision, recall, f1 score """ true_pos_count = 0 false_pos_count = 0 # calculate precision, recall, F1 score for iou in IoU_prediction: if iou > iou_threshold: true_pos_count += 1 else: false_pos_count += 1 # val_polygon_count = len(IoU_ground_truth) # false_neg_count = val_polygon_count - true_pos_count # use the following method, because in beiluhe case, a mapped polygon can cover two or more thaw slumps if iou_threshold <= 0: false_neg_count = len(IoU_ground_truth[np.where(IoU_ground_truth ==0 )]) else: false_neg_count = len(IoU_ground_truth[np.where(IoU_ground_truth < iou_threshold)]) if false_neg_count < 0: basic.outputlogMessage('warning, false negative count is smaller than 0, recall can not be trusted') precision = float(true_pos_count) / (float(true_pos_count) + float(false_pos_count)) recall = float(true_pos_count) / (float(true_pos_count) + float(false_neg_count)) if (true_pos_count > 0): F1score = 2.0 * precision * recall / (precision + recall) else: F1score = 0 basic.outputlogMessage("iou_thr: %.3f,TP:%3d, FP:%3d, FN:%3d, TP+FP:%3d, TP+FN:%3d"%(iou_threshold,true_pos_count,false_pos_count,false_neg_count, true_pos_count+false_pos_count,true_pos_count+false_neg_count)) return precision, recall, F1score def calculate_average_precision(precision_list,recall_list): """ compute average_precision Args: precision_list: list of precision recall_list: list of recall Returns: """ count = len(precision_list) if len(recall_list) != count: raise ValueError("the number in precision_list and recall_list is inconsistent") ap = 0 for idx in range(1,count): ap += precision_list[idx]*(recall_list[idx] - recall_list[idx-1]) #abs return ap def precision_recall_curve_iou(input_shp,groud_truth_shp): """ instead of using precision_recall_curve in sklearn.metrics, here we calculate the precision recall based on IoU Args: input_shp: shape file of mapped polygons groud_truth_shp:shape file of ground truth polygons Returns: precision, recall, threshold """ basic.outputlogMessage('calculate precision recall curve for %s'%input_shp) # calculate the IoU of each predicted polygons iou_pre = np.array(get_iou_scores(input_shp, groud_truth_shp)) # calculate the IoU of each ground truth, for false negative iou_GT = np.array(get_iou_scores(groud_truth_shp, input_shp)) precision_list = [] recall_list = [] iou_thr_list = [] f1score_list = [] # for iou_thr in np.arange(-0.01, 1.01, 0.05): for iou_thr in np.arange(1, -0.01, -0.04): #-0.05 # abs(iou_thr) >=0, it is strange (0 > -0.000 return true), Jan 16 2019. hlc # but it turns our that precision cannot be 1, so just keep it. # iou_thr = abs(iou_thr) if iou_thr < 0: iou_thr = 0 precision, recall, f1score = calculate_precision_recall_iou(iou_pre, iou_GT, iou_thr) #abs(iou_thr) basic.outputlogMessage("iou_thr: %.3f, precision: %.4f, recall: %.4f, f1score: %.4f"%(iou_thr,precision, recall, f1score)) precision_list.append(precision) recall_list.append(recall) f1score_list.append(f1score) iou_thr_list.append(iou_thr) return precision_list, recall_list, iou_thr_list def plot_precision_recall_curve(input_shp,groud_truth_shp,save_path): # from sklearn.metrics import precision_recall_curve try: from sklearn.utils.fixes import signature except ImportError: from funcsigs import signature precision, recall, _ = precision_recall_curve_iou(input_shp,groud_truth_shp) average_precision = calculate_average_precision(precision,recall) # In matplotlib < 1.5, plt.fill_between does not have a 'step' argument step_pos = 'mid' # post step_kwargs = ({'step': step_pos} if 'step' in signature(plt.fill_between).parameters else {}) plt.step(recall, precision, color='b', alpha=0.2, where=step_pos) plt.plot(recall, precision, 'r--') plt.fill_between(recall, precision, alpha=0.2, color='b', **step_kwargs) plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([-0.01, 1.05]) plt.xlim([-0.01, 1.01]) plt.title('2-class Precision-Recall curve: AP={0:0.2f}'.format( average_precision)) # save average_precision to txt file txt_path = os.path.splitext(save_path)[0]+'_ap.txt' with open(txt_path,'w') as f_obj: f_obj.writelines('shape_file average_precision\n') f_obj.writelines('%s %.4lf\n' % (input_shp, average_precision)) # plt.show() plt.savefig(save_path,dpi=300) basic.outputlogMessage("Output figures to %s" % os.path.abspath(save_path)) def plot_precision_recall_curve_multi(input_shp_list,groud_truth_shp,save_path,legend_loc='best'): """ plot precision_recall of multi shapefiles to a figure Args: input_shp_list: a list of shapefiles groud_truth_shp: the ground truth file or a list save_path: output figure path Returns: """ precision_list = [] recall_list = [] average_precision_list = [] line_labels = [] # label_set = ['2017','2018','2019'] for idx,input_shp in enumerate(input_shp_list): if isinstance(groud_truth_shp, list): precision, recall, _ = precision_recall_curve_iou(input_shp, groud_truth_shp[idx]) else: precision, recall, _ = precision_recall_curve_iou(input_shp, groud_truth_shp) precision_list.append(precision) recall_list.append(recall) average_precision = calculate_average_precision(precision, recall) average_precision_list.append(average_precision) file_name = os.path.splitext(os.path.basename(input_shp))[0] if 'fold' in file_name: # k-fold cross-validation tmp = file_name.split('_') if 'rmTimeiou' in file_name: label = '_'.join(tmp[-4:-1]) else: label = '_'.join(tmp[-3:]) elif 'imgAug' in file_name: # image augmentation test tmp = file_name.split('_') label = tmp[-1] else: label = str(idx) # label = label_set[idx] line_labels.append('%s: AP=%.2f'%(label,average_precision)) # save average_precision to txt file txt_path = os.path.splitext(save_path)[0]+'_ap.txt' with open(txt_path,'w') as f_obj: f_obj.writelines('shape_file average_precision\n') for shp_file,average_pre in zip(input_shp_list,average_precision_list): f_obj.writelines('%s %.4lf\n'%(shp_file,average_pre)) # matplotlib build-in color # b: blue # g: green # r: red # c: cyan # m: magenta # y: yellow # k: black # w: white line_color = ['b', 'g', 'r', 'c', 'y', 'k','m'] # linestyle = ['-','--','-.',":",'+-','x-'] # linestyle = [ '+','x' ,'*','s', 'h', 'd', 'p', 'H', 'D'] #, color_used_count = len(line_color) line_used_count = len(linestyle) for x in range(0,len(input_shp_list)): recall = recall_list[x] precision = precision_list[x] outlook = line_color[x % color_used_count] + linestyle[x // color_used_count] step_pos = 'mid' plt.step(recall, precision, outlook, where=step_pos,label=line_labels[x]) # plt.plot(recall, precision, 'r--') plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([-0.01, 1.05]) plt.xlim([-0.01, 1.01]) plt.title('Precision-Recall curve') print('********legend_loc*************', legend_loc) if legend_loc=='best': plt.legend(loc='best', bbox_to_anchor=(1, 0.5), title="Average Precision", fontsize=9) else: plt.legend(loc=legend_loc, title="Average Precision", fontsize=9) # plt.show() plt.savefig(save_path, dpi=300) basic.outputlogMessage("Output figures to %s" % os.path.abspath(save_path)) return True def main(options, args): shape_file = args[0] if io_function.is_file_exist(shape_file) is False: return False out_fig_path = options.output # get ground truth polygons val_path = parameters.get_validation_shape() # ground truth basic.outputlogMessage('the ground truth polygons are in %s'%val_path) # calculate f1 score # calculate_f1_score(shape_file,val_path,0.5) # precision_recall_curve_iou(shape_file, val_path) if len(args) == 1: plot_precision_recall_curve(shape_file, val_path,out_fig_path) else: plot_precision_recall_curve_multi(args, val_path, out_fig_path) if __name__ == '__main__': usage = "usage: %prog [options] shapefile or shapefiles" parser = OptionParser(usage=usage, version="1.0 2017-10-28") parser.description = 'Introduction: plot accuracies of the results ' parser.add_option("-p", "--para", action="store", dest="para_file",default='para.ini', help="the parameters file") parser.add_option("-o", "--output", action="store", dest="output",default='P_R.jpg', help="the parameters file") (options, args) = parser.parse_args() if len(sys.argv) < 2 or len(args) < 1: parser.print_help() sys.exit(2) # set parameters files, mandatory for the path of ground truth polygons if options.para_file is None: print('error, no parameters file') parser.print_help() sys.exit(2) else: parameters.set_saved_parafile_path(options.para_file) basic.setlogfile('accuracies_log.txt') main(options, args) pass
<filename>plot_accuracies.py #!/usr/bin/env python # Filename: plot_accuracies """ introduction: plot accuracies of the results, including Receiver Operating Characteristic (ROC), and Precision-Recall authors: <NAME> email:<EMAIL> add time: 31 Dec, 2018 """ import os, sys from optparse import OptionParser import matplotlib.pyplot as plt import numpy as np # import vector_features import vector_features from vector_features import shape_opeation import parameters import basic_src.io_function as io_function import basic_src.basic as basic from sklearn.metrics import f1_score from sklearn.metrics import precision_recall_fscore_support # plt.rc('xtick',labelsize=20) # plt.rc('ytick',labelsize=20) def get_iou_scores(result_shp, ground_truth_shp): """ get IoU scores of all the polygons in result_shp Args: result_shp: the path of result file ground_truth_shp: the path of ground truth file Returns: IoU values """ IoUs = vector_features.calculate_IoU_scores(result_shp, ground_truth_shp) return IoUs def get_y_true_prediction(input_shp,groud_truth_shp,iou_threshold): """ get ground truth and prediction array of polygons based on IoU values Args: input_shp: shape file of mapped polygons groud_truth_shp: shape file of ground truth polygons iou_threshold: iou threshold Returns: y_true,y_prediction ( numpy array) """ # calculate the IoU of each predicted polygons iou_pre = np.array(get_iou_scores(input_shp, groud_truth_shp)) # calculate the IoU of each ground truth, for false negative iou_GT = np.array(get_iou_scores(groud_truth_shp, input_shp)) count_pre = len(iou_pre) y_pred = np.ones(count_pre) # all the predicted output are considered as targets (1) # set true positive and false positve y_true = np.zeros(count_pre) y_true[np.where(iou_pre > iou_threshold)] = 1 # modify y_true based on iou_GT for false negative count_false_neg = len(iou_GT[np.where(iou_GT < iou_threshold)]) print(count_false_neg) # idx = 0 # while (count_false_neg>0): # print(idx) # if y_true[idx]==0 and y_pred[idx] == 1: # all y_pred are 1 # y_true[idx] = 1 # y_pred[idx] = 0 # count_false_neg -= 1 # idx += 1 # add false negatives y_true = np.append(y_true, np.ones(count_false_neg)) y_pred = np.append(y_pred, np.zeros(count_false_neg)) # tp = np.where(y_true==1 and y_pred==1) tp = 0 fp = 0 fn = 0 for y_t, y_p in zip(y_true, y_pred): if y_p == 1 and y_t == 1: tp += 1 elif y_p == 1 and y_t == 0: fp += 1 elif y_p == 0 and y_t == 1: fn += 1 else: pass print('tp=%d, fp=%d, fn=%d' % (tp, fp, fn)) return y_true,y_pred def get_y_true_and_scores(input_shp,groud_truth_shp): """ get ground truth and the scores (IoU values) array of polygons Args: input_shp: shape file of mapped polygons groud_truth_shp: shape file of ground truth polygons Returns: y_true,y_scores ( numpy array) """ # calculate the IoU of each predicted polygons iou_pre = np.array(get_iou_scores(input_shp, groud_truth_shp)) # it seems unable to get it 1 Jan 2019 # return y_true,y_pred def calculate_f1_score(input_shp,groud_truth_shp,threshold): y_true, y_pred = get_y_true_prediction(input_shp,groud_truth_shp,threshold) # score = f1_score(y_true, y_pred) #, default average='binary' p_r_f1 =precision_recall_fscore_support(y_true, y_pred,average='binary') print(p_r_f1) return True def calculate_precision_recall_iou(IoU_prediction,IoU_ground_truth,iou_threshold): """ calculate precision, recall based on IoU values Args: IoU_prediction: IoU of each mapped polygons, should be 1d numpy array IoU_ground_truth: IoU of each ground truth polygons: for count false negatives, should be 1d numpy array iou_threshold: IoU threshold Returns: precision, recall, f1 score """ true_pos_count = 0 false_pos_count = 0 # calculate precision, recall, F1 score for iou in IoU_prediction: if iou > iou_threshold: true_pos_count += 1 else: false_pos_count += 1 # val_polygon_count = len(IoU_ground_truth) # false_neg_count = val_polygon_count - true_pos_count # use the following method, because in beiluhe case, a mapped polygon can cover two or more thaw slumps if iou_threshold <= 0: false_neg_count = len(IoU_ground_truth[np.where(IoU_ground_truth ==0 )]) else: false_neg_count = len(IoU_ground_truth[np.where(IoU_ground_truth < iou_threshold)]) if false_neg_count < 0: basic.outputlogMessage('warning, false negative count is smaller than 0, recall can not be trusted') precision = float(true_pos_count) / (float(true_pos_count) + float(false_pos_count)) recall = float(true_pos_count) / (float(true_pos_count) + float(false_neg_count)) if (true_pos_count > 0): F1score = 2.0 * precision * recall / (precision + recall) else: F1score = 0 basic.outputlogMessage("iou_thr: %.3f,TP:%3d, FP:%3d, FN:%3d, TP+FP:%3d, TP+FN:%3d"%(iou_threshold,true_pos_count,false_pos_count,false_neg_count, true_pos_count+false_pos_count,true_pos_count+false_neg_count)) return precision, recall, F1score def calculate_average_precision(precision_list,recall_list): """ compute average_precision Args: precision_list: list of precision recall_list: list of recall Returns: """ count = len(precision_list) if len(recall_list) != count: raise ValueError("the number in precision_list and recall_list is inconsistent") ap = 0 for idx in range(1,count): ap += precision_list[idx]*(recall_list[idx] - recall_list[idx-1]) #abs return ap def precision_recall_curve_iou(input_shp,groud_truth_shp): """ instead of using precision_recall_curve in sklearn.metrics, here we calculate the precision recall based on IoU Args: input_shp: shape file of mapped polygons groud_truth_shp:shape file of ground truth polygons Returns: precision, recall, threshold """ basic.outputlogMessage('calculate precision recall curve for %s'%input_shp) # calculate the IoU of each predicted polygons iou_pre = np.array(get_iou_scores(input_shp, groud_truth_shp)) # calculate the IoU of each ground truth, for false negative iou_GT = np.array(get_iou_scores(groud_truth_shp, input_shp)) precision_list = [] recall_list = [] iou_thr_list = [] f1score_list = [] # for iou_thr in np.arange(-0.01, 1.01, 0.05): for iou_thr in np.arange(1, -0.01, -0.04): #-0.05 # abs(iou_thr) >=0, it is strange (0 > -0.000 return true), Jan 16 2019. hlc # but it turns our that precision cannot be 1, so just keep it. # iou_thr = abs(iou_thr) if iou_thr < 0: iou_thr = 0 precision, recall, f1score = calculate_precision_recall_iou(iou_pre, iou_GT, iou_thr) #abs(iou_thr) basic.outputlogMessage("iou_thr: %.3f, precision: %.4f, recall: %.4f, f1score: %.4f"%(iou_thr,precision, recall, f1score)) precision_list.append(precision) recall_list.append(recall) f1score_list.append(f1score) iou_thr_list.append(iou_thr) return precision_list, recall_list, iou_thr_list def plot_precision_recall_curve(input_shp,groud_truth_shp,save_path): # from sklearn.metrics import precision_recall_curve try: from sklearn.utils.fixes import signature except ImportError: from funcsigs import signature precision, recall, _ = precision_recall_curve_iou(input_shp,groud_truth_shp) average_precision = calculate_average_precision(precision,recall) # In matplotlib < 1.5, plt.fill_between does not have a 'step' argument step_pos = 'mid' # post step_kwargs = ({'step': step_pos} if 'step' in signature(plt.fill_between).parameters else {}) plt.step(recall, precision, color='b', alpha=0.2, where=step_pos) plt.plot(recall, precision, 'r--') plt.fill_between(recall, precision, alpha=0.2, color='b', **step_kwargs) plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([-0.01, 1.05]) plt.xlim([-0.01, 1.01]) plt.title('2-class Precision-Recall curve: AP={0:0.2f}'.format( average_precision)) # save average_precision to txt file txt_path = os.path.splitext(save_path)[0]+'_ap.txt' with open(txt_path,'w') as f_obj: f_obj.writelines('shape_file average_precision\n') f_obj.writelines('%s %.4lf\n' % (input_shp, average_precision)) # plt.show() plt.savefig(save_path,dpi=300) basic.outputlogMessage("Output figures to %s" % os.path.abspath(save_path)) def plot_precision_recall_curve_multi(input_shp_list,groud_truth_shp,save_path,legend_loc='best'): """ plot precision_recall of multi shapefiles to a figure Args: input_shp_list: a list of shapefiles groud_truth_shp: the ground truth file or a list save_path: output figure path Returns: """ precision_list = [] recall_list = [] average_precision_list = [] line_labels = [] # label_set = ['2017','2018','2019'] for idx,input_shp in enumerate(input_shp_list): if isinstance(groud_truth_shp, list): precision, recall, _ = precision_recall_curve_iou(input_shp, groud_truth_shp[idx]) else: precision, recall, _ = precision_recall_curve_iou(input_shp, groud_truth_shp) precision_list.append(precision) recall_list.append(recall) average_precision = calculate_average_precision(precision, recall) average_precision_list.append(average_precision) file_name = os.path.splitext(os.path.basename(input_shp))[0] if 'fold' in file_name: # k-fold cross-validation tmp = file_name.split('_') if 'rmTimeiou' in file_name: label = '_'.join(tmp[-4:-1]) else: label = '_'.join(tmp[-3:]) elif 'imgAug' in file_name: # image augmentation test tmp = file_name.split('_') label = tmp[-1] else: label = str(idx) # label = label_set[idx] line_labels.append('%s: AP=%.2f'%(label,average_precision)) # save average_precision to txt file txt_path = os.path.splitext(save_path)[0]+'_ap.txt' with open(txt_path,'w') as f_obj: f_obj.writelines('shape_file average_precision\n') for shp_file,average_pre in zip(input_shp_list,average_precision_list): f_obj.writelines('%s %.4lf\n'%(shp_file,average_pre)) # matplotlib build-in color # b: blue # g: green # r: red # c: cyan # m: magenta # y: yellow # k: black # w: white line_color = ['b', 'g', 'r', 'c', 'y', 'k','m'] # linestyle = ['-','--','-.',":",'+-','x-'] # linestyle = [ '+','x' ,'*','s', 'h', 'd', 'p', 'H', 'D'] #, color_used_count = len(line_color) line_used_count = len(linestyle) for x in range(0,len(input_shp_list)): recall = recall_list[x] precision = precision_list[x] outlook = line_color[x % color_used_count] + linestyle[x // color_used_count] step_pos = 'mid' plt.step(recall, precision, outlook, where=step_pos,label=line_labels[x]) # plt.plot(recall, precision, 'r--') plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([-0.01, 1.05]) plt.xlim([-0.01, 1.01]) plt.title('Precision-Recall curve') print('********legend_loc*************', legend_loc) if legend_loc=='best': plt.legend(loc='best', bbox_to_anchor=(1, 0.5), title="Average Precision", fontsize=9) else: plt.legend(loc=legend_loc, title="Average Precision", fontsize=9) # plt.show() plt.savefig(save_path, dpi=300) basic.outputlogMessage("Output figures to %s" % os.path.abspath(save_path)) return True def main(options, args): shape_file = args[0] if io_function.is_file_exist(shape_file) is False: return False out_fig_path = options.output # get ground truth polygons val_path = parameters.get_validation_shape() # ground truth basic.outputlogMessage('the ground truth polygons are in %s'%val_path) # calculate f1 score # calculate_f1_score(shape_file,val_path,0.5) # precision_recall_curve_iou(shape_file, val_path) if len(args) == 1: plot_precision_recall_curve(shape_file, val_path,out_fig_path) else: plot_precision_recall_curve_multi(args, val_path, out_fig_path) if __name__ == '__main__': usage = "usage: %prog [options] shapefile or shapefiles" parser = OptionParser(usage=usage, version="1.0 2017-10-28") parser.description = 'Introduction: plot accuracies of the results ' parser.add_option("-p", "--para", action="store", dest="para_file",default='para.ini', help="the parameters file") parser.add_option("-o", "--output", action="store", dest="output",default='P_R.jpg', help="the parameters file") (options, args) = parser.parse_args() if len(sys.argv) < 2 or len(args) < 1: parser.print_help() sys.exit(2) # set parameters files, mandatory for the path of ground truth polygons if options.para_file is None: print('error, no parameters file') parser.print_help() sys.exit(2) else: parameters.set_saved_parafile_path(options.para_file) basic.setlogfile('accuracies_log.txt') main(options, args) pass
en
0.659424
#!/usr/bin/env python # Filename: plot_accuracies introduction: plot accuracies of the results, including Receiver Operating Characteristic (ROC), and Precision-Recall authors: <NAME> email:<EMAIL> add time: 31 Dec, 2018 # import vector_features # plt.rc('xtick',labelsize=20) # plt.rc('ytick',labelsize=20) get IoU scores of all the polygons in result_shp Args: result_shp: the path of result file ground_truth_shp: the path of ground truth file Returns: IoU values get ground truth and prediction array of polygons based on IoU values Args: input_shp: shape file of mapped polygons groud_truth_shp: shape file of ground truth polygons iou_threshold: iou threshold Returns: y_true,y_prediction ( numpy array) # calculate the IoU of each predicted polygons # calculate the IoU of each ground truth, for false negative # all the predicted output are considered as targets (1) # set true positive and false positve # modify y_true based on iou_GT for false negative # idx = 0 # while (count_false_neg>0): # print(idx) # if y_true[idx]==0 and y_pred[idx] == 1: # all y_pred are 1 # y_true[idx] = 1 # y_pred[idx] = 0 # count_false_neg -= 1 # idx += 1 # add false negatives # tp = np.where(y_true==1 and y_pred==1) get ground truth and the scores (IoU values) array of polygons Args: input_shp: shape file of mapped polygons groud_truth_shp: shape file of ground truth polygons Returns: y_true,y_scores ( numpy array) # calculate the IoU of each predicted polygons # it seems unable to get it 1 Jan 2019 # return y_true,y_pred # score = f1_score(y_true, y_pred) #, default average='binary' calculate precision, recall based on IoU values Args: IoU_prediction: IoU of each mapped polygons, should be 1d numpy array IoU_ground_truth: IoU of each ground truth polygons: for count false negatives, should be 1d numpy array iou_threshold: IoU threshold Returns: precision, recall, f1 score # calculate precision, recall, F1 score # val_polygon_count = len(IoU_ground_truth) # false_neg_count = val_polygon_count - true_pos_count # use the following method, because in beiluhe case, a mapped polygon can cover two or more thaw slumps compute average_precision Args: precision_list: list of precision recall_list: list of recall Returns: #abs instead of using precision_recall_curve in sklearn.metrics, here we calculate the precision recall based on IoU Args: input_shp: shape file of mapped polygons groud_truth_shp:shape file of ground truth polygons Returns: precision, recall, threshold # calculate the IoU of each predicted polygons # calculate the IoU of each ground truth, for false negative # for iou_thr in np.arange(-0.01, 1.01, 0.05): #-0.05 # abs(iou_thr) >=0, it is strange (0 > -0.000 return true), Jan 16 2019. hlc # but it turns our that precision cannot be 1, so just keep it. # iou_thr = abs(iou_thr) #abs(iou_thr) # from sklearn.metrics import precision_recall_curve # In matplotlib < 1.5, plt.fill_between does not have a 'step' argument # post # save average_precision to txt file # plt.show() plot precision_recall of multi shapefiles to a figure Args: input_shp_list: a list of shapefiles groud_truth_shp: the ground truth file or a list save_path: output figure path Returns: # label_set = ['2017','2018','2019'] # k-fold cross-validation # image augmentation test # label = label_set[idx] # save average_precision to txt file # matplotlib build-in color # b: blue # g: green # r: red # c: cyan # m: magenta # y: yellow # k: black # w: white # # linestyle = [ '+','x' ,'*','s', 'h', 'd', 'p', 'H', 'D'] #, # plt.plot(recall, precision, 'r--') # plt.show() # get ground truth polygons # ground truth # calculate f1 score # calculate_f1_score(shape_file,val_path,0.5) # precision_recall_curve_iou(shape_file, val_path) # set parameters files, mandatory for the path of ground truth polygons
2.788802
3
networks/fusion_mld2_fcn.py
rfww/EfficientChangeDetection
0
6619589
<filename>networks/fusion_mld2_fcn.py import torch import torch.nn as nn import torch.nn.init as init import torch.nn.functional as F from torch.utils import model_zoo from torchvision import models class SegNetEnc(nn.Module): def __init__(self, in_channels, out_channels, num_layers): super().__init__() layers = [ nn.Upsample(scale_factor=2,mode='bilinear'), nn.Conv2d(in_channels, in_channels // 2, 3, padding=1), nn.BatchNorm2d(in_channels // 2), nn.ReLU(inplace=True), ] layers += [ nn.Conv2d(in_channels // 2, in_channels // 2, 3, padding=1), nn.BatchNorm2d(in_channels // 2), nn.ReLU(inplace=True), ] * num_layers layers += [ nn.Conv2d(in_channels // 2, out_channels, 3, padding=1), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), ] self.encode = nn.Sequential(*layers) def forward(self, x): return self.encode(x) class Fusion_mld2_fcn(nn.Module): def __init__(self, num_classes): super().__init__() ######mldnet2######################################## decoders = list(models.vgg16(pretrained=True).features.children()) self.dec1 = nn.Sequential(*decoders[:5]) self.dec2 = nn.Sequential(*decoders[5:10]) self.dec3 = nn.Sequential(*decoders[10:17]) self.dec4 = nn.Sequential(*decoders[17:24]) self.dec5 = nn.Sequential(*decoders[24:]) # for m in self.modules(): # if isinstance(m, nn.Conv2d): # m.requires_grad = False self.enc5 = SegNetEnc(512, 512, 1) self.enc4 = SegNetEnc(1024, 256, 1) self.enc3 = SegNetEnc(512, 128, 1) self.enc2 = SegNetEnc(256, 64, 0) self.enc5xy = SegNetEnc(512, 256, 0) self.enc4xy = SegNetEnc(512, 128, 0) self.enc3xy = SegNetEnc(256, 64, 0) self.enc2xy = SegNetEnc(128, 64, 0) self.enc1 = nn.Sequential( nn.Upsample(scale_factor=2, mode='bilinear'), nn.Conv2d(128, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(inplace=True), ) self.enc1xy = nn.Sequential( nn.Upsample(scale_factor=2, mode='bilinear'), nn.Conv2d(128, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(inplace=True), ) self.final5 = nn.Conv2d(256, num_classes, 3, padding=1) self.final4 = nn.Conv2d(128, num_classes, 3, padding=1) self.final3 = nn.Conv2d(64, num_classes, 3, padding=1) self.fuse = nn.Conv2d(18, num_classes, 3, padding=1) self.conv_cat1 = nn.Conv2d(4,num_classes,3,padding=1) self.conv_cat2 = nn.Conv2d(6, num_classes, 3, padding=1) self.conv_cat3 = nn.Conv2d(6, num_classes, 3, padding=1) #self.concat2 = nn.Conv2d(4, num_classes, 3, padding=1) #########FCN####################################### my_model = models.vgg16(pretrained=True) input_1_new = nn.Conv2d(6, 64, (3, 3), 1, 1) my_model.features[0] = input_1_new feats = list(my_model.features.children()) self.feats = nn.Sequential(*feats[0:10]) self.feat3 = nn.Sequential(*feats[10:17]) self.feat4 = nn.Sequential(*feats[17:24]) self.feat5 = nn.Sequential(*feats[24:31]) #for m in self.modules(): # if isinstance(m, nn.Conv2d): # m.requires_grad = False self.fconn = nn.Sequential( nn.Conv2d(512, 4096, 7), nn.ReLU(inplace=True), nn.Dropout(), nn.Conv2d(4096, 4096, 1), nn.ReLU(inplace=True), nn.Dropout(), ) self.score_feat3 = nn.Conv2d(256, num_classes, 1) self.score_feat4 = nn.Conv2d(512, num_classes, 1) self.score_fconn = nn.Conv2d(4096, num_classes, 1) def forward(self, x, y): #########forward_fcn###################### concat_xy = torch.cat([x, y], 1) feats = self.feats(concat_xy) feat3 = self.feat3(feats) feat4 = self.feat4(feat3) feat5 = self.feat5(feat4) fconn = self.fconn(feat5) score_feat3 = self.score_feat3(feat3) score_feat4 = self.score_feat4(feat4) score_fconn = self.score_fconn(fconn) score_1 = F.upsample_bilinear(score_fconn, score_feat4.size()[2:]) score_fuse1 = score_1 + score_feat4 score_2 = F.upsample_bilinear(score_fuse1, score_feat3.size()[2:]) score_fuse2 = score_2 + score_feat3 score_3 = F.upsample_bilinear(score_fuse2, x.size()[2:]) ##########forward_mldnet2###################### ''' Attention, input size should be the 32x. ''' dec1 = self.dec1(x) dec2 = self.dec2(dec1) dec3 = self.dec3(dec2) dec4 = self.dec4(dec3) dec5 = self.dec5(dec4) enc5 = self.enc5(dec5) enc4 = self.enc4(torch.cat([dec4, enc5], 1)) enc3 = self.enc3(torch.cat([dec3, enc4], 1)) enc2 = self.enc2(torch.cat([dec2, enc3], 1)) enc1 = self.enc1(torch.cat([dec1, enc2], 1)) dec1y = self.dec1(y) dec2y = self.dec2(dec1y) dec3y = self.dec3(dec2y) dec4y = self.dec4(dec3y) dec5y = self.dec5(dec4y) enc5y = self.enc5(dec5y) enc4y = self.enc4(torch.cat([dec4y, enc5y], 1)) enc3y = self.enc3(torch.cat([dec3y, enc4y], 1)) enc2y = self.enc2(torch.cat([dec2y, enc3y], 1)) enc1y = self.enc1(torch.cat([dec1y, enc2y], 1)) # difference of multiple layers enc5xy = self.enc5xy(abs(enc5 - enc5y)) enc4xy = self.enc4xy(torch.cat([abs(enc4 - enc4y), enc5xy], 1)) enc3xy = self.enc3xy(torch.cat([abs(enc3 - enc3y), enc4xy], 1)) enc5xy_n = F.upsample_bilinear(self.final5(enc5xy), x.size()[2:]) enc4xy_n = F.upsample_bilinear(self.final4(enc4xy), x.size()[2:]) enc3xy_n = F.upsample_bilinear(self.final3(enc3xy), x.size()[2:]) score_final1 = F.upsample_bilinear(score_1, x.size()[2:]) score_final2 = F.upsample_bilinear(score_2, x.size()[2:]) score_final3 = score_3 conv_cat1 = self.conv_cat_1(torch.cat([self.final5(enc5xy),score_1],1)) conv_cat1_up = F.upsample_bilinear(conv_cat1, score_2.size()[2:]) conv_cat2 = self.conv_cat_2(torch.cat([self.final4(enc4xy), score_2,conv_cat1_up], 1)) conv_cat2_up = F.upsample_bilinear(conv_cat2, score_3.size()[2:]) conv_cat3 = self.conv_cat_3(torch.cat([self.final3(enc4xy), score_3,conv_cat2_up], 1)) conv_cat3_up = F.upsample_bilinear(conv_cat3, x.size()[2:]) conv_cat1_n = F.upsample_bilinear(conv_cat1, x.size()[2:]) conv_cat2_n = F.upsample_bilinear(conv_cat2, x.size()[2:]) conv_cat3_n = conv_cat3_up final = self.fuse(torch.cat([enc5xy_n, enc4xy_n, enc3xy_n, score_final1, score_final2, score_final3, conv_cat1_n, conv_cat2_n, conv_cat3_n], 1)) return {enc5xy_n, enc4xy_n, enc3xy_n, score_final1, score_final2, score_final3,conv_cat1_n, conv_cat2_n, conv_cat3_n, final} #model = Fusion_mld_fcn() #print(model) #print(model.score_feat4) #print(model.feats[0]) #print(model.input_1) #model_2 = models.vgg16(pretrained=False) #print(model_2) #input_1 = model_2.features[0] #input_1_new = nn.Conv2d(6,64,(3,3),1,1) #model_2.features[0] = input_1_new #print(input_1_new) #print(model_2)
<filename>networks/fusion_mld2_fcn.py import torch import torch.nn as nn import torch.nn.init as init import torch.nn.functional as F from torch.utils import model_zoo from torchvision import models class SegNetEnc(nn.Module): def __init__(self, in_channels, out_channels, num_layers): super().__init__() layers = [ nn.Upsample(scale_factor=2,mode='bilinear'), nn.Conv2d(in_channels, in_channels // 2, 3, padding=1), nn.BatchNorm2d(in_channels // 2), nn.ReLU(inplace=True), ] layers += [ nn.Conv2d(in_channels // 2, in_channels // 2, 3, padding=1), nn.BatchNorm2d(in_channels // 2), nn.ReLU(inplace=True), ] * num_layers layers += [ nn.Conv2d(in_channels // 2, out_channels, 3, padding=1), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), ] self.encode = nn.Sequential(*layers) def forward(self, x): return self.encode(x) class Fusion_mld2_fcn(nn.Module): def __init__(self, num_classes): super().__init__() ######mldnet2######################################## decoders = list(models.vgg16(pretrained=True).features.children()) self.dec1 = nn.Sequential(*decoders[:5]) self.dec2 = nn.Sequential(*decoders[5:10]) self.dec3 = nn.Sequential(*decoders[10:17]) self.dec4 = nn.Sequential(*decoders[17:24]) self.dec5 = nn.Sequential(*decoders[24:]) # for m in self.modules(): # if isinstance(m, nn.Conv2d): # m.requires_grad = False self.enc5 = SegNetEnc(512, 512, 1) self.enc4 = SegNetEnc(1024, 256, 1) self.enc3 = SegNetEnc(512, 128, 1) self.enc2 = SegNetEnc(256, 64, 0) self.enc5xy = SegNetEnc(512, 256, 0) self.enc4xy = SegNetEnc(512, 128, 0) self.enc3xy = SegNetEnc(256, 64, 0) self.enc2xy = SegNetEnc(128, 64, 0) self.enc1 = nn.Sequential( nn.Upsample(scale_factor=2, mode='bilinear'), nn.Conv2d(128, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(inplace=True), ) self.enc1xy = nn.Sequential( nn.Upsample(scale_factor=2, mode='bilinear'), nn.Conv2d(128, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(inplace=True), ) self.final5 = nn.Conv2d(256, num_classes, 3, padding=1) self.final4 = nn.Conv2d(128, num_classes, 3, padding=1) self.final3 = nn.Conv2d(64, num_classes, 3, padding=1) self.fuse = nn.Conv2d(18, num_classes, 3, padding=1) self.conv_cat1 = nn.Conv2d(4,num_classes,3,padding=1) self.conv_cat2 = nn.Conv2d(6, num_classes, 3, padding=1) self.conv_cat3 = nn.Conv2d(6, num_classes, 3, padding=1) #self.concat2 = nn.Conv2d(4, num_classes, 3, padding=1) #########FCN####################################### my_model = models.vgg16(pretrained=True) input_1_new = nn.Conv2d(6, 64, (3, 3), 1, 1) my_model.features[0] = input_1_new feats = list(my_model.features.children()) self.feats = nn.Sequential(*feats[0:10]) self.feat3 = nn.Sequential(*feats[10:17]) self.feat4 = nn.Sequential(*feats[17:24]) self.feat5 = nn.Sequential(*feats[24:31]) #for m in self.modules(): # if isinstance(m, nn.Conv2d): # m.requires_grad = False self.fconn = nn.Sequential( nn.Conv2d(512, 4096, 7), nn.ReLU(inplace=True), nn.Dropout(), nn.Conv2d(4096, 4096, 1), nn.ReLU(inplace=True), nn.Dropout(), ) self.score_feat3 = nn.Conv2d(256, num_classes, 1) self.score_feat4 = nn.Conv2d(512, num_classes, 1) self.score_fconn = nn.Conv2d(4096, num_classes, 1) def forward(self, x, y): #########forward_fcn###################### concat_xy = torch.cat([x, y], 1) feats = self.feats(concat_xy) feat3 = self.feat3(feats) feat4 = self.feat4(feat3) feat5 = self.feat5(feat4) fconn = self.fconn(feat5) score_feat3 = self.score_feat3(feat3) score_feat4 = self.score_feat4(feat4) score_fconn = self.score_fconn(fconn) score_1 = F.upsample_bilinear(score_fconn, score_feat4.size()[2:]) score_fuse1 = score_1 + score_feat4 score_2 = F.upsample_bilinear(score_fuse1, score_feat3.size()[2:]) score_fuse2 = score_2 + score_feat3 score_3 = F.upsample_bilinear(score_fuse2, x.size()[2:]) ##########forward_mldnet2###################### ''' Attention, input size should be the 32x. ''' dec1 = self.dec1(x) dec2 = self.dec2(dec1) dec3 = self.dec3(dec2) dec4 = self.dec4(dec3) dec5 = self.dec5(dec4) enc5 = self.enc5(dec5) enc4 = self.enc4(torch.cat([dec4, enc5], 1)) enc3 = self.enc3(torch.cat([dec3, enc4], 1)) enc2 = self.enc2(torch.cat([dec2, enc3], 1)) enc1 = self.enc1(torch.cat([dec1, enc2], 1)) dec1y = self.dec1(y) dec2y = self.dec2(dec1y) dec3y = self.dec3(dec2y) dec4y = self.dec4(dec3y) dec5y = self.dec5(dec4y) enc5y = self.enc5(dec5y) enc4y = self.enc4(torch.cat([dec4y, enc5y], 1)) enc3y = self.enc3(torch.cat([dec3y, enc4y], 1)) enc2y = self.enc2(torch.cat([dec2y, enc3y], 1)) enc1y = self.enc1(torch.cat([dec1y, enc2y], 1)) # difference of multiple layers enc5xy = self.enc5xy(abs(enc5 - enc5y)) enc4xy = self.enc4xy(torch.cat([abs(enc4 - enc4y), enc5xy], 1)) enc3xy = self.enc3xy(torch.cat([abs(enc3 - enc3y), enc4xy], 1)) enc5xy_n = F.upsample_bilinear(self.final5(enc5xy), x.size()[2:]) enc4xy_n = F.upsample_bilinear(self.final4(enc4xy), x.size()[2:]) enc3xy_n = F.upsample_bilinear(self.final3(enc3xy), x.size()[2:]) score_final1 = F.upsample_bilinear(score_1, x.size()[2:]) score_final2 = F.upsample_bilinear(score_2, x.size()[2:]) score_final3 = score_3 conv_cat1 = self.conv_cat_1(torch.cat([self.final5(enc5xy),score_1],1)) conv_cat1_up = F.upsample_bilinear(conv_cat1, score_2.size()[2:]) conv_cat2 = self.conv_cat_2(torch.cat([self.final4(enc4xy), score_2,conv_cat1_up], 1)) conv_cat2_up = F.upsample_bilinear(conv_cat2, score_3.size()[2:]) conv_cat3 = self.conv_cat_3(torch.cat([self.final3(enc4xy), score_3,conv_cat2_up], 1)) conv_cat3_up = F.upsample_bilinear(conv_cat3, x.size()[2:]) conv_cat1_n = F.upsample_bilinear(conv_cat1, x.size()[2:]) conv_cat2_n = F.upsample_bilinear(conv_cat2, x.size()[2:]) conv_cat3_n = conv_cat3_up final = self.fuse(torch.cat([enc5xy_n, enc4xy_n, enc3xy_n, score_final1, score_final2, score_final3, conv_cat1_n, conv_cat2_n, conv_cat3_n], 1)) return {enc5xy_n, enc4xy_n, enc3xy_n, score_final1, score_final2, score_final3,conv_cat1_n, conv_cat2_n, conv_cat3_n, final} #model = Fusion_mld_fcn() #print(model) #print(model.score_feat4) #print(model.feats[0]) #print(model.input_1) #model_2 = models.vgg16(pretrained=False) #print(model_2) #input_1 = model_2.features[0] #input_1_new = nn.Conv2d(6,64,(3,3),1,1) #model_2.features[0] = input_1_new #print(input_1_new) #print(model_2)
en
0.251121
######mldnet2######################################## # for m in self.modules(): # if isinstance(m, nn.Conv2d): # m.requires_grad = False #self.concat2 = nn.Conv2d(4, num_classes, 3, padding=1) #########FCN####################################### #for m in self.modules(): # if isinstance(m, nn.Conv2d): # m.requires_grad = False #########forward_fcn###################### ##########forward_mldnet2###################### Attention, input size should be the 32x. # difference of multiple layers #model = Fusion_mld_fcn() #print(model) #print(model.score_feat4) #print(model.feats[0]) #print(model.input_1) #model_2 = models.vgg16(pretrained=False) #print(model_2) #input_1 = model_2.features[0] #input_1_new = nn.Conv2d(6,64,(3,3),1,1) #model_2.features[0] = input_1_new #print(input_1_new) #print(model_2)
2.397759
2
examples/correct/plot_attenuation.py
kmuehlbauer/pyart
0
6619590
""" ================================ Correct reflectivity attenuation ================================ In this example the reflectivity attenuation is calculated and then corrected for a polarimetric radar using a Z-PHI method implemented in Py-ART. """ print __doc__ # Author: <NAME> (<EMAIL>) # License: BSD 3 clause import matplotlib.pyplot as plt import pyart RADAR_NAME = 'sgpcsaprsurcmacI7.c0.20110520.095101.nc' # read in the data radar = pyart.io.read_cfradial(RADAR_NAME) # remove existing corrections radar.fields.pop('specific_attenuation') radar.fields.pop('corrected_reflectivity_horizontal') # perform attenuation correction spec_at, cor_z = pyart.correct.calculate_attenuation( radar, 0, refl_field='reflectivity_horizontal', ncp_field='norm_coherent_power', rhv_field='copol_coeff', phidp_field='proc_dp_phase_shift') radar.add_field('specific_attenuation', spec_at) radar.add_field('corrected_reflectivity_horizontal', cor_z) # create the plot fig = plt.figure(figsize=(15, 5)) ax1 = fig.add_subplot(131) display = pyart.graph.RadarDisplay(radar) display.plot('reflectivity_horizontal', 0, ax=ax1, vmin=0, vmax=60., colorbar_label='', title='Raw Reflectivity') ax2 = fig.add_subplot(132) display.plot('specific_attenuation', 0, vmin=0, vmax=1.0, colorbar_label='', ax=ax2, title='Specific Attenuation') ax3 = fig.add_subplot(133) display = pyart.graph.RadarDisplay(radar) display.plot('corrected_reflectivity_horizontal', 0, vmin=0, vmax=60., colorbar_label='', ax=ax3, title='Corrected Reflectivity') plt.suptitle('Attenuation correction using Py-ART', fontsize=16) plt.show()
""" ================================ Correct reflectivity attenuation ================================ In this example the reflectivity attenuation is calculated and then corrected for a polarimetric radar using a Z-PHI method implemented in Py-ART. """ print __doc__ # Author: <NAME> (<EMAIL>) # License: BSD 3 clause import matplotlib.pyplot as plt import pyart RADAR_NAME = 'sgpcsaprsurcmacI7.c0.20110520.095101.nc' # read in the data radar = pyart.io.read_cfradial(RADAR_NAME) # remove existing corrections radar.fields.pop('specific_attenuation') radar.fields.pop('corrected_reflectivity_horizontal') # perform attenuation correction spec_at, cor_z = pyart.correct.calculate_attenuation( radar, 0, refl_field='reflectivity_horizontal', ncp_field='norm_coherent_power', rhv_field='copol_coeff', phidp_field='proc_dp_phase_shift') radar.add_field('specific_attenuation', spec_at) radar.add_field('corrected_reflectivity_horizontal', cor_z) # create the plot fig = plt.figure(figsize=(15, 5)) ax1 = fig.add_subplot(131) display = pyart.graph.RadarDisplay(radar) display.plot('reflectivity_horizontal', 0, ax=ax1, vmin=0, vmax=60., colorbar_label='', title='Raw Reflectivity') ax2 = fig.add_subplot(132) display.plot('specific_attenuation', 0, vmin=0, vmax=1.0, colorbar_label='', ax=ax2, title='Specific Attenuation') ax3 = fig.add_subplot(133) display = pyart.graph.RadarDisplay(radar) display.plot('corrected_reflectivity_horizontal', 0, vmin=0, vmax=60., colorbar_label='', ax=ax3, title='Corrected Reflectivity') plt.suptitle('Attenuation correction using Py-ART', fontsize=16) plt.show()
en
0.693255
================================ Correct reflectivity attenuation ================================ In this example the reflectivity attenuation is calculated and then corrected for a polarimetric radar using a Z-PHI method implemented in Py-ART. # Author: <NAME> (<EMAIL>) # License: BSD 3 clause # read in the data # remove existing corrections # perform attenuation correction # create the plot
2.75876
3
data/kaggle_dataset.py
UESTC2021MLGroup/Swin-Transformer
0
6619591
<filename>data/kaggle_dataset.py import os import cv2 import torch import torch.nn as nn import pandas as pd import numpy as np import albumentations as A from albumentations.pytorch import ToTensorV2 from torch.utils.data import Dataset class KaggleDataset(Dataset): def __init__(self, is_train, data_root='/home/dahu/xueruini/onion_rain/pytorch/dataset/plant-pathology-2021-fgvc8/train_images/', csv_root='/home/dahu/xueruini/onion_rain/pytorch/dataset/plant-pathology-2021-fgvc8/div/', ): self.data_root = data_root if is_train: csv_data = pd.read_csv(csv_root+"trainset.csv") self.transform = A.Compose([ A.SmallestMaxSize(256), A.RandomCrop(224, 224), A.Flip(p=0.5), A.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)), ToTensorV2() ]) else: csv_data = pd.read_csv(csv_root+"valset.csv") self.transform = A.Compose([ A.SmallestMaxSize(256), A.CenterCrop(224, 224), A.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)), ToTensorV2() ]) self.img_paths = csv_data['image'].values self.labels = csv_data['t_label'].values def __len__(self): return len(self.img_paths) def __getitem__(self, index): image = cv2.imread(os.path.join(self.data_root, self.img_paths[index])) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image = self.transform(image=image)['image'] labels = self.labels[index] labels = labels[1:-1].split(" ") label = np.array([np.float32(x) for x in labels]) return image, label def denormalization(x): ''' de-normalization ''' mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) x = (((x.transpose(1, 2, 0) * std) + mean) * 255.).astype(np.uint8) return x # if __name__ == '__main__': # import matplotlib.pyplot as plt # data_dir = '../../data/train_images/' # csv_file = '../dataset_csv/all_train.csv' # trainset = KaggleDataSet(data_root=data_dir, csv_file=csv_file, mode='train') # trainloader = DataLoader(dataset=trainset, batch_size=4, shuffle=True) # for _, data in enumerate(trainloader): # imgs, labels = data # imgs = imgs.numpy() # # labels = labels.numpy() # # print(imgs, imgs.shape) # print(labels) # figure, ax = plt.subplots(nrows=1, ncols=4, figsize=(24, 10)) # for i in range(imgs.shape[0]): # img = denormalization(imgs[i]) # ax[i].imshow(img) # plt.show() # plt.savefig("test_dataloader.png") # break
<filename>data/kaggle_dataset.py import os import cv2 import torch import torch.nn as nn import pandas as pd import numpy as np import albumentations as A from albumentations.pytorch import ToTensorV2 from torch.utils.data import Dataset class KaggleDataset(Dataset): def __init__(self, is_train, data_root='/home/dahu/xueruini/onion_rain/pytorch/dataset/plant-pathology-2021-fgvc8/train_images/', csv_root='/home/dahu/xueruini/onion_rain/pytorch/dataset/plant-pathology-2021-fgvc8/div/', ): self.data_root = data_root if is_train: csv_data = pd.read_csv(csv_root+"trainset.csv") self.transform = A.Compose([ A.SmallestMaxSize(256), A.RandomCrop(224, 224), A.Flip(p=0.5), A.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)), ToTensorV2() ]) else: csv_data = pd.read_csv(csv_root+"valset.csv") self.transform = A.Compose([ A.SmallestMaxSize(256), A.CenterCrop(224, 224), A.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)), ToTensorV2() ]) self.img_paths = csv_data['image'].values self.labels = csv_data['t_label'].values def __len__(self): return len(self.img_paths) def __getitem__(self, index): image = cv2.imread(os.path.join(self.data_root, self.img_paths[index])) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image = self.transform(image=image)['image'] labels = self.labels[index] labels = labels[1:-1].split(" ") label = np.array([np.float32(x) for x in labels]) return image, label def denormalization(x): ''' de-normalization ''' mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) x = (((x.transpose(1, 2, 0) * std) + mean) * 255.).astype(np.uint8) return x # if __name__ == '__main__': # import matplotlib.pyplot as plt # data_dir = '../../data/train_images/' # csv_file = '../dataset_csv/all_train.csv' # trainset = KaggleDataSet(data_root=data_dir, csv_file=csv_file, mode='train') # trainloader = DataLoader(dataset=trainset, batch_size=4, shuffle=True) # for _, data in enumerate(trainloader): # imgs, labels = data # imgs = imgs.numpy() # # labels = labels.numpy() # # print(imgs, imgs.shape) # print(labels) # figure, ax = plt.subplots(nrows=1, ncols=4, figsize=(24, 10)) # for i in range(imgs.shape[0]): # img = denormalization(imgs[i]) # ax[i].imshow(img) # plt.show() # plt.savefig("test_dataloader.png") # break
en
0.340388
de-normalization # if __name__ == '__main__': # import matplotlib.pyplot as plt # data_dir = '../../data/train_images/' # csv_file = '../dataset_csv/all_train.csv' # trainset = KaggleDataSet(data_root=data_dir, csv_file=csv_file, mode='train') # trainloader = DataLoader(dataset=trainset, batch_size=4, shuffle=True) # for _, data in enumerate(trainloader): # imgs, labels = data # imgs = imgs.numpy() # # labels = labels.numpy() # # print(imgs, imgs.shape) # print(labels) # figure, ax = plt.subplots(nrows=1, ncols=4, figsize=(24, 10)) # for i in range(imgs.shape[0]): # img = denormalization(imgs[i]) # ax[i].imshow(img) # plt.show() # plt.savefig("test_dataloader.png") # break
2.634685
3
engine/algorithms/__init__.py
dentonmwood/codeDuplicationParser
1
6619592
"""Package containing all implemented clone detection algorithms.""" OXYGEN = "oxygen" CHLORINE = "chlorine" IODINE = "iodine"
"""Package containing all implemented clone detection algorithms.""" OXYGEN = "oxygen" CHLORINE = "chlorine" IODINE = "iodine"
en
0.810964
Package containing all implemented clone detection algorithms.
1.000333
1
flask/app.py
isALEXme/cryptus
1
6619593
# import twitter # from requests_oauthlib import OAuth1Session from flask import Flask, request # from flask_cors import CORS app = Flask(__name__) # CORS(app) @app.route("/symbols_to_text") def hi(): text = request.args.get('text') return "text" if __name__ == "__main__": app.run()
# import twitter # from requests_oauthlib import OAuth1Session from flask import Flask, request # from flask_cors import CORS app = Flask(__name__) # CORS(app) @app.route("/symbols_to_text") def hi(): text = request.args.get('text') return "text" if __name__ == "__main__": app.run()
en
0.28016
# import twitter # from requests_oauthlib import OAuth1Session # from flask_cors import CORS # CORS(app)
2.483268
2
Algorithms/0128_Longest_Consecutive_Sequence/Python/Longest_Consecutive_Sequence_Solution_1.py
lht19900714/Leetcode_Solutions
0
6619594
# Space: O(n) # Time: O(n) class Solution: def longestConsecutive(self, nums): if not nums: return 0 nums = sorted(list(set(nums))) res = 0 counter = 1 index = 1 while index < len(nums): if nums[index] == nums[index - 1] + 1: counter += 1 else: res = max(res, counter) counter = 1 index += 1 return max(res, counter)
# Space: O(n) # Time: O(n) class Solution: def longestConsecutive(self, nums): if not nums: return 0 nums = sorted(list(set(nums))) res = 0 counter = 1 index = 1 while index < len(nums): if nums[index] == nums[index - 1] + 1: counter += 1 else: res = max(res, counter) counter = 1 index += 1 return max(res, counter)
en
0.367409
# Space: O(n) # Time: O(n)
3.372845
3
codino/data/CodonDesign.py
dzhang32/codino
0
6619595
from codino.data import FreqTable class CodonDesign: def __init__(self) -> None: """CodonDesign class for storing codon designs. Stores the frequency of each nucleotide (A/T/C/G) at each position (1/2/3) of a codon. Frequencies are stored in FreqTables. """ self.first = FreqTable({"A": 0.0, "T": 0.0, "C": 0.0, "G": 0.0}) self.second = FreqTable({"A": 0.0, "T": 0.0, "C": 0.0, "G": 0.0}) self.third = FreqTable({"A": 0.0, "T": 0.0, "C": 0.0, "G": 0.0}) def set_codon_design(self, first: dict, second: dict, third: dict) -> None: """Method for setting the codon design Sets the frequency of the nucleotides at the 3 positions. Args: first (dict): nucleotide frequencies for first position. second (dict): nucleotide frequencies for second position. third (dict): nucleotide frequencies for third position. """ self.first.freq = first self.second.freq = second self.third.freq = third
from codino.data import FreqTable class CodonDesign: def __init__(self) -> None: """CodonDesign class for storing codon designs. Stores the frequency of each nucleotide (A/T/C/G) at each position (1/2/3) of a codon. Frequencies are stored in FreqTables. """ self.first = FreqTable({"A": 0.0, "T": 0.0, "C": 0.0, "G": 0.0}) self.second = FreqTable({"A": 0.0, "T": 0.0, "C": 0.0, "G": 0.0}) self.third = FreqTable({"A": 0.0, "T": 0.0, "C": 0.0, "G": 0.0}) def set_codon_design(self, first: dict, second: dict, third: dict) -> None: """Method for setting the codon design Sets the frequency of the nucleotides at the 3 positions. Args: first (dict): nucleotide frequencies for first position. second (dict): nucleotide frequencies for second position. third (dict): nucleotide frequencies for third position. """ self.first.freq = first self.second.freq = second self.third.freq = third
en
0.84257
CodonDesign class for storing codon designs. Stores the frequency of each nucleotide (A/T/C/G) at each position (1/2/3) of a codon. Frequencies are stored in FreqTables. Method for setting the codon design Sets the frequency of the nucleotides at the 3 positions. Args: first (dict): nucleotide frequencies for first position. second (dict): nucleotide frequencies for second position. third (dict): nucleotide frequencies for third position.
3.648556
4
t/eviction_full_memory_test.py
rohankumardubey/orioledb
947
6619596
<filename>t/eviction_full_memory_test.py #!/usr/bin/env python3 # coding: utf-8 import unittest from .base_test import BaseTest from .base_test import ThreadQueryExecutor class EvictionFullMemoryTest(BaseTest): def test_eviction_table_full_memory(self): node = self.node node.append_conf('postgresql.conf', "orioledb.debug_disable_bgwriter = true\n" "orioledb.main_buffers = 8MB\n") node.start() node.safe_psql('postgres', "CREATE EXTENSION IF NOT EXISTS orioledb;\n" "CREATE TABLE IF NOT EXISTS o_test (\n" " key int8 NOT NULL,\n" " val int8 NOT NULL,\n" " val2 text NOT NULL,\n" " PRIMARY KEY (key)\n" ") USING orioledb;\n") n = 200000 con = node.connect() con.begin() con.execute("INSERT INTO o_test (SELECT id, %s - id, repeat('x', 1000) FROM generate_series(%s, %s, 1) id);" % (str(n), str(1), str(n))) con.commit() con.close() node.stop() def test_eviction_table_full_memory_root_incomplete_split(self): node = self.node node.append_conf('postgresql.conf', "orioledb.debug_disable_bgwriter = true\n" "orioledb.main_buffers = 8MB\n") node.start() node.safe_psql('postgres', "CREATE EXTENSION IF NOT EXISTS orioledb;\n" "CREATE TABLE IF NOT EXISTS o_test (\n" " key int8 NOT NULL,\n" " val int8 NOT NULL,\n" " val2 text NOT NULL,\n" " PRIMARY KEY (key, val)\n" ") USING orioledb;\n") before_root_split = 255000 n = 256000 step = 1000 con1 = node.connect() con2 = node.connect() con1_pid = con1.pid con2_pid = con2.pid con1.execute("SET orioledb.enable_stopevents = true;") con2.execute("SELECT pg_stopevent_set('split_fail', '$.treeName == \"o_test_pkey\" && $.level == 2');") # prevent to fix root split by an apply_undo() con2.execute("SELECT pg_stopevent_set('before_apply_undo', 'true');") for i in range(1, before_root_split, step): con1.begin() con1.execute("INSERT INTO o_test (SELECT id, %s - id, repeat('x', 2000) FROM generate_series(%s, %s, 1) id);" % (str(n), str(i), str(i + step - 1))) con1.commit() t1 = ThreadQueryExecutor(con1, "INSERT INTO o_test (SELECT id, %s - id, repeat('x', 2000) FROM generate_series(%s, %s, 1) id);" % (str(200000), str(before_root_split + 1), str(before_root_split + step))) t1.start() while node.execute("SELECT pg_isolation_test_session_is_blocked(%d, '{%d}');" % (con1_pid, con2_pid))[0][0] == False: continue # we have 1 reserved free page, table creation needs 7, try to get con2.execute("CREATE TABLE o_get_free_pages (\n" " key integer NOT NULL,\n" " PRIMARY KEY (key)\n" ") USING orioledb;\n") con2.execute("SELECT * FROM o_get_free_pages;") con2.execute("SELECT pg_stopevent_reset('split_fail');") con2.execute("SELECT pg_stopevent_reset('before_apply_undo');") try: t1.join() except AssertionError: raise except Exception: self.assertTrue(True) con1.close() con2.close() node.stop() if __name__ == "__main__": unittest.main()
<filename>t/eviction_full_memory_test.py #!/usr/bin/env python3 # coding: utf-8 import unittest from .base_test import BaseTest from .base_test import ThreadQueryExecutor class EvictionFullMemoryTest(BaseTest): def test_eviction_table_full_memory(self): node = self.node node.append_conf('postgresql.conf', "orioledb.debug_disable_bgwriter = true\n" "orioledb.main_buffers = 8MB\n") node.start() node.safe_psql('postgres', "CREATE EXTENSION IF NOT EXISTS orioledb;\n" "CREATE TABLE IF NOT EXISTS o_test (\n" " key int8 NOT NULL,\n" " val int8 NOT NULL,\n" " val2 text NOT NULL,\n" " PRIMARY KEY (key)\n" ") USING orioledb;\n") n = 200000 con = node.connect() con.begin() con.execute("INSERT INTO o_test (SELECT id, %s - id, repeat('x', 1000) FROM generate_series(%s, %s, 1) id);" % (str(n), str(1), str(n))) con.commit() con.close() node.stop() def test_eviction_table_full_memory_root_incomplete_split(self): node = self.node node.append_conf('postgresql.conf', "orioledb.debug_disable_bgwriter = true\n" "orioledb.main_buffers = 8MB\n") node.start() node.safe_psql('postgres', "CREATE EXTENSION IF NOT EXISTS orioledb;\n" "CREATE TABLE IF NOT EXISTS o_test (\n" " key int8 NOT NULL,\n" " val int8 NOT NULL,\n" " val2 text NOT NULL,\n" " PRIMARY KEY (key, val)\n" ") USING orioledb;\n") before_root_split = 255000 n = 256000 step = 1000 con1 = node.connect() con2 = node.connect() con1_pid = con1.pid con2_pid = con2.pid con1.execute("SET orioledb.enable_stopevents = true;") con2.execute("SELECT pg_stopevent_set('split_fail', '$.treeName == \"o_test_pkey\" && $.level == 2');") # prevent to fix root split by an apply_undo() con2.execute("SELECT pg_stopevent_set('before_apply_undo', 'true');") for i in range(1, before_root_split, step): con1.begin() con1.execute("INSERT INTO o_test (SELECT id, %s - id, repeat('x', 2000) FROM generate_series(%s, %s, 1) id);" % (str(n), str(i), str(i + step - 1))) con1.commit() t1 = ThreadQueryExecutor(con1, "INSERT INTO o_test (SELECT id, %s - id, repeat('x', 2000) FROM generate_series(%s, %s, 1) id);" % (str(200000), str(before_root_split + 1), str(before_root_split + step))) t1.start() while node.execute("SELECT pg_isolation_test_session_is_blocked(%d, '{%d}');" % (con1_pid, con2_pid))[0][0] == False: continue # we have 1 reserved free page, table creation needs 7, try to get con2.execute("CREATE TABLE o_get_free_pages (\n" " key integer NOT NULL,\n" " PRIMARY KEY (key)\n" ") USING orioledb;\n") con2.execute("SELECT * FROM o_get_free_pages;") con2.execute("SELECT pg_stopevent_reset('split_fail');") con2.execute("SELECT pg_stopevent_reset('before_apply_undo');") try: t1.join() except AssertionError: raise except Exception: self.assertTrue(True) con1.close() con2.close() node.stop() if __name__ == "__main__": unittest.main()
en
0.7885
#!/usr/bin/env python3 # coding: utf-8 # prevent to fix root split by an apply_undo() # we have 1 reserved free page, table creation needs 7, try to get
2.557123
3
Tests/Runnable3/r_builtinlist_t.py
jwilk/Pyrex
5
6619597
from r_builtinlist import f x = f() print x
from r_builtinlist import f x = f() print x
none
1
1.438628
1
Algorithms/main.py
anh-honcharuk/Algorithms
0
6619598
from base_algorithms.sorting import Sorting l = [1, 3, 3, 3, 4, 2, -1, 8, -10, 5, 4] # print(Sorting.insertion_sort(l, True)) print(Sorting.quick_sort(l, False))
from base_algorithms.sorting import Sorting l = [1, 3, 3, 3, 4, 2, -1, 8, -10, 5, 4] # print(Sorting.insertion_sort(l, True)) print(Sorting.quick_sort(l, False))
en
0.304782
# print(Sorting.insertion_sort(l, True))
3.264845
3
flopt/solution.py
nariaki3551/flopt
4
6619599
<gh_stars>1-10 import random from math import sqrt from flopt.env import setup_logger logger = setup_logger(__name__) class Solution: """ Solution Class Parameters ---------- name : str name of solution variables : list of VarElement family variables which has no duplicate Attributes ---------- name : str name of solution type : str _variables : list of varElement variable array _var_dict : dict key is name of variable, key is variable Examples ---------- Create a Solution which has Integer, Continuous and Binary Variables >>> a = Variable(name='a', lowBound=0, upBound=1, cat='Integer') >>> b = Variable(name='b', lowBound=1, upBound=2, cat='Continuous') >>> c = Variable(name='c', cat='Binary') >>> sol = Solution(name='abc', [a, b, c]) Four arithmetic operations are supported between Solutions or between a Solution and a constant. >>> sol1 = Solution(name='sol1', [a, b]) >>> sol2 = Solution(name='sol2', [a, c]) >>> sol_plus = sol1 + sol2 # (Solution + Solution or Solution + list) >>> sol_minus = sol1 - sol2 # (Solution - Solution or Solution - list) >>> sol_product = sol1 * 2 # (Solution * constant) >>> sol_divide = sol1 / 2 # (Solution / constant) """ def __init__(self, name=None, variables=[]): self.name = name self.type = 'Solution' self._variables = sorted(variables, key=lambda var: var.name) self._var_dict = None def toDict(self): """ Returns ------- dict: key is name of variable, value is VarElement family or Expression or Const """ if self._var_dict is None: self._var_dict = {variable.name: variable for variable in self._variables} return self._var_dict def value(self): """ Returns ------- list values of the variables in the Solution """ return [variable.value() for variable in self._variables] def setValue(self, name, value): """ Parameters ---------- name: str value: int or float """ self.toDict()[name].setValue(value) def getVariables(self): """ Returns ------- list Variable instances which belong to the Solution """ return self._variables def clone(self): """ Returns ------- Solution Copy of the Solution (call by value) """ return +self def copy(self, other): """ Copy the values of a Solution to itself (call by value) """ for vb, ovb in zip(self._variables, other._variables): vb.setValue(ovb.value()) def setRandom(self): """ Set the solution values uniformly random """ for vb in self._variables: vb.setRandom() def feasible(self): """ Returns ------- bool Whether the solution is feasible or not """ return all(vb.feasible() for vb in self._variables) def clip(self): """ Guarantee feasibility of the solution """ for vb in self._variables: vb.clip() def squaredNorm(self): """ Returns ------- float Squared 2-norm of the solution as a vector in Euclid space """ return sum(vb.value()*vb.value() for vb in self._variables) def norm(self): """ Returns ------- float 2-norm of the solution as a vector in Euclid space """ return sqrt(self.squaredNorm()) def dot(self, other): """ Returns ------- float Inner product between the Solution and another Solution """ inner = 0 for vb1, vb2 in zip(self._variables, other._variables): inner += vb1.value()*vb2.value() return inner def __pos__(self): variables = [ var.clone() for var in self._variables ] return Solution(f'+({self.name})', variables) def __neg__(self): variables = [ var.clone() for var in self._variables ] for var in variables: var.setValue(-var.value()) return Solution(f'-({self.name})', variables) def __add__(self, other): """ Solution + Solution Solution + list Solutino + scalar """ variables = [ var.clone() for var in self._variables ] if isinstance(other, Solution): for var1, var2 in zip(variables, other._variables): var1.setValue(var1.value() + var2.value()) return Solution('+Solution', variables) elif isinstance(other, list): for var, v in zip(variables, other): var.setValue(var.value() + v) return Solution('+list', variables) elif isinstance(other, (int, float)): for var in variables: var.setValue(var.value() + other) return Solution('+scalar', variables) else: return NotImplemented def __radd__(self, other): return self + other def __sub__(self, other): """ Solution - Solution = (Solution + (-Solution)) Solution - list = (Solution + (-list)) Solutino - scalar = (Solution + (-scalar)) """ variables = [ var.clone() for var in self._variables ] if isinstance(other, Solution): for var1, var2 in zip(variables, other._variables): var1.setValue(var1.value() - var2.value()) return Solution('+Solution', variables) elif isinstance(other, list): for var, v in zip(variables, other): var.setValue(var.value() - v) return Solution('+list', variables) elif isinstance(other, (int, float)): for var in variables: var.setValue(var.value() - other) return Solution('+scalar', variables) else: return NotImplemented def __rsub__(self, other): return - self + other def __mul__(self, other): """ Solution * Solution (hadamard product) Solution * list Solution * scalar """ variables = [ var.clone() for var in self._variables ] if isinstance(other, Solution): for var1, var2 in zip(variables, other._variables): var1.setValue(var1.value() * var2.value()) return Solution('*Solution', variables) elif isinstance(other, list): for var, v in zip(variables, other): var.setValue(var.value() * v) return Solution('*list', variables) elif isinstance(other, (int, float)): for var in variables: var.setValue(var.value() * other) return Solution('*scalar', variables) else: return NotImplemented def __rmul__(self, other): return self * other def __truediv__(self, other): """ Solution / list = Solution * (1/list) Solution / scalar = Solution * (1/scalar) """ if isinstance(other, list): reverse_list = [1/v for v in other] return self * reverse_list elif isinstance(other, (int, float)): return self * (1 / other) else: return NotImplemented def __abs__(self): variables = [ var.clone() for var in self._variables ] for var in variables: var.setValue(abs(var.value())) return Solution('abs', variables) def __hash__(self): return hash((self.name, tuple(self._variables))) def __len__(self): return len(self._variables) def __iter__(self): return iter(self._variables) def __getitem__(self, k): return self._variables[k] def __str__(self): return self.__repr__() def __repr__(self): return f'Solution({self.name}, [{", ".join([vb.name for vb in self._variables])}])'
import random from math import sqrt from flopt.env import setup_logger logger = setup_logger(__name__) class Solution: """ Solution Class Parameters ---------- name : str name of solution variables : list of VarElement family variables which has no duplicate Attributes ---------- name : str name of solution type : str _variables : list of varElement variable array _var_dict : dict key is name of variable, key is variable Examples ---------- Create a Solution which has Integer, Continuous and Binary Variables >>> a = Variable(name='a', lowBound=0, upBound=1, cat='Integer') >>> b = Variable(name='b', lowBound=1, upBound=2, cat='Continuous') >>> c = Variable(name='c', cat='Binary') >>> sol = Solution(name='abc', [a, b, c]) Four arithmetic operations are supported between Solutions or between a Solution and a constant. >>> sol1 = Solution(name='sol1', [a, b]) >>> sol2 = Solution(name='sol2', [a, c]) >>> sol_plus = sol1 + sol2 # (Solution + Solution or Solution + list) >>> sol_minus = sol1 - sol2 # (Solution - Solution or Solution - list) >>> sol_product = sol1 * 2 # (Solution * constant) >>> sol_divide = sol1 / 2 # (Solution / constant) """ def __init__(self, name=None, variables=[]): self.name = name self.type = 'Solution' self._variables = sorted(variables, key=lambda var: var.name) self._var_dict = None def toDict(self): """ Returns ------- dict: key is name of variable, value is VarElement family or Expression or Const """ if self._var_dict is None: self._var_dict = {variable.name: variable for variable in self._variables} return self._var_dict def value(self): """ Returns ------- list values of the variables in the Solution """ return [variable.value() for variable in self._variables] def setValue(self, name, value): """ Parameters ---------- name: str value: int or float """ self.toDict()[name].setValue(value) def getVariables(self): """ Returns ------- list Variable instances which belong to the Solution """ return self._variables def clone(self): """ Returns ------- Solution Copy of the Solution (call by value) """ return +self def copy(self, other): """ Copy the values of a Solution to itself (call by value) """ for vb, ovb in zip(self._variables, other._variables): vb.setValue(ovb.value()) def setRandom(self): """ Set the solution values uniformly random """ for vb in self._variables: vb.setRandom() def feasible(self): """ Returns ------- bool Whether the solution is feasible or not """ return all(vb.feasible() for vb in self._variables) def clip(self): """ Guarantee feasibility of the solution """ for vb in self._variables: vb.clip() def squaredNorm(self): """ Returns ------- float Squared 2-norm of the solution as a vector in Euclid space """ return sum(vb.value()*vb.value() for vb in self._variables) def norm(self): """ Returns ------- float 2-norm of the solution as a vector in Euclid space """ return sqrt(self.squaredNorm()) def dot(self, other): """ Returns ------- float Inner product between the Solution and another Solution """ inner = 0 for vb1, vb2 in zip(self._variables, other._variables): inner += vb1.value()*vb2.value() return inner def __pos__(self): variables = [ var.clone() for var in self._variables ] return Solution(f'+({self.name})', variables) def __neg__(self): variables = [ var.clone() for var in self._variables ] for var in variables: var.setValue(-var.value()) return Solution(f'-({self.name})', variables) def __add__(self, other): """ Solution + Solution Solution + list Solutino + scalar """ variables = [ var.clone() for var in self._variables ] if isinstance(other, Solution): for var1, var2 in zip(variables, other._variables): var1.setValue(var1.value() + var2.value()) return Solution('+Solution', variables) elif isinstance(other, list): for var, v in zip(variables, other): var.setValue(var.value() + v) return Solution('+list', variables) elif isinstance(other, (int, float)): for var in variables: var.setValue(var.value() + other) return Solution('+scalar', variables) else: return NotImplemented def __radd__(self, other): return self + other def __sub__(self, other): """ Solution - Solution = (Solution + (-Solution)) Solution - list = (Solution + (-list)) Solutino - scalar = (Solution + (-scalar)) """ variables = [ var.clone() for var in self._variables ] if isinstance(other, Solution): for var1, var2 in zip(variables, other._variables): var1.setValue(var1.value() - var2.value()) return Solution('+Solution', variables) elif isinstance(other, list): for var, v in zip(variables, other): var.setValue(var.value() - v) return Solution('+list', variables) elif isinstance(other, (int, float)): for var in variables: var.setValue(var.value() - other) return Solution('+scalar', variables) else: return NotImplemented def __rsub__(self, other): return - self + other def __mul__(self, other): """ Solution * Solution (hadamard product) Solution * list Solution * scalar """ variables = [ var.clone() for var in self._variables ] if isinstance(other, Solution): for var1, var2 in zip(variables, other._variables): var1.setValue(var1.value() * var2.value()) return Solution('*Solution', variables) elif isinstance(other, list): for var, v in zip(variables, other): var.setValue(var.value() * v) return Solution('*list', variables) elif isinstance(other, (int, float)): for var in variables: var.setValue(var.value() * other) return Solution('*scalar', variables) else: return NotImplemented def __rmul__(self, other): return self * other def __truediv__(self, other): """ Solution / list = Solution * (1/list) Solution / scalar = Solution * (1/scalar) """ if isinstance(other, list): reverse_list = [1/v for v in other] return self * reverse_list elif isinstance(other, (int, float)): return self * (1 / other) else: return NotImplemented def __abs__(self): variables = [ var.clone() for var in self._variables ] for var in variables: var.setValue(abs(var.value())) return Solution('abs', variables) def __hash__(self): return hash((self.name, tuple(self._variables))) def __len__(self): return len(self._variables) def __iter__(self): return iter(self._variables) def __getitem__(self, k): return self._variables[k] def __str__(self): return self.__repr__() def __repr__(self): return f'Solution({self.name}, [{", ".join([vb.name for vb in self._variables])}])'
en
0.661866
Solution Class Parameters ---------- name : str name of solution variables : list of VarElement family variables which has no duplicate Attributes ---------- name : str name of solution type : str _variables : list of varElement variable array _var_dict : dict key is name of variable, key is variable Examples ---------- Create a Solution which has Integer, Continuous and Binary Variables >>> a = Variable(name='a', lowBound=0, upBound=1, cat='Integer') >>> b = Variable(name='b', lowBound=1, upBound=2, cat='Continuous') >>> c = Variable(name='c', cat='Binary') >>> sol = Solution(name='abc', [a, b, c]) Four arithmetic operations are supported between Solutions or between a Solution and a constant. >>> sol1 = Solution(name='sol1', [a, b]) >>> sol2 = Solution(name='sol2', [a, c]) >>> sol_plus = sol1 + sol2 # (Solution + Solution or Solution + list) >>> sol_minus = sol1 - sol2 # (Solution - Solution or Solution - list) >>> sol_product = sol1 * 2 # (Solution * constant) >>> sol_divide = sol1 / 2 # (Solution / constant) Returns ------- dict: key is name of variable, value is VarElement family or Expression or Const Returns ------- list values of the variables in the Solution Parameters ---------- name: str value: int or float Returns ------- list Variable instances which belong to the Solution Returns ------- Solution Copy of the Solution (call by value) Copy the values of a Solution to itself (call by value) Set the solution values uniformly random Returns ------- bool Whether the solution is feasible or not Guarantee feasibility of the solution Returns ------- float Squared 2-norm of the solution as a vector in Euclid space Returns ------- float 2-norm of the solution as a vector in Euclid space Returns ------- float Inner product between the Solution and another Solution Solution + Solution Solution + list Solutino + scalar Solution - Solution = (Solution + (-Solution)) Solution - list = (Solution + (-list)) Solutino - scalar = (Solution + (-scalar)) Solution * Solution (hadamard product) Solution * list Solution * scalar Solution / list = Solution * (1/list) Solution / scalar = Solution * (1/scalar)
3.558232
4
lemur_digicert/constants.py
opendns/lemur-digicert
12
6619600
<gh_stars>10-100 """These are the digicert certificates required for the lemur plugin.""" DIGICERT_ROOT = """-----<KEY> -----END CERTIFICATE----- """
"""These are the digicert certificates required for the lemur plugin.""" DIGICERT_ROOT = """-----<KEY> -----END CERTIFICATE----- """
en
0.584021
These are the digicert certificates required for the lemur plugin. -----<KEY> -----END CERTIFICATE-----
1.309286
1
singlecellmultiomics/bamProcessing/split_bam_by_cluster.py
zztin/SingleCellMultiOmics
17
6619601
<filename>singlecellmultiomics/bamProcessing/split_bam_by_cluster.py #!/usr/bin/env python ''' DESCRIPTION Split bams into pseudobulks based on metadata FOR HELP python split_bam_by_cluster.py --help AUTHOR: <NAME> (<EMAIL>) LAB: Quantitative Biology Lab (https://www.hubrecht.eu/research-groups/van-oudenaarden-group/) CREATED ON: 2020-01-09 LAST CHANGE: see git log LICENSE: MIT License (see: http://opensource.org/licenses/MIT) ''' import sys, argparse, datetime import pysam import csv import os def reformat_header(header, add_prefix="chr"): new_header = header.to_dict() contigs = new_header['SQ'] new_contigs = [] for contig in contigs: contig['SN'] = ''.join([add_prefix, contig['SN']]) new_contigs.append(contig) new_header['SQ'] = new_contigs return pysam.AlignmentHeader.from_dict(new_header) def scan_bam_get_sampnames(infile, tag="SM"): ''' Read bam file and get sampnames ''' tags = set() with pysam.AlignmentFile(infile, "rb") as inbam: for read in inbam: tags.add(readTag(read, tag)) return(tags) def readTag(read, tag, missing='Missing', defective='Defective'): '''From /hpc/hub_oudenaarden/bdebarbanson/internalTools/modularDemultiplexer/taggedBamFileToCountTable.py''' value=None if tag=='chrom': return str(read.reference_name) if not read.has_tag(tag): return missing else: try: value = read.get_tag(tag) except Exception as e: value = defective return value def main(): parser = argparse.ArgumentParser(description='Split bams into pseudobulks based on metadata') parser.add_argument('-infile', metavar='INFILE', required=True, help='Merged bam file') parser.add_argument('-annotfile', metavar='INFILE', required=True, help='Annotations of merged clusters. Expect first row are colum names (skipped), first column are cell names (should match SM tag in bam) and second column is cluster name, used for bam file outputs') parser.add_argument('-outdir', metavar='OUTDIR', required=True, help='Output directory') parser.add_argument('-tagid', metavar='TAG NAME', required=False, default="SM", help='Tag name to match first column in annot file (default is SM)') parser.add_argument('--annot_no_colnames', action='store_true', help='Set if annot has no column name') parser.add_argument('-mapq', metavar="MAPQ value", required=True, default=40, type=int) parser.add_argument('--add_chr_prefix', action='store_true', help="Add chr prefix to chromosome name") parser.add_argument('--overwrite', action='store_true', help="Does not check if bam files exists, will just write to file") parser.add_argument('--quiet', '-q', action='store_true', help='Suppress some print statements') parser.add_argument('-logfile', '-l', metavar='LOGFILE', default = None, help='Write arguments to logfile') args = parser.parse_args() # store command line arguments for reproducibility CMD_INPUTS = ' '.join(['python'] + sys.argv) # easy printing later # store argparse inputs for reproducibility / debugging purposes args_dic = vars(args) # ARG_INPUTS = ['%s=%s' % (key, val) for key, val in args_dic.iteritems()] # for python2 ARG_INPUTS = ['%s=%s' % (key, val) for key, val in args_dic.items()] # for python3 ARG_INPUTS = ' '.join(ARG_INPUTS) # Print arguments supplied by user if not args.quiet: if args.logfile is not None: sys.stdout = open(args.logfile, "w+") print(datetime.datetime.now().strftime('Code output on %c')) print('Command line inputs:') print(CMD_INPUTS) print ('Argparse variables:') print(ARG_INPUTS) samp_tag_id = args.tagid samp_cname_indx = 0 samp_cluster_indx = 1 # initialize outbam objects bname = os.path.splitext(os.path.basename(args.infile))[0] writebamdic = {} # bam write objs sorteddic={} # output files for sorted bam files unsorteddic={} # tmp files unsorted, will be deleted afterwards # # get sampnames_all by reading the bam file # sampnames_all = scan_bam_get_sampnames(args.infile, tag = samp_tag_id) # sampnames_all are sample names # print(str(len(sampnames_all)) + " sampnames_all found in bam file") # # samp_ignored = set() # read annot file print("Reading annot file...") samp2clstr_dic = {} samps_good = [] clstrs_lst = [] clstrs = set() with open(args.annotfile, "r") as annotfile: jreader = csv.reader(annotfile, delimiter = "\t") if not args.annot_no_colnames: jheader = next(jreader) print("header: %s" % jheader) for row in jreader: samp, clstr = row[samp_cname_indx], row[samp_cluster_indx] if samp not in samp2clstr_dic: samp2clstr_dic[samp] = clstr else: raise Exception('Samp %s is duplicated' % samp) samps_good.append(samp) clstrs_lst.append(clstr) clstrs.add(clstr) print("Reading annot file... DONE") # # Check that every sample is in sampnames_all # print("Checking samps are found in bam...") # for samp in samps_good: # assert samp in sampnames_all # print("Checking samps are found in bam... DONE") # check that no output bam files will clash with existing bams, exit if no overwrite ooption if not args.overwrite: for clstr in clstrs: checktmppath = os.path.join(args.outdir, '.'.join([bname, clstr, "unsorted", "bam"])) checkoutpath = os.path.join(args.outdir, '.'.join([bname, clstr, "sorted", "bam"])) assert not os.path.exists(checktmppath) assert not os.path.exists(checkoutpath) dup_count = 0 assign_count = 0 unassign_count = 0 print("Splitting bams into clusters ...") with pysam.AlignmentFile(args.infile, "rb") as inbam: if args.add_chr_prefix: new_header = reformat_header(inbam.header, add_prefix = "chr") for clstr in clstrs: tmppath = os.path.join(args.outdir, '.'.join([bname, clstr, "unsorted", "bam"])) outpath = os.path.join(args.outdir, '.'.join([bname, clstr, "sorted", "bam"])) unsorteddic[clstr] = tmppath sorteddic[clstr] = outpath if not args.add_chr_prefix: writebamdic[clstr] = pysam.AlignmentFile(tmppath, "wb", template = inbam) else: writebamdic[clstr] = pysam.AlignmentFile(tmppath, "wb", header = new_header) for total_count, read in enumerate(inbam): if read.is_duplicate: dup_count += 1 continue readsamp = readTag(read, samp_tag_id) if readsamp in samp2clstr_dic: # write to outpuet clstr = samp2clstr_dic[readsamp] writebamdic[clstr].write(read) assign_count += 1 else: unassign_count += 1 # close bam files, sort, index and cleanup for clstr in clstrs: writebamdic[clstr].close() pysam.sort('-o', sorteddic[clstr], unsorteddic[clstr]) pysam.index(sorteddic[clstr]) # clean up for clstr in clstrs: os.remove(unsorteddic[clstr]) print("Splitting bams into clusters ... DONE") # Print arguments supplied by user if not args.quiet: if args.logfile is not None: sys.stdout = open(args.logfile, "w+") print(datetime.datetime.now().strftime('Code finished on: %c')) if __name__ == '__main__': main()
<filename>singlecellmultiomics/bamProcessing/split_bam_by_cluster.py #!/usr/bin/env python ''' DESCRIPTION Split bams into pseudobulks based on metadata FOR HELP python split_bam_by_cluster.py --help AUTHOR: <NAME> (<EMAIL>) LAB: Quantitative Biology Lab (https://www.hubrecht.eu/research-groups/van-oudenaarden-group/) CREATED ON: 2020-01-09 LAST CHANGE: see git log LICENSE: MIT License (see: http://opensource.org/licenses/MIT) ''' import sys, argparse, datetime import pysam import csv import os def reformat_header(header, add_prefix="chr"): new_header = header.to_dict() contigs = new_header['SQ'] new_contigs = [] for contig in contigs: contig['SN'] = ''.join([add_prefix, contig['SN']]) new_contigs.append(contig) new_header['SQ'] = new_contigs return pysam.AlignmentHeader.from_dict(new_header) def scan_bam_get_sampnames(infile, tag="SM"): ''' Read bam file and get sampnames ''' tags = set() with pysam.AlignmentFile(infile, "rb") as inbam: for read in inbam: tags.add(readTag(read, tag)) return(tags) def readTag(read, tag, missing='Missing', defective='Defective'): '''From /hpc/hub_oudenaarden/bdebarbanson/internalTools/modularDemultiplexer/taggedBamFileToCountTable.py''' value=None if tag=='chrom': return str(read.reference_name) if not read.has_tag(tag): return missing else: try: value = read.get_tag(tag) except Exception as e: value = defective return value def main(): parser = argparse.ArgumentParser(description='Split bams into pseudobulks based on metadata') parser.add_argument('-infile', metavar='INFILE', required=True, help='Merged bam file') parser.add_argument('-annotfile', metavar='INFILE', required=True, help='Annotations of merged clusters. Expect first row are colum names (skipped), first column are cell names (should match SM tag in bam) and second column is cluster name, used for bam file outputs') parser.add_argument('-outdir', metavar='OUTDIR', required=True, help='Output directory') parser.add_argument('-tagid', metavar='TAG NAME', required=False, default="SM", help='Tag name to match first column in annot file (default is SM)') parser.add_argument('--annot_no_colnames', action='store_true', help='Set if annot has no column name') parser.add_argument('-mapq', metavar="MAPQ value", required=True, default=40, type=int) parser.add_argument('--add_chr_prefix', action='store_true', help="Add chr prefix to chromosome name") parser.add_argument('--overwrite', action='store_true', help="Does not check if bam files exists, will just write to file") parser.add_argument('--quiet', '-q', action='store_true', help='Suppress some print statements') parser.add_argument('-logfile', '-l', metavar='LOGFILE', default = None, help='Write arguments to logfile') args = parser.parse_args() # store command line arguments for reproducibility CMD_INPUTS = ' '.join(['python'] + sys.argv) # easy printing later # store argparse inputs for reproducibility / debugging purposes args_dic = vars(args) # ARG_INPUTS = ['%s=%s' % (key, val) for key, val in args_dic.iteritems()] # for python2 ARG_INPUTS = ['%s=%s' % (key, val) for key, val in args_dic.items()] # for python3 ARG_INPUTS = ' '.join(ARG_INPUTS) # Print arguments supplied by user if not args.quiet: if args.logfile is not None: sys.stdout = open(args.logfile, "w+") print(datetime.datetime.now().strftime('Code output on %c')) print('Command line inputs:') print(CMD_INPUTS) print ('Argparse variables:') print(ARG_INPUTS) samp_tag_id = args.tagid samp_cname_indx = 0 samp_cluster_indx = 1 # initialize outbam objects bname = os.path.splitext(os.path.basename(args.infile))[0] writebamdic = {} # bam write objs sorteddic={} # output files for sorted bam files unsorteddic={} # tmp files unsorted, will be deleted afterwards # # get sampnames_all by reading the bam file # sampnames_all = scan_bam_get_sampnames(args.infile, tag = samp_tag_id) # sampnames_all are sample names # print(str(len(sampnames_all)) + " sampnames_all found in bam file") # # samp_ignored = set() # read annot file print("Reading annot file...") samp2clstr_dic = {} samps_good = [] clstrs_lst = [] clstrs = set() with open(args.annotfile, "r") as annotfile: jreader = csv.reader(annotfile, delimiter = "\t") if not args.annot_no_colnames: jheader = next(jreader) print("header: %s" % jheader) for row in jreader: samp, clstr = row[samp_cname_indx], row[samp_cluster_indx] if samp not in samp2clstr_dic: samp2clstr_dic[samp] = clstr else: raise Exception('Samp %s is duplicated' % samp) samps_good.append(samp) clstrs_lst.append(clstr) clstrs.add(clstr) print("Reading annot file... DONE") # # Check that every sample is in sampnames_all # print("Checking samps are found in bam...") # for samp in samps_good: # assert samp in sampnames_all # print("Checking samps are found in bam... DONE") # check that no output bam files will clash with existing bams, exit if no overwrite ooption if not args.overwrite: for clstr in clstrs: checktmppath = os.path.join(args.outdir, '.'.join([bname, clstr, "unsorted", "bam"])) checkoutpath = os.path.join(args.outdir, '.'.join([bname, clstr, "sorted", "bam"])) assert not os.path.exists(checktmppath) assert not os.path.exists(checkoutpath) dup_count = 0 assign_count = 0 unassign_count = 0 print("Splitting bams into clusters ...") with pysam.AlignmentFile(args.infile, "rb") as inbam: if args.add_chr_prefix: new_header = reformat_header(inbam.header, add_prefix = "chr") for clstr in clstrs: tmppath = os.path.join(args.outdir, '.'.join([bname, clstr, "unsorted", "bam"])) outpath = os.path.join(args.outdir, '.'.join([bname, clstr, "sorted", "bam"])) unsorteddic[clstr] = tmppath sorteddic[clstr] = outpath if not args.add_chr_prefix: writebamdic[clstr] = pysam.AlignmentFile(tmppath, "wb", template = inbam) else: writebamdic[clstr] = pysam.AlignmentFile(tmppath, "wb", header = new_header) for total_count, read in enumerate(inbam): if read.is_duplicate: dup_count += 1 continue readsamp = readTag(read, samp_tag_id) if readsamp in samp2clstr_dic: # write to outpuet clstr = samp2clstr_dic[readsamp] writebamdic[clstr].write(read) assign_count += 1 else: unassign_count += 1 # close bam files, sort, index and cleanup for clstr in clstrs: writebamdic[clstr].close() pysam.sort('-o', sorteddic[clstr], unsorteddic[clstr]) pysam.index(sorteddic[clstr]) # clean up for clstr in clstrs: os.remove(unsorteddic[clstr]) print("Splitting bams into clusters ... DONE") # Print arguments supplied by user if not args.quiet: if args.logfile is not None: sys.stdout = open(args.logfile, "w+") print(datetime.datetime.now().strftime('Code finished on: %c')) if __name__ == '__main__': main()
en
0.645299
#!/usr/bin/env python DESCRIPTION Split bams into pseudobulks based on metadata FOR HELP python split_bam_by_cluster.py --help AUTHOR: <NAME> (<EMAIL>) LAB: Quantitative Biology Lab (https://www.hubrecht.eu/research-groups/van-oudenaarden-group/) CREATED ON: 2020-01-09 LAST CHANGE: see git log LICENSE: MIT License (see: http://opensource.org/licenses/MIT) Read bam file and get sampnames From /hpc/hub_oudenaarden/bdebarbanson/internalTools/modularDemultiplexer/taggedBamFileToCountTable.py # store command line arguments for reproducibility # easy printing later # store argparse inputs for reproducibility / debugging purposes # ARG_INPUTS = ['%s=%s' % (key, val) for key, val in args_dic.iteritems()] # for python2 # for python3 # Print arguments supplied by user # initialize outbam objects # bam write objs # output files for sorted bam files # tmp files unsorted, will be deleted afterwards # # get sampnames_all by reading the bam file # sampnames_all = scan_bam_get_sampnames(args.infile, tag = samp_tag_id) # sampnames_all are sample names # print(str(len(sampnames_all)) + " sampnames_all found in bam file") # # samp_ignored = set() # read annot file # # Check that every sample is in sampnames_all # print("Checking samps are found in bam...") # for samp in samps_good: # assert samp in sampnames_all # print("Checking samps are found in bam... DONE") # check that no output bam files will clash with existing bams, exit if no overwrite ooption # write to outpuet # close bam files, sort, index and cleanup # clean up # Print arguments supplied by user
2.662548
3
week4_programs/rtr2_change_buffer_take2.py
morganoh/Python_with_Kirk
0
6619602
<filename>week4_programs/rtr2_change_buffer_take2.py #!/usr/bin/env python """ use paramiko to send cmd to RTR2 """ import paramiko import time from getpass import getpass MAX_BUFFER = 65535 def prepare_buffer(rtr2): if rtr2.recv_ready(): # print 'buffer is full' return rtr2.recv(MAX_BUFFER) def disable_paging(rtr2): cmd = 'terminal length 0 \n' rtr2.send(cmd) time.sleep(1) prepare_buffer(rtr2) def send_cmd(rtr2, cmd): #print cmd rtr2.send(cmd) time.sleep(2) if rtr2.recv_ready(): return rtr2.recv(MAX_BUFFER) else: print 'buffer is empty' def main(): """ set up paramiko cxn and send the cmd """ ip_addr = '172.16.17.32' port = 8022 username = 'pyclass' password = <PASSWORD>() remote_conn_pre = paramiko.SSHClient() remote_conn_pre.load_system_host_keys() remote_conn_pre.connect(ip_addr, port=port, username=username, password=password, look_for_keys=False, allow_agent=False) rtr2 = remote_conn_pre.invoke_shell() prepare_buffer(rtr2) disable_paging(rtr2) cmd = 'show run | inc logging \n' output = send_cmd(rtr2, cmd) print output cmd = 'conf t \n' send_cmd(rtr2, cmd) cmd = 'logging buffered 30000 \n' send_cmd(rtr2, cmd) cmd = 'exit \n' send_cmd(rtr2, cmd) cmd = 'wr \n' send_cmd(rtr2, cmd) cmd = 'show run | inc logging \n' output = send_cmd(rtr2, cmd) print output if __name__ == "__main__": main()
<filename>week4_programs/rtr2_change_buffer_take2.py #!/usr/bin/env python """ use paramiko to send cmd to RTR2 """ import paramiko import time from getpass import getpass MAX_BUFFER = 65535 def prepare_buffer(rtr2): if rtr2.recv_ready(): # print 'buffer is full' return rtr2.recv(MAX_BUFFER) def disable_paging(rtr2): cmd = 'terminal length 0 \n' rtr2.send(cmd) time.sleep(1) prepare_buffer(rtr2) def send_cmd(rtr2, cmd): #print cmd rtr2.send(cmd) time.sleep(2) if rtr2.recv_ready(): return rtr2.recv(MAX_BUFFER) else: print 'buffer is empty' def main(): """ set up paramiko cxn and send the cmd """ ip_addr = '172.16.17.32' port = 8022 username = 'pyclass' password = <PASSWORD>() remote_conn_pre = paramiko.SSHClient() remote_conn_pre.load_system_host_keys() remote_conn_pre.connect(ip_addr, port=port, username=username, password=password, look_for_keys=False, allow_agent=False) rtr2 = remote_conn_pre.invoke_shell() prepare_buffer(rtr2) disable_paging(rtr2) cmd = 'show run | inc logging \n' output = send_cmd(rtr2, cmd) print output cmd = 'conf t \n' send_cmd(rtr2, cmd) cmd = 'logging buffered 30000 \n' send_cmd(rtr2, cmd) cmd = 'exit \n' send_cmd(rtr2, cmd) cmd = 'wr \n' send_cmd(rtr2, cmd) cmd = 'show run | inc logging \n' output = send_cmd(rtr2, cmd) print output if __name__ == "__main__": main()
en
0.538515
#!/usr/bin/env python use paramiko to send cmd to RTR2 # print 'buffer is full' #print cmd set up paramiko cxn and send the cmd
3.005764
3
pyconde/proposals/validators.py
EuroPython/djep
5
6619603
import re from django.core import validators as core_validators RE_DOUBLE_WS = re.compile(r'\s\s+') class MaxWordsValidator(core_validators.BaseValidator): message = "Dieses Feld darf nicht mehr als %(limit_value)s Worte enthalten" def compare(self, value, limit): normalized_value = RE_DOUBLE_WS.subn(' ', value)[0] num_words = len(normalized_value.split(" ")) return num_words > limit class MaxLengthValidator(core_validators.MaxLengthValidator): message = "Dieses Feld darf nicht mehr als %(limit_value)s Zeichen enthalten"
import re from django.core import validators as core_validators RE_DOUBLE_WS = re.compile(r'\s\s+') class MaxWordsValidator(core_validators.BaseValidator): message = "Dieses Feld darf nicht mehr als %(limit_value)s Worte enthalten" def compare(self, value, limit): normalized_value = RE_DOUBLE_WS.subn(' ', value)[0] num_words = len(normalized_value.split(" ")) return num_words > limit class MaxLengthValidator(core_validators.MaxLengthValidator): message = "Dieses Feld darf nicht mehr als %(limit_value)s Zeichen enthalten"
none
1
2.564721
3
Code/FlexSpec/UserInterface/SlitBokeh.py
dxwayne/SASFS1
0
6619604
<reponame>dxwayne/SASFS1 #!/usr/bin/env python3 # -*- coding: utf-8 -*- # bokeh serve ./SlitBokeh.py # (wg-python-fix-pdbrc) ### HEREHEREHERE import os import optparse import sys import io import re import json from Display import fakedisplay from bokeh.events import ButtonClick from bokeh.io import curdoc from bokeh.layouts import column, row, Spacer from bokeh.models import ColumnDataSource, Div, Slider, TextInput, Button from bokeh.models import RadioGroup from bokeh.models import Select #from bokeh.models.widgets import Tabs, Panel ############################################################################# # # /home/git/external/xxx.SAS_NA1_3D_Spectrograph/Code/NA1Focus/SlitBokeh.py # #emacs helpers # (insert (format "\n# %s " (buffer-file-name))) # # (set-input-method 'TeX' t) # (toggle-input-method) # # (wg-astroconda3-pdb) # CONDA Python3 # # (wg-python-fix-pdbrc) # PDB DASH DEBUG end-comments # # (ediff-current-file) # (find-file-other-frame "./.pdbrc") # (setq mypdbcmd (concat (buffer-file-name) "<args...>")) # (progn (wg-python-fix-pdbrc) (pdb mypdbcmd)) # # (wg-astroconda-pdb) # IRAF27 # # (set-background-color "light blue") # # https://docs.bokeh.org/en/latest/docs/user_guide/interaction/widgets.html#paragraph # # # (wg-python-toc) # ############################################################################# __doc__ = """ /home/git/external/xxx.SAS_NA1_3D_Spectrograph/Code/NA1Focus/SlitBokeh.py [options] files... This class displays a rate field, a state field (on/off) and a small error text field. A little documentation help. (wg-browser "https://docs.bokeh.org/en/latest/docs/reference.html#refguide") Slit is a tiny class, that should be part of every Arduino, giving the user the ability to start a LED blinking. The blink pattern is on for a duration, off for a duration, and a pause between the on/off states. I can make a short pulse every 10 seconds or every 1 second. (The off specification). Slit Description: The Flex Spec Ovio holder has one position Dark. The home position is set to that Kzin Ring Assy. """ __author__ = '<NAME>' __version__ = '0.1' __all__ = ['BokehOVIOSlit','BokehOVIOSlitException'] # list of quoted items to export # (wg-python-class "BokehOVIOSlit") ############################################################################## # BokehOVIOSlitException # ############################################################################## class BokehOVIOSlitException(Exception): """Special exception to allow differentiated capture of exceptions""" def __init__(self,message,errors=None): super(BokehOVIOSlitException,self).__init__("FlexSlit "+ message) self.errors = errors @staticmethod def __format__(e): return f" FlexSlit: {e.__str__()}\n" # BokehOVIOSlitException ############################################################################## # BokehOVIOSlit # ############################################################################## class BokehOVIOSlit(object): """ A small class to blink the led, with varying rate """ # FAKE up some enums. brre = re.compile(r'\n') # used to convert newline to <br/> ovioslittuples = [ ( "1" , "10" ), ( "2" , "20" ), ( "3" , "30" ), ( "4" , "40" ), ( "5" , "50" ), ( "6" , "70" ), ( "7" , "100" ), ( "8" , "150" ), ( "9" , "200" ), ( "10" , "300" ), ( "11" , "500" ), # masked out in FlexSpec "Dark" ( "12" , "700" ) ] oviodropdowns = [ "10" , "20" , "30" , "40" , "50" , "70" , "100", "150", "200", "300", "Shutter", "700" ] #__slots__ = [''] # add legal instance variables # (setq properties `("" "")) def __init__(self, flexname : str = "Default", name : str = "OvioSlit", display = fakedisplay, width=200): # BokehOVIOSlit::__init__() """Initialize this class.""" #super().__init__() # (wg-python-property-variables) self.display = display self.flexname = flexname # the name of the instrument for this instance self.name = name # the name of the device in this instrument self.wwidth = width # display width for its Bokeh widgets self.slit = "20" # initial condition self.state = 'undefined' # haven't started yet self.lamp = 0 # the illumination lamp associated self.validp = False # wake up in false position self.spacer = Spacer(width=self.wwidth, height=5, background='black') self.slitlamp = RadioGroup(labels=[f"Illuminator Off", f"Illuminator On" ], height=50, width=self.wwidth, active=0, orientation='horizontal') self.slitchoices = Select(title=f"OVIO Slits",value='20',options=self.oviodropdowns, width=self.wwidth) self.slitchoices .on_change('value',lambda attr, old, new: self.update_dropdown (attr, old, new)) self.slitlamp .on_change('active', lambda attr, old, new: self.radio_handler (attr, old, new)) self.send_state() # set the initial state. ### BokehOVIOSlit.__init__() def radio_handler(self,attr, old, new): # BokehFlexBlinky::radio_handler() """Do something about the blink via an event lambda""" self.lamp = new # self.blink_group.active if(self.lamp not in [0,1]): self.lamp = 3 self.send_state() ### BokehOVIOSlit.radio_handler() def update_dropdown(self,attr,old,new): # BokehRoboFocuser::update_button_in() """update_debugbtn Button via an event lambda""" self.slit = new # self.slitchoices.value self.send_state() # display(f"{self.slit}") ### BokehOVIOSlit.display() def send_state(self): # BokehOVIOSlit::send_state() """Several ways to send things""" devstate = dict( [ ( "slit" , self.slit), # ascii text of the slit width. ( "illuminator" , self.lamp) ]) slitcmd = dict([("Process", devstate), ("Receipt" , 0)]) slitcmd['Receipt'] = 1 # set the receipt as desired d2 = dict([(f"{self.name}", slitcmd)]) d3 = dict([(f"{self.flexname}", d2)]) jdict = json.dumps(d3) #self.display.display(f'{{ {jdict} , "returnreceipt" : 1 }}') self.display.display(f'{jdict}') ### BokehOVIOSlit.send_state() def dumper(self,ddict): # BokehOVIOSlit::dumper() """Given a dictionary, display the results""" for fsname,payload in ddict.items(): print(f"FS1 Name: {fsname}") for command, cmdkey in payload.items(): print(f" cmd: {command}") for var,value in cmdkey.items(): print(f" {cmd} {value}") return self # BokehOVIOSlit.dumper() def layout(self): # BokehOVIOSlit::layout() """Get the layout in gear""" return(row ( column ( self.slitchoices, self.slitlamp ) )) ### BokehOVIOSlit.layout() def debug(self,msg="",skip=[],os=sys.stderr): # BokehOVIOSlit::debug() """Help with momentary debugging, file to fit. msg -- special tag for this call skip -- the member variables to ignore os -- output stream: may be IOStream etc. """ import pprint print("BokehOVIOSlit - %s " % msg, file=os) for key,value in self.__dict__.items(): if(key in skip): continue print(f'{key:20s} =',file=os,end='') pprint.pprint(value,stream=os,indent=4) return self ### BokehOVIOSlit.debug() __BokehOVIOSlit_debug = debug # really preserve our debug name if we're inherited # (wg-python-properties properties) # class BokehOVIOSlit ############################################################################## # Main # Regression Tests ############################################################################## # HEREHEREHERE if(0): opts = optparse.OptionParser(usage="%prog "+__doc__) opts.add_option("-v", "--verbose", action="store_true", dest="verboseflag", default=False, help="<bool> be verbose about work.") (options, args) = opts.parse_args() curdoc().theme = 'dark_minimal' curdoc().title = "Slit1 Test" slits = BokehOVIOSlit("FlexSpec_Rodda") curdoc().add_root(row(slits.layout()))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # bokeh serve ./SlitBokeh.py # (wg-python-fix-pdbrc) ### HEREHEREHERE import os import optparse import sys import io import re import json from Display import fakedisplay from bokeh.events import ButtonClick from bokeh.io import curdoc from bokeh.layouts import column, row, Spacer from bokeh.models import ColumnDataSource, Div, Slider, TextInput, Button from bokeh.models import RadioGroup from bokeh.models import Select #from bokeh.models.widgets import Tabs, Panel ############################################################################# # # /home/git/external/xxx.SAS_NA1_3D_Spectrograph/Code/NA1Focus/SlitBokeh.py # #emacs helpers # (insert (format "\n# %s " (buffer-file-name))) # # (set-input-method 'TeX' t) # (toggle-input-method) # # (wg-astroconda3-pdb) # CONDA Python3 # # (wg-python-fix-pdbrc) # PDB DASH DEBUG end-comments # # (ediff-current-file) # (find-file-other-frame "./.pdbrc") # (setq mypdbcmd (concat (buffer-file-name) "<args...>")) # (progn (wg-python-fix-pdbrc) (pdb mypdbcmd)) # # (wg-astroconda-pdb) # IRAF27 # # (set-background-color "light blue") # # https://docs.bokeh.org/en/latest/docs/user_guide/interaction/widgets.html#paragraph # # # (wg-python-toc) # ############################################################################# __doc__ = """ /home/git/external/xxx.SAS_NA1_3D_Spectrograph/Code/NA1Focus/SlitBokeh.py [options] files... This class displays a rate field, a state field (on/off) and a small error text field. A little documentation help. (wg-browser "https://docs.bokeh.org/en/latest/docs/reference.html#refguide") Slit is a tiny class, that should be part of every Arduino, giving the user the ability to start a LED blinking. The blink pattern is on for a duration, off for a duration, and a pause between the on/off states. I can make a short pulse every 10 seconds or every 1 second. (The off specification). Slit Description: The Flex Spec Ovio holder has one position Dark. The home position is set to that Kzin Ring Assy. """ __author__ = '<NAME>' __version__ = '0.1' __all__ = ['BokehOVIOSlit','BokehOVIOSlitException'] # list of quoted items to export # (wg-python-class "BokehOVIOSlit") ############################################################################## # BokehOVIOSlitException # ############################################################################## class BokehOVIOSlitException(Exception): """Special exception to allow differentiated capture of exceptions""" def __init__(self,message,errors=None): super(BokehOVIOSlitException,self).__init__("FlexSlit "+ message) self.errors = errors @staticmethod def __format__(e): return f" FlexSlit: {e.__str__()}\n" # BokehOVIOSlitException ############################################################################## # BokehOVIOSlit # ############################################################################## class BokehOVIOSlit(object): """ A small class to blink the led, with varying rate """ # FAKE up some enums. brre = re.compile(r'\n') # used to convert newline to <br/> ovioslittuples = [ ( "1" , "10" ), ( "2" , "20" ), ( "3" , "30" ), ( "4" , "40" ), ( "5" , "50" ), ( "6" , "70" ), ( "7" , "100" ), ( "8" , "150" ), ( "9" , "200" ), ( "10" , "300" ), ( "11" , "500" ), # masked out in FlexSpec "Dark" ( "12" , "700" ) ] oviodropdowns = [ "10" , "20" , "30" , "40" , "50" , "70" , "100", "150", "200", "300", "Shutter", "700" ] #__slots__ = [''] # add legal instance variables # (setq properties `("" "")) def __init__(self, flexname : str = "Default", name : str = "OvioSlit", display = fakedisplay, width=200): # BokehOVIOSlit::__init__() """Initialize this class.""" #super().__init__() # (wg-python-property-variables) self.display = display self.flexname = flexname # the name of the instrument for this instance self.name = name # the name of the device in this instrument self.wwidth = width # display width for its Bokeh widgets self.slit = "20" # initial condition self.state = 'undefined' # haven't started yet self.lamp = 0 # the illumination lamp associated self.validp = False # wake up in false position self.spacer = Spacer(width=self.wwidth, height=5, background='black') self.slitlamp = RadioGroup(labels=[f"Illuminator Off", f"Illuminator On" ], height=50, width=self.wwidth, active=0, orientation='horizontal') self.slitchoices = Select(title=f"OVIO Slits",value='20',options=self.oviodropdowns, width=self.wwidth) self.slitchoices .on_change('value',lambda attr, old, new: self.update_dropdown (attr, old, new)) self.slitlamp .on_change('active', lambda attr, old, new: self.radio_handler (attr, old, new)) self.send_state() # set the initial state. ### BokehOVIOSlit.__init__() def radio_handler(self,attr, old, new): # BokehFlexBlinky::radio_handler() """Do something about the blink via an event lambda""" self.lamp = new # self.blink_group.active if(self.lamp not in [0,1]): self.lamp = 3 self.send_state() ### BokehOVIOSlit.radio_handler() def update_dropdown(self,attr,old,new): # BokehRoboFocuser::update_button_in() """update_debugbtn Button via an event lambda""" self.slit = new # self.slitchoices.value self.send_state() # display(f"{self.slit}") ### BokehOVIOSlit.display() def send_state(self): # BokehOVIOSlit::send_state() """Several ways to send things""" devstate = dict( [ ( "slit" , self.slit), # ascii text of the slit width. ( "illuminator" , self.lamp) ]) slitcmd = dict([("Process", devstate), ("Receipt" , 0)]) slitcmd['Receipt'] = 1 # set the receipt as desired d2 = dict([(f"{self.name}", slitcmd)]) d3 = dict([(f"{self.flexname}", d2)]) jdict = json.dumps(d3) #self.display.display(f'{{ {jdict} , "returnreceipt" : 1 }}') self.display.display(f'{jdict}') ### BokehOVIOSlit.send_state() def dumper(self,ddict): # BokehOVIOSlit::dumper() """Given a dictionary, display the results""" for fsname,payload in ddict.items(): print(f"FS1 Name: {fsname}") for command, cmdkey in payload.items(): print(f" cmd: {command}") for var,value in cmdkey.items(): print(f" {cmd} {value}") return self # BokehOVIOSlit.dumper() def layout(self): # BokehOVIOSlit::layout() """Get the layout in gear""" return(row ( column ( self.slitchoices, self.slitlamp ) )) ### BokehOVIOSlit.layout() def debug(self,msg="",skip=[],os=sys.stderr): # BokehOVIOSlit::debug() """Help with momentary debugging, file to fit. msg -- special tag for this call skip -- the member variables to ignore os -- output stream: may be IOStream etc. """ import pprint print("BokehOVIOSlit - %s " % msg, file=os) for key,value in self.__dict__.items(): if(key in skip): continue print(f'{key:20s} =',file=os,end='') pprint.pprint(value,stream=os,indent=4) return self ### BokehOVIOSlit.debug() __BokehOVIOSlit_debug = debug # really preserve our debug name if we're inherited # (wg-python-properties properties) # class BokehOVIOSlit ############################################################################## # Main # Regression Tests ############################################################################## # HEREHEREHERE if(0): opts = optparse.OptionParser(usage="%prog "+__doc__) opts.add_option("-v", "--verbose", action="store_true", dest="verboseflag", default=False, help="<bool> be verbose about work.") (options, args) = opts.parse_args() curdoc().theme = 'dark_minimal' curdoc().title = "Slit1 Test" slits = BokehOVIOSlit("FlexSpec_Rodda") curdoc().add_root(row(slits.layout()))
en
0.396373
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # bokeh serve ./SlitBokeh.py # (wg-python-fix-pdbrc) ### HEREHEREHERE #from bokeh.models.widgets import Tabs, Panel ############################################################################# # # /home/git/external/xxx.SAS_NA1_3D_Spectrograph/Code/NA1Focus/SlitBokeh.py # #emacs helpers # (insert (format "\n# %s " (buffer-file-name))) # # (set-input-method 'TeX' t) # (toggle-input-method) # # (wg-astroconda3-pdb) # CONDA Python3 # # (wg-python-fix-pdbrc) # PDB DASH DEBUG end-comments # # (ediff-current-file) # (find-file-other-frame "./.pdbrc") # (setq mypdbcmd (concat (buffer-file-name) "<args...>")) # (progn (wg-python-fix-pdbrc) (pdb mypdbcmd)) # # (wg-astroconda-pdb) # IRAF27 # # (set-background-color "light blue") # # https://docs.bokeh.org/en/latest/docs/user_guide/interaction/widgets.html#paragraph # # # (wg-python-toc) # ############################################################################# /home/git/external/xxx.SAS_NA1_3D_Spectrograph/Code/NA1Focus/SlitBokeh.py [options] files... This class displays a rate field, a state field (on/off) and a small error text field. A little documentation help. (wg-browser "https://docs.bokeh.org/en/latest/docs/reference.html#refguide") Slit is a tiny class, that should be part of every Arduino, giving the user the ability to start a LED blinking. The blink pattern is on for a duration, off for a duration, and a pause between the on/off states. I can make a short pulse every 10 seconds or every 1 second. (The off specification). Slit Description: The Flex Spec Ovio holder has one position Dark. The home position is set to that Kzin Ring Assy. # list of quoted items to export # (wg-python-class "BokehOVIOSlit") ############################################################################## # BokehOVIOSlitException # ############################################################################## Special exception to allow differentiated capture of exceptions # BokehOVIOSlitException ############################################################################## # BokehOVIOSlit # ############################################################################## A small class to blink the led, with varying rate # FAKE up some enums. # used to convert newline to <br/> # masked out in FlexSpec "Dark" #__slots__ = [''] # add legal instance variables # (setq properties `("" "")) # BokehOVIOSlit::__init__() Initialize this class. #super().__init__() # (wg-python-property-variables) # the name of the instrument for this instance # the name of the device in this instrument # display width for its Bokeh widgets # initial condition # haven't started yet # the illumination lamp associated # wake up in false position # set the initial state. ### BokehOVIOSlit.__init__() # BokehFlexBlinky::radio_handler() Do something about the blink via an event lambda # self.blink_group.active ### BokehOVIOSlit.radio_handler() # BokehRoboFocuser::update_button_in() update_debugbtn Button via an event lambda # self.slitchoices.value # display(f"{self.slit}") ### BokehOVIOSlit.display() # BokehOVIOSlit::send_state() Several ways to send things # ascii text of the slit width. # set the receipt as desired #self.display.display(f'{{ {jdict} , "returnreceipt" : 1 }}') ### BokehOVIOSlit.send_state() # BokehOVIOSlit::dumper() Given a dictionary, display the results # BokehOVIOSlit.dumper() # BokehOVIOSlit::layout() Get the layout in gear ### BokehOVIOSlit.layout() # BokehOVIOSlit::debug() Help with momentary debugging, file to fit. msg -- special tag for this call skip -- the member variables to ignore os -- output stream: may be IOStream etc. ### BokehOVIOSlit.debug() # really preserve our debug name if we're inherited # (wg-python-properties properties) # class BokehOVIOSlit ############################################################################## # Main # Regression Tests ############################################################################## # HEREHEREHERE
2.123131
2
capirca/lib/__init__.py
qwe19272375/capirca
604
6619605
"""Libraries for Capirca."""
"""Libraries for Capirca."""
en
0.649002
Libraries for Capirca.
1.069599
1
IM_test/app_lib/caseReport.py
joakimzhang/qa_study
0
6619606
<reponame>joakimzhang/qa_study #!coding:utf-8 import jinja2 import os import socket import globalVariable import sendMail template = jinja2.Template(""" <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html lang='en'> <head xmlns="http://www.w3.org/1999/xhtml"> <meta charset='utf-8' /> <title>Test results</title> <style> .title { text-align:center; } .report { font-family:"Trebuchet MS", Arial, Helvetica, sans-serif; width:100%; border-collapse:collapse; } .report td, #report th { font-size:1em; border:1px solid #98bf21; padding:3px 7px 2px 7px; } .report th { font-size:1.1em; text-align:left; padding-top:5px; padding-bottom:4px; background-color:#97CBFF; color:#ffffff; } .report tr.alt td { color:#000000; background-color:#EAF2D3; } caption { font-size:25px; font-weight: bold } </style> </head> <body> <h3 class='title'> App Automation Report </h3> <table id="testruns" class="report"> <thead> <tr> <th style="width:10em">Timestamp</th> <th style="width:30%">Test</th> <th>Exit status</th> <th>Notes</th> <th style="width:5em">Duration</th> </tr> </thead> <tbody> {% for run in runs %} <tr bgcolor="{{run.bg_color()}}"> <td>{{run.timestamp}}</td> <td>{{run.test_name}}</td> <td> {% if run.exit_status == 'PASS(memory check)' %} <a href = {{run.img_url()}}>{{run.exit_status}}</a> {% else %} {{run.exit_status}} {% if run.exit_status not in ("", "PASS", "PASS(memory check)") %} - <span>{{run.failure_reason|e}}</span> {% endif %} {% endif %} </td> <td>{{run.notes|e}}</td> <td>{{run.duration}}</td> </tr> {% endfor %} </tbody> </table> </body> </html> """) class CaseInfo(): def __init__(self, *args, **kwargs): self.__dict__.update(kwargs) def bg_color(self): if self.exit_status == 'PASS' or self.exit_status == 'PASS(memory check)': return "#edffe6" elif self.exit_status == 'FAIL': return "#ff9797" # Red: Possible system-under-test failure def img_url(self): if socket.gethostbyname(socket.gethostname()) != globalVariable.APACHE_SERVER: img_url = 'http://%s/not_exist.jpg'%globalVariable.APACHE_SERVER else: img_url = os.path.join('http://%s'%globalVariable.APACHE_SERVER, globalVariable.IMAGE_DICT[self.test_name]) img_url = img_url.replace('\\', '/') return img_url class CaseFactory(object): cases = [] def __init__(self, *args, **kwargs): self.cases.append(CaseInfo(*args, **kwargs)) @classmethod def create_html(cls, html = 'report.html'): with open(html, "w+") as f: f.write(template.render(name = 'app', runs = cls.cases)) @classmethod def send_report(cls, report_time): cls.create_html() with open('report.html', 'r') as f: content = f.read() inst = sendMail.SendMail() inst.send_html_mail('App Automation Report at %s'%report_time, content) if __name__ == '__main__': CaseFactory(timestamp = 1, test_name = 'test1', exit_status = 'PASS', failure_reason = 'success', duration = '30', note = '') CaseFactory(timestamp = 2, test_name = 'test2', exit_status = 'FAIL', failure_reason = 'not match', duration = '28', note = '') CaseFactory.create_html()
#!coding:utf-8 import jinja2 import os import socket import globalVariable import sendMail template = jinja2.Template(""" <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html lang='en'> <head xmlns="http://www.w3.org/1999/xhtml"> <meta charset='utf-8' /> <title>Test results</title> <style> .title { text-align:center; } .report { font-family:"Trebuchet MS", Arial, Helvetica, sans-serif; width:100%; border-collapse:collapse; } .report td, #report th { font-size:1em; border:1px solid #98bf21; padding:3px 7px 2px 7px; } .report th { font-size:1.1em; text-align:left; padding-top:5px; padding-bottom:4px; background-color:#97CBFF; color:#ffffff; } .report tr.alt td { color:#000000; background-color:#EAF2D3; } caption { font-size:25px; font-weight: bold } </style> </head> <body> <h3 class='title'> App Automation Report </h3> <table id="testruns" class="report"> <thead> <tr> <th style="width:10em">Timestamp</th> <th style="width:30%">Test</th> <th>Exit status</th> <th>Notes</th> <th style="width:5em">Duration</th> </tr> </thead> <tbody> {% for run in runs %} <tr bgcolor="{{run.bg_color()}}"> <td>{{run.timestamp}}</td> <td>{{run.test_name}}</td> <td> {% if run.exit_status == 'PASS(memory check)' %} <a href = {{run.img_url()}}>{{run.exit_status}}</a> {% else %} {{run.exit_status}} {% if run.exit_status not in ("", "PASS", "PASS(memory check)") %} - <span>{{run.failure_reason|e}}</span> {% endif %} {% endif %} </td> <td>{{run.notes|e}}</td> <td>{{run.duration}}</td> </tr> {% endfor %} </tbody> </table> </body> </html> """) class CaseInfo(): def __init__(self, *args, **kwargs): self.__dict__.update(kwargs) def bg_color(self): if self.exit_status == 'PASS' or self.exit_status == 'PASS(memory check)': return "#edffe6" elif self.exit_status == 'FAIL': return "#ff9797" # Red: Possible system-under-test failure def img_url(self): if socket.gethostbyname(socket.gethostname()) != globalVariable.APACHE_SERVER: img_url = 'http://%s/not_exist.jpg'%globalVariable.APACHE_SERVER else: img_url = os.path.join('http://%s'%globalVariable.APACHE_SERVER, globalVariable.IMAGE_DICT[self.test_name]) img_url = img_url.replace('\\', '/') return img_url class CaseFactory(object): cases = [] def __init__(self, *args, **kwargs): self.cases.append(CaseInfo(*args, **kwargs)) @classmethod def create_html(cls, html = 'report.html'): with open(html, "w+") as f: f.write(template.render(name = 'app', runs = cls.cases)) @classmethod def send_report(cls, report_time): cls.create_html() with open('report.html', 'r') as f: content = f.read() inst = sendMail.SendMail() inst.send_html_mail('App Automation Report at %s'%report_time, content) if __name__ == '__main__': CaseFactory(timestamp = 1, test_name = 'test1', exit_status = 'PASS', failure_reason = 'success', duration = '30', note = '') CaseFactory(timestamp = 2, test_name = 'test2', exit_status = 'FAIL', failure_reason = 'not match', duration = '28', note = '') CaseFactory.create_html()
en
0.246105
#!coding:utf-8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html lang='en'> <head xmlns="http://www.w3.org/1999/xhtml"> <meta charset='utf-8' /> <title>Test results</title> <style> .title { text-align:center; } .report { font-family:"Trebuchet MS", Arial, Helvetica, sans-serif; width:100%; border-collapse:collapse; } .report td, #report th { font-size:1em; border:1px solid #98bf21; padding:3px 7px 2px 7px; } .report th { font-size:1.1em; text-align:left; padding-top:5px; padding-bottom:4px; background-color:#97CBFF; color:#ffffff; } .report tr.alt td { color:#000000; background-color:#EAF2D3; } caption { font-size:25px; font-weight: bold } </style> </head> <body> <h3 class='title'> App Automation Report </h3> <table id="testruns" class="report"> <thead> <tr> <th style="width:10em">Timestamp</th> <th style="width:30%">Test</th> <th>Exit status</th> <th>Notes</th> <th style="width:5em">Duration</th> </tr> </thead> <tbody> {% for run in runs %} <tr bgcolor="{{run.bg_color()}}"> <td>{{run.timestamp}}</td> <td>{{run.test_name}}</td> <td> {% if run.exit_status == 'PASS(memory check)' %} <a href = {{run.img_url()}}>{{run.exit_status}}</a> {% else %} {{run.exit_status}} {% if run.exit_status not in ("", "PASS", "PASS(memory check)") %} - <span>{{run.failure_reason|e}}</span> {% endif %} {% endif %} </td> <td>{{run.notes|e}}</td> <td>{{run.duration}}</td> </tr> {% endfor %} </tbody> </table> </body> </html> # Red: Possible system-under-test failure
2.267509
2
run.py
DDzzxiaohongdou/corrector-of-bert
1
6619607
from flask import Flask, request as freq from bert_corrector import BertCorrector app = Flask(__name__) d = BertCorrector() @app.route('/correcting', methods=['GET', 'POST']) def corrector(): string = dict(freq.args)['data'] corrected_string = d.bert_correct(string) print(string, corrected_string) return corrected_string if __name__ == '__main__': app.run(host='127.0.0.1',port=5000,debug=False)
from flask import Flask, request as freq from bert_corrector import BertCorrector app = Flask(__name__) d = BertCorrector() @app.route('/correcting', methods=['GET', 'POST']) def corrector(): string = dict(freq.args)['data'] corrected_string = d.bert_correct(string) print(string, corrected_string) return corrected_string if __name__ == '__main__': app.run(host='127.0.0.1',port=5000,debug=False)
none
1
2.537194
3
beowulf/__init__.py
beowulf-foundation/beowulf-python
9
6619608
<filename>beowulf/__init__.py # -*- coding: utf-8 -*- # from .beowulf import Beowulf __version__ = '0.0.2'
<filename>beowulf/__init__.py # -*- coding: utf-8 -*- # from .beowulf import Beowulf __version__ = '0.0.2'
en
0.679546
# -*- coding: utf-8 -*- # from .beowulf import Beowulf
1.082815
1
read_AERONETfiles.py
rgryan92/MD-analysis-scripts
0
6619609
<reponame>rgryan92/MD-analysis-scripts<gh_stars>0 # -*- coding: utf-8 -*- """ Created on Mon Oct 23 12:36:05 2017 @author: rgryan FILE TO READ IN AND UNDERSTAND AERONET AEROSOL DATA FROM CANBERRA """ import pandas as pd #%% filepath = '/Users/rgryan/Google Drive/Documents/PhD/Data/AERONET_Canberra_March2017/20170301_20170331_Canberra' # for angstrom exponent # ===================== ang_path = '~/Google Drive/Documents/PhD/Data/AERONET_Canberra_March2017/030101_171231_Canberra (2)/' ang_file = '030101_171231_Canberra.lev20' ang_df = pd.read_csv(ang_path+ang_file, sep=',', header=4, parse_dates=[['Date(dd-mm-yy)','Time(hh:mm:ss)']]) ang_df_dti = ang_df.set_index(pd.DatetimeIndex(ang_df['Date(dd-mm-yy)_Time(hh:mm:ss)'])) ang_exp_monthly = ang_df_dti['340-440Angstrom'].resample('M').mean() #%% ang_exp_febr = ang_exp_monthly.loc[ang_exp_monthly.index.month==2] ang_exp_febr_mean = ang_exp_febr.mean() ang_exp_febr_std = ang_exp_febr.std() ang_exp_march = ang_exp_monthly.loc[ang_exp_monthly.index.month==3] ang_exp_march_mean = ang_exp_march.mean() ang_exp_march_std = ang_exp_march.std() ang_exp_april = ang_exp_monthly.loc[ang_exp_monthly.index.month==4] ang_exp_april_mean = ang_exp_april.mean() ang_exp_april_std = ang_exp_april.std() ang_exp_overall_mean = (ang_exp_april_mean+ang_exp_march_mean+ang_exp_febr_mean)/3 ang_exp_overall_std = (ang_exp_april_std+ang_exp_march_std+ang_exp_febr_std)/3 #%% aem = ang_exp_febr.plot(color='red') ang_exp_march.plot(ax=aem, color='blue') ang_exp_april.plot(ax=aem,color='orange') #%% asy_path = '~/Google Drive/Documents/PhD/Data/AERONET_Canberra_March2017/030101_171231_Canberra/030101_171231_Canberra.asy' asy_df = pd.read_csv(asy_path, sep=',', header=3, parse_dates=[['Date(dd-mm-yyyy)','Time(hh:mm:ss)']]) asy_df_dti = asy_df.set_index(pd.DatetimeIndex(asy_df['Date(dd-mm-yyyy)_Time(hh:mm:ss)'])) asy_exp_monthly = asy_df_dti.resample('M').mean() #%% asy_440_mean = asy_exp_monthly['ASYM440-T'].mean() asy_440_std = asy_exp_monthly['ASYM440-T'].std() asy_676_mean = asy_exp_monthly['ASYM676-T'].mean() asy_676_std = asy_exp_monthly['ASYM676-T'].std() asy_870_mean = asy_exp_monthly['ASYM870-T'].mean() asy_870_std = asy_exp_monthly['ASYM870-T'].std() asy_1020_mean = asy_exp_monthly['ASYM1020-T'].mean() asy_1020_std = asy_exp_monthly['ASYM1020-T'].std() asyp = asy_exp_monthly['ASYM440-T'].plot(color='blue') asy_exp_monthly['ASYM676-T'].plot(ax=asyp, color='red') asy_exp_monthly['ASYM870-T'].plot(ax=asyp, color='green') asy_exp_monthly['ASYM1020-T'].plot(ax=asyp, color='orange') #%% # For Single scattering albedo ssa_path = '~/Google Drive/Documents/PhD/Data/AERONET_Canberra_March2017/030101_171231_Canberra (3)/030101_171231_Canberra.ssa' ssa_df = pd.read_csv(ssa_path, sep=',', header=3, parse_dates=[['Date(dd-mm-yyyy)','Time(hh:mm:ss)']]) ssa_df_dti = ssa_df.set_index(pd.DatetimeIndex(ssa_df['Date(dd-mm-yyyy)_Time(hh:mm:ss)'])) ssa_exp_monthly = ssa_df_dti.resample('M').mean() #%% ssa_440_mean = ssa_exp_monthly['SSA440-T'].mean() ssa_440_std = ssa_exp_monthly['SSA440-T'].std() ssa_676_mean = ssa_exp_monthly['SSA676-T'].mean() ssa_676_std = ssa_exp_monthly['SSA676-T'].std() ssa_870_mean = ssa_exp_monthly['SSA870-T'].mean() ssa_870_std = ssa_exp_monthly['SSA870-T'].std() ssa_1020_mean = ssa_exp_monthly['SSA1020-T'].mean() ssa_1020_std = ssa_exp_monthly['SSA1020-T'].std() ssap = ssa_exp_monthly['SSA440-T'].plot(color='blue') ssa_exp_monthly['SSA676-T'].plot(ax=ssap, color='red') ssa_exp_monthly['SSA870-T'].plot(ax=ssap, color='green') ssa_exp_monthly['SSA1020-T'].plot(ax=ssap, color='orange') #%% aodd_path = 'C:/Users/rgryan/Google Drive/Documents/PhD/Data/AERONET_Canberra_March2017/AOD files_dailyaverages/' canfile = '030101_171231_Canberra.lev20' colfile = '010101_031231_Coleambally.lev20' adefile = '060101_091231_Adelaide_Site_7.lev20' brifile = '100101_151231_Brisbane-Uni_of_QLD.lev20' tinfile = '980101_121231_Tinga_Tingana.lev20' fowfile = '130101_171231_Fowlers_Gap.lev20' candf = pd.read_csv(aodd_path+canfile, sep=',', header=4, parse_dates=[['Date(dd-mm-yy)','Time(hh:mm:ss)']], dayfirst=True) candf = candf.set_index(pd.DatetimeIndex(candf['Date(dd-mm-yy)_Time(hh:mm:ss)'])) candf_monthly = candf.resample('M').mean() coldf = pd.read_csv(aodd_path+colfile, sep=',', header=4, parse_dates=[['Date(dd-mm-yy)','Time(hh:mm:ss)']]) coldf = coldf.set_index(pd.DatetimeIndex(coldf['Date(dd-mm-yy)_Time(hh:mm:ss)'])) coldf_monthly = coldf.resample('M').mean() adedf = pd.read_csv(aodd_path+adefile, sep=',', header=4, parse_dates=[['Date(dd-mm-yy)','Time(hh:mm:ss)']], dayfirst=True) adedf = adedf.set_index(pd.DatetimeIndex(adedf['Date(dd-mm-yy)_Time(hh:mm:ss)'])) adedf_monthly = adedf.resample('M').mean() fowdf = pd.read_csv(aodd_path+fowfile, sep=',', header=4, parse_dates=[['Date(dd-mm-yy)','Time(hh:mm:ss)']], dayfirst=True) fowdf = fowdf.set_index(pd.DatetimeIndex(fowdf['Date(dd-mm-yy)_Time(hh:mm:ss)'])) fowdf_monthly = fowdf.resample('M').mean() bridf = pd.read_csv(aodd_path+brifile, sep=',', header=4, parse_dates=[['Date(dd-mm-yy)','Time(hh:mm:ss)']], dayfirst=True) bridf = bridf.set_index(pd.DatetimeIndex(bridf['Date(dd-mm-yy)_Time(hh:mm:ss)'])) bridf_monthly = bridf.resample('M').mean() tindf = pd.read_csv(aodd_path+tinfile, sep=',', header=4, parse_dates=[['Date(dd-mm-yy)','Time(hh:mm:ss)']], dayfirst=True) tindf = tindf.set_index(pd.DatetimeIndex(tindf['Date(dd-mm-yy)_Time(hh:mm:ss)'])) tindf_monthly = tindf.resample('M').mean() #%% aodplot = candf_monthly['AOT_440'].plot(figsize=(10,2), color='blue') coldf_monthly['AOT_440'].plot(ax=aodplot, color='purple') adedf_monthly['AOT_440'].plot(ax=aodplot, color='red') bridf_monthly['AOT_440'].plot(ax=aodplot, color='grey') tindf_monthly['AOT_440'].plot(ax=aodplot, color='orange') fowdf_monthly['AOT_440'].plot(ax=aodplot, color='green') aodplot.legend(['Canberra', 'Coleambally', 'Adelaide', 'Brisbane', 'Tingana', 'Fowlers Gap'], loc=2, bbox_to_anchor=(1,1)) f = aodplot.get_figure() f.savefig(aodd_path+'AOD_avgs_SE_Australia.png', bbox_inches='tight')
# -*- coding: utf-8 -*- """ Created on Mon Oct 23 12:36:05 2017 @author: rgryan FILE TO READ IN AND UNDERSTAND AERONET AEROSOL DATA FROM CANBERRA """ import pandas as pd #%% filepath = '/Users/rgryan/Google Drive/Documents/PhD/Data/AERONET_Canberra_March2017/20170301_20170331_Canberra' # for angstrom exponent # ===================== ang_path = '~/Google Drive/Documents/PhD/Data/AERONET_Canberra_March2017/030101_171231_Canberra (2)/' ang_file = '030101_171231_Canberra.lev20' ang_df = pd.read_csv(ang_path+ang_file, sep=',', header=4, parse_dates=[['Date(dd-mm-yy)','Time(hh:mm:ss)']]) ang_df_dti = ang_df.set_index(pd.DatetimeIndex(ang_df['Date(dd-mm-yy)_Time(hh:mm:ss)'])) ang_exp_monthly = ang_df_dti['340-440Angstrom'].resample('M').mean() #%% ang_exp_febr = ang_exp_monthly.loc[ang_exp_monthly.index.month==2] ang_exp_febr_mean = ang_exp_febr.mean() ang_exp_febr_std = ang_exp_febr.std() ang_exp_march = ang_exp_monthly.loc[ang_exp_monthly.index.month==3] ang_exp_march_mean = ang_exp_march.mean() ang_exp_march_std = ang_exp_march.std() ang_exp_april = ang_exp_monthly.loc[ang_exp_monthly.index.month==4] ang_exp_april_mean = ang_exp_april.mean() ang_exp_april_std = ang_exp_april.std() ang_exp_overall_mean = (ang_exp_april_mean+ang_exp_march_mean+ang_exp_febr_mean)/3 ang_exp_overall_std = (ang_exp_april_std+ang_exp_march_std+ang_exp_febr_std)/3 #%% aem = ang_exp_febr.plot(color='red') ang_exp_march.plot(ax=aem, color='blue') ang_exp_april.plot(ax=aem,color='orange') #%% asy_path = '~/Google Drive/Documents/PhD/Data/AERONET_Canberra_March2017/030101_171231_Canberra/030101_171231_Canberra.asy' asy_df = pd.read_csv(asy_path, sep=',', header=3, parse_dates=[['Date(dd-mm-yyyy)','Time(hh:mm:ss)']]) asy_df_dti = asy_df.set_index(pd.DatetimeIndex(asy_df['Date(dd-mm-yyyy)_Time(hh:mm:ss)'])) asy_exp_monthly = asy_df_dti.resample('M').mean() #%% asy_440_mean = asy_exp_monthly['ASYM440-T'].mean() asy_440_std = asy_exp_monthly['ASYM440-T'].std() asy_676_mean = asy_exp_monthly['ASYM676-T'].mean() asy_676_std = asy_exp_monthly['ASYM676-T'].std() asy_870_mean = asy_exp_monthly['ASYM870-T'].mean() asy_870_std = asy_exp_monthly['ASYM870-T'].std() asy_1020_mean = asy_exp_monthly['ASYM1020-T'].mean() asy_1020_std = asy_exp_monthly['ASYM1020-T'].std() asyp = asy_exp_monthly['ASYM440-T'].plot(color='blue') asy_exp_monthly['ASYM676-T'].plot(ax=asyp, color='red') asy_exp_monthly['ASYM870-T'].plot(ax=asyp, color='green') asy_exp_monthly['ASYM1020-T'].plot(ax=asyp, color='orange') #%% # For Single scattering albedo ssa_path = '~/Google Drive/Documents/PhD/Data/AERONET_Canberra_March2017/030101_171231_Canberra (3)/030101_171231_Canberra.ssa' ssa_df = pd.read_csv(ssa_path, sep=',', header=3, parse_dates=[['Date(dd-mm-yyyy)','Time(hh:mm:ss)']]) ssa_df_dti = ssa_df.set_index(pd.DatetimeIndex(ssa_df['Date(dd-mm-yyyy)_Time(hh:mm:ss)'])) ssa_exp_monthly = ssa_df_dti.resample('M').mean() #%% ssa_440_mean = ssa_exp_monthly['SSA440-T'].mean() ssa_440_std = ssa_exp_monthly['SSA440-T'].std() ssa_676_mean = ssa_exp_monthly['SSA676-T'].mean() ssa_676_std = ssa_exp_monthly['SSA676-T'].std() ssa_870_mean = ssa_exp_monthly['SSA870-T'].mean() ssa_870_std = ssa_exp_monthly['SSA870-T'].std() ssa_1020_mean = ssa_exp_monthly['SSA1020-T'].mean() ssa_1020_std = ssa_exp_monthly['SSA1020-T'].std() ssap = ssa_exp_monthly['SSA440-T'].plot(color='blue') ssa_exp_monthly['SSA676-T'].plot(ax=ssap, color='red') ssa_exp_monthly['SSA870-T'].plot(ax=ssap, color='green') ssa_exp_monthly['SSA1020-T'].plot(ax=ssap, color='orange') #%% aodd_path = 'C:/Users/rgryan/Google Drive/Documents/PhD/Data/AERONET_Canberra_March2017/AOD files_dailyaverages/' canfile = '030101_171231_Canberra.lev20' colfile = '010101_031231_Coleambally.lev20' adefile = '060101_091231_Adelaide_Site_7.lev20' brifile = '100101_151231_Brisbane-Uni_of_QLD.lev20' tinfile = '980101_121231_Tinga_Tingana.lev20' fowfile = '130101_171231_Fowlers_Gap.lev20' candf = pd.read_csv(aodd_path+canfile, sep=',', header=4, parse_dates=[['Date(dd-mm-yy)','Time(hh:mm:ss)']], dayfirst=True) candf = candf.set_index(pd.DatetimeIndex(candf['Date(dd-mm-yy)_Time(hh:mm:ss)'])) candf_monthly = candf.resample('M').mean() coldf = pd.read_csv(aodd_path+colfile, sep=',', header=4, parse_dates=[['Date(dd-mm-yy)','Time(hh:mm:ss)']]) coldf = coldf.set_index(pd.DatetimeIndex(coldf['Date(dd-mm-yy)_Time(hh:mm:ss)'])) coldf_monthly = coldf.resample('M').mean() adedf = pd.read_csv(aodd_path+adefile, sep=',', header=4, parse_dates=[['Date(dd-mm-yy)','Time(hh:mm:ss)']], dayfirst=True) adedf = adedf.set_index(pd.DatetimeIndex(adedf['Date(dd-mm-yy)_Time(hh:mm:ss)'])) adedf_monthly = adedf.resample('M').mean() fowdf = pd.read_csv(aodd_path+fowfile, sep=',', header=4, parse_dates=[['Date(dd-mm-yy)','Time(hh:mm:ss)']], dayfirst=True) fowdf = fowdf.set_index(pd.DatetimeIndex(fowdf['Date(dd-mm-yy)_Time(hh:mm:ss)'])) fowdf_monthly = fowdf.resample('M').mean() bridf = pd.read_csv(aodd_path+brifile, sep=',', header=4, parse_dates=[['Date(dd-mm-yy)','Time(hh:mm:ss)']], dayfirst=True) bridf = bridf.set_index(pd.DatetimeIndex(bridf['Date(dd-mm-yy)_Time(hh:mm:ss)'])) bridf_monthly = bridf.resample('M').mean() tindf = pd.read_csv(aodd_path+tinfile, sep=',', header=4, parse_dates=[['Date(dd-mm-yy)','Time(hh:mm:ss)']], dayfirst=True) tindf = tindf.set_index(pd.DatetimeIndex(tindf['Date(dd-mm-yy)_Time(hh:mm:ss)'])) tindf_monthly = tindf.resample('M').mean() #%% aodplot = candf_monthly['AOT_440'].plot(figsize=(10,2), color='blue') coldf_monthly['AOT_440'].plot(ax=aodplot, color='purple') adedf_monthly['AOT_440'].plot(ax=aodplot, color='red') bridf_monthly['AOT_440'].plot(ax=aodplot, color='grey') tindf_monthly['AOT_440'].plot(ax=aodplot, color='orange') fowdf_monthly['AOT_440'].plot(ax=aodplot, color='green') aodplot.legend(['Canberra', 'Coleambally', 'Adelaide', 'Brisbane', 'Tingana', 'Fowlers Gap'], loc=2, bbox_to_anchor=(1,1)) f = aodplot.get_figure() f.savefig(aodd_path+'AOD_avgs_SE_Australia.png', bbox_inches='tight')
en
0.317858
# -*- coding: utf-8 -*- Created on Mon Oct 23 12:36:05 2017 @author: rgryan FILE TO READ IN AND UNDERSTAND AERONET AEROSOL DATA FROM CANBERRA #%% # for angstrom exponent # ===================== #%% #%% #%% #%% #%% # For Single scattering albedo #%% #%% #%%
2.763302
3
publications/migrations/0017_auto_20210128_0948.py
MarkJaroski/aho-dev-dct
0
6619610
# Generated by Django 2.1.2 on 2021-01-28 06:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('publications', '0016_auto_20201024_0911'), ] operations = [ migrations.AlterField( model_name='stgknowledgeproducttranslation', name='year_published', field=models.IntegerField(default=2021, verbose_name='Year Published'), ), ]
# Generated by Django 2.1.2 on 2021-01-28 06:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('publications', '0016_auto_20201024_0911'), ] operations = [ migrations.AlterField( model_name='stgknowledgeproducttranslation', name='year_published', field=models.IntegerField(default=2021, verbose_name='Year Published'), ), ]
en
0.828973
# Generated by Django 2.1.2 on 2021-01-28 06:48
1.40554
1
mozillians/users/urls.py
yogesh-kamble/mozillians
0
6619611
<filename>mozillians/users/urls.py<gh_stars>0 from django.conf.urls import patterns, url from django.contrib.auth.decorators import login_required from cities_light.models import Country from mozillians.users.views import (BaseProfileAdminAutocomplete, CityAutocomplete, CountryAutocomplete, RegionAutocomplete, TimeZoneAutocomplete, UsersAdminAutocomplete, VouchedAutocomplete, VoucherAutocomplete) urlpatterns = patterns( '', # Admin urls for django-autocomplete-light. url('users-autocomplete/$', login_required(UsersAdminAutocomplete.as_view()), name='users-autocomplete'), url('vouchee-autocomplete/$', login_required(BaseProfileAdminAutocomplete.as_view()), name='vouchee-autocomplete'), url('voucher-autocomplete/$', login_required(VoucherAutocomplete.as_view()), name='voucher-autocomplete'), url('vouched-autocomplete/$', login_required(VouchedAutocomplete.as_view()), name='vouched-autocomplete'), url('country-autocomplete/$', login_required(CountryAutocomplete.as_view(model=Country)), name='country-autocomplete'), url('region-autocomplete/$', login_required(RegionAutocomplete.as_view()), name='region-autocomplete'), url('city-autocomplete/$', login_required(CityAutocomplete.as_view()), name='city-autocomplete'), url('timezone-autocomplete/$', login_required(TimeZoneAutocomplete.as_view()), name='timezone-autocomplete'), )
<filename>mozillians/users/urls.py<gh_stars>0 from django.conf.urls import patterns, url from django.contrib.auth.decorators import login_required from cities_light.models import Country from mozillians.users.views import (BaseProfileAdminAutocomplete, CityAutocomplete, CountryAutocomplete, RegionAutocomplete, TimeZoneAutocomplete, UsersAdminAutocomplete, VouchedAutocomplete, VoucherAutocomplete) urlpatterns = patterns( '', # Admin urls for django-autocomplete-light. url('users-autocomplete/$', login_required(UsersAdminAutocomplete.as_view()), name='users-autocomplete'), url('vouchee-autocomplete/$', login_required(BaseProfileAdminAutocomplete.as_view()), name='vouchee-autocomplete'), url('voucher-autocomplete/$', login_required(VoucherAutocomplete.as_view()), name='voucher-autocomplete'), url('vouched-autocomplete/$', login_required(VouchedAutocomplete.as_view()), name='vouched-autocomplete'), url('country-autocomplete/$', login_required(CountryAutocomplete.as_view(model=Country)), name='country-autocomplete'), url('region-autocomplete/$', login_required(RegionAutocomplete.as_view()), name='region-autocomplete'), url('city-autocomplete/$', login_required(CityAutocomplete.as_view()), name='city-autocomplete'), url('timezone-autocomplete/$', login_required(TimeZoneAutocomplete.as_view()), name='timezone-autocomplete'), )
en
0.82746
# Admin urls for django-autocomplete-light.
1.927813
2
main.py
lvjonok/maze-gui-gen
5
6619612
<reponame>lvjonok/maze-gui-gen<gh_stars>1-10 """!/usr/bin/env python3""" import sys from PyQt5 import QtWidgets from source.mainWindow import MazeGenApp def main(): app = QtWidgets.QApplication(sys.argv) app.setStyle("fusion") window = MazeGenApp() window.show() app.exec_() if __name__ == "__main__": main()
"""!/usr/bin/env python3""" import sys from PyQt5 import QtWidgets from source.mainWindow import MazeGenApp def main(): app = QtWidgets.QApplication(sys.argv) app.setStyle("fusion") window = MazeGenApp() window.show() app.exec_() if __name__ == "__main__": main()
fr
0.448822
!/usr/bin/env python3
2.115768
2
SignRecorder.pyw
Jeffrey-Sardina/SignRecorder
1
6619613
import cv2 import tkinter as tk from tkinter import filedialog import threading import traceback import sys import logging import os import time from PIL import Image, ImageTk import abc import json ''' Program data global variables ''' #backend logger = None #experiment data webcam_num = 1 study_name = '' study_files = [] subject_id_entry_box = None experiment = None #recording window = None recorder = None just_started = True #files out_dir = None video_path = None video_id = None last_video_id = None #tk ui main_frame = None pop_up_window = None width = 0 height = 0 key_tracker = None padding_x = 10 padding_y = 10 default_font = 20 #Settings settings_dict_defaults = {'backcolor': '#000000', 'ui_element_color': '#888888', 'forecolor': '#000000', 'draggable_color0': '#888888', 'draggable_color1': '#aaaaaa'} settings_dict = {} ''' Initialization ''' def main(): ''' First method called in this thread of program execution. Runs through a servies of initialization steps and then loads the gui. Once the gui is loaded, the gui takes over control of program execution from there onwards. ''' init_logging() load_config() init_gui() def init_logging(): ''' Initializes the loggins system. The logging system is intended to allow the program to save data about each run to disk, and the logger itself will re-write any existing logs each time so as to conserve space and avoid cluttering the running directory with files. This method also triggers the first log write. Most methods in this program trigger a log call. For simplicity, the calls to logging are not mentioned in the method descriptions in general. ''' global logger logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) file_handler = logging.FileHandler('SignRecorder.log', mode='w') logger.addHandler(file_handler) file_handler_format = logging.Formatter('%(levelname)s - %(asctime)s - %(message)s') file_handler.setFormatter(file_handler_format) logger.info('init_logging: Starting log') def load_config(): ''' Loads the user settings from the config.csv file. If the file is not pressent or is corrputed, it will use default values and write a new config file, overwritting the old one if it is present. ''' global settings_dict logger.info('load_config:') try: with open('config.json', 'r') as config: settings_dict = json.loads(config.read()) except Exception as err: message = 'load_config: Could not read config file' logger.error(message + ': ' + str(err)) recover_config_file() def recover_config_file(): ''' This method should only be called if the config file is corrupted or missing. It re-writes the config data and replaces all data with the default values, or the last loaded non-corrupt data value if such a data value is present. If this operations fails, the program will continue to run, but no config file will be generated. ''' global settings_dict logger.info('recover_config_file: loading default settings and attempting to recover the config file') settings_dict = settings_dict_defaults try: with open('config.json', 'w') as config: print(json.dumps(settings_dict_defaults), file=config) except Exception as err: message = 'Attempt to recover config file failed: Could not write new config file' logger.critical('recover_config_file:' + message + ': ' + str(err)) pop_up(message) def find_webcams(search_num): ''' Searches to see how many webcams are attactched to the current system. This is done by attempting to open each webcam from number 0 (the default webcam) to number search_num, which is given to the method. If the webcam opens, then the program knows it has found a wewbcam; if not, the webcam either cannot be accessed by the program or is not present. All opened webcams are closed after searching, and not webcam inpout is recorded at this step. Parameters: search_num: The number of webcams for which to search ''' global webcam_num webcam_num = 0 for i in range(search_num): webcam_i = cv2.VideoCapture(i) if webcam_i.isOpened(): webcam_num += 1 webcam_i.release() logger.info('find_webcams: ' + str(webcam_num) + ' webcams found for recording') def init_gui(): ''' Initializes the gui. The gui is created in a maximized state and takes over main-thread program execution. Note that all gui operations should remain on the main thread, except where the gui allows (suchs as in triggered events). This method also sets up the key_tracker to manage keypress events and attempt to authenticate them (since some OS's will trigger a key press and / or release repeatedly when a key is help down). The gui also maps the default close event (~the red X) to an ooperations that cleans up the program state properly. This should help to prevent memory leaks on an unexpected closure. ''' global width, height, window, key_tracker, main_frame logger.info('init_gui:') #Master window window = tk.Tk() window.wm_title('Sign Recorder') window.config(background = settings_dict['backcolor']) width = window.winfo_screenwidth() height = window.winfo_screenheight() window.geometry("%dx%d+0+0" % (width, height)) #Main Frame in window main_frame = MainFrame(window, background = settings_dict['backcolor']) main_frame.prepare_display() main_frame.pack(side="top", fill="both", expand=True) #input key_tracker = KeyTracker() window.bind_all('<KeyPress>', key_tracker.report_key_press) window.bind_all('<KeyRelease>', key_tracker.report_key_release) key_tracker.track('space') #Exitting window.protocol("WM_DELETE_WINDOW", on_close) #Show window window.mainloop() ''' Core backend program functionality ''' def pop_up(message): ''' Creates a pop-up window to display a message. Please only call this method for important errors such as files that fail to load--each pop up will take focue from the main window and thus disrupt the user. ''' global pop_up_window logger.info('pop_up: message=' + message) pop_up_window = tk.Tk() pop_up_window.wm_title('Message') pop_up_window.config(background = settings_dict['backcolor']) pop_up_text = tk.Text(pop_up_window, font = default_font, height = 5, width = 70, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) pop_up_text.insert(tk.INSERT, message) pop_up_text.config(state = 'disabled') pop_up_text.grid(row = 0, column = 0, padx = padding_x, pady = padding_y) select_files_button = tk.Button(pop_up_window, text ="Close", command = pop_up_window.destroy, font = default_font, height = 3, width = 10, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) select_files_button.grid(row=1, column=0) def write_out(name, message): ''' Writes out a meta-file that contains metadata about the recorded video. The data is: stimulus_name: the name of the file used as a stimulus for this recording display_time: the amount of time the stimulus was displayed before recording recording_time: the time length of the recording total_time: the total time for this step of the experiment, = display_time + recording_time ''' logger.info('write_out: writing meta file at path=' + out_dir + ' with name=' + name) file_name = os.path.join(out_dir, name + '.meta.csv') try: if os.path.exists(file_name): message = 'Cannot overwrite existing meta file: ' logger.critical('write_out: ' + message + file_name) pop_up(message + '\n' + file_name) raise Exception(message + file_name) with open(file_name, 'w') as meta: print(message, file=meta) except Exception as err: message = 'Failed to write out file: ' + file_name logger.critical('write_out: ' + message + ': ' + str(err)) pop_up(message) raise Exception(message) def on_close(close = True): ''' Handles properly closing the program and its spawned resources. As much as possible, all close events should be routed to this method rather than immediately calling an exit function. Parameter: close: Whether this method should close the program. If false, all program resources still will be cleared but the program will not be closed. This should be done when a critical exception occurs so the exception can still be raised. ''' logger.info('on_close: Cleaning resources and closing' if close else 'on_close: Cleaning resources to prepare for closing') window.destroy() try: recorder.end() except: pass if close: sys.exit(0) ''' Experiment and data collection ''' def on_key_press(event): ''' Called whenever a key press event is detected. This method should not be linked to key press events directly; the use of the KeyTracker class is necessary to authenticate key presses as valid before attempting to respond to them. If this program has just started, the program runs a different method to respond to the key press event to manage the yet un-initialized variables. ''' experiment.on_input_press(event.keysym) def on_key_release(event): ''' Called whenever a key release event is detected. This method should not be linked to key release events directly; the use of the KeyTracker class is necessary to authenticate key releases as valid before attempting to respond to them. ''' experiment.on_input_release(event.keysym) class Experiment(abc.ABC): @abc.abstractmethod def on_input_press(self, input_key): pass @abc.abstractmethod def on_input_release(self, input_key): pass class Naming_Experiment(Experiment): #Experiment Parameters stimuli = [] subject_id = None stimulus_type = None #Experiment Running recording = False last_video_id = None video_id = None keep_displaying = True current_stimulus = 0 can_start_recording = True data = '' #Timing display_timer = None recording_timer = None def __init__(self, data): ''' Creates a new Naming_Experiment, which is an experiemnt in which single stimuli are presented and the subject is asked to produce the sign for what is shown. Parameters: data: A dictionary containing experiment data. This should contain the follwoing keys: file, containing absolute paths to all of the stimuli to use; stimulus_type, which tells whether the stimulus is Image or Video ''' self.stimuli = data['stimulus_files'] self.stimulus_type = data['stimulus_type'] self.display_timer = Timer() self.recording_timer = Timer() def on_input_press(self, input_key): ''' This method should be called every time space is pressed (if that space-press has been authenticated). It proceeds to the next stimulus and will begin recording, ending the current stimulus and recording. It also ends the recording_timer if it was running, and updates program state tracking variables to refect the current state of the progam. If there are no more stimuli to run, the program displays a pop-up message stating that data collection is complete. ''' logger.info('Naming_Experiment: on_input_press: current_stimulus=' + str(self.current_stimulus) + ' recording=' + str(self.recording)) self.recording = False if self.recording_timer.active(): self.recording_timer.end() self.data += str(self.current_stimulus) + '_' + '_recordingTime,' + str(self.recording_timer.timespan) + '\n' if self.current_stimulus >= len(self.stimuli): message = 'All data for ' + str(self.subject_id) + ' has been collected' write_out(self.subject_id + '_timing.csv', self.data) pop_up(message) logger.info('Naming_Experiment: on_input_press: ' + message) main_frame.select_start_experiment() self.reset_for_next_subject() else: self.load_stimulus() def on_input_release(self, input_key): ''' This method should be called when space is released (if that release has been authenticated). It begins recording and starts the recording timer. It also updates program state tracking variables to refect the current state of the progam. ''' if self.subject_id == None: self.subject_id = subject_id_entry_box.get().strip() if self.can_start_recording and self.current_stimulus < len(self.stimuli): logger.info('Naming_Experiment: on_input_release: current_stimulus=' + str(self.current_stimulus) + '; recording starting') self.last_video_id = self.video_id self.video_id = os.path.basename(self.stimuli[self.current_stimulus].strip()) self.recording = True self.keep_displaying = False self.recording_timer.begin() self.current_stimulus += 1 recorder = Recorder(self.subject_id + '-' + self.video_id, True) recorder.begin() else: logger.warning('Naming_Experiment: on_input_release: can_start_recording is False, video must end before the signer may be recorded') def load_stimulus(self): ''' Loads and displays the next stimulis for the current subject, but should not be used for the first stimulus of a subjecct. It resets the display timer, which measures the time that a stimulus is displayed before signing. Later, it will also write timer output to a meta file with the same name as the output file. Timer data it not yet verified though, so it is not ready for use. ''' global keep_displaying logger.info('Naming_Experiment: load_stimulus: current_stimulus=' + str(self.current_stimulus) + ' stimulus type=' + str(self.stimulus_type)) keep_displaying = True stimulus = self.stimuli[self.current_stimulus].strip() if self.display_timer.active(): self.display_timer.end() self.data += str(self.current_stimulus) + '_' + '_displayTime,' + str(self.display_timer.timespan) + '\n' if self.stimulus_type == 'Image': self.display_timer.begin() Image_Displayer(stimulus).begin() elif self.stimulus_type == 'Video': self.display_timer.begin() Video_Displayer(stimulus).begin() def reset_for_next_subject(self): ''' Resets the environment so that the next subject can begin the experiment. ''' logger.info('Naming_Experiment: reset_for_next_subject: Resetting the environment for the next subject') key_tracker.reset() self.subject_id = None self.recording = False self.last_video_id = None self.video_id = None self.keep_displaying = True self.current_stimulus = 0 self.can_start_recording = True subject_id_entry_box.delete(0, last='end') class Lexical_Priming_Experiment(Experiment): #Experiment Parameters stimuli_tuples = [] subject_id = None stimulus_type = None primer_type = None primer_time = 5 #Experiment Running recording = False last_video_id = None video_id = None keep_displaying = True current_round = 0 can_start_recording = True display_primer = True #Timing display_timer = None recording_timer = None primer_timer = None def __init__(self, data): ''' Creates a new Lexical_Priming_Experiment, in which there is a primer image followed by a stimulus for signing. Recording begins after the stimulus has been shown. Transition between the primer and stimulus is done using space, as is transition between the stimulus and the recording, etc. Parameters: data: A dictionary containing experiment data. This should contain the follwoing keys: files, which contains a tuple of: (absolute path of the primer, that of the stimulus); stimulus_type, which tells whether the stimulus is Image or Video; primer_type, which tells whether the primer is Image or Video; primer_time, which contains the time to show the primer (in seconds, only needed if primer_time is Image) ''' self.stimuli_tuples = data['files'] self.stimulus_type = data['stimulus_type'] self.primer_type = data['primer_type'] self.primer_time = data['primer_time'] if self.primer_type == 'Image' else 0 self.display_timer = Timer() self.recording_timer = Timer() self.prim_timers = Timer() def on_input_press(self, input_key): ''' This method should be called every time space is pressed (if that press has been authenticated), except the first. It proceeds to the next stimulus and will begin recording, ending the current stimulus and recording. It also ends the recording_timer if it was running, and updates program state tracking variables to refect the current state of the progam. If there are no more stimuli to run, the program displays a pop-up message stating that data collection is complete. ''' logger.info('Lexical_Priming_Experiment: on_input_press: current_stimulus=' + str(self.current_round) + ' recording=' + str(self.recording) + ', display_primer=' + self.display_primer) if self.display_primer: pass else: self.recording = False if self.recording_timer.active(): self.recording_timer.end() if self.current_round >= len(self.stimuli_tuples): main_frame.select_start_experiment() pop_up('All data for ' + self.subject_id + ' has been collected') self.reset_for_next_subject() else: self.load_primer() def on_input_release(self, input_key): ''' This method should be called when space is released (if that release has been authenticated). It begins recording and starts the recording timer. It also updates program state tracking variables to refect the current state of the progam. ''' if self.display_primer: self.display_primer = False #code here else: if self.subject_id == None: self.subject_id = subject_id_entry_box.get().strip() if self.can_start_recording and self.current_round < len(self.stimuli_tuples): logger.info('Lexical_Priming_Experiment: on_input_release: current_round=' + str(self.current_round) + '; recording starting') self.last_video_id = self.video_id self.video_id = os.path.basename(self.stimuli_tuples[self.current_round][0].strip()) + '-' + os.path.basename(self.stimuli_tuples[self.current_round][1].strip()) self.recording = True self.keep_displaying = False self.recording_timer.begin() self.current_round += 1 recorder = Recorder(self.subject_id + '-' + self.video_id, True) recorder.begin() else: logger.warning('Naming_Experiment: on_input_release: can_start_recording is False, video must end before the signer may be recorded') def load_primer(self): #WHat about stimuli? ''' Loads and displays the next stimulus for the current subject, but should not be used for the first stimulus of a subjecct. It resets the display timer, which measures the time that a stimulus is displayed before signing. Later, it will also write timer output to a meta file with the same name as the output file. Timer data it not yet verified though, so it is not ready for use. ''' global keep_displaying logger.info('Lexical_Priming_Experiment: load_stimulus: current_stimulus=' + str(self.current_round) + ' stimulus type=' + str(self.stimulus_type)) keep_displaying = True primer = self.stimuli_tuples[self.current_round][0].strip() timer = None if self.display_timer.active(): self.display_timer.end() if self.primer_type == 'Image': self.display_timer.begin() Image_Displayer(primer).begin() timer = threading.Timer(self.primer_time, self.on_primer_finished) #In seconds elif self.primer_type == 'Video': self.display_timer.begin() Video_Displayer(primer).begin() timer = threading.Timer(self.primer_time, self.on_primer_finished) #In seconds timer.start() def on_primer_finished(self): stimulus = self.stimuli_tuples[self.current_round][1].strip() if self.stimulus_type == 'Image': self.display_timer.begin() Image_Displayer(stimulus).begin() elif self.stimulus_type == 'Video': self.display_timer.begin() Video_Displayer(stimulus).begin() def reset_for_next_subject(self): ''' Resets the environment so that the next subject can begin the experiment. ''' logger.info('Lexical_Priming_Experiment: reset_for_next_subject: Resetting the environment for the next subject') key_tracker.reset() self.subject_id = None self.recording = False self.last_video_id = None self.video_id = None self.keep_displaying = True self.current_stimulus = 0 self.can_start_recording = True subject_id_entry_box.delete(0, last='end') ''' Data and user-input ''' class Recorder(): ''' This class handles all recording using the webcam, and writes recrodings to disk. ''' name = '' mirror = False web_cam = None video_writer = None def __init__(self, name, mirror): ''' Initializes the Recorder. Parameters: name: The name to five to the recording file mirror: Whether the recording should be mirrored when saved to disk ''' logger.info('Recorder: __init__: name=' + self.name + ' mirror=' + str(mirror)) self.name = name self.mirror = mirror def begin(self): ''' Begins recording from the webcam. The recording will continue untill end is called, or until 1 is pressed. Note that pressing 1 to quit should be used for debug purposes only ''' # Capturing video from webcam: self.web_cam = cv2.VideoCapture(0) fps = self.web_cam.get(cv2.CAP_PROP_FPS) #get width and height of reading frame width = int(self.web_cam.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(self.web_cam.get(cv2.CAP_PROP_FRAME_HEIGHT)) # Define the codec and fourcc = cv2.VideoWriter_fourcc(*"XVID") #create VideoWriter object file_name = os.path.join(out_dir, self.name + '.avi') if os.path.exists(file_name): message = 'Cannot overwrite existing video file: ' logger.critical('Recorder: begin: ' + message + file_name) pop_up(message + '\n' + file_name) raise Exception(message + file_name) else: self.video_writer = cv2.VideoWriter(file_name, fourcc, fps, (width, height)) if not self.web_cam.isOpened(): message = 'Could not open webcam' logger.warning('Recorder: begin: ' + message) pop_up(message) raise Exception(message) logger.info('Recorder: begin: starting recording loop') while self.web_cam.isOpened(): # Capture frame-by-frame is_reading, frame = self.web_cam.read() if is_reading and experiment.recording: if self.mirror: frame = cv2.flip(frame, 1) self.video_writer.write(frame) else: break if cv2.waitKey(1) & 0xFF == ord('1'): #quit on 1 experiment.on_input_release('space') break self.end() def end(self): ''' Ends the recording and releases resources. ''' logger.info('Recorder: end: recording ended, releasing resources') self.web_cam.release() self.video_writer.release() class Video_Displayer(): file_name = '' video_input = None fps = None display = None callback = None def __init__(self, file_name, callback = None): logger.info('Video_Displayer: __init__: file_name=' + file_name) self.file_name = file_name self.callback = callback def begin(self): experiment.can_start_recording = False self.video_input = cv2.VideoCapture(self.file_name) self.fps = int(self.video_input.get(cv2.CAP_PROP_FPS)) self.display = main_frame.page_show_stimuli.display_region logger.info('Video_Displayer: begin: ' + self.file_name + ' running at fps=' + str(int(self.fps))) if not self.video_input.isOpened(): message = 'Could not open video file for reading' logger.warning('Video_Displayer: begin: ' + message) pop_up(message) raise Exception(message) main_frame.select_show_stimuli() self.run_frame() def run_frame(self): #Get the next frame is_reading, frame = self.video_input.read() if is_reading: #Load the image for the current frame and convert to imagetk cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA) img = Image.fromarray(cv2image) img_width, img_height = get_proper_resize_dimensions_for_fullscreen(img) img = img.resize((int(img_width), int(img_height))) imgtk = ImageTk.PhotoImage(image=img) self.display.imgtk = imgtk self.display.configure(image=imgtk) if self.video_input.isOpened(): self.display.after(self.fps, self.run_frame) else: self.end('Video_Displayer: run_frame: display ended due to unexpected closure of video_input') experiment.can_start_recording = True if not self.callback == None: self.callback() else: self.end('Video_Displayer: run_frame: display ended naturally') experiment.can_start_recording = True if not self.callback == None: self.callback() def end(self, message = 'Video_Displayer: end: run_frame ended'): logger.info(message) self.video_input.release() if not self.callback == None: self.callback() class Image_Displayer(): file_name = '' display = None def __init__(self, file_name): logger.info('Image_Displayer: __init__: ' + file_name) self.file_name = file_name def begin(self): logger.info('Image_Displayer: begin:') self.display = main_frame.page_show_stimuli.display_region main_frame.select_show_stimuli() #Load the image for the current frame and convert to imagetk cv2image = cv2.imread(self.file_name) b,g,r = cv2.split(cv2image) cv2image = cv2.merge((r,g,b)) img = Image.fromarray(cv2image) img_width, img_height = get_proper_resize_dimensions_for_fullscreen(img) img = img.resize((int(img_width), int(img_height))) imgtk = ImageTk.PhotoImage(image=img) # Put it in the display window self.display.imgtk = imgtk self.display.configure(image=imgtk) class KeyTracker(): key = '' last_press_time = 0 last_release_time = 0 last_release_callback_time = 0 first_callback_call = True last_event_was_press = False def track(self, key): logger.info('KeyTracker: track: key=' + key) self.key = key def reset(self): logger.info('KeyTracker: reset: resetting') self.last_press_time = 0 self.last_release_time = 0 self.last_release_callback_time = 0 self.first_callback_call = True self.last_event_was_press = False def is_pressed(self): return time.time() - self.last_press_time < .01 #In seconds def report_key_press(self, event): if not self.last_event_was_press and event.keysym == self.key: self.last_event_was_press = True if not self.is_pressed(): logger.info('KeyTracker: report_key_press: valid keypress detected: key=' + self.key) self.last_press_time = time.time() on_key_press(event) else: self.last_press_time = time.time() def report_key_release(self, event): if self.last_event_was_press and event.keysym == self.key: self.last_event_was_press = False self.last_release_time = time.time() timer = threading.Timer(.015, self.report_key_release_callback, args=[event]) #In seconds timer.start() def report_key_release_callback(self, event): if self.first_callback_call: self.last_release_callback_time = time.time() self.first_callback_call = False if not self.is_pressed(): self.last_release_callback_time = time.time() logger.info('KeyTracker: report_key_release_callback: key=' + self.key + ', is released= ' + str((not self.is_pressed()))) if not self.is_pressed(): on_key_release(event) class Timer(): start_time = 0 end_time = 0 timespan = 0 def begin(self): self.start_time = time.time() def end(self): self.end_time = time.time() self.timespan = self.end_time - self.start_time def active(self): return self.start_time > self.end_time ''' UI and layout management ''' def arrange_header_in(page): button_frame = page.button_frame top_bar_buttons = [] #Place buttons in the top-level button frame top_bar_buttons.append(tk.Button(button_frame, text="Main Menu", font=default_font, command=main_frame.select_main_menu, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor'])) top_bar_buttons.append(tk.Button(button_frame, text="Create Experiment", font=default_font, command=main_frame.select_create_experiment, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor'])) top_bar_buttons.append(tk.Button(button_frame, text="Start Experiment", font=default_font, command=main_frame.select_start_experiment, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor'])) #Grid buttons col = 0 for button in top_bar_buttons: button.grid(row=0, column=col, pady=10) col += 1 button_frame.grid(row=0, column=0) def get_proper_resize_dimensions_for_fullscreen(img): ''' This method gets the largest-area resize of an image to be displayed on a fullscreen display without allowing any of the image to overflow off-screen. It maintains the image aspect ratio. ''' #Get image dimensions original_width = img.width original_height = img.height #Get the scalars that transform the original size into the fullscreen dize width_scalar = width / original_width height_scalar = height / original_height #Our goal is to make the image as largs as possible without goinf over the screen size. #We also do not want to loose out aspect ratio. So let's see whether using the width_scalar # or the height_scalar does that best width_based_scaling_height = original_height * width_scalar width_based_scaling_valid = True if width_based_scaling_height > height: width_based_scaling_valid = False height_based_scaling_width = original_width * height_scalar height_based_scaling_valid = True if height_based_scaling_width > width: height_based_scaling_valid = False if width_based_scaling_valid and not height_based_scaling_valid: return width, width_based_scaling_height else: return height_based_scaling_width, height class Widget_Drag_Controller(): ''' This class handles dragging widgets that below to a common set in such a way as to change their positions in that set. So if the numbers 1, 2, 3 are shown on screen, it's goal is to allow you to click on, say, the 3 and move it in from of the one, and then to read back that array in the new order. ''' item = None callback = None move_frame = None def __init__(self, item, widgets, callback): ''' Parameters: item: The specific item out of the set that can be dragged widgets: The set of all widgets that are ordered on the screen and can be dragged callback: the function to call after a drag and drop. It should accept a list of files in the new order as a parameter. ''' self.item = item self.widgets = widgets self.callback = callback #Bind clicks on the item itself self.item.bind("<ButtonPress-1>", self.on_start) self.item.bind("<B1-Motion>", self.on_move) self.item.bind("<ButtonRelease-1>", self.on_end) self.item.configure(cursor="hand1") def on_start(self, event): print('on_start') self.last_seen = self.item self.move_frame = tk.Frame() tk.Label(self.move_frame, text = self.item.cget('text'), font = self.item.cget('font'), anchor = self.item.cget('anchor'), background = self.item.cget('background')).pack(side = 'top', fill = 'x') def on_move(self, event): print('on_move') x, y = event.widget.winfo_pointerxy() self.move_frame.place(x = x, y = int(y - (self.item.winfo_height() + self.item.winfo_height() / 2))) def on_end(self, event): print('on_end') self.move_frame.destroy() x, y = event.widget.winfo_pointerxy() target = event.widget.winfo_containing(x, y) move_to = self.widgets.index(target) move_from = self.widgets.index(self.item) if move_to > move_from: self.widgets.insert(move_to + 1, self.item) del self.widgets[move_from] elif move_to < move_from: self.widgets.insert(move_to, self.item) del self.widgets[move_from + 1] files = [widget.cget('text') for widget in self.widgets] self.callback(files) class File_Arrangement_Region(): canvas = None display_frame = None elements = [] width = 0 height = 0 owner = None widget_drag_controllers = [] owner_update_callback = None def __init__(self, owner, owner_update_callback, root, width, height, row, column, rowspan = 1, columnspan = 1): self.owner_update_callback = owner_update_callback self.width = width self.height = height self.owner = owner outer_frame = tk.Frame(root, background = settings_dict['ui_element_color']) outer_frame.grid(row = row, column = column, rowspan = rowspan, columnspan = columnspan, padx=padding_x, pady=padding_y) self.canvas = tk.Canvas(outer_frame, background = settings_dict['ui_element_color']) self.display_frame = tk.Frame(self.canvas, background = settings_dict['ui_element_color']) scrollbar_y = tk.Scrollbar(outer_frame, orient = 'vertical',command = self.canvas.yview) scrollbar_x = tk.Scrollbar(outer_frame, orient = 'horizontal',command = self.canvas.xview) self.canvas.configure(yscrollcommand = scrollbar_y.set) self.canvas.configure(xscrollcommand = scrollbar_x.set) scrollbar_y.pack(side = 'right',fill = 'y') scrollbar_x.pack(side = 'bottom', fill = 'x') self.canvas.pack(side = 'left') self.canvas.create_window((0, 0), window = self.display_frame, anchor = 'nw') self.display_frame.bind('<Configure>', self.scroll_configure) def scroll_configure(self, event): self.canvas.configure(scrollregion = self.canvas.bbox('all'), width = self.width, height = self.height) def set_elements(self, files): #Remove old elements self.widget_drag_controllers.clear() for child in self.display_frame.winfo_children(): child.destroy() #Add new elements (OLD) for i in range(len(files)): highlight = settings_dict['draggable_color' + str(i % 2)] tk.Label(self.display_frame, text=files[i], font = default_font, anchor = 'w', background = highlight).pack(side = 'top', fill = 'x') for label in self.display_frame.winfo_children(): print(label); self.widget_drag_controllers.append(Widget_Drag_Controller(label, self.display_frame.winfo_children(), self.update_owner_data)) '''#Add new elements for i in range(len(files)): highlight = settings_dict['draggable_color' + str(i % 2)] container = tk.Frame(self.display_frame, width = width, height = int(height / 1.25), background = highlight) label = tk.Label(container, text=files[i], font = default_font, anchor = 'w', background = highlight) label.pack(side = 'left') remove_button = tk.Button(container, text ="-", command = self.on_button_remove, font = default_font, height = 1, width = 3, background = highlight, foreground = settings_dict['forecolor']) remove_button.pack(side = 'right') label.bindtags(("draggable",) + label.bindtags()) container.pack(side = 'top', fill = 'x') for element in self.display_frame.winfo_children(): print(element); self.widget_drag_controllers.append(Widget_Drag_Controller(element, self.display_frame.winfo_children(), self.update_owner_data))''' def on_button_remove(self): pass def update_owner_data(self, files): self.owner_update_callback(files) class Page(tk.Frame): button_frame = None def __init__(self, *args, **kwargs): tk.Frame.__init__(self, *args, **kwargs) self.button_frame = tk.Frame(self, background = settings_dict['backcolor']) def show(self): print('Show') print(self) self.lift() class Page_Main_Menu(Page): def __init__(self, *args, **kwargs): Page.__init__(self, *args, **kwargs) self.init_elements() def init_elements(self): about_text = ''' Version: 0.2.1beta Developer: <NAME> SignRecorder is a simple program for recording and saving video files for sign language data collection and experiments. It is currently hosted on GitHub (https://github.com/Jeffrey-Sardina/SignRecorder) as an open-source project. To get started, click on either 'Create Experiemnt' or 'Start Experiment'. The program will guide you through loading stimuli and experimental methods. Once you have made an experiemnt, save it so that you can load it later. ''' arrange_header_in(self) file_text = tk.Text(self, font = default_font, height = 15, width = 70, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) file_text.insert(tk.INSERT, about_text) file_text.config(state = 'disabled') file_text.grid(row=1, column=0, padx=padding_x, pady=padding_y) class Page_Naming_Paradigm(Page): file_arrangement_region = None stimulus_option_selected = None num_rows = 0 def __init__(self, *args, **kwargs): Page.__init__(self, *args, **kwargs) self.init_elements() def init_elements(self): stimulus_text = tk.Text(self, font = default_font, height = 3, width = 70, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) stimulus_text.insert(tk.INSERT, '\nSelect Stimulus Type') stimulus_text.tag_configure("center", justify='center') stimulus_text.tag_add("center", 1.0, "end") stimulus_text.config(state = 'disabled') stimulus_text.grid(row=0, column=0, padx=padding_x, pady=padding_y) self.num_rows += 1 stimulus_options = ['Video', 'Image'] stimulus_default_option = stimulus_options[0] self.stimulus_option_selected = tk.StringVar(self) stimulus_option_menu = tk.OptionMenu(self, self.stimulus_option_selected, *stimulus_options) self.stimulus_option_selected.set(stimulus_default_option) stimulus_option_menu.config(background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor'], height = 1, width = 30, font = default_font) stimulus_option_menu.grid(row=1, column=0, padx=padding_x, pady=padding_y) self.num_rows += 1 select_files_button = tk.Button(self, text ="Select Stimulus Files", command = self.load_files, font = default_font, height = 1, width = 30, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) select_files_button.grid(row=2, column=0, padx=padding_x, pady=padding_y) self.num_rows += 1 self.file_arrangement_region = File_Arrangement_Region(self, self.change_files, self, width / 2, height / 1.5, 0, 1, 20) self.file_arrangement_region.set_elements(['Selected Files:']) def load_files(self): logger.info('Page_Naming_Paradigm: load_files: loading files') self.files = filedialog.askopenfilenames(parent=self, initialdir="/", title='Select Files' + self.stimulus_option_selected.get() + ' files') display_strs = self.files self.file_arrangement_region.set_elements(display_strs) def change_files(self, files): self.files = files self.file_arrangement_region.set_elements(self.files) def dict_data(self): data = {} data['paradigm'] = 'Naming' data['stimulus_type'] = self.stimulus_option_selected.get() data['stimulus_files'] = self.files return data class Page_Lexical_Priming(Page): stimulus_file_arrangement_region = None primer_file_arrangement_region = None stimulus_option_selected = None primer_option_selected = None stimulus_files = [] primer_files = [] num_rows = 0 def __init__(self, *args, **kwargs): Page.__init__(self, *args, **kwargs) self.init_elements() def init_elements(self): stimulus_text = tk.Text(self, font = default_font, height = 3, width = 70, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) stimulus_text.insert(tk.INSERT, '\nSelect Stimulus Type') stimulus_text.tag_configure("center", justify='center') stimulus_text.tag_add("center", 1.0, "end") stimulus_text.config(state = 'disabled') stimulus_text.grid(row=0, column=0, padx=padding_x, pady=padding_y) self.num_rows += 1 stimulus_options = ['Video', 'Image'] stimulus_default_option = stimulus_options[0] self.stimulus_option_selected = tk.StringVar(self) stimulus_option_menu = tk.OptionMenu(self, self.stimulus_option_selected, *stimulus_options) self.stimulus_option_selected.set(stimulus_default_option) stimulus_option_menu.config(background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor'], height = 1, width = 30, font = default_font) stimulus_option_menu.grid(row=1, column=0, padx=padding_x, pady=padding_y) self.num_rows += 1 primer_text = tk.Text(self, font = default_font, height = 3, width = 70, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) primer_text.insert(tk.INSERT, '\nSelect Primer Type') primer_text.tag_configure("center", justify='center') primer_text.tag_add("center", 1.0, "end") primer_text.config(state = 'disabled') primer_text.grid(row=2, column=0, padx=padding_x, pady=padding_y) self.num_rows += 1 primer_options = ['Video', 'Image'] primer_default_option = primer_options[0] self.primer_option_selected = tk.StringVar(self) primer_option_menu = tk.OptionMenu(self, self.primer_option_selected, *primer_options) self.primer_option_selected.set(primer_default_option) primer_option_menu.config(background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor'], height = 1, width = 30, font = default_font) primer_option_menu.grid(row=3, column=0, padx=padding_x, pady=padding_y) self.num_rows += 1 stimulus_select_files_button = tk.Button(self, text ="Select Stimulus Files", command = self.load_stimulus_files, font = default_font, height = 1, width = 30, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) stimulus_select_files_button.grid(row=4, column=0, padx=padding_x, pady=padding_y) self.num_rows += 1 self.stimulus_file_arrangement_region = File_Arrangement_Region(self, self.change_stimulus_files, self, width / 4, height / 1.5, 0, 1, 20) self.stimulus_file_arrangement_region.set_elements(['Selected Files:']) primer_select_files_button = tk.Button(self, text ="Select Primer Files", command = self.load_primer_files, font = default_font, height = 1, width = 30, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) primer_select_files_button.grid(row=5, column=0, padx=padding_x, pady=padding_y) self.num_rows += 1 self.primer_file_arrangement_region = File_Arrangement_Region(self, self.change_primer_files, self, width / 4, height / 1.5, 0, 2, 20) self.primer_file_arrangement_region.set_elements(['Selected Files:']) def load_stimulus_files(self): self.load_files(True) def load_primer_files(self): self.load_files(False) def load_files(self, is_stimulus): logger.info('Page_Lexical_Priming: load_files: loading files, is_stimulus=' + str(is_stimulus)) if is_stimulus: self.stimulus_files = filedialog.askopenfilenames(parent=self, initialdir="/", title='Select Stimulus Files' + self.stimulus_option_selected.get() + ' files') self.stimulus_file_arrangement_region.set_elements(self.stimulus_files) else: self.primer_files = filedialog.askopenfilenames(parent=self, initialdir="/", title='Select Primer Files' + self.primer_option_selected.get() + ' files') self.primer_file_arrangement_region.set_elements(self.primer_files) def change_stimulus_files(self, files): self.stimulus_files = files self.stimulus_file_arrangement_region.set_elements(self.stimulus_files) def change_primer_files(self, files): self.primer_files = files self.primer_file_arrangement_region.set_elements(self.primer_files) def dict_data(self): primers = self.primer_option_selected.get() stimuli = self.stimulus_files if len(primers) != len(stimuli): message = 'Cannot write file: There must be a 1:1 mapping of primers to stimuli' logger.warning('Page_Lexical_Priming: dict_data: ' + message) pop_up(message) return [] data = {} data['paradigm'] = 'Lexical_Priming' data['files'] = [(primer, stimulus) for primer in primers for stimulus in stimuli] data['stimulus_type'] = self.stimulus_option_selected.get() return data class Page_Create_Experiment(Page): files = [] option_selected = None paradigm_option_selected = None entry = None selected_files_info_text = None page_naming_paradigm = None page_lexical_priming = None create_experiment_button = None def __init__(self, *args, **kwargs): Page.__init__(self, *args, **kwargs) self.init_elements() def init_elements(self): arrange_header_in(self) self.page_naming_paradigm = Page_Naming_Paradigm(self, background = settings_dict['backcolor']) self.page_lexical_priming = Page_Lexical_Priming(self, background = settings_dict['backcolor']) paradigm_text = tk.Text(self, font = default_font, height = 3, width = 70, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) paradigm_text.insert(tk.INSERT, '\nSelect Experiemnt Paradigm') paradigm_text.tag_configure("center", justify='center') paradigm_text.tag_add("center", 1.0, "end") paradigm_text.config(state = 'disabled') paradigm_text.grid(row=1, column=0, padx=padding_x, pady=padding_y) paradigm_options = ['Naming', 'Lexcial Priming'] default_paradigm_option = paradigm_options[0] self.paradigm_option_selected = tk.StringVar(self) self.paradigm_option_selected.trace('w', self.paradigm_selected) paradigm_option_menu = tk.OptionMenu(self, self.paradigm_option_selected, *paradigm_options) self.paradigm_option_selected.set(default_paradigm_option) paradigm_option_menu.config(background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor'], height = 1, width = 30, font = default_font) paradigm_option_menu.grid(row=2, column=0, padx=padding_x, pady=padding_y) #Container container = tk.Frame(self, width = width, height = int(height / 1.25), background = settings_dict['backcolor']) container.grid(row=3, column=0, rowspan = 10, columnspan = 400, padx=0, pady=padding_y) #Place pages in the container frame self.page_naming_paradigm.place(in_=container) self.page_lexical_priming.place(in_=container) paradigm_option_string = self.paradigm_option_selected.get() if paradigm_option_string == 'Naming': self.page_naming_paradigm.show() elif paradigm_option_string == 'Lexcial Priming': self.page_lexical_priming.show() #Create Experiment Button self.create_experiment_button = tk.Button(self, text ="Create Experiment", command = self.create_experiment, font = default_font, height = 1, width = 30, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) self.create_experiment_button.grid(row = 1, column = 1, padx = padding_x, pady = padding_y) def create_experiment(self): logger.info('Page_Create_Experiment: create_experiment: creating experiment') paradigm_option_string = self.paradigm_option_selected.get() exp_data = None if paradigm_option_string == 'Naming': exp_data = self.page_naming_paradigm.dict_data() elif paradigm_option_string == 'Lexcial Priming': exp_data = self.page_lexical_priming.dict_data() data = {} data['paradigm'] = paradigm_option_string data.update(exp_data) try: experimant_name = filedialog.asksaveasfilename(initialdir = "/", title = "Save file", filetypes = (("experiment files","*.exp"), ("all files","*.*"))) with open(experimant_name, 'w') as experiment: print(json.dumps(data), file=experiment) except Exception as err: message = 'Error: Could not write experiment file' logger.error('Page_Create_Experiment: create_experiment: ' + message + ': ' + str(err)) pop_up(message) def paradigm_selected(self, name, index, mode): paradigm_option_string = self.paradigm_option_selected.get() logger.info('Page_Create_Experiment: paradigm_selected: paradigm_option_string=' + paradigm_option_string) if paradigm_option_string == 'Naming': pass #self.page_naming_paradigm.lift() #self.page_lexical_priming.lower() elif paradigm_option_string == 'Lexcial Priming': pass #self.page_lexical_priming.lift() #self.page_naming_paradigm.lower() class Page_Start_Experiment(Page): def __init__(self, *args, **kwargs): Page.__init__(self, *args, **kwargs) self.init_elements() def init_elements(self): global subject_id_entry_box arrange_header_in(self) file_text = tk.Text(self, font = default_font, height = 3, width = 70, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) file_text.insert(tk.INSERT, '\nSelect an experiment file to load') file_text.tag_configure("center", justify='center') file_text.tag_add("center", 1.0, "end") file_text.config(state = 'disabled') file_text.grid(row=1, column=0, padx=padding_x, pady=padding_y) select_file_button = tk.Button(self, text ="Choose file", command = self.load_experiment, font = default_font, height = 1, width = 30, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) select_file_button.grid(row=2, column=0, padx=padding_x, pady=padding_y) dir_text = tk.Text(self, font = default_font, height = 3, width = 70, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) dir_text.insert(tk.INSERT, '\nSelect a folder in which to save the output') dir_text.tag_configure("center", justify='center') dir_text.tag_add("center", 1.0, "end") dir_text.config(state = 'disabled') dir_text.grid(row=3, column=0, padx=padding_x, pady=padding_y) select_file_button = tk.Button(self, text ="Choose output folder", command = self.load_dir, font = default_font, height = 1, width = 30, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) select_file_button.grid(row=4, column=0, padx=padding_x, pady=padding_y) entry_text = tk.Text(self, font = default_font, height = 3, width = 70, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) entry_text.insert(tk.INSERT, '\nEnter subject ID') entry_text.tag_configure("center", justify='center') entry_text.tag_add("center", 1.0, "end") entry_text.config(state = 'disabled') entry_text.grid(row=5, column=0, padx=padding_x, pady=padding_y) subject_id_entry_box = tk.Entry(self, font = default_font, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) subject_id_entry_box.grid(row=6, column=0, padx=padding_x, pady=padding_y) how_to_string = ''' When you are ready to begin the experiment, press the space bar. Once you are ready to sign based on what you see, press the space bar to start recording. Once you are done signing, press the space bar again. You will then see the next prompt and the program will begin recording. ''' how_to_text = tk.Text(self, font = default_font, height = 9, width = 70, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) how_to_text.insert(tk.INSERT, how_to_string) how_to_text.config(state = 'disabled') how_to_text.grid(row=7, column=0, padx=padding_x, pady=padding_y) def load_dir(self): global out_dir logger.info('Page_Start_Experiment: load_dir: loading save folder') try: out_dir = filedialog.askdirectory(parent = self, initialdir="/", title='Select Save Folder') except Exception as err: message = 'Could not load the selected directory' logger.error('Page_Start_Experiment: load_dir: ' + message + ': ' + str(err)) pop_up(message) def load_experiment(self): global experiment logger.info('Page_Start_Experiment: load_experiment: loading experiment') experiment_file = filedialog.askopenfilename(parent=self, initialdir="/", title='Select Experiment') try: with open(experiment_file, 'r') as experiment_data: data = json.loads(experiment_data.read()) if data['paradigm'] == 'Naming': experiment = Naming_Experiment(data) elif data['paradigm'] == 'Lexical Priming': pass except Exception as err: message = 'Could not load experiment file' logger.error('Page_Start_Experiment: load_experiment:' + message + ': ' + str(err)) pop_up(message) class Page_Show_Stimuli(Page): display_region = None def __init__(self, *args, **kwargs): Page.__init__(self, *args, **kwargs) self.init_display_region() def init_display_region(self): self.display_region = tk.Label(self) self.display_region.config(background = "#000000") self.display_region.grid(row=0, column=0) class MainFrame(tk.Frame): page_main_menu = None page_create_experiment = None page_start_experiment = None page_show_stimuli = None def __init__(self, *args, **kwargs): tk.Frame.__init__(self, *args, **kwargs) #self.buttonframe = tk.Frame(main_frame, background = settings_dict['backcolor']) self.config(background = settings_dict['backcolor']) def prepare_display(self): #Pages self.page_main_menu = Page_Main_Menu(self, width = width, height = height, background = settings_dict['backcolor']) self.page_create_experiment = Page_Create_Experiment(self, width = width, height = height, background = settings_dict['backcolor']) self.page_start_experiment = Page_Start_Experiment(self, width = width, height = height, background = settings_dict['backcolor']) self.page_show_stimuli = Page_Show_Stimuli(self, width = width, height = height, background = settings_dict['backcolor']) #Container container = tk.Frame(self, background = settings_dict['backcolor']) container.pack(side="top", fill="both", expand=True) #Place pages in the container frame self.page_main_menu.place(in_=container) self.page_create_experiment.place(in_=container) self.page_start_experiment.place(in_=container) self.page_show_stimuli.place(in_=container) #Show the main menu self.page_main_menu.show() def select_main_menu(self): self.set_fullscreen_exclusive(False) self.page_main_menu.lift() self.page_create_experiment.lower() self.page_start_experiment.lower() self.page_show_stimuli.lower() def select_create_experiment(self): self.set_fullscreen_exclusive(False) self.page_create_experiment.lift() self.page_main_menu.lower() self.page_start_experiment.lower() self.page_show_stimuli.lower() def select_start_experiment(self): self.set_fullscreen_exclusive(False) self.page_start_experiment.lift() self.page_create_experiment.lower() self.page_main_menu.lower() self.page_show_stimuli.lower() def select_show_stimuli(self): self.set_fullscreen_exclusive(True) self.page_show_stimuli.lift() self.page_main_menu.lower() self.page_create_experiment.lower() self.page_start_experiment.lower() def set_fullscreen_exclusive(self, fullscreen_exclusive): window.attributes('-fullscreen', fullscreen_exclusive) ''' This code starts program execition. The entire program is run in a try-except statement so that, should any error occur: The program can write out the error to the command line The program can still run on on_close() function to try to clean up all resources The logger is not used here since, among the possible errors that could cause a crash is the logger not having write permissions and it is still important the the failure be printed to a readable output. ''' try: main() except Exception as e: trace = traceback.format_exc() print('Something bad happened ' + str(e) + '\n' + str(trace)) on_close(False) raise
import cv2 import tkinter as tk from tkinter import filedialog import threading import traceback import sys import logging import os import time from PIL import Image, ImageTk import abc import json ''' Program data global variables ''' #backend logger = None #experiment data webcam_num = 1 study_name = '' study_files = [] subject_id_entry_box = None experiment = None #recording window = None recorder = None just_started = True #files out_dir = None video_path = None video_id = None last_video_id = None #tk ui main_frame = None pop_up_window = None width = 0 height = 0 key_tracker = None padding_x = 10 padding_y = 10 default_font = 20 #Settings settings_dict_defaults = {'backcolor': '#000000', 'ui_element_color': '#888888', 'forecolor': '#000000', 'draggable_color0': '#888888', 'draggable_color1': '#aaaaaa'} settings_dict = {} ''' Initialization ''' def main(): ''' First method called in this thread of program execution. Runs through a servies of initialization steps and then loads the gui. Once the gui is loaded, the gui takes over control of program execution from there onwards. ''' init_logging() load_config() init_gui() def init_logging(): ''' Initializes the loggins system. The logging system is intended to allow the program to save data about each run to disk, and the logger itself will re-write any existing logs each time so as to conserve space and avoid cluttering the running directory with files. This method also triggers the first log write. Most methods in this program trigger a log call. For simplicity, the calls to logging are not mentioned in the method descriptions in general. ''' global logger logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) file_handler = logging.FileHandler('SignRecorder.log', mode='w') logger.addHandler(file_handler) file_handler_format = logging.Formatter('%(levelname)s - %(asctime)s - %(message)s') file_handler.setFormatter(file_handler_format) logger.info('init_logging: Starting log') def load_config(): ''' Loads the user settings from the config.csv file. If the file is not pressent or is corrputed, it will use default values and write a new config file, overwritting the old one if it is present. ''' global settings_dict logger.info('load_config:') try: with open('config.json', 'r') as config: settings_dict = json.loads(config.read()) except Exception as err: message = 'load_config: Could not read config file' logger.error(message + ': ' + str(err)) recover_config_file() def recover_config_file(): ''' This method should only be called if the config file is corrupted or missing. It re-writes the config data and replaces all data with the default values, or the last loaded non-corrupt data value if such a data value is present. If this operations fails, the program will continue to run, but no config file will be generated. ''' global settings_dict logger.info('recover_config_file: loading default settings and attempting to recover the config file') settings_dict = settings_dict_defaults try: with open('config.json', 'w') as config: print(json.dumps(settings_dict_defaults), file=config) except Exception as err: message = 'Attempt to recover config file failed: Could not write new config file' logger.critical('recover_config_file:' + message + ': ' + str(err)) pop_up(message) def find_webcams(search_num): ''' Searches to see how many webcams are attactched to the current system. This is done by attempting to open each webcam from number 0 (the default webcam) to number search_num, which is given to the method. If the webcam opens, then the program knows it has found a wewbcam; if not, the webcam either cannot be accessed by the program or is not present. All opened webcams are closed after searching, and not webcam inpout is recorded at this step. Parameters: search_num: The number of webcams for which to search ''' global webcam_num webcam_num = 0 for i in range(search_num): webcam_i = cv2.VideoCapture(i) if webcam_i.isOpened(): webcam_num += 1 webcam_i.release() logger.info('find_webcams: ' + str(webcam_num) + ' webcams found for recording') def init_gui(): ''' Initializes the gui. The gui is created in a maximized state and takes over main-thread program execution. Note that all gui operations should remain on the main thread, except where the gui allows (suchs as in triggered events). This method also sets up the key_tracker to manage keypress events and attempt to authenticate them (since some OS's will trigger a key press and / or release repeatedly when a key is help down). The gui also maps the default close event (~the red X) to an ooperations that cleans up the program state properly. This should help to prevent memory leaks on an unexpected closure. ''' global width, height, window, key_tracker, main_frame logger.info('init_gui:') #Master window window = tk.Tk() window.wm_title('Sign Recorder') window.config(background = settings_dict['backcolor']) width = window.winfo_screenwidth() height = window.winfo_screenheight() window.geometry("%dx%d+0+0" % (width, height)) #Main Frame in window main_frame = MainFrame(window, background = settings_dict['backcolor']) main_frame.prepare_display() main_frame.pack(side="top", fill="both", expand=True) #input key_tracker = KeyTracker() window.bind_all('<KeyPress>', key_tracker.report_key_press) window.bind_all('<KeyRelease>', key_tracker.report_key_release) key_tracker.track('space') #Exitting window.protocol("WM_DELETE_WINDOW", on_close) #Show window window.mainloop() ''' Core backend program functionality ''' def pop_up(message): ''' Creates a pop-up window to display a message. Please only call this method for important errors such as files that fail to load--each pop up will take focue from the main window and thus disrupt the user. ''' global pop_up_window logger.info('pop_up: message=' + message) pop_up_window = tk.Tk() pop_up_window.wm_title('Message') pop_up_window.config(background = settings_dict['backcolor']) pop_up_text = tk.Text(pop_up_window, font = default_font, height = 5, width = 70, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) pop_up_text.insert(tk.INSERT, message) pop_up_text.config(state = 'disabled') pop_up_text.grid(row = 0, column = 0, padx = padding_x, pady = padding_y) select_files_button = tk.Button(pop_up_window, text ="Close", command = pop_up_window.destroy, font = default_font, height = 3, width = 10, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) select_files_button.grid(row=1, column=0) def write_out(name, message): ''' Writes out a meta-file that contains metadata about the recorded video. The data is: stimulus_name: the name of the file used as a stimulus for this recording display_time: the amount of time the stimulus was displayed before recording recording_time: the time length of the recording total_time: the total time for this step of the experiment, = display_time + recording_time ''' logger.info('write_out: writing meta file at path=' + out_dir + ' with name=' + name) file_name = os.path.join(out_dir, name + '.meta.csv') try: if os.path.exists(file_name): message = 'Cannot overwrite existing meta file: ' logger.critical('write_out: ' + message + file_name) pop_up(message + '\n' + file_name) raise Exception(message + file_name) with open(file_name, 'w') as meta: print(message, file=meta) except Exception as err: message = 'Failed to write out file: ' + file_name logger.critical('write_out: ' + message + ': ' + str(err)) pop_up(message) raise Exception(message) def on_close(close = True): ''' Handles properly closing the program and its spawned resources. As much as possible, all close events should be routed to this method rather than immediately calling an exit function. Parameter: close: Whether this method should close the program. If false, all program resources still will be cleared but the program will not be closed. This should be done when a critical exception occurs so the exception can still be raised. ''' logger.info('on_close: Cleaning resources and closing' if close else 'on_close: Cleaning resources to prepare for closing') window.destroy() try: recorder.end() except: pass if close: sys.exit(0) ''' Experiment and data collection ''' def on_key_press(event): ''' Called whenever a key press event is detected. This method should not be linked to key press events directly; the use of the KeyTracker class is necessary to authenticate key presses as valid before attempting to respond to them. If this program has just started, the program runs a different method to respond to the key press event to manage the yet un-initialized variables. ''' experiment.on_input_press(event.keysym) def on_key_release(event): ''' Called whenever a key release event is detected. This method should not be linked to key release events directly; the use of the KeyTracker class is necessary to authenticate key releases as valid before attempting to respond to them. ''' experiment.on_input_release(event.keysym) class Experiment(abc.ABC): @abc.abstractmethod def on_input_press(self, input_key): pass @abc.abstractmethod def on_input_release(self, input_key): pass class Naming_Experiment(Experiment): #Experiment Parameters stimuli = [] subject_id = None stimulus_type = None #Experiment Running recording = False last_video_id = None video_id = None keep_displaying = True current_stimulus = 0 can_start_recording = True data = '' #Timing display_timer = None recording_timer = None def __init__(self, data): ''' Creates a new Naming_Experiment, which is an experiemnt in which single stimuli are presented and the subject is asked to produce the sign for what is shown. Parameters: data: A dictionary containing experiment data. This should contain the follwoing keys: file, containing absolute paths to all of the stimuli to use; stimulus_type, which tells whether the stimulus is Image or Video ''' self.stimuli = data['stimulus_files'] self.stimulus_type = data['stimulus_type'] self.display_timer = Timer() self.recording_timer = Timer() def on_input_press(self, input_key): ''' This method should be called every time space is pressed (if that space-press has been authenticated). It proceeds to the next stimulus and will begin recording, ending the current stimulus and recording. It also ends the recording_timer if it was running, and updates program state tracking variables to refect the current state of the progam. If there are no more stimuli to run, the program displays a pop-up message stating that data collection is complete. ''' logger.info('Naming_Experiment: on_input_press: current_stimulus=' + str(self.current_stimulus) + ' recording=' + str(self.recording)) self.recording = False if self.recording_timer.active(): self.recording_timer.end() self.data += str(self.current_stimulus) + '_' + '_recordingTime,' + str(self.recording_timer.timespan) + '\n' if self.current_stimulus >= len(self.stimuli): message = 'All data for ' + str(self.subject_id) + ' has been collected' write_out(self.subject_id + '_timing.csv', self.data) pop_up(message) logger.info('Naming_Experiment: on_input_press: ' + message) main_frame.select_start_experiment() self.reset_for_next_subject() else: self.load_stimulus() def on_input_release(self, input_key): ''' This method should be called when space is released (if that release has been authenticated). It begins recording and starts the recording timer. It also updates program state tracking variables to refect the current state of the progam. ''' if self.subject_id == None: self.subject_id = subject_id_entry_box.get().strip() if self.can_start_recording and self.current_stimulus < len(self.stimuli): logger.info('Naming_Experiment: on_input_release: current_stimulus=' + str(self.current_stimulus) + '; recording starting') self.last_video_id = self.video_id self.video_id = os.path.basename(self.stimuli[self.current_stimulus].strip()) self.recording = True self.keep_displaying = False self.recording_timer.begin() self.current_stimulus += 1 recorder = Recorder(self.subject_id + '-' + self.video_id, True) recorder.begin() else: logger.warning('Naming_Experiment: on_input_release: can_start_recording is False, video must end before the signer may be recorded') def load_stimulus(self): ''' Loads and displays the next stimulis for the current subject, but should not be used for the first stimulus of a subjecct. It resets the display timer, which measures the time that a stimulus is displayed before signing. Later, it will also write timer output to a meta file with the same name as the output file. Timer data it not yet verified though, so it is not ready for use. ''' global keep_displaying logger.info('Naming_Experiment: load_stimulus: current_stimulus=' + str(self.current_stimulus) + ' stimulus type=' + str(self.stimulus_type)) keep_displaying = True stimulus = self.stimuli[self.current_stimulus].strip() if self.display_timer.active(): self.display_timer.end() self.data += str(self.current_stimulus) + '_' + '_displayTime,' + str(self.display_timer.timespan) + '\n' if self.stimulus_type == 'Image': self.display_timer.begin() Image_Displayer(stimulus).begin() elif self.stimulus_type == 'Video': self.display_timer.begin() Video_Displayer(stimulus).begin() def reset_for_next_subject(self): ''' Resets the environment so that the next subject can begin the experiment. ''' logger.info('Naming_Experiment: reset_for_next_subject: Resetting the environment for the next subject') key_tracker.reset() self.subject_id = None self.recording = False self.last_video_id = None self.video_id = None self.keep_displaying = True self.current_stimulus = 0 self.can_start_recording = True subject_id_entry_box.delete(0, last='end') class Lexical_Priming_Experiment(Experiment): #Experiment Parameters stimuli_tuples = [] subject_id = None stimulus_type = None primer_type = None primer_time = 5 #Experiment Running recording = False last_video_id = None video_id = None keep_displaying = True current_round = 0 can_start_recording = True display_primer = True #Timing display_timer = None recording_timer = None primer_timer = None def __init__(self, data): ''' Creates a new Lexical_Priming_Experiment, in which there is a primer image followed by a stimulus for signing. Recording begins after the stimulus has been shown. Transition between the primer and stimulus is done using space, as is transition between the stimulus and the recording, etc. Parameters: data: A dictionary containing experiment data. This should contain the follwoing keys: files, which contains a tuple of: (absolute path of the primer, that of the stimulus); stimulus_type, which tells whether the stimulus is Image or Video; primer_type, which tells whether the primer is Image or Video; primer_time, which contains the time to show the primer (in seconds, only needed if primer_time is Image) ''' self.stimuli_tuples = data['files'] self.stimulus_type = data['stimulus_type'] self.primer_type = data['primer_type'] self.primer_time = data['primer_time'] if self.primer_type == 'Image' else 0 self.display_timer = Timer() self.recording_timer = Timer() self.prim_timers = Timer() def on_input_press(self, input_key): ''' This method should be called every time space is pressed (if that press has been authenticated), except the first. It proceeds to the next stimulus and will begin recording, ending the current stimulus and recording. It also ends the recording_timer if it was running, and updates program state tracking variables to refect the current state of the progam. If there are no more stimuli to run, the program displays a pop-up message stating that data collection is complete. ''' logger.info('Lexical_Priming_Experiment: on_input_press: current_stimulus=' + str(self.current_round) + ' recording=' + str(self.recording) + ', display_primer=' + self.display_primer) if self.display_primer: pass else: self.recording = False if self.recording_timer.active(): self.recording_timer.end() if self.current_round >= len(self.stimuli_tuples): main_frame.select_start_experiment() pop_up('All data for ' + self.subject_id + ' has been collected') self.reset_for_next_subject() else: self.load_primer() def on_input_release(self, input_key): ''' This method should be called when space is released (if that release has been authenticated). It begins recording and starts the recording timer. It also updates program state tracking variables to refect the current state of the progam. ''' if self.display_primer: self.display_primer = False #code here else: if self.subject_id == None: self.subject_id = subject_id_entry_box.get().strip() if self.can_start_recording and self.current_round < len(self.stimuli_tuples): logger.info('Lexical_Priming_Experiment: on_input_release: current_round=' + str(self.current_round) + '; recording starting') self.last_video_id = self.video_id self.video_id = os.path.basename(self.stimuli_tuples[self.current_round][0].strip()) + '-' + os.path.basename(self.stimuli_tuples[self.current_round][1].strip()) self.recording = True self.keep_displaying = False self.recording_timer.begin() self.current_round += 1 recorder = Recorder(self.subject_id + '-' + self.video_id, True) recorder.begin() else: logger.warning('Naming_Experiment: on_input_release: can_start_recording is False, video must end before the signer may be recorded') def load_primer(self): #WHat about stimuli? ''' Loads and displays the next stimulus for the current subject, but should not be used for the first stimulus of a subjecct. It resets the display timer, which measures the time that a stimulus is displayed before signing. Later, it will also write timer output to a meta file with the same name as the output file. Timer data it not yet verified though, so it is not ready for use. ''' global keep_displaying logger.info('Lexical_Priming_Experiment: load_stimulus: current_stimulus=' + str(self.current_round) + ' stimulus type=' + str(self.stimulus_type)) keep_displaying = True primer = self.stimuli_tuples[self.current_round][0].strip() timer = None if self.display_timer.active(): self.display_timer.end() if self.primer_type == 'Image': self.display_timer.begin() Image_Displayer(primer).begin() timer = threading.Timer(self.primer_time, self.on_primer_finished) #In seconds elif self.primer_type == 'Video': self.display_timer.begin() Video_Displayer(primer).begin() timer = threading.Timer(self.primer_time, self.on_primer_finished) #In seconds timer.start() def on_primer_finished(self): stimulus = self.stimuli_tuples[self.current_round][1].strip() if self.stimulus_type == 'Image': self.display_timer.begin() Image_Displayer(stimulus).begin() elif self.stimulus_type == 'Video': self.display_timer.begin() Video_Displayer(stimulus).begin() def reset_for_next_subject(self): ''' Resets the environment so that the next subject can begin the experiment. ''' logger.info('Lexical_Priming_Experiment: reset_for_next_subject: Resetting the environment for the next subject') key_tracker.reset() self.subject_id = None self.recording = False self.last_video_id = None self.video_id = None self.keep_displaying = True self.current_stimulus = 0 self.can_start_recording = True subject_id_entry_box.delete(0, last='end') ''' Data and user-input ''' class Recorder(): ''' This class handles all recording using the webcam, and writes recrodings to disk. ''' name = '' mirror = False web_cam = None video_writer = None def __init__(self, name, mirror): ''' Initializes the Recorder. Parameters: name: The name to five to the recording file mirror: Whether the recording should be mirrored when saved to disk ''' logger.info('Recorder: __init__: name=' + self.name + ' mirror=' + str(mirror)) self.name = name self.mirror = mirror def begin(self): ''' Begins recording from the webcam. The recording will continue untill end is called, or until 1 is pressed. Note that pressing 1 to quit should be used for debug purposes only ''' # Capturing video from webcam: self.web_cam = cv2.VideoCapture(0) fps = self.web_cam.get(cv2.CAP_PROP_FPS) #get width and height of reading frame width = int(self.web_cam.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(self.web_cam.get(cv2.CAP_PROP_FRAME_HEIGHT)) # Define the codec and fourcc = cv2.VideoWriter_fourcc(*"XVID") #create VideoWriter object file_name = os.path.join(out_dir, self.name + '.avi') if os.path.exists(file_name): message = 'Cannot overwrite existing video file: ' logger.critical('Recorder: begin: ' + message + file_name) pop_up(message + '\n' + file_name) raise Exception(message + file_name) else: self.video_writer = cv2.VideoWriter(file_name, fourcc, fps, (width, height)) if not self.web_cam.isOpened(): message = 'Could not open webcam' logger.warning('Recorder: begin: ' + message) pop_up(message) raise Exception(message) logger.info('Recorder: begin: starting recording loop') while self.web_cam.isOpened(): # Capture frame-by-frame is_reading, frame = self.web_cam.read() if is_reading and experiment.recording: if self.mirror: frame = cv2.flip(frame, 1) self.video_writer.write(frame) else: break if cv2.waitKey(1) & 0xFF == ord('1'): #quit on 1 experiment.on_input_release('space') break self.end() def end(self): ''' Ends the recording and releases resources. ''' logger.info('Recorder: end: recording ended, releasing resources') self.web_cam.release() self.video_writer.release() class Video_Displayer(): file_name = '' video_input = None fps = None display = None callback = None def __init__(self, file_name, callback = None): logger.info('Video_Displayer: __init__: file_name=' + file_name) self.file_name = file_name self.callback = callback def begin(self): experiment.can_start_recording = False self.video_input = cv2.VideoCapture(self.file_name) self.fps = int(self.video_input.get(cv2.CAP_PROP_FPS)) self.display = main_frame.page_show_stimuli.display_region logger.info('Video_Displayer: begin: ' + self.file_name + ' running at fps=' + str(int(self.fps))) if not self.video_input.isOpened(): message = 'Could not open video file for reading' logger.warning('Video_Displayer: begin: ' + message) pop_up(message) raise Exception(message) main_frame.select_show_stimuli() self.run_frame() def run_frame(self): #Get the next frame is_reading, frame = self.video_input.read() if is_reading: #Load the image for the current frame and convert to imagetk cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA) img = Image.fromarray(cv2image) img_width, img_height = get_proper_resize_dimensions_for_fullscreen(img) img = img.resize((int(img_width), int(img_height))) imgtk = ImageTk.PhotoImage(image=img) self.display.imgtk = imgtk self.display.configure(image=imgtk) if self.video_input.isOpened(): self.display.after(self.fps, self.run_frame) else: self.end('Video_Displayer: run_frame: display ended due to unexpected closure of video_input') experiment.can_start_recording = True if not self.callback == None: self.callback() else: self.end('Video_Displayer: run_frame: display ended naturally') experiment.can_start_recording = True if not self.callback == None: self.callback() def end(self, message = 'Video_Displayer: end: run_frame ended'): logger.info(message) self.video_input.release() if not self.callback == None: self.callback() class Image_Displayer(): file_name = '' display = None def __init__(self, file_name): logger.info('Image_Displayer: __init__: ' + file_name) self.file_name = file_name def begin(self): logger.info('Image_Displayer: begin:') self.display = main_frame.page_show_stimuli.display_region main_frame.select_show_stimuli() #Load the image for the current frame and convert to imagetk cv2image = cv2.imread(self.file_name) b,g,r = cv2.split(cv2image) cv2image = cv2.merge((r,g,b)) img = Image.fromarray(cv2image) img_width, img_height = get_proper_resize_dimensions_for_fullscreen(img) img = img.resize((int(img_width), int(img_height))) imgtk = ImageTk.PhotoImage(image=img) # Put it in the display window self.display.imgtk = imgtk self.display.configure(image=imgtk) class KeyTracker(): key = '' last_press_time = 0 last_release_time = 0 last_release_callback_time = 0 first_callback_call = True last_event_was_press = False def track(self, key): logger.info('KeyTracker: track: key=' + key) self.key = key def reset(self): logger.info('KeyTracker: reset: resetting') self.last_press_time = 0 self.last_release_time = 0 self.last_release_callback_time = 0 self.first_callback_call = True self.last_event_was_press = False def is_pressed(self): return time.time() - self.last_press_time < .01 #In seconds def report_key_press(self, event): if not self.last_event_was_press and event.keysym == self.key: self.last_event_was_press = True if not self.is_pressed(): logger.info('KeyTracker: report_key_press: valid keypress detected: key=' + self.key) self.last_press_time = time.time() on_key_press(event) else: self.last_press_time = time.time() def report_key_release(self, event): if self.last_event_was_press and event.keysym == self.key: self.last_event_was_press = False self.last_release_time = time.time() timer = threading.Timer(.015, self.report_key_release_callback, args=[event]) #In seconds timer.start() def report_key_release_callback(self, event): if self.first_callback_call: self.last_release_callback_time = time.time() self.first_callback_call = False if not self.is_pressed(): self.last_release_callback_time = time.time() logger.info('KeyTracker: report_key_release_callback: key=' + self.key + ', is released= ' + str((not self.is_pressed()))) if not self.is_pressed(): on_key_release(event) class Timer(): start_time = 0 end_time = 0 timespan = 0 def begin(self): self.start_time = time.time() def end(self): self.end_time = time.time() self.timespan = self.end_time - self.start_time def active(self): return self.start_time > self.end_time ''' UI and layout management ''' def arrange_header_in(page): button_frame = page.button_frame top_bar_buttons = [] #Place buttons in the top-level button frame top_bar_buttons.append(tk.Button(button_frame, text="Main Menu", font=default_font, command=main_frame.select_main_menu, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor'])) top_bar_buttons.append(tk.Button(button_frame, text="Create Experiment", font=default_font, command=main_frame.select_create_experiment, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor'])) top_bar_buttons.append(tk.Button(button_frame, text="Start Experiment", font=default_font, command=main_frame.select_start_experiment, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor'])) #Grid buttons col = 0 for button in top_bar_buttons: button.grid(row=0, column=col, pady=10) col += 1 button_frame.grid(row=0, column=0) def get_proper_resize_dimensions_for_fullscreen(img): ''' This method gets the largest-area resize of an image to be displayed on a fullscreen display without allowing any of the image to overflow off-screen. It maintains the image aspect ratio. ''' #Get image dimensions original_width = img.width original_height = img.height #Get the scalars that transform the original size into the fullscreen dize width_scalar = width / original_width height_scalar = height / original_height #Our goal is to make the image as largs as possible without goinf over the screen size. #We also do not want to loose out aspect ratio. So let's see whether using the width_scalar # or the height_scalar does that best width_based_scaling_height = original_height * width_scalar width_based_scaling_valid = True if width_based_scaling_height > height: width_based_scaling_valid = False height_based_scaling_width = original_width * height_scalar height_based_scaling_valid = True if height_based_scaling_width > width: height_based_scaling_valid = False if width_based_scaling_valid and not height_based_scaling_valid: return width, width_based_scaling_height else: return height_based_scaling_width, height class Widget_Drag_Controller(): ''' This class handles dragging widgets that below to a common set in such a way as to change their positions in that set. So if the numbers 1, 2, 3 are shown on screen, it's goal is to allow you to click on, say, the 3 and move it in from of the one, and then to read back that array in the new order. ''' item = None callback = None move_frame = None def __init__(self, item, widgets, callback): ''' Parameters: item: The specific item out of the set that can be dragged widgets: The set of all widgets that are ordered on the screen and can be dragged callback: the function to call after a drag and drop. It should accept a list of files in the new order as a parameter. ''' self.item = item self.widgets = widgets self.callback = callback #Bind clicks on the item itself self.item.bind("<ButtonPress-1>", self.on_start) self.item.bind("<B1-Motion>", self.on_move) self.item.bind("<ButtonRelease-1>", self.on_end) self.item.configure(cursor="hand1") def on_start(self, event): print('on_start') self.last_seen = self.item self.move_frame = tk.Frame() tk.Label(self.move_frame, text = self.item.cget('text'), font = self.item.cget('font'), anchor = self.item.cget('anchor'), background = self.item.cget('background')).pack(side = 'top', fill = 'x') def on_move(self, event): print('on_move') x, y = event.widget.winfo_pointerxy() self.move_frame.place(x = x, y = int(y - (self.item.winfo_height() + self.item.winfo_height() / 2))) def on_end(self, event): print('on_end') self.move_frame.destroy() x, y = event.widget.winfo_pointerxy() target = event.widget.winfo_containing(x, y) move_to = self.widgets.index(target) move_from = self.widgets.index(self.item) if move_to > move_from: self.widgets.insert(move_to + 1, self.item) del self.widgets[move_from] elif move_to < move_from: self.widgets.insert(move_to, self.item) del self.widgets[move_from + 1] files = [widget.cget('text') for widget in self.widgets] self.callback(files) class File_Arrangement_Region(): canvas = None display_frame = None elements = [] width = 0 height = 0 owner = None widget_drag_controllers = [] owner_update_callback = None def __init__(self, owner, owner_update_callback, root, width, height, row, column, rowspan = 1, columnspan = 1): self.owner_update_callback = owner_update_callback self.width = width self.height = height self.owner = owner outer_frame = tk.Frame(root, background = settings_dict['ui_element_color']) outer_frame.grid(row = row, column = column, rowspan = rowspan, columnspan = columnspan, padx=padding_x, pady=padding_y) self.canvas = tk.Canvas(outer_frame, background = settings_dict['ui_element_color']) self.display_frame = tk.Frame(self.canvas, background = settings_dict['ui_element_color']) scrollbar_y = tk.Scrollbar(outer_frame, orient = 'vertical',command = self.canvas.yview) scrollbar_x = tk.Scrollbar(outer_frame, orient = 'horizontal',command = self.canvas.xview) self.canvas.configure(yscrollcommand = scrollbar_y.set) self.canvas.configure(xscrollcommand = scrollbar_x.set) scrollbar_y.pack(side = 'right',fill = 'y') scrollbar_x.pack(side = 'bottom', fill = 'x') self.canvas.pack(side = 'left') self.canvas.create_window((0, 0), window = self.display_frame, anchor = 'nw') self.display_frame.bind('<Configure>', self.scroll_configure) def scroll_configure(self, event): self.canvas.configure(scrollregion = self.canvas.bbox('all'), width = self.width, height = self.height) def set_elements(self, files): #Remove old elements self.widget_drag_controllers.clear() for child in self.display_frame.winfo_children(): child.destroy() #Add new elements (OLD) for i in range(len(files)): highlight = settings_dict['draggable_color' + str(i % 2)] tk.Label(self.display_frame, text=files[i], font = default_font, anchor = 'w', background = highlight).pack(side = 'top', fill = 'x') for label in self.display_frame.winfo_children(): print(label); self.widget_drag_controllers.append(Widget_Drag_Controller(label, self.display_frame.winfo_children(), self.update_owner_data)) '''#Add new elements for i in range(len(files)): highlight = settings_dict['draggable_color' + str(i % 2)] container = tk.Frame(self.display_frame, width = width, height = int(height / 1.25), background = highlight) label = tk.Label(container, text=files[i], font = default_font, anchor = 'w', background = highlight) label.pack(side = 'left') remove_button = tk.Button(container, text ="-", command = self.on_button_remove, font = default_font, height = 1, width = 3, background = highlight, foreground = settings_dict['forecolor']) remove_button.pack(side = 'right') label.bindtags(("draggable",) + label.bindtags()) container.pack(side = 'top', fill = 'x') for element in self.display_frame.winfo_children(): print(element); self.widget_drag_controllers.append(Widget_Drag_Controller(element, self.display_frame.winfo_children(), self.update_owner_data))''' def on_button_remove(self): pass def update_owner_data(self, files): self.owner_update_callback(files) class Page(tk.Frame): button_frame = None def __init__(self, *args, **kwargs): tk.Frame.__init__(self, *args, **kwargs) self.button_frame = tk.Frame(self, background = settings_dict['backcolor']) def show(self): print('Show') print(self) self.lift() class Page_Main_Menu(Page): def __init__(self, *args, **kwargs): Page.__init__(self, *args, **kwargs) self.init_elements() def init_elements(self): about_text = ''' Version: 0.2.1beta Developer: <NAME> SignRecorder is a simple program for recording and saving video files for sign language data collection and experiments. It is currently hosted on GitHub (https://github.com/Jeffrey-Sardina/SignRecorder) as an open-source project. To get started, click on either 'Create Experiemnt' or 'Start Experiment'. The program will guide you through loading stimuli and experimental methods. Once you have made an experiemnt, save it so that you can load it later. ''' arrange_header_in(self) file_text = tk.Text(self, font = default_font, height = 15, width = 70, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) file_text.insert(tk.INSERT, about_text) file_text.config(state = 'disabled') file_text.grid(row=1, column=0, padx=padding_x, pady=padding_y) class Page_Naming_Paradigm(Page): file_arrangement_region = None stimulus_option_selected = None num_rows = 0 def __init__(self, *args, **kwargs): Page.__init__(self, *args, **kwargs) self.init_elements() def init_elements(self): stimulus_text = tk.Text(self, font = default_font, height = 3, width = 70, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) stimulus_text.insert(tk.INSERT, '\nSelect Stimulus Type') stimulus_text.tag_configure("center", justify='center') stimulus_text.tag_add("center", 1.0, "end") stimulus_text.config(state = 'disabled') stimulus_text.grid(row=0, column=0, padx=padding_x, pady=padding_y) self.num_rows += 1 stimulus_options = ['Video', 'Image'] stimulus_default_option = stimulus_options[0] self.stimulus_option_selected = tk.StringVar(self) stimulus_option_menu = tk.OptionMenu(self, self.stimulus_option_selected, *stimulus_options) self.stimulus_option_selected.set(stimulus_default_option) stimulus_option_menu.config(background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor'], height = 1, width = 30, font = default_font) stimulus_option_menu.grid(row=1, column=0, padx=padding_x, pady=padding_y) self.num_rows += 1 select_files_button = tk.Button(self, text ="Select Stimulus Files", command = self.load_files, font = default_font, height = 1, width = 30, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) select_files_button.grid(row=2, column=0, padx=padding_x, pady=padding_y) self.num_rows += 1 self.file_arrangement_region = File_Arrangement_Region(self, self.change_files, self, width / 2, height / 1.5, 0, 1, 20) self.file_arrangement_region.set_elements(['Selected Files:']) def load_files(self): logger.info('Page_Naming_Paradigm: load_files: loading files') self.files = filedialog.askopenfilenames(parent=self, initialdir="/", title='Select Files' + self.stimulus_option_selected.get() + ' files') display_strs = self.files self.file_arrangement_region.set_elements(display_strs) def change_files(self, files): self.files = files self.file_arrangement_region.set_elements(self.files) def dict_data(self): data = {} data['paradigm'] = 'Naming' data['stimulus_type'] = self.stimulus_option_selected.get() data['stimulus_files'] = self.files return data class Page_Lexical_Priming(Page): stimulus_file_arrangement_region = None primer_file_arrangement_region = None stimulus_option_selected = None primer_option_selected = None stimulus_files = [] primer_files = [] num_rows = 0 def __init__(self, *args, **kwargs): Page.__init__(self, *args, **kwargs) self.init_elements() def init_elements(self): stimulus_text = tk.Text(self, font = default_font, height = 3, width = 70, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) stimulus_text.insert(tk.INSERT, '\nSelect Stimulus Type') stimulus_text.tag_configure("center", justify='center') stimulus_text.tag_add("center", 1.0, "end") stimulus_text.config(state = 'disabled') stimulus_text.grid(row=0, column=0, padx=padding_x, pady=padding_y) self.num_rows += 1 stimulus_options = ['Video', 'Image'] stimulus_default_option = stimulus_options[0] self.stimulus_option_selected = tk.StringVar(self) stimulus_option_menu = tk.OptionMenu(self, self.stimulus_option_selected, *stimulus_options) self.stimulus_option_selected.set(stimulus_default_option) stimulus_option_menu.config(background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor'], height = 1, width = 30, font = default_font) stimulus_option_menu.grid(row=1, column=0, padx=padding_x, pady=padding_y) self.num_rows += 1 primer_text = tk.Text(self, font = default_font, height = 3, width = 70, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) primer_text.insert(tk.INSERT, '\nSelect Primer Type') primer_text.tag_configure("center", justify='center') primer_text.tag_add("center", 1.0, "end") primer_text.config(state = 'disabled') primer_text.grid(row=2, column=0, padx=padding_x, pady=padding_y) self.num_rows += 1 primer_options = ['Video', 'Image'] primer_default_option = primer_options[0] self.primer_option_selected = tk.StringVar(self) primer_option_menu = tk.OptionMenu(self, self.primer_option_selected, *primer_options) self.primer_option_selected.set(primer_default_option) primer_option_menu.config(background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor'], height = 1, width = 30, font = default_font) primer_option_menu.grid(row=3, column=0, padx=padding_x, pady=padding_y) self.num_rows += 1 stimulus_select_files_button = tk.Button(self, text ="Select Stimulus Files", command = self.load_stimulus_files, font = default_font, height = 1, width = 30, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) stimulus_select_files_button.grid(row=4, column=0, padx=padding_x, pady=padding_y) self.num_rows += 1 self.stimulus_file_arrangement_region = File_Arrangement_Region(self, self.change_stimulus_files, self, width / 4, height / 1.5, 0, 1, 20) self.stimulus_file_arrangement_region.set_elements(['Selected Files:']) primer_select_files_button = tk.Button(self, text ="Select Primer Files", command = self.load_primer_files, font = default_font, height = 1, width = 30, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) primer_select_files_button.grid(row=5, column=0, padx=padding_x, pady=padding_y) self.num_rows += 1 self.primer_file_arrangement_region = File_Arrangement_Region(self, self.change_primer_files, self, width / 4, height / 1.5, 0, 2, 20) self.primer_file_arrangement_region.set_elements(['Selected Files:']) def load_stimulus_files(self): self.load_files(True) def load_primer_files(self): self.load_files(False) def load_files(self, is_stimulus): logger.info('Page_Lexical_Priming: load_files: loading files, is_stimulus=' + str(is_stimulus)) if is_stimulus: self.stimulus_files = filedialog.askopenfilenames(parent=self, initialdir="/", title='Select Stimulus Files' + self.stimulus_option_selected.get() + ' files') self.stimulus_file_arrangement_region.set_elements(self.stimulus_files) else: self.primer_files = filedialog.askopenfilenames(parent=self, initialdir="/", title='Select Primer Files' + self.primer_option_selected.get() + ' files') self.primer_file_arrangement_region.set_elements(self.primer_files) def change_stimulus_files(self, files): self.stimulus_files = files self.stimulus_file_arrangement_region.set_elements(self.stimulus_files) def change_primer_files(self, files): self.primer_files = files self.primer_file_arrangement_region.set_elements(self.primer_files) def dict_data(self): primers = self.primer_option_selected.get() stimuli = self.stimulus_files if len(primers) != len(stimuli): message = 'Cannot write file: There must be a 1:1 mapping of primers to stimuli' logger.warning('Page_Lexical_Priming: dict_data: ' + message) pop_up(message) return [] data = {} data['paradigm'] = 'Lexical_Priming' data['files'] = [(primer, stimulus) for primer in primers for stimulus in stimuli] data['stimulus_type'] = self.stimulus_option_selected.get() return data class Page_Create_Experiment(Page): files = [] option_selected = None paradigm_option_selected = None entry = None selected_files_info_text = None page_naming_paradigm = None page_lexical_priming = None create_experiment_button = None def __init__(self, *args, **kwargs): Page.__init__(self, *args, **kwargs) self.init_elements() def init_elements(self): arrange_header_in(self) self.page_naming_paradigm = Page_Naming_Paradigm(self, background = settings_dict['backcolor']) self.page_lexical_priming = Page_Lexical_Priming(self, background = settings_dict['backcolor']) paradigm_text = tk.Text(self, font = default_font, height = 3, width = 70, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) paradigm_text.insert(tk.INSERT, '\nSelect Experiemnt Paradigm') paradigm_text.tag_configure("center", justify='center') paradigm_text.tag_add("center", 1.0, "end") paradigm_text.config(state = 'disabled') paradigm_text.grid(row=1, column=0, padx=padding_x, pady=padding_y) paradigm_options = ['Naming', 'Lexcial Priming'] default_paradigm_option = paradigm_options[0] self.paradigm_option_selected = tk.StringVar(self) self.paradigm_option_selected.trace('w', self.paradigm_selected) paradigm_option_menu = tk.OptionMenu(self, self.paradigm_option_selected, *paradigm_options) self.paradigm_option_selected.set(default_paradigm_option) paradigm_option_menu.config(background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor'], height = 1, width = 30, font = default_font) paradigm_option_menu.grid(row=2, column=0, padx=padding_x, pady=padding_y) #Container container = tk.Frame(self, width = width, height = int(height / 1.25), background = settings_dict['backcolor']) container.grid(row=3, column=0, rowspan = 10, columnspan = 400, padx=0, pady=padding_y) #Place pages in the container frame self.page_naming_paradigm.place(in_=container) self.page_lexical_priming.place(in_=container) paradigm_option_string = self.paradigm_option_selected.get() if paradigm_option_string == 'Naming': self.page_naming_paradigm.show() elif paradigm_option_string == 'Lexcial Priming': self.page_lexical_priming.show() #Create Experiment Button self.create_experiment_button = tk.Button(self, text ="Create Experiment", command = self.create_experiment, font = default_font, height = 1, width = 30, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) self.create_experiment_button.grid(row = 1, column = 1, padx = padding_x, pady = padding_y) def create_experiment(self): logger.info('Page_Create_Experiment: create_experiment: creating experiment') paradigm_option_string = self.paradigm_option_selected.get() exp_data = None if paradigm_option_string == 'Naming': exp_data = self.page_naming_paradigm.dict_data() elif paradigm_option_string == 'Lexcial Priming': exp_data = self.page_lexical_priming.dict_data() data = {} data['paradigm'] = paradigm_option_string data.update(exp_data) try: experimant_name = filedialog.asksaveasfilename(initialdir = "/", title = "Save file", filetypes = (("experiment files","*.exp"), ("all files","*.*"))) with open(experimant_name, 'w') as experiment: print(json.dumps(data), file=experiment) except Exception as err: message = 'Error: Could not write experiment file' logger.error('Page_Create_Experiment: create_experiment: ' + message + ': ' + str(err)) pop_up(message) def paradigm_selected(self, name, index, mode): paradigm_option_string = self.paradigm_option_selected.get() logger.info('Page_Create_Experiment: paradigm_selected: paradigm_option_string=' + paradigm_option_string) if paradigm_option_string == 'Naming': pass #self.page_naming_paradigm.lift() #self.page_lexical_priming.lower() elif paradigm_option_string == 'Lexcial Priming': pass #self.page_lexical_priming.lift() #self.page_naming_paradigm.lower() class Page_Start_Experiment(Page): def __init__(self, *args, **kwargs): Page.__init__(self, *args, **kwargs) self.init_elements() def init_elements(self): global subject_id_entry_box arrange_header_in(self) file_text = tk.Text(self, font = default_font, height = 3, width = 70, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) file_text.insert(tk.INSERT, '\nSelect an experiment file to load') file_text.tag_configure("center", justify='center') file_text.tag_add("center", 1.0, "end") file_text.config(state = 'disabled') file_text.grid(row=1, column=0, padx=padding_x, pady=padding_y) select_file_button = tk.Button(self, text ="Choose file", command = self.load_experiment, font = default_font, height = 1, width = 30, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) select_file_button.grid(row=2, column=0, padx=padding_x, pady=padding_y) dir_text = tk.Text(self, font = default_font, height = 3, width = 70, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) dir_text.insert(tk.INSERT, '\nSelect a folder in which to save the output') dir_text.tag_configure("center", justify='center') dir_text.tag_add("center", 1.0, "end") dir_text.config(state = 'disabled') dir_text.grid(row=3, column=0, padx=padding_x, pady=padding_y) select_file_button = tk.Button(self, text ="Choose output folder", command = self.load_dir, font = default_font, height = 1, width = 30, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) select_file_button.grid(row=4, column=0, padx=padding_x, pady=padding_y) entry_text = tk.Text(self, font = default_font, height = 3, width = 70, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) entry_text.insert(tk.INSERT, '\nEnter subject ID') entry_text.tag_configure("center", justify='center') entry_text.tag_add("center", 1.0, "end") entry_text.config(state = 'disabled') entry_text.grid(row=5, column=0, padx=padding_x, pady=padding_y) subject_id_entry_box = tk.Entry(self, font = default_font, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) subject_id_entry_box.grid(row=6, column=0, padx=padding_x, pady=padding_y) how_to_string = ''' When you are ready to begin the experiment, press the space bar. Once you are ready to sign based on what you see, press the space bar to start recording. Once you are done signing, press the space bar again. You will then see the next prompt and the program will begin recording. ''' how_to_text = tk.Text(self, font = default_font, height = 9, width = 70, background = settings_dict['ui_element_color'], foreground = settings_dict['forecolor']) how_to_text.insert(tk.INSERT, how_to_string) how_to_text.config(state = 'disabled') how_to_text.grid(row=7, column=0, padx=padding_x, pady=padding_y) def load_dir(self): global out_dir logger.info('Page_Start_Experiment: load_dir: loading save folder') try: out_dir = filedialog.askdirectory(parent = self, initialdir="/", title='Select Save Folder') except Exception as err: message = 'Could not load the selected directory' logger.error('Page_Start_Experiment: load_dir: ' + message + ': ' + str(err)) pop_up(message) def load_experiment(self): global experiment logger.info('Page_Start_Experiment: load_experiment: loading experiment') experiment_file = filedialog.askopenfilename(parent=self, initialdir="/", title='Select Experiment') try: with open(experiment_file, 'r') as experiment_data: data = json.loads(experiment_data.read()) if data['paradigm'] == 'Naming': experiment = Naming_Experiment(data) elif data['paradigm'] == 'Lexical Priming': pass except Exception as err: message = 'Could not load experiment file' logger.error('Page_Start_Experiment: load_experiment:' + message + ': ' + str(err)) pop_up(message) class Page_Show_Stimuli(Page): display_region = None def __init__(self, *args, **kwargs): Page.__init__(self, *args, **kwargs) self.init_display_region() def init_display_region(self): self.display_region = tk.Label(self) self.display_region.config(background = "#000000") self.display_region.grid(row=0, column=0) class MainFrame(tk.Frame): page_main_menu = None page_create_experiment = None page_start_experiment = None page_show_stimuli = None def __init__(self, *args, **kwargs): tk.Frame.__init__(self, *args, **kwargs) #self.buttonframe = tk.Frame(main_frame, background = settings_dict['backcolor']) self.config(background = settings_dict['backcolor']) def prepare_display(self): #Pages self.page_main_menu = Page_Main_Menu(self, width = width, height = height, background = settings_dict['backcolor']) self.page_create_experiment = Page_Create_Experiment(self, width = width, height = height, background = settings_dict['backcolor']) self.page_start_experiment = Page_Start_Experiment(self, width = width, height = height, background = settings_dict['backcolor']) self.page_show_stimuli = Page_Show_Stimuli(self, width = width, height = height, background = settings_dict['backcolor']) #Container container = tk.Frame(self, background = settings_dict['backcolor']) container.pack(side="top", fill="both", expand=True) #Place pages in the container frame self.page_main_menu.place(in_=container) self.page_create_experiment.place(in_=container) self.page_start_experiment.place(in_=container) self.page_show_stimuli.place(in_=container) #Show the main menu self.page_main_menu.show() def select_main_menu(self): self.set_fullscreen_exclusive(False) self.page_main_menu.lift() self.page_create_experiment.lower() self.page_start_experiment.lower() self.page_show_stimuli.lower() def select_create_experiment(self): self.set_fullscreen_exclusive(False) self.page_create_experiment.lift() self.page_main_menu.lower() self.page_start_experiment.lower() self.page_show_stimuli.lower() def select_start_experiment(self): self.set_fullscreen_exclusive(False) self.page_start_experiment.lift() self.page_create_experiment.lower() self.page_main_menu.lower() self.page_show_stimuli.lower() def select_show_stimuli(self): self.set_fullscreen_exclusive(True) self.page_show_stimuli.lift() self.page_main_menu.lower() self.page_create_experiment.lower() self.page_start_experiment.lower() def set_fullscreen_exclusive(self, fullscreen_exclusive): window.attributes('-fullscreen', fullscreen_exclusive) ''' This code starts program execition. The entire program is run in a try-except statement so that, should any error occur: The program can write out the error to the command line The program can still run on on_close() function to try to clean up all resources The logger is not used here since, among the possible errors that could cause a crash is the logger not having write permissions and it is still important the the failure be printed to a readable output. ''' try: main() except Exception as e: trace = traceback.format_exc() print('Something bad happened ' + str(e) + '\n' + str(trace)) on_close(False) raise
en
0.868349
Program data global variables #backend #experiment data #recording #files #tk ui #Settings Initialization First method called in this thread of program execution. Runs through a servies of initialization steps and then loads the gui. Once the gui is loaded, the gui takes over control of program execution from there onwards. Initializes the loggins system. The logging system is intended to allow the program to save data about each run to disk, and the logger itself will re-write any existing logs each time so as to conserve space and avoid cluttering the running directory with files. This method also triggers the first log write. Most methods in this program trigger a log call. For simplicity, the calls to logging are not mentioned in the method descriptions in general. Loads the user settings from the config.csv file. If the file is not pressent or is corrputed, it will use default values and write a new config file, overwritting the old one if it is present. This method should only be called if the config file is corrupted or missing. It re-writes the config data and replaces all data with the default values, or the last loaded non-corrupt data value if such a data value is present. If this operations fails, the program will continue to run, but no config file will be generated. Searches to see how many webcams are attactched to the current system. This is done by attempting to open each webcam from number 0 (the default webcam) to number search_num, which is given to the method. If the webcam opens, then the program knows it has found a wewbcam; if not, the webcam either cannot be accessed by the program or is not present. All opened webcams are closed after searching, and not webcam inpout is recorded at this step. Parameters: search_num: The number of webcams for which to search Initializes the gui. The gui is created in a maximized state and takes over main-thread program execution. Note that all gui operations should remain on the main thread, except where the gui allows (suchs as in triggered events). This method also sets up the key_tracker to manage keypress events and attempt to authenticate them (since some OS's will trigger a key press and / or release repeatedly when a key is help down). The gui also maps the default close event (~the red X) to an ooperations that cleans up the program state properly. This should help to prevent memory leaks on an unexpected closure. #Master window #Main Frame in window #input #Exitting #Show window Core backend program functionality Creates a pop-up window to display a message. Please only call this method for important errors such as files that fail to load--each pop up will take focue from the main window and thus disrupt the user. Writes out a meta-file that contains metadata about the recorded video. The data is: stimulus_name: the name of the file used as a stimulus for this recording display_time: the amount of time the stimulus was displayed before recording recording_time: the time length of the recording total_time: the total time for this step of the experiment, = display_time + recording_time Handles properly closing the program and its spawned resources. As much as possible, all close events should be routed to this method rather than immediately calling an exit function. Parameter: close: Whether this method should close the program. If false, all program resources still will be cleared but the program will not be closed. This should be done when a critical exception occurs so the exception can still be raised. Experiment and data collection Called whenever a key press event is detected. This method should not be linked to key press events directly; the use of the KeyTracker class is necessary to authenticate key presses as valid before attempting to respond to them. If this program has just started, the program runs a different method to respond to the key press event to manage the yet un-initialized variables. Called whenever a key release event is detected. This method should not be linked to key release events directly; the use of the KeyTracker class is necessary to authenticate key releases as valid before attempting to respond to them. #Experiment Parameters #Experiment Running #Timing Creates a new Naming_Experiment, which is an experiemnt in which single stimuli are presented and the subject is asked to produce the sign for what is shown. Parameters: data: A dictionary containing experiment data. This should contain the follwoing keys: file, containing absolute paths to all of the stimuli to use; stimulus_type, which tells whether the stimulus is Image or Video This method should be called every time space is pressed (if that space-press has been authenticated). It proceeds to the next stimulus and will begin recording, ending the current stimulus and recording. It also ends the recording_timer if it was running, and updates program state tracking variables to refect the current state of the progam. If there are no more stimuli to run, the program displays a pop-up message stating that data collection is complete. This method should be called when space is released (if that release has been authenticated). It begins recording and starts the recording timer. It also updates program state tracking variables to refect the current state of the progam. Loads and displays the next stimulis for the current subject, but should not be used for the first stimulus of a subjecct. It resets the display timer, which measures the time that a stimulus is displayed before signing. Later, it will also write timer output to a meta file with the same name as the output file. Timer data it not yet verified though, so it is not ready for use. Resets the environment so that the next subject can begin the experiment. #Experiment Parameters #Experiment Running #Timing Creates a new Lexical_Priming_Experiment, in which there is a primer image followed by a stimulus for signing. Recording begins after the stimulus has been shown. Transition between the primer and stimulus is done using space, as is transition between the stimulus and the recording, etc. Parameters: data: A dictionary containing experiment data. This should contain the follwoing keys: files, which contains a tuple of: (absolute path of the primer, that of the stimulus); stimulus_type, which tells whether the stimulus is Image or Video; primer_type, which tells whether the primer is Image or Video; primer_time, which contains the time to show the primer (in seconds, only needed if primer_time is Image) This method should be called every time space is pressed (if that press has been authenticated), except the first. It proceeds to the next stimulus and will begin recording, ending the current stimulus and recording. It also ends the recording_timer if it was running, and updates program state tracking variables to refect the current state of the progam. If there are no more stimuli to run, the program displays a pop-up message stating that data collection is complete. This method should be called when space is released (if that release has been authenticated). It begins recording and starts the recording timer. It also updates program state tracking variables to refect the current state of the progam. #code here #WHat about stimuli? Loads and displays the next stimulus for the current subject, but should not be used for the first stimulus of a subjecct. It resets the display timer, which measures the time that a stimulus is displayed before signing. Later, it will also write timer output to a meta file with the same name as the output file. Timer data it not yet verified though, so it is not ready for use. #In seconds #In seconds Resets the environment so that the next subject can begin the experiment. Data and user-input This class handles all recording using the webcam, and writes recrodings to disk. Initializes the Recorder. Parameters: name: The name to five to the recording file mirror: Whether the recording should be mirrored when saved to disk Begins recording from the webcam. The recording will continue untill end is called, or until 1 is pressed. Note that pressing 1 to quit should be used for debug purposes only # Capturing video from webcam: #get width and height of reading frame # Define the codec and #create VideoWriter object # Capture frame-by-frame #quit on 1 Ends the recording and releases resources. #Get the next frame #Load the image for the current frame and convert to imagetk #Load the image for the current frame and convert to imagetk # Put it in the display window #In seconds #In seconds UI and layout management #Place buttons in the top-level button frame #Grid buttons This method gets the largest-area resize of an image to be displayed on a fullscreen display without allowing any of the image to overflow off-screen. It maintains the image aspect ratio. #Get image dimensions #Get the scalars that transform the original size into the fullscreen dize #Our goal is to make the image as largs as possible without goinf over the screen size. #We also do not want to loose out aspect ratio. So let's see whether using the width_scalar # or the height_scalar does that best This class handles dragging widgets that below to a common set in such a way as to change their positions in that set. So if the numbers 1, 2, 3 are shown on screen, it's goal is to allow you to click on, say, the 3 and move it in from of the one, and then to read back that array in the new order. Parameters: item: The specific item out of the set that can be dragged widgets: The set of all widgets that are ordered on the screen and can be dragged callback: the function to call after a drag and drop. It should accept a list of files in the new order as a parameter. #Bind clicks on the item itself #Remove old elements #Add new elements (OLD) #Add new elements for i in range(len(files)): highlight = settings_dict['draggable_color' + str(i % 2)] container = tk.Frame(self.display_frame, width = width, height = int(height / 1.25), background = highlight) label = tk.Label(container, text=files[i], font = default_font, anchor = 'w', background = highlight) label.pack(side = 'left') remove_button = tk.Button(container, text ="-", command = self.on_button_remove, font = default_font, height = 1, width = 3, background = highlight, foreground = settings_dict['forecolor']) remove_button.pack(side = 'right') label.bindtags(("draggable",) + label.bindtags()) container.pack(side = 'top', fill = 'x') for element in self.display_frame.winfo_children(): print(element); self.widget_drag_controllers.append(Widget_Drag_Controller(element, self.display_frame.winfo_children(), self.update_owner_data)) Version: 0.2.1beta Developer: <NAME> SignRecorder is a simple program for recording and saving video files for sign language data collection and experiments. It is currently hosted on GitHub (https://github.com/Jeffrey-Sardina/SignRecorder) as an open-source project. To get started, click on either 'Create Experiemnt' or 'Start Experiment'. The program will guide you through loading stimuli and experimental methods. Once you have made an experiemnt, save it so that you can load it later. #Container #Place pages in the container frame #Create Experiment Button #self.page_naming_paradigm.lift() #self.page_lexical_priming.lower() #self.page_lexical_priming.lift() #self.page_naming_paradigm.lower() When you are ready to begin the experiment, press the space bar. Once you are ready to sign based on what you see, press the space bar to start recording. Once you are done signing, press the space bar again. You will then see the next prompt and the program will begin recording. #self.buttonframe = tk.Frame(main_frame, background = settings_dict['backcolor']) #Pages #Container #Place pages in the container frame #Show the main menu This code starts program execition. The entire program is run in a try-except statement so that, should any error occur: The program can write out the error to the command line The program can still run on on_close() function to try to clean up all resources The logger is not used here since, among the possible errors that could cause a crash is the logger not having write permissions and it is still important the the failure be printed to a readable output.
2.924879
3
src/encoder.py
delixfe/valuenet
1
6619614
<filename>src/encoder.py from transformers import BertConfig, BertForSequenceClassification, BertTokenizer def get_encoder_model(pretrained_model): print("load pretrained model/tokenizer for '{}'".format(pretrained_model)) config_class, model_class, tokenizer_class = (BertConfig, BertForSequenceClassification, BertTokenizer) config = config_class.from_pretrained(pretrained_model) tokenizer = tokenizer_class.from_pretrained(pretrained_model) model = model_class.from_pretrained(pretrained_model, config=config) return model, tokenizer
<filename>src/encoder.py from transformers import BertConfig, BertForSequenceClassification, BertTokenizer def get_encoder_model(pretrained_model): print("load pretrained model/tokenizer for '{}'".format(pretrained_model)) config_class, model_class, tokenizer_class = (BertConfig, BertForSequenceClassification, BertTokenizer) config = config_class.from_pretrained(pretrained_model) tokenizer = tokenizer_class.from_pretrained(pretrained_model) model = model_class.from_pretrained(pretrained_model, config=config) return model, tokenizer
none
1
2.707438
3
mk_satpylab.py
deapplegate/wtgpipeline
1
6619615
<gh_stars>1-10 import matplotlib import pylab, sys, re file = sys.argv[1] lines = open(file,'r').readlines() x = [] y = [] z = [] err = [] for line in lines: spt = re.split('\s+',line) aptmag = float(spt[1]) catmag = float(spt[2]) radius = float(spt[3]) star_class = float(spt[4]) sdss_error = float(spt[5]) color = float(spt[6]) print color if aptmag != 0 and catmag < 40 and catmag > 10 and color > 0.5: # and radius < 3.3 and aptmag>-1.5: print spt x.append(aptmag) y.append(aptmag - catmag) z.append(radius) err.append(sdss_error) #pylab.scatter(z,x) pylab.errorbar(x,y,err,fmt='o',markersize=0.01) pylab.show()
import matplotlib import pylab, sys, re file = sys.argv[1] lines = open(file,'r').readlines() x = [] y = [] z = [] err = [] for line in lines: spt = re.split('\s+',line) aptmag = float(spt[1]) catmag = float(spt[2]) radius = float(spt[3]) star_class = float(spt[4]) sdss_error = float(spt[5]) color = float(spt[6]) print color if aptmag != 0 and catmag < 40 and catmag > 10 and color > 0.5: # and radius < 3.3 and aptmag>-1.5: print spt x.append(aptmag) y.append(aptmag - catmag) z.append(radius) err.append(sdss_error) #pylab.scatter(z,x) pylab.errorbar(x,y,err,fmt='o',markersize=0.01) pylab.show()
en
0.46965
# and radius < 3.3 and aptmag>-1.5: #pylab.scatter(z,x)
2.580416
3
tests/optimal.py
bisounoursrulio/package_test
0
6619616
<reponame>bisounoursrulio/package_test import numpy as np # ----------------------------------------------- # Optimal loss function (rho) # ------------------------------------------------------------------- def rhooptimal(u, clipping): """ The Fast-Tau Estimator for Regression, <NAME>, <NAME>, and <NAME> www.tandfonline.com/doi/pdf/10.1198/106186008X343785 The equation is found p. 611. To get the exact formula, it is necessary to use 3*c instead of c. """ import numpy as np y = np.abs(u / clipping) r = np.ones(u.shape) i = y <= 2. # middle part of the curve r[i] = y[i] ** 2 / 2. / 3.25 i = np.logical_and(y > 2, y <= 3) # intermediate part of the curve f = lambda z: (1.792 - 0.972 * z ** 2 + 0.432 * z ** 4 - 0.052 * z ** 6 + 0.002 * z ** 8) / 3.25 r[i] = f(y[i]) return r # ------------------------------------------------------------------- # Optimal score function (psi) # ------------------------------------------------------------------- def scoreoptimal(u, clipping): u = np.array(u) p = np.zeros(u.shape) uabs = np.abs(u) # u absolute values i = uabs <= 2 * clipping # central part of teh score function p[i] = u[i] / clipping ** 2 / 3.25 i = np.logical_and(uabs > 2 * clipping, uabs <= 3 * clipping) f = lambda z: (-1.944 * z / clipping ** 2 + 1.728 * z ** 3 / clipping ** 4 - 0.312 * z ** 5 / clipping ** 6 + 0.016 * z ** 7 / clipping ** 8) / 3.25 p[i] = f(u[i]) return p
import numpy as np # ----------------------------------------------- # Optimal loss function (rho) # ------------------------------------------------------------------- def rhooptimal(u, clipping): """ The Fast-Tau Estimator for Regression, <NAME>, <NAME>, and <NAME> www.tandfonline.com/doi/pdf/10.1198/106186008X343785 The equation is found p. 611. To get the exact formula, it is necessary to use 3*c instead of c. """ import numpy as np y = np.abs(u / clipping) r = np.ones(u.shape) i = y <= 2. # middle part of the curve r[i] = y[i] ** 2 / 2. / 3.25 i = np.logical_and(y > 2, y <= 3) # intermediate part of the curve f = lambda z: (1.792 - 0.972 * z ** 2 + 0.432 * z ** 4 - 0.052 * z ** 6 + 0.002 * z ** 8) / 3.25 r[i] = f(y[i]) return r # ------------------------------------------------------------------- # Optimal score function (psi) # ------------------------------------------------------------------- def scoreoptimal(u, clipping): u = np.array(u) p = np.zeros(u.shape) uabs = np.abs(u) # u absolute values i = uabs <= 2 * clipping # central part of teh score function p[i] = u[i] / clipping ** 2 / 3.25 i = np.logical_and(uabs > 2 * clipping, uabs <= 3 * clipping) f = lambda z: (-1.944 * z / clipping ** 2 + 1.728 * z ** 3 / clipping ** 4 - 0.312 * z ** 5 / clipping ** 6 + 0.016 * z ** 7 / clipping ** 8) / 3.25 p[i] = f(u[i]) return p
en
0.447363
# ----------------------------------------------- # Optimal loss function (rho) # ------------------------------------------------------------------- The Fast-Tau Estimator for Regression, <NAME>, <NAME>, and <NAME> www.tandfonline.com/doi/pdf/10.1198/106186008X343785 The equation is found p. 611. To get the exact formula, it is necessary to use 3*c instead of c. # middle part of the curve # intermediate part of the curve # ------------------------------------------------------------------- # Optimal score function (psi) # ------------------------------------------------------------------- # u absolute values # central part of teh score function
2.873129
3
hal_fuzz/hal_fuzz/handlers/atmel_asf_v3.py
diagprov/hal-fuzz
117
6619617
<gh_stars>100-1000 import sys from unicorn.arm_const import * from ..models.ethernet import EthernetModel from ..util import * import sys ########################### USART ############################### def usart_write_wait(uc): #usart_ptr = uc.reg_read(UC_ARM_REG_R0) #hw_addr = bytes2int(uc.mem_read(usart_ptr, 4)) data = int2bytes(uc.reg_read(UC_ARM_REG_R1))[:1] # Just the first byte sys.stdout.write(data.decode()) uc.reg_write(UC_ARM_REG_R0, 0) def usart_write_buffer_wait(uc): #usart_ptr = uc.reg_read(UC_ARM_REG_R0) #hw_addr = bytes2int(uc.mem_read(usart_ptr, 4)) import ipdb; ipdb.set_trace() buf_addr = uc.reg_read(UC_ARM_REG_R1) buf_len = uc.reg_read(UC_ARM_REG_R2) data = uc.mem_read(buf_addr, buf_len) #sys.stdout.write(data) print(data) uc.reg_write(UC_ARM_REG_R0, 0) ########################### Ethernet ############################### # netif Offsets NETIF_STATE = 32 NETIF_INPUT = 16 # struct ksz8851snl_device Offsets NUM_RX_BUFFS = 2 NUM_TX_BUFFS = 2 DEVICE_RX_DESC = 0 DEVICE_TX_DESC = 4 * NUM_RX_BUFFS DEVICE_RX_PBUF = DEVICE_TX_DESC + (4 * NUM_TX_BUFFS) DEVICE_TX_PBUF = DEVICE_RX_PBUF + (4 * NUM_RX_BUFFS) DEVICE_RX_HEAD = DEVICE_TX_PBUF + (4 * NUM_TX_BUFFS) DEVICE_RX_TAIL = DEVICE_RX_HEAD + 4 DEVICE_TX_HEAD = DEVICE_RX_TAIL + 4 DEVICE_TX_TAIL = DEVICE_TX_HEAD + 4 DEVICE_NETIF = DEVICE_TX_TAIL + 4 # pbuf offsets PBUF_NEXT = 0 PBUF_PAYLOAD = 4 PBUF_TOT_LEN = 8 PBUF_LEN = 10 PBUF_TYPE = 12 PBUF_FLAGS = 13 PBUF_REF = 14 # Ethernet Types ETHTYPE_ARP = 0x0806 ETHTYPE_IP = 0x0800 PADDING = 2 # Padding used on ethernet frames to keep alignment SUPPORTED_TYPES = (ETHTYPE_ARP, ETHTYPE_IP) ethernet_dev_ptr = None ethernet_orig_lr = None ethernet_netif_ptr = None def is_supported_frame_type(frame): if len(frame) < 14: return False else: ty = struct.unpack('!H', frame[12:14])[0] #log.info("Frame ty: %s" % hex(ty)) #log.info("Frame : %s" % binascii.hexlify(frame[:20])) return ty in (SUPPORTED_TYPES) def get_id(uc): return 'ksz8851' def call_populate_queues(uc): ''' This will call the ksz8851snl_rx_populate_queue returning to ethernetif_input ''' global ethernet_dev_ptr global ethernet_orig_lr ethernet_orig_lr = uc.reg_read(UC_ARM_REG_LR) uc.reg_write(UC_ARM_REG_R0, ethernet_dev_ptr) uc.reg_write(UC_ARM_REG_LR, uc.reg_read(UC_ARM_REG_PC) | 1) # Make sure thumb bit is set uc.reg_write(UC_ARM_REG_PC, uc.symbols['ksz8851snl_rx_populate_queue'] | 1) def ethernetif_input(uc): # 1. See if there are frames #now = time.time() #log.info("In ETHERNET_INPUT: %f" % (now - self.last_exec_time)) #self.last_exec_time = time.time() #start_time = time.time() global ethernet_orig_lr global ethernet_dev_ptr global ethernet_netif_ptr (num_frames, size_1st_frame) = EthernetModel.get_frame_info(get_id(uc)) if num_frames > 0: if ethernet_netif_ptr is None: # Will be none if not returning from populate_queues ethernet_netif_ptr = uc.reg_read(UC_ARM_REG_R0) ethernet_dev_ptr = bytes2int(uc.mem_read(ethernet_netif_ptr + NETIF_STATE, 4)) else: # Executing on return from popluate_queues uc.reg_write(UC_ARM_REG_LR, ethernet_orig_lr) # Get Pbuf, if null use populate_queues to allocate new ones rx_pbuf_ptr = bytes2int(uc.mem_read(ethernet_dev_ptr + DEVICE_RX_PBUF, 4)) if rx_pbuf_ptr == 0: call_populate_queues(uc) return frame = EthernetModel.get_rx_frame(get_id(uc)) if frame != None and is_supported_frame_type(frame): # Remove pbuf addr from hw buffers. Allows new one to be made # and this one to be freed by stack uc.mem_write(ethernet_dev_ptr + DEVICE_RX_PBUF, int2bytes(0)) # Get payload_ptr payload_ptr = bytes2int(uc.mem_read(rx_pbuf_ptr + PBUF_PAYLOAD, 4)) # Write to memory uc.mem_write(payload_ptr + PADDING, frame) uc.mem_write(rx_pbuf_ptr + PBUF_TOT_LEN, int2bytes(len(frame))[:2]) uc.mem_write(rx_pbuf_ptr + PBUF_LEN, int2bytes(len(frame))[:2]) # Get input function, and call it input_fn_ptr = bytes2int(uc.mem_read(ethernet_netif_ptr + NETIF_INPUT, 4)) # Call netif->input uc.reg_write(UC_ARM_REG_R0, rx_pbuf_ptr) uc.reg_write(UC_ARM_REG_R1, ethernet_netif_ptr) uc.reg_write(UC_ARM_REG_PC, input_fn_ptr) ethernet_dev_ptr = None ethernet_netif_ptr = None def _do_exti(chan): # Set the EXTI, so that the CPU knows that we want a packet, not a button press or something # TODO: This is ugly. Can we do better? EDG doesn't think so, but... someone should try sr = 1 << (chan & 0x1f) uc.mem_write(0x40001810, int2bytes(sr)) # Pend interrupt manually nvic.NVIC.set_pending(20) # That's EIC def ksz8851snl_low_level_output(uc): #pbuf_free = uc.symbols['pbuf_free'] pbuf_ptr = uc.reg_read(UC_ARM_REG_R1) frame_bufs = [] p = pbuf_ptr # os.system('stty sane') # Make so display works # IPython.embed() padding = PADDING while p != 0: length = bytes2int(uc.mem_read(p + PBUF_LEN, 2) + b'\x00\x00') payload_ptr = bytes2int(uc.mem_read(p + PBUF_PAYLOAD, 4)) frame_bufs.append(uc.mem_read(payload_ptr + padding, length - padding)) padding = 0 # Padding only on first pbuf p = bytes2int(uc.mem_read(p + PBUF_NEXT, 4)) frame = bytearray(b'').join(frame_bufs) EthernetModel.tx_frame(get_id(uc), frame) # qemu.call_ret_0(pbuf_free, pbuf_ptr)
import sys from unicorn.arm_const import * from ..models.ethernet import EthernetModel from ..util import * import sys ########################### USART ############################### def usart_write_wait(uc): #usart_ptr = uc.reg_read(UC_ARM_REG_R0) #hw_addr = bytes2int(uc.mem_read(usart_ptr, 4)) data = int2bytes(uc.reg_read(UC_ARM_REG_R1))[:1] # Just the first byte sys.stdout.write(data.decode()) uc.reg_write(UC_ARM_REG_R0, 0) def usart_write_buffer_wait(uc): #usart_ptr = uc.reg_read(UC_ARM_REG_R0) #hw_addr = bytes2int(uc.mem_read(usart_ptr, 4)) import ipdb; ipdb.set_trace() buf_addr = uc.reg_read(UC_ARM_REG_R1) buf_len = uc.reg_read(UC_ARM_REG_R2) data = uc.mem_read(buf_addr, buf_len) #sys.stdout.write(data) print(data) uc.reg_write(UC_ARM_REG_R0, 0) ########################### Ethernet ############################### # netif Offsets NETIF_STATE = 32 NETIF_INPUT = 16 # struct ksz8851snl_device Offsets NUM_RX_BUFFS = 2 NUM_TX_BUFFS = 2 DEVICE_RX_DESC = 0 DEVICE_TX_DESC = 4 * NUM_RX_BUFFS DEVICE_RX_PBUF = DEVICE_TX_DESC + (4 * NUM_TX_BUFFS) DEVICE_TX_PBUF = DEVICE_RX_PBUF + (4 * NUM_RX_BUFFS) DEVICE_RX_HEAD = DEVICE_TX_PBUF + (4 * NUM_TX_BUFFS) DEVICE_RX_TAIL = DEVICE_RX_HEAD + 4 DEVICE_TX_HEAD = DEVICE_RX_TAIL + 4 DEVICE_TX_TAIL = DEVICE_TX_HEAD + 4 DEVICE_NETIF = DEVICE_TX_TAIL + 4 # pbuf offsets PBUF_NEXT = 0 PBUF_PAYLOAD = 4 PBUF_TOT_LEN = 8 PBUF_LEN = 10 PBUF_TYPE = 12 PBUF_FLAGS = 13 PBUF_REF = 14 # Ethernet Types ETHTYPE_ARP = 0x0806 ETHTYPE_IP = 0x0800 PADDING = 2 # Padding used on ethernet frames to keep alignment SUPPORTED_TYPES = (ETHTYPE_ARP, ETHTYPE_IP) ethernet_dev_ptr = None ethernet_orig_lr = None ethernet_netif_ptr = None def is_supported_frame_type(frame): if len(frame) < 14: return False else: ty = struct.unpack('!H', frame[12:14])[0] #log.info("Frame ty: %s" % hex(ty)) #log.info("Frame : %s" % binascii.hexlify(frame[:20])) return ty in (SUPPORTED_TYPES) def get_id(uc): return 'ksz8851' def call_populate_queues(uc): ''' This will call the ksz8851snl_rx_populate_queue returning to ethernetif_input ''' global ethernet_dev_ptr global ethernet_orig_lr ethernet_orig_lr = uc.reg_read(UC_ARM_REG_LR) uc.reg_write(UC_ARM_REG_R0, ethernet_dev_ptr) uc.reg_write(UC_ARM_REG_LR, uc.reg_read(UC_ARM_REG_PC) | 1) # Make sure thumb bit is set uc.reg_write(UC_ARM_REG_PC, uc.symbols['ksz8851snl_rx_populate_queue'] | 1) def ethernetif_input(uc): # 1. See if there are frames #now = time.time() #log.info("In ETHERNET_INPUT: %f" % (now - self.last_exec_time)) #self.last_exec_time = time.time() #start_time = time.time() global ethernet_orig_lr global ethernet_dev_ptr global ethernet_netif_ptr (num_frames, size_1st_frame) = EthernetModel.get_frame_info(get_id(uc)) if num_frames > 0: if ethernet_netif_ptr is None: # Will be none if not returning from populate_queues ethernet_netif_ptr = uc.reg_read(UC_ARM_REG_R0) ethernet_dev_ptr = bytes2int(uc.mem_read(ethernet_netif_ptr + NETIF_STATE, 4)) else: # Executing on return from popluate_queues uc.reg_write(UC_ARM_REG_LR, ethernet_orig_lr) # Get Pbuf, if null use populate_queues to allocate new ones rx_pbuf_ptr = bytes2int(uc.mem_read(ethernet_dev_ptr + DEVICE_RX_PBUF, 4)) if rx_pbuf_ptr == 0: call_populate_queues(uc) return frame = EthernetModel.get_rx_frame(get_id(uc)) if frame != None and is_supported_frame_type(frame): # Remove pbuf addr from hw buffers. Allows new one to be made # and this one to be freed by stack uc.mem_write(ethernet_dev_ptr + DEVICE_RX_PBUF, int2bytes(0)) # Get payload_ptr payload_ptr = bytes2int(uc.mem_read(rx_pbuf_ptr + PBUF_PAYLOAD, 4)) # Write to memory uc.mem_write(payload_ptr + PADDING, frame) uc.mem_write(rx_pbuf_ptr + PBUF_TOT_LEN, int2bytes(len(frame))[:2]) uc.mem_write(rx_pbuf_ptr + PBUF_LEN, int2bytes(len(frame))[:2]) # Get input function, and call it input_fn_ptr = bytes2int(uc.mem_read(ethernet_netif_ptr + NETIF_INPUT, 4)) # Call netif->input uc.reg_write(UC_ARM_REG_R0, rx_pbuf_ptr) uc.reg_write(UC_ARM_REG_R1, ethernet_netif_ptr) uc.reg_write(UC_ARM_REG_PC, input_fn_ptr) ethernet_dev_ptr = None ethernet_netif_ptr = None def _do_exti(chan): # Set the EXTI, so that the CPU knows that we want a packet, not a button press or something # TODO: This is ugly. Can we do better? EDG doesn't think so, but... someone should try sr = 1 << (chan & 0x1f) uc.mem_write(0x40001810, int2bytes(sr)) # Pend interrupt manually nvic.NVIC.set_pending(20) # That's EIC def ksz8851snl_low_level_output(uc): #pbuf_free = uc.symbols['pbuf_free'] pbuf_ptr = uc.reg_read(UC_ARM_REG_R1) frame_bufs = [] p = pbuf_ptr # os.system('stty sane') # Make so display works # IPython.embed() padding = PADDING while p != 0: length = bytes2int(uc.mem_read(p + PBUF_LEN, 2) + b'\x00\x00') payload_ptr = bytes2int(uc.mem_read(p + PBUF_PAYLOAD, 4)) frame_bufs.append(uc.mem_read(payload_ptr + padding, length - padding)) padding = 0 # Padding only on first pbuf p = bytes2int(uc.mem_read(p + PBUF_NEXT, 4)) frame = bytearray(b'').join(frame_bufs) EthernetModel.tx_frame(get_id(uc), frame) # qemu.call_ret_0(pbuf_free, pbuf_ptr)
en
0.563615
########################### USART ############################### #usart_ptr = uc.reg_read(UC_ARM_REG_R0) #hw_addr = bytes2int(uc.mem_read(usart_ptr, 4)) # Just the first byte #usart_ptr = uc.reg_read(UC_ARM_REG_R0) #hw_addr = bytes2int(uc.mem_read(usart_ptr, 4)) #sys.stdout.write(data) ########################### Ethernet ############################### # netif Offsets # struct ksz8851snl_device Offsets # pbuf offsets # Ethernet Types # Padding used on ethernet frames to keep alignment #log.info("Frame ty: %s" % hex(ty)) #log.info("Frame : %s" % binascii.hexlify(frame[:20])) This will call the ksz8851snl_rx_populate_queue returning to ethernetif_input # Make sure thumb bit is set # 1. See if there are frames #now = time.time() #log.info("In ETHERNET_INPUT: %f" % (now - self.last_exec_time)) #self.last_exec_time = time.time() #start_time = time.time() # Will be none if not returning from populate_queues # Executing on return from popluate_queues # Get Pbuf, if null use populate_queues to allocate new ones # Remove pbuf addr from hw buffers. Allows new one to be made # and this one to be freed by stack # Get payload_ptr # Write to memory # Get input function, and call it # Call netif->input # Set the EXTI, so that the CPU knows that we want a packet, not a button press or something # TODO: This is ugly. Can we do better? EDG doesn't think so, but... someone should try # Pend interrupt manually # That's EIC #pbuf_free = uc.symbols['pbuf_free'] # os.system('stty sane') # Make so display works # IPython.embed() # Padding only on first pbuf # qemu.call_ret_0(pbuf_free, pbuf_ptr)
2.172461
2
counter.py
Space4all/kau-notify
2
6619618
<gh_stars>1-10 #-*- coding: utf-8 -*- from flask import Flask, request,session, redirect, url_for, abort, render_template, flash, send_from_directory from app.models import * from app import app from google.appengine.ext import ndb import logging BoardDict = {"항공우주 및 기계공학부": "AME", \ "항공전자정보공학부": "ETC", \ "항공재료공학과": "AVS", \ "소프트웨어학과": "SOF", \ "항공교통물류학부": "ATL", \ "경영학부": "BUS", \ "항공운항학과": "AEO"} @app.route('/counter', methods=('GET', 'POST')) def counter(): counter_qry = Counter.query() for c in counter_qry.fetch(1): c.counter = 430 #구독자 수 메일 받은 것 기반으로 재설정 c.put() return ('', 204) # @app.route('/setdb', methods=('GET', 'POST')) # def setdb(): # qry = Subs.query() # for user in qry.fetch(): # if user.dept: # dept=BoardDict[str(user.dept)] # user.subsboard = [ # MainBoard(type='General'), # MainBoard(type='Academic'), # ] # user.deptboard = [ # DeptBoard(type=dept) # ] # user.put() # return ('', 204) # # @app.route('/removedept', methods=('GET', 'POST')) # def removedept(): # qry = Subs.query() # for user in qry.fetch(): # if 'dept' in user._properties: # user._clone_properties() # del user._properties['dept'] # user.put() # return ('', 204)
#-*- coding: utf-8 -*- from flask import Flask, request,session, redirect, url_for, abort, render_template, flash, send_from_directory from app.models import * from app import app from google.appengine.ext import ndb import logging BoardDict = {"항공우주 및 기계공학부": "AME", \ "항공전자정보공학부": "ETC", \ "항공재료공학과": "AVS", \ "소프트웨어학과": "SOF", \ "항공교통물류학부": "ATL", \ "경영학부": "BUS", \ "항공운항학과": "AEO"} @app.route('/counter', methods=('GET', 'POST')) def counter(): counter_qry = Counter.query() for c in counter_qry.fetch(1): c.counter = 430 #구독자 수 메일 받은 것 기반으로 재설정 c.put() return ('', 204) # @app.route('/setdb', methods=('GET', 'POST')) # def setdb(): # qry = Subs.query() # for user in qry.fetch(): # if user.dept: # dept=BoardDict[str(user.dept)] # user.subsboard = [ # MainBoard(type='General'), # MainBoard(type='Academic'), # ] # user.deptboard = [ # DeptBoard(type=dept) # ] # user.put() # return ('', 204) # # @app.route('/removedept', methods=('GET', 'POST')) # def removedept(): # qry = Subs.query() # for user in qry.fetch(): # if 'dept' in user._properties: # user._clone_properties() # del user._properties['dept'] # user.put() # return ('', 204)
en
0.269168
#-*- coding: utf-8 -*- #구독자 수 메일 받은 것 기반으로 재설정 # @app.route('/setdb', methods=('GET', 'POST')) # def setdb(): # qry = Subs.query() # for user in qry.fetch(): # if user.dept: # dept=BoardDict[str(user.dept)] # user.subsboard = [ # MainBoard(type='General'), # MainBoard(type='Academic'), # ] # user.deptboard = [ # DeptBoard(type=dept) # ] # user.put() # return ('', 204) # # @app.route('/removedept', methods=('GET', 'POST')) # def removedept(): # qry = Subs.query() # for user in qry.fetch(): # if 'dept' in user._properties: # user._clone_properties() # del user._properties['dept'] # user.put() # return ('', 204)
2.305556
2
LeetCodeSolutions/python/115_Distinct_Subsequences.py
ChuanleiGuo/AlgorithmsPlayground
1
6619619
class Solution(object): def numDistinct(self, s, t): """ :type s: str :type t: str :rtype: int """ l_s = len(s) l_t = len(t) dp = [[0] * (l_t + 1) for _ in range(l_s + 1)] for i in range(l_s + 1): dp[i][0] = 1 for i in range(1, l_s + 1): for j in range(1, l_t + 1): if s[i - 1] == t[j - 1]: dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j] else: dp[i][j] = dp[i - 1][j] return dp[l_s][l_t]
class Solution(object): def numDistinct(self, s, t): """ :type s: str :type t: str :rtype: int """ l_s = len(s) l_t = len(t) dp = [[0] * (l_t + 1) for _ in range(l_s + 1)] for i in range(l_s + 1): dp[i][0] = 1 for i in range(1, l_s + 1): for j in range(1, l_t + 1): if s[i - 1] == t[j - 1]: dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j] else: dp[i][j] = dp[i - 1][j] return dp[l_s][l_t]
en
0.303445
:type s: str :type t: str :rtype: int
2.987296
3
examples/example_fincalc.py
Shephexd/linchfin
8
6619620
import pandas as pd import numpy as np import os from linchfin.common.calc import * current_dir = os.path.dirname(__file__) os.chdir(current_dir) print(current_dir) CPIAUCSL = pd.read_csv('sample/data/CPIAUCSL.csv') FEDFUNDS = pd.read_csv('sample/data/FEDFUNDS.csv') T10Y2Y = pd.read_csv('sample/data/T10Y2Y.csv') print(T10Y2Y)
import pandas as pd import numpy as np import os from linchfin.common.calc import * current_dir = os.path.dirname(__file__) os.chdir(current_dir) print(current_dir) CPIAUCSL = pd.read_csv('sample/data/CPIAUCSL.csv') FEDFUNDS = pd.read_csv('sample/data/FEDFUNDS.csv') T10Y2Y = pd.read_csv('sample/data/T10Y2Y.csv') print(T10Y2Y)
none
1
2.226823
2
Python_Scripts/os_health.py
CyberWing/Srv_Programs
0
6619621
#!/usr/bin/python #Script can perform server health check.... #Modified Date 21/Aug/2015 ###### import os import subprocess import time print "\t################################################################" print "\t# LINUX SERVER HEALTH CHECK PROGRAM #" print "\t# EMAIL : #" print "\t# <EMAIL> #" print "\t# #" print "\t# Written by PhyoMinHtun #" print "\t################################################################" pass time.sleep(1) os.system("date") print "\t#########################################################################" print "\t# Help: #" print "\t# 0: Type input [0 or exit] for exit program: #" print "\t# 1: Type input [1] for checking TCP ports: #" print "\t# 2: Type input [2] for last logins: #" print "\t# 3: Type input [3] for check Disk,System Info: and memory usage: #" print "\t# 4: Type input [4] for utilization and most expensive processes: #" print "\t# 5: Type input [5] for current socket connections: #" print "\t# 6: Type input [6] for check public IP address: #" print "\t# 7: Type input [7] for Show who is logged on and what they are doing: #" print "\t#########################################################################" def exit(): exit def nmap(): print "checking TCP ports:" chk_port="nmap -p- -T4 127.0.0.1" os.system(chk_port) print "=======================================" def lastlogin(): print "Last logins:" b=os.popen('last -a |head -3') last=b.read() print last print "=======================================" def chk_info(): print "Check Disk,System Info: and memory usage:" subprocess.call(["df","-h"]) subprocess.call(["free","-m"]) print "" print "System Information is: \n",subprocess.call(["uname","-a"]) print "=======================================" def utilize_expensive_process(): print "Utilization and most expensive processes:" c=os.popen('top -b |head -3') process=c.read() print process print "=======================================" def current_socket_con(): print "Current connections:" d=os.popen('ss -s') socket=d.read() print socket os.system("netstat -nlpt") print "=======================================" def chk_pubip(): print "Check Server Public IP:" e=os.popen('wget -qO- ifconfig.me/ip') ip=e.read() print ip print "=======================================" def chk_login(): print "Show who is logged on and what they are doing:" os.system("w -s") def main(): login=raw_input("Do you want to run this script?yes or no? ") if(login=="yes") or (login=="YES"): input=raw_input("Enter your input: ") if(input=="0") or (input=="exit"): exit() if(input=="1"): nmap() if(input=="2"): lastlogin() if(input=="3"): chk_info() if(input=="4"): utilize_expensive_process() if(input=="5"): current_socket_con() if(input=="6"): chk_pubip() if(input=="7"): chk_login() elif (login=="no") or (login=="NO"): print "Thank you for your using server health check script..." else: print "Invalid Input Key!" main() #DONE
#!/usr/bin/python #Script can perform server health check.... #Modified Date 21/Aug/2015 ###### import os import subprocess import time print "\t################################################################" print "\t# LINUX SERVER HEALTH CHECK PROGRAM #" print "\t# EMAIL : #" print "\t# <EMAIL> #" print "\t# #" print "\t# Written by PhyoMinHtun #" print "\t################################################################" pass time.sleep(1) os.system("date") print "\t#########################################################################" print "\t# Help: #" print "\t# 0: Type input [0 or exit] for exit program: #" print "\t# 1: Type input [1] for checking TCP ports: #" print "\t# 2: Type input [2] for last logins: #" print "\t# 3: Type input [3] for check Disk,System Info: and memory usage: #" print "\t# 4: Type input [4] for utilization and most expensive processes: #" print "\t# 5: Type input [5] for current socket connections: #" print "\t# 6: Type input [6] for check public IP address: #" print "\t# 7: Type input [7] for Show who is logged on and what they are doing: #" print "\t#########################################################################" def exit(): exit def nmap(): print "checking TCP ports:" chk_port="nmap -p- -T4 127.0.0.1" os.system(chk_port) print "=======================================" def lastlogin(): print "Last logins:" b=os.popen('last -a |head -3') last=b.read() print last print "=======================================" def chk_info(): print "Check Disk,System Info: and memory usage:" subprocess.call(["df","-h"]) subprocess.call(["free","-m"]) print "" print "System Information is: \n",subprocess.call(["uname","-a"]) print "=======================================" def utilize_expensive_process(): print "Utilization and most expensive processes:" c=os.popen('top -b |head -3') process=c.read() print process print "=======================================" def current_socket_con(): print "Current connections:" d=os.popen('ss -s') socket=d.read() print socket os.system("netstat -nlpt") print "=======================================" def chk_pubip(): print "Check Server Public IP:" e=os.popen('wget -qO- ifconfig.me/ip') ip=e.read() print ip print "=======================================" def chk_login(): print "Show who is logged on and what they are doing:" os.system("w -s") def main(): login=raw_input("Do you want to run this script?yes or no? ") if(login=="yes") or (login=="YES"): input=raw_input("Enter your input: ") if(input=="0") or (input=="exit"): exit() if(input=="1"): nmap() if(input=="2"): lastlogin() if(input=="3"): chk_info() if(input=="4"): utilize_expensive_process() if(input=="5"): current_socket_con() if(input=="6"): chk_pubip() if(input=="7"): chk_login() elif (login=="no") or (login=="NO"): print "Thank you for your using server health check script..." else: print "Invalid Input Key!" main() #DONE
en
0.32299
#!/usr/bin/python #Script can perform server health check.... #Modified Date 21/Aug/2015 ###### ################################################################" # LINUX SERVER HEALTH CHECK PROGRAM #" # EMAIL : #" # <EMAIL> #" # #" # Written by PhyoMinHtun #" ################################################################" #########################################################################" # Help: #" # 0: Type input [0 or exit] for exit program: #" # 1: Type input [1] for checking TCP ports: #" # 2: Type input [2] for last logins: #" # 3: Type input [3] for check Disk,System Info: and memory usage: #" # 4: Type input [4] for utilization and most expensive processes: #" # 5: Type input [5] for current socket connections: #" # 6: Type input [6] for check public IP address: #" # 7: Type input [7] for Show who is logged on and what they are doing: #" #########################################################################" #DONE
2.970382
3
modules/gui/viztooldlg.py
alfredometere/PASYVAT
0
6619622
<filename>modules/gui/viztooldlg.py # -*- coding: utf-8 -*- """ Created on Wed Nov 14 18:02:14 2012 @author: alfredo """ from PyQt4.QtGui import * from PyQt4.Qwt5 import * from PyQt4.Qwt5.qplt import * from guiqwt import * from vtk.qt4.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor from guiqwt.plot import * from guiqwt.tools import * from guiqwt.config import * from guiqwt.builder import * import vtk import sys import csv import os class VizToolDlg(QWidget): def __init__(self, renwin): super(VizToolDlg,self).__init__() self.renwin = renwin self.init_ui() def init_ui(self): self.setWindowTitle("Parametric Rotation Controls") self.setMinimumSize(868,505) self.gamma_angle_counter = QwtCounter(self) self.gamma_angle_slider = QwtSlider(self) self.gamma_angle_label = QLabel(self) self.beta_angle_label = QLabel(self) self.alpha_angle_label = QLabel(self) self.gamma_angle_counter_2 = QwtCounter(self) self.gamma_angle_slider_2 = QwtSlider(self) self.gamma_angle_counter_3 = QwtCounter(self) self.gamma_angle_slider_3 = QwtSlider(self) self.gamma_angle_counter_4 = QwtCounter(self) self.gamma_angle_counter_5 = QwtCounter(self) self.gamma_angle_slider_4 = QwtSlider(self) self.gamma_angle_counter_6 = QwtCounter(self) self.gamma_angle_slider_5 = QwtSlider(self) self.gamma_angle_slider_6 = QwtSlider(self) self.gamma_angle_counter_7 = QwtCounter(self) self.gamma_angle_counter_8 = QwtCounter(self) self.gamma_angle_slider_7 = QwtSlider(self) self.gamma_angle_counter_9 = QwtCounter(self) self.gamma_angle_slider_8 = QwtSlider(self) self.gamma_angle_slider_9 = QwtSlider(self) self.label = QLabel(self) self.label_2 = QLabel(self) self.label_3 = QLabel(self) self.label_4 = QLabel(self) self.label_5 = QLabel(self) self.label_6 = QLabel(self) self.label_7 = QLabel(self) self.label_8 = QLabel(self) self.label_9 = QLabel(self) self.line = QFrame(self) self.line_2 = QFrame(self) self.font = QFont(self) self.gamma_angle_counter.setObjectName(QString("gamma_angle_counter")) self.gamma_angle_counter.setGeometry(QRect(20, 410, 271, 29)) self.gamma_angle_slider.setObjectName(QString("gamma_angle_slider")) self.gamma_angle_slider.setGeometry(QRect(20, 450, 271, 21)) self.gamma_angle_label.setObjectName(QString("gamma_angle_label")) self.gamma_angle_label.setGeometry(QRect(400, 350, 66, 17)) self.font.setBold(True) self.font.setItalic(True) self.font.setWeight(75) self.gamma_angle_label.setFont(self.font) self.gamma_angle_label.setAlignment(Qt.AlignCenter) self.gamma_angle_label.setText(QString("Gamma")) self.beta_angle_label.setObjectName(QString("beta_angle_label")) self.beta_angle_label.setGeometry(QRect(400, 200, 66, 17)) self.beta_angle_label.setFont(self.font) self.beta_angle_label.setText(QString("Beta")) self.beta_angle_label.setAlignment(Qt.AlignCenter) self.alpha_angle_label.setObjectName(QString("alpha_angle_label")) self.alpha_angle_label.setGeometry(QRect(400, 60, 66, 17)) self.alpha_angle_label.setFont(self.font) self.alpha_angle_label.setText(QString("Alpha")) self.alpha_angle_label.setAlignment(Qt.AlignCenter) self.gamma_angle_counter_2.setObjectName(QString("gamma_angle_counter_2")) self.gamma_angle_counter_2.setGeometry(QRect(300, 410, 271, 29)) self.gamma_angle_slider_2.setObjectName(QString("gamma_angle_slider_2")) self.gamma_angle_slider_2.setGeometry(QRect(300, 450, 271, 21)) self.gamma_angle_counter_3.setObjectName(QString("gamma_angle_counter_3")) self.gamma_angle_counter_3.setGeometry(QRect(580, 410, 271, 29)) self.gamma_angle_slider_3.setObjectName(QString("gamma_angle_slider_3")) self.gamma_angle_slider_3.setGeometry(QRect(580, 450, 271, 21)) self.gamma_angle_counter_4.setObjectName(QString("gamma_angle_counter_4")) self.gamma_angle_counter_4.setGeometry(QRect(20, 260, 271, 29)) self.gamma_angle_counter_5.setObjectName(QString("gamma_angle_counter_5")) self.gamma_angle_counter_5.setGeometry(QRect(300, 260, 271, 29)) self.gamma_angle_slider_4.setObjectName(QString("gamma_angle_slider_4")) self.gamma_angle_slider_4.setGeometry(QRect(300, 300, 271, 21)) self.gamma_angle_counter_6.setObjectName(QString("gamma_angle_counter_6")) self.gamma_angle_counter_6.setGeometry(QRect(580, 260, 271, 29)) self.gamma_angle_slider_5.setObjectName(QString("gamma_angle_slider_5")) self.gamma_angle_slider_5.setGeometry(QRect(20, 300, 271, 21)) self.gamma_angle_slider_6.setObjectName(QString("gamma_angle_slider_6")) self.gamma_angle_slider_6.setGeometry(QRect(580, 300, 271, 21)) self.gamma_angle_counter_7.setObjectName(QString("gamma_angle_counter_7")) self.gamma_angle_counter_7.setGeometry(QRect(20, 120, 271, 29)) self.gamma_angle_counter_8.setObjectName(QString("gamma_angle_counter_8")) self.gamma_angle_counter_8.setGeometry(QRect(300, 120, 271, 29)) self.gamma_angle_slider_7.setObjectName(QString("gamma_angle_slider_7")) self.gamma_angle_slider_7.setGeometry(QRect(300, 160, 271, 21)) self.gamma_angle_counter_9.setObjectName(QString("gamma_angle_counter_9")) self.gamma_angle_counter_9.setGeometry(QRect(580, 120, 271, 29)) self.gamma_angle_slider_8.setObjectName(QString("gamma_angle_slider_8")) self.gamma_angle_slider_8.setGeometry(QRect(20, 160, 271, 21)) self.gamma_angle_slider_9.setObjectName(QString("gamma_angle_slider_9")) self.gamma_angle_slider_9.setGeometry(QRect(580, 160, 271, 21)) self.label.setObjectName(QString("label")) self.label.setGeometry(QRect(120, 100, 66, 17)) self.font1 = QFont(self) self.font1.setItalic(True) self.label.setFont(self.font1) self.label.setText(QString("Camera")) self.label.setAlignment(Qt.AlignCenter) self.label_2.setObjectName(QString("label_2")) self.label_2.setGeometry(QRect(400, 100, 66, 17)) self.label_2.setFont(self.font1) self.label_2.setText(QString("Object")) self.label_2.setAlignment(Qt.AlignCenter) self.label_3.setObjectName(QString("label_3")) self.label_3.setGeometry(QRect(680, 100, 66, 17)) self.label_3.setFont(self.font1) self.label_3.setText(QString("Slicer")) self.label_3.setAlignment(Qt.AlignCenter) self.label_4.setObjectName(QString("label_4")) self.label_4.setGeometry(QRect(680, 240, 66, 17)) self.label_4.setFont(self.font1) self.label_4.setText(QString("Slicer")) self.label_4.setAlignment(Qt.AlignCenter) self.label_5.setObjectName(QString("label_5")) self.label_5.setGeometry(QRect(120, 240, 66, 17)) self.label_5.setFont(self.font1) self.label_5.setText(QString("Camera")) self.label_5.setAlignment(Qt.AlignCenter) self.label_6.setObjectName(QString("label_6")) self.label_6.setGeometry(QRect(400, 240, 66, 17)) self.label_6.setFont(self.font1) self.label_6.setText(QString("Object")) self.label_6.setAlignment(Qt.AlignCenter) self.label_7.setObjectName(QString("label_7")) self.label_7.setGeometry(QRect(680, 390, 66, 17)) self.label_7.setFont(self.font1) self.label_7.setText(QString("Slicer")) self.label_7.setAlignment(Qt.AlignCenter) self.label_8.setObjectName(QString("label_8")) self.label_8.setGeometry(QRect(120, 390, 66, 17)) self.label_8.setFont(self.font1) self.label_8.setText(QString("Camera")) self.label_8.setAlignment(Qt.AlignCenter) self.label_9.setObjectName(QString("label_9")) self.label_9.setGeometry(QRect(400, 390, 66, 17)) self.label_9.setFont(self.font1) self.label_9.setText(QString("Object")) self.label_9.setAlignment(Qt.AlignCenter) self.line.setObjectName(QString("line")) self.line.setGeometry(QRect(20, 180, 831, 16)) self.line.setFrameShape(QFrame.HLine) self.line.setFrameShadow(QFrame.Sunken) self.line_2.setObjectName(QString("line_2")) self.line_2.setGeometry(QRect(20, 320, 831, 16)) self.line_2.setFrameShape(QFrame.HLine) self.line_2.setFrameShadow(QFrame.Sunken) def UpdateCoords(self, object,event,actor): pos = str(actor.GetPosition()) print pos #self._poslabel.setText(str(actor.GetPosition())
<filename>modules/gui/viztooldlg.py # -*- coding: utf-8 -*- """ Created on Wed Nov 14 18:02:14 2012 @author: alfredo """ from PyQt4.QtGui import * from PyQt4.Qwt5 import * from PyQt4.Qwt5.qplt import * from guiqwt import * from vtk.qt4.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor from guiqwt.plot import * from guiqwt.tools import * from guiqwt.config import * from guiqwt.builder import * import vtk import sys import csv import os class VizToolDlg(QWidget): def __init__(self, renwin): super(VizToolDlg,self).__init__() self.renwin = renwin self.init_ui() def init_ui(self): self.setWindowTitle("Parametric Rotation Controls") self.setMinimumSize(868,505) self.gamma_angle_counter = QwtCounter(self) self.gamma_angle_slider = QwtSlider(self) self.gamma_angle_label = QLabel(self) self.beta_angle_label = QLabel(self) self.alpha_angle_label = QLabel(self) self.gamma_angle_counter_2 = QwtCounter(self) self.gamma_angle_slider_2 = QwtSlider(self) self.gamma_angle_counter_3 = QwtCounter(self) self.gamma_angle_slider_3 = QwtSlider(self) self.gamma_angle_counter_4 = QwtCounter(self) self.gamma_angle_counter_5 = QwtCounter(self) self.gamma_angle_slider_4 = QwtSlider(self) self.gamma_angle_counter_6 = QwtCounter(self) self.gamma_angle_slider_5 = QwtSlider(self) self.gamma_angle_slider_6 = QwtSlider(self) self.gamma_angle_counter_7 = QwtCounter(self) self.gamma_angle_counter_8 = QwtCounter(self) self.gamma_angle_slider_7 = QwtSlider(self) self.gamma_angle_counter_9 = QwtCounter(self) self.gamma_angle_slider_8 = QwtSlider(self) self.gamma_angle_slider_9 = QwtSlider(self) self.label = QLabel(self) self.label_2 = QLabel(self) self.label_3 = QLabel(self) self.label_4 = QLabel(self) self.label_5 = QLabel(self) self.label_6 = QLabel(self) self.label_7 = QLabel(self) self.label_8 = QLabel(self) self.label_9 = QLabel(self) self.line = QFrame(self) self.line_2 = QFrame(self) self.font = QFont(self) self.gamma_angle_counter.setObjectName(QString("gamma_angle_counter")) self.gamma_angle_counter.setGeometry(QRect(20, 410, 271, 29)) self.gamma_angle_slider.setObjectName(QString("gamma_angle_slider")) self.gamma_angle_slider.setGeometry(QRect(20, 450, 271, 21)) self.gamma_angle_label.setObjectName(QString("gamma_angle_label")) self.gamma_angle_label.setGeometry(QRect(400, 350, 66, 17)) self.font.setBold(True) self.font.setItalic(True) self.font.setWeight(75) self.gamma_angle_label.setFont(self.font) self.gamma_angle_label.setAlignment(Qt.AlignCenter) self.gamma_angle_label.setText(QString("Gamma")) self.beta_angle_label.setObjectName(QString("beta_angle_label")) self.beta_angle_label.setGeometry(QRect(400, 200, 66, 17)) self.beta_angle_label.setFont(self.font) self.beta_angle_label.setText(QString("Beta")) self.beta_angle_label.setAlignment(Qt.AlignCenter) self.alpha_angle_label.setObjectName(QString("alpha_angle_label")) self.alpha_angle_label.setGeometry(QRect(400, 60, 66, 17)) self.alpha_angle_label.setFont(self.font) self.alpha_angle_label.setText(QString("Alpha")) self.alpha_angle_label.setAlignment(Qt.AlignCenter) self.gamma_angle_counter_2.setObjectName(QString("gamma_angle_counter_2")) self.gamma_angle_counter_2.setGeometry(QRect(300, 410, 271, 29)) self.gamma_angle_slider_2.setObjectName(QString("gamma_angle_slider_2")) self.gamma_angle_slider_2.setGeometry(QRect(300, 450, 271, 21)) self.gamma_angle_counter_3.setObjectName(QString("gamma_angle_counter_3")) self.gamma_angle_counter_3.setGeometry(QRect(580, 410, 271, 29)) self.gamma_angle_slider_3.setObjectName(QString("gamma_angle_slider_3")) self.gamma_angle_slider_3.setGeometry(QRect(580, 450, 271, 21)) self.gamma_angle_counter_4.setObjectName(QString("gamma_angle_counter_4")) self.gamma_angle_counter_4.setGeometry(QRect(20, 260, 271, 29)) self.gamma_angle_counter_5.setObjectName(QString("gamma_angle_counter_5")) self.gamma_angle_counter_5.setGeometry(QRect(300, 260, 271, 29)) self.gamma_angle_slider_4.setObjectName(QString("gamma_angle_slider_4")) self.gamma_angle_slider_4.setGeometry(QRect(300, 300, 271, 21)) self.gamma_angle_counter_6.setObjectName(QString("gamma_angle_counter_6")) self.gamma_angle_counter_6.setGeometry(QRect(580, 260, 271, 29)) self.gamma_angle_slider_5.setObjectName(QString("gamma_angle_slider_5")) self.gamma_angle_slider_5.setGeometry(QRect(20, 300, 271, 21)) self.gamma_angle_slider_6.setObjectName(QString("gamma_angle_slider_6")) self.gamma_angle_slider_6.setGeometry(QRect(580, 300, 271, 21)) self.gamma_angle_counter_7.setObjectName(QString("gamma_angle_counter_7")) self.gamma_angle_counter_7.setGeometry(QRect(20, 120, 271, 29)) self.gamma_angle_counter_8.setObjectName(QString("gamma_angle_counter_8")) self.gamma_angle_counter_8.setGeometry(QRect(300, 120, 271, 29)) self.gamma_angle_slider_7.setObjectName(QString("gamma_angle_slider_7")) self.gamma_angle_slider_7.setGeometry(QRect(300, 160, 271, 21)) self.gamma_angle_counter_9.setObjectName(QString("gamma_angle_counter_9")) self.gamma_angle_counter_9.setGeometry(QRect(580, 120, 271, 29)) self.gamma_angle_slider_8.setObjectName(QString("gamma_angle_slider_8")) self.gamma_angle_slider_8.setGeometry(QRect(20, 160, 271, 21)) self.gamma_angle_slider_9.setObjectName(QString("gamma_angle_slider_9")) self.gamma_angle_slider_9.setGeometry(QRect(580, 160, 271, 21)) self.label.setObjectName(QString("label")) self.label.setGeometry(QRect(120, 100, 66, 17)) self.font1 = QFont(self) self.font1.setItalic(True) self.label.setFont(self.font1) self.label.setText(QString("Camera")) self.label.setAlignment(Qt.AlignCenter) self.label_2.setObjectName(QString("label_2")) self.label_2.setGeometry(QRect(400, 100, 66, 17)) self.label_2.setFont(self.font1) self.label_2.setText(QString("Object")) self.label_2.setAlignment(Qt.AlignCenter) self.label_3.setObjectName(QString("label_3")) self.label_3.setGeometry(QRect(680, 100, 66, 17)) self.label_3.setFont(self.font1) self.label_3.setText(QString("Slicer")) self.label_3.setAlignment(Qt.AlignCenter) self.label_4.setObjectName(QString("label_4")) self.label_4.setGeometry(QRect(680, 240, 66, 17)) self.label_4.setFont(self.font1) self.label_4.setText(QString("Slicer")) self.label_4.setAlignment(Qt.AlignCenter) self.label_5.setObjectName(QString("label_5")) self.label_5.setGeometry(QRect(120, 240, 66, 17)) self.label_5.setFont(self.font1) self.label_5.setText(QString("Camera")) self.label_5.setAlignment(Qt.AlignCenter) self.label_6.setObjectName(QString("label_6")) self.label_6.setGeometry(QRect(400, 240, 66, 17)) self.label_6.setFont(self.font1) self.label_6.setText(QString("Object")) self.label_6.setAlignment(Qt.AlignCenter) self.label_7.setObjectName(QString("label_7")) self.label_7.setGeometry(QRect(680, 390, 66, 17)) self.label_7.setFont(self.font1) self.label_7.setText(QString("Slicer")) self.label_7.setAlignment(Qt.AlignCenter) self.label_8.setObjectName(QString("label_8")) self.label_8.setGeometry(QRect(120, 390, 66, 17)) self.label_8.setFont(self.font1) self.label_8.setText(QString("Camera")) self.label_8.setAlignment(Qt.AlignCenter) self.label_9.setObjectName(QString("label_9")) self.label_9.setGeometry(QRect(400, 390, 66, 17)) self.label_9.setFont(self.font1) self.label_9.setText(QString("Object")) self.label_9.setAlignment(Qt.AlignCenter) self.line.setObjectName(QString("line")) self.line.setGeometry(QRect(20, 180, 831, 16)) self.line.setFrameShape(QFrame.HLine) self.line.setFrameShadow(QFrame.Sunken) self.line_2.setObjectName(QString("line_2")) self.line_2.setGeometry(QRect(20, 320, 831, 16)) self.line_2.setFrameShape(QFrame.HLine) self.line_2.setFrameShadow(QFrame.Sunken) def UpdateCoords(self, object,event,actor): pos = str(actor.GetPosition()) print pos #self._poslabel.setText(str(actor.GetPosition())
en
0.393492
# -*- coding: utf-8 -*- Created on Wed Nov 14 18:02:14 2012 @author: alfredo #self._poslabel.setText(str(actor.GetPosition())
1.955745
2
danesfield/segmentation/semantic/tasks/concrete_eval.py
willdunklin/Danesfield
96
6619623
############################################################################### # Copyright Kitware Inc. and Contributors # Distributed under the Apache License, 2.0 (apache.org/licenses/LICENSE-2.0) # See accompanying Copyright.txt and LICENSE files for details ############################################################################### import os import cv2 import numpy as np from osgeo import gdal from osgeo.gdalnumeric import CopyDatasetInfo from .eval import Evaluator import shutil class FullImageEvaluator(Evaluator): """ Mixin for processing not crops """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def process_data(self, predicted, model, data, prefix=""): names, samples, masks = self.get_data(data) for i in range(len(names)): self.prev_name = names[i] self.full_pred = np.squeeze(predicted[i, ...]) if samples is not None: self.full_image = (samples[i, ...] * 255).astype(np.uint8) if masks is not None: self.full_mask = (np.squeeze(masks[i, ...]) * 255).astype(np.uint8) self.on_image_constructed(prefix) def save(self, name, prefix=""): cv2.imwrite(os.path.join(self.config.results_dir, 'results', self.config.folder, 'mask_{}'.format(name)), (self.full_pred * 255).astype(np.uint8)) class GdalSaver(Evaluator): """ Mixin for gdal data type """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.paths = self.ds.paths path = os.path.join(self.config.results_dir, 'results', self.config.folder) shutil.rmtree(path, True) if not os.path.exists(path): os.makedirs(path, exist_ok=True) def save(self, name, prefix=""): has_mask = False ref_file = os.path.join(self.paths['images'], name) res_path_geo = os.path.join(self.config.results_dir, 'results', self.config.folder, prefix + name) driver = gdal.GetDriverByName('GTiff') outRaster = driver.Create(res_path_geo, self.full_pred.shape[1], self.full_pred.shape[0], 1, gdal.GDT_Float32) if os.path.isfile(ref_file): gdalData = gdal.Open(ref_file, gdal.GA_ReadOnly) nodata = gdalData.GetRasterBand(1).GetNoDataValue() if has_mask: mask = np.array(gdalData.GetRasterBand(4).ReadAsArray()) empty_mask = np.zeros((self.full_pred.shape[0], self.full_pred.shape[1])) empty_mask[0:mask.shape[0], 0:mask.shape[1]] = mask empty_mask = np.invert(empty_mask.astype(np.bool)) self.full_pred[empty_mask] = nodata geoTrans = gdalData.GetGeoTransform() outRaster.SetGeoTransform(geoTrans) CopyDatasetInfo(gdalData, outRaster) outband = outRaster.GetRasterBand(1) outband.WriteArray(self.full_pred) outRaster.FlushCache() class GdalFullEvaluator(GdalSaver, FullImageEvaluator): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def save(self, name, prefix=""): print('prefix = ' + prefix + ', name = ' + name) name = name.replace('.png', '.tif') GdalSaver.save(self, name, prefix)
############################################################################### # Copyright Kitware Inc. and Contributors # Distributed under the Apache License, 2.0 (apache.org/licenses/LICENSE-2.0) # See accompanying Copyright.txt and LICENSE files for details ############################################################################### import os import cv2 import numpy as np from osgeo import gdal from osgeo.gdalnumeric import CopyDatasetInfo from .eval import Evaluator import shutil class FullImageEvaluator(Evaluator): """ Mixin for processing not crops """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def process_data(self, predicted, model, data, prefix=""): names, samples, masks = self.get_data(data) for i in range(len(names)): self.prev_name = names[i] self.full_pred = np.squeeze(predicted[i, ...]) if samples is not None: self.full_image = (samples[i, ...] * 255).astype(np.uint8) if masks is not None: self.full_mask = (np.squeeze(masks[i, ...]) * 255).astype(np.uint8) self.on_image_constructed(prefix) def save(self, name, prefix=""): cv2.imwrite(os.path.join(self.config.results_dir, 'results', self.config.folder, 'mask_{}'.format(name)), (self.full_pred * 255).astype(np.uint8)) class GdalSaver(Evaluator): """ Mixin for gdal data type """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.paths = self.ds.paths path = os.path.join(self.config.results_dir, 'results', self.config.folder) shutil.rmtree(path, True) if not os.path.exists(path): os.makedirs(path, exist_ok=True) def save(self, name, prefix=""): has_mask = False ref_file = os.path.join(self.paths['images'], name) res_path_geo = os.path.join(self.config.results_dir, 'results', self.config.folder, prefix + name) driver = gdal.GetDriverByName('GTiff') outRaster = driver.Create(res_path_geo, self.full_pred.shape[1], self.full_pred.shape[0], 1, gdal.GDT_Float32) if os.path.isfile(ref_file): gdalData = gdal.Open(ref_file, gdal.GA_ReadOnly) nodata = gdalData.GetRasterBand(1).GetNoDataValue() if has_mask: mask = np.array(gdalData.GetRasterBand(4).ReadAsArray()) empty_mask = np.zeros((self.full_pred.shape[0], self.full_pred.shape[1])) empty_mask[0:mask.shape[0], 0:mask.shape[1]] = mask empty_mask = np.invert(empty_mask.astype(np.bool)) self.full_pred[empty_mask] = nodata geoTrans = gdalData.GetGeoTransform() outRaster.SetGeoTransform(geoTrans) CopyDatasetInfo(gdalData, outRaster) outband = outRaster.GetRasterBand(1) outband.WriteArray(self.full_pred) outRaster.FlushCache() class GdalFullEvaluator(GdalSaver, FullImageEvaluator): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def save(self, name, prefix=""): print('prefix = ' + prefix + ', name = ' + name) name = name.replace('.png', '.tif') GdalSaver.save(self, name, prefix)
de
0.406201
############################################################################### # Copyright Kitware Inc. and Contributors # Distributed under the Apache License, 2.0 (apache.org/licenses/LICENSE-2.0) # See accompanying Copyright.txt and LICENSE files for details ############################################################################### Mixin for processing not crops Mixin for gdal data type
2.107419
2
src/nadav_try.py
guysoft/WaveCatchers
0
6619624
<reponame>guysoft/WaveCatchers<filename>src/nadav_try.py import os from os.path import isfile, join import pandas as pd from FFT_pipeline import my_fft, multiplied_fft basic_path = os.path.realpath(os.path.join(os.path.dirname(__file__), "..")) dataset_path = join(path, "dataset", "dataset1") freq, FFT = [my_fft(file) for file in os.listdir(dataset_path) if isfile(join(dataset_path, file))]
import os from os.path import isfile, join import pandas as pd from FFT_pipeline import my_fft, multiplied_fft basic_path = os.path.realpath(os.path.join(os.path.dirname(__file__), "..")) dataset_path = join(path, "dataset", "dataset1") freq, FFT = [my_fft(file) for file in os.listdir(dataset_path) if isfile(join(dataset_path, file))]
none
1
2.527339
3
tests/test_fragments.py
leelasd/molfunc
1
6619625
<filename>tests/test_fragments.py from molfunc.fragments import fragments, all_aliases, all_smiles from molfunc.fragments import LibFragmentMolecule from molfunc.fragments import get_fragment_molecule from molfunc.fragments import get_smiles_aliases from molfunc.exceptions import MolFuncCritical import pytest import os here = os.path.dirname(os.path.abspath(__file__)) def test_general_structure(): assert len(fragments) > 0 assert isinstance(fragments[0], LibFragmentMolecule) assert 'me' in all_aliases assert 'C[*]' in all_smiles def test_get_fragment_molecule(): methyl = get_fragment_molecule(name='me') assert methyl.n_atoms == 4 methyl = get_fragment_molecule(smiles='C[*]') assert methyl.n_atoms == 4 with pytest.raises(MolFuncCritical): # Cannot get a fragment with no name or SMILES string _ = get_fragment_molecule() not_a_valid_fragment = get_fragment_molecule(name='xxxx') assert not_a_valid_fragment is None def test_fragment_from_file(): benzene_file_path = os.path.join(here, 'data', 'benzene.xyz') with pytest.raises(MolFuncCritical): # This xyz file has no aliases, so should break making the fragment _ = get_smiles_aliases(filename=benzene_file_path)
<filename>tests/test_fragments.py from molfunc.fragments import fragments, all_aliases, all_smiles from molfunc.fragments import LibFragmentMolecule from molfunc.fragments import get_fragment_molecule from molfunc.fragments import get_smiles_aliases from molfunc.exceptions import MolFuncCritical import pytest import os here = os.path.dirname(os.path.abspath(__file__)) def test_general_structure(): assert len(fragments) > 0 assert isinstance(fragments[0], LibFragmentMolecule) assert 'me' in all_aliases assert 'C[*]' in all_smiles def test_get_fragment_molecule(): methyl = get_fragment_molecule(name='me') assert methyl.n_atoms == 4 methyl = get_fragment_molecule(smiles='C[*]') assert methyl.n_atoms == 4 with pytest.raises(MolFuncCritical): # Cannot get a fragment with no name or SMILES string _ = get_fragment_molecule() not_a_valid_fragment = get_fragment_molecule(name='xxxx') assert not_a_valid_fragment is None def test_fragment_from_file(): benzene_file_path = os.path.join(here, 'data', 'benzene.xyz') with pytest.raises(MolFuncCritical): # This xyz file has no aliases, so should break making the fragment _ = get_smiles_aliases(filename=benzene_file_path)
en
0.709561
# Cannot get a fragment with no name or SMILES string # This xyz file has no aliases, so should break making the fragment
2.229473
2
Chapter 13/ch13_r03.py
PacktPublishing/Modern-Python-Cookbook
107
6619626
"""Python Cookbook Chapter 13, recipe 3. """ def load_config_file(config_file) -> dict: '''Loads a configuration mapping object with contents of a given file. :param config_file: File-like object that can be read. :returns: mapping with configuration parameter values ''' code = compile(config_file.read(), config_file.name, 'exec') locals = {} exec(code, {'__builtins__':__builtins__}, locals) return locals from pathlib import Path import platform def load_config_file_path(config_file) -> dict: code = compile(config_file.read(), config_file.name, 'exec') globals = {'__builtins__':__builtins__, 'Path': Path, 'platform': platform} locals = {} exec(code, globals, locals) return locals import io settings_file = io.StringIO(""" '''Weather forecast for Offshore including the Bahamas ''' query = {'mz': ['ANZ532', 'AMZ117', 'AMZ080']} url = { 'scheme': 'http', 'netloc': 'forecast.weather.gov', 'path': '/shmrn.php' } """) # Add a ``name`` attribute to mimic a file settings_file.name = 'settings.py' settings_file_2 = io.StringIO( ''' base = Path('/var/app/') log = base/'log' out = base/'out' ''' ) # Add a ``name`` attribute to mimic a file settings_file_2.name = 'settings.py' __test__ = { 'load_config_file': ''' >>> from pprint import pprint >>> pprint(load_config_file(settings_file)) {'__doc__': 'Weather forecast for Offshore including the Bahamas\\n', 'query': {'mz': ['ANZ532', 'AMZ117', 'AMZ080']}, 'url': {'netloc': 'forecast.weather.gov', 'path': '/shmrn.php', 'scheme': 'http'}} ''', 'load_config_file_path': ''' >>> from pprint import pprint >>> settings = load_config_file_path(settings_file_2) >>> pprint(settings) {'base': PosixPath('/var/app'), 'log': PosixPath('/var/app/log'), 'out': PosixPath('/var/app/out')} ''' } if __name__ == "__main__": import doctest doctest.testmod()
"""Python Cookbook Chapter 13, recipe 3. """ def load_config_file(config_file) -> dict: '''Loads a configuration mapping object with contents of a given file. :param config_file: File-like object that can be read. :returns: mapping with configuration parameter values ''' code = compile(config_file.read(), config_file.name, 'exec') locals = {} exec(code, {'__builtins__':__builtins__}, locals) return locals from pathlib import Path import platform def load_config_file_path(config_file) -> dict: code = compile(config_file.read(), config_file.name, 'exec') globals = {'__builtins__':__builtins__, 'Path': Path, 'platform': platform} locals = {} exec(code, globals, locals) return locals import io settings_file = io.StringIO(""" '''Weather forecast for Offshore including the Bahamas ''' query = {'mz': ['ANZ532', 'AMZ117', 'AMZ080']} url = { 'scheme': 'http', 'netloc': 'forecast.weather.gov', 'path': '/shmrn.php' } """) # Add a ``name`` attribute to mimic a file settings_file.name = 'settings.py' settings_file_2 = io.StringIO( ''' base = Path('/var/app/') log = base/'log' out = base/'out' ''' ) # Add a ``name`` attribute to mimic a file settings_file_2.name = 'settings.py' __test__ = { 'load_config_file': ''' >>> from pprint import pprint >>> pprint(load_config_file(settings_file)) {'__doc__': 'Weather forecast for Offshore including the Bahamas\\n', 'query': {'mz': ['ANZ532', 'AMZ117', 'AMZ080']}, 'url': {'netloc': 'forecast.weather.gov', 'path': '/shmrn.php', 'scheme': 'http'}} ''', 'load_config_file_path': ''' >>> from pprint import pprint >>> settings = load_config_file_path(settings_file_2) >>> pprint(settings) {'base': PosixPath('/var/app'), 'log': PosixPath('/var/app/log'), 'out': PosixPath('/var/app/out')} ''' } if __name__ == "__main__": import doctest doctest.testmod()
en
0.452536
Python Cookbook Chapter 13, recipe 3. Loads a configuration mapping object with contents of a given file. :param config_file: File-like object that can be read. :returns: mapping with configuration parameter values '''Weather forecast for Offshore including the Bahamas ''' query = {'mz': ['ANZ532', 'AMZ117', 'AMZ080']} url = { 'scheme': 'http', 'netloc': 'forecast.weather.gov', 'path': '/shmrn.php' } # Add a ``name`` attribute to mimic a file base = Path('/var/app/') log = base/'log' out = base/'out' # Add a ``name`` attribute to mimic a file >>> from pprint import pprint >>> pprint(load_config_file(settings_file)) {'__doc__': 'Weather forecast for Offshore including the Bahamas\\n', 'query': {'mz': ['ANZ532', 'AMZ117', 'AMZ080']}, 'url': {'netloc': 'forecast.weather.gov', 'path': '/shmrn.php', 'scheme': 'http'}} >>> from pprint import pprint >>> settings = load_config_file_path(settings_file_2) >>> pprint(settings) {'base': PosixPath('/var/app'), 'log': PosixPath('/var/app/log'), 'out': PosixPath('/var/app/out')}
3.008955
3
collection/choices.py
Zadigo/mycommerce
0
6619627
from django.db.models import Choices from django.utils.translation import gettext_lazy as _ # TODO: This requires more categories # including personalized ones class CollectionCategoryChoices(Choices): ACCESSORIES = _('Accessories') ACTIVEWEAR = _('Activewear') BAGS = _('Bags') BRAS = _('Bras') DENIM = _('Denim') DRESSES = _('Dresses') PANTS = _('Pants') PANTIES = _('Panties') SHOES = _('Shoes') SHORTS = _('Shorts') SUITS = _('Suits') TOPS = _('Tops')
from django.db.models import Choices from django.utils.translation import gettext_lazy as _ # TODO: This requires more categories # including personalized ones class CollectionCategoryChoices(Choices): ACCESSORIES = _('Accessories') ACTIVEWEAR = _('Activewear') BAGS = _('Bags') BRAS = _('Bras') DENIM = _('Denim') DRESSES = _('Dresses') PANTS = _('Pants') PANTIES = _('Panties') SHOES = _('Shoes') SHORTS = _('Shorts') SUITS = _('Suits') TOPS = _('Tops')
en
0.761405
# TODO: This requires more categories # including personalized ones
2.212009
2
streamlit_app.py
fhebal/kkbox-survival-app
0
6619628
import streamlit as st import pandas as pd from pandas import CategoricalDtype from lifelines.datasets import load_rossi from lifelines import WeibullAFTFitter from utils import plotter, read_config from joblib import dump, load import json # SETUP # st.set_page_config(layout="wide") df = pd.read_csv('./data/imputed_consumer.csv', nrows=100) model = load('model/churn.joblib') with open('scoring_dict.json', 'r') as f: scoring_dict = json.loads(f.read()) DURATION = 'duration' EVENT = 'observed' cfg = read_config('data_dictionary.yaml') # INDIVIDAL PREDICTIONS st.sidebar.title("Individual Prediction") slider_1 = st.sidebar.slider('bd', 0, 100) slider_2 = st.sidebar.slider('latest_payment_plan_days',0, 30) slider_3 = st.sidebar.slider('avg_num_unq',0, 100) slider_4 = st.sidebar.slider('duration', 0, 50) slider_5 = st.sidebar.selectbox('is_auto_renew_1', [0, 1]) slider_6 = st.sidebar.selectbox('observed', [0, 1]) slider_7 = st.sidebar.selectbox('gender_1.0', [0, 1]) select_options = [x for x in scoring_dict.keys() if 'latest_payment_method' in x] selectbox = st.sidebar.selectbox('Select ONE', select_options) scoring_dict['bd'] = slider_1 scoring_dict['latest_payment_plan_days'] = slider_2 scoring_dict['avg_num_unq'] = slider_3 scoring_dict['duration'] = slider_4 scoring_dict['is_auto_renew_1'] = slider_5 scoring_dict['observed'] = slider_6 scoring_dict['gender_1.0'] = slider_7 scoring_dict[selectbox] = 1 prediction_output = model.predict_expectation(pd.DataFrame(scoring_dict),conditional_after=pd.DataFrame(scoring_dict)['duration']).values[0].round(0).astype(int) #predict_input = pd.DataFrame([week, 0, fin, age, 1, 1, mar, paro, 1]).T #predict_input.columns = ['week', 'arrest', 'fin', 'age', 'race', 'wexp', 'mar', 'paro', 'prio'] st.sidebar.write("## Weeks until churn:", round(prediction_output)) # custom features # STREAMLIT CODE st.title('KKBox Survival Analysis') st.write("Data source: " + 'https://www.kaggle.com/c/kkbox-churn-prediction-challenge/data') st.write('''In this challenge, you are asked to predict whether a user will churn after his/her subscription expires. Specifically, we want to forecast if a user make a new service subscription transaction within 30 days after the current membership expiration date.''') col1 = st.beta_columns(1) # KAPLAN MEIER CURVES drop_cols = [ 'customer_id', 'bd', 'city', 'reg_month', 'tx_last_date', 'mem_end_date', 'latest_actual_amount_paid', 'latest_payment_method_id', 'avg_tot_secs', 'avg_num_unq', 'duration' ] st.title('Kaplan-Meier Curves') option = st.selectbox( '', [x for x in df.columns if x not in drop_cols]) plt = plotter(df, option, DURATION, EVENT, CategoricalDtype) KM_plot = st.pyplot(plt) st.title("Model Summary") st.write(model.summary) # COX PROPORTIONAL HAZARDS SUMMARY #from lifelines import CoxPHFitter #rossi= load_rossi() #st.title('Regression Model Summary') #cph = CoxPHFitter() #cph.fit(df, duration_col=DURATION, event_col=EVENT) #st.write("## Coefficients") #cols = ['coef','exp(coef)', 'exp(coef) lower 95%', 'exp(coef) upper 95%', 'p'] #cph.summary[cols] #st.write("## Summary") #col_2 = [ # cph._n_examples, # sum(cph.event_observed), # cph.baseline_estimation_method, # cph.event_col, # cph.duration_col, # cph._class_name, # cph.log_likelihood_, # cph.concordance_index_, # cph.AIC_partial_] #col_1 = [ # 'observations', # 'events_oberved', # 'baseline estimation', # 'event column', # 'duration column', # 'model', # 'log likelihood', # 'concordance', # 'partial AIC' #] #results = pd.DataFrame([col_1,col_2]).T #results.columns = ['', ' '] #results.set_index('') #results
import streamlit as st import pandas as pd from pandas import CategoricalDtype from lifelines.datasets import load_rossi from lifelines import WeibullAFTFitter from utils import plotter, read_config from joblib import dump, load import json # SETUP # st.set_page_config(layout="wide") df = pd.read_csv('./data/imputed_consumer.csv', nrows=100) model = load('model/churn.joblib') with open('scoring_dict.json', 'r') as f: scoring_dict = json.loads(f.read()) DURATION = 'duration' EVENT = 'observed' cfg = read_config('data_dictionary.yaml') # INDIVIDAL PREDICTIONS st.sidebar.title("Individual Prediction") slider_1 = st.sidebar.slider('bd', 0, 100) slider_2 = st.sidebar.slider('latest_payment_plan_days',0, 30) slider_3 = st.sidebar.slider('avg_num_unq',0, 100) slider_4 = st.sidebar.slider('duration', 0, 50) slider_5 = st.sidebar.selectbox('is_auto_renew_1', [0, 1]) slider_6 = st.sidebar.selectbox('observed', [0, 1]) slider_7 = st.sidebar.selectbox('gender_1.0', [0, 1]) select_options = [x for x in scoring_dict.keys() if 'latest_payment_method' in x] selectbox = st.sidebar.selectbox('Select ONE', select_options) scoring_dict['bd'] = slider_1 scoring_dict['latest_payment_plan_days'] = slider_2 scoring_dict['avg_num_unq'] = slider_3 scoring_dict['duration'] = slider_4 scoring_dict['is_auto_renew_1'] = slider_5 scoring_dict['observed'] = slider_6 scoring_dict['gender_1.0'] = slider_7 scoring_dict[selectbox] = 1 prediction_output = model.predict_expectation(pd.DataFrame(scoring_dict),conditional_after=pd.DataFrame(scoring_dict)['duration']).values[0].round(0).astype(int) #predict_input = pd.DataFrame([week, 0, fin, age, 1, 1, mar, paro, 1]).T #predict_input.columns = ['week', 'arrest', 'fin', 'age', 'race', 'wexp', 'mar', 'paro', 'prio'] st.sidebar.write("## Weeks until churn:", round(prediction_output)) # custom features # STREAMLIT CODE st.title('KKBox Survival Analysis') st.write("Data source: " + 'https://www.kaggle.com/c/kkbox-churn-prediction-challenge/data') st.write('''In this challenge, you are asked to predict whether a user will churn after his/her subscription expires. Specifically, we want to forecast if a user make a new service subscription transaction within 30 days after the current membership expiration date.''') col1 = st.beta_columns(1) # KAPLAN MEIER CURVES drop_cols = [ 'customer_id', 'bd', 'city', 'reg_month', 'tx_last_date', 'mem_end_date', 'latest_actual_amount_paid', 'latest_payment_method_id', 'avg_tot_secs', 'avg_num_unq', 'duration' ] st.title('Kaplan-Meier Curves') option = st.selectbox( '', [x for x in df.columns if x not in drop_cols]) plt = plotter(df, option, DURATION, EVENT, CategoricalDtype) KM_plot = st.pyplot(plt) st.title("Model Summary") st.write(model.summary) # COX PROPORTIONAL HAZARDS SUMMARY #from lifelines import CoxPHFitter #rossi= load_rossi() #st.title('Regression Model Summary') #cph = CoxPHFitter() #cph.fit(df, duration_col=DURATION, event_col=EVENT) #st.write("## Coefficients") #cols = ['coef','exp(coef)', 'exp(coef) lower 95%', 'exp(coef) upper 95%', 'p'] #cph.summary[cols] #st.write("## Summary") #col_2 = [ # cph._n_examples, # sum(cph.event_observed), # cph.baseline_estimation_method, # cph.event_col, # cph.duration_col, # cph._class_name, # cph.log_likelihood_, # cph.concordance_index_, # cph.AIC_partial_] #col_1 = [ # 'observations', # 'events_oberved', # 'baseline estimation', # 'event column', # 'duration column', # 'model', # 'log likelihood', # 'concordance', # 'partial AIC' #] #results = pd.DataFrame([col_1,col_2]).T #results.columns = ['', ' '] #results.set_index('') #results
en
0.399565
# SETUP # st.set_page_config(layout="wide") # INDIVIDAL PREDICTIONS #predict_input = pd.DataFrame([week, 0, fin, age, 1, 1, mar, paro, 1]).T #predict_input.columns = ['week', 'arrest', 'fin', 'age', 'race', 'wexp', 'mar', 'paro', 'prio'] # Weeks until churn:", round(prediction_output)) # custom features # STREAMLIT CODE In this challenge, you are asked to predict whether a user will churn after his/her subscription expires. Specifically, we want to forecast if a user make a new service subscription transaction within 30 days after the current membership expiration date. # KAPLAN MEIER CURVES # COX PROPORTIONAL HAZARDS SUMMARY #from lifelines import CoxPHFitter #rossi= load_rossi() #st.title('Regression Model Summary') #cph = CoxPHFitter() #cph.fit(df, duration_col=DURATION, event_col=EVENT) #st.write("## Coefficients") #cols = ['coef','exp(coef)', 'exp(coef) lower 95%', 'exp(coef) upper 95%', 'p'] #cph.summary[cols] #st.write("## Summary") #col_2 = [ # cph._n_examples, # sum(cph.event_observed), # cph.baseline_estimation_method, # cph.event_col, # cph.duration_col, # cph._class_name, # cph.log_likelihood_, # cph.concordance_index_, # cph.AIC_partial_] #col_1 = [ # 'observations', # 'events_oberved', # 'baseline estimation', # 'event column', # 'duration column', # 'model', # 'log likelihood', # 'concordance', # 'partial AIC' #] #results = pd.DataFrame([col_1,col_2]).T #results.columns = ['', ' '] #results.set_index('') #results
2.311892
2
tests/conftest.py
OlgaKuratkina/cajitos
0
6619629
import peewee as pw import pytest from mixer.backend.peewee import mixer from cajitos_site import db from cajitos_site import models as mod from cajitos_site.utils.utils import get_models_from_module @pytest.fixture(scope='function') def app(): from cajitos_site import create_app app = create_app(None, 'cajitos_site.settings.test') app.app_context().push() _init_db(db) yield app _shutdown_db(db) def _init_db(db): tables = get_models_from_module(mod) db.create_tables(tables) user1 = mixer.blend(mod.User, email=mixer.RANDOM) user2 = mixer.blend(mod.User, email=mixer.RANDOM) mixer.cycle(5).blend(mod.Post, author=user1, title=mixer.RANDOM, content=mixer.RANDOM) mixer.cycle(5).blend(mod.Post, author=user2, title=mixer.RANDOM, content=mixer.RANDOM) mod.Followers.create(following_user=user2, followed_user=user1) def _shutdown_db(db): tables = get_models_from_module(mod) db.drop_tables(tables) @pytest.fixture def user(): return mixer.blend(mod.User, username='John', email='<EMAIL>', password='<PASSWORD>') # @pytest.fixture(scope='session') # def db_session(app): # from cajitos_site import db # db.drop_all() # db.create_all() # return db # # # @pytest.yield_fixture(scope='function', autouse=True) # def db(app, db_session): # try: # yield db_session # finally: # db_session.session.rollback() # table_names = ', '.join('"{0}"'.format(table) for table in db_session.get_tables_for_bind()) # db_session.engine.execute('TRUNCATE {0} RESTART IDENTITY'.format(table_names)) # db_session.session.commit()
import peewee as pw import pytest from mixer.backend.peewee import mixer from cajitos_site import db from cajitos_site import models as mod from cajitos_site.utils.utils import get_models_from_module @pytest.fixture(scope='function') def app(): from cajitos_site import create_app app = create_app(None, 'cajitos_site.settings.test') app.app_context().push() _init_db(db) yield app _shutdown_db(db) def _init_db(db): tables = get_models_from_module(mod) db.create_tables(tables) user1 = mixer.blend(mod.User, email=mixer.RANDOM) user2 = mixer.blend(mod.User, email=mixer.RANDOM) mixer.cycle(5).blend(mod.Post, author=user1, title=mixer.RANDOM, content=mixer.RANDOM) mixer.cycle(5).blend(mod.Post, author=user2, title=mixer.RANDOM, content=mixer.RANDOM) mod.Followers.create(following_user=user2, followed_user=user1) def _shutdown_db(db): tables = get_models_from_module(mod) db.drop_tables(tables) @pytest.fixture def user(): return mixer.blend(mod.User, username='John', email='<EMAIL>', password='<PASSWORD>') # @pytest.fixture(scope='session') # def db_session(app): # from cajitos_site import db # db.drop_all() # db.create_all() # return db # # # @pytest.yield_fixture(scope='function', autouse=True) # def db(app, db_session): # try: # yield db_session # finally: # db_session.session.rollback() # table_names = ', '.join('"{0}"'.format(table) for table in db_session.get_tables_for_bind()) # db_session.engine.execute('TRUNCATE {0} RESTART IDENTITY'.format(table_names)) # db_session.session.commit()
en
0.46778
# @pytest.fixture(scope='session') # def db_session(app): # from cajitos_site import db # db.drop_all() # db.create_all() # return db # # # @pytest.yield_fixture(scope='function', autouse=True) # def db(app, db_session): # try: # yield db_session # finally: # db_session.session.rollback() # table_names = ', '.join('"{0}"'.format(table) for table in db_session.get_tables_for_bind()) # db_session.engine.execute('TRUNCATE {0} RESTART IDENTITY'.format(table_names)) # db_session.session.commit()
1.997333
2
aioreactive/testing/observer.py
tr11/aioreactive
0
6619630
from typing import TypeVar from aioreactive.core.bases import AsyncObserverBase from aioreactive.core.utils import anoop T = TypeVar('T') class AsyncAnonymousObserver(AsyncObserverBase): """A test AsyncAnonymousObserver. Records all values and events that happens and makes them available through the values property: The values are recorded as tuples: - sends: (time, T) - throws: (time, err) - close: (time,) Note: we will not see the difference between sent and thrown exceptions. This should however not be any problem, and we have decided to keep it this way for simplicity. """ def __init__(self, send=anoop, throw=anoop, close=anoop): super().__init__() self._values = [] self._send = send self._throw = throw self._close = close async def asend_core(self, value: T): print("AsyncAnonymousObserver:asend_core(%d)" % value) time = self._loop.time() self._values.append((time, value)) await self._send(value) async def athrow_core(self, err: Exception): time = self._loop.time() self._values.append((time, err)) await self._throw(err) async def aclose_core(self): time = self._loop.time() self._values.append((time,)) await self._close() @property def values(self): return self._values
from typing import TypeVar from aioreactive.core.bases import AsyncObserverBase from aioreactive.core.utils import anoop T = TypeVar('T') class AsyncAnonymousObserver(AsyncObserverBase): """A test AsyncAnonymousObserver. Records all values and events that happens and makes them available through the values property: The values are recorded as tuples: - sends: (time, T) - throws: (time, err) - close: (time,) Note: we will not see the difference between sent and thrown exceptions. This should however not be any problem, and we have decided to keep it this way for simplicity. """ def __init__(self, send=anoop, throw=anoop, close=anoop): super().__init__() self._values = [] self._send = send self._throw = throw self._close = close async def asend_core(self, value: T): print("AsyncAnonymousObserver:asend_core(%d)" % value) time = self._loop.time() self._values.append((time, value)) await self._send(value) async def athrow_core(self, err: Exception): time = self._loop.time() self._values.append((time, err)) await self._throw(err) async def aclose_core(self): time = self._loop.time() self._values.append((time,)) await self._close() @property def values(self): return self._values
en
0.937922
A test AsyncAnonymousObserver. Records all values and events that happens and makes them available through the values property: The values are recorded as tuples: - sends: (time, T) - throws: (time, err) - close: (time,) Note: we will not see the difference between sent and thrown exceptions. This should however not be any problem, and we have decided to keep it this way for simplicity.
2.630738
3
tests/test_slides.py
abtawfik/pySlides
0
6619631
######################### # Load the main package # ######################### from .context import pyslides ################## # Testing module # ################## import pytest @pytest.mark.parametrize("attr", [('add'), ('save')]) def test_slides_has_needed_attrs(attr): assert hasattr(pyslides.Slides, attr)
######################### # Load the main package # ######################### from .context import pyslides ################## # Testing module # ################## import pytest @pytest.mark.parametrize("attr", [('add'), ('save')]) def test_slides_has_needed_attrs(attr): assert hasattr(pyslides.Slides, attr)
de
0.765382
######################### # Load the main package # ######################### ################## # Testing module # ##################
2.366574
2
P31.py
chaitraliv/Assignments
0
6619632
<reponame>chaitraliv/Assignments #SOLUTION FOR P31 #P31 (**) Determine whether a given integer number is prime. num = int(input('Enter any number = ')) if num >1: #CHECK ONLY FOR POSITIVE INTEGERS for i in range (2, num ): if (num % i) == 0: #IF REMENDER IS ZERO FOR ANY DIVISION,IT IS NOT PRIME print('is %d prime - F' %num) break else: print('is %d prime - T' % num) #ELSE IT IS PRIME else: print(num,'is not prime') #FOR NEGATIVE NUMBERS
#SOLUTION FOR P31 #P31 (**) Determine whether a given integer number is prime. num = int(input('Enter any number = ')) if num >1: #CHECK ONLY FOR POSITIVE INTEGERS for i in range (2, num ): if (num % i) == 0: #IF REMENDER IS ZERO FOR ANY DIVISION,IT IS NOT PRIME print('is %d prime - F' %num) break else: print('is %d prime - T' % num) #ELSE IT IS PRIME else: print(num,'is not prime') #FOR NEGATIVE NUMBERS
en
0.317785
#SOLUTION FOR P31 #P31 (**) Determine whether a given integer number is prime. #CHECK ONLY FOR POSITIVE INTEGERS #IF REMENDER IS ZERO FOR ANY DIVISION,IT IS NOT PRIME #ELSE IT IS PRIME #FOR NEGATIVE NUMBERS
4.146199
4
CodeExtractor.py
ArielBlG/stackoverflow_java_queries
0
6619633
<filename>CodeExtractor.py import re import pandas as pd class codeExtractor(): def __init__(self,dataset=None,path=None): """ Code Extractor Constructor - Recieves a dataset or path to a csv file and keeps the data as in Attribute. """ if path == None: self.data = dataset else: self.data = pd.read_csv(path) def extractCodes(self): """ extractCodes Function - cleans the dataset by removing unnecessary tags like <p> and keeps <code> tags. Return - dictionary -> title : codeslist """ new_data = self.data['body'] index = 0 code_dict = {} for data in new_data: code = [] row = re.sub('<p>.*?</p>', '', data) for curr_code in re.findall(r"<code>(.*?)</code>", row, flags=re.DOTALL): code.append(curr_code) code_dict[self.data['title'][index]] = code index+=1 return code_dict
<filename>CodeExtractor.py import re import pandas as pd class codeExtractor(): def __init__(self,dataset=None,path=None): """ Code Extractor Constructor - Recieves a dataset or path to a csv file and keeps the data as in Attribute. """ if path == None: self.data = dataset else: self.data = pd.read_csv(path) def extractCodes(self): """ extractCodes Function - cleans the dataset by removing unnecessary tags like <p> and keeps <code> tags. Return - dictionary -> title : codeslist """ new_data = self.data['body'] index = 0 code_dict = {} for data in new_data: code = [] row = re.sub('<p>.*?</p>', '', data) for curr_code in re.findall(r"<code>(.*?)</code>", row, flags=re.DOTALL): code.append(curr_code) code_dict[self.data['title'][index]] = code index+=1 return code_dict
en
0.679651
Code Extractor Constructor - Recieves a dataset or path to a csv file and keeps the data as in Attribute. extractCodes Function - cleans the dataset by removing unnecessary tags like <p> and keeps <code> tags. Return - dictionary -> title : codeslist
3.428143
3
main.py
UdonDa/normalizing-flows-pytorch
39
6619634
<filename>main.py import time import shutil import hydra import numpy as np import torch import torchvision from omegaconf import OmegaConf from torch.utils.tensorboard import SummaryWriter from torch.distributions.multivariate_normal import MultivariateNormal from flows import MAF, Glow, Ffjord, Flowpp, RealNVP, ResFlow, PlanarFlow from flows.misc import anomaly_hook from common.utils import image_plot, save_image, scatter_plot from flows.dataset import FlowDataLoader from flows.modules import Logit, Identity from common.logging import Logging networks = { 'planar': PlanarFlow, 'realnvp': RealNVP, 'glow': Glow, 'flow++': Flowpp, 'maf': MAF, 'resflow': ResFlow, 'ffjord': Ffjord, } # ----------------------------------------------- # logging # ----------------------------------------------- logger = Logging(__file__) # ----------------------------------------------- # train/eval model # ----------------------------------------------- class Model(object): def __init__(self, dims=(2, ), datatype=None, cfg=None): if torch.cuda.is_available(): self.device = torch.device('cuda', cfg.run.gpu) else: self.device = torch.device('cpu') self.name = cfg.network.name self.dims = dims self.dimension = np.prod(dims) mu = torch.zeros(self.dimension, dtype=torch.float32, device=self.device) covar = torch.eye(self.dimension, dtype=torch.float32, device=self.device) self.normal = MultivariateNormal(mu, covar) self.net = networks[self.name](dims=self.dims, datatype=datatype, cfg=cfg.network) self.net.to(self.device) if cfg.optimizer.name == 'rmsprop': self.optim = torch.optim.RMSprop(self.net.parameters(), lr=cfg.optimizer.lr, weight_decay=cfg.optimizer.weight_decay) elif cfg.optimizer.name == 'adam': self.optim = torch.optim.Adam(self.net.parameters(), lr=cfg.optimizer.lr, betas=(cfg.optimizer.beta1, cfg.optimizer.beta2), weight_decay=cfg.optimizer.weight_decay) else: raise Exception('optimizer "%s" is currently not supported' % (cfg.optimizer.name)) self.schduler = torch.optim.lr_scheduler.StepLR(self.optim, step_size=cfg.optimizer.decay_steps, gamma=cfg.optimizer.decay_ratio) def train(self): self.net.train() def eval(self): self.net.eval() def train_on_batch(self, y): y = y.to(self.device) y = y.contiguous() z, log_det_jacobian = self.net(y) z = z.view(y.size(0), -1) loss = -1.0 * torch.mean(self.normal.log_prob(z) + log_det_jacobian) self.optim.zero_grad() loss.backward() self.optim.step() self.schduler.step() return z, loss def save_ckpt(self, step, filename): ckpt = { 'net': self.net.state_dict(), 'optim': self.optim.state_dict(), 'step': step, } torch.save(ckpt, filename) def load_ckpt(self, filename): ckpt = torch.load(filename) self.net.load_state_dict(ckpt['net']) self.optim.load_state_dict(ckpt['optim']) epoch = ckpt['step'] return epoch def sample_y(self, n): z = self.sample_z(n) z = z.to(self.device) y, log_det_jacobians = self.net.backward(z.view(-1, *self.dims)) log_p = self.normal.log_prob(z) - log_det_jacobians return y, torch.exp(log_p) def sample_z(self, n): return self.normal.sample([n]) def log_py(self, y): y = y.to(self.device) z, log_det_jacobians = self.net(y) return self.log_pz(z) + log_det_jacobians def log_pz(self, z): return self.normal.log_prob(z) def py(self, y): return torch.exp(self.log_py(y)) def pz(self, z): return torch.exp(self.log_pz(z)) def report(self, writer, y_data, step=0, save_files=False): # set to evaluation mode self.net.eval() # prepare y_data = y_data.to(self.device) n_samples = y_data.size(0) if y_data.dim() == 2 and y_data.size(1) == 2: dtype = '2d' elif y_data.dim() == 2 and y_data.size(1) == 3: dtype = '3d' else: dtype = 'image' title = '%s_%d_steps' % (self.name, step) # testing if dtype == '2d': # plot data samples xs = y_data[:, 0].cpu().numpy() ys = y_data[:, 1].cpu().numpy() y_image = scatter_plot(xs, ys, title=title) writer.add_image('2d/data/y', y_image, step, dataformats='HWC') if save_image: out_file = 'y_data_{:06d}.jpg'.format(step) save_image(out_file, y_image) latest_file = 'y_data_latest.jpg' shutil.copyfile(out_file, latest_file) # plot latent samples z, _ = self.net(y_data) pz = self.pz(z) z = z.detach().cpu().numpy() pz = pz.detach().cpu().numpy() xs = z[:, 0] ys = z[:, 1] z_image = scatter_plot(xs, ys, colors=pz, title=title) writer.add_image('2d/train/z', z_image, step, dataformats='HWC') if save_image: out_file = 'z_sample_{:06d}.jpg'.format(step) save_image(out_file, z_image) latest_file = 'z_sample_latest.jpg' shutil.copyfile(out_file, latest_file) # save plot y, py = self.sample_y(max(100, n_samples)) y = y.detach().cpu().numpy() py = py.detach().cpu().numpy() xs = y[:, 0] ys = y[:, 1] y_image = scatter_plot(xs, ys, colors=py, title=title) writer.add_image('2d/test/y', y_image, step, dataformats='HWC') if save_image: out_file = 'y_sample_{:06d}.jpg'.format(step) save_image(out_file, y_image) latest_file = 'y_sample_latest.jpg' shutil.copyfile(out_file, latest_file) # 2D visualization map_size = 256 ix = (np.arange(map_size) + 0.5) / map_size * 2.0 - 1.0 iy = (np.arange(map_size) + 0.5) / map_size * -2.0 + 1.0 ix, iy = np.meshgrid(ix, iy) ix = ix.reshape((-1)) iy = iy.reshape((-1)) y = np.stack([ix, iy], axis=1) y = torch.tensor(y, dtype=torch.float32, requires_grad=True) py = self.py(y) py = py.detach().cpu().numpy() py_map = py.reshape((map_size, map_size)) map_image = image_plot(py_map, title=title, extent=[-1, 1, -1, 1]) writer.add_image('2d/test/map', map_image, step, dataformats='HWC') if save_image: out_file = 'y_dist_{:06d}.jpg'.format(step) save_image(out_file, map_image) latest_file = 'y_dist_latest.jpg' shutil.copyfile(out_file, latest_file) if dtype == '3d': # plot latent samples z, _ = self.net(y_data) pz = self.pz(z) z = z.detach().cpu().numpy() pz = pz.detach().cpu().numpy() xs = z[:, 0] ys = z[:, 1] zs = z[:, 2] z_image = scatter_plot(xs, ys, zs, colors=pz, title=title) writer.add_image('3d/train/z', z_image, step, dataformats='HWC') if save_image: out_file = 'z_sample_{:06d}.jpg'.format(step) save_image(out_file, z_image) latest_file = 'z_sample_latest.jpg' shutil.copyfile(out_file, latest_file) # save plot y, py = self.sample_y(max(100, n_samples)) y = y.detach().cpu().numpy() py = py.detach().cpu().numpy() xs = y[:, 0] ys = y[:, 1] zs = y[:, 2] y_image = scatter_plot(xs, ys, zs, colors=py, title=title) writer.add_image('3d/test/y', y_image, step, dataformats='HWC') if save_image: out_file = 'y_sample_{:06d}.jpg'.format(step) save_image(out_file, y_image) latest_file = 'y_sample_latest.jpg' shutil.copyfile(out_file, latest_file) if dtype == 'image': # plot data samples images = torch.clamp(y_data.detach().cpu(), 0.0, 1.0) grid_image = torchvision.utils.make_grid(images, nrow=8, pad_value=1) grid_image = grid_image.permute(1, 2, 0).numpy() writer.add_image('image/test/data', grid_image, step, dataformats='HWC') if save_image: out_file = 'y_data_{:06d}.jpg'.format(step) save_image(out_file, grid_image) latest_file = 'y_data_latest.jpg' shutil.copyfile(out_file, latest_file) # sample with generative flow y, _ = self.sample_y(max(64, n_samples)) y = y.detach().cpu().numpy() images = torch.from_numpy(y[:64]) images = torch.clamp(images, 0.0, 1.0) grid_image = torchvision.utils.make_grid(images, nrow=8, pad_value=1) grid_image = grid_image.permute(1, 2, 0).numpy() writer.add_image('image/test/sample', grid_image, step, dataformats='HWC') if save_image: out_file = 'y_image_{:06d}.jpg'.format(step) save_image(out_file, grid_image) latest_file = 'y_image_latest.jpg' shutil.copyfile(out_file, latest_file) @hydra.main(config_path='configs', config_name='default') def main(cfg): # show parameters print('***** parameters ****') print(OmegaConf.to_yaml(cfg)) print('*********************') print('') # dataset dataset = FlowDataLoader(cfg.run.distrib, batch_size=cfg.train.samples, total_steps=cfg.train.steps, shuffle=True) # setup train/eval model model = Model(dims=dataset.dims, datatype=dataset.dtype, cfg=cfg) # summary writer writer = SummaryWriter('./') # CuDNN backends if cfg.run.debug: torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False torch.autograd.set_detect_anomaly(True) for submodule in model.net.modules(): submodule.register_forward_hook(anomaly_hook) else: torch.backends.cudnn.benchmark = True # resume from checkpoint start_step = 0 if cfg.run.ckpt_path is not None: start_step = model.load_ckpt(cfg.run.ckpt_path) # training step = start_step for data in dataset: # training model.train() start_time = time.perf_counter() y = data z, loss = model.train_on_batch(y) elapsed_time = time.perf_counter() - start_time # update for the next step step += 1 # reports if step == start_step + 1 or step % (cfg.run.display * 10) == 0: # logging logger.info('[%d/%d] loss=%.5f [%.3f s/it]' % (step, cfg.train.steps, loss.item(), elapsed_time)) if step == start_step + 1 or step % (cfg.run.display * 100) == 0: writer.add_scalar('{:s}/train/loss'.format(dataset.dtype), loss.item(), step) save_files = step % (cfg.run.display * 1000) == 0 model.report(writer, y, step=step, save_files=save_files) writer.flush() if step == start_step + 1 or step % (cfg.run.display * 1000) == 0: # save ckpt ckpt_file = 'latest.pth' model.save_ckpt(step, ckpt_file) if __name__ == '__main__': main()
<filename>main.py import time import shutil import hydra import numpy as np import torch import torchvision from omegaconf import OmegaConf from torch.utils.tensorboard import SummaryWriter from torch.distributions.multivariate_normal import MultivariateNormal from flows import MAF, Glow, Ffjord, Flowpp, RealNVP, ResFlow, PlanarFlow from flows.misc import anomaly_hook from common.utils import image_plot, save_image, scatter_plot from flows.dataset import FlowDataLoader from flows.modules import Logit, Identity from common.logging import Logging networks = { 'planar': PlanarFlow, 'realnvp': RealNVP, 'glow': Glow, 'flow++': Flowpp, 'maf': MAF, 'resflow': ResFlow, 'ffjord': Ffjord, } # ----------------------------------------------- # logging # ----------------------------------------------- logger = Logging(__file__) # ----------------------------------------------- # train/eval model # ----------------------------------------------- class Model(object): def __init__(self, dims=(2, ), datatype=None, cfg=None): if torch.cuda.is_available(): self.device = torch.device('cuda', cfg.run.gpu) else: self.device = torch.device('cpu') self.name = cfg.network.name self.dims = dims self.dimension = np.prod(dims) mu = torch.zeros(self.dimension, dtype=torch.float32, device=self.device) covar = torch.eye(self.dimension, dtype=torch.float32, device=self.device) self.normal = MultivariateNormal(mu, covar) self.net = networks[self.name](dims=self.dims, datatype=datatype, cfg=cfg.network) self.net.to(self.device) if cfg.optimizer.name == 'rmsprop': self.optim = torch.optim.RMSprop(self.net.parameters(), lr=cfg.optimizer.lr, weight_decay=cfg.optimizer.weight_decay) elif cfg.optimizer.name == 'adam': self.optim = torch.optim.Adam(self.net.parameters(), lr=cfg.optimizer.lr, betas=(cfg.optimizer.beta1, cfg.optimizer.beta2), weight_decay=cfg.optimizer.weight_decay) else: raise Exception('optimizer "%s" is currently not supported' % (cfg.optimizer.name)) self.schduler = torch.optim.lr_scheduler.StepLR(self.optim, step_size=cfg.optimizer.decay_steps, gamma=cfg.optimizer.decay_ratio) def train(self): self.net.train() def eval(self): self.net.eval() def train_on_batch(self, y): y = y.to(self.device) y = y.contiguous() z, log_det_jacobian = self.net(y) z = z.view(y.size(0), -1) loss = -1.0 * torch.mean(self.normal.log_prob(z) + log_det_jacobian) self.optim.zero_grad() loss.backward() self.optim.step() self.schduler.step() return z, loss def save_ckpt(self, step, filename): ckpt = { 'net': self.net.state_dict(), 'optim': self.optim.state_dict(), 'step': step, } torch.save(ckpt, filename) def load_ckpt(self, filename): ckpt = torch.load(filename) self.net.load_state_dict(ckpt['net']) self.optim.load_state_dict(ckpt['optim']) epoch = ckpt['step'] return epoch def sample_y(self, n): z = self.sample_z(n) z = z.to(self.device) y, log_det_jacobians = self.net.backward(z.view(-1, *self.dims)) log_p = self.normal.log_prob(z) - log_det_jacobians return y, torch.exp(log_p) def sample_z(self, n): return self.normal.sample([n]) def log_py(self, y): y = y.to(self.device) z, log_det_jacobians = self.net(y) return self.log_pz(z) + log_det_jacobians def log_pz(self, z): return self.normal.log_prob(z) def py(self, y): return torch.exp(self.log_py(y)) def pz(self, z): return torch.exp(self.log_pz(z)) def report(self, writer, y_data, step=0, save_files=False): # set to evaluation mode self.net.eval() # prepare y_data = y_data.to(self.device) n_samples = y_data.size(0) if y_data.dim() == 2 and y_data.size(1) == 2: dtype = '2d' elif y_data.dim() == 2 and y_data.size(1) == 3: dtype = '3d' else: dtype = 'image' title = '%s_%d_steps' % (self.name, step) # testing if dtype == '2d': # plot data samples xs = y_data[:, 0].cpu().numpy() ys = y_data[:, 1].cpu().numpy() y_image = scatter_plot(xs, ys, title=title) writer.add_image('2d/data/y', y_image, step, dataformats='HWC') if save_image: out_file = 'y_data_{:06d}.jpg'.format(step) save_image(out_file, y_image) latest_file = 'y_data_latest.jpg' shutil.copyfile(out_file, latest_file) # plot latent samples z, _ = self.net(y_data) pz = self.pz(z) z = z.detach().cpu().numpy() pz = pz.detach().cpu().numpy() xs = z[:, 0] ys = z[:, 1] z_image = scatter_plot(xs, ys, colors=pz, title=title) writer.add_image('2d/train/z', z_image, step, dataformats='HWC') if save_image: out_file = 'z_sample_{:06d}.jpg'.format(step) save_image(out_file, z_image) latest_file = 'z_sample_latest.jpg' shutil.copyfile(out_file, latest_file) # save plot y, py = self.sample_y(max(100, n_samples)) y = y.detach().cpu().numpy() py = py.detach().cpu().numpy() xs = y[:, 0] ys = y[:, 1] y_image = scatter_plot(xs, ys, colors=py, title=title) writer.add_image('2d/test/y', y_image, step, dataformats='HWC') if save_image: out_file = 'y_sample_{:06d}.jpg'.format(step) save_image(out_file, y_image) latest_file = 'y_sample_latest.jpg' shutil.copyfile(out_file, latest_file) # 2D visualization map_size = 256 ix = (np.arange(map_size) + 0.5) / map_size * 2.0 - 1.0 iy = (np.arange(map_size) + 0.5) / map_size * -2.0 + 1.0 ix, iy = np.meshgrid(ix, iy) ix = ix.reshape((-1)) iy = iy.reshape((-1)) y = np.stack([ix, iy], axis=1) y = torch.tensor(y, dtype=torch.float32, requires_grad=True) py = self.py(y) py = py.detach().cpu().numpy() py_map = py.reshape((map_size, map_size)) map_image = image_plot(py_map, title=title, extent=[-1, 1, -1, 1]) writer.add_image('2d/test/map', map_image, step, dataformats='HWC') if save_image: out_file = 'y_dist_{:06d}.jpg'.format(step) save_image(out_file, map_image) latest_file = 'y_dist_latest.jpg' shutil.copyfile(out_file, latest_file) if dtype == '3d': # plot latent samples z, _ = self.net(y_data) pz = self.pz(z) z = z.detach().cpu().numpy() pz = pz.detach().cpu().numpy() xs = z[:, 0] ys = z[:, 1] zs = z[:, 2] z_image = scatter_plot(xs, ys, zs, colors=pz, title=title) writer.add_image('3d/train/z', z_image, step, dataformats='HWC') if save_image: out_file = 'z_sample_{:06d}.jpg'.format(step) save_image(out_file, z_image) latest_file = 'z_sample_latest.jpg' shutil.copyfile(out_file, latest_file) # save plot y, py = self.sample_y(max(100, n_samples)) y = y.detach().cpu().numpy() py = py.detach().cpu().numpy() xs = y[:, 0] ys = y[:, 1] zs = y[:, 2] y_image = scatter_plot(xs, ys, zs, colors=py, title=title) writer.add_image('3d/test/y', y_image, step, dataformats='HWC') if save_image: out_file = 'y_sample_{:06d}.jpg'.format(step) save_image(out_file, y_image) latest_file = 'y_sample_latest.jpg' shutil.copyfile(out_file, latest_file) if dtype == 'image': # plot data samples images = torch.clamp(y_data.detach().cpu(), 0.0, 1.0) grid_image = torchvision.utils.make_grid(images, nrow=8, pad_value=1) grid_image = grid_image.permute(1, 2, 0).numpy() writer.add_image('image/test/data', grid_image, step, dataformats='HWC') if save_image: out_file = 'y_data_{:06d}.jpg'.format(step) save_image(out_file, grid_image) latest_file = 'y_data_latest.jpg' shutil.copyfile(out_file, latest_file) # sample with generative flow y, _ = self.sample_y(max(64, n_samples)) y = y.detach().cpu().numpy() images = torch.from_numpy(y[:64]) images = torch.clamp(images, 0.0, 1.0) grid_image = torchvision.utils.make_grid(images, nrow=8, pad_value=1) grid_image = grid_image.permute(1, 2, 0).numpy() writer.add_image('image/test/sample', grid_image, step, dataformats='HWC') if save_image: out_file = 'y_image_{:06d}.jpg'.format(step) save_image(out_file, grid_image) latest_file = 'y_image_latest.jpg' shutil.copyfile(out_file, latest_file) @hydra.main(config_path='configs', config_name='default') def main(cfg): # show parameters print('***** parameters ****') print(OmegaConf.to_yaml(cfg)) print('*********************') print('') # dataset dataset = FlowDataLoader(cfg.run.distrib, batch_size=cfg.train.samples, total_steps=cfg.train.steps, shuffle=True) # setup train/eval model model = Model(dims=dataset.dims, datatype=dataset.dtype, cfg=cfg) # summary writer writer = SummaryWriter('./') # CuDNN backends if cfg.run.debug: torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False torch.autograd.set_detect_anomaly(True) for submodule in model.net.modules(): submodule.register_forward_hook(anomaly_hook) else: torch.backends.cudnn.benchmark = True # resume from checkpoint start_step = 0 if cfg.run.ckpt_path is not None: start_step = model.load_ckpt(cfg.run.ckpt_path) # training step = start_step for data in dataset: # training model.train() start_time = time.perf_counter() y = data z, loss = model.train_on_batch(y) elapsed_time = time.perf_counter() - start_time # update for the next step step += 1 # reports if step == start_step + 1 or step % (cfg.run.display * 10) == 0: # logging logger.info('[%d/%d] loss=%.5f [%.3f s/it]' % (step, cfg.train.steps, loss.item(), elapsed_time)) if step == start_step + 1 or step % (cfg.run.display * 100) == 0: writer.add_scalar('{:s}/train/loss'.format(dataset.dtype), loss.item(), step) save_files = step % (cfg.run.display * 1000) == 0 model.report(writer, y, step=step, save_files=save_files) writer.flush() if step == start_step + 1 or step % (cfg.run.display * 1000) == 0: # save ckpt ckpt_file = 'latest.pth' model.save_ckpt(step, ckpt_file) if __name__ == '__main__': main()
en
0.550429
# ----------------------------------------------- # logging # ----------------------------------------------- # ----------------------------------------------- # train/eval model # ----------------------------------------------- # set to evaluation mode # prepare # testing # plot data samples # plot latent samples # save plot # 2D visualization # plot latent samples # save plot # plot data samples # sample with generative flow # show parameters # dataset # setup train/eval model # summary writer # CuDNN backends # resume from checkpoint # training # training # update for the next step # reports # logging # save ckpt
2.046593
2
nlplingo/nn/trigger_model.py
BBN-E/nlplingo
3
6619635
from __future__ import absolute_import from __future__ import division from __future__ import with_statement import logging import os import keras import numpy as np from keras.models import Model from nlplingo.nn.extraction_model import ExtractionModel from nlplingo.nn.keras_models.model.base_model import KerasExtractionModel from nlplingo.common.serialize_disk import load_class_weights from keras.callbacks import EarlyStopping early_stopping = EarlyStopping(monitor='val_loss', patience=2) logger = logging.getLogger(__name__) class TriggerModel(ExtractionModel): def __init__(self, params, extractor_params, event_domain, embeddings, hyper_params, features): """ :type: params: dict :type event_domain: nlplingo.event.event_domain.EventDomain :type embeddings: nlplingo.embeddings.word_embeddings.WordEmbedding :type hyper_params: nlplingo.nn.extractor.HyperParameters :type features: nlplingo.tasks.eventtrigger.feature.EventTriggerFeature """ super(TriggerModel, self).__init__(params, extractor_params, event_domain, embeddings, hyper_params, features) self.number_of_entity_bio_types = len(event_domain.entity_bio_types) self.num_output = len(event_domain.event_types) # TODO remove or generalize this: # currently, this attribute is only used by TriggerModels and is set # only in KerasExtractionModels (and there are only TriggerKerasModels) self.is_binary = None @property def none_label_index(self): return self.event_domain.get_event_type_index('None') class TriggerKerasModel(TriggerModel, KerasExtractionModel): def __init__(self, params, extractor_params, event_domain, embeddings, hyper_params, features): """ :type params: dict :type extractor_params: dict :type event_domain: nlplingo.event.event_domain.EventDomain :type embeddings: nlplingo.embeddings.word_embeddings.WordEmbedding :type hyper_params: nlplingo.nn.extractor.HyperParameters :type features: nlplingo.tasks.common.feature.feature_setting.FeatureSetting """ # Calls TriggerModel init (for task-specific model params) # then KerasExtractionModel init (builds Keras LayerCreator using them) super(TriggerKerasModel, self).__init__(params, extractor_params, event_domain, embeddings, hyper_params, features) def create_model(self): super(TriggerKerasModel, self).create_model() class CNNTriggerModel(TriggerKerasModel): def __init__(self, params, extractor_params, event_domain, embeddings, hyper_params, features): """ :type extractor_params: dict :type event_domain: nlplingo.event.event_domain.EventDomain :type embeddings: nlplingo.embeddings.word_embeddings.WordEmbedding :type hyper_params: nlplingo.nn.extractor.HyperParameters :type features: nlplingo.tasks.eventtrigger.feature.EventTriggerFeature """ super(CNNTriggerModel, self).__init__( params, extractor_params, event_domain, embeddings, hyper_params, features) self.create_model() def create_model(self): super(CNNTriggerModel, self).create_model() model_input_dict = dict() outputs_to_merge_1 = [] self.layers.add_sentence_word_embedding_layer( "sentence_word_embedding", model_input_dict, outputs_to_merge_1, self.layers.EmbeddingLayer.PRETRAINED) self.layers.add_sentence_word_embedding_layer( "sentence_word_embedding_vector", model_input_dict, outputs_to_merge_1, self.layers.EmbeddingLayer.NONE) # For each word the pos_array_input defines the distance to the target work. # Embed each distance into an 'embedding_vec_length' dimensional vector space self.layers.add_unary_position_layer( "unary_word_position", model_input_dict, outputs_to_merge_1) # Sentence feature input is the result of merging word vectors and embeddings self.layers.add_sentence_ner_embedding_layer( "sentence_ner_type", model_input_dict, outputs_to_merge_1, self.num_ne_bio_types) merged = self.layers.merge(outputs_to_merge_1) outputs_to_merge_2 = [] self.layers.add_convolutional_layers( merged, outputs_to_merge_2, self.layers.BorderMode.SAME) self.layers.add_unary_window_layer( "unary_window", model_input_dict, outputs_to_merge_2, self.layers.EmbeddingLayer.PRETRAINED) self.layers.add_unary_window_layer( "unary_window_vector", model_input_dict, outputs_to_merge_2, self.layers.EmbeddingLayer.NONE) # Hierarchical Transfer (implemented as optional feature) weighted_layer = self.layers.apply_hierarchical_transfer_layer( outputs_to_merge_2) # historically self.activation = 'softmax' or 'sigmoid' model_outputs = [] self.layers.add_decision_layer([weighted_layer], model_outputs) self.compile(model_outputs, model_input_dict) class MultiLayerTriggerModelEmbedded(TriggerKerasModel): def __init__(self, params, extractor_params, event_domain, embeddings, hyper_params, features): """ :type extractor_params: dict :type event_domain: nlplingo.event.event_domain.EventDomain :type embeddings: nlplingo.embeddings.word_embeddings.WordEmbedding :type hyper_params: nlplingo.nn.extractor.HyperParameters :type features: nlplingo.tasks.eventtrigger.feature.EventTriggerFeature """ super(MultiLayerTriggerModelEmbedded, self).__init__(params, extractor_params, event_domain, embeddings, hyper_params, features) self.create_model() def create_model(self): super(MultiLayerTriggerModelEmbedded, self).create_model() model_input_dict = dict() layer_list = [] # word vectors for window around the unary datapoint self.layers.add_unary_window_layer( "unary_window_vector", model_input_dict, layer_list, self.layers.EmbeddingLayer.NONE) # word vectors for the entire sentence containing the unary datapoint self.layers.add_sentence_word_embedding_layer( "sentence_word_embedding_vector", model_input_dict, layer_list, self.layers.EmbeddingLayer.NONE) # For each word the pos_array_input defines distance to the target word. # Embed each distance into an 'embedding_vec_length'-D vector space self.layers.add_unary_position_layer( "unary_word_position", model_input_dict, layer_list) self.layers.add_sentence_ner_embedding_layer( "sentence_ner_type", layer_list, model_input_dict, self.num_ne_bio_types) # Hidden layer input is merged word vecs and sentence embeddings hidden_input = self.layers.merge(layer_list) hidden_output = self.layers.build_hidden_layers(hidden_input) # historically self.activation = 'softmax' or 'sigmoid' model_outputs = [] self.layers.add_decision_layer([hidden_output], model_outputs) self.compile(model_outputs, model_input_dict)
from __future__ import absolute_import from __future__ import division from __future__ import with_statement import logging import os import keras import numpy as np from keras.models import Model from nlplingo.nn.extraction_model import ExtractionModel from nlplingo.nn.keras_models.model.base_model import KerasExtractionModel from nlplingo.common.serialize_disk import load_class_weights from keras.callbacks import EarlyStopping early_stopping = EarlyStopping(monitor='val_loss', patience=2) logger = logging.getLogger(__name__) class TriggerModel(ExtractionModel): def __init__(self, params, extractor_params, event_domain, embeddings, hyper_params, features): """ :type: params: dict :type event_domain: nlplingo.event.event_domain.EventDomain :type embeddings: nlplingo.embeddings.word_embeddings.WordEmbedding :type hyper_params: nlplingo.nn.extractor.HyperParameters :type features: nlplingo.tasks.eventtrigger.feature.EventTriggerFeature """ super(TriggerModel, self).__init__(params, extractor_params, event_domain, embeddings, hyper_params, features) self.number_of_entity_bio_types = len(event_domain.entity_bio_types) self.num_output = len(event_domain.event_types) # TODO remove or generalize this: # currently, this attribute is only used by TriggerModels and is set # only in KerasExtractionModels (and there are only TriggerKerasModels) self.is_binary = None @property def none_label_index(self): return self.event_domain.get_event_type_index('None') class TriggerKerasModel(TriggerModel, KerasExtractionModel): def __init__(self, params, extractor_params, event_domain, embeddings, hyper_params, features): """ :type params: dict :type extractor_params: dict :type event_domain: nlplingo.event.event_domain.EventDomain :type embeddings: nlplingo.embeddings.word_embeddings.WordEmbedding :type hyper_params: nlplingo.nn.extractor.HyperParameters :type features: nlplingo.tasks.common.feature.feature_setting.FeatureSetting """ # Calls TriggerModel init (for task-specific model params) # then KerasExtractionModel init (builds Keras LayerCreator using them) super(TriggerKerasModel, self).__init__(params, extractor_params, event_domain, embeddings, hyper_params, features) def create_model(self): super(TriggerKerasModel, self).create_model() class CNNTriggerModel(TriggerKerasModel): def __init__(self, params, extractor_params, event_domain, embeddings, hyper_params, features): """ :type extractor_params: dict :type event_domain: nlplingo.event.event_domain.EventDomain :type embeddings: nlplingo.embeddings.word_embeddings.WordEmbedding :type hyper_params: nlplingo.nn.extractor.HyperParameters :type features: nlplingo.tasks.eventtrigger.feature.EventTriggerFeature """ super(CNNTriggerModel, self).__init__( params, extractor_params, event_domain, embeddings, hyper_params, features) self.create_model() def create_model(self): super(CNNTriggerModel, self).create_model() model_input_dict = dict() outputs_to_merge_1 = [] self.layers.add_sentence_word_embedding_layer( "sentence_word_embedding", model_input_dict, outputs_to_merge_1, self.layers.EmbeddingLayer.PRETRAINED) self.layers.add_sentence_word_embedding_layer( "sentence_word_embedding_vector", model_input_dict, outputs_to_merge_1, self.layers.EmbeddingLayer.NONE) # For each word the pos_array_input defines the distance to the target work. # Embed each distance into an 'embedding_vec_length' dimensional vector space self.layers.add_unary_position_layer( "unary_word_position", model_input_dict, outputs_to_merge_1) # Sentence feature input is the result of merging word vectors and embeddings self.layers.add_sentence_ner_embedding_layer( "sentence_ner_type", model_input_dict, outputs_to_merge_1, self.num_ne_bio_types) merged = self.layers.merge(outputs_to_merge_1) outputs_to_merge_2 = [] self.layers.add_convolutional_layers( merged, outputs_to_merge_2, self.layers.BorderMode.SAME) self.layers.add_unary_window_layer( "unary_window", model_input_dict, outputs_to_merge_2, self.layers.EmbeddingLayer.PRETRAINED) self.layers.add_unary_window_layer( "unary_window_vector", model_input_dict, outputs_to_merge_2, self.layers.EmbeddingLayer.NONE) # Hierarchical Transfer (implemented as optional feature) weighted_layer = self.layers.apply_hierarchical_transfer_layer( outputs_to_merge_2) # historically self.activation = 'softmax' or 'sigmoid' model_outputs = [] self.layers.add_decision_layer([weighted_layer], model_outputs) self.compile(model_outputs, model_input_dict) class MultiLayerTriggerModelEmbedded(TriggerKerasModel): def __init__(self, params, extractor_params, event_domain, embeddings, hyper_params, features): """ :type extractor_params: dict :type event_domain: nlplingo.event.event_domain.EventDomain :type embeddings: nlplingo.embeddings.word_embeddings.WordEmbedding :type hyper_params: nlplingo.nn.extractor.HyperParameters :type features: nlplingo.tasks.eventtrigger.feature.EventTriggerFeature """ super(MultiLayerTriggerModelEmbedded, self).__init__(params, extractor_params, event_domain, embeddings, hyper_params, features) self.create_model() def create_model(self): super(MultiLayerTriggerModelEmbedded, self).create_model() model_input_dict = dict() layer_list = [] # word vectors for window around the unary datapoint self.layers.add_unary_window_layer( "unary_window_vector", model_input_dict, layer_list, self.layers.EmbeddingLayer.NONE) # word vectors for the entire sentence containing the unary datapoint self.layers.add_sentence_word_embedding_layer( "sentence_word_embedding_vector", model_input_dict, layer_list, self.layers.EmbeddingLayer.NONE) # For each word the pos_array_input defines distance to the target word. # Embed each distance into an 'embedding_vec_length'-D vector space self.layers.add_unary_position_layer( "unary_word_position", model_input_dict, layer_list) self.layers.add_sentence_ner_embedding_layer( "sentence_ner_type", layer_list, model_input_dict, self.num_ne_bio_types) # Hidden layer input is merged word vecs and sentence embeddings hidden_input = self.layers.merge(layer_list) hidden_output = self.layers.build_hidden_layers(hidden_input) # historically self.activation = 'softmax' or 'sigmoid' model_outputs = [] self.layers.add_decision_layer([hidden_output], model_outputs) self.compile(model_outputs, model_input_dict)
en
0.499824
:type: params: dict :type event_domain: nlplingo.event.event_domain.EventDomain :type embeddings: nlplingo.embeddings.word_embeddings.WordEmbedding :type hyper_params: nlplingo.nn.extractor.HyperParameters :type features: nlplingo.tasks.eventtrigger.feature.EventTriggerFeature # TODO remove or generalize this: # currently, this attribute is only used by TriggerModels and is set # only in KerasExtractionModels (and there are only TriggerKerasModels) :type params: dict :type extractor_params: dict :type event_domain: nlplingo.event.event_domain.EventDomain :type embeddings: nlplingo.embeddings.word_embeddings.WordEmbedding :type hyper_params: nlplingo.nn.extractor.HyperParameters :type features: nlplingo.tasks.common.feature.feature_setting.FeatureSetting # Calls TriggerModel init (for task-specific model params) # then KerasExtractionModel init (builds Keras LayerCreator using them) :type extractor_params: dict :type event_domain: nlplingo.event.event_domain.EventDomain :type embeddings: nlplingo.embeddings.word_embeddings.WordEmbedding :type hyper_params: nlplingo.nn.extractor.HyperParameters :type features: nlplingo.tasks.eventtrigger.feature.EventTriggerFeature # For each word the pos_array_input defines the distance to the target work. # Embed each distance into an 'embedding_vec_length' dimensional vector space # Sentence feature input is the result of merging word vectors and embeddings # Hierarchical Transfer (implemented as optional feature) # historically self.activation = 'softmax' or 'sigmoid' :type extractor_params: dict :type event_domain: nlplingo.event.event_domain.EventDomain :type embeddings: nlplingo.embeddings.word_embeddings.WordEmbedding :type hyper_params: nlplingo.nn.extractor.HyperParameters :type features: nlplingo.tasks.eventtrigger.feature.EventTriggerFeature # word vectors for window around the unary datapoint # word vectors for the entire sentence containing the unary datapoint # For each word the pos_array_input defines distance to the target word. # Embed each distance into an 'embedding_vec_length'-D vector space # Hidden layer input is merged word vecs and sentence embeddings # historically self.activation = 'softmax' or 'sigmoid'
2.024041
2
public resource/math homework/forloop.py
shwzh1990/python_coding
0
6619636
<reponame>shwzh1990/python_coding #! /usr/bin/env python #coding=utf-8 ''' count = 0 for i in range(100,201): if i % 7 == 0: count = count + 1 print(count) ''' print((201-100)//7)
#! /usr/bin/env python #coding=utf-8 ''' count = 0 for i in range(100,201): if i % 7 == 0: count = count + 1 print(count) ''' print((201-100)//7)
en
0.506715
#! /usr/bin/env python #coding=utf-8 count = 0 for i in range(100,201): if i % 7 == 0: count = count + 1 print(count)
3.458066
3
surrogates/utils/serialization.py
SimonBoothroyd/surrogates
1
6619637
<reponame>SimonBoothroyd/surrogates import abc import json from typing import Any, Callable, Dict, Iterator, List, Optional import numpy class NumpyNDArray(numpy.ndarray): """A stub type which wraps around a `numpy.ndarray`, and enables pydantic serialization / deserialization support.""" @classmethod def __get_validators__(cls) -> Iterator[Callable]: yield cls.validate @classmethod def validate(cls, value: List[List[float]]) -> numpy.ndarray: if isinstance(value, numpy.ndarray): return value return numpy.array(value) class Serializable(abc.ABC): """Represents a class which can be serialized via a `dict` intermediate. """ @staticmethod @abc.abstractmethod def _validate(dictionary: Dict[Any, Any]): """Raise an exception if the dictionary is not a valid representation of this class. Parameters ---------- dictionary: dict The dictionary to validate. """ raise NotImplementedError() @abc.abstractmethod def to_dict(self) -> Dict[Any, Any]: """Converts this object to a dictionary of only primitive types. Returns ------- dict The dictionary representation. """ raise NotImplementedError() @classmethod @abc.abstractmethod def from_dict(cls, dictionary: Dict[Any, Any]): """Creates this object from its dictionary type. Parameters ---------- dictionary: dict The dictionary to create the object from. Returns ------- cls The created object. """ cls._validate(dictionary) def to_json(self, file_path: Optional[str] = None) -> str: """Converts this object to a JSON representation and optionally saves it to disk. Parameters ---------- file_path: str, optional The file path to save the JSON representation to. If `None`, no file will be created. Returns ------- str The JSON representation of the object. """ json_string = json.dumps( self.to_dict(), sort_keys=True, indent=4, separators=(",", ": ") ) if file_path is not None: with open(file_path, "w") as file: file.write(json_string) return json_string @classmethod def from_json( cls, json_string: Optional[str] = None, file_path: Optional[str] = None ) -> str: """Converts this object to a JSON representation and optionally saves it to disk. Parameters ---------- json_string: str, optional The JSON string to create this object from. This must be set if `file_path` is `None` file_path: str, optional The path to the JSON representation to create this object from. This must be set if `json_string` is `None` Returns ------- str The JSON representation of the object. """ assert (json_string is None and file_path is not None) or ( json_string is not None and file_path is None ) if file_path is not None: with open(file_path, "r") as file: json_string = file.read() dictionary = json.loads(json_string) return cls.from_dict(dictionary)
import abc import json from typing import Any, Callable, Dict, Iterator, List, Optional import numpy class NumpyNDArray(numpy.ndarray): """A stub type which wraps around a `numpy.ndarray`, and enables pydantic serialization / deserialization support.""" @classmethod def __get_validators__(cls) -> Iterator[Callable]: yield cls.validate @classmethod def validate(cls, value: List[List[float]]) -> numpy.ndarray: if isinstance(value, numpy.ndarray): return value return numpy.array(value) class Serializable(abc.ABC): """Represents a class which can be serialized via a `dict` intermediate. """ @staticmethod @abc.abstractmethod def _validate(dictionary: Dict[Any, Any]): """Raise an exception if the dictionary is not a valid representation of this class. Parameters ---------- dictionary: dict The dictionary to validate. """ raise NotImplementedError() @abc.abstractmethod def to_dict(self) -> Dict[Any, Any]: """Converts this object to a dictionary of only primitive types. Returns ------- dict The dictionary representation. """ raise NotImplementedError() @classmethod @abc.abstractmethod def from_dict(cls, dictionary: Dict[Any, Any]): """Creates this object from its dictionary type. Parameters ---------- dictionary: dict The dictionary to create the object from. Returns ------- cls The created object. """ cls._validate(dictionary) def to_json(self, file_path: Optional[str] = None) -> str: """Converts this object to a JSON representation and optionally saves it to disk. Parameters ---------- file_path: str, optional The file path to save the JSON representation to. If `None`, no file will be created. Returns ------- str The JSON representation of the object. """ json_string = json.dumps( self.to_dict(), sort_keys=True, indent=4, separators=(",", ": ") ) if file_path is not None: with open(file_path, "w") as file: file.write(json_string) return json_string @classmethod def from_json( cls, json_string: Optional[str] = None, file_path: Optional[str] = None ) -> str: """Converts this object to a JSON representation and optionally saves it to disk. Parameters ---------- json_string: str, optional The JSON string to create this object from. This must be set if `file_path` is `None` file_path: str, optional The path to the JSON representation to create this object from. This must be set if `json_string` is `None` Returns ------- str The JSON representation of the object. """ assert (json_string is None and file_path is not None) or ( json_string is not None and file_path is None ) if file_path is not None: with open(file_path, "r") as file: json_string = file.read() dictionary = json.loads(json_string) return cls.from_dict(dictionary)
en
0.634201
A stub type which wraps around a `numpy.ndarray`, and enables pydantic serialization / deserialization support. Represents a class which can be serialized via a `dict` intermediate. Raise an exception if the dictionary is not a valid representation of this class. Parameters ---------- dictionary: dict The dictionary to validate. Converts this object to a dictionary of only primitive types. Returns ------- dict The dictionary representation. Creates this object from its dictionary type. Parameters ---------- dictionary: dict The dictionary to create the object from. Returns ------- cls The created object. Converts this object to a JSON representation and optionally saves it to disk. Parameters ---------- file_path: str, optional The file path to save the JSON representation to. If `None`, no file will be created. Returns ------- str The JSON representation of the object. Converts this object to a JSON representation and optionally saves it to disk. Parameters ---------- json_string: str, optional The JSON string to create this object from. This must be set if `file_path` is `None` file_path: str, optional The path to the JSON representation to create this object from. This must be set if `json_string` is `None` Returns ------- str The JSON representation of the object.
3.174409
3
Python Fundamentals/Lists Advanced/palindrome_strings.py
bvoytash/Software-University
0
6619638
<reponame>bvoytash/Software-University word_string = input().split() palindrome = input() palindrome_string = [el for el in word_string if el[::-1] == el] occurrences = [1 for el in palindrome_string if el == palindrome] print(palindrome_string) print(f"Found palindrome {len(occurrences)} times")
word_string = input().split() palindrome = input() palindrome_string = [el for el in word_string if el[::-1] == el] occurrences = [1 for el in palindrome_string if el == palindrome] print(palindrome_string) print(f"Found palindrome {len(occurrences)} times")
none
1
3.918151
4
robot-simulation/quadruped/scripts/basic_tests.py
mithi/algorithm-playground
85
6619639
from comm.pwm import PWM from time import sleep driver = PWM(0x40) driver.setPWMFreq(50) def map(z, x, y, a, b): # x to y is the old range # a to b is the new range # z is somewhere in between x and y # c is somewhere in between a and b c = (z - x) * (b - a) / (y - x) + a return c class Joint: def __init__(self, ch, a, b, x, y, n): self.ch = ch # min and max pwm values self.n = n # value at neutral position (angle zero) self.a = a # the 'a' pwm signal corresponds to: # hip: towards the sides and away from either the back or front # knee: upper leg towards ground # ankle: lower leg towards the upper leg from the perpendicular self.b = b # the 'b' pwm signal corresponds to: # hip: away from the sides and towards either back or front # knee: upper leg towards the sky # ankle: lowerleg away from the upper leg from the perpendicular # min and max angle values in degrees # x is negative, corresponds to 'a' self.x = x # y is positive, corresponds to 'b' self.y = y def neutral_pose(self): driver.setPWM(self.ch, 0, self.n) def pose(self, z): c = map(z, self.x, self.y, self.a, self.b) driver.setPWM(self.ch, 0, c) def off(self): driver.setPWM(self.ch, 0, 0) MIN_ANGLE = -70 MAX_ANGLE = 70 hip_front_left = Joint(0, 165, 500, MIN_ANGLE, MAX_ANGLE, 330) hip_front_right = Joint(3, 510, 160, MIN_ANGLE, MAX_ANGLE, 330) hip_back_left = Joint(6, 500, 155, MIN_ANGLE, MAX_ANGLE, 320) hip_back_right = Joint(9, 170, 510, MIN_ANGLE, MAX_ANGLE, 350) knee_front_left = Joint(1, 165, 505, MIN_ANGLE, MAX_ANGLE, 345) knee_front_right = Joint(4, 465, 130, MIN_ANGLE, MAX_ANGLE, 280) knee_back_left = Joint(7, 475, 120, MIN_ANGLE, MAX_ANGLE, 290) knee_back_right = Joint(10, 140, 485, MIN_ANGLE, MAX_ANGLE, 315) ankle_front_left = Joint(2, 400, 190, MIN_ANGLE, MAX_ANGLE, 350) ankle_front_right = Joint(5, 220, 450, MIN_ANGLE, MAX_ANGLE, 280) ankle_back_left = Joint(8, 250, 470, MIN_ANGLE, MAX_ANGLE, 290) ankle_back_right = Joint(11, 380, 170, MIN_ANGLE, MAX_ANGLE, 335) hips = [ hip_front_left, hip_front_right, hip_back_left, hip_back_right ] knees = [ knee_front_left, knee_front_right, knee_back_left, knee_back_right ] ankles = [ ankle_front_left, ankle_front_right, ankle_back_left, ankle_back_right ] def quadruped_neutral_pose(): for hip, knee, ankle in zip(hips, knees, ankles): hip.neutral_pose() knee.neutral_pose() ankle.neutral_pose() def turn_off_everything(): for hip, knee, ankle in zip(hips, knees, ankles): hip.off() knee.off() ankle.off() t = 0.25 s = 2.0 print 'Quadruped positioning to: neutral pose' quadruped_neutral_pose() sleep(s) print 'DONE \n' print 'turn off all the joints for a few seconds' turn_off_everything() sleep(s) print 'DONE \n' print 'TEST ZERO' for hip, knee, ankle in zip(hips, knees, ankles): hip.pose(0) sleep(t) knee.pose(0) sleep(t) ankle.pose(0) sleep(t) sleep(s) print 'DONE \n' #======================================== print 'TEST ONE: hip angles are zero' for hip in hips: hip.pose(0) sleep(t) sleep(s) print 'DONE \n' #======================================== print 'TEST TWO: hip angles are positive' for hip in hips: hip.pose(30) sleep(t) sleep(s) print 'DONE \n' #======================================== print 'TEST THREE: hip angles are negative' for hip in hips: hip.pose(-60) sleep(t) sleep(s) print 'DONE \n' #======================================== print 'Quadruped positioning to: neutral pose' quadruped_neutral_pose() sleep(s) print 'DONE \n' #======================================== print 'TEST FOUR: knee angles are zero' for knee in knees: knee.pose(0) sleep(t) sleep(s) print 'DONE \n' #======================================== print 'TEST FIVE: knee angles are positive' for knee in knees: knee.pose(60) sleep(t) sleep(s) print 'DONE \n' #======================================== print 'TEST SIX: knee angles are negative' for knee in knees: knee.pose(-60) sleep(t) sleep(s) print 'DONE \n' #======================================== print 'Quadruped positioning to: neutral pose' quadruped_neutral_pose() sleep(s) print 'DONE \n' #======================================== print 'TEST SEVEN: ankle angles are zero' for ankle in ankles: ankle.pose(0) sleep(t) sleep(s) print 'DONE \n' #======================================== print 'TEST EIGHT: ankle angles are negative' for ankle in ankles: ankle.pose(-60) sleep(t) sleep(s) print 'DONE \n' #======================================== print 'TEST NINE: ankle angles are positive' for ankle in ankles: ankle.pose(60) sleep(t) sleep(s) print 'DONE \n'
from comm.pwm import PWM from time import sleep driver = PWM(0x40) driver.setPWMFreq(50) def map(z, x, y, a, b): # x to y is the old range # a to b is the new range # z is somewhere in between x and y # c is somewhere in between a and b c = (z - x) * (b - a) / (y - x) + a return c class Joint: def __init__(self, ch, a, b, x, y, n): self.ch = ch # min and max pwm values self.n = n # value at neutral position (angle zero) self.a = a # the 'a' pwm signal corresponds to: # hip: towards the sides and away from either the back or front # knee: upper leg towards ground # ankle: lower leg towards the upper leg from the perpendicular self.b = b # the 'b' pwm signal corresponds to: # hip: away from the sides and towards either back or front # knee: upper leg towards the sky # ankle: lowerleg away from the upper leg from the perpendicular # min and max angle values in degrees # x is negative, corresponds to 'a' self.x = x # y is positive, corresponds to 'b' self.y = y def neutral_pose(self): driver.setPWM(self.ch, 0, self.n) def pose(self, z): c = map(z, self.x, self.y, self.a, self.b) driver.setPWM(self.ch, 0, c) def off(self): driver.setPWM(self.ch, 0, 0) MIN_ANGLE = -70 MAX_ANGLE = 70 hip_front_left = Joint(0, 165, 500, MIN_ANGLE, MAX_ANGLE, 330) hip_front_right = Joint(3, 510, 160, MIN_ANGLE, MAX_ANGLE, 330) hip_back_left = Joint(6, 500, 155, MIN_ANGLE, MAX_ANGLE, 320) hip_back_right = Joint(9, 170, 510, MIN_ANGLE, MAX_ANGLE, 350) knee_front_left = Joint(1, 165, 505, MIN_ANGLE, MAX_ANGLE, 345) knee_front_right = Joint(4, 465, 130, MIN_ANGLE, MAX_ANGLE, 280) knee_back_left = Joint(7, 475, 120, MIN_ANGLE, MAX_ANGLE, 290) knee_back_right = Joint(10, 140, 485, MIN_ANGLE, MAX_ANGLE, 315) ankle_front_left = Joint(2, 400, 190, MIN_ANGLE, MAX_ANGLE, 350) ankle_front_right = Joint(5, 220, 450, MIN_ANGLE, MAX_ANGLE, 280) ankle_back_left = Joint(8, 250, 470, MIN_ANGLE, MAX_ANGLE, 290) ankle_back_right = Joint(11, 380, 170, MIN_ANGLE, MAX_ANGLE, 335) hips = [ hip_front_left, hip_front_right, hip_back_left, hip_back_right ] knees = [ knee_front_left, knee_front_right, knee_back_left, knee_back_right ] ankles = [ ankle_front_left, ankle_front_right, ankle_back_left, ankle_back_right ] def quadruped_neutral_pose(): for hip, knee, ankle in zip(hips, knees, ankles): hip.neutral_pose() knee.neutral_pose() ankle.neutral_pose() def turn_off_everything(): for hip, knee, ankle in zip(hips, knees, ankles): hip.off() knee.off() ankle.off() t = 0.25 s = 2.0 print 'Quadruped positioning to: neutral pose' quadruped_neutral_pose() sleep(s) print 'DONE \n' print 'turn off all the joints for a few seconds' turn_off_everything() sleep(s) print 'DONE \n' print 'TEST ZERO' for hip, knee, ankle in zip(hips, knees, ankles): hip.pose(0) sleep(t) knee.pose(0) sleep(t) ankle.pose(0) sleep(t) sleep(s) print 'DONE \n' #======================================== print 'TEST ONE: hip angles are zero' for hip in hips: hip.pose(0) sleep(t) sleep(s) print 'DONE \n' #======================================== print 'TEST TWO: hip angles are positive' for hip in hips: hip.pose(30) sleep(t) sleep(s) print 'DONE \n' #======================================== print 'TEST THREE: hip angles are negative' for hip in hips: hip.pose(-60) sleep(t) sleep(s) print 'DONE \n' #======================================== print 'Quadruped positioning to: neutral pose' quadruped_neutral_pose() sleep(s) print 'DONE \n' #======================================== print 'TEST FOUR: knee angles are zero' for knee in knees: knee.pose(0) sleep(t) sleep(s) print 'DONE \n' #======================================== print 'TEST FIVE: knee angles are positive' for knee in knees: knee.pose(60) sleep(t) sleep(s) print 'DONE \n' #======================================== print 'TEST SIX: knee angles are negative' for knee in knees: knee.pose(-60) sleep(t) sleep(s) print 'DONE \n' #======================================== print 'Quadruped positioning to: neutral pose' quadruped_neutral_pose() sleep(s) print 'DONE \n' #======================================== print 'TEST SEVEN: ankle angles are zero' for ankle in ankles: ankle.pose(0) sleep(t) sleep(s) print 'DONE \n' #======================================== print 'TEST EIGHT: ankle angles are negative' for ankle in ankles: ankle.pose(-60) sleep(t) sleep(s) print 'DONE \n' #======================================== print 'TEST NINE: ankle angles are positive' for ankle in ankles: ankle.pose(60) sleep(t) sleep(s) print 'DONE \n'
en
0.667944
# x to y is the old range # a to b is the new range # z is somewhere in between x and y # c is somewhere in between a and b # min and max pwm values # value at neutral position (angle zero) # the 'a' pwm signal corresponds to: # hip: towards the sides and away from either the back or front # knee: upper leg towards ground # ankle: lower leg towards the upper leg from the perpendicular # the 'b' pwm signal corresponds to: # hip: away from the sides and towards either back or front # knee: upper leg towards the sky # ankle: lowerleg away from the upper leg from the perpendicular # min and max angle values in degrees # x is negative, corresponds to 'a' # y is positive, corresponds to 'b' #======================================== #======================================== #======================================== #======================================== #======================================== #======================================== #======================================== #======================================== #======================================== #======================================== #========================================
3.038403
3
Chapter 11/ch11_1_31.py
bpbpublications/TEST-YOUR-SKILLS-IN-PYTHON-LANGUAGE
0
6619640
<reponame>bpbpublications/TEST-YOUR-SKILLS-IN-PYTHON-LANGUAGE t1=tuple({1:"Gold", 2:"Silver"}) t2=("Hello", ("Hi", "Bye")) print(t1+ t2*2) #(1,2, "Hello", ("Hi", "Bye"), "Hello", ("Hi", "Bye"))
t1=tuple({1:"Gold", 2:"Silver"}) t2=("Hello", ("Hi", "Bye")) print(t1+ t2*2) #(1,2, "Hello", ("Hi", "Bye"), "Hello", ("Hi", "Bye"))
ko
0.497834
#(1,2, "Hello", ("Hi", "Bye"), "Hello", ("Hi", "Bye"))
3.490105
3
wikipedia/example-config.py
mitkonikov/SchoolNetUtilities
0
6619641
<reponame>mitkonikov/SchoolNetUtilities<filename>wikipedia/example-config.py<gh_stars>0 MYSQL_HOST = "localhost" MYSQL_USER = "root" MYSQL_PASSWORD = "" MYSQL_DATABASE = "db_words" RAW_DIR = "./RAW" OUT_NAME = "wikipedia-mk" UNWANTED_PAGES = ["корисник", "разговор", "разговор со корисник", "шаблон", "разговор за шаблон", "податотека", "разговор за податотека", "категорија", "разговор за категорија", "википедија", "разговор за википедија", "медијавики", "разговор за медијавики", "помош", "разговор за помош", "портал", "разговор за портал", "модул", "разговор за модул", "gadget", "gadget talk", "gadget definition", "gadget definition talk", "вп", "кат"] UNWANTED_KEYWORDS = ["(појаснување).+", "^\d{1,}$", "^(ngc).+", "^(предлошка).+", "^(ic).+", "^(Разговор за предлошка).+", "^(список).+", "^(космос).+", "^(iso ).+", "^(hd ).+", "^(hr ).+", "^(грб на ).+", "^(градови ).+"]
MYSQL_HOST = "localhost" MYSQL_USER = "root" MYSQL_PASSWORD = "" MYSQL_DATABASE = "db_words" RAW_DIR = "./RAW" OUT_NAME = "wikipedia-mk" UNWANTED_PAGES = ["корисник", "разговор", "разговор со корисник", "шаблон", "разговор за шаблон", "податотека", "разговор за податотека", "категорија", "разговор за категорија", "википедија", "разговор за википедија", "медијавики", "разговор за медијавики", "помош", "разговор за помош", "портал", "разговор за портал", "модул", "разговор за модул", "gadget", "gadget talk", "gadget definition", "gadget definition talk", "вп", "кат"] UNWANTED_KEYWORDS = ["(појаснување).+", "^\d{1,}$", "^(ngc).+", "^(предлошка).+", "^(ic).+", "^(Разговор за предлошка).+", "^(список).+", "^(космос).+", "^(iso ).+", "^(hd ).+", "^(hr ).+", "^(грб на ).+", "^(градови ).+"]
none
1
2.106681
2
EB-Bill-Calculator.py
gowthaman-new/python-practise-programs
1
6619642
<filename>EB-Bill-Calculator.py # THIS PROGRAM IS ROBUST. YOU CAN CHANGE THE slabRange & slabCalculation VALUES. YOU CAN ALSO ADD MORE RANGES IF YOU NEED slabRange = [100, 200, 300, 300] slabCalculation = [1, 2, 3, 5] # Calculates the value of index [0] for slabRange & slabCalculation def initAmountCalculation(): return (slabRange[0] * slabCalculation[0]) # Calculates the value of all indices for slabRange & slabCalculation except the first and the last index def midAmountCalculation(): sum = 0 for i in range(1, len(slabRange) - 1): sum = sum + ((slabRange[i] - slabRange[i-1]) * slabCalculation[i]) return sum # Calculates only the last index [slabRange & slabCalculation] value def endAmountCalculation(): return ((units - slabRange[len(slabRange)-1]) * slabCalculation[len(slabRange)-1]) # Calculates all the index [slabRange & slabCalculation] values except first & last index. This calculation is based upon the index value def recurringDifferenceCalculation(index): result = 0 for i in range(1, index): result = result + ((slabRange[i] - slabRange[i-1]) * slabCalculation[i]) return result # Calculates the last index [slabRange & slabCalculation] value & its based upon the index value def calcAmountWithInRange(index): return (units - slabRange[index-1]) * slabCalculation[index] # Main Method which calculates the EB Bill def ebBillCalculation(units): if len(slabCalculation) != len(slabRange): return "length of slabRange & slabCalculation is not matching. So exiting..." if (units <= slabRange[0]): return units * slabCalculation[0] if (len(slabRange) >= 2): if (units <= slabRange[1]): return (initAmountCalculation() + calcAmountWithInRange(1)) if (units > slabRange[len(slabRange)-1]): return (initAmountCalculation() + midAmountCalculation() + endAmountCalculation()) for i in range(2, len(slabRange)): if (units <= slabRange[i]): return (initAmountCalculation() + recurringDifferenceCalculation(i) + calcAmountWithInRange(i)) units = 250; print(ebBillCalculation(units));
<filename>EB-Bill-Calculator.py # THIS PROGRAM IS ROBUST. YOU CAN CHANGE THE slabRange & slabCalculation VALUES. YOU CAN ALSO ADD MORE RANGES IF YOU NEED slabRange = [100, 200, 300, 300] slabCalculation = [1, 2, 3, 5] # Calculates the value of index [0] for slabRange & slabCalculation def initAmountCalculation(): return (slabRange[0] * slabCalculation[0]) # Calculates the value of all indices for slabRange & slabCalculation except the first and the last index def midAmountCalculation(): sum = 0 for i in range(1, len(slabRange) - 1): sum = sum + ((slabRange[i] - slabRange[i-1]) * slabCalculation[i]) return sum # Calculates only the last index [slabRange & slabCalculation] value def endAmountCalculation(): return ((units - slabRange[len(slabRange)-1]) * slabCalculation[len(slabRange)-1]) # Calculates all the index [slabRange & slabCalculation] values except first & last index. This calculation is based upon the index value def recurringDifferenceCalculation(index): result = 0 for i in range(1, index): result = result + ((slabRange[i] - slabRange[i-1]) * slabCalculation[i]) return result # Calculates the last index [slabRange & slabCalculation] value & its based upon the index value def calcAmountWithInRange(index): return (units - slabRange[index-1]) * slabCalculation[index] # Main Method which calculates the EB Bill def ebBillCalculation(units): if len(slabCalculation) != len(slabRange): return "length of slabRange & slabCalculation is not matching. So exiting..." if (units <= slabRange[0]): return units * slabCalculation[0] if (len(slabRange) >= 2): if (units <= slabRange[1]): return (initAmountCalculation() + calcAmountWithInRange(1)) if (units > slabRange[len(slabRange)-1]): return (initAmountCalculation() + midAmountCalculation() + endAmountCalculation()) for i in range(2, len(slabRange)): if (units <= slabRange[i]): return (initAmountCalculation() + recurringDifferenceCalculation(i) + calcAmountWithInRange(i)) units = 250; print(ebBillCalculation(units));
en
0.613279
# THIS PROGRAM IS ROBUST. YOU CAN CHANGE THE slabRange & slabCalculation VALUES. YOU CAN ALSO ADD MORE RANGES IF YOU NEED # Calculates the value of index [0] for slabRange & slabCalculation # Calculates the value of all indices for slabRange & slabCalculation except the first and the last index # Calculates only the last index [slabRange & slabCalculation] value # Calculates all the index [slabRange & slabCalculation] values except first & last index. This calculation is based upon the index value # Calculates the last index [slabRange & slabCalculation] value & its based upon the index value # Main Method which calculates the EB Bill
3.281313
3
xldlib/xlpy/tools/peak_picking/centroid.py
Alexhuszagh/XLDiscoverer
0
6619643
''' XlPy/Tools/Peak_Picking/centroid ________________________________ Elucidate if a peak is centroided and centroid it if it is not :copyright: (c) 2015 The Regents of the University of California. :license: GNU GPL, see licenses/GNU GPLv3.txt for more details. ''' # load future from __future__ import division # load modules import numpy as np from scipy import integrate from xldlib.definitions import ZIP # CONSTANTS # --------- CENTROIDED_THRESHOLD = 0.05 # CHECKERS # -------- def check_centroided(intensity): '''Detects whether the file has centroided or profile-type peaks.''' # break if not enough values assert intensity.size > 5 # check to see if a good percentage of intensities are 0 # high percentage means not centroided indexes, = np.where(intensity == 0.) return (indexes.size / intensity.size) < CENTROIDED_THRESHOLD def find_peaks(x, y, baseline=0.): ''' Returns a generator with m/z and intensity arrays corresponding to individual peaks. >>> x = np.array([351.95169, 351.95294, 351.95419, 351.95544, ... 351.95668, 351.95793, 351.95918, 351.96042, 351.96167, 351.96292, ... 351.96416, 351.96541, 351.96666]) >>> y = np.array([0.0, 0.0, 0.0, 415.131, 763.698, 1136.421, 1729.902, ... 2430.958, 2676.107, 2086.312, 915.789, 0.0, 0.0]) >>> [[i.tolist() for i in item] for item in find_peaks(x, y)] [[[351.95419, 351.95544, 351.95668, 351.95793, 351.95918, 351.96042, 351.96167, 351.96292, 351.96416], [0.0, 415.131, 763.698, 1136.421, 1729.902, 2430.958, 2676.107, 2086.312, 915.789]]] ''' if not isinstance(x, np.ndarray): x = np.array(x) if not isinstance(y, np.ndarray): y = np.array(y) baseline, = np.where(y <= baseline) x = (i for i in np.split(x, baseline) if i.size > 1) y = (i for i in np.split(y, baseline) if i.size > 1) return ZIP(x, y) def centroid_peak(x, y): ''' Centroid an x,y array pair and return an x and y value. Weights the centroiding based off the intensity of the y values. >>> x = np.array([351.95419, 351.95544, 351.95668, 351.95793, 351.95918, ... 351.96042, 351.96167, 351.96292, 351.96416]) >>> y = np.array([0., 415.131, 763.698, 1136.421, 1729.902, 2430.958, ... 2676.107, 2086.312, 915.789]) >>> centroid_peak(x, y) (351.96059175911802, 14.578820424997993) ''' # take weighted average for positions, cumtrapz for heights x_out = np.average(x, weights=y) y_out = integrate.cumtrapz(y, x=x)[-1] return x_out, y_out def centroid_scan(mz, intensity): ''' Finds all the peaks and centroids each peak, reconstructing a peaklist from the centroided values. ''' peaks = find_peaks(mz, intensity) centroided = (centroid_peak(*i) for i in peaks) flat = (i for item in centroided for i in item) flattened = np.fromiter(flat, dtype=float) return flattened[::2], flattened[1::2]
''' XlPy/Tools/Peak_Picking/centroid ________________________________ Elucidate if a peak is centroided and centroid it if it is not :copyright: (c) 2015 The Regents of the University of California. :license: GNU GPL, see licenses/GNU GPLv3.txt for more details. ''' # load future from __future__ import division # load modules import numpy as np from scipy import integrate from xldlib.definitions import ZIP # CONSTANTS # --------- CENTROIDED_THRESHOLD = 0.05 # CHECKERS # -------- def check_centroided(intensity): '''Detects whether the file has centroided or profile-type peaks.''' # break if not enough values assert intensity.size > 5 # check to see if a good percentage of intensities are 0 # high percentage means not centroided indexes, = np.where(intensity == 0.) return (indexes.size / intensity.size) < CENTROIDED_THRESHOLD def find_peaks(x, y, baseline=0.): ''' Returns a generator with m/z and intensity arrays corresponding to individual peaks. >>> x = np.array([351.95169, 351.95294, 351.95419, 351.95544, ... 351.95668, 351.95793, 351.95918, 351.96042, 351.96167, 351.96292, ... 351.96416, 351.96541, 351.96666]) >>> y = np.array([0.0, 0.0, 0.0, 415.131, 763.698, 1136.421, 1729.902, ... 2430.958, 2676.107, 2086.312, 915.789, 0.0, 0.0]) >>> [[i.tolist() for i in item] for item in find_peaks(x, y)] [[[351.95419, 351.95544, 351.95668, 351.95793, 351.95918, 351.96042, 351.96167, 351.96292, 351.96416], [0.0, 415.131, 763.698, 1136.421, 1729.902, 2430.958, 2676.107, 2086.312, 915.789]]] ''' if not isinstance(x, np.ndarray): x = np.array(x) if not isinstance(y, np.ndarray): y = np.array(y) baseline, = np.where(y <= baseline) x = (i for i in np.split(x, baseline) if i.size > 1) y = (i for i in np.split(y, baseline) if i.size > 1) return ZIP(x, y) def centroid_peak(x, y): ''' Centroid an x,y array pair and return an x and y value. Weights the centroiding based off the intensity of the y values. >>> x = np.array([351.95419, 351.95544, 351.95668, 351.95793, 351.95918, ... 351.96042, 351.96167, 351.96292, 351.96416]) >>> y = np.array([0., 415.131, 763.698, 1136.421, 1729.902, 2430.958, ... 2676.107, 2086.312, 915.789]) >>> centroid_peak(x, y) (351.96059175911802, 14.578820424997993) ''' # take weighted average for positions, cumtrapz for heights x_out = np.average(x, weights=y) y_out = integrate.cumtrapz(y, x=x)[-1] return x_out, y_out def centroid_scan(mz, intensity): ''' Finds all the peaks and centroids each peak, reconstructing a peaklist from the centroided values. ''' peaks = find_peaks(mz, intensity) centroided = (centroid_peak(*i) for i in peaks) flat = (i for item in centroided for i in item) flattened = np.fromiter(flat, dtype=float) return flattened[::2], flattened[1::2]
en
0.675312
XlPy/Tools/Peak_Picking/centroid ________________________________ Elucidate if a peak is centroided and centroid it if it is not :copyright: (c) 2015 The Regents of the University of California. :license: GNU GPL, see licenses/GNU GPLv3.txt for more details. # load future # load modules # CONSTANTS # --------- # CHECKERS # -------- Detects whether the file has centroided or profile-type peaks. # break if not enough values # check to see if a good percentage of intensities are 0 # high percentage means not centroided Returns a generator with m/z and intensity arrays corresponding to individual peaks. >>> x = np.array([351.95169, 351.95294, 351.95419, 351.95544, ... 351.95668, 351.95793, 351.95918, 351.96042, 351.96167, 351.96292, ... 351.96416, 351.96541, 351.96666]) >>> y = np.array([0.0, 0.0, 0.0, 415.131, 763.698, 1136.421, 1729.902, ... 2430.958, 2676.107, 2086.312, 915.789, 0.0, 0.0]) >>> [[i.tolist() for i in item] for item in find_peaks(x, y)] [[[351.95419, 351.95544, 351.95668, 351.95793, 351.95918, 351.96042, 351.96167, 351.96292, 351.96416], [0.0, 415.131, 763.698, 1136.421, 1729.902, 2430.958, 2676.107, 2086.312, 915.789]]] Centroid an x,y array pair and return an x and y value. Weights the centroiding based off the intensity of the y values. >>> x = np.array([351.95419, 351.95544, 351.95668, 351.95793, 351.95918, ... 351.96042, 351.96167, 351.96292, 351.96416]) >>> y = np.array([0., 415.131, 763.698, 1136.421, 1729.902, 2430.958, ... 2676.107, 2086.312, 915.789]) >>> centroid_peak(x, y) (351.96059175911802, 14.578820424997993) # take weighted average for positions, cumtrapz for heights Finds all the peaks and centroids each peak, reconstructing a peaklist from the centroided values.
2.515345
3
api/src/service/AiService.py
SamuelJansen/FeatureManager
1
6619644
import numpy from python_framework import Service, ServiceMethod from python_helper import Constant, log from Sample import Sample from Feature import Feature from FeatureData import FeatureData from dto.BestFitDto import BestFitRequestDto import DefaultValue, DataSetKey @Service() class AiService: @ServiceMethod(requestClass=[FeatureData, int]) def patchFeatureData(self, featureData, value): featureData.iterationCount += 1 featureData.value += ((value - featureData.value) / featureData.iterationCount) featureData.feature.iterationCount += 1 featureData.feature.value += ((value - featureData.feature.value) / featureData.feature.iterationCount) @ServiceMethod(requestClass=[[Feature], Sample, int]) def patchSample(self, featureList, sample, value): for feature in featureList : featureData = self.helper.featureData.getRespectiveFeatureDataByFeature(feature, sample.featureDataList) self.validator.featureData.validateModelNotNone(featureData) self.patchFeatureData(featureData, value) sample.iterationCount += 1 sample.value += ((value - sample.value) / sample.iterationCount) @ServiceMethod(requestClass=[[BestFitRequestDto]]) def getTargetData(self, bestFitList): return [DefaultValue.MAXIMUM_DATA_VALUE for x in bestFitList] @ServiceMethod(requestClass=[[int], set, int]) def getBestFitList(self, targetData, dataSet, amount): if not dataSet or 0 == len(dataSet) : return [] log.debug(AiService, f'Querying {amount} samples ...') targetArray = numpy.asarray(targetData) dataSetMatrix = numpy.asarray([data[DataSetKey.VALUE_LIST] for data in dataSet.values()]) euclidianDistanceList = numpy.asarray(numpy.sum((targetArray - dataSetMatrix)**2, axis=1)) log.debug(AiService, f'euclidianDistanceList = {euclidianDistanceList}') bestFitIndexList = numpy.argsort(euclidianDistanceList) log.debug(AiService, f'bestFitIndexList = {bestFitIndexList}') log.debug(AiService, f'dataSetMatrix = {dataSetMatrix}') bestFitList = [] for bestFitIndex in bestFitIndexList[:amount] : bestFit = dataSet[list(dataSet.values())[bestFitIndex][DataSetKey.SAMPLE].key][DataSetKey.SAMPLE] bestFitList.append(bestFit) log.debug(AiService,f'Optimum match: {bestFitList}') return bestFitList
import numpy from python_framework import Service, ServiceMethod from python_helper import Constant, log from Sample import Sample from Feature import Feature from FeatureData import FeatureData from dto.BestFitDto import BestFitRequestDto import DefaultValue, DataSetKey @Service() class AiService: @ServiceMethod(requestClass=[FeatureData, int]) def patchFeatureData(self, featureData, value): featureData.iterationCount += 1 featureData.value += ((value - featureData.value) / featureData.iterationCount) featureData.feature.iterationCount += 1 featureData.feature.value += ((value - featureData.feature.value) / featureData.feature.iterationCount) @ServiceMethod(requestClass=[[Feature], Sample, int]) def patchSample(self, featureList, sample, value): for feature in featureList : featureData = self.helper.featureData.getRespectiveFeatureDataByFeature(feature, sample.featureDataList) self.validator.featureData.validateModelNotNone(featureData) self.patchFeatureData(featureData, value) sample.iterationCount += 1 sample.value += ((value - sample.value) / sample.iterationCount) @ServiceMethod(requestClass=[[BestFitRequestDto]]) def getTargetData(self, bestFitList): return [DefaultValue.MAXIMUM_DATA_VALUE for x in bestFitList] @ServiceMethod(requestClass=[[int], set, int]) def getBestFitList(self, targetData, dataSet, amount): if not dataSet or 0 == len(dataSet) : return [] log.debug(AiService, f'Querying {amount} samples ...') targetArray = numpy.asarray(targetData) dataSetMatrix = numpy.asarray([data[DataSetKey.VALUE_LIST] for data in dataSet.values()]) euclidianDistanceList = numpy.asarray(numpy.sum((targetArray - dataSetMatrix)**2, axis=1)) log.debug(AiService, f'euclidianDistanceList = {euclidianDistanceList}') bestFitIndexList = numpy.argsort(euclidianDistanceList) log.debug(AiService, f'bestFitIndexList = {bestFitIndexList}') log.debug(AiService, f'dataSetMatrix = {dataSetMatrix}') bestFitList = [] for bestFitIndex in bestFitIndexList[:amount] : bestFit = dataSet[list(dataSet.values())[bestFitIndex][DataSetKey.SAMPLE].key][DataSetKey.SAMPLE] bestFitList.append(bestFit) log.debug(AiService,f'Optimum match: {bestFitList}') return bestFitList
none
1
2.30709
2
src/rpi/main.py
ECE-597SD/AR-IoT
0
6619645
<reponame>ECE-597SD/AR-IoT import app2pi as a2p import pi2argon as p2a def main(): return if __name__ == "__main__": main()
import app2pi as a2p import pi2argon as p2a def main(): return if __name__ == "__main__": main()
none
1
1.64107
2
tests/test_issues.py
VectrixSecurity/Vectrix-Python
11
6619646
<reponame>VectrixSecurity/Vectrix-Python<gh_stars>10-100 from tests import Issue correct_issue = { "issue": "Public S3 Bucket", "asset_id": ["arn:aws:s3:::sample-id-model"], "metadata": { "aws_s3_bucket_name": { "priority": -1, "value": "sample-id" } } } class TestIssue(Issue): def __init__(self): super().__init__() self._issue = "Public S3 Bucket" self._asset_id = ["arn:aws:s3:::sample-id-model"] self._metadata = { "aws_s3_bucket_name": { "priority": -1, "value": "sample-id" } } __test__ = False def test_issue_to_dict(): assert TestIssue().to_dict() == correct_issue
from tests import Issue correct_issue = { "issue": "Public S3 Bucket", "asset_id": ["arn:aws:s3:::sample-id-model"], "metadata": { "aws_s3_bucket_name": { "priority": -1, "value": "sample-id" } } } class TestIssue(Issue): def __init__(self): super().__init__() self._issue = "Public S3 Bucket" self._asset_id = ["arn:aws:s3:::sample-id-model"] self._metadata = { "aws_s3_bucket_name": { "priority": -1, "value": "sample-id" } } __test__ = False def test_issue_to_dict(): assert TestIssue().to_dict() == correct_issue
none
1
2.732221
3
Ejercicio 1/Servidor/suma.py
afsaa/Cliente-Servidor2018-2
0
6619647
<reponame>afsaa/Cliente-Servidor2018-2<filename>Ejercicio 1/Servidor/suma.py import socket HOST = '192.168.9.93' PORT = 50002 s_recv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Listening to ip {} in port {}'.format(HOST, PORT) s_recv.bind((HOST, PORT)) s_recv.listen(10) while True: conn, addr = s_recv.accept() print 'Connected by', addr while True: data = conn.recv(1024) if not data: break if ',' in data: operation, op1, op2 = data.split(',') if operation == '+': result = int(op1) + int(op2) else: result = 'Match Error. Operation not supported. Struct for operation +,op,op without spaces.' else: result = 'Match Error. Operation not supported. Struct for operation +,op,op without spaces.' conn.send(str(result)) conn.close()
1/Servidor/suma.py import socket HOST = '192.168.9.93' PORT = 50002 s_recv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Listening to ip {} in port {}'.format(HOST, PORT) s_recv.bind((HOST, PORT)) s_recv.listen(10) while True: conn, addr = s_recv.accept() print 'Connected by', addr while True: data = conn.recv(1024) if not data: break if ',' in data: operation, op1, op2 = data.split(',') if operation == '+': result = int(op1) + int(op2) else: result = 'Match Error. Operation not supported. Struct for operation +,op,op without spaces.' else: result = 'Match Error. Operation not supported. Struct for operation +,op,op without spaces.' conn.send(str(result)) conn.close()
none
1
2.728661
3
Module_03/amazon.py
JoseGtz/2021_python_selenium
0
6619648
from common.webdriver_factory import get_driver from selenium.webdriver.support.wait import WebDriverWait driver = get_driver('chrome') wait = WebDriverWait(driver, 10) driver.get('https://www.amazon.com/') elements = driver.find_elements_by_xpath("//a") print(f'Tags con A encontrados: {len(elements)}') for element in elements: print(element) elements = driver.find_elements_by_xpath("//head/*") print(f'Elementos hijos de Head encontrados: {len(elements)}') for element in elements: print(element) driver.quit()
from common.webdriver_factory import get_driver from selenium.webdriver.support.wait import WebDriverWait driver = get_driver('chrome') wait = WebDriverWait(driver, 10) driver.get('https://www.amazon.com/') elements = driver.find_elements_by_xpath("//a") print(f'Tags con A encontrados: {len(elements)}') for element in elements: print(element) elements = driver.find_elements_by_xpath("//head/*") print(f'Elementos hijos de Head encontrados: {len(elements)}') for element in elements: print(element) driver.quit()
none
1
3.344284
3
spira/yevon/filters/edge_filter.py
JCoetzee123/spira
0
6619649
<reponame>JCoetzee123/spira from spira.yevon import constants from spira.log import SPIRA_LOG as LOG from spira.yevon.filters.filter import Filter from spira.yevon.gdsii.elem_list import ElementList from spira.yevon.geometry.edges.edges import EdgeAdapter from spira.core.parameters.variables import IntegerParameter from spira.yevon.process.purpose_layer import PurposeLayerParameter from spira.yevon.process import get_rule_deck RDD = get_rule_deck() __all__ = ['EdgeFilter'] class __EdgeFilter__(Filter): purpose = PurposeLayerParameter() edge_type = IntegerParameter(default=constants.EDGE_TYPE_NORMAL) class EdgeFilter(__EdgeFilter__): """ Filter only passes edges with the specified purpose. """ def __filter___Cell____(self, item): from copy import deepcopy from spira.yevon.gdsii.cell import Cell elems = ElementList() for p1 in deepcopy(item.elements): if p1.layer.purpose == RDD.PURPOSE.METAL: for edge in p1.edges: e = EdgeAdapter(original_edge=edge, edge_type=self.edge_type) # print(e) elems += e # elems += edge.outside.transform(edge.transformation) elems += p1 cell = Cell(elements=elems) return cell def __repr__(self): return "[SPiRA: EdgeFilter] ())".format()
from spira.yevon import constants from spira.log import SPIRA_LOG as LOG from spira.yevon.filters.filter import Filter from spira.yevon.gdsii.elem_list import ElementList from spira.yevon.geometry.edges.edges import EdgeAdapter from spira.core.parameters.variables import IntegerParameter from spira.yevon.process.purpose_layer import PurposeLayerParameter from spira.yevon.process import get_rule_deck RDD = get_rule_deck() __all__ = ['EdgeFilter'] class __EdgeFilter__(Filter): purpose = PurposeLayerParameter() edge_type = IntegerParameter(default=constants.EDGE_TYPE_NORMAL) class EdgeFilter(__EdgeFilter__): """ Filter only passes edges with the specified purpose. """ def __filter___Cell____(self, item): from copy import deepcopy from spira.yevon.gdsii.cell import Cell elems = ElementList() for p1 in deepcopy(item.elements): if p1.layer.purpose == RDD.PURPOSE.METAL: for edge in p1.edges: e = EdgeAdapter(original_edge=edge, edge_type=self.edge_type) # print(e) elems += e # elems += edge.outside.transform(edge.transformation) elems += p1 cell = Cell(elements=elems) return cell def __repr__(self): return "[SPiRA: EdgeFilter] ())".format()
en
0.587973
Filter only passes edges with the specified purpose. # print(e) # elems += edge.outside.transform(edge.transformation)
2.057964
2
geeksforgeeks/string-conversion.py
dapper91/contests
0
6619650
''' https://practice.geeksforgeeks.org/problems/string-conversion/0 ''' from sys import stdin def is_string_convertable(x, y): xi, yi = 0, 0 indexes = [] while True: if yi == len(y): break if xi == len(x): if len(indexes) == 0: break else: xi = indexes.pop() + 1 yi -= 1 continue if x[xi].upper() == y[yi]: indexes.append(xi) xi += 1; yi += 1 else: if x[xi].isupper(): if len(indexes) == 0: break else: xi = indexes.pop() + 1 yi -= 1 else: xi += 1 return len(indexes) == len(y) tests = int(stdin.readline()) for _ in range(tests): n1, n2 = map(int, stdin.readline().split()) x, y = stdin.readline().split() if is_string_convertable(x, y): print("Yes") else: print("No")
''' https://practice.geeksforgeeks.org/problems/string-conversion/0 ''' from sys import stdin def is_string_convertable(x, y): xi, yi = 0, 0 indexes = [] while True: if yi == len(y): break if xi == len(x): if len(indexes) == 0: break else: xi = indexes.pop() + 1 yi -= 1 continue if x[xi].upper() == y[yi]: indexes.append(xi) xi += 1; yi += 1 else: if x[xi].isupper(): if len(indexes) == 0: break else: xi = indexes.pop() + 1 yi -= 1 else: xi += 1 return len(indexes) == len(y) tests = int(stdin.readline()) for _ in range(tests): n1, n2 = map(int, stdin.readline().split()) x, y = stdin.readline().split() if is_string_convertable(x, y): print("Yes") else: print("No")
en
0.435469
https://practice.geeksforgeeks.org/problems/string-conversion/0
3.8639
4