max_stars_repo_path
stringlengths 4
245
| max_stars_repo_name
stringlengths 7
115
| max_stars_count
int64 101
368k
| id
stringlengths 2
8
| content
stringlengths 6
1.03M
|
---|---|---|---|---|
src/app/test/api/http/unit/handlers/v1/job_test.py | jlrpnbbngtn/beer-garden | 230 | 11094365 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
import copy
import json
import unittest
from datetime import datetime
from mock import patch
from beer_garden.db.mongo.models import DateTrigger, Job, RequestTemplate
from .. import TestHandlerBase
@unittest.skip("TODO")
class JobAPITest(TestHandlerBase):
def setUp(self):
self.ts_epoch = 1451606400000
self.ts_dt = datetime(2016, 1, 1)
self.job_dict = {
"name": "job_name",
"trigger_type": "date",
"trigger": {"run_date": self.ts_epoch, "timezone": "utc"},
"request_template": {
"system": "system",
"system_version": "1.0.0",
"instance_name": "default",
"command": "speak",
"parameters": {"message": "hey!"},
"comment": "hi!",
"metadata": {"request": "stuff"},
},
"misfire_grace_time": 3,
"coalesce": True,
"next_run_time": self.ts_epoch,
"success_count": 0,
"error_count": 0,
"status": "RUNNING",
"max_instances": 3,
}
db_dict = copy.deepcopy(self.job_dict)
db_dict["request_template"] = RequestTemplate(**db_dict["request_template"])
db_dict["trigger"]["run_date"] = self.ts_dt
db_dict["trigger"] = DateTrigger(**db_dict["trigger"])
db_dict["next_run_time"] = self.ts_dt
self.job = Job(**db_dict)
super(JobAPITest, self).setUp()
def tearDown(self):
Job.objects.delete()
def test_get_404(self):
self.job.save()
bad_id = "".join(["1" for _ in range(24)])
if bad_id == self.job.id:
bad_id = "".join(["2" for _ in range(24)])
response = self.fetch("/api/v1/jobs/" + bad_id)
self.assertEqual(404, response.code)
def test_get(self):
self.job.save()
self.job_dict["id"] = str(self.job.id)
response = self.fetch("/api/v1/jobs/" + str(self.job.id))
self.assertEqual(200, response.code)
self.assertEqual(json.loads(response.body.decode("utf-8")), self.job_dict)
@patch("brew_view.request_scheduler")
def test_delete(self, scheduler_mock):
self.job.save()
response = self.fetch("/api/v1/jobs/" + str(self.job.id), method="DELETE")
self.assertEqual(204, response.code)
scheduler_mock.remove_job.assert_called_with(
str(self.job.id), jobstore="beer_garden"
)
@patch("brew_view.request_scheduler")
def test_pause(self, scheduler_mock):
self.job.save()
body = json.dumps(
{
"operations": [
{"operation": "update", "path": "/status", "value": "PAUSED"}
]
}
)
response = self.fetch(
"/api/v1/jobs/" + str(self.job.id),
method="PATCH",
body=body,
headers={"content-type": "application/json"},
)
self.assertEqual(200, response.code)
scheduler_mock.pause_job.assert_called_with(
str(self.job.id), jobstore="beer_garden"
)
self.job.reload()
self.assertEqual(self.job.status, "PAUSED")
@patch("brew_view.request_scheduler")
def test_resume(self, scheduler_mock):
self.job.status = "PAUSED"
self.job.save()
body = json.dumps(
{
"operations": [
{"operation": "update", "path": "/status", "value": "RUNNING"}
]
}
)
response = self.fetch(
"/api/v1/jobs/" + str(self.job.id),
method="PATCH",
body=body,
headers={"content-type": "application/json"},
)
self.assertEqual(200, response.code)
scheduler_mock.resume_job.assert_called_with(
str(self.job.id), jobstore="beer_garden"
)
self.job.reload()
self.assertEqual(self.job.status, "RUNNING")
def test_invalid_operation(self):
self.job.save()
body = json.dumps(
{
"operations": [
{"operation": "INVALID", "path": "/status", "value": "RUNNING"}
]
}
)
response = self.fetch(
"/api/v1/jobs/" + str(self.job.id),
method="PATCH",
body=body,
headers={"content-type": "application/json"},
)
self.assertGreaterEqual(400, response.code)
def test_invalid_path(self):
self.job.save()
body = json.dumps(
{
"operations": [
{"operation": "update", "path": "/INVALID", "value": "RUNNING"}
]
}
)
response = self.fetch(
"/api/v1/jobs/" + str(self.job.id),
method="PATCH",
body=body,
headers={"content-type": "application/json"},
)
self.assertGreaterEqual(400, response.code)
def test_invalid_value(self):
self.job.save()
body = json.dumps(
{
"operations": [
{"operation": "update", "path": "/status", "value": "INVALID"}
]
}
)
response = self.fetch(
"/api/v1/jobs/" + str(self.job.id),
method="PATCH",
body=body,
headers={"content-type": "application/json"},
)
self.assertGreaterEqual(400, response.code)
@unittest.skip("TODO")
class JobListAPITest(TestHandlerBase):
def setUp(self):
self.ts_epoch = 1451606400000
self.ts_dt = datetime(2016, 1, 1)
self.job_dict = {
"name": "job_name",
"trigger_type": "date",
"trigger": {"run_date": self.ts_epoch, "timezone": "utc"},
"request_template": {
"system": "system",
"system_version": "1.0.0",
"instance_name": "default",
"command": "speak",
"parameters": {"message": "hey!"},
"comment": "hi!",
"metadata": {"request": "stuff"},
},
"misfire_grace_time": 3,
"coalesce": True,
"next_run_time": self.ts_epoch,
"success_count": 0,
"error_count": 0,
"status": "RUNNING",
"max_instances": 3,
}
db_dict = copy.deepcopy(self.job_dict)
db_dict["request_template"] = RequestTemplate(**db_dict["request_template"])
db_dict["trigger"]["run_date"] = self.ts_dt
db_dict["trigger"] = DateTrigger(**db_dict["trigger"])
db_dict["next_run_time"] = self.ts_dt
self.job = Job(**db_dict)
super(JobListAPITest, self).setUp()
def tearDown(self):
Job.objects.delete()
def test_get(self):
self.job.save()
self.job_dict["id"] = str(self.job.id)
response = self.fetch("/api/v1/jobs")
self.assertEqual(200, response.code)
self.assertEqual(json.loads(response.body.decode("utf-8")), [self.job_dict])
def test_get_with_filter_param(self):
self.job.save()
self.job_dict["id"] = str(self.job.id)
response = self.fetch("/api/v1/jobs?name=DOES_NOT_EXIST")
self.assertEqual(200, response.code)
self.assertEqual(json.loads(response.body.decode("utf-8")), [])
response = self.fetch("/api/v1/jobs?name=job_name")
self.assertEqual(200, response.code)
self.assertEqual(json.loads(response.body.decode("utf-8")), [self.job_dict])
@patch("brew_view.request_scheduler")
def test_post(self, scheduler_mock):
body = json.dumps(self.job_dict)
self.job_dict["id"] = None
response = self.fetch("/api/v1/jobs", method="POST", body=body)
self.assertEqual(response.code, 201)
data_without_id = json.loads(response.body.decode("utf-8"))
data_without_id["id"] = None
self.assertEqual(data_without_id, self.job_dict)
self.assertEqual(scheduler_mock.add_job.call_count, 1)
@patch("brew_view.request_scheduler")
def test_post_error_delete(self, scheduler_mock):
body = json.dumps(self.job_dict)
self.job_dict["id"] = None
scheduler_mock.add_job.side_effect = ValueError
response = self.fetch("/api/v1/jobs", method="POST", body=body)
self.assertGreaterEqual(response.code, 500)
|
tests/transforms/test_collate.py | siahuat0727/torchio | 1,340 | 11094373 | from torch.utils.data import DataLoader
import torchio as tio
from ..utils import TorchioTestCase
class TestCollate(TorchioTestCase):
def get_heterogeneous_dataset(self):
# Keys missing in one of the samples will not be present in the batch
# This is relevant for the case in which a transform is applied to some
# samples only, according to its probability (p argument)
transform_no = tio.RandomElasticDeformation(p=0, max_displacement=1)
transform_yes = tio.RandomElasticDeformation(p=1, max_displacement=1)
sample_no = transform_no(self.sample_subject)
sample_yes = transform_yes(self.sample_subject)
data = sample_no, sample_yes
class Dataset:
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
def __getitem__(self, index):
return self.data[index]
return Dataset(data)
def test_collate(self):
loader = DataLoader(self.get_heterogeneous_dataset(), batch_size=2)
tio.utils.get_first_item(loader)
def test_history_collate(self):
loader = DataLoader(
self.get_heterogeneous_dataset(),
batch_size=4,
collate_fn=tio.utils.history_collate,
)
batch = tio.utils.get_first_item(loader)
empty_history, one_history = batch['history']
assert not empty_history
assert len(one_history) == 1
|
octopus/engine/helper.py | SillyTin/octopus | 212 | 11094389 | <reponame>SillyTin/octopus
#from .constants import TT256, TT255
import re
from z3 import *
TT256 = 2 ** 256
TT256M1 = 2 ** 256 - 1
TT255 = 2 ** 255
class helper(object):
def is_symbolic(value):
return not isinstance(value, int)
def is_real(value):
return isinstance(value, int)
def isAllReal(*args):
for i in args:
if is_symbolic(i):
return False
return True
def safe_decode(hex_encoded_string):
if (hex_encoded_string.startswith("0x")):
return bytes.fromhex(hex_encoded_string[2:])
else:
return bytes.fromhex(hex_encoded_string)
def to_signed(i):
return i if i < TT255 else i - TT256
def get_trace_line(instr, state):
stack = str(state.stack[::-1])
# stack = re.sub("(\d+)", lambda m: hex(int(m.group(1))), stack)
stack = re.sub("\n", "", stack)
return str(instr['address']) + " " + instr['opcode'] + "\tSTACK: " + stack
def convert_to_bitvec(item):
# converting boolean expression to bitvector
if type(item) == BoolRef:
return If(item, BitVecVal(1, 256), BitVecVal(0, 256))
elif type(item) == bool:
if item:
return BitVecVal(1, 256)
else:
return BitVecVal(0, 256)
elif type(item) == int:
return BitVecVal(item, 256)
else:
return simplify(item)
def convert_to_concrete_int(item):
if (type(item) == int):
return item
if (type(item) == BitVecNumRef):
return item.as_long()
return simplify(item).as_long()
def get_concrete_int(item):
if (type(item) == int):
return item
if (type(item) == BitVecNumRef):
return item.as_long()
return simplify(item).as_long()
def concrete_int_from_bytes(_bytes, start_index):
# logging.debug("-- concrete_int_from_bytes: " + str(_bytes[start_index:start_index+32]))
b = _bytes[start_index:start_index+32]
val = int.from_bytes(b, byteorder='big')
return val
def concrete_int_to_bytes(val):
# logging.debug("concrete_int_to_bytes " + str(val))
if (type(val) == int):
return val.to_bytes(32, byteorder='big')
return (simplify(val).as_long()).to_bytes(32, byteorder='big')
|
examples/python/setup.py | C-NERD/nimview | 103 | 11094414 | <reponame>C-NERD/nimview<filename>examples/python/setup.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# python setup.py sdist
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
from subprocess import check_call
import os
from shutil import copy, rmtree
this_directory = os.path.abspath(os.path.dirname(__file__))
targetDir = "nimview"
# create another nimview subfolder as setup.py is much friendlier if you do so
rmtree(targetDir, ignore_errors=True)
os.makedirs(targetDir, exist_ok=True)
os.makedirs(targetDir + "/src", exist_ok=True)
srcFiles = [ "src/library.nim", "nakefile.nim", "LICENSE", "README.md"]
for index, fileName in enumerate(srcFiles):
fullFileName = os.path.join(this_directory, fileName)
if os.path.isfile(fullFileName):
copy(fullFileName, targetDir + "/" + fileName)
class NimExtension(Extension):
def __init__(self, name, sourcedir=''):
Extension.__init__(self, name, sources=[])
self.sourcedir = os.path.abspath(sourcedir)
class NimBuild(build_ext):
def run(self):
for ext in self.extensions:
self.build_extension(ext)
def build_extension(self, ext):
print("=> build_extension")
os.makedirs(self.build_temp, exist_ok=True)
os.makedirs(self.build_temp + "/src", exist_ok=True)
extdir = self.get_ext_fullpath(ext.name)
os.makedirs(extdir + "/src", exist_ok=True)
for fileName in srcFiles:
fullFileName = os.path.join(targetDir, fileName)
if os.path.isfile(fullFileName):
target = self.build_temp + "/" + fileName
print("copy " + fullFileName + " => " + target)
copy(fullFileName, target)
check_call(['nimble', 'install', 'nimview', '-dy'], cwd=self.build_temp)
print("=> dependencies installed")
check_call(['nake', 'pyLib'], cwd=self.build_temp, shell=True)
print("=> pyLib created")
libFiles = [ "out/nimview.so", "out/nimview.pyd"]
install_target = os.path.abspath(os.path.dirname(extdir))
os.makedirs(install_target + "/src", exist_ok=True)
for fileName in libFiles:
fullFileName = os.path.join(self.build_temp, fileName)
if os.path.isfile(fullFileName):
print("copy " + fullFileName + " => " + install_target)
copy(fullFileName, install_target)
setup(
ext_modules=[NimExtension('.')],
cmdclass={
'build_ext': NimBuild,
},
package_data={
"nimview": srcFiles + ["nimview.so", "nimview.pyd"]
},
install_requires=[
"choosenim_install" # Auto-installs Nim compiler
]
)
|
tests/CLI/modules/vs/vs_placement_tests.py | dvzrv/softlayer-python | 126 | 11094422 | <gh_stars>100-1000
"""
SoftLayer.tests.CLI.modules.vs_placement_tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:license: MIT, see LICENSE for more details.
"""
from unittest import mock as mock
from SoftLayer import testing
class VSPlacementTests(testing.TestCase):
def test_create_options(self):
result = self.run_command(['vs', 'placementgroup', 'create-options'])
self.assert_no_fail(result)
self.assert_called_with('SoftLayer_Virtual_PlacementGroup', 'getAvailableRouters')
self.assert_called_with('SoftLayer_Virtual_PlacementGroup_Rule', 'getAllObjects')
self.assertEqual([], self.calls('SoftLayer_Virtual_PlacementGroup', 'createObject'))
@mock.patch('SoftLayer.CLI.formatting.confirm')
def test_create_group(self, confirm_mock):
confirm_mock.return_value = True
result = self.run_command(['vs', 'placementgroup', 'create', '--name=test', '--backend_router=1', '--rule=2'])
create_args = {
'name': 'test',
'backendRouterId': 1,
'ruleId': 2
}
self.assert_no_fail(result)
self.assert_called_with('SoftLayer_Virtual_PlacementGroup', 'createObject', args=(create_args,))
self.assertEqual([], self.calls('SoftLayer_Virtual_PlacementGroup', 'getAvailableRouters'))
def test_list_groups(self):
result = self.run_command(['vs', 'placementgroup', 'list'])
self.assert_no_fail(result)
self.assert_called_with('SoftLayer_Account', 'getPlacementGroups')
def test_detail_group_id(self):
result = self.run_command(['vs', 'placementgroup', 'detail', '12345'])
self.assert_no_fail(result)
self.assert_called_with('SoftLayer_Virtual_PlacementGroup', 'getObject', identifier=12345)
def test_detail_group_name(self):
result = self.run_command(['vs', 'placementgroup', 'detail', 'test'])
self.assert_no_fail(result)
group_filter = {
'placementGroups': {
'name': {'operation': 'test'}
}
}
self.assert_called_with('SoftLayer_Account', 'getPlacementGroups', filter=group_filter)
self.assert_called_with('SoftLayer_Virtual_PlacementGroup', 'getObject', identifier=12345)
@mock.patch('SoftLayer.CLI.formatting.confirm')
def test_delete_group_id(self, confirm_mock):
confirm_mock.return_value = True
result = self.run_command(['vs', 'placementgroup', 'delete', '12345'])
self.assert_no_fail(result)
self.assert_called_with('SoftLayer_Virtual_PlacementGroup', 'deleteObject', identifier=12345)
@mock.patch('SoftLayer.CLI.formatting.confirm')
def test_delete_group_id_cancel(self, confirm_mock):
confirm_mock.return_value = False
result = self.run_command(['vs', 'placementgroup', 'delete', '12345'])
self.assertEqual(result.exit_code, 2)
self.assertEqual([], self.calls('SoftLayer_Virtual_PlacementGroup', 'deleteObject'))
@mock.patch('SoftLayer.CLI.formatting.confirm')
def test_delete_group_name(self, confirm_mock):
confirm_mock.return_value = True
result = self.run_command(['vs', 'placementgroup', 'delete', 'test'])
group_filter = {
'placementGroups': {
'name': {'operation': 'test'}
}
}
self.assert_no_fail(result)
self.assert_called_with('SoftLayer_Account', 'getPlacementGroups', filter=group_filter)
self.assert_called_with('SoftLayer_Virtual_PlacementGroup', 'deleteObject', identifier=12345)
@mock.patch('SoftLayer.CLI.formatting.confirm')
def test_delete_group_purge(self, confirm_mock):
confirm_mock.return_value = True
result = self.run_command(['vs', 'placementgroup', 'delete', '1234', '--purge'])
self.assert_no_fail(result)
self.assert_called_with('SoftLayer_Virtual_PlacementGroup', 'getObject')
self.assert_called_with('SoftLayer_Virtual_Guest', 'deleteObject', identifier=69131875)
@mock.patch('SoftLayer.CLI.formatting.confirm')
def test_delete_group_purge_cancel(self, confirm_mock):
confirm_mock.return_value = False
result = self.run_command(['vs', 'placementgroup', 'delete', '1234', '--purge'])
self.assertEqual(result.exit_code, 2)
self.assertEqual([], self.calls('SoftLayer_Virtual_Guest', 'deleteObject'))
@mock.patch('SoftLayer.CLI.formatting.confirm')
def test_delete_group_purge_nothing(self, confirm_mock):
group_mock = self.set_mock('SoftLayer_Virtual_PlacementGroup', 'getObject')
group_mock.return_value = {
"id": 1234,
"name": "test-group",
"guests": [],
}
confirm_mock.return_value = True
result = self.run_command(['vs', 'placementgroup', 'delete', '1234', '--purge'])
self.assertEqual(result.exit_code, 2)
self.assert_called_with('SoftLayer_Virtual_PlacementGroup', 'getObject')
self.assertEqual([], self.calls('SoftLayer_Virtual_Guest', 'deleteObject'))
|
142_HITNET/test.py | IgiArdiyanto/PINTO_model_zoo | 1,529 | 11094427 | import warnings
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='3'
warnings.simplefilter(action='ignore', category=FutureWarning)
warnings.simplefilter(action='ignore', category=Warning)
import tensorflow as tf
import numpy as np
from pprint import pprint
import time
import platform
H=256
W=256
THREADS=4
# MODEL='flyingthings_finalpass_xl'
# CHANNEL=6
MODEL='eth3d'
CHANNEL=2
# MODEL='middlebury_d400'
# CHANNEL=6
interpreter = tf.lite.Interpreter(f'{MODEL}/saved_model_{H}x{W}/model_float32.tflite', num_threads=THREADS)
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
input_shape = input_details[0]['shape']
input_height = input_shape[1]
input_width = input_shape[2]
channels = input_shape[3]
size = (1, input_height, input_width, CHANNEL)
input_tensor = np.ones(size, dtype=np.float32)
start = time.perf_counter()
roop_count = 10
reference_output_disparity = None
for i in range(roop_count):
interpreter.set_tensor(input_details[0]['index'], input_tensor)
interpreter.invoke()
reference_output_disparity = interpreter.get_tensor(output_details[0]['index'])
inference_time = (time.perf_counter() - start) / roop_count
# pprint(reference_output_disparity)
print(f'Model: {MODEL}')
print(f'Input resolution: {H}x{W}')
print(f'Number of Threads: {THREADS}')
print(f'Platform: {platform.platform()}')
print(f'Average of {roop_count} times inference: {(inference_time * 1000):.1f}ms')
"""
$ python3 test.py
INFO: Created TensorFlow Lite XNNPACK delegate for CPU.
INFO: Created TensorFlow Lite delegate for select TF ops.
INFO: TfLiteFlexDelegate delegate: 20 nodes delegated out of 772 nodes with 10 partitions.
Model: eth3d
Input resolution: 256x256
Number of Threads: 4
Platform: Linux-5.11.0-27-generic-x86_64-with-glibc2.29
Average of 10 times inference: 360.6ms
""" |
neurogym/envs/contrib/cv_learning.py | ruyuanzhang/neurogym | 112 | 11094432 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
from gym import spaces
import neurogym as ngym
import matplotlib.pyplot as plt
class CVLearning(ngym.TrialEnv):
r"""Implements shaping for the delay-response task, in which agents
have to integrate two stimuli and report which one is larger on
average after a delay.
Args:
stim_scale: Controls the difficulty of the experiment. (def: 1., float)
max_num_reps: Maximum number of times that agent can go in a row
to the same side during phase 0. (def: 3, int)
th_stage: Performance threshold needed to proceed to the following
phase. (def: 0.7, float)
keep_days: Number of days that the agent will be kept in the same phase
once arrived to the goal performacance. (def: 1, int)
trials_day: Number of trials performed during one day. (def: 200, int)
perf_len: Number of trials used to compute instantaneous performance.
(def: 20, int)
stages: Stages used to train the agent. (def: [0, 1, 2, 3, 4], list)
"""
metadata = {
'paper_link': 'https://www.nature.com/articles/s41586-019-0919-7',
'paper_name': 'Discrete attractor dynamics underlies persistent' +
' activity in the frontal cortex',
'tags': ['perceptual', 'delayed response', 'two-alternative',
'supervised']
}
def __init__(self, dt=100, rewards=None, timing=None, stim_scale=1.,
sigma=1.0, max_num_reps=3, th_stage=0.7, keep_days=1,
trials_day=300, perf_len=20, stages=[0, 1, 2, 3, 4], n_ch=10):
super().__init__(dt=dt)
self.choices = [1, 2]
self.n_ch = n_ch # number of obs and actions different from fixation
# cohs specifies the amount of evidence
# (which is modulated by stim_scale)
self.cohs = np.array([0, 6.4, 12.8, 25.6, 51.2])*stim_scale
self.sigma = sigma / np.sqrt(self.dt) # Input noise
# Rewards
self.rewards = {'abort': -0.1, 'correct': +1., 'fail': -1.}
if rewards:
self.rewards.update(rewards)
self.delay_durs = [1000, 3000]
self.timing = {
'fixation': 200,
'stimulus': 1150,
'delay': lambda: self.rng.uniform(*self.delay_durs),
'decision': 1500}
if timing:
self.timing.update(timing)
self.stages = stages
self.r_fail = self.rewards['fail']
self.action = 0
self.abort = False
self.firstcounts = True # whether trial ends at first attempt
self.first_flag = False # whether first attempt has been done
self.ind = 0 # index of the current stage
if th_stage == -1:
self.curr_ph = self.stages[-1]
else:
self.curr_ph = self.stages[self.ind]
self.rew = 0
# PERFORMANCE VARIABLES
self.trials_counter = 0
# Day/session performance
self.curr_perf = 0
self.trials_day = trials_day
self.th_perf = th_stage
self.day_perf = np.empty(trials_day)
self.w_keep = [keep_days]*len(self.stages) # TODO: simplify??
# number of days to keep an agent on a stage
# once it has reached th_perf
self.days_keep = self.w_keep[self.ind]
self.keep_stage = False # wether the agent can move to the next stage
# Instantaneous performance (moving window)
self.inst_perf = 0
self.perf_len = perf_len # window length
self.mov_perf = np.zeros(perf_len)
# STAGE VARIABLES
# stage 0
# max number of consecutive times that an agent can repeat an action
# receiving positive reward on stage 0
self.max_num_reps = max_num_reps
# counter of consecutive actions at the same side
self.action_counter = 0
# stage 2
# min performance to keep the agent in stage 2
self.min_perf = 0.5 # TODO: no magic numbers
self.stage_reminder = False # control if a stage has been explored
# stage 3
self.inc_delays = 0 # proportion of the total delays dur to keep
self.delay_milestone = 0 # delays durs at the beggining of a day
# proportion of the total delays dur to incease every time that the
# agent reaches a threshold performance
self.inc_factor = 0.25
self.inc_delays_th = th_stage # th perf to increase delays in stage 3
self.dec_delays_th = 0.5 # th perf to decrease delays in stage 3
# number of trials spent on a specific delays duration
self.trials_delay = 0
self.max_delays = True # wheter delays have reached their max dur
self.dur = [0]*len(self.delay_durs)
# action and observation spaces
self.action_space = spaces.Discrete(n_ch+1)
self.observation_space = spaces.Box(-np.inf, np.inf, shape=(n_ch+1,),
dtype=np.float32)
def _new_trial(self, **kwargs):
"""
new_trial() is called when a trial ends to generate the next trial.
The following variables are created:
durations: Stores the duration of the different periods.
ground truth: Correct response for the trial.
coh: Stimulus coherence (evidence) for the trial.
obs: Observation.
"""
self.set_phase()
if self.curr_ph == 0:
# control that agent does not repeat side more than 3 times
self.count(self.action)
trial = {
'ground_truth': self.rng.choice(self.choices),
'coh': self.rng.choice(self.cohs),
'sigma': self.sigma,
}
# init durations with None
self.durs = {key: None for key in self.timing}
self.firstcounts = True
self.first_choice_rew = None
if self.curr_ph == 0:
# no stim, reward is in both left and right
# agent cannot go N times in a row to the same side
if np.abs(self.action_counter) >= self.max_num_reps:
ground_truth = 1 if self.action == 2 else 2
trial.update({'ground_truth': ground_truth})
self.rewards['fail'] = 0
else:
self.rewards['fail'] = self.rewards['correct']
self.durs.update({'stimulus': 0,
'delay': 0})
trial.update({'sigma': 0})
elif self.curr_ph == 1:
# stim introduced with no ambiguity
# wrong answer is not penalized
# agent can keep exploring until finding the right answer
self.durs.update({'delay': 0})
trial.update({'coh': 100})
trial.update({'sigma': 0})
self.rewards['fail'] = 0
self.firstcounts = False
elif self.curr_ph == 2:
# first answer counts
# wrong answer is penalized
self.durs.update({'delay': (0)})
trial.update({'coh': 100})
trial.update({'sigma': 0})
self.rewards['fail'] = self.r_fail
elif self.curr_ph == 3:
self.rewards['fail'] = self.r_fail
# increasing or decreasing delays durs
if self.trials_delay > self.perf_len:
if self.inst_perf >= self.inc_delays_th and\
self.inc_delays < 1:
self.inc_delays += self.inc_factor
self.trials_delay = 0
elif (self.inst_perf <= self.dec_delays_th and
self.inc_delays > self.delay_milestone):
self.inc_delays -= self.inc_factor
self.trials_delay = 0
self.dur = [int(d*self.inc_delays) for d in self.delay_durs]
if self.dur == self.delay_durs:
self.max_delays = True
else:
self.max_delays = False
self.durs.update({'delay': np.random.choice(self.dur)})
# delay component is introduced
trial.update({'coh': 100})
trial.update({'sigma': 0})
# phase 4: ambiguity component is introduced
self.first_flag = False
# ---------------------------------------------------------------------
# Trial
# ---------------------------------------------------------------------
trial.update(kwargs)
# ---------------------------------------------------------------------
# Periods
# ---------------------------------------------------------------------
self.add_period('fixation')
self.add_period('stimulus', duration=self.durs['stimulus'],
after='fixation')
self.add_period('delay', duration=self.durs['delay'],
after='stimulus')
self.add_period('decision', after='delay')
# define observations
self.set_ob([1]+[0]*self.n_ch, 'fixation')
stim = self.view_ob('stimulus')
stim[:, 0] = 1
stim[:, 1:3] = (1 - trial['coh']/100)/2
stim[:, trial['ground_truth']] = (1 + trial['coh']/100)/2
stim[:, 3:] = 0.5
stim[:, 1:] +=\
self.rng.randn(stim.shape[0], self.n_ch) * trial['sigma']
self.set_ob([1]+[0]*self.n_ch, 'delay')
self.set_groundtruth(trial['ground_truth'], 'decision')
return trial
def count(self, action):
'''
check the last three answers during stage 0 so the network has to
alternate between left and right
'''
if action != 0:
new = action - 2/action
if np.sign(self.action_counter) == np.sign(new):
self.action_counter += new
else:
self.action_counter = new
def set_phase(self):
# print(self.curr_ph)
self.day_perf[self.trials_counter] =\
1*(self.rew == self.rewards['correct'])
self.mov_perf[self.trials_counter % self.perf_len] =\
1*(self.rew == self.rewards['correct'])
self.trials_counter += 1
self.trials_delay += 1
# Instantaneous perfromace
if self.trials_counter > self.perf_len:
self.inst_perf = np.mean(self.mov_perf)
if self.inst_perf < self.min_perf and self.curr_ph == 2:
if 1 in self.stages:
self.curr_ph = 1
self.stage_reminder = True
self.ind -= 1
elif self.inst_perf > self.th_perf and self.stage_reminder:
self.curr_ph = 2
self.ind += 1
self.stage_reminder = False
# End of the day
if self.trials_counter >= self.trials_day:
self.trials_counter = 0
self.curr_perf = np.mean(self.day_perf)
self.day_perf = np.empty(self.trials_day)
self.delay_milestone = self.inc_delays
# Keeping or changing stage
if self.curr_perf >= self.th_perf and self.max_delays:
self.keep_stage = True
else:
self.keep_stage = False
self.days_keep = self.w_keep[self.ind]
if self.keep_stage:
if self.days_keep <= 0 and\
self.curr_ph < self.stages[-1]:
self.ind += 1
self.curr_ph = self.stages[self.ind]
self.days_keep = self.w_keep[self.ind] + 1
self.keep_stage = False
self.days_keep -= 1
def _step(self, action):
# obs, reward, done, info = self.env._step(action)
# ---------------------------------------------------------------------
new_trial = False
# rewards
reward = 0
gt = self.gt_now
first_choice = False
if action != 0 and not self.in_period('decision'):
new_trial = self.abort
reward = self.rewards['abort']
elif self.in_period('decision'):
if action == gt:
reward = self.rewards['correct']
new_trial = True
if not self.first_flag:
first_choice = True
self.first_flag = True
self.performance = 1
elif action == 3 - gt: # 3-action is the other act
reward = self.rewards['fail']
new_trial = self.firstcounts
if not self.first_flag:
first_choice = True
self.first_flag = True
self.performance =\
self.rewards['fail'] == self.rewards['correct']
# check if first choice (phase 1)
if not self.firstcounts and first_choice:
self.first_choice_rew = reward
# set reward for all phases
self.rew = self.first_choice_rew or reward
if new_trial and self.curr_ph == 0:
self.action = action
info = {'new_trial': new_trial, 'gt': gt, 'num_tr': self.num_tr,
'curr_ph': self.curr_ph, 'first_rew': self.rew,
'keep_stage': self.keep_stage, 'inst_perf': self.inst_perf,
'trials_day': self.trials_counter, 'durs': self.dur,
'inc_delays': self.inc_delays, 'curr_perf': self.curr_perf,
'trials_count': self.trials_counter, 'th_perf': self.th_perf,
'num_stps': self.t_ind}
return self.ob_now, reward, False, info
if __name__ == '__main__':
plt.close('all')
env = CVLearning(stages=[0, 2, 3, 4], trials_day=2, keep_days=1)
data = ngym.utils.plot_env(env, num_steps=200)
env = CVLearning(stages=[3, 4], trials_day=2, keep_days=1)
data = ngym.utils.plot_env(env, num_steps=200) |
pyq/astmatch.py | mindriot101/pyq | 144 | 11094450 | from sizzle.match import MatchEngine
import ast
import astor
class ASTMatchEngine(MatchEngine):
def __init__(self):
super(ASTMatchEngine, self).__init__()
self.register_pseudo('extends', self.pseudo_extends)
def match(self, selector, filename):
module = astor.parsefile(filename)
for match in super(ASTMatchEngine, self).match(selector, module.body):
lineno = match.lineno
if isinstance(match, (ast.ClassDef, ast.FunctionDef)):
for d in match.decorator_list:
lineno += 1
yield match, lineno
@staticmethod
def pseudo_extends(matcher, node, value):
if not isinstance(node, ast.ClassDef):
return False
if not value:
return node.bases == []
bases = node.bases
selectors = value.split(',')
for selector in selectors:
matches = matcher.match_data(
matcher.parse_selector(selector)[0], bases)
if any(matches):
return True
def match_type(self, typ, node):
if typ == 'class':
return isinstance(node, ast.ClassDef)
if typ == 'def':
return isinstance(node, ast.FunctionDef)
if typ == 'import':
return isinstance(node, (ast.Import, ast.ImportFrom))
if typ == 'assign':
return isinstance(node, ast.Assign)
if typ == 'attr':
return isinstance(node, ast.Attribute)
if typ == 'call':
if isinstance(node, ast.Call):
return True
# Python 2.x compatibility
return hasattr(ast, 'Print') and isinstance(node, ast.Print)
def match_id(self, id_, node):
if isinstance(node, (ast.ClassDef, ast.FunctionDef)):
return node.name == id_
if isinstance(node, ast.Name):
return node.id == id_
if isinstance(node, ast.Attribute):
return node.attr == id_
if isinstance(node, ast.Assign):
for target in node.targets:
if hasattr(target, 'id'):
if target.id == id_:
return True
if hasattr(target, 'elts'):
if id_ in self._extract_names_from_tuple(target):
return True
elif isinstance(target, ast.Subscript):
if hasattr(target.value, 'id'):
if target.value.id == id_:
return True
if isinstance(node, ast.Call):
if isinstance(node.func, ast.Name) and node.func.id == id_:
return True
if id_ == 'print' \
and hasattr(ast, 'Print') and isinstance(node, ast.Print):
# Python 2.x compatibility
return True
def match_attr(self, lft, op, rgt, node):
values = []
if lft == 'from':
if isinstance(node, ast.ImportFrom) and node.module:
values.append(node.module)
elif lft == 'full':
if isinstance(node, (ast.Import, ast.ImportFrom)):
module = ''
if isinstance(node, ast.ImportFrom):
if node.module:
module = node.module + '.'
for n in node.names:
values.append(module + n.name)
if n.asname:
values.append(module + n.asname)
elif lft == 'name':
if isinstance(node, (ast.Import, ast.ImportFrom)):
for alias in node.names:
if alias.asname:
values.append(alias.asname)
values.append(alias.name)
elif isinstance(node, ast.Call):
if hasattr(node.func, 'id'):
values.append(node.func.id)
elif hasattr(ast, 'Print') and isinstance(node, ast.Print):
values.append('print')
elif isinstance(node, ast.Assign):
for target in node.targets:
if hasattr(target, 'id'):
values.append(target.id)
elif hasattr(target, 'elts'):
values.extend(self._extract_names_from_tuple(target))
elif isinstance(target, ast.Subscript):
if hasattr(target.value, 'id'):
values.append(target.value.id)
elif hasattr(node, lft):
values.append(getattr(node, lft))
elif lft in ('kwarg', 'arg'):
if isinstance(node, ast.Call):
if lft == 'kwarg':
values = [kw.arg for kw in node.keywords]
elif lft == 'arg':
values = [arg.id for arg in node.args]
if op == '=':
return any(value == rgt for value in values)
if op == '!=':
return any(value != rgt for value in values)
if op == '*=':
return any(rgt in value for value in values)
if op == '^=':
return any(value.startswith(rgt) for value in values)
if op == '$=':
return any(value.endswith(rgt) for value in values)
raise Exception('Attribute operator {} not implemented'.format(op))
def iter_data(self, data):
for node in data:
for n in self.iter_node(node):
yield n
def iter_node(self, node):
silence = (ast.Expr,)
if not isinstance(node, silence):
try:
body = node.body
# check if is iterable
list(body)
except TypeError:
body = [node.body]
except AttributeError:
body = None
yield node, body
for attr in ('value', 'func', 'right', 'left'):
if hasattr(node, attr):
value = getattr(node, attr)
# reversed is used here so matches are returned in the
# sequence they are read, eg.: foo.bar.bang
for n in reversed(list(self.iter_node(value))):
yield n
@classmethod
def _extract_names_from_tuple(cls, tupl):
r = []
for item in tupl.elts:
if hasattr(item, 'elts'):
r.extend(cls._extract_names_from_tuple(item))
else:
r.append(item.id)
return r
|
tracking/eval/formatchecker.py | holajoa/keras-YOLOv3-model-set | 601 | 11094464 | <gh_stars>100-1000
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
from utilities import write_stderr_red
class FormatChecker:
def __init__(self, groundtruth, hypotheses):
"""Constructor """
self.groundtruth_ = groundtruth
self.hypotheses_ = hypotheses
def checkForAmbiguousIDs(self):
"""Check ground truth and hypotheses for multiple use of the same id per frame"""
result = True
for frame in self.groundtruth_["frames"]:
ids = set()
for groundtruth in frame["annotations"]:
if not "id" in groundtruth:
# We should have already warned about a missing ID in checkForExistingIDs
# no need to raise an exception in this function by trying to access missing IDs
continue
if groundtruth["id"] in ids:
result &= False
write_stderr_red("Warning:", "Ambiguous id (%s) found in ground truth, timestamp %f, frame %d!" % (str(groundtruth["id"]), frame["timestamp"], frame["num"] if "num" in frame else -1))
else:
ids.add(groundtruth["id"])
for frame in self.hypotheses_["frames"]:
ids = set()
for hypothesis in frame["hypotheses"]:
if hypothesis["id"] in ids:
result &= False
write_stderr_red("Warning:", "Ambiguous hypothesis (%s) found in hypotheses, timestamp %f, frame %d!" % (str(hypothesis["id"]), frame["timestamp"], frame["num"] if "num" in frame else -1))
else:
ids.add(hypothesis["id"])
return result # true: OK, false: ambiguous id found
def checkForExistingIDs(self):
"""Check ground truth and hypotheses for having a valid id. Valid: existing and non-empty."""
result = True
for f in self.groundtruth_["frames"]:
for g in f["annotations"]:
if not "id" in g.keys():
write_stderr_red("Warning:", "Groundtruth without ID found, timestamp %f, frame %d!" % (f["timestamp"], f["num"] if "num" in f else -1))
result &= False
continue
if g["id"] == "":
write_stderr_red("Warning:", "Groundtruth with empty ID found, timestamp %f, frame %d!" % (f["timestamp"], f["num"] if "num" in f else -1))
result &= False
continue
# Hypotheses without ids or with empty ids
for f in self.hypotheses_["frames"]:
for h in f["hypotheses"]:
if not "id" in h.keys():
write_stderr_red("Warning:", "Hypothesis without ID found, timestamp %f, frame %d!" % (f["timestamp"], f["num"] if "num" in f else -1))
result &= False
continue
if h["id"] == "":
write_stderr_red("Warning:", "Hypothesis with empty ID found, timestamp %f, frame %d!" % (f["timestamp"], f["num"] if "num" in f else -1))
result &= False
continue
return result # true: OK, false: missing id found
def checkForCompleteness(self):
"""Check ground truth and hypotheses for containing width, height, x and y"""
result = True
expectedKeys = ("x", "y", "width", "height")
for f in self.groundtruth_["frames"]:
for g in f["annotations"]:
for key in expectedKeys:
if not key in g.keys():
write_stderr_red("Warning:", "Groundtruth without key %s found, timestamp %f, frame %d!" % (key, f["timestamp"], f["num"] if "num" in f else -1))
result &= False
# Hypotheses without ids or with empty ids
for f in self.hypotheses_["frames"]:
for h in f["hypotheses"]:
for key in expectedKeys:
if not key in h.keys():
write_stderr_red("Warning:", "Hypothesis without key %s found, timestamp %f, frame %d!" % (key, f["timestamp"], f["num"] if "num" in f else -1))
result &= False
return result # true: OK, false: missing id found
|
tests/test_globals.py | hacs/integration | 2,039 | 11094522 | <gh_stars>1000+
"""Test globals."""
# pylint: disable=missing-docstring
def test_global_hacs(hacs):
assert hacs.core.lovelace_mode == "yaml"
hacs.core.lovelace_mode = "storage"
assert hacs.core.lovelace_mode == "storage"
|
slashtags/mixins/__init__.py | Onii-Chan-Discord/phen-cogs | 105 | 11094546 | <reponame>Onii-Chan-Discord/phen-cogs<gh_stars>100-1000
from .commands import Commands # noqa
from .processor import Processor # noqa
|
etl/parsers/etw/Microsoft_Windows_L2NACP.py | IMULMUL/etl-parser | 104 | 11094548 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
"""
Microsoft-Windows-L2NACP
GUID : 85fe7609-ff4a-48e9-9d50-12918e43e1da
"""
from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct
from etl.utils import WString, CString, SystemTime, Guid
from etl.dtyp import Sid
from etl.parsers.etw.core import Etw, declare, guid
@declare(guid=guid("85fe7609-ff4a-48e9-9d50-12918e43e1da"), event_id=13003, version=0)
class Microsoft_Windows_L2NACP_13003_0(Etw):
pattern = Struct(
"Result" / Int32ul,
"Reason" / Int32ul,
"InterfaceGuid" / Guid,
"ProfileName" / WString
)
@declare(guid=guid("85fe7609-ff4a-48e9-9d50-12918e43e1da"), event_id=13004, version=0)
class Microsoft_Windows_L2NACP_13004_0(Etw):
pattern = Struct(
"Result" / Int32ul,
"InterfaceGuid" / Guid,
"ProfileName" / WString
)
@declare(guid=guid("85fe7609-ff4a-48e9-9d50-12918e43e1da"), event_id=13023, version=0)
class Microsoft_Windows_L2NACP_13023_0(Etw):
pattern = Struct(
"Result" / Int32ul,
"Reason" / Int32ul,
"InterfaceGuid" / Guid
)
@declare(guid=guid("85fe7609-ff4a-48e9-9d50-12918e43e1da"), event_id=13024, version=0)
class Microsoft_Windows_L2NACP_13024_0(Etw):
pattern = Struct(
"Result" / Int32ul,
"InterfaceGuid" / Guid
)
@declare(guid=guid("85fe7609-ff4a-48e9-9d50-12918e43e1da"), event_id=14000, version=0)
class Microsoft_Windows_L2NACP_14000_0(Etw):
pattern = Struct(
"Enabled" / Int8ul,
"Remote" / Int8ul,
"Dot3Allowed" / Int8ul,
"WlanAllowed" / Int8ul,
"CredentialsFound" / Int8ul
)
|
atcoder/abc068/b.py | Ashindustry007/competitive-programming | 506 | 11094560 | <gh_stars>100-1000
#!/usr/bin/env python3
# https://abc068.contest.atcoder.jp/tasks/abc068_b
n = int(input())
k = 1
while k * 2 <= n: k *= 2
print(k)
|
examples/generation/docking_generation/guacamol_tdc/guacamol_baselines/smiles_lstm_ppo/running_reward.py | Shicheng-Guo/TDC | 577 | 11094561 | class RunningReward(object):
def __init__(self, keep_factor: float, initial_value=0) -> None:
"""
Args:
keep_factor: How much of the last value to keep when a new one is added.
initial_value: Initial reward
"""
assert keep_factor >= 0.0
assert keep_factor <= 1.0
self._keep_factor = keep_factor
self._reward = initial_value
self.last_added = initial_value
@property
def value(self):
"""Get the current running reward."""
return self._reward
def update(self, reward):
"""Update the running reward with a new value."""
self._reward *= self._keep_factor
self._reward += reward * (1.0 - self._keep_factor)
self.last_added = reward
|
Scripted/attic/PicasaSnap/gdata/calendar/client.py | hung-lab/SlicerCIP | 267 | 11094584 | #!/usr/bin/python
#
# Copyright (C) 2011 Google Inc.
#
# 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.
"""CalendarClient extends the GDataService to streamline Google Calendar operations.
CalendarService: Provides methods to query feeds and manipulate items. Extends
GDataService.
DictionaryToParamList: Function which converts a dictionary into a list of
URL arguments (represented as strings). This is a
utility function used in CRUD operations.
"""
__author__ = 'alainv (<NAME>)'
import urllib.request, urllib.parse, urllib.error
import gdata.client
import gdata.calendar.data
import atom.data
import atom.http_core
import gdata.gauth
DEFAULT_BATCH_URL = ('https://www.google.com/calendar/feeds/default/private'
'/full/batch')
class CalendarClient(gdata.client.GDClient):
"""Client for the Google Calendar service."""
api_version = '2'
auth_service = 'cl'
server = "www.google.com"
contact_list = "default"
auth_scopes = gdata.gauth.AUTH_SCOPES['cl']
def __init__(self, domain=None, auth_token=None, **kwargs):
"""Constructs a new client for the Calendar API.
Args:
domain: string The Google Apps domain (if any).
kwargs: The other parameters to pass to the gdata.client.GDClient
constructor.
"""
gdata.client.GDClient.__init__(self, auth_token=auth_token, **kwargs)
self.domain = domain
def get_calendar_feed_uri(self, feed='', projection='full', scheme="https"):
"""Builds a feed URI.
Args:
projection: The projection to apply to the feed contents, for example
'full', 'base', 'base/12345', 'full/batch'. Default value: 'full'.
scheme: The URL scheme such as 'http' or 'https', None to return a
relative URI without hostname.
Returns:
A feed URI using the given scheme and projection.
Example: '/calendar/feeds/default/owncalendars/full'.
"""
prefix = scheme and '%s://%s' % (scheme, self.server) or ''
suffix = feed and '/%s/%s' % (feed, projection) or ''
return '%s/calendar/feeds/default%s' % (prefix, suffix)
GetCalendarFeedUri = get_calendar_feed_uri
def get_calendar_event_feed_uri(self, calendar='default', visibility='private',
projection='full', scheme="https"):
"""Builds a feed URI.
Args:
projection: The projection to apply to the feed contents, for example
'full', 'base', 'base/12345', 'full/batch'. Default value: 'full'.
scheme: The URL scheme such as 'http' or 'https', None to return a
relative URI without hostname.
Returns:
A feed URI using the given scheme and projection.
Example: '/calendar/feeds/default/private/full'.
"""
prefix = scheme and '%s://%s' % (scheme, self.server) or ''
return '%s/calendar/feeds/%s/%s/%s' % (prefix, calendar,
visibility, projection)
GetCalendarEventFeedUri = get_calendar_event_feed_uri
def get_calendars_feed(self, uri,
desired_class=gdata.calendar.data.CalendarFeed,
auth_token=None, **kwargs):
"""Obtains a calendar feed.
Args:
uri: The uri of the calendar feed to request.
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (desired_class=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.calendar.data.CalendarFeed.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
"""
return self.get_feed(uri, auth_token=auth_token,
desired_class=desired_class, **kwargs)
GetCalendarsFeed = get_calendars_feed
def get_own_calendars_feed(self,
desired_class=gdata.calendar.data.CalendarFeed,
auth_token=None, **kwargs):
"""Obtains a feed containing the calendars owned by the current user.
Args:
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (desired_class=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.calendar.data.CalendarFeed.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
"""
return self.GetCalendarsFeed(uri=self.GetCalendarFeedUri(feed='owncalendars'),
desired_class=desired_class, auth_token=auth_token,
**kwargs)
GetOwnCalendarsFeed = get_own_calendars_feed
def get_all_calendars_feed(self, desired_class=gdata.calendar.data.CalendarFeed,
auth_token=None, **kwargs):
"""Obtains a feed containing all the ccalendars the current user has access to.
Args:
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (desired_class=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.calendar.data.CalendarFeed.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
"""
return self.GetCalendarsFeed(uri=self.GetCalendarFeedUri(feed='allcalendars'),
desired_class=desired_class, auth_token=auth_token,
**kwargs)
GetAllCalendarsFeed = get_all_calendars_feed
def get_calendar_entry(self, uri, desired_class=gdata.calendar.data.CalendarEntry,
auth_token=None, **kwargs):
"""Obtains a single calendar entry.
Args:
uri: The uri of the desired calendar entry.
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (desired_class=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.calendar.data.CalendarEntry.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
"""
return self.get_entry(uri, auth_token=auth_token, desired_class=desired_class,
**kwargs)
GetCalendarEntry = get_calendar_entry
def get_calendar_event_feed(self, uri=None,
desired_class=gdata.calendar.data.CalendarEventFeed,
auth_token=None, **kwargs):
"""Obtains a feed of events for the desired calendar.
Args:
uri: The uri of the desired calendar entry.
Defaults to https://www.google.com/calendar/feeds/default/private/full.
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (desired_class=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.calendar.data.CalendarEventFeed.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
"""
uri = uri or self.GetCalendarEventFeedUri()
return self.get_feed(uri, auth_token=auth_token,
desired_class=desired_class, **kwargs)
GetCalendarEventFeed = get_calendar_event_feed
def get_event_entry(self, uri, desired_class=gdata.calendar.data.CalendarEventEntry,
auth_token=None, **kwargs):
"""Obtains a single event entry.
Args:
uri: The uri of the desired calendar event entry.
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (desired_class=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.calendar.data.CalendarEventEntry.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
"""
return self.get_entry(uri, auth_token=auth_token, desired_class=desired_class,
**kwargs)
GetEventEntry = get_event_entry
def get_calendar_acl_feed(self, uri='https://www.google.com/calendar/feeds/default/acl/full',
desired_class=gdata.calendar.data.CalendarAclFeed,
auth_token=None, **kwargs):
"""Obtains an Access Control List feed.
Args:
uri: The uri of the desired Acl feed.
Defaults to https://www.google.com/calendar/feeds/default/acl/full.
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (desired_class=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.calendar.data.CalendarAclFeed.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
"""
return self.get_feed(uri, auth_token=auth_token, desired_class=desired_class,
**kwargs)
GetCalendarAclFeed = get_calendar_acl_feed
def get_calendar_acl_entry(self, uri, desired_class=gdata.calendar.data.CalendarAclEntry,
auth_token=None, **kwargs):
"""Obtains a single Access Control List entry.
Args:
uri: The uri of the desired Acl feed.
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (desired_class=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.calendar.data.CalendarAclEntry.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
"""
return self.get_entry(uri, auth_token=auth_token, desired_class=desired_class,
**kwargs)
GetCalendarAclEntry = get_calendar_acl_entry
def insert_calendar(self, new_calendar, insert_uri=None, auth_token=None, **kwargs):
"""Adds an new calendar to Google Calendar.
Args:
new_calendar: atom.Entry or subclass A new calendar which is to be added to
Google Calendar.
insert_uri: the URL to post new contacts to the feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the contact created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
insert_uri = insert_uri or self.GetCalendarFeedUri(feed='owncalendars')
return self.Post(new_calendar, insert_uri,
auth_token=auth_token, **kwargs)
InsertCalendar = insert_calendar
def insert_calendar_subscription(self, calendar, insert_uri=None,
auth_token=None, **kwargs):
"""Subscribes the authenticated user to the provided calendar.
Args:
calendar: The calendar to which the user should be subscribed.
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the subscription created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
insert_uri = insert_uri or self.GetCalendarFeedUri(feed='allcalendars')
return self.Post(calendar, insert_uri, auth_token=auth_token, **kwargs)
InsertCalendarSubscription = insert_calendar_subscription
def insert_event(self, new_event, insert_uri=None, auth_token=None, **kwargs):
"""Adds an new event to Google Calendar.
Args:
new_event: atom.Entry or subclass A new event which is to be added to
Google Calendar.
insert_uri: the URL to post new contacts to the feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the contact created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
insert_uri = insert_uri or self.GetCalendarEventFeedUri()
return self.Post(new_event, insert_uri,
auth_token=auth_token, **kwargs)
InsertEvent = insert_event
def insert_acl_entry(self, new_acl_entry,
insert_uri = 'https://www.google.com/calendar/feeds/default/acl/full',
auth_token=None, **kwargs):
"""Adds an new Acl entry to Google Calendar.
Args:
new_acl_event: atom.Entry or subclass A new acl which is to be added to
Google Calendar.
insert_uri: the URL to post new contacts to the feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the contact created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Post(new_acl_entry, insert_uri, auth_token=auth_token, **kwargs)
InsertAclEntry = insert_acl_entry
def execute_batch(self, batch_feed, url, desired_class=None):
"""Sends a batch request feed to the server.
Args:
batch_feed: gdata.contacts.CalendarEventFeed A feed containing batch
request entries. Each entry contains the operation to be performed
on the data contained in the entry. For example an entry with an
operation type of insert will be used as if the individual entry
had been inserted.
url: str The batch URL to which these operations should be applied.
converter: Function (optional) The function used to convert the server's
response to an object.
Returns:
The results of the batch request's execution on the server. If the
default converter is used, this is stored in a ContactsFeed.
"""
return self.Post(batch_feed, url, desired_class=desired_class)
ExecuteBatch = execute_batch
def update(self, entry, auth_token=None, **kwargs):
"""Edits the entry on the server by sending the XML for this entry.
Performs a PUT and converts the response to a new entry object with a
matching class to the entry passed in.
Args:
entry:
auth_token:
Returns:
A new Entry object of a matching type to the entry which was passed in.
"""
return gdata.client.GDClient.Update(self, entry, auth_token=auth_token,
force=True, **kwargs)
Update = update
class CalendarEventQuery(gdata.client.Query):
"""
Create a custom Calendar Query
Full specs can be found at: U{Calendar query parameters reference
<http://code.google.com/apis/calendar/data/2.0/reference.html#Parameters>}
"""
def __init__(self, feed=None, ctz=None, fields=None, futureevents=None,
max_attendees=None, orderby=None, recurrence_expansion_start=None,
recurrence_expansion_end=None, singleevents=None, showdeleted=None,
showhidden=None, sortorder=None, start_min=None, start_max=None,
updated_min=None, **kwargs):
"""
@param max_results: The maximum number of entries to return. If you want
to receive all of the contacts, rather than only the default maximum, you
can specify a very large number for max-results.
@param start-index: The 1-based index of the first result to be retrieved.
@param updated-min: The lower bound on entry update dates.
@param group: Constrains the results to only the contacts belonging to the
group specified. Value of this parameter specifies group ID
@param orderby: Sorting criterion. The only supported value is
lastmodified.
@param showdeleted: Include deleted contacts in the returned contacts feed
@pram sortorder: Sorting order direction. Can be either ascending or
descending.
@param requirealldeleted: Only relevant if showdeleted and updated-min
are also provided. It dictates the behavior of the server in case it
detects that placeholders of some entries deleted since the point in
time specified as updated-min may have been lost.
"""
gdata.client.Query.__init__(self, **kwargs)
self.ctz = ctz
self.fields = fields
self.futureevents = futureevents
self.max_attendees = max_attendees
self.orderby = orderby
self.recurrence_expansion_start = recurrence_expansion_start
self.recurrence_expansion_end = recurrence_expansion_end
self.singleevents = singleevents
self.showdeleted = showdeleted
self.showhidden = showhidden
self.sortorder = sortorder
self.start_min = start_min
self.start_max = start_max
self.updated_min = updated_min
def modify_request(self, http_request):
if self.ctz:
gdata.client._add_query_param('ctz', self.ctz, http_request)
if self.fields:
gdata.client._add_query_param('fields', self.fields, http_request)
if self.futureevents:
gdata.client._add_query_param('futureevents', self.futureevents, http_request)
if self.max_attendees:
gdata.client._add_query_param('max-attendees', self.max_attendees, http_request)
if self.orderby:
gdata.client._add_query_param('orderby', self.orderby, http_request)
if self.recurrence_expansion_start:
gdata.client._add_query_param('recurrence-expansion-start',
self.recurrence_expansion_start, http_request)
if self.recurrence_expansion_end:
gdata.client._add_query_param('recurrence-expansion-end',
self.recurrence_expansion_end, http_request)
if self.singleevents:
gdata.client._add_query_param('singleevents', self.singleevents, http_request)
if self.showdeleted:
gdata.client._add_query_param('showdeleted', self.showdeleted, http_request)
if self.showhidden:
gdata.client._add_query_param('showhidden', self.showhidden, http_request)
if self.sortorder:
gdata.client._add_query_param('sortorder', self.sortorder, http_request)
if self.start_min:
gdata.client._add_query_param('start-min', self.start_min, http_request)
if self.start_max:
gdata.client._add_query_param('start-max', self.start_max, http_request)
if self.updated_min:
gdata.client._add_query_param('updated-min', self.updated_min, http_request)
gdata.client.Query.modify_request(self, http_request)
ModifyRequest = modify_request
|
src/ssort/__init__.py | bwhmather/ssort | 238 | 11094597 | <reponame>bwhmather/ssort
"""
The python source code statement sorter.
"""
from ssort._exceptions import ResolutionError
from ssort._ssort import ssort
# Let linting tools know that we mean to re-export ResolutionError.
assert ResolutionError is not None
__version__ = "0.9.0"
__all__ = ["ssort"]
|
koku/api/resource_types/test/openshift_projects/test_views.py | rubik-ai/koku | 157 | 11094608 | #
# Copyright 2021 Red Hat Inc.
# SPDX-License-Identifier: Apache-2.0
#
"""Test the Resource Types views."""
from django.db.models import F
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from tenant_schemas.utils import schema_context
from api.iam.test.iam_test_case import IamTestCase
from api.iam.test.iam_test_case import RbacPermissions
from reporting.provider.ocp.models import OCPCostSummaryByProjectP
class ResourceTypesViewTestOpenshiftProjects(IamTestCase):
"""Tests the resource types views."""
def setUp(self):
"""Set up the customer view tests."""
super().setUp()
self.client = APIClient()
@RbacPermissions({"openshift.project": {"read": ["cost-management"]}})
def test_openshift_project_with_project_access_view(self):
"""Test endpoint runs with a customer owner."""
with schema_context(self.schema_name):
expected = (
OCPCostSummaryByProjectP.objects.annotate(**{"value": F("namespace")})
.values("value")
.distinct()
.filter(namespace__in=["cost-management"])
.count()
)
# check that the expected is not zero
self.assertTrue(expected)
url = reverse("openshift-projects")
response = self.client.get(url, **self.headers)
self.assertEqual(response.status_code, status.HTTP_200_OK)
json_result = response.json()
self.assertIsNotNone(json_result.get("data"))
self.assertIsInstance(json_result.get("data"), list)
self.assertEqual(len(json_result.get("data")), expected)
@RbacPermissions({"openshift.cluster": {"read": ["OCP-on-AWS"]}})
def test_openshift_project_with_cluster_access_view(self):
"""Test endpoint runs with a customer owner."""
with schema_context(self.schema_name):
expected = (
OCPCostSummaryByProjectP.objects.annotate(**{"value": F("namespace")})
.values("value")
.distinct()
.filter(cluster_id__in=["OCP-on-AWS"])
.count()
)
# check that the expected is not zero
self.assertTrue(expected)
url = reverse("openshift-projects")
response = self.client.get(url, **self.headers)
self.assertEqual(response.status_code, status.HTTP_200_OK)
json_result = response.json()
self.assertIsNotNone(json_result.get("data"))
self.assertIsInstance(json_result.get("data"), list)
self.assertEqual(len(json_result.get("data")), expected)
@RbacPermissions(
{"openshift.cluster": {"read": ["OCP-on-AWS"]}, "openshift.project": {"read": ["cost-management"]}}
)
def test_openshift_project_with_cluster_and_project_access_view(self):
"""Test endpoint runs with a customer owner."""
with schema_context(self.schema_name):
expected = (
OCPCostSummaryByProjectP.objects.annotate(**{"value": F("namespace")})
.values("value")
.distinct()
.filter(namespace__in=["cost-management"], cluster_id__in=["OCP-on-AWS"])
.count()
)
# check that the expected is not zero
self.assertTrue(expected)
url = reverse("openshift-projects")
response = self.client.get(url, **self.headers)
self.assertEqual(response.status_code, status.HTTP_200_OK)
json_result = response.json()
self.assertIsNotNone(json_result.get("data"))
self.assertIsInstance(json_result.get("data"), list)
self.assertEqual(len(json_result.get("data")), expected)
@RbacPermissions({"openshift.cluster": {"read": ["OCP-on-AWS"]}, "openshift.project": {"read": ["*"]}})
def test_openshift_project_with_cluster_and_all_project_access_view(self):
"""Test endpoint runs with a customer owner."""
with schema_context(self.schema_name):
expected = (
OCPCostSummaryByProjectP.objects.annotate(**{"value": F("namespace")})
.values("value")
.distinct()
.filter(cluster_id__in=["OCP-on-AWS"])
.count()
)
# check that the expected is not zero
self.assertTrue(expected)
url = reverse("openshift-projects")
response = self.client.get(url, **self.headers)
self.assertEqual(response.status_code, status.HTTP_200_OK)
json_result = response.json()
self.assertIsNotNone(json_result.get("data"))
self.assertIsInstance(json_result.get("data"), list)
self.assertEqual(len(json_result.get("data")), expected)
@RbacPermissions({"openshift.cluster": {"read": ["*"]}, "openshift.project": {"read": ["cost-management"]}})
def test_openshift_project_with_all_cluster_and_project_access_view(self):
"""Test endpoint runs with a customer owner."""
with schema_context(self.schema_name):
expected = (
OCPCostSummaryByProjectP.objects.annotate(**{"value": F("namespace")})
.values("value")
.distinct()
.filter(namespace__in=["cost-management"])
.count()
)
# check that the expected is not zero
self.assertTrue(expected)
url = reverse("openshift-projects")
response = self.client.get(url, **self.headers)
self.assertEqual(response.status_code, status.HTTP_200_OK)
json_result = response.json()
self.assertIsNotNone(json_result.get("data"))
self.assertIsInstance(json_result.get("data"), list)
self.assertEqual(len(json_result.get("data")), expected)
|
bgp-add-fake-routes.py | 9l/scapy | 129 | 11094616 | <reponame>9l/scapy
#!/usr/bin/env python3
#Import time so we can set a sleep timer
import time
#Import scapy
from scapy.all import *
#Import BGP
load_contrib('bgp')
#Capture a BGP packet off the wire
#You will need to change the IP address here to a valid
#BGP neighbor to impersonate
pkt = sniff(filter="tcp and ip dst 192.168.1.249",count=1)
#Loop for sending packets
for i in range (0, 3):
#Create a new Ethernet frame
frame1=Ether()
#Set destination MAC address to captured BGP frame
frame1.dst = pkt[0].dst
#Set source MAC address to captured BGP frame
frame1.src = pkt[0].src
#Set Ethernet Type to captured BGP frame
frame1.type = pkt[0].type
#Set destination port to captured BGP packet TCP port number
mydport = pkt[0].dport
#Set source port to captured BGP packet TCP port number
mysport = pkt[0].sport
#Set sequence number to captured BGP packet + i (loop value)
seq_num = pkt[0].seq + i
#Set ack number to captured BGP packet
ack_num = pkt[0].ack
#Set source IP address to captured BGP packet
ipsrc = pkt[0][IP].src
#Set desination IP address to captured BGP packet
ipdst = pkt[0][IP].dst
#Set BGP origin to IGP
setORIGIN=BGPPathAttr(type_flags="Transitive", type_code="ORIGIN", attribute=[BGPPAOrigin(origin="IGP")])
#Set BGP autonomos system path - change this to the right value
setAS=BGPPathAttr(type_flags="Transitive", type_code="AS_PATH", attribute=None)
#Set BGP next hop - change this to the right value
setNEXTHOP=BGPPathAttr(type_flags="Transitive", type_code="NEXT_HOP", attribute=[BGPPANextHop(next_hop="192.168.1.246")])
#Set BGP MED - change this to the right value
setMED=BGPPathAttr(type_flags="Optional", type_code="MULTI_EXIT_DISC", attribute=[BGPPAMultiExitDisc(med=0)])
#Set BGP local preference - change this to the right value
setLOCALPREF=BGPPathAttr(type_flags="Transitive", type_code="LOCAL_PREF", attribute=[BGPPALocalPref(local_pref=100)])
#Create BGP Update packet with source and destination IP address
#Set Attributes and route to update
bgp_update = IP(src=ipsrc, dst=ipdst, ttl=1)\
/TCP(dport=mydport, sport=mysport, flags="PA", seq=seq_num, ack=ack_num)\
/BGPHeader(marker=340282366920938463463374607431768211455, type="UPDATE")\
/BGPUpdate(withdrawn_routes_len=0, \
path_attr=[setORIGIN, setAS, setNEXTHOP, setMED, setLOCALPREF], nlri=[BGPNLRI_IPv4(prefix="12.12.12.12/32")])
#Display new packet
bgp_update.show()
#Reset len values to force recalculation
del bgp_update[BGPHeader].len
del bgp_update[BGPHeader].path_attr_len
del bgp_update[BGPUpdate].path_attr_len
del bgp_update[BGPUpdate][0][BGPPathAttr].attr_len
del bgp_update[BGPUpdate][1][BGPPathAttr].attr_len
del bgp_update[BGPUpdate][3][BGPPathAttr].attr_len
del bgp_update[BGPUpdate][4][BGPPathAttr].attr_len
del bgp_update[IP].len
#Send packet into network = frame1 + bgp_update
sendp(frame1/bgp_update)
|
rotkehlchen/api/websockets/notifier.py | rotkehlchenio/rotkehlchen | 137 | 11094656 | <gh_stars>100-1000
import json
import logging
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional
from geventwebsocket import WebSocketApplication
from geventwebsocket.exceptions import WebSocketError
from geventwebsocket.websocket import WebSocket
from rotkehlchen.greenlets import GreenletManager
from rotkehlchen.logging import RotkehlchenLogsAdapter
if TYPE_CHECKING:
from rotkehlchen.api.websockets.typedefs import WSMessageType
logger = logging.getLogger(__name__)
log = RotkehlchenLogsAdapter(logger)
def _ws_send_impl(
websocket: WebSocket,
to_send_msg: str,
success_callback: Optional[Callable] = None,
success_callback_args: Optional[Dict[str, Any]] = None,
failure_callback: Optional[Callable] = None,
failure_callback_args: Optional[Dict[str, Any]] = None,
) -> None:
try:
websocket.send(to_send_msg)
except WebSocketError as e:
log.error(f'Websocket send with message {to_send_msg} failed due to {str(e)}')
if failure_callback:
failure_callback_args = {} if failure_callback_args is None else failure_callback_args # noqa: E501
failure_callback(**failure_callback_args)
return
if success_callback: # send success
success_callback_args = {} if success_callback_args is None else success_callback_args # noqa: E501
success_callback(**success_callback_args)
class RotkiNotifier():
def __init__(
self,
greenlet_manager: GreenletManager,
) -> None:
self.greenlet_manager = greenlet_manager
self.subscribers: List[WebSocket] = []
def subscribe(self, websocket: WebSocket) -> None:
log.info(f'Websocket with hash id {hash(websocket)} subscribed to rotki notifier')
self.subscribers.append(websocket)
def unsubscribe(self, websocket: WebSocket) -> None:
try:
self.subscribers.remove(websocket)
log.info(f'Websocket with hash id {hash(websocket)} unsubscribed from rotki notifier') # noqa: E501
except ValueError:
pass
def broadcast(
self,
message_type: 'WSMessageType',
to_send_data: Dict[str, Any],
success_callback: Optional[Callable] = None,
success_callback_args: Optional[Dict[str, Any]] = None,
failure_callback: Optional[Callable] = None,
failure_callback_args: Optional[Dict[str, Any]] = None,
) -> None:
message_data = {'type': str(message_type), 'data': to_send_data}
message = json.dumps(message_data) # TODO: Check for dumps error
to_remove_indices = set()
spawned_one_broadcast = False
for idx, websocket in enumerate(self.subscribers):
if websocket.closed is True:
to_remove_indices.add(idx)
continue
self.greenlet_manager.spawn_and_track(
after_seconds=None,
task_name=f'Websocket send for {str(message_type)}',
exception_is_error=True,
method=_ws_send_impl,
websocket=websocket,
to_send_msg=message,
success_callback=success_callback,
success_callback_args=success_callback_args,
failure_callback=failure_callback,
failure_callback_args=failure_callback_args,
)
spawned_one_broadcast = True
if len(to_remove_indices) != 0: # removed closed websockets from the list
self.subscribers = [
i for j, i in enumerate(self.subscribers) if j not in to_remove_indices
]
if spawned_one_broadcast is False and failure_callback is not None:
failure_callback_args = {} if failure_callback_args is None else failure_callback_args # noqa: E501
failure_callback(**failure_callback_args)
class RotkiWSApp(WebSocketApplication):
"""The WebSocket app that's instantiated for every message as it seems from the code
Only way to pass it extra arguments is through "environ" which is why we have
a different class "RotkiNotifier" handling the bulk of the work
"""
def on_open(self, *args: Any, **kwargs: Any) -> None:
rotki_notifier: RotkiNotifier = self.ws.environ['rotki_notifier']
rotki_notifier.subscribe(self.ws)
def on_message(self, message: Optional[str], *args: Any, **kwargs: Any) -> None:
if self.ws.closed:
return
try:
self.ws.send(message, **kwargs)
except WebSocketError as e:
log.warning(
f'Got WebSocketError {str(e)} for sending message {message} to a websocket',
)
def on_close(self, *args: Any, **kwargs: Any) -> None:
if self.ws.environ is not None:
rotki_notifier: RotkiNotifier = self.ws.environ['rotki_notifier']
rotki_notifier.unsubscribe(self.ws)
|
tools/Polygraphy/polygraphy/exception/__init__.py | KaliberAI/TensorRT | 5,249 | 11094676 | <reponame>KaliberAI/TensorRT<filename>tools/Polygraphy/polygraphy/exception/__init__.py<gh_stars>1000+
from polygraphy.exception.exception import *
|
nipio_tests/backend_test.py | onlyrico/nip.io | 648 | 11094677 | <reponame>onlyrico/nip.io<filename>nipio_tests/backend_test.py
# Copyright 2019 Exentrique Solutions 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
#
# https://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 collections
import ipaddress
import os
import sys
import unittest
from assertpy import assert_that
from mock.mock import patch, call
from nipio.backend import DynamicBackend
def _get_test_config_filename(filename):
return os.path.join(os.path.dirname(os.path.realpath(__file__)), filename)
class DynamicBackendTest(unittest.TestCase):
def setUp(self):
os.environ.clear()
self.mock_sys_patcher = patch("nipio.backend.sys")
self.mock_sys = self.mock_sys_patcher.start()
self.mock_sys.stderr.write = sys.stderr.write
import nipio
nipio.backend._is_debug = lambda: True
def tearDown(self):
sys.stderr.flush()
self.mock_sys_patcher.stop()
def test_backend_ends_response_to_ANY_request_if_ip_is_blacklisted(self):
self._send_commands(
["Q", "subdomain.127.0.0.2.nip.io.test", "IN", "ANY", "1", "127.0.0.1"]
)
self._run_backend()
self._assert_expected_responses(["LOG", "Blacklisted: 127.0.0.2"])
def test_backend_ends_response_to_A_request_if_ip_is_blacklisted(self):
self._send_commands(
["Q", "subdomain.127.0.0.2.nip.io.test", "IN", "A", "1", "127.0.0.1"]
)
self._run_backend()
self._assert_expected_responses(["LOG", "Blacklisted: 127.0.0.2"])
def test_backend_ends_response_to_ANY_request_if_ip_is_not_whitelisted(self):
self._send_commands(
["Q", "subdomain.10.0.10.1.nip.io.test", "IN", "ANY", "1", "127.0.0.1"]
)
self._run_backend()
self._assert_expected_responses(["LOG", "Not Whitelisted: 10.0.10.1"])
def test_backend_ends_response_to_A_request_if_ip_is_not_whitelisted(self):
self._send_commands(
["Q", "subdomain.10.0.10.1.nip.io.test", "IN", "A", "1", "127.0.0.1"]
)
self._run_backend()
self._assert_expected_responses(["LOG", "Not Whitelisted: 10.0.10.1"])
def test_backend_with_empty_whitelist_responds_to_ANY_request_for_valid_ip(self):
self._send_commands(
["Q", "subdomain.10.0.10.1.nip.io.test", "IN", "ANY", "1", "127.0.0.1"]
)
self._run_backend_without_whitelist()
self._assert_expected_responses(
["DATA", "0", "1", "subdomain.10.0.10.1.nip.io.test", "IN", "A", "200", "22", "10.0.10.1"],
[
"DATA",
"0",
"1",
"subdomain.10.0.10.1.nip.io.test",
"IN",
"NS",
"200",
"22",
"ns1.nip.io.test",
],
[
"DATA",
"0",
"1",
"subdomain.10.0.10.1.nip.io.test",
"IN",
"NS",
"200",
"22",
"ns2.nip.io.test",
],
)
def test_backend_with_empty_whitelist_responds_to_A_request_for_valid_ip(self):
self._send_commands(
["Q", "subdomain.10.0.10.1.nip.io.test", "IN", "A", "1", "127.0.0.1"]
)
self._run_backend_without_whitelist()
self._assert_expected_responses(
["DATA", "0", "1", "subdomain.10.0.10.1.nip.io.test", "IN", "A", "200", "22", "10.0.10.1"],
[
"DATA",
"0",
"1",
"subdomain.10.0.10.1.nip.io.test",
"IN",
"NS",
"200",
"22",
"ns1.nip.io.test",
],
[
"DATA",
"0",
"1",
"subdomain.10.0.10.1.nip.io.test",
"IN",
"NS",
"200",
"22",
"ns2.nip.io.test",
],
)
def test_backend_responds_to_ANY_request_with_valid_ip(self):
self._send_commands(
["Q", "subdomain.127.0.0.1.nip.io.test", "IN", "ANY", "1", "127.0.0.1"]
)
self._run_backend()
self._assert_expected_responses(
["DATA", "0", "1", "subdomain.127.0.0.1.nip.io.test", "IN", "A", "200", "22", "127.0.0.1"],
[
"DATA",
"0",
"1",
"subdomain.127.0.0.1.nip.io.test",
"IN",
"NS",
"200",
"22",
"ns1.nip.io.test",
],
[
"DATA",
"0",
"1",
"subdomain.127.0.0.1.nip.io.test",
"IN",
"NS",
"200",
"22",
"ns2.nip.io.test",
],
)
def test_backend_responds_to_A_request_with_valid_ip(self):
self._send_commands(
["Q", "subdomain.127.0.0.1.nip.io.test", "IN", "A", "1", "127.0.0.1"]
)
self._run_backend()
self._assert_expected_responses(
["DATA", "0", "1", "subdomain.127.0.0.1.nip.io.test", "IN", "A", "200", "22", "127.0.0.1"],
[
"DATA",
"0",
"1",
"subdomain.127.0.0.1.nip.io.test",
"IN",
"NS",
"200",
"22",
"ns1.nip.io.test",
],
[
"DATA",
"0",
"1",
"subdomain.127.0.0.1.nip.io.test",
"IN",
"NS",
"200",
"22",
"ns2.nip.io.test",
],
)
def test_backend_responds_to_ANY_request_with_valid_ip_separated_by_dashes(self):
self._send_commands(
["Q", "subdomain-127-0-0-1.nip.io.test", "IN", "ANY", "1", "127.0.0.1"]
)
self._run_backend()
self._assert_expected_responses(
["DATA", "0", "1", "subdomain-127-0-0-1.nip.io.test", "IN", "A", "200", "22", "127.0.0.1"],
[
"DATA",
"0",
"1",
"subdomain-127-0-0-1.nip.io.test",
"IN",
"NS",
"200",
"22",
"ns1.nip.io.test",
],
[
"DATA",
"0",
"1",
"subdomain-127-0-0-1.nip.io.test",
"IN",
"NS",
"200",
"22",
"ns2.nip.io.test",
],
)
def test_backend_responds_to_A_request_with_valid_ip_separated_by_dashes(self):
self._send_commands(
["Q", "subdomain-127-0-0-1.nip.io.test", "IN", "A", "1", "127.0.0.1"]
)
self._run_backend()
self._assert_expected_responses(
["DATA", "0", "1", "subdomain-127-0-0-1.nip.io.test", "IN", "A", "200", "22", "127.0.0.1"],
[
"DATA",
"0",
"1",
"subdomain-127-0-0-1.nip.io.test",
"IN",
"NS",
"200",
"22",
"ns1.nip.io.test",
],
[
"DATA",
"0",
"1",
"subdomain-127-0-0-1.nip.io.test",
"IN",
"NS",
"200",
"22",
"ns2.nip.io.test",
],
)
def test_backend_responds_to_A_request_with_valid_ip_hexstring(self):
self._send_commands(["Q", "user-deadbeef.nip.io.test", "IN", "A", "1", "127.0.0.1"])
self._run_backend()
self._assert_expected_responses(
["DATA", "0", "1", "user-deadbeef.nip.io.test", "IN", "A", "200", "22", "172.16.58.3"],
["DATA", "0", "1", "user-deadbeef.nip.io.test", "IN", "NS", "200", "22", "ns1.nip.io.test"],
["DATA", "0", "1", "user-deadbeef.nip.io.test", "IN", "NS", "200", "22", "ns2.nip.io.test"],
)
def test_backend_responds_to_long_hexstring_with_invalid_response(self):
self._send_commands(["Q", "deadbeefcafe.nip.io.test", "IN", "A", "1", "127.0.0.1"])
self._run_backend()
self._assert_expected_responses(
["LOG", "Invalid IP address: deadbeefcafe.nip.io.test"]
)
def test_backend_responds_to_short_hexstring_with_invalid_response(self):
self._send_commands(["Q", "user-dec0ded.nip.io.test", "IN", "A", "1", "127.0.0.1"])
self._run_backend()
self._assert_expected_responses(
["LOG", "Invalid IP address: user-dec0ded.nip.io.test"]
)
def test_backend_responds_to_invalid_hexstring_with_invalid_response(self):
self._send_commands(["Q", "deadcode.nip.io.test", "IN", "A", "1", "127.0.0.1"])
self._run_backend()
self._assert_expected_responses(
["LOG", "Invalid IP address: deadcode.nip.io.test"]
)
def test_backend_responds_to_invalid_ip_in_ANY_request_with_invalid_response(self):
self._send_commands(
["Q", "subdomain.127.0.1.nip.io.test", "IN", "ANY", "1", "127.0.0.1"]
)
self._run_backend()
self._assert_expected_responses(
["LOG", "Invalid IP address: subdomain.127.0.1.nip.io.test"]
)
def test_backend_responds_to_invalid_ip_in_A_request_with_invalid_response(self):
self._send_commands(
["Q", "subdomain.127.0.1.nip.io.test", "IN", "A", "1", "127.0.0.1"]
)
self._run_backend()
self._assert_expected_responses(
["LOG", "Invalid IP address: subdomain.127.0.1.nip.io.test"]
)
def test_backend_responds_to_short_ip_in_ANY_request_with_invalid_response(self):
self._send_commands(["Q", "127.0.1.nip.io.test", "IN", "ANY", "1", "127.0.0.1"])
self._run_backend()
self._assert_expected_responses(
["LOG", "Invalid IP address: 127.0.1.nip.io.test"]
)
def test_backend_responds_to_short_ip_in_A_request_with_invalid_response(self):
self._send_commands(["Q", "127.0.1.nip.io.test", "IN", "A", "1", "127.0.0.1"])
self._run_backend()
self._assert_expected_responses(
["LOG", "Invalid IP address: 127.0.1.nip.io.test"]
)
def test_backend_responds_to_large_ip_in_ANY_request_with_invalid_response(self):
self._send_commands(
["Q", "subdomain.127.0.300.1.nip.io.test", "IN", "ANY", "1", "127.0.0.1"]
)
self._run_backend()
self._assert_expected_responses(
["LOG", "Invalid IP address: subdomain.127.0.300.1.nip.io.test"]
)
def test_backend_responds_to_large_ip_in_A_request_with_invalid_response(self):
self._send_commands(
["Q", "subdomain.127.0.300.1.nip.io.test", "IN", "A", "1", "127.0.0.1"]
)
self._run_backend()
self._assert_expected_responses(
["LOG", "Invalid IP address: subdomain.127.0.300.1.nip.io.test"]
)
def test_backend_responds_to_string_in_ip_in_ANY_request_with_invalid_response(self):
self._send_commands(
["Q", "subdomain.127.0.STRING.1.nip.io.test", "IN", "ANY", "1", "127.0.0.1"]
)
self._run_backend()
self._assert_expected_responses(
["LOG", "Invalid IP address: subdomain.127.0.string.1.nip.io.test"]
)
def test_backend_responds_to_string_in_ip_in_A_request_with_invalid_response(self):
self._send_commands(
["Q", "subdomain.127.0.STRING.1.nip.io.test", "IN", "A", "1", "127.0.0.1"]
)
self._run_backend()
self._assert_expected_responses(
["LOG", "Invalid IP address: subdomain.127.0.string.1.nip.io.test"]
)
def test_backend_responds_to_no_ip_in_ANY_request_with_invalid_response(self):
self._send_commands(
["Q", "subdomain.127.0.1.nip.io.test", "IN", "ANY", "1", "127.0.0.1"]
)
self._run_backend()
self._assert_expected_responses(
["LOG", "Invalid IP address: subdomain.127.0.1.nip.io.test"]
)
def test_backend_responds_to_no_ip_in_A_request_with_invalid_response(self):
self._send_commands(
["Q", "subdomain.127.0.1.nip.io.test", "IN", "A", "1", "127.0.0.1"]
)
self._run_backend()
self._assert_expected_responses(
["LOG", "Invalid IP address: subdomain.127.0.1.nip.io.test"]
)
def test_backend_responds_to_self_domain_to_A_request(self):
self._send_commands(["Q", "nip.io.test", "IN", "A", "1", "127.0.0.1"])
self._run_backend()
self._assert_expected_responses(
["DATA", "0", "1", "nip.io.test", "IN", "A", "200", "22", "127.0.0.33"],
["DATA", "0", "1", "nip.io.test", "IN", "NS", "200", "22", "ns1.nip.io.test"],
["DATA", "0", "1", "nip.io.test", "IN", "NS", "200", "22", "ns2.nip.io.test"],
)
def test_backend_responds_to_self_domain_to_ANY_request(self):
self._send_commands(["Q", "nip.io.test", "IN", "ANY", "1", "127.0.0.1"])
self._run_backend()
self._assert_expected_responses(
["DATA", "0", "1", "nip.io.test", "IN", "A", "200", "22", "127.0.0.33"],
["DATA", "0", "1", "nip.io.test", "IN", "NS", "200", "22", "ns1.nip.io.test"],
["DATA", "0", "1", "nip.io.test", "IN", "NS", "200", "22", "ns2.nip.io.test"],
)
def test_backend_responds_to_name_servers_A_request_with_valid_ip(self):
self._send_commands(["Q", "ns1.nip.io.test", "IN", "A", "1", "127.0.0.1"])
self._run_backend()
self._assert_expected_responses(
["DATA", "0", "1", "ns1.nip.io.test", "IN", "A", "200", "22", "127.0.0.34"],
)
def test_backend_responds_to_name_servers_ANY_request_with_valid_ip(self):
self._send_commands(["Q", "ns2.nip.io.test", "IN", "ANY", "1", "127.0.0.1"])
self._run_backend()
self._assert_expected_responses(
["DATA", "0", "1", "ns2.nip.io.test", "IN", "A", "200", "22", "127.0.0.35"],
)
def test_backend_responds_to_SOA_request_for_self(self):
self._send_commands(["Q", "nip.io.test", "IN", "SOA", "1", "127.0.0.1"])
self._run_backend()
self._assert_expected_responses(
["DATA", "0", "1", "nip.io.test", "IN", "SOA", "200", "22", "MY_SOA"]
)
def test_backend_responds_to_SOA_request_for_valid_ip(self):
self._send_commands(
["Q", "subdomain.1192.168.3.11.nip.io.test", "IN", "SOA", "1", "127.0.0.1"]
)
self._run_backend()
self._assert_expected_responses(
["DATA", "0", "1", "subdomain.127.0.0.1.nip.io.test", "IN", "SOA", "200", "22", "MY_SOA"]
)
def test_backend_responds_to_SOA_request_for_invalid_ip(self):
self._send_commands(
["Q", "subdomain.127.0.1.nip.io.test", "IN", "SOA", "1", "127.0.0.1"]
)
self._run_backend()
self._assert_expected_responses(
["DATA", "0", "1", "subdomain.127.0.1.nip.io.test", "IN", "SOA", "200", "22", "MY_SOA"]
)
def test_backend_responds_to_SOA_request_for_no_ip(self):
self._send_commands(["Q", "subdomain.nip.io.test", "IN", "SOA", "1", "127.0.0.1"])
self._run_backend()
self._assert_expected_responses(
["DATA", "0", "1", "subdomain.nip.io.test", "IN", "SOA", "200", "22", "MY_SOA"]
)
def test_backend_responds_to_SOA_request_for_nameserver(self):
self._send_commands(["Q", "ns1.nip.io.test", "IN", "SOA", "1", "127.0.0.1"])
self._run_backend()
self._assert_expected_responses(
["DATA", "0", "1", "ns1.nip.io.test", "IN", "SOA", "200", "22", "MY_SOA"]
)
def test_backend_responds_to_A_request_for_unknown_domain_with_invalid_response(
self,
):
self._send_commands(["Q", "unknown.domain", "IN", "A", "1", "127.0.0.1"])
self._run_backend()
self._assert_expected_responses(
["LOG", "Unknown type: A, domain: unknown.domain"]
)
def test_backend_responds_to_invalid_request_with_invalid_response(self):
self._send_commands(["Q", "nip.io.test", "IN", "INVALID", "1", "127.0.0.1"])
self._run_backend()
self._assert_expected_responses(
["LOG", "Unknown type: INVALID, domain: nip.io.test"]
)
def test_backend_responds_to_invalid_command_with_fail(self):
self._send_commands(["INVALID", "COMMAND"])
self._run_backend()
calls = [
call("OK"),
call("\t"),
call("nip.io backend - We are good"),
call("\n"),
call("FAIL"),
call("\n"),
]
self.mock_sys.stdout.write.assert_has_calls(calls)
assert_that(self.mock_sys.stdout.write.call_count).is_equal_to(len(calls))
assert_that(self.mock_sys.stdout.flush.call_count).is_equal_to(2)
def test_configure_with_full_config(self):
backend = self._configure_backend()
assert_that(backend.id).is_equal_to("55")
assert_that(backend.ip_address).is_equal_to("127.0.0.40")
assert_that(backend.domain).is_equal_to("nip.io.test")
assert_that(backend.ttl).is_equal_to("1000")
assert_that(backend.name_servers).is_equal_to(
{"ns1.nip.io.test": "127.0.0.41", "ns2.nip.io.test": "127.0.0.42"}
)
assert_that(backend.whitelisted_ranges).is_equal_to([
ipaddress.IPv4Network('127.0.0.0/8'),
ipaddress.IPv4Network('192.168.0.0/16'),
])
assert_that(backend.blacklisted_ips).is_equal_to(["10.0.0.100"])
assert_that(backend.soa).is_equal_to("ns1.nip.io.test [email protected] 55")
def test_configure_with_environment_variables_set(self):
os.environ["NIPIO_DOMAIN"] = "example.com"
os.environ["NIPIO_TTL"] = "1000"
os.environ["NIPIO_NONWILD_DEFAULT_IP"] = "127.0.0.30"
os.environ["NIPIO_SOA_ID"] = "99"
os.environ["NIPIO_SOA_HOSTMASTER"] = "<EMAIL>"
os.environ["NIPIO_SOA_NS"] = "ns1.example.com"
os.environ[
"NIPIO_NAMESERVERS"
] = "ns1.example.com=127.0.0.31 ns2.example.com=127.0.0.32"
os.environ["NIPIO_WHITELIST"] = "whitelist1=10.0.0.0/8"
os.environ[
"NIPIO_BLACKLIST"
] = "black_listed=10.0.0.111 black_listed2=10.0.0.112"
backend = self._configure_backend()
assert_that(backend.id).is_equal_to("99")
assert_that(backend.ip_address).is_equal_to("127.0.0.30")
assert_that(backend.domain).is_equal_to("example.com")
assert_that(backend.ttl).is_equal_to("1000")
assert_that(backend.name_servers).is_equal_to(
{"ns1.example.com": "127.0.0.31", "ns2.example.com": "127.0.0.32"}
)
assert_that(backend.whitelisted_ranges).is_equal_to([
ipaddress.IPv4Network('10.0.0.0/8'),
])
assert_that(backend.blacklisted_ips).is_equal_to(["10.0.0.111", "10.0.0.112"])
assert_that(backend.soa).is_equal_to(
"ns1.example.com host<EMAIL> 99"
)
def test_configure_with_env_lists_config(self):
os.environ["NIPIO_WHITELIST"] = "whitelist1=10.0.0.0/8"
os.environ[
"NIPIO_BLACKLIST"
] = "black_listed=10.0.0.111 black_listed2=10.0.0.112"
backend = self._configure_backend(filename="backend_test_no_lists.conf")
assert_that(backend.whitelisted_ranges).is_equal_to([
ipaddress.IPv4Network('10.0.0.0/8'),
])
assert_that(backend.blacklisted_ips).is_equal_to(["10.0.0.111", "10.0.0.112"])
def test_configure_with_config_missing_lists(self):
backend = self._configure_backend(filename="backend_test_no_lists.conf")
assert_that(backend.whitelisted_ranges).is_empty()
assert_that(backend.blacklisted_ips).is_empty()
def _run_backend(self):
backend = self._create_backend()
backend.run()
def _run_backend_without_whitelist(self):
backend = self._create_backend()
backend.whitelisted_ranges = []
backend.run()
def _send_commands(self, *commands):
commands_to_send = ["HELO\t5\n"]
for command in commands:
commands_to_send.append("\t".join(command) + "\n")
commands_to_send.append("END\n")
self.mock_sys.stdin.readline.side_effect = commands_to_send
def _assert_expected_responses(self, *responses):
calls = [
call("OK"),
call("\t"),
call("nip.io backend - We are good"),
call("\n"),
]
for response in responses:
tab_separated = ["\t"] * (len(response) * 2 - 1)
tab_separated[0::2] = response
tab_separated.append("\n")
calls.extend([call(response_item) for response_item in tab_separated])
calls.extend(
[call("END"), call("\n"), ]
)
self.mock_sys.stdout.write.assert_has_calls(calls)
assert_that(self.mock_sys.stdout.write.call_count).is_equal_to(len(calls))
assert_that(self.mock_sys.stdout.flush.call_count).is_equal_to(
len(responses) + 2
)
@staticmethod
def _create_backend():
backend = DynamicBackend()
backend.id = "22"
backend.soa = "MY_SOA"
backend.ip_address = "127.0.0.33"
backend.ttl = "200"
backend.name_servers = collections.OrderedDict(
[("ns1.nip.io.test", "127.0.0.34"), ("ns2.nip.io.test", "127.0.0.35"), ]
)
backend.domain = "nip.io.test"
backend.whitelisted_ranges = [
# This allows us to test that the blacklist works even when the IPs are
# part of whitelisted ranges
ipaddress.IPv4Network('127.0.0.0/8'),
# This range covers deadbeef
ipaddress.IPv4Network('172.16.58.3/32'),
]
backend.blacklisted_ips = ["127.0.0.2"]
return backend
@staticmethod
def _configure_backend(filename="backend_test.conf"):
backend = DynamicBackend()
backend.configure(_get_test_config_filename(filename))
return backend
|
turla/carbon_tool.py | macdaliot/malware-ioc | 1,141 | 11094691 | #!/usr/bin/env python2
# Copyright (c) 2017, ESET
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from Crypto.Cipher import CAST
import sys
import argparse
def main():
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("-e", "--encrypt", help="encrypt carbon file", required=False)
parser.add_argument("-d", "--decrypt", help="decrypt carbon file", required=False)
try:
args = parser.parse_args()
except IOError as e:
parser.error(e)
return 0
if len(sys.argv) != 3:
parser.print_help()
return 0
key = <KEY>"
iv = "\x12\x34\x56\x78\x9A\xBC\xDE\xF0"
cipher = CAST.new(key, CAST.MODE_OFB, iv)
if args.encrypt:
plaintext = open(args.encrypt, "rb").read()
while len(plaintext) % 8 != 0:
plaintext += "\x00"
data = cipher.encrypt(plaintext)
open(args.encrypt + "_encrypted", "wb").write(data)
else:
ciphertext = open(args.decrypt, "rb").read()
while len(ciphertext) % 8 != 0:
ciphertext += "\x00"
data = cipher.decrypt(ciphertext)
open(args.decrypt + "_decrypted", "wb").write(data)
if __name__ == "__main__":
main()
|
tests/micropython/heapalloc.py | braytac/micropython | 303 | 11094708 | # check that we can do certain things without allocating heap memory
import gc
def f1(a):
print(a)
def f2(a, b=2):
print(a, b)
def f3(a, b, c, d):
x1 = x2 = a
x3 = x4 = b
x5 = x6 = c
x7 = x8 = d
print(x1, x3, x5, x7, x2 + x4 + x6 + x8)
global_var = 1
def test():
global global_var
global_var = 2 # set an existing global variable
for i in range(2): # for loop
f1(i) # function call
f1(i * 2 + 1) # binary operation with small ints
f1(a=i) # keyword arguments
f2(i) # default arg (second one)
f2(i, i) # 2 args
f3(1, 2, 3, 4) # function with lots of local state
# call h with heap allocation disabled and all memory used up
gc.disable()
try:
while True:
'a'.lower # allocates 1 cell for boundmeth
except MemoryError:
pass
test()
gc.enable()
|
app/modules/teams/parameters.py | IsmaelJS/test-github-actions | 1,420 | 11094712 | <reponame>IsmaelJS/test-github-actions
# encoding: utf-8
"""
Input arguments (Parameters) for Team resources RESTful API
-----------------------------------------------------------
"""
from flask_marshmallow import base_fields
from flask_restplus_patched import PostFormParameters, PatchJSONParameters
from . import schemas
from .models import Team
class CreateTeamParameters(PostFormParameters, schemas.BaseTeamSchema):
class Meta(schemas.BaseTeamSchema.Meta):
pass
class PatchTeamDetailsParameters(PatchJSONParameters):
# pylint: disable=abstract-method,missing-docstring
OPERATION_CHOICES = (
PatchJSONParameters.OP_REPLACE,
)
PATH_CHOICES = tuple(
'/%s' % field for field in (
Team.title.key,
)
)
class AddTeamMemberParameters(PostFormParameters):
user_id = base_fields.Integer(required=True)
is_leader = base_fields.Boolean(required=False)
|
theme/management/commands/report_quota_inconsistency.py | hydroshare/hydroshare | 178 | 11094722 |
import csv
import math
from django.core.management.base import BaseCommand
from django.core.exceptions import ValidationError
from hs_core.hydroshare import convert_file_size_to_unit
from theme.models import UserQuota
from hs_core.hydroshare.resource import get_quota_usage_from_irods
class Command(BaseCommand):
help = "Output potential quota inconsistencies between iRODS and Django for all users in HydroShare"
def add_arguments(self, parser):
parser.add_argument('output_file_name_with_path', help='output file name with path')
def handle(self, *args, **options):
quota_report_list = []
for uq in UserQuota.objects.filter(
user__is_active=True).filter(user__is_superuser=False):
used_value = 0.0
try:
used_value = get_quota_usage_from_irods(uq.user.username)
except ValidationError:
pass
used_value = convert_file_size_to_unit(used_value, "gb")
if not math.isclose(used_value, uq.used_value, abs_tol=0.1):
# report inconsistency
report_dict = {
'user': uq.user.username,
'django': uq.used_value,
'irods': used_value}
quota_report_list.append(report_dict)
print('quota incosistency: {} reported in django vs {} reported in iRODS for user {}'.format(
uq.used_value, used_value, uq.user.username), flush=True)
if quota_report_list:
with open(options['output_file_name_with_path'], 'w') as csvfile:
w = csv.writer(csvfile)
fields = [
'User'
'Quota reported in Django',
'Quota reported in iRODS'
]
w.writerow(fields)
for q in quota_report_list:
values = [
q['user'],
q['django'],
q['irods']
]
w.writerow([str(v) for v in values])
|
pysmi/borrower/pyfile.py | itsmehara/pysmi | 121 | 11094738 | #
# This file is part of pysmi software.
#
# Copyright (c) 2015-2020, <NAME> <<EMAIL>>
# License: http://snmplabs.com/pysmi/license.html
#
try:
import importlib
try:
SOURCE_SUFFIXES = importlib.machinery.SOURCE_SUFFIXES
except Exception:
raise ImportError()
except ImportError:
import imp
SOURCE_SUFFIXES = [s[0] for s in imp.get_suffixes()
if s[2] == imp.PY_SOURCE]
from pysmi.borrower.base import AbstractBorrower
class PyFileBorrower(AbstractBorrower):
"""Create PySNMP MIB file borrowing object"""
exts = SOURCE_SUFFIXES
|
execution_trace/tests/functions/f_try_ok.py | yoyonel/python-execution-trace | 197 | 11094741 | <reponame>yoyonel/python-execution-trace
from execution_trace.record import record
@record(10) # 1
def f(): # 2
"""Fn with a try that does not raise.""" # 3
x = 3 # 4
try: # 5
x = x + 1 # 6
except: # 7
y = 2 # 8
args = ()
expected_trace = [{u'data': [{u'lineno': 3, u'state': {}},
{u'lineno': 4, u'state': {u'x': u'3'}},
{u'lineno': 5, u'state': {u'x': u'3'}},
{u'lineno': 6, u'state': {u'x': u'4'}}]}]
|
feapder/templates/project_template/main.py | RuixiangS/feapder | 876 | 11094764 | <filename>feapder/templates/project_template/main.py<gh_stars>100-1000
# -*- coding: utf-8 -*-
"""
Created on {DATE}
---------
@summary: 爬虫入口
---------
@author: {USER}
"""
from feapder import ArgumentParser
from spiders import *
def crawl_xxx():
"""
AirSpider爬虫
"""
spider = xxx.XXXSpider()
spider.start()
def crawl_xxx():
"""
Spider爬虫
"""
spider = xxx.XXXSpider(redis_key="xxx:xxx")
spider.start()
def crawl_xxx(args):
"""
BatchSpider爬虫
"""
spider = xxx_spider.XXXSpider(
task_table="", # mysql中的任务表
batch_record_table="", # mysql中的批次记录表
batch_name="xxx(周全)", # 批次名字
batch_interval=7, # 批次时间 天为单位 若为小时 可写 1 / 24
task_keys=["<KEY>"], # 需要获取任务表里的字段名,可添加多个
redis_key="xxx:xxxx", # redis中存放request等信息的根key
task_state="state", # mysql中任务状态字段
)
if args == 1:
spider.start_monitor_task()
elif args == 2:
spider.start()
elif args == 3:
spider.init_task()
if __name__ == "__main__":
parser = ArgumentParser(description="xxx爬虫")
parser.add_argument(
"--crawl_xxx", action="store_true", help="xxx爬虫", function=crawl_xxx
)
parser.add_argument(
"--crawl_xxx", action="store_true", help="xxx爬虫", function=crawl_xxx
)
parser.add_argument(
"--crawl_xxx",
type=int,
nargs=1,
help="xxx爬虫",
choices=[1, 2, 3],
function=crawl_xxx,
)
parser.start()
# main.py作为爬虫启动的统一入口,提供命令行的方式启动多个爬虫,若只有一个爬虫,可不编写main.py
# 将上面的xxx修改为自己实际的爬虫名
# 查看运行命令 python main.py --help
# AirSpider与Spider爬虫运行方式 python main.py --crawl_xxx
# BatchSpider运行方式
# 1. 下发任务:python main.py --crawl_xxx 1
# 2. 采集:python main.py --crawl_xxx 2
# 3. 重置任务:python main.py --crawl_xxx 3
|
tests/functional/kvpy/sfx_test_tomb.py | efeslab/hse | 558 | 11094769 | <reponame>efeslab/hse<filename>tests/functional/kvpy/sfx_test_tomb.py
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2021 Micron Technology, Inc. All rights reserved.
from contextlib import ExitStack
from hse2 import hse
from utility import lifecycle, cli
hse.init(cli.CONFIG)
try:
with ExitStack() as stack:
kvdb_ctx = lifecycle.KvdbContext().rparams("durability.enabled=false")
kvdb = stack.enter_context(kvdb_ctx)
kvs_ctx = lifecycle.KvsContext(kvdb, "sfx_test_tomb").cparams(
"prefix.length=1", "suffix.length=2"
)
kvs = stack.enter_context(kvs_ctx)
kvs.put(b"AbcXX", b"1")
kvs.put(b"AbdXX", b"1")
kvs.put(b"AbdXY", b"2")
kvdb.sync(flags=hse.KvdbSyncFlag.ASYNC)
cnt, *_ = kvs.prefix_probe(b"Abd")
assert cnt == hse.KvsPfxProbeCnt.MUL
kvs.delete(b"AbdXY")
cnt, k, _, v, _ = kvs.prefix_probe(b"Abd")
assert cnt == hse.KvsPfxProbeCnt.ONE
assert (k, v) == (b"AbdXX", b"1")
kvdb.sync()
cnt, k, _, v, _ = kvs.prefix_probe(b"Abd")
assert cnt == hse.KvsPfxProbeCnt.ONE
assert (k, v) == (b"AbdXX", b"1")
# Multiple tombs
cnt, k, _, v, _ = kvs.prefix_probe(b"Abc")
assert cnt == hse.KvsPfxProbeCnt.ONE
assert (k, v) == (b"AbcXX", b"1")
kvs.prefix_delete(b"A")
kvs.put(b"AbcX1", b"1")
kvs.put(b"AbcX2", b"1")
kvs.put(b"AbcX3", b"1")
kvs.put(b"AbcX4", b"1")
kvs.put(b"AbcX5", b"1")
kvs.put(b"AbcX6", b"1")
kvdb.sync()
kvs.put(b"AbcX7", b"1")
kvs.put(b"AbcX8", b"1")
kvs.put(b"AbcX9", b"1")
cnt, *_ = kvs.prefix_probe(b"Abc")
assert cnt == hse.KvsPfxProbeCnt.MUL
kvs.delete(b"AbcX1")
kvs.delete(b"AbcX2")
kvs.delete(b"AbcX3")
kvs.delete(b"AbcX7")
kvs.delete(b"AbcX8")
cnt, k, _, v, _ = kvs.prefix_probe(b"Abc")
assert cnt == hse.KvsPfxProbeCnt.MUL
assert (k, v) == (b"AbcX9", b"1")
"""
[HSE_REVISIT] - why is this commented out? @gaurav
txn = kvdb.transaction()
txn.begin()
kvs.delete(b"AbcX9", txn=txn)
cnt, k, _, v, _ = kvs.prefix_probe(b"Abc", txn=txn)
assert cnt == hse.KvsPfxProbeCnt.MUL
assert (k, v) == (b"AbcX4", b"1")
txn.commit()
"""
kvs.delete(b"AbcX9")
cnt, k, _, v, _ = kvs.prefix_probe(b"Abc")
assert cnt == hse.KvsPfxProbeCnt.MUL
assert (k, v) == (b"AbcX4", b"1")
kvdb.sync()
cnt, k, _, v, _ = kvs.prefix_probe(b"Abc")
assert cnt == hse.KvsPfxProbeCnt.MUL
assert (k, v) == (b"AbcX4", b"1")
finally:
hse.fini()
|
test/files/exprs_optics_out1.py | symbiont-sam-halliday/hpython | 160 | 11094786 | for a_, b_ in c_:
a_ += 1
b_ += 2
|
phobos/io/libraries/__init__.py | hawkina/phobos | 323 | 11094796 | #!/usr/bin/python3
# coding=utf-8
# -------------------------------------------------------------------------------
# This file is part of Phobos, a Blender Add-On to edit robot models.
# Copyright (C) 2020 University of Bremen & DFKI GmbH Robotics Innovation Center
#
# You should have received a copy of the 3-Clause BSD License in the LICENSE file.
# If not, see <https://opensource.org/licenses/BSD-3-Clause>.
# -------------------------------------------------------------------------------
"""
Registers the :mod:`models` and :mod:`mechanisms` submodules to Blender.
"""
from . import models, mechanisms
def register():
"""TODO Missing documentation"""
models.register()
mechanisms.register()
def unregister():
"""TODO Missing documentation"""
models.unregister()
mechanisms.unregister()
|
small_text/utils/datetime.py | chschroeder/small-text | 218 | 11094830 | def format_timedelta(td):
if td.days < 0:
raise ValueError('timedelta must be positive')
hours, sec = divmod(td.seconds, 3600)
mins, sec = divmod(sec, 60)
return f'{hours:02}:{mins:02}:{sec:02}'
|
tests/apps/good_flow_app/migrations/0024_add_index_with_condition.py | 15five/django-pg-zero-downtime-migrations | 376 | 11094849 | # Generated by Django 3.1 on 2019-09-22 20:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('good_flow_app', '0023_drop_index'),
]
operations = [
migrations.AddIndex(
model_name='testtable',
index=models.Index(
condition=models.Q(test_field_int__isnull=False),
fields=['test_field_int'],
name='test_index',
),
),
]
|
pywick/transforms/image_transforms.py | achaiah/pywick | 408 | 11094904 | <filename>pywick/transforms/image_transforms.py
"""
Transforms very specific to images such as
color, lighting, contrast, brightness, etc transforms
NOTE: Most of these transforms assume your image intensity
is between 0 and 1, and are torch tensors (NOT numpy or PIL)
"""
import random
import torch as th
from torchvision.transforms.functional import to_tensor
import numpy as np
from ..utils import th_random_choice
class DeNormalize:
"""
Denormalizes a tensor using provided mean, std
"""
def __init__(self, mean, std):
self.mean = mean
self.std = std
def __call__(self, tensor):
for t, m, s in zip(tensor, self.mean, self.std):
t.mul_(s).add_(m)
return tensor
class MaskToSqueezedTensor:
"""
Removes empty dimensions from the mask and converts to a torch.float32 tensor.
Typically used with B/W masks to remove the "channel" dimension
:return tensor
"""
def __init__(self):
self.to_tensor = MaskToFloatTensor()
def __call__(self, img):
# Note, we cannot call the normal torchvision to_tensor method here because it automatically divides by 255 which is NOT what we want.
return self.to_tensor(img).squeeze()
class MaskPixelsToMap:
"""
Replaces the pixel values in range [0-255] with class values from supplied value_map.
:return : numpy.ndarray with dtype=np.uint8
"""
def __init__(self, value_map: dict = None):
"""
:param value_map: Value map to encode. Typically classes are a set of continuous integers starting at 0 (e.g. {55:0, 100:1, 255:2})
"""
self.value_map = value_map
def __call__(self, mask):
"""
:param mask: PIL or OpenCV mask with pixel values in [0-255] range
:return:
"""
mask = np.array(mask) # convert to np
for k, v in self.value_map.items():
mask[mask == k] = v # replace pixels with class values
return mask.astype(np.uint8) # make sure it's in UINT8 format
class MaskToTensor:
"""
Converts a PIL, numpy or CV image to a torch.long representation
"""
def __call__(self, img):
return th.from_numpy(np.array(img, dtype=np.int32)).long()
class MaskToFloatTensor:
"""
Converts a PIL, numpy or CV image to a torch.float32 representation
"""
def __init__(self, divisor: float = None):
"""
:param divisor: Optional divisor for the conversion. Can be specified to convert supplied images from [0-255] range to [0.0-1.0]
"""
self.divisor = divisor
def __call__(self, img):
if self.divisor is None:
return th.from_numpy(np.array(img, dtype=np.float32))
else:
return th.from_numpy(np.array(img, dtype=np.float32) / self.divisor)
def _blend(img1, img2, alpha):
"""
Weighted sum of two images
Arguments
---------
img1 : torch tensor
img2 : torch tensor
alpha : float between 0 and 1
how much weight to put on img1 and 1-alpha weight
to put on img2
"""
return img1.mul(alpha).add(1 - alpha, img2)
class Grayscale:
def __init__(self, keep_channels=False):
"""
Convert RGB image to grayscale
Arguments
---------
keep_channels : boolean
If true, will keep all 3 channels and they will be the same
If false, will just return 1 grayscale channel
"""
self.keep_channels = keep_channels
if keep_channels:
self.channels = 3
else:
self.channels = 1
def __call__(self, *inputs):
outputs = []
idx = None
for idx, _input in enumerate(inputs):
_input_dst = _input[0]*0.299 + _input[1]*0.587 + _input[2]*0.114
_input_gs = _input_dst.repeat(self.channels,1,1)
outputs.append(_input_gs)
return outputs if idx >= 1 else outputs[0]
class RandomGrayscale:
def __init__(self, p=0.5):
"""
Randomly convert RGB image(s) to Grayscale w/ some probability,
NOTE: Always retains the 3 channels if image is grayscaled
p : a float
probability that image will be grayscaled
"""
self.p = p
def __call__(self, *inputs):
pval = random.random()
if pval < self.p:
outputs = Grayscale(keep_channels=True)(*inputs)
else:
outputs = inputs
return outputs
# ----------------------------------------------------
# ----------------------------------------------------
class Gamma:
def __init__(self, value):
"""
Performs Gamma Correction on the input image. Also known as
Power Law Transform. This function transforms the input image
pixelwise according
to the equation Out = In**gamma after scaling each
pixel to the range 0 to 1.
Arguments
---------
value : float
<1 : image will tend to be lighter
=1 : image will stay the same
>1 : image will tend to be darker
"""
self.value = value
def __call__(self, *inputs):
outputs = []
idx = None
for idx, _input in enumerate(inputs):
_input = th.pow(_input, self.value)
outputs.append(_input)
return outputs if idx >= 1 else outputs[0]
class RandomGamma:
def __init__(self, min_val, max_val):
"""
Performs Gamma Correction on the input image with some
randomly selected gamma value between min_val and max_val.
Also known as Power Law Transform. This function transforms
the input image pixelwise according to the equation
Out = In**gamma after scaling each pixel to the range 0 to 1.
Arguments
---------
min_val : float
min range
max_val : float
max range
NOTE:
for values:
<1 : image will tend to be lighter
=1 : image will stay the same
>1 : image will tend to be darker
"""
self.values = (min_val, max_val)
def __call__(self, *inputs):
value = random.uniform(self.values[0], self.values[1])
outputs = Gamma(value)(*inputs)
return outputs
class RandomChoiceGamma:
def __init__(self, values, p=None):
"""
Performs Gamma Correction on the input image with some
gamma value selected in the list of given values.
Also known as Power Law Transform. This function transforms
the input image pixelwise according to the equation
Out = In**gamma after scaling each pixel to the range 0 to 1.
Arguments
---------
values : list of floats
gamma values to sampled from
p : list of floats - same length as `values`
if None, values will be sampled uniformly.
Must sum to 1.
NOTE:
for values:
<1 : image will tend to be lighter
=1 : image will stay the same
>1 : image will tend to be darker
"""
self.values = values
self.p = p
def __call__(self, *inputs):
value = th_random_choice(self.values, p=self.p)
outputs = Gamma(value)(*inputs)
return outputs
# ----------------------------------------------------
# ----------------------------------------------------
class Brightness:
def __init__(self, value):
"""
Alter the Brightness of an image
Arguments
---------
value : brightness factor
=-1 = completely black
<0 = darker
0 = no change
>0 = brighter
=1 = completely white
"""
self.value = max(min(value,1.0),-1.0)
def __call__(self, *inputs):
outputs = []
idx = None
for idx, _input in enumerate(inputs):
_input = th.clamp(_input.float().add(self.value).type(_input.type()), 0, 1)
outputs.append(_input)
return outputs if idx >= 1 else outputs[0]
class RandomBrightness:
def __init__(self, min_val, max_val):
"""
Alter the Brightness of an image with a value randomly selected
between `min_val` and `max_val`
Arguments
---------
min_val : float
min range
max_val : float
max range
"""
self.values = (min_val, max_val)
def __call__(self, *inputs):
value = random.uniform(self.values[0], self.values[1])
outputs = Brightness(value)(*inputs)
return outputs
class RandomChoiceBrightness:
def __init__(self, values, p=None):
"""
Alter the Brightness of an image with a value randomly selected
from the list of given values with given probabilities
Arguments
---------
values : list of floats
brightness values to sampled from
p : list of floats - same length as `values`
if None, values will be sampled uniformly.
Must sum to 1.
"""
self.values = values
self.p = p
def __call__(self, *inputs):
value = th_random_choice(self.values, p=self.p)
outputs = Brightness(value)(*inputs)
return outputs
# ----------------------------------------------------
# ----------------------------------------------------
class Saturation:
def __init__(self, value):
"""
Alter the Saturation of image
Arguments
---------
value : float
=-1 : gray
<0 : colors are more muted
=0 : image stays the same
>0 : colors are more pure
=1 : most saturated
"""
self.value = max(min(value,1.0),-1.0)
def __call__(self, *inputs):
outputs = []
idx = None
for idx, _input in enumerate(inputs):
_in_gs = Grayscale(keep_channels=True)(_input)
alpha = 1.0 + self.value
_in = th.clamp(_blend(_input, _in_gs, alpha), 0, 1)
outputs.append(_in)
return outputs if idx >= 1 else outputs[0]
class RandomSaturation:
def __init__(self, min_val, max_val):
"""
Alter the Saturation of an image with a value randomly selected
between `min_val` and `max_val`
Arguments
---------
min_val : float
min range
max_val : float
max range
"""
self.values = (min_val, max_val)
def __call__(self, *inputs):
value = random.uniform(self.values[0], self.values[1])
outputs = Saturation(value)(*inputs)
return outputs
class RandomChoiceSaturation:
def __init__(self, values, p=None):
"""
Alter the Saturation of an image with a value randomly selected
from the list of given values with given probabilities
Arguments
---------
values : list of floats
saturation values to sampled from
p : list of floats - same length as `values`
if None, values will be sampled uniformly.
Must sum to 1.
"""
self.values = values
self.p = p
def __call__(self, *inputs):
value = th_random_choice(self.values, p=self.p)
outputs = Saturation(value)(*inputs)
return outputs
# ----------------------------------------------------
# ----------------------------------------------------
class Contrast:
"""
"""
def __init__(self, value):
"""
Adjust Contrast of image.
Contrast is adjusted independently for each channel of each image.
For each channel, this Op computes the mean of the image pixels
in the channel and then adjusts each component x of each pixel to
(x - mean) * contrast_factor + mean.
Arguments
---------
value : float
smaller value: less contrast
ZERO: channel means
larger positive value: greater contrast
larger negative value: greater inverse contrast
"""
self.value = value
def __call__(self, *inputs):
outputs = []
idx = None
for idx, _input in enumerate(inputs):
channel_means = _input.mean(1, keepdim=True).mean(2, keepdim=True)
channel_means = channel_means.expand_as(_input)
_input = th.clamp((_input - channel_means) * self.value + channel_means,0,1)
outputs.append(_input)
return outputs if idx >= 1 else outputs[0]
class RandomContrast:
def __init__(self, min_val, max_val):
"""
Alter the Contrast of an image with a value randomly selected
between `min_val` and `max_val`
Arguments
---------
min_val : float
min range
max_val : float
max range
"""
self.values = (min_val, max_val)
def __call__(self, *inputs):
value = random.uniform(self.values[0], self.values[1])
outputs = Contrast(value)(*inputs)
return outputs
class RandomChoiceContrast:
def __init__(self, values, p=None):
"""
Alter the Contrast of an image with a value randomly selected
from the list of given values with given probabilities
Arguments
---------
values : list of floats
contrast values to sampled from
p : list of floats - same length as `values`
if None, values will be sampled uniformly.
Must sum to 1.
"""
self.values = values
self.p = p
def __call__(self, *inputs):
value = th_random_choice(self.values, p=self.p)
outputs = Contrast(value)(*inputs)
return outputs
# ----------------------------------------------------
# ----------------------------------------------------
def rgb_to_hsv(x):
"""
Convert from RGB to HSV
"""
hsv = th.zeros(*x.size())
c_min = x.min(0)
c_max = x.max(0)
delta = c_max[0] - c_min[0]
# set H
r_idx = c_max[1].eq(0)
hsv[0][r_idx] = ((x[1][r_idx] - x[2][r_idx]) / delta[r_idx]) % 6
g_idx = c_max[1].eq(1)
hsv[0][g_idx] = 2 + ((x[2][g_idx] - x[0][g_idx]) / delta[g_idx])
b_idx = c_max[1].eq(2)
hsv[0][b_idx] = 4 + ((x[0][b_idx] - x[1][b_idx]) / delta[b_idx])
hsv[0] = hsv[0].mul(60)
# set S
hsv[1] = delta / c_max[0]
# set V - good
hsv[2] = c_max[0]
return hsv
|
solutions/python/largest-continuous-sum.py | lhayhurst/interview-with-python | 201 | 11094907 | """solution to the largest-continuous-sum problem"""
import unittest
from functools import reduce
def largest_continuous_sum_one(arr):
""" returns the largest continous sub sequence in the given list of numbers. """
largest = 0
queue = []
for num in arr:
queue.append(num)
if len(queue) > 1:
curr_sum = reduce(lambda x, y: x + y, queue)
curr_sum = curr_sum if curr_sum > num else num
if largest < curr_sum:
largest = curr_sum
return largest
def largest_continous_sum_two(arr):
if len(arr) == 0: # handle an edge case
return None
max_sum = current_sum = arr[0]
for num in arr[1:]:
current_sum=max(current_sum+num, num)
max_sum=max(current_sum, max_sum)
return max_sum
# Unit testing
class largest_continous_sum_test(unittest.TestCase):
def setUp(self):
self.arrOne = [1,2,3,4,5]
self.arrTwo = [4,5,1,-1000]
def test_largest_continuous_sum_one(self):
self.assertEqual(
largest_continuous_sum_one( self.arrOne ), 15
)
self.assertEqual(
largest_continuous_sum_one( self.arrTwo ), 10
)
def test_largest_continous_sum_two(self):
self.assertEqual(
largest_continous_sum_two( self.arrOne ) , 15
)
self.assertEqual(
largest_continous_sum_two( self.arrTwo ), 10
)
if __name__ == '__main__':
unittest.main()
|
application/device/smartindustry/motor.py | jason-fox/fogflow | 102 | 11094919 | #!/usr/bin/env python
import time
import os
import signal
import sys
import json
import requests
from flask import Flask, jsonify, abort, request, make_response
from threading import Thread, Lock
import logging
import nxt
app = Flask(__name__, static_url_path = "")
discoveryURL = 'http://192.168.1.80:8070/ngsi9'
brokerURL = ''
profile = {}
subscriptionID = ''
b = nxt.find_one_brick()
mxA = nxt.Motor(b, nxt.PORT_A)
mxB = nxt.Motor(b, nxt.PORT_B)
@app.route('/notifyContext', methods = ['POST'])
def notifyContext():
if not request.json:
abort(400)
objs = readContextElements(request.json)
handleNotify(objs)
return jsonify({ 'responseCode': 200 })
def readContextElements(data):
# print data
ctxObjects = []
for response in data['contextResponses']:
if response['statusCode']['code'] == 200:
ctxObj = element2Object(response['contextElement'])
ctxObjects.append(ctxObj)
return ctxObjects
def handleNotify(contextObjs):
#print("received notification")
#print(contextObjs)
for ctxObj in contextObjs:
processInputStreamData(ctxObj)
def processInputStreamData(obj):
#print '===============receive context entity===================='
#print obj
if 'attributes' in obj:
attributes = obj['attributes']
if 'detectedEvent' in attributes:
event = attributes['detectedEvent']['value']
handleEvent(event)
# if 'command' in attributes:
# command = attributes['command']['value']
# handleCommand(command)
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
# delete my registration and context entity
unpublishMySelf()
unsubscribeCmd()
mxA.brake()
mxB.brake()
sys.exit(0)
def findNearbyBroker():
global profile, discoveryURL
nearby = {}
nearby['latitude'] = profile['location']['latitude']
nearby['longitude'] = profile['location']['longitude']
nearby['limit'] = 1
discoveryReq = {}
discoveryReq['entities'] = [{'type': 'IoTBroker', 'isPattern': True}]
discoveryReq['restriction'] = {'scopes':[{'scopeType': 'nearby', 'scopeValue': nearby}]}
discoveryURL = profile['discoveryURL']
headers = {'Accept' : 'application/json', 'Content-Type' : 'application/json'}
response = requests.post(discoveryURL + '/discoverContextAvailability', data=json.dumps(discoveryReq), headers=headers)
if response.status_code != 200:
print 'failed to find a nearby IoT Broker'
return ''
print response.text
registrations = json.loads(response.text)
for registration in registrations['contextRegistrationResponses']:
providerURL = registration['contextRegistration']['providingApplication']
if providerURL != '':
return providerURL
return ''
def publishMySelf():
global profile, brokerURL
# for motor1
deviceCtxObj = {}
deviceCtxObj['entityId'] = {}
deviceCtxObj['entityId']['id'] = 'Device.' + profile['type'] + '.' + '001'
deviceCtxObj['entityId']['type'] = profile['type']
deviceCtxObj['entityId']['isPattern'] = False
deviceCtxObj['attributes'] = {}
deviceCtxObj['attributes']['iconURL'] = {'type': 'string', 'value': profile['iconURL']}
deviceCtxObj['metadata'] = {}
deviceCtxObj['metadata']['location'] = {'type': 'point', 'value': {'latitude': profile['location']['latitude'], 'longitude': profile['location']['longitude'] }}
updateContext(brokerURL, deviceCtxObj)
# for motor2
deviceCtxObj = {}
deviceCtxObj['entityId'] = {}
deviceCtxObj['entityId']['id'] = 'Device.' + profile['type'] + '.' + '002'
deviceCtxObj['entityId']['type'] = profile['type']
deviceCtxObj['entityId']['isPattern'] = False
deviceCtxObj['attributes'] = {}
deviceCtxObj['attributes']['iconURL'] = {'type': 'string', 'value': profile['iconURL']}
deviceCtxObj['metadata'] = {}
deviceCtxObj['metadata']['location'] = {'type': 'point', 'value': {'latitude': profile['location']['latitude'], 'longitude': profile['location']['longitude'] }}
return updateContext(brokerURL, deviceCtxObj)
def unpublishMySelf():
global profile, brokerURL
# for motor1
deviceCtxObj = {}
deviceCtxObj['entityId'] = {}
deviceCtxObj['entityId']['id'] = 'Device.' + profile['type'] + '.' + '001'
deviceCtxObj['entityId']['type'] = profile['type']
deviceCtxObj['entityId']['isPattern'] = False
deleteContext(brokerURL, deviceCtxObj)
# for motor2
deviceCtxObj = {}
deviceCtxObj['entityId'] = {}
deviceCtxObj['entityId']['id'] = 'Device.' + profile['type'] + '.' + '002'
deviceCtxObj['entityId']['type'] = profile['type']
deviceCtxObj['entityId']['isPattern'] = False
deleteContext(brokerURL, deviceCtxObj)
def element2Object(element):
ctxObj = {}
ctxObj['entityId'] = element['entityId'];
ctxObj['attributes'] = {}
if 'attributes' in element:
for attr in element['attributes']:
ctxObj['attributes'][attr['name']] = {'type': attr['type'], 'value': attr['value']}
ctxObj['metadata'] = {}
if 'domainMetadata' in element:
for meta in element['domainMetadata']:
ctxObj['metadata'][meta['name']] = {'type': meta['type'], 'value': meta['value']}
return ctxObj
def object2Element(ctxObj):
ctxElement = {}
ctxElement['entityId'] = ctxObj['entityId'];
ctxElement['attributes'] = []
if 'attributes' in ctxObj:
for key in ctxObj['attributes']:
attr = ctxObj['attributes'][key]
ctxElement['attributes'].append({'name': key, 'type': attr['type'], 'value': attr['value']})
ctxElement['domainMetadata'] = []
if 'metadata' in ctxObj:
for key in ctxObj['metadata']:
meta = ctxObj['metadata'][key]
ctxElement['domainMetadata'].append({'name': key, 'type': meta['type'], 'value': meta['value']})
return ctxElement
def updateContext(broker, ctxObj):
ctxElement = object2Element(ctxObj)
updateCtxReq = {}
updateCtxReq['updateAction'] = 'UPDATE'
updateCtxReq['contextElements'] = []
updateCtxReq['contextElements'].append(ctxElement)
headers = {'Accept' : 'application/json', 'Content-Type' : 'application/json'}
response = requests.post(broker + '/updateContext', data=json.dumps(updateCtxReq), headers=headers)
if response.status_code != 200:
print 'failed to update context'
print response.text
return False
else:
return True
def deleteContext(broker, ctxObj):
ctxElement = object2Element(ctxObj)
updateCtxReq = {}
updateCtxReq['updateAction'] = 'DELETE'
updateCtxReq['contextElements'] = []
updateCtxReq['contextElements'].append(ctxElement)
headers = {'Accept' : 'application/json', 'Content-Type' : 'application/json'}
response = requests.post(broker + '/updateContext', data=json.dumps(updateCtxReq), headers=headers)
if response.status_code != 200:
print 'failed to delete context'
print response.text
def unsubscribeCmd():
global brokerURL
global subscriptionID
print(brokerURL + '/subscription/' + subscriptionID)
response = requests.delete(brokerURL + '/subscription/' + subscriptionID)
print(response.text)
def subscribeCmd():
global subscriptionID
subscribeCtxReq = {}
subscribeCtxReq['entities'] = []
# subscribe push button on behalf of TPU
myID = 'Device.Motor.001'
subscribeCtxReq['entities'].append({'id': myID, 'isPattern': False})
#subscribeCtxReq['attributes'] = ['command']
subscribeCtxReq['reference'] = 'http://' + profile['myIP'] + ':' + str(profile['myPort'])
headers = {'Accept' : 'application/json', 'Content-Type' : 'application/json', 'Require-Reliability' : 'true'}
response = requests.post(brokerURL + '/subscribeContext', data=json.dumps(subscribeCtxReq), headers=headers)
if response.status_code != 200:
print 'failed to subscribe context'
print response.text
return ''
else:
json_data = json.loads(response.text)
subscriptionID = json_data['subscribeResponse']['subscriptionId']
print(subscriptionID)
return subscriptionID
# # subscribe to motor1
# myID = 'Device.' + profile['type'] + '.' + '001'
# subscribeCtxReq['entities'].append({'id': myID, 'isPattern': False})
# subscribeCtxReq['attributes'] = ['command']
# subscribeCtxReq['reference'] = 'http://' + profile['myIP'] + ':' + str(profile['myPort'])
# headers = {'Accept' : 'application/json', 'Content-Type' : 'application/json', 'Require-Reliability' : 'true'}
# response = requests.post(brokerURL + '/subscribeContext', data=json.dumps(subscribeCtxReq), headers=headers)
# if response.status_code != 200:
# print 'failed to subscribe context'
# print response.text
# # subscribe to motor2
# myID = 'Device.' + profile['type'] + '.' + '002'
# subscribeCtxReq['entities'].append({'id': myID, 'isPattern': False})
# subscribeCtxReq['attributes'] = ['command']
# subscribeCtxReq['reference'] = 'http://' + profile['myIP'] + ':' + str(profile['myPort'])
# headers = {'Accept' : 'application/json', 'Content-Type' : 'application/json', 'Require-Reliability' : 'true'}
# response = requests.post(brokerURL + '/subscribeContext', data=json.dumps(subscribeCtxReq), headers=headers)
# if response.status_code != 200:
# print 'failed to subscribe context'
# print response.text
# # subscribe camera on behalf of TPU
# myID = 'Device.Camera.001'
# subscribeCtxReq['entities'].append({'id': myID, 'isPattern': False})
# subscribeCtxReq['attributes'] = ['command']
# subscribeCtxReq['reference'] = 'http://' + profile['myIP'] + ':8008'
# headers = {'Accept' : 'application/json', 'Content-Type' : 'application/json', 'Require-Reliability' : 'true'}
# response = requests.post(brokerURL + '/subscribeContext', data=json.dumps(subscribeCtxReq), headers=headers)
# if response.status_code != 200:
# print 'failed to subscribe context'
# print response.text
def run():
# find a nearby broker for data exchange
global brokerURL
brokerURL = profile['brokerURL'] #findNearbyBroker()
if brokerURL == '':
print 'failed to find a nearby broker'
sys.exit(0)
print "selected broker"
print brokerURL
#announce myself
while True:
ok = publishMySelf()
if ok == True:
break
else:
time.sleep(1)
print("publish myself")
#subscribe to the control commands
while True:
sid = subscribeCmd()
if sid != '':
break
else:
time.sleep(1)
print("subscribe command for myself")
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
print('start to handle the incoming control commands')
myport = profile['myPort']
app.run(host='0.0.0.0', port=myport)
def handleEvent(event):
print event
eventType = event['type']
print(eventType)
if eventType == 'MOVE_FORWARD':
print("MOVE_FORWARD")
mxA.run(-100)
time.sleep(1)
mxA.brake()
if eventType == 'MOVE_LEFT':
print("MOVE_LEFT")
mxB.run(80)
time.sleep(1)
mxB.brake()
if eventType == 'MOVE_RIGHT':
print("MOVE_RIGHT")
mxB.run(-80)
time.sleep(1)
mxB.brake()
if eventType == 'MOVE_BACKWARD':
print("MOVE_BACKWARD")
mxA.run(100)
time.sleep(1)
mxA.brake()
if __name__ == '__main__':
cfgFileName = 'motor.json'
if len(sys.argv) >= 2:
cfgFileName = sys.argv[1]
try:
with open(cfgFileName) as json_file:
profile = json.load(json_file)
profile['type'] = 'Motor'
except Exception as error:
print 'failed to load the device profile'
sys.exit(0)
run()
|
python/mixed/x86_lstm_demo/data_reader.py | PaddlePaddle/Paddle-Inference-demo | 115 | 11094923 | import numpy as np
import struct
from paddle import fluid
def get_data(data_path, place):
inputs = []
labels = []
with open(data_path, 'rb') as in_f:
while True:
plen = in_f.read(4)
if plen is None or len(plen) != 4:
break
alllen = struct.unpack('i', plen)[0]
label_len = alllen & 0xFFFF
seq_len = (alllen >> 16) & 0xFFFF
label = in_f.read(4 * label_len)
label = np.frombuffer(
label, dtype=np.int32).reshape([len(label) // 4])
feat = in_f.read(4 * seq_len * 8)
feat = np.frombuffer(
feat, dtype=np.float32).reshape([len(feat) // 4 // 8, 8])
lod_feat = [feat.shape[0]]
minputs = fluid.create_lod_tensor(feat, [lod_feat], place)
infer_data = fluid.core.PaddleTensor()
infer_data.lod = minputs.lod()
infer_data.data = fluid.core.PaddleBuf(np.array(minputs))
infer_data.shape = minputs.shape()
infer_data.dtype = fluid.core.PaddleDType.FLOAT32
infer_label = fluid.core.PaddleTensor()
infer_label.data = fluid.core.PaddleBuf(np.array(label))
infer_label.shape = label.shape
infer_label.dtype = fluid.core.PaddleDType.INT32
inputs.append(infer_data)
labels.append(infer_label)
return inputs, labels
def get_data_with_ptq_warmup(data_path, place, warmup_batch_size=1):
all_inputs, all_labels = get_data(data_path, place)
warmup_inputs = all_inputs[:warmup_batch_size]
inputs = all_inputs[warmup_batch_size:]
labels = all_labels[warmup_batch_size:]
return warmup_inputs, inputs, labels
|
tests/test_scripts.py | vincentfretin/kinto | 4,618 | 11094928 | <filename>tests/test_scripts.py
import unittest
from unittest import mock
from kinto import scripts
class RebuildQuotasTest(unittest.TestCase):
def setUp(self):
self.registry = mock.MagicMock()
self.registry.settings = {"includes": "kinto.plugins.quotas"}
def test_rebuild_quotas_in_read_only_display_an_error(self):
with mock.patch("kinto.scripts.logger") as mocked:
self.registry.settings["readonly"] = "true"
code = scripts.rebuild_quotas({"registry": self.registry})
assert code == 41
mocked.error.assert_any_call("Cannot rebuild quotas while " "in readonly mode.")
def test_rebuild_quotas_when_not_included_display_an_error(self):
with mock.patch("kinto.scripts.logger") as mocked:
self.registry.settings["includes"] = ""
code = scripts.rebuild_quotas({"registry": self.registry})
assert code == 42
mocked.error.assert_any_call(
"Cannot rebuild quotas when " "quotas plugin is not installed."
)
def test_rebuild_quotas_calls_quotas_script(self):
with mock.patch("kinto.scripts.quotas.rebuild_quotas") as mocked:
code = scripts.rebuild_quotas({"registry": self.registry})
assert code == 0
mocked.assert_called_with(self.registry.storage, dry_run=False)
|
dataset.py | amorgun/pose-with-style | 168 | 11094962 | <reponame>amorgun/pose-with-style<gh_stars>100-1000
from PIL import Image
from torch.utils.data import Dataset
import torchvision.transforms as transforms
import os
import pandas as pd
import numpy as np
import torch
import random
import pickle
class DeepFashionDataset(Dataset):
def __init__(self, path, phase, size):
self.phase = phase # train or test
self.size = size # 256 or 512 FOR 174x256 or 348x512
# set root directories
self.image_root = os.path.join(path, 'DeepFashion_highres', phase)
self.densepose_root = os.path.join(path, 'densepose', phase)
self.parsing_root = os.path.join(path, 'silhouette', phase)
# path to pairs of data
pairs_csv_path = os.path.join(path, 'DeepFashion_highres', 'tools', 'fashion-pairs-%s.csv'%phase)
# uv space
self.uv_root = os.path.join(path, 'complete_coordinates', phase)
# initialize the pairs of data
self.init_pairs(pairs_csv_path)
self.data_size = len(self.pairs)
print('%s data pairs (#=%d)...'%(phase, self.data_size))
if phase == 'train':
# get dictionary of image name and transfrom to detect and align the face
with open(os.path.join(path, 'resources', 'train_face_T.pickle'), 'rb') as handle:
self.faceTransform = pickle.load(handle)
self.transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
def init_pairs(self, pairs_csv_path):
pairs_file = pd.read_csv(pairs_csv_path)
self.pairs = []
self.sources = {}
print('Loading data pairs ...')
for i in range(len(pairs_file)):
pair = [pairs_file.iloc[i]['from'], pairs_file.iloc[i]['to']]
self.pairs.append(pair)
print('Loading data pairs finished ...')
def __len__(self):
return self.data_size
def resize_height_PIL(self, x, height=512):
w, h = x.size
width = int(height * w / h)
return x.resize((width, height), Image.NEAREST) #Image.ANTIALIAS
def resize_PIL(self, x, height=512, width=348, type=Image.NEAREST):
return x.resize((width, height), type)
def tensors2square(self, im, pose, sil):
width = im.shape[2]
diff = self.size - width
if self.phase == 'train':
left = random.randint(0, diff)
right = diff - left
else: # when testing put in the center
left = int((self.size-width)/2)
right = diff - left
im = torch.nn.functional.pad(input=im, pad=(right, left, 0, 0), mode='constant', value=0)
pose = torch.nn.functional.pad(input=pose, pad=(right, left, 0, 0), mode='constant', value=0)
sil = torch.nn.functional.pad(input=sil, pad=(right, left, 0, 0), mode='constant', value=0)
return im, pose, sil, left, right
def __getitem__(self, index):
# get current pair
im1_name, im2_name = self.pairs[index]
# get path to dataset
input_image_path = os.path.join(self.image_root, im1_name)
target_image_path = os.path.join(self.image_root, im2_name)
# dense pose
input_densepose_path = os.path.join(self.densepose_root, im1_name.split('.')[0]+'_iuv.png')
target_densepose_path = os.path.join(self.densepose_root, im2_name.split('.')[0]+'_iuv.png')
# silhouette
input_sil_path = os.path.join(self.parsing_root, im1_name.split('.')[0]+'_sil.png')
target_sil_path = os.path.join(self.parsing_root, im2_name.split('.')[0]+'_sil.png')
# uv space
complete_coor_path = os.path.join(self.uv_root, im1_name.split('.')[0]+'_uv_coor.npy')
# read data
# get original size of data -> for augmentation
input_image_pil = Image.open(input_image_path).convert('RGB')
orig_w, orig_h = input_image_pil.size
if self.phase == 'test':
# set target height and target width
if self.size == 512:
target_h = 512
target_w = 348
if self.size == 256:
target_h = 256
target_w = 174
# images
input_image = self.resize_PIL(input_image_pil, height=target_h, width=target_w, type=Image.ANTIALIAS)
target_image = self.resize_PIL(Image.open(target_image_path).convert('RGB'), height=target_h, width=target_w, type=Image.ANTIALIAS)
# dense pose
input_densepose = np.array(self.resize_PIL(Image.open(input_densepose_path), height=target_h, width=target_w))
target_densepose = np.array(self.resize_PIL(Image.open(target_densepose_path), height=target_h, width=target_w))
# silhouette
silhouette1 = np.array(self.resize_PIL(Image.open(input_sil_path), height=target_h, width=target_w))/255
silhouette2 = np.array(self.resize_PIL(Image.open(target_sil_path), height=target_h, width=target_w))/255
# union with densepose mask for a more accurate mask
silhouette1 = 1-((1-silhouette1) * (input_densepose[:, :, 0] == 0).astype('float'))
else:
input_image = self.resize_height_PIL(input_image_pil, self.size)
target_image = self.resize_height_PIL(Image.open(target_image_path).convert('RGB'), self.size)
# dense pose
input_densepose = np.array(self.resize_height_PIL(Image.open(input_densepose_path), self.size))
target_densepose = np.array(self.resize_height_PIL(Image.open(target_densepose_path), self.size))
# silhouette
silhouette1 = np.array(self.resize_height_PIL(Image.open(input_sil_path), self.size))/255
silhouette2 = np.array(self.resize_height_PIL(Image.open(target_sil_path), self.size))/255
# union with densepose masks
silhouette1 = 1-((1-silhouette1) * (input_densepose[:, :, 0] == 0).astype('float'))
silhouette2 = 1-((1-silhouette2) * (target_densepose[:, :, 0] == 0).astype('float'))
# read uv-space data
complete_coor = np.load(complete_coor_path)
# Transform
input_image = self.transform(input_image)
target_image = self.transform(target_image)
# Dense Pose
input_densepose = torch.from_numpy(input_densepose).permute(2, 0, 1)
target_densepose = torch.from_numpy(target_densepose).permute(2, 0, 1)
# silhouette
silhouette1 = torch.from_numpy(silhouette1).float().unsqueeze(0) # from h,w to c,h,w
silhouette2 = torch.from_numpy(silhouette2).float().unsqueeze(0) # from h,w to c,h,w
# put into a square
input_image, input_densepose, silhouette1, Sleft, Sright = self.tensors2square(input_image, input_densepose, silhouette1)
target_image, target_densepose, silhouette2, Tleft, Tright = self.tensors2square(target_image, target_densepose, silhouette2)
if self.phase == 'train':
# remove loaded center shift and add augmentation shift
loaded_shift = int((orig_h-orig_w)/2)
complete_coor = ((complete_coor+1)/2)*(orig_h-1) # [-1, 1] to [0, orig_h]
complete_coor[:,:,0] = complete_coor[:,:,0] - loaded_shift # remove center shift
complete_coor = ((2*complete_coor/(orig_h-1))-1) # [0, orig_h] (no shift in w) to [-1, 1]
complete_coor = ((complete_coor+1)/2) * (self.size-1) # [-1, 1] to [0, size] (no shift in w)
complete_coor[:,:,0] = complete_coor[:,:,0] + Sright # add augmentation shift to w
complete_coor = ((2*complete_coor/(self.size-1))-1) # [0, size] (with shift in w) to [-1,1]
# to tensor
complete_coor = torch.from_numpy(complete_coor).float().permute(2, 0, 1)
else:
# might have hxw inconsistencies since dp is of different sizes.. fixing this..
loaded_shift = int((orig_h-orig_w)/2)
complete_coor = ((complete_coor+1)/2)*(orig_h-1) # [-1, 1] to [0, orig_h]
complete_coor[:,:,0] = complete_coor[:,:,0] - loaded_shift # remove center shift
# before: width complete_coor[:,:,0] 0-orig_w-1
# and height complete_coor[:,:,1] 0-orig_h-1
complete_coor[:,:,0] = (complete_coor[:,:,0]/(orig_w-1))*(target_w-1)
complete_coor[:,:,1] = (complete_coor[:,:,1]/(orig_h-1))*(target_h-1)
complete_coor[:,:,0] = complete_coor[:,:,0] + Sright # add center shift to w
complete_coor = ((2*complete_coor/(self.size-1))-1) # [0, size] (with shift in w) to [-1,1]
# to tensor
complete_coor = torch.from_numpy(complete_coor).float().permute(2, 0, 1)
# either source or target pass 1:5
if self.phase == 'train':
choice = random.randint(0, 6)
if choice == 0:
# source pass
target_im = input_image
target_p = input_densepose
target_sil = silhouette1
target_image_name = im1_name
target_left_pad = Sleft
target_right_pad = Sright
else:
# target pass
target_im = target_image
target_p = target_densepose
target_sil = silhouette2
target_image_name = im2_name
target_left_pad = Tleft
target_right_pad = Tright
else:
target_im = target_image
target_p = target_densepose
target_sil = silhouette2
target_image_name = im2_name
target_left_pad = Tleft
target_right_pad = Tright
# Get the face transfrom
if self.phase == 'train':
if target_image_name in self.faceTransform.keys():
FT = torch.from_numpy(self.faceTransform[target_image_name]).float()
else: # no face detected
FT = torch.zeros((3,3))
# return data
if self.phase == 'train':
return {'input_image':input_image, 'target_image':target_im,
'target_sil': target_sil,
'target_pose':target_p,
'TargetFaceTransform': FT, 'target_left_pad':torch.tensor(target_left_pad), 'target_right_pad':torch.tensor(target_right_pad),
'input_sil': silhouette1, 'complete_coor':complete_coor,
}
if self.phase == 'test':
save_name = im1_name.split('.')[0] + '_2_' + im2_name.split('.')[0] + '_vis.png'
return {'input_image':input_image, 'target_image':target_im,
'target_sil': target_sil,
'target_pose':target_p,
'target_left_pad':torch.tensor(target_left_pad), 'target_right_pad':torch.tensor(target_right_pad),
'input_sil': silhouette1, 'complete_coor':complete_coor,
'save_name':save_name,
}
|
python2/pracmln/mln/inference/__init__.py | seba90/pracmln | 123 | 11094969 | <filename>python2/pracmln/mln/inference/__init__.py
from exact import EnumerationAsk
from mcsat import MCSAT, SampleSAT
from gibbs import GibbsSampler
# from ipfpm import IPFPM
from maxwalk import SAMaxWalkSAT
from wcspinfer import WCSPInference
from infer import Inference
|
mpf/tests/test_Playfield.py | Scottacus64/mpf | 163 | 11094970 | from mpf.tests.MpfTestCase import MpfTestCase
class TestPlayfield(MpfTestCase):
def get_config_file(self):
return 'test_playfield.yaml'
def get_machine_path(self):
return 'tests/machine_files/playfield/'
# nothing to test currently
|
leetcode.com/python/946_Validate_Stack_Sequences.py | vansh-tiwari/coding-interview-gym | 713 | 11094988 | <reponame>vansh-tiwari/coding-interview-gym<filename>leetcode.com/python/946_Validate_Stack_Sequences.py<gh_stars>100-1000
# Time and space both O(n)
class Solution(object):
def validateStackSequences(self, pushed, popped):
"""
:type pushed: List[int]
:type popped: List[int]
:rtype: bool
"""
stack = []
for i in range(len(pushed)):
stack.append(pushed[i])
while stack and popped and popped[0] == stack[-1]:
stack.pop()
popped.pop(0)
return len(stack) == 0
# Time : :(n) | Space: O(1)
class Solution(object):
def validateStackSequences(self, pushed, popped):
"""
:type pushed: List[int]
:type popped: List[int]
:rtype: bool
"""
|
hypergan/train_hooks/needs_pytorch/learning_rate_dropout_train_hook.py | limberc/HyperGAN | 889 | 11094995 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from hypergan.train_hooks.base_train_hook import BaseTrainHook
from operator import itemgetter
from tensorflow.python.framework import ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.training import optimizer
from torch.autograd import Variable
from torch.autograd import grad as torch_grad
import hyperchamber as hc
import inspect
import numpy as np
import torch
import torch.nn as nn
class LearningRateDropoutTrainHook(BaseTrainHook):
""" https://arxiv.org/abs/1912.00144 """
def __init__(self, gan=None, config=None, trainer=None):
super().__init__(config=config, gan=gan, trainer=trainer)
self.ones = self.gan.configurable_param(self.config.ones or 1.0)
self.zeros = self.gan.configurable_param(self.config.zeros or 0.0)
self.dropout = self.gan.configurable_param(self.config.dropout or 0.9)
def forward(self):
return [None, None]
def gradients(self, d_grads, g_grads):
d_ones = [torch.ones_like(_g) for _g in d_grads]
g_ones = [torch.ones_like(_g) for _g in g_grads]
d_zeros = [torch.zeros_like(_g) for _g in d_grads]
g_zeros = [torch.zeros_like(_g) for _g in g_grads]
da = [torch.where((torch.rand_like(_d_grads)- (1.0-self.dropout)) < 0, _o, _z) for _d_grads, _o, _z in zip(d_grads, d_ones, d_zeros)]
ga = [torch.where((torch.rand_like(_g_grads)- (1.0-self.dropout)) < 0, _o, _z) for _g_grads, _o, _z in zip(g_grads, g_ones, g_zeros)]
if self.config.skip_d is None:
d_grads = [_a * _grad for _a, _grad in zip(da, d_grads)]
if self.config.skip_g is None:
g_grads = [_a * _grad for _a, _grad in zip(ga, g_grads)]
#def count_params(variables):
# return np.sum([np.prod(self.ops.shape(t)) for t in variables ])
#self.gan.add_metric('dropout-one', ones)
#self.gan.add_metric('dropout-perc', dropout)
#self.gan.add_metric('dropout', sum([self.ops.squash((1.0-_a/ones), tf.reduce_sum) for _a in da]) / count_params(da))
return [d_grads, g_grads]
|
Packs/XSOARContentUpdateNotifications/Scripts/ListInstalledContentPacks/ListInstalledContentPacks.py | diCagri/content | 799 | 11095023 | import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
args = demisto.args()
updated = True if args.get('updates') == 'true' else False
packs = demisto.executeCommand("demisto-api-get", {"uri": "/contentpacks/installed-expired"})[0]['Contents'].get('response')
parsed_packs = [{
"name": x.get('name'),
"version": x.get('currentVersion'),
"update": x.get('updateAvailable', False)
} for x in packs]
if updated:
parsed_packs[:] = [x for x in parsed_packs if x.get('update')]
command_results = CommandResults(
outputs_prefix="InstalledPacks",
outputs_key_field="name",
outputs=parsed_packs,
readable_output=tableToMarkdown("Installed Content Packs:", parsed_packs, ["name", "version", "update"])
)
return_results(command_results)
|
examples/independent_marl.py | apexrl/malib | 258 | 11095024 | <filename>examples/independent_marl.py<gh_stars>100-1000
# """
# Implementation of independent learning applied to MARL cases.
# """
# import argparse
# from malib.envs.mpe.env import MPE
# from malib.runner import run
# parser = argparse.ArgumentParser(
# "Independent multi-agent learning on mpe environments."
# )
# parser.add_argument("--batch_size", type=int, default=64)
# parser.add_argument("--num_epoch", type=int, default=100)
# parser.add_argument("--fragment_length", type=int, default=25)
# parser.add_argument("--worker_num", type=int, default=6)
# parser.add_argument("--algorithm", type=str, default="PPO")
# if __name__ == "__main__":
# args = parser.parse_args()
# env_description = {
# "creator": MPE,
# "config": {
# "env_id": "simple_tag_v2",
# "scenario_configs": {
# "num_good": 2,
# "num_adversaries": 2,
# "num_obstacles": 2,
# "max_cycles": 25,
# },
# },
# }
# env = MPE(**env_description["config"])
# env_description["possible_agents"] = env.possible_agents
# run(
# env_description=env_description,
# training={
# "interface": {
# "type": "independent",
# "observation_spaces": env.observation_spaces,
# "action_spaces": env.action_spaces,
# },
# "config": {
# "agent": {
# "observation_spaces": env.observation_spaces,
# "action_spaces": env.action_spaces,
# },
# "batch_size": args.batch_size,
# "grad_norm_clipping": 0.5,
# },
# },
# algorithms={"PPO": {"name": "PPO"}},
# rollout={
# "type": "async",
# "stopper": "simple_rollout",
# "metric_type": "simple",
# "fragment_length": 75,
# "num_episodes": 100,
# },
# global_evaluator={
# "name": "generic",
# "config": {"stop_metrics": {}},
# },
# )
|
tests/utils/test_shell.py | tomekr/cement | 826 | 11095039 |
import time
import mock
from pytest import raises
from cement.utils import shell
from cement.core.exc import FrameworkError
INPUT = 'builtins.input'
def add(a, b):
return a + b
def test_cmd():
out, err, ret = shell.cmd('echo KAPLA!')
assert ret == 0
assert out == b'KAPLA!\n'
ret = shell.cmd('echo KAPLA', capture=False)
assert ret == 0
def test_exec_cmd():
out, err, ret = shell.exec_cmd(['echo', 'KAPLA!'])
assert ret == 0
assert out == b'KAPLA!\n'
def test_exec_cmd_shell_true():
out, err, ret = shell.exec_cmd(['echo KAPLA!'], shell=True)
assert ret == 0
assert out == b'KAPLA!\n'
def test_exec_cmd2():
ret = shell.exec_cmd2(['echo'])
assert ret == 0
def test_exec_cmd2_shell_true():
ret = shell.exec_cmd2(['echo johnny'], shell=True)
assert ret == 0
def test_exec_cmd_bad_command():
out, err, ret = shell.exec_cmd(['false'])
assert ret == 1
def test_exec_cmd2_bad_command():
ret = shell.exec_cmd2(['false'])
assert ret == 1
def test_spawn():
p = shell.spawn(add, args=(23, 2))
p.join()
assert p.exitcode == 0
t = shell.spawn(time.sleep, args=(2,), thread=True)
# before joining it is alive
res = t.is_alive()
assert res is True
t.join()
# after joining it is not alive
res = t.is_alive()
assert res is False
def test_spawn_process():
p = shell.spawn_process(add, args=(23, 2))
p.join()
assert p.exitcode == 0
p = shell.spawn_process(add, join=True, args=(23, 2))
assert p.exitcode == 0
def test_spawn_thread():
t = shell.spawn_thread(time.sleep, args=(2,))
# before joining it is alive
res = t.is_alive()
assert res is True
t.join()
# after joining it is not alive
res = t.is_alive()
assert res is False
t = shell.spawn_thread(time.sleep, join=True, args=(2,))
res = t.is_alive()
assert res is False
def test_prompt_simple():
with mock.patch(INPUT, return_value='Test Input'):
p = shell.Prompt("Test Prompt")
assert p.input == 'Test Input'
def test_prompt_clear():
# test with a non-clear command:
with mock.patch(INPUT, return_value='Test Input'):
p = shell.Prompt("Test Prompt",
clear=True,
clear_command='true',
)
assert p.input == 'Test Input'
def test_prompt_options():
# test options (non-numbered.. user inputs actual option)
with mock.patch(INPUT, return_value='y'):
p = shell.Prompt("Test Prompt", options=['y', 'n'])
assert p.input == 'y'
# test default value
with mock.patch(INPUT, return_value=''):
p = shell.Prompt("Test Prompt", options=['y', 'n'], default='n')
assert p.input == 'n'
def test_prompt_numbered_options():
# test numbered selection (user inputs number)
with mock.patch(INPUT, return_value='3'):
p = shell.Prompt("Test Prompt",
options=['yes', 'no', 'maybe'],
numbered=True,
)
assert p.input == 'maybe'
# test default value
with mock.patch(INPUT, return_value=''):
p = shell.Prompt(
"Test Prompt",
options=['yes', 'no', 'maybe'],
numbered=True,
default='2',
)
assert p.input == 'no'
def test_prompt_input_is_none():
# test that self.input is none if no default, and no input
with mock.patch(INPUT, return_value=''):
p = shell.Prompt('Test Prompt',
max_attempts=3,
max_attempts_exception=False,
)
assert p.input is None
def test_prompt_max_attempts():
# test that self.input is none if no default, and no input
with mock.patch(INPUT, return_value=''):
msg = "Maximum attempts exceeded getting valid user input"
with raises(FrameworkError, match=msg):
shell.Prompt('Test Prompt',
max_attempts=3,
max_attempts_exception=True,
)
def test_prompt_index_and_value_errors():
with mock.patch(INPUT, return_value='5'):
p = shell.Prompt(
"Test Prompt",
options=['yes', 'no', 'maybe'],
numbered=True,
max_attempts=3,
max_attempts_exception=False,
)
assert p.input is None
def test_prompt_case_insensitive():
with mock.patch(INPUT, return_value='NO'):
p = shell.Prompt(
"Test Prompt",
options=['yes', 'no', 'maybe'],
case_insensitive=True,
)
assert p.input == 'NO'
with mock.patch(INPUT, return_value='NOT VALID'):
p = shell.Prompt(
"Test Prompt",
options=['yes', 'no', 'maybe'],
case_insensitive=True,
max_attempts=3,
max_attempts_exception=False,
)
assert p.input is None
def test_prompt_case_sensitive():
with mock.patch(INPUT, return_value='NO'):
p = shell.Prompt(
"Test Prompt",
options=['yes', 'no', 'maybe'],
case_insensitive=False,
max_attempts=3,
max_attempts_exception=False,
)
assert p.input is None
|
code/quaternions/blender_camera_quaternions.py | ricklentz/2dimageto3dmodel | 150 | 11095040 | """
author: <NAME>
"""
from math import sqrt, pow, acos, pi, asin
from scipy.spatial.transform import Rotation as R
import numpy as np
import torch
def scale_to_n(axis, n):
return axis / n
def blender_camera_position_to_torch_tensor_quaternion(blender_camera_info):
x, y, z = blender_camera_info[0]
# distance from camera
d = sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2))
x, y, z = scale_to_n(x, d), scale_to_n(y, d), scale_to_n(z, d)
d_2D = sqrt(pow(x, 2) + pow(y, 2))
x2D, y2D = scale_to_n(x, d_2D), scale_to_n(y, d_2D)
# z axis
yaw = acos(x2D)
if y2D > 0:
yaw = 2 * pi - yaw
"""
Yaw, pitch and roll is a way of describing the rotation of the camera in 3D. There is other ways like quaternions
but this is the simplest. Yaw, pitch and roll is the name of how much we should rotate around each axis.
Think about yourself as the camera right now. Look around a bit. Yaw is the angle when moving the head
left <=> right (rotation around Y-axis). Pitch is up and down (rotation around X-axis). Roll, which we usually
don't experience is when you tilt your head (rotation around Z-axis).
"""
roll = 0
pitch = asin(z)
yaw = yaw + pi
# Initialize from Euler angles
quaternion = R.from_euler(
seq="yzx",
angles=[yaw, pitch, roll] # Euler angles specified in radians
).as_quat()
# form matrix: scalar part, vector part
quaternion = np.r_[quaternion[-1], quaternion[:-1]]
return torch.tensor(quaternion.astype(
dtype=np.float32
))
|
course/migrations/0007_add_participation_preapproval.py | inducer/courseflow | 284 | 11095090 | <reponame>inducer/courseflow
from django.db import models, migrations
import django.utils.timezone
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('course', '0006_flowpagevisit_remote_address'),
]
operations = [
migrations.CreateModel(
name='ParticipationPreapproval',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('email', models.EmailField(max_length=254)),
('role', models.CharField(max_length=50, choices=[('instructor', 'Instructor'), ('ta', 'Teaching Assistant'), ('student', 'Student')])),
('creation_time', models.DateTimeField(default=django.utils.timezone.now, db_index=True)),
('course', models.ForeignKey(to='course.Course', on_delete=models.CASCADE)),
('creator', models.ForeignKey(to=settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)),
],
options={
'ordering': ('course', 'email'),
},
bases=(models.Model,),
),
migrations.AlterUniqueTogether(
name='participationpreapproval',
unique_together={('course', 'email')},
),
]
|
source/mitparallel/util.py | jaesikchoi/gpss-research | 151 | 11095091 | <reponame>jaesikchoi/gpss-research
import config
import os
import tempfile
def mkstemp_safe(directory, suffix):
(os_file_handle, file_name) = tempfile.mkstemp(dir=directory, suffix=suffix)
os.close(os_file_handle)
return file_name
def create_temp_file(extension):
return mkstemp_safe(config.TEMP_PATH, extension)
|
hyperglass/external/bgptools.py | blkmajik/hyperglass | 298 | 11095123 | """Query & parse data from bgp.tools.
- See https://bgp.tools/credits for acknowledgements and licensing.
- See https://bgp.tools/kb/api for query documentation.
"""
# Standard Library
import re
import socket
import asyncio
from typing import Dict, List
# Project
from hyperglass.log import log
from hyperglass.cache import SyncCache, AsyncCache
from hyperglass.configuration import REDIS_CONFIG, params
DEFAULT_KEYS = ("asn", "ip", "prefix", "country", "rir", "allocated", "org")
CACHE_KEY = "hyperglass.external.bgptools"
def parse_whois(output: str, targets: List[str]) -> Dict[str, str]:
"""Parse raw whois output from bgp.tools.
Sample output:
AS | IP | BGP Prefix | CC | Registry | Allocated | AS Name
13335 | 1.1.1.1 | 1.1.1.0/24 | US | ARIN | 2010-07-14 | Cloudflare, Inc.
"""
def lines(raw):
"""Generate clean string values for each column."""
for r in (r for r in raw.split("\n") if r):
fields = (
re.sub(r"(\n|\r)", "", field).strip(" ") for field in r.split("|")
)
yield fields
data = {}
for line in lines(output):
# Unpack each line's parsed values.
asn, ip, prefix, country, rir, allocated, org = line
# Match the line to the item in the list of resources to query.
if ip in targets:
i = targets.index(ip)
data[targets[i]] = {
"asn": asn,
"ip": ip,
"prefix": prefix,
"country": country,
"rir": rir,
"allocated": allocated,
"org": org,
}
log.debug("Parsed bgp.tools data: {}", data)
return data
async def run_whois(targets: List[str]) -> str:
"""Open raw socket to bgp.tools and execute query."""
# Construct bulk query
query = "\n".join(("begin", *targets, "end\n")).encode()
# Open the socket to bgp.tools
log.debug("Opening connection to bgp.tools")
reader, writer = await asyncio.open_connection("bgp.tools", port=43)
# Send the query
writer.write(query)
if writer.can_write_eof():
writer.write_eof()
await writer.drain()
# Read the response
response = b""
while True:
data = await reader.read(128)
if data:
response += data
else:
log.debug("Closing connection to bgp.tools")
writer.close()
break
return response.decode()
def run_whois_sync(targets: List[str]) -> str:
"""Open raw socket to bgp.tools and execute query."""
# Construct bulk query
query = "\n".join(("begin", *targets, "end\n")).encode()
# Open the socket to bgp.tools
log.debug("Opening connection to bgp.tools")
sock = socket.socket()
sock.connect(("bgp.tools", 43))
sock.send(query)
# Read the response
response = b""
while True:
data = sock.recv(128)
if data:
response += data
else:
log.debug("Closing connection to bgp.tools")
sock.shutdown(1)
sock.close()
break
return response.decode()
async def network_info(*targets: str) -> Dict[str, Dict[str, str]]:
"""Get ASN, Containing Prefix, and other info about an internet resource."""
targets = [str(t) for t in targets]
cache = AsyncCache(db=params.cache.database, **REDIS_CONFIG)
# Set default data structure.
data = {t: {k: "" for k in DEFAULT_KEYS} for t in targets}
# Get all cached bgp.tools data.
cached = await cache.get_dict(CACHE_KEY)
# Try to use cached data for each of the items in the list of
# resources.
for t in targets:
if t in cached:
# Reassign the cached network info to the matching resource.
data[t] = cached[t]
log.debug("Using cached network info for {}", t)
# Remove cached items from the resource list so they're not queried.
targets = [t for t in targets if t not in cached]
try:
if targets:
whoisdata = await run_whois(targets)
if whoisdata:
# If the response is not empty, parse it.
data.update(parse_whois(whoisdata, targets))
# Cache the response
for t in targets:
await cache.set_dict(CACHE_KEY, t, data[t])
log.debug("Cached network info for {}", t)
except Exception as err:
log.error(str(err))
return data
def network_info_sync(*targets: str) -> Dict[str, Dict[str, str]]:
"""Get ASN, Containing Prefix, and other info about an internet resource."""
targets = [str(t) for t in targets]
cache = SyncCache(db=params.cache.database, **REDIS_CONFIG)
# Set default data structure.
data = {t: {k: "" for k in DEFAULT_KEYS} for t in targets}
# Get all cached bgp.tools data.
cached = cache.get_dict(CACHE_KEY)
# Try to use cached data for each of the items in the list of
# resources.
for t in targets:
if t in cached:
# Reassign the cached network info to the matching resource.
data[t] = cached[t]
log.debug("Using cached network info for {}", t)
# Remove cached items from the resource list so they're not queried.
targets = [t for t in targets if t not in cached]
try:
if targets:
whoisdata = run_whois_sync(targets)
if whoisdata:
# If the response is not empty, parse it.
data.update(parse_whois(whoisdata, targets))
# Cache the response
for t in targets:
cache.set_dict(CACHE_KEY, t, data[t])
log.debug("Cached network info for {}", t)
except Exception as err:
log.error(str(err))
return data
|
testing/cookbook/table_query_result_mapper.py | kstepanmpmg/mldb | 665 | 11095148 | #
# table_query_result_mapper.py
# Mich, 2016-01-13
# Copyright (c) 2016 mldb.ai inc. All rights reserved.
#
# MLDB doesn't guarantee column ordering of SQL queries will match the ordering
# of the result. Here is a column mapper example to work around that.
#
from mldb import mldb
class TableQueryResultMapper(object):
class MappedRow(object):
def __init__(self, mapping, row):
self._mapping = mapping
self._row = row
def __getattr__(self, name):
return self._row[self._mapping[name]]
def __getitem__(self, name):
return self._row[self._mapping[name]]
def __str__(self):
return str({
k : self._row[v]
for k, v in self._mapping.items()})
def __init__(self, result):
assert result[0][0] == '_rowName'
self.result = result[1:]
self._mapping = {
name: idx for idx, name in enumerate(result[0])
}
def __getitem__(self, idx):
return self.__class__.MappedRow(self._mapping, self.result[idx])
mldb.log("Creating a demo dataset")
ds = mldb.create_dataset({'id' : 'ds', 'type' : 'sparse.mutable'})
ds.record_row('user1', [['colD', 'd', 0], ['colZ', 'zz', 0], ['colA', 'a', 0]])
ds.commit()
query = "SELECT colZ, colD, colA FROM ds"
res = mldb.query("SELECT colZ, colD, colA FROM ds")
mldb.log(query)
mldb.log(res[0])
mldb.log("As you can see, the following result is not in the same order as "
"the query.")
mapped_res = TableQueryResultMapper(res)
mldb.log("Example usage of the mapper.")
mldb.log("Dot notation: mapped_res[1]._rowName")
mldb.log(mapped_res[0]._rowName)
mldb.log("Bracket notation: mapped_res[1]['colD']")
mldb.log(mapped_res[0]['colD'])
request.set_return("success")
|
terrascript/data/external.py | mjuenema/python-terrascript | 507 | 11095153 | <gh_stars>100-1000
# terrascript/data/external.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:16:09 UTC)
#
# For imports without namespace, e.g.
#
# >>> import terrascript.data.external
#
# instead of
#
# >>> import terrascript.data.hashicorp.external
#
# This is only available for 'official' and 'partner' providers.
from terrascript.data.hashicorp.external import *
|
imagetagger/imagetagger/administration/views.py | jbargu/imagetagger | 212 | 11095166 | from django.shortcuts import render, get_object_or_404, redirect
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib import messages
from django.db import transaction
from .forms import AnnotationTypeCreationForm, AnnotationTypeEditForm
from imagetagger.annotations.models import Annotation, AnnotationType
@staff_member_required
def annotation_types(request):
return render(request, 'administration/annotation_type.html', {
'annotation_types': AnnotationType.objects.all().order_by('name'),
'create_form': AnnotationTypeCreationForm,
})
@staff_member_required
def annotation_type(request, annotation_type_id):
selected_annotation_type = get_object_or_404(AnnotationType, id=annotation_type_id)
return render(request, 'administration/annotation_type.html', {
'annotation_types': AnnotationType.objects.all().order_by('name'),
'annotation_type': selected_annotation_type,
'vector_type_name': AnnotationType.get_vector_type_name(selected_annotation_type.vector_type),
'create_form': AnnotationTypeCreationForm(),
'edit_form': AnnotationTypeEditForm(instance=selected_annotation_type)
})
@staff_member_required
def create_annotation_type(request):
if request.method == 'POST':
form = AnnotationTypeCreationForm(request.POST)
if form.is_valid():
if AnnotationType.objects.filter(name=form.cleaned_data.get('name')).exists():
form.add_error(
'name',
_('The name is already in use by an annotation type.'))
else:
with transaction.atomic():
type = form.save()
messages.success(request, _('The annotation type was created successfully.'))
return redirect(reverse('administration:annotation_type', args=(type.id,)))
else:
return redirect(reverse('administration:annotation_types'))
@staff_member_required
def edit_annotation_type(request, annotation_type_id):
selected_annotation_type = get_object_or_404(AnnotationType, id=annotation_type_id)
if request.method == 'POST':
if not request.POST['name'] == selected_annotation_type.name and AnnotationType.objects.filter(name=request.POST['name']).exists():
messages.error(request, _('The name is already in use by an annotation type.'))
else:
selected_annotation_type.name = request.POST['name']
selected_annotation_type.active = 'active' in request.POST.keys()
selected_annotation_type.enable_concealed = 'enable_concealed' in request.POST.keys()
selected_annotation_type.enable_blurred = 'enable_blurred' in request.POST.keys()
selected_annotation_type.save()
messages.success(request, _('The annotation type was edited successfully.'))
return redirect(reverse('administration:annotation_type', args=(annotation_type_id, )))
@staff_member_required
def migrate_bounding_box_to_0_polygon(request, annotation_type_id):
selected_annotation_type = get_object_or_404(AnnotationType, id=annotation_type_id)
if selected_annotation_type.vector_type is AnnotationType.VECTOR_TYPE.BOUNDING_BOX:
annotations = Annotation.objects.filter(annotation_type=selected_annotation_type)
for annotation in annotations:
annotation.verifications.all().delete()
if annotation.vector:
annotation.vector = {
'x1': annotation.vector['x1'],
'y1': annotation.vector['y1'],
'x2': annotation.vector['x2'],
'y2': annotation.vector['y1'],
'x3': annotation.vector['x2'],
'y3': annotation.vector['y2'],
'x4': annotation.vector['x1'],
'y4': annotation.vector['y2'],
}
annotation.save()
selected_annotation_type.vector_type = AnnotationType.VECTOR_TYPE.POLYGON
selected_annotation_type.node_count = 0
selected_annotation_type.save()
return redirect(reverse('administration:annotation_type', args=(annotation_type_id, )))
@staff_member_required
def migrate_bounding_box_to_4_polygon(request, annotation_type_id):
selected_annotation_type = get_object_or_404(AnnotationType, id=annotation_type_id)
if selected_annotation_type.vector_type is AnnotationType.VECTOR_TYPE.BOUNDING_BOX:
annotations = Annotation.objects.filter(annotation_type=selected_annotation_type)
for annotation in annotations:
annotation.verifications.all().delete()
if annotation.vector:
annotation.vector = {
'x1': annotation.vector['x1'],
'y1': annotation.vector['y1'],
'x2': annotation.vector['x2'],
'y2': annotation.vector['y1'],
'x3': annotation.vector['x2'],
'y3': annotation.vector['y2'],
'x4': annotation.vector['x1'],
'y4': annotation.vector['y2'],
}
annotation.save()
selected_annotation_type.vector_type = AnnotationType.VECTOR_TYPE.POLYGON
selected_annotation_type.node_count = 4
selected_annotation_type.save()
return redirect(reverse('administration:annotation_type', args=(annotation_type_id, )))
|
src/genie/libs/parser/ios/show_service.py | nujo/genieparser | 204 | 11095184 | <filename>src/genie/libs/parser/ios/show_service.py<gh_stars>100-1000
'''show_service.py
IOS parser for the following show command
* show service-group state
* show service-group stats
'''
# import iosxe parser
from genie.libs.parser.iosxe.show_service import \
ShowServiceGroupState as ShowServiceGroupState_iosxe, \
ShowServiceGroupStats as ShowServiceGroupStats_iosxe, \
ShowServiceGroupTrafficStats as ShowServiceGroupTrafficStats_iosxe
class ShowServiceGroupState(ShowServiceGroupState_iosxe):
'''Parser for show service-group state'''
pass
class ShowServiceGroupStats(ShowServiceGroupStats_iosxe):
'''Parser for show service-group stats'''
pass
class ShowServiceGroupTrafficStats(ShowServiceGroupTrafficStats_iosxe):
"""Parser for :
show service-group traffic-stats
show service-group traffic-stats <group> """
pass |
tools/site_compare/scrapers/__init__.py | zealoussnow/chromium | 14,668 | 11095249 | #!/usr/bin/env python
# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Selects the appropriate scraper for a given browser and version."""
from __future__ import print_function
import types
# TODO(jhaas): unify all optional scraper parameters into kwargs
def GetScraper(browser):
"""Given a browser and an optional version, returns the scraper module.
Args:
browser: either a string (browser name) or a tuple (name, version)
Returns:
module
"""
if type(browser) == types.StringType: browser = (browser, None)
package = __import__(browser[0], globals(), locals(), [''])
module = package.GetScraper(browser[1])
if browser[1] is not None: module.version = browser[1]
return module
# if invoked rather than imported, do some tests
if __name__ == "__main__":
print(GetScraper("IE"))
|
alipay/aop/api/response/AlipayCommerceDataScenicMappingQueryResponse.py | antopen/alipay-sdk-python-all | 213 | 11095273 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.ScenicAuditResponse import ScenicAuditResponse
class AlipayCommerceDataScenicMappingQueryResponse(AlipayResponse):
def __init__(self):
super(AlipayCommerceDataScenicMappingQueryResponse, self).__init__()
self._scenic_audit_response = None
@property
def scenic_audit_response(self):
return self._scenic_audit_response
@scenic_audit_response.setter
def scenic_audit_response(self, value):
if isinstance(value, ScenicAuditResponse):
self._scenic_audit_response = value
else:
self._scenic_audit_response = ScenicAuditResponse.from_alipay_dict(value)
def parse_response_content(self, response_content):
response = super(AlipayCommerceDataScenicMappingQueryResponse, self).parse_response_content(response_content)
if 'scenic_audit_response' in response:
self.scenic_audit_response = response['scenic_audit_response']
|
inflate/pack_exe.py | bocke/Amiga-Stuff | 153 | 11095283 | <filename>inflate/pack_exe.py
# pack_exe.py
#
# Convert an Amiga load file into a self-unpacking executable.
#
# Written & released by <NAME> <<EMAIL>>
#
# This is free and unencumbered software released into the public domain.
# See the file COPYING for more details, or visit <http://unlicense.org>.
import crcmod.predefined
import struct, sys, os
# The unpacker code fragments and the degzip binary are in the
# same directory as the script.
scriptdir = os.path.split(os.path.abspath(__file__))[0] + '/'
# Hunk/Block identifiers.
HUNK_HEADER = 0x3f3
HUNK_CODE = 0x3e9
HUNK_DATA = 0x3ea
HUNK_BSS = 0x3eb
HUNK_RELOC32 = 0x3ec
HUNK_END = 0x3f2
# Dictionary of Hunk/Block names.
hname = {
HUNK_CODE: 'Code',
HUNK_DATA: 'Data',
HUNK_BSS: 'BSS ',
}
memname = {
0: '',
1: 'Chip',
2: 'Fast',
3: 'Extra-Attr',
}
# Minimum number of bytes that compression must save.
MIN_COMPRESSION = 8
# Command for creating gzip files.
GZIP = "zopfli"
#GZIP = "gzip -fk9"
# Prefix for intermediate (temporary) files.
PREFIX = '_pack'
# Relocation table:
# u16 hunk (0xffff = sentinel)
# u16 nr (0 = sentinel)
# u16 target
# u8 delta1[, delta3[3]] (delta3 iff delta1==0)
# delta = (deltaN + 1) * 2
relocs = bytes()
# List of allocation sizes and attributes (HUNK_HEADER).
allocs = []
# DEFLATE stream size (in bytes) for each hunk.
# If 0 then that hunk is stored uncompressed.
stream_sizes = []
# List of output hunks
hunks = []
# Summary information about each hunk's processing
infos = []
# Delta-encode a list of Amiga RELOC32 offsets:
# Delta_n = (Off_n - Off_n-1) / 2 - 1; Off_0 = -4
def process_relocs(target, offs):
global relocs
offs.sort()
relocs += struct.pack('>2H', len(offs), target)
p = -4
for o in offs:
assert o > p and -(o-p)&1 == 0
delta = ((o - p) >> 1) - 1
assert 0 <= delta <= ((1<<24)-1)
relocs += struct.pack('>B' if 1 <= delta <= 255 else '>I', delta)
p = o
relocs += bytes(-len(relocs)&1)
# Get the (one) position-independent code hunk from an Amiga load file.
def get_code(name):
with open(scriptdir + name, 'rb') as f:
(id, x, nr, first, last) = struct.unpack('>5I', f.read(5*4))
assert id == HUNK_HEADER and x == 0
assert nr == 1 and first == 0 and last == 0
(x, id, nr) = struct.unpack('>3I', f.read(3*4))
assert id == HUNK_CODE and nr == x
code = bytes(f.read(nr * 4))
(id,) = struct.unpack('>I', f.read(4))
assert id == HUNK_END
#print('"%s": %u bytes (%u longs)' % (name, len(code), len(code)//4))
return code
# Compress the given raw byte sequence.
def pack(raw):
# Compress to a DEFLATE stream.
with open(PREFIX, 'wb') as f:
f.write(raw)
os.system(GZIP + ' ' + PREFIX)
os.system(scriptdir + 'degzip -H ' + PREFIX + '.gz ' + PREFIX + '.raw'
' >/dev/null')
with open(PREFIX+'.raw', 'rb') as f:
packed = f.read()
(inb, outb, crc, leeway) = struct.unpack('>2I2H', packed[:12])
# Extract the DEFLATE stream and check the header's length fields.
inb -= 14
packed = packed[12:-2]
assert inb == len(packed) and outb == len(raw)
# Check the header CRC.
crc16 = crcmod.predefined.Crc('crc-ccitt-false')
crc16.update(raw)
assert crc == crc16.crcValue
# Pad the DEFLATE stream.
padding = -len(packed) & 3
packed += bytes(padding)
# Extend and pad leeway.
leeway += padding
leeway += -leeway & 3
return (packed, crc, leeway)
# Read next hunk from the input file, compress it if appropriate, and appends
# the encoded output hunk to hunks[], updates allocs[i], and appends
# delta-encoded RELOC32 blocks to relocs[].
def process_hunk(f, i):
global allocs, stream_sizes, relocs, hunks, infos
old_pos = f.tell()
alloc = _alloc = (allocs[i] & 0x3fffffff) * 4
first_reloc = True # Have we seen a RELOC32 block yet?
seen_dat = False # Have we seen CODE/DATA/BSS yet?
hunk = bytes() # Full encoding of this hunk
while True:
(_id,) = struct.unpack('>I', f.read(4))
id = _id & 0x3fffffff
if id == HUNK_CODE or id == HUNK_DATA:
if seen_dat:
f.seek(-4, os.SEEK_CUR)
break # Done with this hunk!
seen_dat = id
(_nr,) = struct.unpack('>I', f.read(4))
nr = _nr & 0x3fffffff
raw = f.read(nr*4)
assert alloc >= len(raw)
(packed, crc, leeway) = pack(raw)
if i != 0 and nr*4 < len(packed)+MIN_COMPRESSION:
# This hunk is not worth compressing. Store it as is.
packed = raw
stream_sizes.append(0) # No compression
else:
if i == 0:
# First hunk must be code: we inject our entry/exit code
assert id == HUNK_CODE
packed = get_code('depacker_entry') + packed
# Allocate explicit extra space for the final exit code
# This must always extend the allocation as these bytes
# will not be zeroed before we jump to the original exe.
alloc += 8
# Extend the hunk allocation for depacker leeway.
# We also deal with compression making the hunk longer here
# (hunk 0 only, as other hunks we would store uncompressed).
alloc = max(alloc, len(raw) + leeway, len(packed))
stream_sizes.append(len(packed)) # DEFLATE stream size
# Write out this block.
hunk += struct.pack('>2I', id, len(packed)//4) + packed
elif id == HUNK_BSS:
assert i != 0
if seen_dat:
f.seek(-4, os.SEEK_CUR)
break # Done with this hunk!
seen_dat = id
(_nr,) = struct.unpack('>I', f.read(4))
nr = _nr & 0x3fffffff
assert alloc >= nr*4
stream_sizes.append(0) # No compression
# Write out this block as is.
hunk += struct.pack('>2I', id, alloc//4)
elif id == HUNK_END:
assert seen_dat
break # Done with this hunk!
elif id == HUNK_RELOC32:
while True:
(nr,) = struct.unpack('>I', f.read(4))
if nr == 0:
break # Done with RELOC32
(h,) = struct.unpack('>I', f.read(4))
offs = list(struct.unpack('>%dI' % nr, f.read(nr*4)))
if first_reloc:
# Write out this hunk's number.
relocs += struct.pack('>H', i)
first_reloc = False
# Write out the target hunk number and delta-encoded offsets.
process_relocs(h, offs)
else:
print("Unexpected hunk %04x" % (id))
assert False
# Generate HUNK_END (optional?)
# hunk += struct.pack('>I', HUNK_END)
if not first_reloc:
# There were relocations for this hunk: Write the sentinel value.
relocs += struct.pack('>H', 0)
# Update the allocation size for this hunk.
assert alloc&3 == 0
allocs[i] &= 0xc0000000
allocs[i] |= alloc // 4
# Add this hunk to the global list for later write-out.
hunks.append(hunk)
infos.append((seen_dat, _alloc, alloc, f.tell()-old_pos, len(hunk)))
# Generate the final hunk, which contains the depacker, the packed-stream
# size table, the delta-encoded relocation tables, and the relocator.
# Everything except the depacker itself is stored compressed.
def generate_final_hunk():
global allocs, relocs, hunks, infos
depacker = get_code('depacker_main')
# Generate the raw byte sequence for compression:
# 1. Table of stream sizes;
stream_sizes.append(0) # Sentinel value for the stream-size table
raw = struct.pack('>%dI' % len(stream_sizes), *stream_sizes)
# 2. Relocation and epilogue code; and 3. Relocation tables.
raw += get_code('depacker_packed') + relocs
# Ensure everything is a longword multiple.
raw += bytes(-len(raw) & 3)
assert len(depacker)&3 == 0 and len(raw)&3 == 0
# Allocation size covers the depacker and the depacked stream.
alloc = len(depacker) + 4 + len(raw)
# Compress the raw byte sequence.
(packed, crc, leeway) = pack(raw)
if len(raw) < len(packed)+MIN_COMPRESSION:
# Not worth compressing, so don't bother.
hunk = depacker + bytes(4) + raw # 'bytes(4)' means not packed
else:
# Compress everything except the depacker itself (and the
# longword containing the size of the compressed stream).
packed_len = len(depacker) + len(packed)
alloc += leeway # Include depacker leeway in the hunk allocation
hunk = depacker + struct.pack('>I', len(packed)) + packed
assert alloc&3 == 0 and len(hunk)&3 == 0
# Add the hunk header/footer metadata to the code block.
hunk = struct.pack('>2I', HUNK_CODE, len(hunk)//4) + hunk
hunk += struct.pack('>I', HUNK_END)
# Add this hunk and its allocation size to the global lists.
hunks.append(hunk)
allocs.append(alloc//4)
infos.append((0, 0, alloc, 0, len(hunk)))
def process(f, out_f):
global allocs, relocs, hunks
# Read the load-file header of the input file, including every
# hunk's original allocation size.
(id, x, nr, first, last) = struct.unpack('>5I', f.read(5*4))
assert id == HUNK_HEADER and x == 0
assert first == 0 and last == nr-1 and nr > 0
allocs = list(struct.unpack('>%dI' % nr, f.read(nr*4)))
# Read and process each input hunk.
for i in range(nr):
process_hunk(f, i)
# Append the final sentinel value to the relocation table.
relocs += struct.pack('>H', 0xffff)
# Generate the depacker hunk.
generate_final_hunk()
nr += 1
# Remove intermediate temporary files.
os.system('rm ' + PREFIX + '*')
# Write out the compressed executable: HUNK_HEADER, then each hunk in turn.
out_f.write(struct.pack('>5I', HUNK_HEADER, 0, nr, 0, nr-1))
out_f.write(struct.pack('>%dI' % nr, *allocs))
[out_f.write(hunk) for hunk in hunks]
# Return the original- and compressed-file sizes to the caller.
f.seek(0, os.SEEK_END)
in_sz = f.tell()
out_sz = out_f.tell()
return (in_sz, out_sz)
def usage(argv):
print("%s input-file output-file" % argv[0])
sys.exit(1)
def main(argv):
if sys.version_info[0] < 3:
print("** Requires Python 3")
usage(argv)
if len(argv) != 3:
usage(argv)
(in_sz, out_sz) = process(open(argv[1], 'rb'), open(argv[2], 'wb'))
tot_old_alloc = tot_new_alloc = tot_old_store = tot_new_store = 0
for (id, old_alloc, new_alloc, old_store, new_store) in infos:
tot_old_alloc += old_alloc
tot_new_alloc += new_alloc
tot_old_store += old_store
tot_new_store += new_store
print(' [Nr] Type File ( delta, %) Memory (delta)')
print('-----------------------------------------------------------')
# Account for HUNK_HEADER: We grew it by 4 bytes (one extra hunk).
hlen = (len(infos)+5)*4
tot_old_store += hlen-4
tot_new_store += hlen
print(' [--] Header %7u (%+8u, %+5.1f%%)' % (hlen, 4, 400/(hlen-4)))
# Stats summary for all the original hunks.
for i in range(len(infos)-1):
(id, old_alloc, new_alloc, old_store, new_store) = infos[i]
if new_store != 0:
print(' [%02u] %s %9u (%+8u, %+5.1f%%) %7u (%+5u) %s' %
(i, hname[id], new_store, new_store-old_store,
(new_store-old_store)*100/old_store,
new_alloc, new_alloc-old_alloc,
memname[allocs[i] >> 30]))
# Summarise the new depacker/relocation hunk.
(id, old_alloc, new_alloc, old_store, new_store) = infos[-1]
print(' [%02u] DEPACK %7u %20s %7u' %
(len(infos)-1, new_store, '', new_alloc))
# Print totals. Note that extra allocation reduces after unpacking:
# The depacker/relocation hunk is freed before running the original exe.
print('-----------------------------------------------------------')
print('%20u (%+8u, %+5.1f%%) %7u (%+5u)' %
(tot_new_store, tot_new_store-tot_old_store,
(tot_new_store-tot_old_store)*100/tot_old_store,
tot_new_alloc, tot_new_alloc-tot_old_alloc))
print('After depack: %25s %7u (%+5u)' %
('', tot_new_alloc-new_alloc,
tot_new_alloc-new_alloc-tot_old_alloc))
# A very final summary.
print('\n** RESULT:\n** Original: {} = {} bytes\n'
'** Compressed: {} = {} bytes\n'
'** Shrunk {} bytes ({:.1f}%)'
.format(argv[1], in_sz, argv[2], out_sz, in_sz - out_sz,
(in_sz-out_sz)*100/in_sz))
if __name__ == "__main__":
main(sys.argv)
|
genrate_fragments/step1_clean_triple.py | YangLingWHU/gAnswer | 328 | 11095287 | import re
'''
Step 1: Clean the triple file. In the dbpedia case, we just need the part of resource URI that indicate entity/type/predicate names.
'''
fileName = []#List of triple files to be process
notRdf = open('./notRdf.txt','w')#Record the lines that refers to a type but not rdf:type
for index2,fname in enumerate(fileName):
f = open('./'+fname)
triple = open('output triple files here','w')
prefix_f = open('output prefix files here','w')# save the prefix in files in case of it may be useful in the future.
i = 0
count = 0
prefix_set = set()
for line in f:
if line[0] != '<':
print(i)
i = i + 1
count += 1
continue
line = line[:-3].replace('> <','>$-$-$<').replace('> "','>$-$-$"')
line = line.split('$-$-$')
if i==0:
i += 1
continue
new_line=[]
if "type>" in line[1]:
if "rdf" not in line[1]:
notRdf.write(str(line)+'\n')
continue
for index,item in enumerate(line):
if not item:
count +=1
break
if item[0]=='<':
pos = item.rfind('/')
word = item[pos+1:-1].split("#")
if len(word)<2:
new_line.append('<'+word[0]+'>')
else:
new_line.append('<'+word[1]+'>')
if index == 1:
tmp = new_line[1][1:len(new_line[1])-1]
pos2 = line[1].rfind(tmp)
prefix = line[1][1:pos2-1]
prefix_set.add(tmp + '^^^'+prefix+'\n')
continue
elif item.count('"') >=2:
item = item.split('^^')[0].split('@')[0]
pattern = re.compile('"(.*)"')
word = '"'+''.join(pattern.findall(item))+'"'
new_line.append(word)
continue
else:
print(i)
i += 1
#print('\t'.join(new_line))
if i%1000000==0:
print("%d:%d"%(8,i))
triple.write('\t'.join(new_line)+'\n')
for item in prefix_set:
prefix_f.write(item)
f.close()
triple.close()
prefix_f.close()
|
tests/types/test_geometry.py | peterandluc/PyHDB | 332 | 11095302 | <gh_stars>100-1000
from io import BytesIO
import random
#
import pytest
from pyhdb.protocol import types
# ########################## Test value unpacking #####################################
@pytest.mark.parametrize("given,expected", [
(b"\xFF", None),
(b"\x2d\x50\x4f\x49\x4e\x54\x20\x28\x31\x2e\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x20\x32\x2e\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x29",
"POINT (1.0000000000000000 2.0000000000000000)"),
(b"\x59\x4c\x49\x4e\x45\x53\x54\x52\x49\x4e\x47\x20\x28\x31\x2e\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x20\x32\x2e" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x2c" + \
b"\x20\x32\x2e\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x20\x31\x2e\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x30\x29",
"LINESTRING (1.0000000000000000 2.0000000000000000, " + \
"2.0000000000000000 1.0000000000000000)"),
(b"\xa7\x50\x4f\x4c\x59\x47\x4f\x4e\x20\x28\x28\x31\x2e\x30\x30\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x20\x31\x2e\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x2c\x20\x30" + \
b"\x2e\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x20\x30\x2e\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x2c\x20\x2d\x31\x2e\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x20\x31\x2e\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x2c\x20\x31\x2e\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x20\x31\x2e\x30\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x29\x29",
"POLYGON ((1.0000000000000000 1.0000000000000000, " + \
"0.0000000000000000 0.0000000000000000, " + \
"-1.0000000000000000 1.0000000000000000, " + \
"1.0000000000000000 1.0000000000000000))"),
(b"\x32\x4d\x55\x4c\x54\x49\x50\x4f\x49\x4e\x54\x20\x28\x31\x2e\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x20\x32\x2e" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x29",
"MULTIPOINT (1.0000000000000000 2.0000000000000000)"),
(b"\x60\x4d\x55\x4c\x54\x49\x4c\x49\x4e\x45\x53\x54\x52\x49\x4e\x47\x20" + \
b"\x28\x28\x31\x2e\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x20\x32\x2e\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x30\x30\x2c\x20\x32\x2e\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x20\x31\x2e\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x29\x29",
"MULTILINESTRING ((1.0000000000000000 2.0000000000000000, " + \
"2.0000000000000000 1.0000000000000000))"),
(b"\xae\x4d\x55\x4c\x54\x49\x50\x4f\x4c\x59\x47\x4f\x4e\x20\x28\x28\x28" + \
b"\x31\x2e\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x20\x31\x2e\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x2c\x20\x30\x2e\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x20\x30\x2e\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x2c\x20\x2d\x31\x2e\x30\x30\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x20\x31\x2e\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x2c\x20\x31" + \
b"\x2e\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x20\x31\x2e\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x29\x29\x29",
"MULTIPOLYGON (((1.0000000000000000 1.0000000000000000, " + \
"0.0000000000000000 0.0000000000000000, " + \
"-1.0000000000000000 1.0000000000000000, " + \
"1.0000000000000000 1.0000000000000000)))"),
])
def test_unpack_geometry_wkt(given, expected):
given = BytesIO(given)
assert types.Geometry.from_resultset(given) == expected
# ########################## Test value packing #####################################
@pytest.mark.parametrize("given,expected", [
(None, b"\x1d\xFF", ),
("POINT (1.0000000000000000 2.0000000000000000)",
b"\x1d\x2d\x50\x4f\x49\x4e\x54\x20\x28\x31\x2e\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x20\x32\x2e\x30\x30\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x29"),
("LINESTRING (1.0000000000000000 2.0000000000000000, " + \
"2.0000000000000000 1.0000000000000000)",
b"\x1d\x59\x4c\x49\x4e\x45\x53\x54\x52\x49\x4e\x47\x20\x28\x31\x2e\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x20\x32" + \
b"\x2e\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x2c\x20\x32\x2e\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x20\x31\x2e\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x30\x30\x29"),
("POLYGON ((1.0000000000000000 1.0000000000000000, " + \
"0.0000000000000000 0.0000000000000000, " + \
"-1.0000000000000000 1.0000000000000000, " + \
"1.0000000000000000 1.0000000000000000))",
b"\x1d\xa7\x50\x4f\x4c\x59\x47\x4f\x4e\x20\x28\x28\x31\x2e\x30\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x20\x31\x2e\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x2c\x20" + \
b"\x30\x2e\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x20\x30\x2e\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x2c\x20\x2d\x31\x2e\x30\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x20\x31\x2e\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x2c\x20\x31\x2e\x30\x30\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x20\x31\x2e\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x29\x29"),
("MULTIPOINT (1.0000000000000000 2.0000000000000000)",
b"\x1d\x32\x4d\x55\x4c\x54\x49\x50\x4f\x49\x4e\x54\x20\x28\x31\x2e\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x20\x32" + \
b"\x2e\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x29"),
("MULTILINESTRING ((1.0000000000000000 2.0000000000000000, " + \
"2.0000000000000000 1.0000000000000000))",
b"\x1d\x60\x4d\x55\x4c\x54\x49\x4c\x49\x4e\x45\x53\x54\x52\x49\x4e\x47" + \
b"\x20\x28\x28\x31\x2e\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x30\x20\x32\x2e\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x2c\x20\x32\x2e\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x20\x31\x2e\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x29\x29"),
("MULTIPOLYGON (((1.0000000000000000 1.0000000000000000, " + \
"0.0000000000000000 0.0000000000000000, " + \
"-1.0000000000000000 1.0000000000000000, " + \
"1.0000000000000000 1.0000000000000000)))",
b"\x1d\xae\x4d\x55\x4c\x54\x49\x50\x4f\x4c\x59\x47\x4f\x4e\x20\x28\x28" + \
b"\x28\x31\x2e\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x20\x31\x2e\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x30\x2c\x20\x30\x2e\x30\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x20\x30\x2e\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x2c\x20\x2d\x31\x2e\x30\x30\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x20\x31\x2e\x30" + \
b"\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x2c\x20" + \
b"\x31\x2e\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x20\x31\x2e\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30" + \
b"\x30\x30\x30\x29\x29\x29"),
])
def test_pack_geometry_wkt(given, expected):
assert types.Geometry.prepare(given) == expected
# #############################################################################################################
# Real HANA interaction with geormetry (integration tests)
# #############################################################################################################
import tests.helper
TABLE = 'PYHDB_TEST_GEOMETRY'
TABLE_POINT = TABLE + "_POINT"
TABLE_GEOMETRY = TABLE + "_GEOMETRY"
TABLE_FIELDS_POINT = "point ST_POINT NOT NULL"
TABLE_FIELDS_GEOMETRY = "geo ST_GEOMETRY NOT NULL"
@pytest.fixture
def test_table_point(request, connection):
tests.helper.create_table_fixture(request, connection, TABLE_POINT,
TABLE_FIELDS_POINT, column_table=True)
@pytest.fixture
def test_table_geometry(request, connection):
tests.helper.create_table_fixture(request, connection, TABLE_GEOMETRY,
TABLE_FIELDS_GEOMETRY, column_table=True)
@pytest.mark.hanatest
def test_insert_point(connection, test_table_point):
"""Insert spatial point into table"""
cursor = connection.cursor()
point_x = random.randint(-100.0, 100.0)
point_y = random.randint(-100.0, 100.0)
wkt_string = "POINT(%f %f)" % (point_x, point_y)
cursor.execute("insert into %s (point) values (:1)" % TABLE_POINT, [wkt_string])
connection.commit()
cursor = connection.cursor()
row = cursor.execute('select point.ST_X(), point.ST_Y() from %s' % TABLE_POINT).fetchone()
assert row[0] == point_x
assert row[1] == point_y
@pytest.mark.hanatest
def test_insert_linestring(connection, test_table_geometry):
"""Insert spatial linestring into table"""
cursor = connection.cursor()
point1_x = random.randint(-100.0, 100.0)
point1_y = random.randint(-100.0, 100.0)
point2_x = random.randint(-100.0, 100.0)
point2_y = random.randint(-100.0, 100.0)
wkt_string = "LINESTRING(%f %f, %f %f)" % (point1_x, point1_y, point2_x, point2_y)
cursor.execute("insert into %s (geo) values (:1)" % TABLE_GEOMETRY, [wkt_string])
connection.commit()
cursor = connection.cursor()
sql = """
Select geo.ST_StartPoint().ST_X(), geo.ST_StartPoint().ST_Y(),
geo.ST_EndPoint().ST_X(), geo.ST_EndPoint().ST_Y()
From %s
"""
row = cursor.execute(sql % TABLE_GEOMETRY).fetchone()
assert row[0] == point1_x
assert row[1] == point1_y
assert row[2] == point2_x
assert row[3] == point2_y
@pytest.mark.hanatest
def test_insert_polygon(connection, test_table_geometry):
"""Insert spatial polygon into table"""
cursor = connection.cursor()
# The edges of a polygon can not cross. Therefore we build an arbitrary quadtrangle.
point1_x = random.randint(0, 100.0)
point1_y = random.randint(0, 100.0)
point2_x = random.randint(0, 100.0)
point2_y = random.randint(-100.0, 0)
point3_x = random.randint(-100.0, 0)
point3_y = random.randint(-100.0, 0)
point4_x = random.randint(-100.0, 0)
point4_y = random.randint(0, 100.0)
wkt_string = "POLYGON((%f %f, %f %f, %f %f, %f %f, %f %f))" % (
point1_x, point1_y, point2_x, point2_y, point3_x, point3_y,
point4_x, point4_y, point1_x, point1_y
)
cursor.execute("insert into %s (geo) values (:1)" % TABLE_GEOMETRY, [wkt_string])
connection.commit()
cursor = connection.cursor()
# We don't want to check all points of the polygon.
# We will only check the minimal and maximal values.
sql = """
Select geo.ST_XMin(), geo.ST_XMax(), geo.ST_YMin(), geo.ST_YMax()
From %s
"""
row = cursor.execute(sql % TABLE_GEOMETRY).fetchone()
assert row[0] == min(point1_x, point2_x, point3_x, point4_x)
assert row[1] == max(point1_x, point2_x, point3_x, point4_x)
assert row[2] == min(point1_y, point2_y, point3_y, point4_y)
assert row[3] == max(point1_y, point2_y, point3_y, point4_y)
|
visualization/view_scene.py | PratyushaMaiti/gtsfm | 122 | 11095303 | <reponame>PratyushaMaiti/gtsfm<filename>visualization/view_scene.py<gh_stars>100-1000
"""
Script to render a GTSFM scene using either Open3d or Mayavi mlab.
Authors: <NAME>
"""
import argparse
import os
from pathlib import Path
import numpy as np
from gtsam import Rot3, Pose3
import gtsfm.utils.io as io_utils
#from visualization.mayavi_vis_utils import draw_scene_mayavi
from visualization.open3d_vis_utils import draw_scene_open3d
REPO_ROOT = Path(__file__).parent.parent.resolve()
def compute_point_cloud_center_robust(point_cloud: np.ndarray) -> np.ndarray:
"""Robustly estimate the point cloud center.
Args:
point_cloud: array of shape (N,3) representing 3d points.
Returns:
mean_pt: coordinates of central point, ignoring outliers.
"""
ranges = np.linalg.norm(point_cloud, axis=1)
outlier_thresh = np.percentile(ranges, 75)
mean_pt = point_cloud[ranges < outlier_thresh].mean(axis=0)
return mean_pt
def view_scene(args: argparse.Namespace) -> None:
"""Read GTSFM output from .txt files and render the scene to the GUI.
We also zero-center the point cloud, and transform camera poses to a new
world frame, where the point cloud is zero-centered.
Args:
args: rendering options.
"""
points_fpath = f"{args.output_dir}/points3D.txt"
images_fpath = f"{args.output_dir}/images.txt"
cameras_fpath = f"{args.output_dir}/cameras.txt"
wTi_list, img_fnames = io_utils.read_images_txt(images_fpath)
calibrations = io_utils.read_cameras_txt(cameras_fpath)
if len(calibrations) == 1:
calibrations = calibrations * len(img_fnames)
point_cloud, rgb = io_utils.read_points_txt(points_fpath)
mean_pt = compute_point_cloud_center_robust(point_cloud)
# Zero-center the point cloud (about estimated center)
zcwTw = Pose3(Rot3(np.eye(3)), -mean_pt)
# expression below is equivalent to applying zcwTw.transformFrom() to each world point
point_cloud -= mean_pt
is_nearby = np.linalg.norm(point_cloud, axis=1) < args.max_range
point_cloud = point_cloud[is_nearby]
rgb = rgb[is_nearby]
for i in range(len(wTi_list)):
wTi_list[i] = zcwTw.compose(wTi_list[i])
if args.rendering_library == "open3d":
draw_scene_open3d(point_cloud, rgb, wTi_list, calibrations, args)
# elif args.rendering_library == "mayavi":
# draw_scene_mayavi(point_cloud, rgb, wTi_list, calibrations, args)
else:
raise RuntimeError("Unsupported rendering library")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Visualize GTSFM result with Mayavi or Open3d.")
parser.add_argument(
"--rendering_library",
type=str,
default="open3d",
choices=["mayavi", "open3d"],
help="3d rendering library to use.",
)
parser.add_argument(
"--output_dir",
type=str,
default=os.path.join(REPO_ROOT, "results", "ba_output"),
help="Path to a directory containing GTSFM output. "
"This directory should contain 3 files: cameras.txt, images.txt, and points3D.txt",
)
parser.add_argument(
"--point_rendering_mode",
type=str,
default="point",
choices=["point", "sphere"],
help="Render each 3d point as a `point` (optimized in Open3d) or `sphere` (optimized in Mayavi).",
)
parser.add_argument(
"--max_range",
type=float,
default=20,
help="maximum range of points (from estimated point cloud center) to render.",
)
parser.add_argument(
"--sphere_radius",
type=float,
default=0.1,
help="if points are rendered as spheres, then spheres are rendered with this radius.",
)
args = parser.parse_args()
if args.point_rendering_mode == "point" and args.rendering_library == "mayavi":
raise RuntimeError("Mayavi only supports rendering points as spheres.")
view_scene(args)
|
h2o-docs/src/booklets/v2_2015/source/GLM_Vignette_code_examples/glm_gamma_example.py | ahmedengu/h2o-3 | 6,098 | 11095340 | import h2o
from h2o.estimators.glm import H2OGeneralizedLinearEstimator
h2o.init()
h2o_df = h2o.import_file("http://h2o-public-test-data.s3.amazonaws.com/smalldata/prostate/prostate.csv")
gamma_inverse = H2OGeneralizedLinearEstimator(family = "gamma", link = "inverse")
gamma_inverse.train(y = "DPROS", x = ["AGE","RACE","CAPSULE","DCAPS","PSA","VOL"], training_frame = h2o_df)
gamma_log = H2OGeneralizedLinearEstimator(family = "gamma", link = "log")
gamma_log.train(y="DPROS", x = ["AGE","RACE","CAPSULE","DCAPS","PSA","VOL"], training_frame = h2o_df)
|
jedi/api/errors.py | mrclary/jedi | 641 | 11095366 | """
This file is about errors in Python files and not about exception handling in
Jedi.
"""
def parso_to_jedi_errors(grammar, module_node):
return [SyntaxError(e) for e in grammar.iter_errors(module_node)]
class SyntaxError(object):
"""
Syntax errors are generated by :meth:`.Script.get_syntax_errors`.
"""
def __init__(self, parso_error):
self._parso_error = parso_error
@property
def line(self):
"""The line where the error starts (starting with 1)."""
return self._parso_error.start_pos[0]
@property
def column(self):
"""The column where the error starts (starting with 0)."""
return self._parso_error.start_pos[1]
@property
def until_line(self):
"""The line where the error ends (starting with 1)."""
return self._parso_error.end_pos[0]
@property
def until_column(self):
"""The column where the error ends (starting with 0)."""
return self._parso_error.end_pos[1]
def __repr__(self):
return '<%s from=%s to=%s>' % (
self.__class__.__name__,
self._parso_error.start_pos,
self._parso_error.end_pos,
)
|
pytorch-DRIT-PONO-MS/src/dataset.py | Boyiliee/PONO | 133 | 11095398 | <filename>pytorch-DRIT-PONO-MS/src/dataset.py
import os
import torch.utils.data as data
from PIL import Image
from torchvision.transforms import Compose, Resize, RandomCrop, CenterCrop, RandomHorizontalFlip, ToTensor, Normalize
import random
class dataset_single(data.Dataset):
def __init__(self, opts, setname, input_dim):
self.dataroot = opts.dataroot
images = os.listdir(os.path.join(self.dataroot, opts.phase + setname))
self.img = [os.path.join(self.dataroot, opts.phase + setname, x) for x in images]
self.size = len(self.img)
self.input_dim = input_dim
# setup image transformation
transforms = [Resize((opts.resize_size, opts.resize_size), Image.BICUBIC)]
transforms.append(CenterCrop(opts.crop_size))
transforms.append(ToTensor())
transforms.append(Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]))
self.transforms = Compose(transforms)
print('%s: %d images'%(setname, self.size))
return
def __getitem__(self, index):
data = self.load_img(self.img[index], self.input_dim)
return data
def load_img(self, img_name, input_dim):
img = Image.open(img_name).convert('RGB')
img = self.transforms(img)
if input_dim == 1:
img = img[0, ...] * 0.299 + img[1, ...] * 0.587 + img[2, ...] * 0.114
img = img.unsqueeze(0)
return img
def __len__(self):
return self.size
class dataset_unpair(data.Dataset):
def __init__(self, opts):
self.dataroot = opts.dataroot
# A
images_A = os.listdir(os.path.join(self.dataroot, opts.phase + 'A'))
self.A = [os.path.join(self.dataroot, opts.phase + 'A', x) for x in images_A]
# B
images_B = os.listdir(os.path.join(self.dataroot, opts.phase + 'B'))
self.B = [os.path.join(self.dataroot, opts.phase + 'B', x) for x in images_B]
self.A_size = len(self.A)
self.B_size = len(self.B)
self.dataset_size = max(self.A_size, self.B_size)
self.input_dim_A = opts.input_dim_a
self.input_dim_B = opts.input_dim_b
# setup image transformation
transforms = [Resize((opts.resize_size, opts.resize_size), Image.BICUBIC)]
if opts.phase == 'train':
transforms.append(RandomCrop(opts.crop_size))
else:
transforms.append(CenterCrop(opts.crop_size))
if not opts.no_flip:
transforms.append(RandomHorizontalFlip())
transforms.append(ToTensor())
transforms.append(Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]))
self.transforms = Compose(transforms)
print('A: %d, B: %d images'%(self.A_size, self.B_size))
return
def __getitem__(self, index):
if self.dataset_size == self.A_size:
data_A = self.load_img(self.A[index], self.input_dim_A)
data_B = self.load_img(self.B[random.randint(0, self.B_size - 1)], self.input_dim_B)
else:
data_A = self.load_img(self.A[random.randint(0, self.A_size - 1)], self.input_dim_A)
data_B = self.load_img(self.B[index], self.input_dim_B)
return data_A, data_B
def load_img(self, img_name, input_dim):
img = Image.open(img_name).convert('RGB')
img = self.transforms(img)
if input_dim == 1:
img = img[0, ...] * 0.299 + img[1, ...] * 0.587 + img[2, ...] * 0.114
img = img.unsqueeze(0)
return img
def __len__(self):
return self.dataset_size
|
test/phonon/test_band_structure.py | ladyteam/phonopy | 127 | 11095442 | """Tests for band structure calculation."""
from phonopy.phonon.band_structure import get_band_qpoints
def test_band_structure(ph_nacl):
"""Test band structure calculation by NaCl."""
ph_nacl.run_band_structure(
_get_band_qpoints(), with_group_velocities=False, is_band_connection=False
)
ph_nacl.get_band_structure_dict()
def test_band_structure_gv(ph_nacl):
"""Test band structure calculation with group velocity by NaCl."""
ph_nacl.run_band_structure(
_get_band_qpoints(), with_group_velocities=True, is_band_connection=False
)
ph_nacl.get_band_structure_dict()
def test_band_structure_bc(ph_nacl):
"""Test band structure calculation with band connection by NaCl."""
ph_nacl.run_band_structure(
_get_band_qpoints(), with_group_velocities=False, is_band_connection=True
)
ph_nacl.get_band_structure_dict()
def _get_band_qpoints():
band_paths = [
[[0, 0, 0], [0.5, 0.5, 0.5]],
[[0.5, 0.5, 0], [0, 0, 0], [0.5, 0.25, 0.75]],
]
qpoints = get_band_qpoints(band_paths, npoints=11)
return qpoints
|
couler/tests/daemon_step_test.py | javoweb/couler | 700 | 11095462 | <reponame>javoweb/couler
# Copyright 2021 The Couler Authors. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import couler.argo as couler
from couler.tests.argo_test import ArgoBaseTestCase
class DaemonStepTest(ArgoBaseTestCase):
def setUp(self) -> None:
couler._cleanup()
def tearDown(self):
couler._cleanup()
def test_run_daemon_container(self):
self.assertEqual(len(couler.workflow.templates), 0)
couler.run_container(
image="python:3.6", command="echo $uname", daemon=True
)
self.assertEqual(len(couler.workflow.templates), 1)
template = couler.workflow.get_template(
"test-run-daemon-container"
).to_dict()
self.assertEqual("test-run-daemon-container", template["name"])
self.assertTrue(template["daemon"])
self.assertEqual("python:3.6", template["container"]["image"])
self.assertEqual(["echo $uname"], template["container"]["command"])
def test_run_daemon_script(self):
self.assertEqual(len(couler.workflow.templates), 0)
couler.run_script(
image="python:3.6", command="bash", source="ls", daemon=True
)
self.assertEqual(len(couler.workflow.templates), 1)
template = couler.workflow.get_template(
"test-run-daemon-script"
).to_dict()
self.assertEqual("test-run-daemon-script", template["name"])
self.assertTrue(template["daemon"])
self.assertEqual("python:3.6", template["script"]["image"])
self.assertEqual(["bash"], template["script"]["command"])
self.assertEqual("ls", template["script"]["source"])
|
gslib/tests/test_cloud_api_delegator.py | stanhu/gsutil | 649 | 11095475 | # -*- coding: utf-8 -*-
# Copyright 2020 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for cloud_api_delegator.py."""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from gslib import cloud_api
from gslib import cloud_api_delegator
from gslib import context_config
from gslib import cs_api_map
from gslib.tests import testcase
from gslib.tests.testcase import base
from gslib.tests.util import unittest
from six import add_move, MovedModule
add_move(MovedModule('mock', 'mock', 'unittest.mock'))
from six.moves import mock
class TestCloudApiDelegator(testcase.GsUtilUnitTestCase):
"""Test delegator class for cloud provider API clients."""
@mock.patch.object(context_config, 'get_context_config')
def testRaisesErrorIfMtlsUsedWithXml(self, mock_get_context_config):
mock_context_config = mock.Mock()
mock_context_config.use_client_certificate = True
mock_get_context_config.return_value = mock_context_config
# api_map setup from command_runner.py.
api_map = cs_api_map.GsutilApiMapFactory.GetApiMap(
gsutil_api_class_map_factory=cs_api_map.GsutilApiClassMapFactory,
support_map={'s3': [cs_api_map.ApiSelector.XML]},
default_map={'s3': cs_api_map.ApiSelector.XML})
delegator = cloud_api_delegator.CloudApiDelegator(None, api_map, None, None)
with self.assertRaises(cloud_api.ArgumentException):
delegator.GetApiSelector(provider='s3')
|
machina/apps/forum/migrations/0001_initial.py | OneRainbowDev/django-machina | 572 | 11095485 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import mptt.fields
import machina.models.fields
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Forum',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('is_active', models.BooleanField(default=True, db_index=True)),
('created', models.DateTimeField(auto_now_add=True, verbose_name='Creation date')),
('updated', models.DateTimeField(auto_now=True, verbose_name='Update date')),
('name', models.CharField(max_length=100, verbose_name='Name')),
('slug', models.SlugField(max_length=255, verbose_name='Slug')),
('description', machina.models.fields.MarkupTextField(no_rendered_field=True, null=True, verbose_name='Description', blank=True)),
('image', machina.models.fields.ExtendedImageField(upload_to='machina/forum_images', null=True, verbose_name='Forum image', blank=True)),
('link', models.URLField(null=True, verbose_name='Forum link', blank=True)),
('link_redirects', models.BooleanField(default=False, help_text='Records the number of times a forum link was clicked', verbose_name='Track link redirects count')),
('type', models.PositiveSmallIntegerField(db_index=True, verbose_name='Forum type', choices=[(0, 'Default forum'), (1, 'Category forum'), (2, 'Link forum')])),
('posts_count', models.PositiveIntegerField(default=0, verbose_name='Number of posts', editable=False, blank=True)),
('topics_count', models.PositiveIntegerField(default=0, verbose_name='Number of topics', editable=False, blank=True)),
('link_redirects_count', models.PositiveIntegerField(default=0, verbose_name='Track link redirects count', editable=False, blank=True)),
('last_post_on', models.DateTimeField(null=True, verbose_name='Last post added on', blank=True)),
('display_sub_forum_list', models.BooleanField(default=True, help_text='Displays this forum on the legend of its parent-forum (sub forums list)', verbose_name='Display in parent-forums legend')),
('_description_rendered', models.TextField(null=True, editable=False, blank=True)),
('lft', models.PositiveIntegerField(editable=False, db_index=True)),
('rght', models.PositiveIntegerField(editable=False, db_index=True)),
('tree_id', models.PositiveIntegerField(editable=False, db_index=True)),
('level', models.PositiveIntegerField(editable=False, db_index=True)),
('parent', mptt.fields.TreeForeignKey(related_name='children', verbose_name='Parent', blank=True, to='forum.Forum', null=True, on_delete=models.CASCADE)),
],
options={
'ordering': ['tree_id', 'lft'],
'abstract': False,
'verbose_name': 'Forum',
'verbose_name_plural': 'Forums',
'permissions': [],
},
),
]
|
tests/input/portugal/test.py | jacobwhall/panflute | 361 | 11095494 | import panflute as pf
input_fn = 'benchmark.json'
output_fn = 'panflute.json'
def empty_test(element, doc):
return
def test_filter(element, doc):
if type(element)==pf.Header:
return []
if type(element)==pf.Str:
element.text = element.text + '!!'
return element
print('\nLoading JSON...')
with open(input_fn, encoding='utf-8') as f:
doc = pf.load(f)
print('Dumping JSON...')
with open(output_fn, mode='w', encoding='utf-8') as f:
pf.dump(doc, f)
f.write('\n')
print(' - Done!')
print('\nComparing...')
with open(input_fn, encoding='utf-8') as f:
input_data = f.read()
with open(output_fn, encoding='utf-8') as f:
output_data = f.read()
print('Are both files the same?')
print(' - Length:', len(input_data) == len(output_data), len(input_data), len(output_data))
print(' - Content:', input_data == output_data)
print('\nApplying trivial filter...')
doc = doc.walk(action=empty_test, doc=doc)
print(' - Done!')
print(' - Dumping JSON...')
with open(output_fn, mode='w', encoding='utf-8') as f:
pf.dump(doc, f)
f.write('\n')
print(' - Done!')
print(' - Comparing...')
with open(input_fn, encoding='utf-8') as f:
input_data = f.read()
with open(output_fn, encoding='utf-8') as f:
output_data = f.read()
print(' - Are both files the same?')
print(' - Length:', len(input_data) == len(output_data), len(input_data), len(output_data))
print(' - Content:', input_data == output_data)
assert input_data == output_data
|
tests/test_optimizers.py | JohnDenis/keras-radam | 357 | 11095513 | <filename>tests/test_optimizers.py
import os
import tempfile
from unittest import TestCase
import numpy as np
from keras_radam.backend import keras
from keras_radam import RAdam
class TestRAdam(TestCase):
@staticmethod
def gen_linear_model(optimizer) -> keras.models.Model:
model = keras.models.Sequential()
model.add(keras.layers.Dense(
input_shape=(17,),
units=3,
bias_constraint=keras.constraints.max_norm(),
name='Dense',
))
model.compile(optimizer, loss='mse')
return model
@staticmethod
def gen_linear_data(w=None) -> (np.ndarray, np.ndarray):
np.random.seed(0xcafe)
x = np.random.standard_normal((4096 * 30, 17))
if w is None:
w = np.random.standard_normal((17, 3))
y = np.dot(x, w)
return x, y, w
def _test_fit(self, optimizer, atol=1e-2):
x, y, w = self.gen_linear_data()
model = self.gen_linear_model(optimizer)
callbacks = [keras.callbacks.EarlyStopping(monitor='loss', patience=3, min_delta=1e-8)]
if isinstance(optimizer, RAdam):
model_path = os.path.join(tempfile.gettempdir(), 'test_accumulation_%f.h5' % np.random.random())
model.save(model_path)
from tensorflow.python.keras.utils.generic_utils import CustomObjectScope
with CustomObjectScope({'RAdam': RAdam}): # Workaround for incorrect global variable used in keras
model = keras.models.load_model(model_path, custom_objects={'RAdam': RAdam})
callbacks.append(keras.callbacks.ReduceLROnPlateau(monitor='loss', min_lr=1e-8, patience=2, verbose=True))
model.fit(x, y,
epochs=100,
batch_size=32,
callbacks=callbacks)
model_path = os.path.join(tempfile.gettempdir(), 'test_accumulation_%f.h5' % np.random.random())
model.save(model_path)
from tensorflow.python.keras.utils.generic_utils import CustomObjectScope
with CustomObjectScope({'RAdam': RAdam}): # Workaround for incorrect global variable used in keras
model = keras.models.load_model(model_path, custom_objects={'RAdam': RAdam})
x, y, w = self.gen_linear_data(w)
predicted = model.predict(x)
self.assertLess(np.max(np.abs(predicted - y)), atol)
def test_amsgrad(self):
self._test_fit(RAdam(amsgrad=True))
def test_decay(self):
self._test_fit(RAdam(decay=1e-4, weight_decay=1e-6), atol=0.1)
def test_warmup(self):
self._test_fit(RAdam(total_steps=38400, warmup_proportion=0.1, min_lr=1e-6))
def test_fit_embed(self):
optimizers = [RAdam]
for optimizer in optimizers:
for amsgrad in [False, True]:
model = keras.models.Sequential()
model.add(keras.layers.Embedding(
input_shape=(None,),
input_dim=5,
output_dim=16,
mask_zero=True,
))
model.add(keras.layers.Bidirectional(keras.layers.LSTM(units=8)))
model.add(keras.layers.Dense(units=2, activation='softmax'))
model.compile(optimizer(
total_steps=38400,
warmup_proportion=0.1,
min_lr=1e-6,
weight_decay=1e-6,
amsgrad=amsgrad,
), loss='sparse_categorical_crossentropy')
x = np.random.randint(0, 5, (64, 3))
y = []
for i in range(x.shape[0]):
if 2 in x[i]:
y.append(1)
else:
y.append(0)
y = np.array(y)
model.fit(x, y, epochs=10)
model_path = os.path.join(tempfile.gettempdir(), 'test_accumulation_%f.h5' % np.random.random())
model.save(model_path)
from tensorflow.python.keras.utils.generic_utils import CustomObjectScope
with CustomObjectScope({'RAdam': RAdam}): # Workaround for incorrect global variable used in keras
keras.models.load_model(model_path, custom_objects={'RAdam': RAdam})
|
docs/codesnippets/194_top_x_of_user.py | rm1410/instaloader | 4,170 | 11095533 | <filename>docs/codesnippets/194_top_x_of_user.py
from itertools import islice
from math import ceil
from instaloader import Instaloader, Profile
PROFILE = ... # profile to download from
X_percentage = 10 # percentage of posts that should be downloaded
L = Instaloader()
profile = Profile.from_username(L.context, PROFILE)
posts_sorted_by_likes = sorted(profile.get_posts(),
key=lambda p: p.likes + p.comments,
reverse=True)
for post in islice(posts_sorted_by_likes, ceil(profile.mediacount * X_percentage / 100)):
L.download_post(post, PROFILE)
|
CircleciScripts/copy_resourcefiles.py | leaksentinel/aws-sdk-ios | 1,026 | 11095553 | <gh_stars>1000+
import os
import sys
from shutil import copyfile
from functions import log, run_command
root = sys.argv[1]
dest = sys.argv[2]
files = {
"LICENSE": "LICENSE",
"LICENSE.APACHE": "LICENSE.APACHE",
"NOTICE": "NOTICE",
"README.md": "README.md",
"CircleciScripts/src/README.html": "src/source.html",
"CircleciScripts/samples/README.html": "samples/samples.html",
}
for source, target in files.items():
s = os.path.join(root, source)
t = os.path.join(dest, target)
target_dir = os.path.dirname(t)
exit_code, out, err = run_command(["mkdir", "-p", target_dir])
if exit_code != 0:
log(f"Failed to make directory '{target_dir}'; output={out}, error={err}")
copyfile(s, t)
|
others/TestMdiArea/HomeWindow.py | sesu089/stackoverflow | 302 | 11095559 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'HomeWindow.ui'
#
# Created by: PyQt5 UI code generator 5.8.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_HomeWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.setWindowModality(QtCore.Qt.WindowModal)
MainWindow.resize(356, 442)
MainWindow.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout_2 = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout_2.setObjectName("gridLayout_2")
self.verticalLayout = QtWidgets.QVBoxLayout()
self.verticalLayout.setObjectName("verticalLayout")
self.frame = QtWidgets.QFrame(self.centralwidget)
self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame.setObjectName("frame")
self.gridLayout = QtWidgets.QGridLayout(self.frame)
self.gridLayout.setObjectName("gridLayout")
self.pushButton = QtWidgets.QPushButton(self.frame)
self.pushButton.setObjectName("pushButton")
self.gridLayout.addWidget(self.pushButton, 0, 0, 1, 1)
self.pushButton_2 = QtWidgets.QPushButton(self.frame)
self.pushButton_2.setObjectName("pushButton_2")
self.gridLayout.addWidget(self.pushButton_2, 1, 0, 1, 1)
self.pushButton_3 = QtWidgets.QPushButton(self.frame)
self.pushButton_3.setObjectName("pushButton_3")
self.gridLayout.addWidget(self.pushButton_3, 2, 0, 1, 1)
self.verticalLayout.addWidget(self.frame)
self.gridLayout_2.addLayout(self.verticalLayout, 0, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Home"))
self.pushButton.setText(_translate("MainWindow", "Open Valve Simulator"))
self.pushButton_2.setText(_translate("MainWindow", "Open Module Program"))
self.pushButton_3.setText(_translate("MainWindow", "Open Metal Sizing"))
|
tests/test_create.py | RemiRigal/jsonpath-ng | 339 | 11095570 | import doctest
from collections import namedtuple
import pytest
import jsonpath_ng
from jsonpath_ng.ext import parse
Params = namedtuple('Params', 'string initial_data insert_val target')
@pytest.mark.parametrize('string, initial_data, insert_val, target', [
Params(string='$.foo',
initial_data={},
insert_val=42,
target={'foo': 42}),
Params(string='$.foo.bar',
initial_data={},
insert_val=42,
target={'foo': {'bar': 42}}),
Params(string='$.foo[0]',
initial_data={},
insert_val=42,
target={'foo': [42]}),
Params(string='$.foo[1]',
initial_data={},
insert_val=42,
target={'foo': [{}, 42]}),
Params(string='$.foo[0].bar',
initial_data={},
insert_val=42,
target={'foo': [{'bar': 42}]}),
Params(string='$.foo[1].bar',
initial_data={},
insert_val=42,
target={'foo': [{}, {'bar': 42}]}),
Params(string='$.foo[0][0]',
initial_data={},
insert_val=42,
target={'foo': [[42]]}),
Params(string='$.foo[1][1]',
initial_data={},
insert_val=42,
target={'foo': [{}, [{}, 42]]}),
Params(string='foo[0]',
initial_data={},
insert_val=42,
target={'foo': [42]}),
Params(string='foo[1]',
initial_data={},
insert_val=42,
target={'foo': [{}, 42]}),
Params(string='foo',
initial_data={},
insert_val=42,
target={'foo': 42}),
# Initial data can be a list if we expect a list back
Params(string='[0]',
initial_data=[],
insert_val=42,
target=[42]),
Params(string='[1]',
initial_data=[],
insert_val=42,
target=[{}, 42]),
# Converts initial data to a list if necessary
Params(string='[0]',
initial_data={},
insert_val=42,
target=[42]),
Params(string='[1]',
initial_data={},
insert_val=42,
target=[{}, 42]),
Params(string='foo[?bar="baz"].qux',
initial_data={'foo': [
{'bar': 'baz'},
{'bar': 'bizzle'},
]},
insert_val=42,
target={'foo': [
{'bar': 'baz', 'qux': 42},
{'bar': 'bizzle'}
]}),
])
def test_update_or_create(string, initial_data, insert_val, target):
jsonpath = parse(string)
result = jsonpath.update_or_create(initial_data, insert_val)
assert result == target
@pytest.mark.parametrize('string, initial_data, insert_val, target', [
# Slice not supported
Params(string='foo[0:1]',
initial_data={},
insert_val=42,
target={'foo': [42, 42]}),
# result is {'foo': {}}
# Filter does not create items to meet criteria
Params(string='foo[?bar="baz"].qux',
initial_data={},
insert_val=42,
target={'foo': [{'bar': 'baz', 'qux': 42}]}),
# result is {'foo': {}}
# Does not convert initial data to a dictionary
Params(string='foo',
initial_data=[],
insert_val=42,
target={'foo': 42}),
# raises TypeError
])
@pytest.mark.xfail
def test_unsupported_classes(string, initial_data, insert_val, target):
jsonpath = parse(string)
result = jsonpath.update_or_create(initial_data, insert_val)
assert result == target
@pytest.mark.parametrize('string, initial_data, insert_val, target', [
Params(string='$.name[0].text',
initial_data={},
insert_val='<NAME>',
target={'name': [{'text': 'Sir Michael'}]}),
Params(string='$.name[0].given[0]',
initial_data={'name': [{'text': '<NAME>'}]},
insert_val='Michael',
target={'name': [{'text': 'Sir Michael',
'given': ['Michael']}]}),
Params(string='$.name[0].prefix[0]',
initial_data={'name': [{'text': 'Sir Michael',
'given': ['Michael']}]},
insert_val='Sir',
target={'name': [{'text': 'Sir Michael',
'given': ['Michael'],
'prefix': ['Sir']}]}),
Params(string='$.birthDate',
initial_data={'name': [{'text': 'Sir Michael',
'given': ['Michael'],
'prefix': ['Sir']}]},
insert_val='1943-05-05',
target={'name': [{'text': '<NAME>',
'given': ['Michael'],
'prefix': ['Sir']}],
'birthDate': '1943-05-05'}),
])
def test_build_doc(string, initial_data, insert_val, target):
jsonpath = parse(string)
result = jsonpath.update_or_create(initial_data, insert_val)
assert result == target
def test_doctests():
results = doctest.testmod(jsonpath_ng)
assert results.failed == 0
|
quokka/core/content/utils.py | songshansitulv/quokka | 1,141 | 11095580 | from quokka.utils.text import slugify_category, slugify
from flask import current_app as app
def url_for_content(content, include_ext=True):
"""Return a relative URL for content dict or Content model
"""
if not isinstance(content, dict):
data = content.data
else:
data = content
category_slug = (
data.get('category_slug') or
slugify_category(data.get('category') or '')
)
slug = data.get('slug') or slugify(data.get('title'))
if category_slug:
slug = f'{category_slug}/{slug}'
content_type = data.get('content_type')
if content_type not in (None, 'article', 'page'):
slug = f'{content_type}/{slug}'
if not include_ext:
return slug
ext = app.config.get("CONTENT_EXTENSION", "html")
if data.get('published'):
# return url_for('quokka.core.content.detail', slug=slug)
return f'{slug}.{ext}'
else:
# return url_for('quokka.core.content.preview', slug=slug)
return f'{slug}.preview'
# TODO: remove this and use model
def url_for_category(category):
# TODO: handle extension for static site
# ext = app.config.get("CONTENT_EXTENSION", "html")
if isinstance(category, str):
return slugify_category(category)
return category.url
def strftime(value, dtformat):
return value.strftime(dtformat)
|
third_party/Paste/paste/progress.py | tingshao/catapult | 5,079 | 11095592 | <filename>third_party/Paste/paste/progress.py
# (c) 2005 <NAME> and contributors; written for Paste (http://pythonpaste.org)
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
# (c) 2005 <NAME>
# This module is part of the Python Paste Project and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
# This code was written with funding by http://prometheusresearch.com
"""
Upload Progress Monitor
This is a WSGI middleware component which monitors the status of files
being uploaded. It includes a small query application which will return
a list of all files being uploaded by particular session/user.
>>> from paste.httpserver import serve
>>> from paste.urlmap import URLMap
>>> from paste.auth.basic import AuthBasicHandler
>>> from paste.debug.debugapp import SlowConsumer, SimpleApplication
>>> # from paste.progress import *
>>> realm = 'Test Realm'
>>> def authfunc(username, password):
... return username == password
>>> map = URLMap({})
>>> ups = UploadProgressMonitor(map, threshold=1024)
>>> map['/upload'] = SlowConsumer()
>>> map['/simple'] = SimpleApplication()
>>> map['/report'] = UploadProgressReporter(ups)
>>> serve(AuthBasicHandler(ups, realm, authfunc))
serving on...
.. note::
This is experimental, and will change in the future.
"""
import time
from paste.wsgilib import catch_errors
DEFAULT_THRESHOLD = 1024 * 1024 # one megabyte
DEFAULT_TIMEOUT = 60*5 # five minutes
ENVIRON_RECEIVED = 'paste.bytes_received'
REQUEST_STARTED = 'paste.request_started'
REQUEST_FINISHED = 'paste.request_finished'
class _ProgressFile(object):
"""
This is the input-file wrapper used to record the number of
``paste.bytes_received`` for the given request.
"""
def __init__(self, environ, rfile):
self._ProgressFile_environ = environ
self._ProgressFile_rfile = rfile
self.flush = rfile.flush
self.write = rfile.write
self.writelines = rfile.writelines
def __iter__(self):
environ = self._ProgressFile_environ
riter = iter(self._ProgressFile_rfile)
def iterwrap():
for chunk in riter:
environ[ENVIRON_RECEIVED] += len(chunk)
yield chunk
return iter(iterwrap)
def read(self, size=-1):
chunk = self._ProgressFile_rfile.read(size)
self._ProgressFile_environ[ENVIRON_RECEIVED] += len(chunk)
return chunk
def readline(self):
chunk = self._ProgressFile_rfile.readline()
self._ProgressFile_environ[ENVIRON_RECEIVED] += len(chunk)
return chunk
def readlines(self, hint=None):
chunk = self._ProgressFile_rfile.readlines(hint)
self._ProgressFile_environ[ENVIRON_RECEIVED] += len(chunk)
return chunk
class UploadProgressMonitor(object):
"""
monitors and reports on the status of uploads in progress
Parameters:
``application``
This is the next application in the WSGI stack.
``threshold``
This is the size in bytes that is needed for the
upload to be included in the monitor.
``timeout``
This is the amount of time (in seconds) that a upload
remains in the monitor after it has finished.
Methods:
``uploads()``
This returns a list of ``environ`` dict objects for each
upload being currently monitored, or finished but whose time
has not yet expired.
For each request ``environ`` that is monitored, there are several
variables that are stored:
``paste.bytes_received``
This is the total number of bytes received for the given
request; it can be compared with ``CONTENT_LENGTH`` to
build a percentage complete. This is an integer value.
``paste.request_started``
This is the time (in seconds) when the request was started
as obtained from ``time.time()``. One would want to format
this for presentation to the user, if necessary.
``paste.request_finished``
This is the time (in seconds) when the request was finished,
canceled, or otherwise disconnected. This is None while
the given upload is still in-progress.
TODO: turn monitor into a queue and purge queue of finished
requests that have passed the timeout period.
"""
def __init__(self, application, threshold=None, timeout=None):
self.application = application
self.threshold = threshold or DEFAULT_THRESHOLD
self.timeout = timeout or DEFAULT_TIMEOUT
self.monitor = []
def __call__(self, environ, start_response):
length = environ.get('CONTENT_LENGTH', 0)
if length and int(length) > self.threshold:
# replace input file object
self.monitor.append(environ)
environ[ENVIRON_RECEIVED] = 0
environ[REQUEST_STARTED] = time.time()
environ[REQUEST_FINISHED] = None
environ['wsgi.input'] = \
_ProgressFile(environ, environ['wsgi.input'])
def finalizer(exc_info=None):
environ[REQUEST_FINISHED] = time.time()
return catch_errors(self.application, environ,
start_response, finalizer, finalizer)
return self.application(environ, start_response)
def uploads(self):
return self.monitor
class UploadProgressReporter(object):
"""
reports on the progress of uploads for a given user
This reporter returns a JSON file (for use in AJAX) listing the
uploads in progress for the given user. By default, this reporter
uses the ``REMOTE_USER`` environment to compare between the current
request and uploads in-progress. If they match, then a response
record is formed.
``match()``
This member function can be overriden to provide alternative
matching criteria. It takes two environments, the first
is the current request, the second is a current upload.
``report()``
This member function takes an environment and builds a
``dict`` that will be used to create a JSON mapping for
the given upload. By default, this just includes the
percent complete and the request url.
"""
def __init__(self, monitor):
self.monitor = monitor
def match(self, search_environ, upload_environ):
if search_environ.get('REMOTE_USER', None) == \
upload_environ.get('REMOTE_USER', 0):
return True
return False
def report(self, environ):
retval = { 'started': time.strftime("%Y-%m-%d %H:%M:%S",
time.gmtime(environ[REQUEST_STARTED])),
'finished': '',
'content_length': environ.get('CONTENT_LENGTH'),
'bytes_received': environ[ENVIRON_RECEIVED],
'path_info': environ.get('PATH_INFO',''),
'query_string': environ.get('QUERY_STRING','')}
finished = environ[REQUEST_FINISHED]
if finished:
retval['finished'] = time.strftime("%Y:%m:%d %H:%M:%S",
time.gmtime(finished))
return retval
def __call__(self, environ, start_response):
body = []
for map in [self.report(env) for env in self.monitor.uploads()
if self.match(environ, env)]:
parts = []
for k, v in map.items():
v = str(v).replace("\\", "\\\\").replace('"', '\\"')
parts.append('%s: "%s"' % (k, v))
body.append("{ %s }" % ", ".join(parts))
body = "[ %s ]" % ", ".join(body)
start_response("200 OK", [('Content-Type', 'text/plain'),
('Content-Length', len(body))])
return [body]
__all__ = ['UploadProgressMonitor', 'UploadProgressReporter']
if "__main__" == __name__:
import doctest
doctest.testmod(optionflags=doctest.ELLIPSIS)
|
tests/syntax/test_imports.py | abol-karimi/Scenic | 141 | 11095596 | <filename>tests/syntax/test_imports.py
"""Tests for imports of Scenic modules.
Note that this is different from modular scenarios defined using the 'scenario'
statement. This file simply tests imports of old-style Scenic modules; the new
system of modular scenarios is tested in 'test_modular.py'.
"""
import os.path
import pytest
from scenic import scenarioFromFile
from scenic.syntax.translator import InvalidScenarioError
from tests.utils import compileScenic, sampleScene, sampleSceneFrom
def test_import_top_absolute(request):
base = os.path.dirname(request.fspath)
fullpathImports = os.path.join(base, 'imports.scenic')
fullpathHelper = os.path.join(base, 'helper.scenic')
scenario = scenarioFromFile(fullpathImports)
assert len(scenario.requirements) == 0
scene, iterations = scenario.generate(maxIterations=1)
# Top-level and inherited Objects
assert len(scene.objects) == 2
ego = scene.egoObject
assert ego.species == 'killer'
assert scene.objects[1].species == 'helpful'
# Parameter depending on imported Python module
assert scene.params['thingy'] == 42
# Parameters depending on import circumstances
assert scene.params['imports_name'] == '__main__'
assert scene.params['imports_file'] == fullpathImports
# Inherited parameters as above
assert scene.params['helper_name'] == 'helper'
assert scene.params['helper_file'] == fullpathHelper
def test_import_top_relative(request):
base = os.path.dirname(request.fspath)
fullpathHelper = os.path.join(base, 'helper.scenic')
oldDirectory = os.getcwd()
os.chdir(base)
try:
scenario = scenarioFromFile('imports.scenic')
assert len(scenario.requirements) == 0
scene, iterations = scenario.generate(maxIterations=1)
assert len(scene.objects) == 2
ego = scene.egoObject
assert ego.species == 'killer'
assert scene.objects[1].species == 'helpful'
assert scene.params['thingy'] == 42
assert scene.params['imports_name'] == '__main__'
assert scene.params['imports_file'] == 'imports.scenic'
assert scene.params['helper_name'] == 'helper'
assert scene.params['helper_file'] == fullpathHelper
finally:
os.chdir(oldDirectory)
def test_module_name_main():
scenario = compileScenic('param name = __name__\n' 'ego = Object')
scene, iterations = scenario.generate(maxIterations=1)
assert scene.params['name'] == '__main__'
def test_import_ego(runLocally):
with runLocally(), pytest.raises(InvalidScenarioError):
compileScenic('import imports')
def test_inherit_requirements(runLocally):
with runLocally():
scenario = compileScenic(
'import helper3\n'
'ego = Object'
)
assert len(scenario.requirements) == 1
for i in range(50):
scene, iterations = scenario.generate(maxIterations=100)
assert len(scene.objects) == 2
constrainedObj = scene.objects[1]
assert constrainedObj.position.x > 0
def test_inherit_constructors(runLocally):
with runLocally():
scenario = compileScenic(
'from helper import Caerbannog\n'
'ego = Caerbannog'
)
def test_multiple_imports(runLocally):
with runLocally():
scenario = compileScenic("""
import helper
import helper
ego = Object
import helper
""")
assert len(scenario.objects) == 2
scene = sampleScene(scenario)
assert len(scene.objects) == 2
def test_import_in_try(runLocally):
with runLocally():
scenario = compileScenic("""
try:
from helper import Caerbannog
x = 12
finally:
y = 4
ego = Caerbannog at x @ y
""")
def test_import_in_except(runLocally):
with runLocally():
scenario = compileScenic("""
try:
import __non_ex_ist_ent___
except ImportError:
from helper import Caerbannog
ego = Caerbannog
""")
def test_import_multiline_1():
compileScenic(
'from math import factorial, \\\n'
' pow\n'
'ego = Object with width pow(factorial(4), 2)'
)
def test_import_multiline_2():
compileScenic(
'from math import (factorial,\n'
' pow)\n'
'ego = Object with width pow(factorial(4), 2)'
)
def test_import_override_param():
scene = sampleSceneFrom("""
param helper_file = 'foo'
import tests.syntax.helper
ego = Object
""")
assert scene.params['helper_file'] != 'foo'
def test_model_not_override_param():
scene = sampleSceneFrom("""
param helper_file = 'foo'
model tests.syntax.helper
ego = Object
""")
assert scene.params['helper_file'] == 'foo'
|
recommender/datasets/movielens.py | yugandharaloori/Recommender-Systems-Comparison | 136 | 11095607 | <filename>recommender/datasets/movielens.py
from io import BytesIO
import numpy as np
import pandas as pd
try:
from pandas.io.common import ZipFile
except ImportError:
from zipfile import ZipFile
def get_movielens_data(local_file=None, get_ratings=True, get_genres=False,
split_genres=True, mdb_mapping=False, get_tags=False, include_time=False):
'''Downloads movielens data and stores it in pandas dataframe.
'''
fields = ['userid', 'movieid', 'rating']
if include_time:
fields.append('timestamp')
if not local_file:
# downloading data
from requests import get
zip_file_url = 'http://files.grouplens.org/datasets/movielens/ml-1m.zip'
zip_response = get(zip_file_url)
zip_contents = BytesIO(zip_response.content)
else:
zip_contents = local_file
ml_data = ml_genres = ml_tags = mapping = None
# loading data into memory
with ZipFile(zip_contents) as zfile:
zip_files = pd.Series(zfile.namelist())
zip_file = zip_files[zip_files.str.contains('ratings')].iat[0]
is_new_format = ('latest' in zip_file) or ('20m' in zip_file)
delimiter = ','
header = 0 if is_new_format else None
if get_ratings:
zdata = zfile.read(zip_file)
zdata = zdata.replace(b'::', delimiter.encode())
# makes data compatible with pandas c-engine
# returns string objects instead of bytes in that case
ml_data = pd.read_csv(BytesIO(zdata), sep=delimiter, header=header, engine='c', names=fields, usecols=fields)
if get_genres:
zip_file = zip_files[zip_files.str.contains('movies')].iat[0]
zdata = zfile.read(zip_file)
if not is_new_format:
# make data compatible with pandas c-engine
# pandas returns string objects instead of bytes in that case
delimiter = '^'
zdata = zdata.replace(b'::', delimiter.encode())
genres_data = pd.read_csv(BytesIO(zdata), sep=delimiter, header=header,
engine='c', encoding='unicode_escape',
names=['movieid', 'movienm', 'genres'])
ml_genres = get_split_genres(genres_data) if split_genres else genres_data
if get_tags:
zip_file = zip_files[zip_files.str.contains('/tags')].iat[0] #not genome
zdata = zfile.read(zip_file)
if not is_new_format:
# make data compatible with pandas c-engine
# pandas returns string objects instead of bytes in that case
delimiter = '^'
zdata = zdata.replace(b'::', delimiter.encode())
fields[2] = 'tag'
ml_tags = pd.read_csv(BytesIO(zdata), sep=delimiter, header=header,
engine='c', encoding='latin1',
names=fields, usecols=range(len(fields)))
if mdb_mapping and is_new_format:
# imdb and tmdb mapping - exists only in ml-latest or 20m datasets
zip_file = zip_files[zip_files.str.contains('links')].iat[0]
with zfile.open(zip_file) as zdata:
mapping = pd.read_csv(zdata, sep=',', header=0, engine='c',
names=['movieid', 'imdbid', 'tmdbid'])
res = [data for data in [ml_data, ml_genres, ml_tags, mapping] if data is not None]
if len(res)==1: res = res[0]
return res
def get_split_genres(genres_data):
return (genres_data[['movieid', 'movienm']]
.join(pd.DataFrame([(i, x)
for i, g in enumerate(genres_data['genres'])
for x in g.split('|')
], columns=['index', 'genreid']
).set_index('index'))
.reset_index(drop=True))
def filter_short_head(data, threshold=0.01):
short_head = data.groupby('movieid', sort=False)['userid'].nunique()
short_head.sort_values(ascending=False, inplace=True)
ratings_perc = short_head.cumsum()*1.0/short_head.sum()
movies_perc = np.arange(1, len(short_head)+1, dtype='f8') / len(short_head)
long_tail_movies = ratings_perc[movies_perc > threshold].index
return long_tail_movies
|
scrapera/text/tests/medium_test.py | Baras64/Scrapera | 300 | 11095620 | from scrapera.text.medium import MediumScraper
scraper = MediumScraper()
scraper.scrape(topic="artificial-intelligence", n_posts=2) |
recipes/Python/520585_VectorObject/recipe-520585.py | tdiprima/code | 2,023 | 11095627 | #a class used for creating any object moving in 2D or a Vector Object (VObject)
#for direction use degrees, think of a 2d environment like:
#
# 90
# |
# |
# 180 ----+----- 0
# |
# |
# 270
#
from math import cos as _cos, sin as _sin, radians as _rad
class VObject():
def __init__(self,x,y,speed,direction):
self.x = x
self.y = y
self.s = speed
self.d = _rad(direction)
def update(self,time=1):
distance = self.s*time
y = (_sin(self.d))*distance
x = (_cos(self.d))*distance
self.x += x
self.y += y
def addspeed(self,speed):
self.s += speed
def steer(self,angle):
self.d += _rad(angle)
def getx(self): return self.x
def gety(self): return self.y
|
samcli/commands/_utils/option_value_processor.py | michaelbrewer/aws-sam-cli | 2,959 | 11095640 | <filename>samcli/commands/_utils/option_value_processor.py
"""
Parsing utilities commonly used to process information for commands
"""
import logging
from typing import Optional, Dict, Tuple
from samcli.commands.exceptions import InvalidImageException
LOG = logging.getLogger(__name__)
def process_env_var(container_env_var: Optional[Tuple[str]]) -> Dict:
"""
Parameters
----------
container_env_var : Tuple
the tuple of command line env vars received from --container-env-var flag
Each input format needs to be either function specific format (FuncName.VarName=Value)
or global format (VarName=Value)
Returns
-------
dictionary
Processed command line environment variables
"""
processed_env_vars: Dict = {}
if container_env_var:
for env_var in container_env_var:
location_key = "Parameters"
env_var_name, value = _parse_key_value_pair(env_var)
if not env_var_name or not value:
LOG.error("Invalid command line --container-env-var input %s, skipped", env_var)
continue
if "." in env_var_name:
location_key, env_var_name = env_var_name.split(".", 1)
if not location_key.strip() or not env_var_name.strip():
LOG.error("Invalid command line --container-env-var input %s, skipped", env_var)
continue
if not processed_env_vars.get(location_key):
processed_env_vars[location_key] = {}
processed_env_vars[location_key][env_var_name] = value
return processed_env_vars
def process_image_options(image_args: Optional[Tuple[str]]) -> Dict:
"""
Parameters
----------
image_args : Tuple
Tuple of command line image options in the format of
"Function1=public.ecr.aws/abc/abc:latest" or
"public.ecr.aws/abc/abc:latest"
Returns
-------
dictionary
Function as key and the corresponding image URI as value.
Global default image URI is contained in the None key.
"""
images: Dict[Optional[str], str] = {}
if image_args:
for image_string in image_args:
function_name, image_uri = _parse_key_value_pair(image_string)
if not image_uri:
raise InvalidImageException(f"Invalid command line image input {image_string}.")
images[function_name] = image_uri
return images
def _parse_key_value_pair(arg: str) -> Tuple[Optional[str], str]:
"""
Parameters
----------
arg : str
Arg in the format of "Value" or "Key=Value"
Returns
-------
key : Optional[str]
If key is not specified, None will be the key.
value : str
"""
key: Optional[str]
value: str
if "=" in arg:
parts = arg.split("=", 1)
key = parts[0].strip()
value = parts[1].strip()
else:
key = None
value = arg.strip()
return key, value
|
T-RNN/Experiment_MNIST.py | ericzy89/DEEPEYE | 106 | 11095682 | __author__ = "<NAME>"
__copyright__ = "Siemens AG, 2017"
__licencse__ = "MIT"
__version__ = "0.1"
"""
MIT License
Copyright (c) 2017 Siemens AG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
"""
On the MNIST data we experiment two 2-layered NN models: The first model contains two dense layers,
while the second model replaces the first dense layer with TT layer.
It can be shown that the when applying a TT layer with significantly less parameters, one can speed
up the training and inference to a very large extent. In detail:
The first standard model has 1048576 parameters in the first layer. It takes ca 48 seconds to train
for one epoch. The accuracy after 50 epochs is 0.9686.
The second model with a TT layer contains 1248 weights and each epoch takes ca 9 seconds;
the accuracy after 50 epochs is 0.9785.
Compression factor = 1248 / 1048576 = 0.00119018554688
According to the original paper, the TT layer is considered to compress the otherwise dense layer.
In this case, however, due to the fact that the model with TT layer actually shows better performances,
"""
# Basic
import numpy as np
# Keras Model
from keras.layers import Input, Dense
from keras.models import Model
from keras.regularizers import l2
from keras.optimizers import *
# TT Layer
from TTLayer import TT_Layer
# Data
from keras.datasets import mnist
# Others
from keras.utils.np_utils import to_categorical
from keras.preprocessing.image import ImageDataGenerator
from sklearn.metrics import average_precision_score, roc_auc_score, accuracy_score
np.random.seed(11111986)
# Load the MNIST data
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train = X_train.astype('float32')
y_train = y_train.astype('int32')
X_test = X_test.astype('float32')
y_test = y_test.astype('int32')
Y_train = to_categorical(y_train, 10)
Y_test = to_categorical(y_test, 10)
# Put 2 arrays on the border of the images to form a 32x32 shape
N = X_train.shape[0]
left0 = np.zeros((N, 2, 28))
right0 = np.zeros((N, 2, 28))
upper0 = np.zeros((N, 32, 2))
lower0 = np.zeros((N, 32, 2))
X_train = np.concatenate([left0, X_train, right0], axis=1)
X_train = np.concatenate([upper0, X_train, lower0], axis=2)
N = X_test.shape[0]
left0 = np.zeros((N, 2, 28))
right0 = np.zeros((N, 2, 28))
upper0 = np.zeros((N, 32, 2))
lower0 = np.zeros((N, 32, 2))
X_test = np.concatenate([left0, X_test, right0], axis=1)
X_test = np.concatenate([upper0, X_test, lower0], axis=2)
X_train /= 255.
X_test /= 255.
X_train = X_train[:, None, :, :]
X_test = X_test[:, None, :, :]
if False: # if apply the imagegenerator
valid_size = int(0.2*X_train.shape[0])
valid_inds = np.random.choice(range(X_train.shape[0]), valid_size, False)
X_valid = X_train[valid_inds]
Y_valid = Y_train[valid_inds]
tr_inds = np.setdiff1d(np.arange(X_train.shape[0]), valid_inds)
X_train = X_train[tr_inds]
Y_train = Y_train[tr_inds]
train_gen = ImageDataGenerator(
featurewise_center=True, # set input mean to 0 over the dataset
samplewise_center=False, # set each sample mean to 0
featurewise_std_normalization=False, # divide inputs by std of the dataset
samplewise_std_normalization=False, # divide each input by its std
zca_whitening=False, # apply ZCA whitening
rotation_range=30, # randomly rotate images in the range (degrees, 0 to 180)
width_shift_range=0.1, # randomly shift images horizontally (fraction of total width)
height_shift_range=0.1, # randomly shift images vertically (fraction of total height)
horizontal_flip=True, # randomly flip images
vertical_flip=False) # randomly flip images
train_gen.fit(X_train)
valid_gen = ImageDataGenerator(
featurewise_center=False,
samplewise_center=False,
featurewise_std_normalization=False,
samplewise_std_normalization=False,
zca_whitening=False,
rotation_range=0,
width_shift_range=0,
height_shift_range=0,
horizontal_flip=False,
vertical_flip=False
)
valid_gen.fit(X_valid)
# Define the model
input = Input(shape=(1, 32, 32,))
h1 = TT_Layer(tt_input_shape=[4, 8, 8, 4], tt_output_shape=[4, 8, 8, 4], tt_ranks=[1, 3, 3, 3, 1],
bias=True, activation='relu', kernel_regularizer=l2(5e-4), debug=False, ortho_init=True)(input)
# Alternatively, try a dense layer:
# h1 = Dense(output_dim=32*32, activation='relu', kernel_regularizer=l2(5e-4))(input)
output = Dense(output_dim=10, activation='softmax', kernel_regularizer=l2(1e-3))(h1)
model = Model(input=input, output=output)
model.compile(optimizer=Adam(1e-3), loss='categorical_crossentropy', metrics=['accuracy'])
# Train the model
# either the old fashion:
model.fit(x=X_train, y=Y_train, verbose=2, epochs=50, batch_size=128,
validation_split=0.2)
# or with ImageDataGenerator
# model.fit_generator(train_gen.flow(X_train, Y_train, batch_size=128),
# samples_per_epoch=len(X_train), nb_epoch=50, verbose=2,
# validation_data=valid_gen.flow(X_valid, Y_valid),
# nb_val_samples=X_valid.shape[0])
# Fitted values: AUROC/AUPRC/ACC
Y_hat = model.predict(x=X_train)
print roc_auc_score(Y_train, Y_hat)
print average_precision_score(Y_train, Y_hat)
print accuracy_score(Y_train, np.round(Y_hat))
# Predicted values:
Y_pred = model.predict(x=X_test)
print roc_auc_score(Y_test, Y_pred)
print average_precision_score(Y_test, Y_pred)
print accuracy_score(Y_test, np.round(Y_pred))
# 0.99970343541
# 0.997838863715
# 0.9785
# TT Layer compresses the first weight matrix to a factor of 1248 / 1048576 = 0.00119
# 9s per epoch
# Test error 0.0215 after 50 epochs, I think we can definitely train/tune the model further
# Without the TT Layer:
X_train = X_train.reshape((X_train.shape[0], 32*32))
X_test = X_test.reshape((X_test.shape[0], 32*32))
input = Input(shape=(32*32,))
h1 = Dense(output_dim=32*32, activation='relu', kernel_regularizer=l2(5e-4))(input)
output = Dense(output_dim=10, activation='softmax', kernel_regularizer=l2(1e-3))(h1)
model = Model(input=input, output=output)
model.compile(optimizer=Adam(1e-3), loss='categorical_crossentropy', metrics=['accuracy'])
# Train the model
model.fit(x=X_train, y=Y_train, verbose=2, nb_epoch=50, batch_size=128,
validation_split=0.2)
# Fitted values: AUROC/AUPRC/ACC
Y_hat = model.predict(x=X_train)
print roc_auc_score(Y_train, Y_hat)
print average_precision_score(Y_train, Y_hat)
print accuracy_score(Y_train, np.round(Y_hat))
# Predicted values:
Y_pred = model.predict(x=X_test)
print roc_auc_score(Y_test, Y_pred)
print average_precision_score(Y_test, Y_pred)
print accuracy_score(Y_test, np.round(Y_pred))
# 0.999554701249
# 0.996718126202
# 0.9686
# ca 48s on average per epoch
# Test error 0.0313 after 50 epochs.
|
examples/008_sklearn.py | szghlm/smote_variants | 271 | 11095692 | <gh_stars>100-1000
# coding: utf-8
# # Integration with sklearn pipelines
#
# In this notebook, provide some illustration for integration with sklearn pipelines.
# In[1]:
import keras
import imblearn
import numpy as np
import smote_variants as sv
import imblearn.datasets as imb_datasets
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
random_seed= 3
# ## Preparing the data
# In[2]:
np.random.seed(random_seed)
# In[3]:
libras= imb_datasets.fetch_datasets()['libras_move']
X, y= libras['data'], libras['target']
# In[4]:
X_train, X_test, y_train, y_test= train_test_split(X, y, test_size= 0.33)
# ## Fitting a pipeline
# In[5]:
oversampler= sv.MulticlassOversampling(sv.distance_SMOTE())
classifier= KNeighborsClassifier(n_neighbors= 5)
# In[6]:
model= Pipeline([('scale', StandardScaler()), ('clf', sv.OversamplingClassifier(oversampler, classifier))])
# In[7]:
model.fit(X, y)
# ## Grid search
# In[8]:
param_grid= {'clf__oversampler':[sv.distance_SMOTE(proportion=0.5),
sv.distance_SMOTE(proportion=1.0),
sv.distance_SMOTE(proportion=1.5)]}
# In[9]:
grid= GridSearchCV(model, param_grid= param_grid, cv= 3, n_jobs= 1, verbose= 2, scoring= 'accuracy')
# In[10]:
grid.fit(X, y)
# In[11]:
print(grid.best_score_)
print(grid.cv_results_)
|
Beginers/stdlib/theCEOspeech/solution.py | arunkgupta/PythonTrainingExercises | 150 | 11095694 | """Your job is to write a speech for your CEO. You have a list of meaningful
phrases that he is fond of such as "knowledge optimization initiatives" and
your task is to weave them in to a speech.
You also have the opening words "Our clear strategic direction is to invoke..."
and some useful joining phrases such as "whilst not forgetting".
The speech that you will write takes the opening words and randomly jumbles the
phrases alternated with joining phrases to make a more complete, if meaningless,
speech. After execution the speech might need some light editing.
Note to my current employer: This is no reflection whatsoever on the
organisation that I work for. This all comes from one of my former CEOs,
<NAME>, during his tenure at Nokia. The code is mine but the words are
all his, slightly transliterated ("<big corp.>" replaces "Nokia",
"<little corp.>" replaces "Symbian" and "<other corp.>" replaces "Microsoft").
Created on 19 Feb 2016
@author: paulross
"""
import random
import textwrap
OPENING_WORDS = ['Our', 'clear', 'strategic', 'direction', 'is', 'to', 'invoke',]
PHRASE_TABLE = (
("accountable", "transition", "leadership"),
("driving", "strategy", "implementation"),
("drilling down into", "active", "core business objectives"),
("next billion", "execution", "with our friends in <other corp.>"),
("creating", "next-generation", "franchise platform"),
("<big corp.>'s", "volume and", "value leadership"),
("significant", "end-user", "experience"),
("transition", "from <small corp.>", "to <other corp.>'s platform"),
("integrating", "shared", "services"),
("empowered to", "improve and expand", "our portfolio of experience"),
("deliver", "new", "innovation"),
("ramping up", "diverse", "collaboration"),
("next generation", "mobile", "ecosystem"),
("focus on", "growth and", "consumer delight"),
("management", "planning", "interlocks"),
("necessary", "operative", "capabilities"),
("knowledge", "optimization", "initiatives"),
("modular", "integration", "environment"),
("software", "creation", "processes"),
("agile", "working", "practices"),
)
INSERTS = ('for', 'with', 'and', 'as well as', 'by',
'whilst not forgetting',
'. Of course',
'. To be absolutely clear',
'. We need',
'and unrelenting',
'with unstoppable',
)
def get_phrase():
"""Return a phrase by choosing words at random from each column of the PHRASE_TABLE."""
return [random.choice(PHRASE_TABLE)[i] for i in range(3)]
def get_insert():
"""Return a randomly chosen set of words to insert between phrases."""
return random.choice(INSERTS)
def write_speech(n):
"""Write a speech with the opening words followed by n random phrases
interspersed with random inserts."""
phrases = OPENING_WORDS
while n:
phrases.extend(get_phrase())
if n > 1:
phrases.append(get_insert())
n -= 1
text = ' '.join(phrases) + '.'
print textwrap.fill(text)
if __name__ == '__main__':
write_speech(40)
|
etl/parsers/etw/Microsoft_Windows_MediaFoundation_Performance.py | IMULMUL/etl-parser | 104 | 11095728 | # -*- coding: utf-8 -*-
"""
Microsoft-Windows-MediaFoundation-Performance
GUID : f404b94e-27e0-4384-bfe8-1d8d390b0aa3
"""
from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct
from etl.utils import WString, CString, SystemTime, Guid
from etl.dtyp import Sid
from etl.parsers.etw.core import Etw, declare, guid
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=3062, version=0)
class Microsoft_Windows_MediaFoundation_Performance_3062_0(Etw):
pattern = Struct(
"dwType" / Int32ul,
"dwConfig" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=3063, version=0)
class Microsoft_Windows_MediaFoundation_Performance_3063_0(Etw):
pattern = Struct(
"dwScaleX" / Int32ul,
"dwScaleY" / Int32ul,
"dwWindowX" / Int32ul,
"dwWindowY" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=3067, version=0)
class Microsoft_Windows_MediaFoundation_Performance_3067_0(Etw):
pattern = Struct(
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=3068, version=0)
class Microsoft_Windows_MediaFoundation_Performance_3068_0(Etw):
pattern = Struct(
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=3069, version=0)
class Microsoft_Windows_MediaFoundation_Performance_3069_0(Etw):
pattern = Struct(
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=3070, version=0)
class Microsoft_Windows_MediaFoundation_Performance_3070_0(Etw):
pattern = Struct(
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=3071, version=0)
class Microsoft_Windows_MediaFoundation_Performance_3071_0(Etw):
pattern = Struct(
"subtype" / Guid
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=3072, version=0)
class Microsoft_Windows_MediaFoundation_Performance_3072_0(Etw):
pattern = Struct(
"result" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=3073, version=0)
class Microsoft_Windows_MediaFoundation_Performance_3073_0(Etw):
pattern = Struct(
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=3074, version=0)
class Microsoft_Windows_MediaFoundation_Performance_3074_0(Etw):
pattern = Struct(
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=3075, version=0)
class Microsoft_Windows_MediaFoundation_Performance_3075_0(Etw):
pattern = Struct(
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=3076, version=0)
class Microsoft_Windows_MediaFoundation_Performance_3076_0(Etw):
pattern = Struct(
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4000, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4000_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"objectType" / Int8ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4001, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4001_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"objectType" / Int8ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4002, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4002_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"byteCount" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4003, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4003_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"sample" / Int64ul,
"timestamp" / Int64sl,
"targetTime" / Int64sl,
"offset" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4004, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4004_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"sample" / Int64ul,
"targetQPC" / Int64sl,
"submittedQPC" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4005, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4005_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"sample" / Int64ul,
"originalTargetQPC" / Int64sl,
"targetQPC" / Int64sl,
"targetAhead" / Int64sl,
"submittedQPC" / Int64sl,
"submittedAhead" / Int64sl,
"now" / Int64sl,
"presentTime" / Int64sl,
"dwmFramesPresented" / Int64ul,
"dwmRefreshStartCount" / Int64sl,
"buffersEmpty" / Int32ul,
"refreshFrameCount" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4006, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4006_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"cPresentCount" / Int32ul,
"dwFlags" / Int32ul,
"hrResult" / Int32ul,
"llPresentTime" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4007, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4007_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"screenHeight" / Int32ul,
"frameHeightx1000" / Int32sl,
"frameRatex1000" / Int32sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4008, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4008_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hThread" / Int64ul,
"sleepType" / Int8ul,
"width" / Int32sl,
"height" / Int32sl,
"format" / Int32ul,
"retryCount" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4009, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4009_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"dataType" / Int8ul,
"sampleTime" / Int64sl,
"bytesDropped" / Int32ul,
"dropReasons" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4010, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4010_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"time" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4011, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4011_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"time" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4012, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4012_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"streamType" / Int8ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4013, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4013_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"stream" / Int64ul,
"byteCount" / Int32ul,
"type" / Bytes(lambda this: this.byteCount)
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4014, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4014_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"clsid" / Guid,
"transform" / Int64ul,
"userTransform" / Int8ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4015, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4015_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"objectCategory" / Int8ul,
"stream" / Int64ul,
"timestamp" / Int64sl,
"clock" / Int64ul,
"sample" / Int64ul,
"bufferSize" / Int32ul,
"sampleSize" / Int32ul,
"duration" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4016, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4016_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"objectCategory" / Int8ul,
"stream" / Int64ul,
"timestamp" / Int64sl,
"clock" / Int64ul,
"sample" / Int64ul,
"bufferSize" / Int32ul,
"sampleSize" / Int32ul,
"duration" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4017, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4017_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"objectCategory" / Int8ul,
"stream" / Int64ul,
"timestamp" / Int64sl,
"clock" / Int64ul,
"sample" / Int64ul,
"bufferSize" / Int32ul,
"sampleSize" / Int32ul,
"duration" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4018, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4018_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"objectCategory" / Int8ul,
"stream" / Int64ul,
"timestamp" / Int64sl,
"clock" / Int64ul,
"sample" / Int64ul,
"bufferSize" / Int32ul,
"sampleSize" / Int32ul,
"duration" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4019, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4019_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"objectCategory" / Int8ul,
"sample" / Int64ul,
"byteCount" / Int32ul,
"sampleTime" / Int64sl,
"processTime" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4020, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4020_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"objectCategory" / Int8ul,
"sample" / Int64ul,
"byteCount" / Int32ul,
"sampleTime" / Int64sl,
"processTime" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4021, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4021_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"objectCategory" / Int8ul,
"sample" / Int64ul,
"byteCount" / Int32ul,
"sampleTime" / Int64sl,
"processTime" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4022, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4022_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"processingType" / Int8sl,
"event" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4023, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4023_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"handle" / Int64ul,
"fileName" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4024, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4024_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"handle" / Int64ul,
"offset" / Int64ul,
"byteCount" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4025, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4025_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"handle" / Int64ul,
"offset" / Int64ul,
"byteCount" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4026, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4026_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"handle" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4027, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4027_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"handle" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4028, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4028_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"sample" / Int64ul,
"sampleTime" / Int64sl,
"sampleDuration" / Int64sl,
"clock" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4029, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4029_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"sample" / Int64ul,
"sampleTime" / Int64sl,
"sampleDuration" / Int64sl,
"clock" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4030, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4030_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"sample" / Int64ul,
"sampleTime" / Int64sl,
"sampleDuration" / Int64sl,
"clock" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4031, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4031_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"sample" / Int64ul,
"sampleTime" / Int64sl,
"sampleDuration" / Int64sl,
"clock" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4032, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4032_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"sample" / Int64ul,
"sampleTime" / Int64sl,
"sampleDuration" / Int64sl,
"clock" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4033, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4033_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"sample" / Int64ul,
"sampleTime" / Int64sl,
"sampleDuration" / Int64sl,
"clock" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4034, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4034_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"sample" / Int64ul,
"sampleTime" / Int64sl,
"sampleDuration" / Int64sl,
"clock" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4035, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4035_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"sample" / Int64ul,
"sampleTime" / Int64sl,
"sampleDuration" / Int64sl,
"clock" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4036, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4036_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"sample" / Int64ul,
"sampleTime" / Int64sl,
"sampleDuration" / Int64sl,
"clock" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4037, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4037_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"sample" / Int64ul,
"sampleTime" / Int64sl,
"sampleDuration" / Int64sl,
"clock" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4038, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4038_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"sample" / Int64ul,
"sampleTime" / Int64sl,
"sampleDuration" / Int64sl,
"clock" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4039, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4039_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"sample" / Int64ul,
"sampleTime" / Int64sl,
"sampleDuration" / Int64sl,
"clock" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4040, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4040_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"sample" / Int64ul,
"sampleTime" / Int64sl,
"sampleDuration" / Int64sl,
"clock" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4041, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4041_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"sample" / Int64ul,
"sampleTime" / Int64sl,
"sampleDuration" / Int64sl,
"clock" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4042, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4042_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"sample" / Int64ul,
"sampleTime" / Int64sl,
"sampleDuration" / Int64sl,
"clock" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4043, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4043_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"sample" / Int64ul,
"sampleTime" / Int64sl,
"sampleDuration" / Int64sl,
"clock" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4044, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4044_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"sample" / Int64ul,
"sampleTime" / Int64sl,
"sampleDuration" / Int64sl,
"clock" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4045, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4045_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"fullness" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4046, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4046_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4047, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4047_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4048, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4048_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4049, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4049_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4050, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4050_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4051, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4051_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4052, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4052_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4053, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4053_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"rtpSeq" / Int32ul,
"packetNumber" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4054, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4054_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"rtpSeq" / Int32ul,
"packetNumber" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4055, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4055_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"rtpSeq" / Int32ul,
"packetNumber" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4056, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4056_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"segmentID" / Int32ul,
"numberPending" / Int32ul,
"time" / Int64sl,
"sample" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4057, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4057_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"segmentID" / Int32ul,
"numberPending" / Int32ul,
"time" / Int64sl,
"sample" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4058, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4058_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"segmentID" / Int32ul,
"numberPending" / Int32ul,
"time" / Int64sl,
"sample" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4059, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4059_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"segmentID" / Int32ul,
"numberPending" / Int32ul,
"time" / Int64sl,
"sample" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4060, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4060_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"segmentID" / Int32ul,
"numberPending" / Int32ul,
"time" / Int64sl,
"sample" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4061, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4061_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"segmentID" / Int32ul,
"numberPending" / Int32ul,
"time" / Int64sl,
"sample" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4062, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4062_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"segmentID" / Int32ul,
"numberPending" / Int32ul,
"time" / Int64sl,
"sample" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4063, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4063_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"segmentID" / Int32ul,
"numberPending" / Int32ul,
"time" / Int64sl,
"sample" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4064, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4064_0(Etw):
pattern = Struct(
"tag" / CString,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4065, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4065_0(Etw):
pattern = Struct(
"tag" / CString,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4066, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4066_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"bytes" / Int32ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4067, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4067_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"bytes" / Int32ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4068, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4068_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"bytes" / Int32ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4069, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4069_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"bytes" / Int32ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4070, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4070_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"bytes" / Int32ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4071, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4071_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"bytes" / Int32ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4072, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4072_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"bytes" / Int32ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4073, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4073_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"bytes" / Int32ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4074, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4074_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"bytes" / Int32ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4075, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4075_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"bytes" / Int32ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4076, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4076_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"bytes" / Int32ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4077, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4077_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"bytes" / Int32ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4078, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4078_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"bytes" / Int32ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4079, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4079_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"bytes" / Int32ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4080, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4080_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"bytes" / Int32ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4081, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4081_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4082, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4082_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4083, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4083_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4084, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4084_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4085, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4085_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4086, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4086_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4087, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4087_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4088, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4088_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4089, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4089_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4090, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4090_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4091, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4091_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4092, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4092_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4093, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4093_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4094, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4094_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4095, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4095_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4096, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4096_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4097, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4097_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4098, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4098_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4099, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4099_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4100, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4100_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4101, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4101_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4102, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4102_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4103, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4103_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4104, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4104_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4105, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4105_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4106, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4106_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4107, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4107_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4108, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4108_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4109, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4109_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4110, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4110_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4111, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4111_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4112, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4112_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4113, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4113_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4114, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4114_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"guid" / Guid
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4115, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4115_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"arg1" / Int32ul,
"arg2" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4116, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4116_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"arg1" / Int32ul,
"arg2" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4117, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4117_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"arg1" / Int32ul,
"arg2" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4118, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4118_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"arg1" / Int32ul,
"arg2" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4119, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4119_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"arg1" / Int32ul,
"arg2" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4120, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4120_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"arg1" / Int32ul,
"arg2" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4121, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4121_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"arg1" / Int32ul,
"arg2" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4122, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4122_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"arg1" / Int32ul,
"arg2" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4123, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4123_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"arg1" / Int32ul,
"arg2" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4124, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4124_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"arg1" / Int32ul,
"arg2" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4125, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4125_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"arg1" / Int32ul,
"arg2" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4126, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4126_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"arg1" / Int32ul,
"arg2" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4127, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4127_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"arg1" / Int32ul,
"arg2" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4128, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4128_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"arg1" / Int32ul,
"arg2" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4129, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4129_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4130, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4130_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4131, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4131_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4132, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4132_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4133, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4133_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4134, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4134_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4135, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4135_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4136, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4136_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4137, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4137_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4138, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4138_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4139, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4139_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4140, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4140_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4141, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4141_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4142, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4142_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4143, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4143_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4144, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4144_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4145, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4145_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4146, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4146_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4147, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4147_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4148, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4148_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4149, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4149_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4150, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4150_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4151, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4151_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4152, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4152_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4153, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4153_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4154, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4154_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4155, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4155_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4156, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4156_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4157, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4157_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4158, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4158_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4159, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4159_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4160, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4160_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4161, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4161_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4162, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4162_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4163, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4163_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4164, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4164_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4165, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4165_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4166, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4166_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4167, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4167_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4168, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4168_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4169, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4169_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4170, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4170_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4171, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4171_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4172, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4172_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4173, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4173_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4174, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4174_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4175, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4175_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4176, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4176_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4177, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4177_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4178, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4178_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4179, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4179_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4180, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4180_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4181, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4181_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4182, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4182_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4183, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4183_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4184, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4184_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4185, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4185_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4186, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4186_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4187, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4187_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4188, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4188_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4189, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4189_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4190, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4190_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4191, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4191_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4192, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4192_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4193, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4193_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4194, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4194_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4195, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4195_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4196, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4196_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4197, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4197_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4198, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4198_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4199, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4199_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4200, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4200_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4201, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4201_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4202, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4202_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4203, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4203_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4204, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4204_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4205, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4205_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4206, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4206_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"arg" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4207, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4207_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"url" / WString,
"objectCreated" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4208, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4208_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"url" / WString,
"objectCreated" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4209, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4209_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"url" / WString,
"objectCreated" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4210, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4210_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"url" / WString,
"objectCreated" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4211, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4211_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"url" / WString,
"objectCreated" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4212, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4212_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"url" / WString,
"objectCreated" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4213, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4213_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"url" / WString,
"objectCreated" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4214, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4214_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"url" / WString,
"objectCreated" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4215, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4215_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"url" / WString,
"objectCreated" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4216, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4216_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"url" / WString,
"objectCreated" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4217, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4217_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"url" / WString,
"objectCreated" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4218, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4218_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"url" / WString,
"objectCreated" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4219, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4219_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"url" / WString,
"objectCreated" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4220, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4220_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"url" / WString,
"objectCreated" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4221, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4221_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"url" / WString,
"objectCreated" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4222, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4222_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"url" / WString,
"objectCreated" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4223, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4223_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"url" / WString,
"objectCreated" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4224, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4224_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"url" / WString,
"objectCreated" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4225, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4225_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"url" / WString,
"objectCreated" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4226, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4226_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"url" / WString,
"objectCreated" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4227, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4227_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"url" / WString,
"objectCreated" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4228, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4228_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"url" / WString,
"objectCreated" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4229, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4229_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"url" / WString,
"objectCreated" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4230, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4230_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"url" / WString,
"objectCreated" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4231, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4231_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"state" / Int32ul,
"context" / Int32ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4232, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4232_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"state" / Int32ul,
"context" / Int32ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4233, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4233_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"state" / Int32ul,
"context" / Int32ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4234, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4234_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"state" / Int32ul,
"context" / Int32ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4235, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4235_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"state" / Int32ul,
"context" / Int32ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4236, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4236_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"state" / Int32ul,
"context" / Int32ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4237, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4237_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"state" / Int32ul,
"context" / Int32ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4238, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4238_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"state" / Int32ul,
"context" / Int32ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4239, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4239_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"state" / Int32ul,
"context" / Int32ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4240, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4240_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4241, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4241_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4242, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4242_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4243, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4243_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4244, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4244_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4245, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4245_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4246, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4246_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4247, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4247_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4248, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4248_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4249, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4249_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4250, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4250_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4251, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4251_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4252, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4252_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4253, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4253_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4254, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4254_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"eventType" / Int32ul,
"time" / Int64sl,
"parameter" / Int64ul,
"url" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4255, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4255_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"eventType" / Int32ul,
"time" / Int64sl,
"parameter" / Int64ul,
"url" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4256, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4256_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"eventType" / Int32ul,
"time" / Int64sl,
"parameter" / Int64ul,
"url" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4257, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4257_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"eventType" / Int32ul,
"time" / Int64sl,
"parameter" / Int64ul,
"url" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4258, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4258_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"eventType" / Int32ul,
"time" / Int64sl,
"parameter" / Int64ul,
"url" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4259, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4259_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"eventType" / Int32ul,
"time" / Int64sl,
"parameter" / Int64ul,
"url" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4260, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4260_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"eventType" / Int32ul,
"time" / Int64sl,
"parameter" / Int64ul,
"url" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4261, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4261_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"knobID" / Int32ul,
"previousLevel" / Int32ul,
"newLevel" / Int32ul,
"dropTime" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4262, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4262_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"knobID" / Int32ul,
"previousLevel" / Int32ul,
"newLevel" / Int32ul,
"dropTime" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4263, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4263_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"knobID" / Int32ul,
"previousLevel" / Int32ul,
"newLevel" / Int32ul,
"dropTime" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4264, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4264_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"eventType" / Int32ul,
"time" / Int64sl,
"parameter" / Int64ul,
"url" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4265, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4265_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"eventType" / Int32ul,
"time" / Int64sl,
"parameter" / Int64ul,
"url" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4266, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4266_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"eventType" / Int32ul,
"time" / Int64sl,
"parameter" / Int64ul,
"url" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4267, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4267_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"eventType" / Int32ul,
"time" / Int64sl,
"parameter" / Int64ul,
"url" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4268, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4268_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"eventType" / Int32ul,
"time" / Int64sl,
"parameter" / Int64ul,
"url" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4269, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4269_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"eventType" / Int32ul,
"time" / Int64sl,
"parameter" / Int64ul,
"url" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4270, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4270_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"eventType" / Int32ul,
"time" / Int64sl,
"parameter" / Int64ul,
"url" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4271, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4271_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"eventType" / Int32ul,
"time" / Int64sl,
"parameter" / Int64ul,
"url" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4272, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4272_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"originalTime" / Int64sl,
"adjustment" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4273, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4273_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"originalTime" / Int64sl,
"adjustment" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4274, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4274_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"sample" / Int64ul,
"sampleTime" / Int64sl,
"sampleDuration" / Int64sl,
"clockTime" / Int64sl,
"hwnd" / Int64ul,
"refreshRate" / Int32ul,
"width" / Int32ul,
"height" / Int32ul,
"left" / Int32ul,
"top" / Int32ul,
"right" / Int32ul,
"bottom" / Int32ul,
"left1" / Int32ul,
"top1" / Int32ul,
"right1" / Int32ul,
"bottom1" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4275, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4275_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"sample" / Int64ul,
"sampleTime" / Int64sl,
"sampleDuration" / Int64sl,
"masterTime" / Int64sl,
"deviceTime" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4276, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4276_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"propertyKey" / Int64ul,
"propvariant" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4277, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4277_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"propertyKey" / Int64ul,
"propvariant" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4278, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4278_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"propertyKey" / Int64ul,
"propvariant" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4279, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4279_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"propertyKey" / Int64ul,
"propvariant" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4280, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4280_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"propertyKey" / Int64ul,
"propvariant" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4281, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4281_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"propertyKey" / Int64ul,
"propvariant" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4282, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4282_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"propertyKey" / Int64ul,
"propvariant" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4283, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4283_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"propertyKey" / Int64ul,
"propvariant" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4284, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4284_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"propertyKey" / Int64ul,
"propvariant" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4285, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4285_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"propertyKey" / Int64ul,
"propvariant" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4286, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4286_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"propertyKey" / Int64ul,
"propvariant" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4287, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4287_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul,
"propertyKey" / Int64ul,
"propvariant" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4288, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4288_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"streamNumber" / Int32ul,
"sampleTime" / Int64sl,
"sampleByteCount" / Int32ul,
"packetNumber" / Int64sl,
"packetSendTime" / Int64sl,
"packetByteCount" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4289, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4289_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"streamNumber" / Int32ul,
"sampleTime" / Int64sl,
"sampleByteCount" / Int32ul,
"packetNumber" / Int64sl,
"packetSendTime" / Int64sl,
"packetByteCount" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4290, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4290_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"streamNumber" / Int32ul,
"sampleTime" / Int64sl,
"sampleByteCount" / Int32ul,
"packetNumber" / Int64sl,
"packetSendTime" / Int64sl,
"packetByteCount" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4291, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4291_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"eventTime" / Int64sl,
"lateBy" / Int64sl,
"callback" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4292, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4292_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4293, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4293_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4294, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4294_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4295, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4295_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4296, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4296_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4297, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4297_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4298, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4298_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4299, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4299_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4300, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4300_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4301, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4301_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4302, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4302_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4303, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4303_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4304, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4304_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4305, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4305_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4306, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4306_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4307, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4307_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4308, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4308_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4309, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4309_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4310, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4310_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4311, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4311_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4312, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4312_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4313, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4313_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4314, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4314_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4315, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4315_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4316, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4316_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4317, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4317_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4318, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4318_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4319, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4319_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4320, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4320_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4321, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4321_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4322, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4322_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4323, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4323_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4324, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4324_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4325, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4325_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4326, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4326_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4327, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4327_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4328, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4328_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4329, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4329_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4330, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4330_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4331, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4331_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4332, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4332_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4333, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4333_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4334, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4334_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4335, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4335_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4336, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4336_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4337, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4337_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4338, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4338_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4339, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4339_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4340, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4340_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4341, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4341_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4342, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4342_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4343, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4343_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4344, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4344_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4345, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4345_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4346, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4346_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4347, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4347_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4348, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4348_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4349, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4349_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4350, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4350_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4351, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4351_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4352, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4352_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4353, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4353_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4354, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4354_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4355, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4355_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4356, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4356_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4357, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4357_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4358, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4358_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4359, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4359_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4360, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4360_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4361, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4361_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4362, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4362_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4363, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4363_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4364, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4364_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int32ul,
"bstr" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4365, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4365_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int32ul,
"bstr" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4366, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4366_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int32ul,
"bstr" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4367, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4367_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int32ul,
"bstr" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4368, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4368_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int32ul,
"bstr" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4369, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4369_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int32ul,
"bstr" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4370, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4370_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int32ul,
"bstr" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4371, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4371_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int32ul,
"bstr" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4372, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4372_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int32ul,
"bstr" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4373, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4373_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int32ul,
"bstr" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4374, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4374_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int32ul,
"bstr" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4375, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4375_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int32ul,
"bstr" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4376, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4376_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int32ul,
"bstr" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4377, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4377_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int32ul,
"bstr" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4378, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4378_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int32ul,
"bstr" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4379, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4379_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int32ul,
"bstr" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4380, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4380_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int32ul,
"bstr" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4381, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4381_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int32ul,
"bstr" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4382, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4382_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int32ul,
"bstr" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4383, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4383_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int32ul,
"bstr" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4384, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4384_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int32ul,
"bstr" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4385, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4385_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int32ul,
"bstr" / WString
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4386, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4386_0(Etw):
pattern = Struct(
"fileName" / WString,
"graphType" / Int8ul,
"lastHr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4387, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4387_0(Etw):
pattern = Struct(
"fileName" / WString,
"graphType" / Int8ul,
"lastHr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4388, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4388_0(Etw):
pattern = Struct(
"fileName" / WString,
"graphType" / Int8ul,
"lastHr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4389, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4389_0(Etw):
pattern = Struct(
"fileName" / WString,
"graphType" / Int8ul,
"lastHr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4390, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4390_0(Etw):
pattern = Struct(
"fileName" / WString,
"graphType" / Int8ul,
"lastHr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4391, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4391_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4392, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4392_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4393, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4393_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4394, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4394_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4395, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4395_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4396, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4396_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4397, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4397_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4398, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4398_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4399, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4399_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4400, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4400_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4401, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4401_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"initialOffset" / Int64sl,
"finalOffset" / Int64sl,
"bytesInCache" / Int32ul,
"cacheSize" / Int32ul,
"sectorSize" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4402, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4402_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"frameIndex" / Int32ul,
"sampleTime" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4403, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4403_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"frameIndex" / Int32ul,
"sampleTime" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4404, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4404_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"frameIndex" / Int32ul,
"sampleTime" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4405, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4405_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"frameIndex" / Int32ul,
"sampleTime" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4406, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4406_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"frameIndex" / Int32ul,
"sampleTime" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4407, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4407_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"frameIndex" / Int32ul,
"sampleTime" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4408, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4408_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4409, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4409_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"parameter" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4410, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4410_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"operation" / Int32sl,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4411, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4411_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"operation" / Int32sl,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4412, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4412_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"contentType" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4413, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4413_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"contentType" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4414, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4414_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"contentType" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4415, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4415_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"contentType" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4416, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4416_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"contentType" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4417, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4417_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"contentType" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4418, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4418_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"contentType" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4419, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4419_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"contentType" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4420, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4420_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"contentType" / Int32ul,
"propertyKeyGuid" / Guid,
"propertyKeyFmtId" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4421, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4421_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"contentType" / Int32ul,
"propertyKeyGuid" / Guid,
"propertyKeyFmtId" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4422, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4422_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"contentType" / Int32ul,
"propertyKeyGuid" / Guid,
"propertyKeyFmtId" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4423, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4423_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"contentType" / Int32ul,
"propertyKeyGuid" / Guid,
"propertyKeyFmtId" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4424, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4424_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"contentType" / Int32ul,
"propertyKeyGuid" / Guid,
"propertyKeyFmtId" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4425, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4425_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"contentType" / Int32ul,
"propertyKeyGuid" / Guid,
"propertyKeyFmtId" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4426, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4426_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"contentType" / Int32ul,
"propertyKeyGuid" / Guid,
"propertyKeyFmtId" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4427, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4427_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"contentType" / Int32ul,
"propertyKeyGuid" / Guid,
"propertyKeyFmtId" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4428, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4428_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4429, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4429_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4430, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4430_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4431, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4431_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4432, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4432_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"duration" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4433, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4433_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"duration" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4434, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4434_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"duration" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4437, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4437_0(Etw):
pattern = Struct(
"Buffer" / Int64ul,
"Width" / Int32ul,
"Height" / Int32ul,
"Format" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4438, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4438_0(Etw):
pattern = Struct(
"Buffer" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4439, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4439_0(Etw):
pattern = Struct(
"Buffer" / Int64ul,
"GUID" / Guid,
"Unknown" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4440, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4440_0(Etw):
pattern = Struct(
"Buffer" / Int64ul,
"GUID" / Guid,
"Unknown" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4441, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4441_0(Etw):
pattern = Struct(
"Pointer" / Int64ul,
"Length" / Int32sl,
"Type" / Int32sl,
"Max" / Int32sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4442, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4442_0(Etw):
pattern = Struct(
"Pointer" / Int64ul,
"Length" / Int32sl,
"Type" / Int32sl,
"Max" / Int32sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4443, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4443_0(Etw):
pattern = Struct(
"Pointer" / Int64ul,
"ParentQueuePointer" / Int64ul,
"Free" / Int32sl,
"Allocated" / Int32sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4444, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4444_0(Etw):
pattern = Struct(
"Pointer" / Int64ul,
"ParentQueuePointer" / Int64ul,
"Free" / Int32sl,
"Allocated" / Int32sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4445, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4445_0(Etw):
pattern = Struct(
"Pointer" / Int64ul,
"Direction" / Int32sl,
"Width" / Int32sl,
"Height" / Int32sl,
"Format" / Int32sl,
"Length" / Int32sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4446, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4446_0(Etw):
pattern = Struct(
"Pointer" / Int64ul,
"Direction" / Int32sl,
"Width" / Int32sl,
"Height" / Int32sl,
"Format" / Int32sl,
"Length" / Int32sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4447, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4447_0(Etw):
pattern = Struct(
"object" / Int64ul,
"contentType" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4448, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4448_0(Etw):
pattern = Struct(
"object" / Int64ul,
"contentType" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4449, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4449_0(Etw):
pattern = Struct(
"object" / Int64ul,
"contentType" / Int32ul,
"bestFrameIndex" / Int32ul,
"totalFrameDecoded" / Int32ul,
"timeoutin100NS" / Int64ul,
"isTimeout" / Int8ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4450, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4450_0(Etw):
pattern = Struct(
"Sample" / Int64ul,
"StreamIndex" / Int32ul,
"SampleTimestamp" / Int64ul,
"AdjustedTimestamp" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4451, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4451_0(Etw):
pattern = Struct(
"Sample" / Int64ul,
"StreamIndex" / Int32ul,
"SampleTimestamp" / Int64ul,
"AdjustedTimestamp" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4452, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4452_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4453, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4453_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4456, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4456_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"isLowLatency" / Int8ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4457, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4457_0(Etw):
pattern = Struct(
"object" / Int64ul,
"StreamIndex" / Int32ul,
"SampleTimestamp" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4458, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4458_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"byteCount" / Int64ul,
"totalByteCount" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4459, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4459_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"isRetryWorkItem" / Int8ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4460, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4460_0(Etw):
pattern = Struct(
"surface" / Int64ul,
"uSubresource" / Int32ul,
"Type" / Int32ul,
"Flags" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4461, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4461_0(Etw):
pattern = Struct(
"surface" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4462, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4462_0(Etw):
pattern = Struct(
"isLosigHardwareResource" / Int8ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4463, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4463_0(Etw):
pattern = Struct(
"IsGoingOn" / Int8ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4464, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4464_0(Etw):
pattern = Struct(
"SoundLevel" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4465, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4465_0(Etw):
pattern = Struct(
"status" / Int8ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4466, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4466_0(Etw):
pattern = Struct(
"tag" / CString,
"object" / Int64ul,
"BufferDuration" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4467, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4467_0(Etw):
pattern = Struct(
"SrcPtr" / Int64ul,
"DstPtr" / Int64ul,
"Width" / Int32sl,
"Height" / Int32sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4468, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4468_0(Etw):
pattern = Struct(
"SrcPtr" / Int64ul,
"DstPtr" / Int64ul,
"ReturnCode" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4469, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4469_0(Etw):
pattern = Struct(
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4470, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4470_0(Etw):
pattern = Struct(
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4471, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4471_0(Etw):
pattern = Struct(
"object" / Int64ul,
"dwStreamID" / Int32ul,
"uiPinID" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4472, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4472_0(Etw):
pattern = Struct(
"Object" / Int64ul,
"Sample" / Int64ul,
"Free" / Int32sl,
"Allocated" / Int32sl,
"MinSampleCount" / Int32sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4473, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4473_0(Etw):
pattern = Struct(
"SrcPtr" / Int64ul,
"Count" / Int32ul,
"DstPtr" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4474, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4474_0(Etw):
pattern = Struct(
"SrcPtr" / Int64ul,
"HResult" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4475, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4475_0(Etw):
pattern = Struct(
"surface" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4476, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4476_0(Etw):
pattern = Struct(
"surface" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4500, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4500_0(Etw):
pattern = Struct(
"Object" / Int64ul,
"PendingCount" / Int32sl,
"BytesSent" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4501, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4501_0(Etw):
pattern = Struct(
"Object" / Int64ul,
"PendingCount" / Int32sl,
"BytesSent" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4502, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4502_0(Etw):
pattern = Struct(
"Object" / Int64ul,
"PendingCount" / Int32sl,
"BytesSent" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4503, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4503_0(Etw):
pattern = Struct(
"Object" / Int64ul,
"PendingReceives" / Int32sl,
"BytesReceived" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4504, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4504_0(Etw):
pattern = Struct(
"Object" / Int64ul,
"PendingReceives" / Int32sl,
"BytesReceived" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4505, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4505_0(Etw):
pattern = Struct(
"Object" / Int64ul,
"PendingReceives" / Int32sl,
"BytesReceived" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4600, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4600_0(Etw):
pattern = Struct(
"system" / Guid
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4601, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4601_0(Etw):
pattern = Struct(
"object" / Int64ul,
"hrResult" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4602, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4602_0(Etw):
pattern = Struct(
"system" / Guid
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4603, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4603_0(Etw):
pattern = Struct(
"available" / Int8ul,
"hrResult" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4604, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4604_0(Etw):
pattern = Struct(
"object" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4605, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4605_0(Etw):
pattern = Struct(
"object" / Int64ul,
"functionID" / Int32ul,
"inputbytes" / Int32ul,
"outputbytes" / Int32ul,
"msTransportTime" / Int32ul,
"msExecutionTime" / Int32ul,
"msTotal" / Int32ul,
"hrResult" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4606, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4606_0(Etw):
pattern = Struct(
"system" / Guid,
"manager" / Int64ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4607, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4607_0(Etw):
pattern = Struct(
"object" / Int64ul,
"hrResult" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4608, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4608_0(Etw):
pattern = Struct(
"object" / Int64ul,
"hrResult" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4612, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4612_0(Etw):
pattern = Struct(
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4614, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4614_0(Etw):
pattern = Struct(
"hr" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4615, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4615_0(Etw):
pattern = Struct(
"object" / Int64ul,
"bytestowrite" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4616, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4616_0(Etw):
pattern = Struct(
"object" / Int64ul,
"byteswritten" / Int32ul,
"hrResult" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4617, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4617_0(Etw):
pattern = Struct(
"object" / Int64ul,
"StreamIndex" / Int32ul,
"StreamType" / Int32ul,
"timestamp" / Int64sl,
"sample" / Int64ul,
"duration" / Int64sl
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4618, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4618_0(Etw):
pattern = Struct(
"object" / Int64ul,
"StreamIndex" / Int32ul,
"hrResult" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4619, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4619_0(Etw):
pattern = Struct(
"object" / Int64ul,
"Index" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4620, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4620_0(Etw):
pattern = Struct(
"object" / Int64ul,
"hrResult" / Int32ul
)
@declare(guid=guid("f404b94e-27e0-4384-bfe8-1d8d390b0aa3"), event_id=4621, version=0)
class Microsoft_Windows_MediaFoundation_Performance_4621_0(Etw):
pattern = Struct(
"object" / Int64ul,
"StreamIndex" / Int32ul,
"StreamType" / Int32ul,
"timestamp" / Int64sl,
"sample" / Int64ul,
"duration" / Int64sl
)
|
util/patch/aslr.py | EarthCompass/patchkit | 631 | 11095737 | <reponame>EarthCompass/patchkit
import random
from collections import defaultdict
from util.patch.dis import irdis, IR
def aslr(pt, count=3):
funcs = {}
saved = []
holes = []
pos = pt.binary.next_alloc()
for func in pt.funcs():
if func.size < 5:
continue
ir = irdis(func.dis())
size = len(pt.asm(ir.asm(), addr=pos))
saved.append((func, ir, size))
holes.append((func.addr + 5, func.size - 5))
func.nop()
pt.make_writable(func.addr)
funcs = defaultdict(list)
tmp = []
for func, ir, size in saved:
for hook in pt.binary.asm_hook:
pt.info('[ASM Hook] %s.%s() on 0x%x' % (hook.__module__, hook.__name__, func.addr))
tmpir = hook(pt, ir)
if tmpir:
ir = IR(tmpir)
tmp.append((func, ir, size))
saved = tmp
holes.sort(key=lambda x: x[1])
for i in xrange(count):
random.shuffle(saved)
for func, ir, size in saved:
txt = ir.asm()
tmp = [h for h in holes if h[0] != func.addr + 5 and h[1] >= size]
if tmp:
addr, hsize = tmp[0]
holes.remove(tmp[0])
raw = pt.asm(txt, addr=addr)
if len(raw) <= hsize:
pt.patch(addr, raw=raw, is_asm=True)
funcs[func].append((addr, len(raw)))
continue
addr, isize = pt.inject(asm=txt, size=True, is_asm=True)
funcs[func].append((addr, isize))
return funcs
|
DQMOffline/Trigger/python/susyHLTEleCaloJetsClient_cfi.py | ckamtsikis/cmssw | 852 | 11095755 | import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDHarvester import DQMEDHarvester
susyHLTEleCaloJetsClient = DQMEDHarvester("DQMGenericClient",
subDirs = cms.untracked.vstring(
'HLT/SUSY/Ele8CaloJet30/*',
'HLT/SUSY/Ele8CaloIdMJet30/*',
'HLT/SUSY/Ele12CaloJet30/*',
'HLT/SUSY/Ele17CaloIdMJet30/*',
'HLT/SUSY/Ele23CaloJet30/*',
'HLT/SUSY/Ele23CaloIdMJet30/*'
),
verbose = cms.untracked.uint32(0), # Set to 2 for all messages
resolution = cms.vstring(),
efficiency = cms.vstring(
"effic_metME 'efficiency vs MET; MET [GeV]; efficiency' metME_numerator metME_denominator",
"effic_elePt_1 'efficiency vs electron pt; electron pt [GeV]; efficiency' elePt_1_numerator elePt_1_denominator",
"effic_eleEta_1 'efficiency vs electron eta; electron eta ; efficiency' eleEta_1_numerator eleEta_1_denominator",
"effic_elePhi_1 'efficiency vs electron phi; electron phi ; efficiency' elePhi_1_numerator elePhi_1_denominator",
"effic_jetPt_1 'efficiency vs leading jet pt; jet pt [GeV]; efficiency' jetPt_1_numerator jetPt_1_denominator",
"effic_jetEta_1 'efficiency vs leading jet eta; jet eta ; efficiency' jetEta_1_numerator jetEta_1_denominator",
"effic_jetPhi_1 'efficiency vs leading jet phi; jet phi ; efficiency' jetPhi_1_numerator jetPhi_1_denominator",
"effic_eventHT 'efficiency vs event HT; event HT [GeV]; efficiency' eventHT_numerator eventHT_denominator",
"effic_jetEtaPhi_HEP17 'efficiency vs jet #eta-#phi; jet #eta; jet #phi' jetEtaPhi_HEP17_numerator jetEtaPhi_HEP17_denominator",
"effic_elePt_1_variableBinning 'efficiency vs electron pt; electron pt [GeV]; efficiency' elePt_1_variableBinning_numerator elePt_1_variableBinning_denominator",
"effic_eleEta_1_variableBinning 'efficiency vs electron eta; electron eta ; efficiency' eleEta_1_variableBinning_numerator eleEta_1_variableBinning_denominator",
"effic_jetPt_1_variableBinning 'efficiency vs leading jet pt; jet pt [GeV]; efficiency' jetPt_1_variableBinning_numerator jetPt_1_variableBinning_denominator",
"effic_jetEta_1_variableBinning 'efficiency vs leading jet eta; jet eta ; efficiency' jetEta_1_variableBinning_numerator jetEta_1_variableBinning_denominator",
"effic_eventHT_variableBinning 'efficiency vs event HT; event HT [GeV]; efficiency' eventHT_variableBinning_numerator eventHT_variableBinning_denominator",
"effic_jetMulti 'efficiency vs jet multiplicity; jet multiplicity; efficiency' jetMulti_numerator jetMulti_denominator",
"effic_eleMulti 'efficiency vs electron multiplicity; electron multiplicity; efficiency' eleMulti_numerator eleMulti_denominator",
"effic_muMulti 'efficiency vs muon multiplicity; muon multiplicity; efficiency' muMulti_numerator muMulti_denominator",
"effic_elePtEta_1 'efficiency vs electron pt-#eta; electron pt [GeV]; electron #eta' elePtEta_1_numerator elePtEta_1_denominator",
"effic_eleEtaPhi_1 'efficiency vs electron #eta-#phi; electron #eta ; electron #phi' eleEtaPhi_1_numerator eleEtaPhi_1_denominator",
"effic_jetPtEta_1 'efficiency vs jet pt-#eta; jet pt [GeV]; jet #eta' jetPtEta_1_numerator jetPtEta_1_denominator",
"effic_jetEtaPhi_1 'efficiency vs jet #eta-#phi; jet #eta ; jet #phi' jetEtaPhi_1_numerator jetEtaPhi_1_denominator",
"effic_elePt_jetPt 'efficiency vs electron pt - jet pt; electron pt [GeV] ; jet pt [GeV]' elePt_jetPt_numerator elePt_jetPt_denominator",
"effic_elePt_eventHT 'efficiency vs electron pt - event HT; electron pt [GeV] ; event HT [GeV]' elePt_eventHT_numerator elePt_eventHT_denominator",
),
)
|
hwt/pyUtils/testUtils.py | ufo2011/hwt | 134 | 11095763 | from itertools import product
class TestMatrix():
"""
Class which instance is a decorator which executes unittest.TestCase
test method with every combination of argumets
"""
def __init__(self, *args, **kwargs):
"""
:note: args, kwargs are lists of arguments which should be passed as a test
arguments
"""
self.args = args
kwargs = sorted(kwargs.items(), key=lambda x: x[0])
self.kwargs_keys = [x[0] for x in kwargs]
self.kwargs_values = [x[1] for x in kwargs]
self.test_arg_values = list(product(*args, *self.kwargs_values))
def split_args_kwargs(self, args):
kwargs_cnt = len(self.kwargs_keys)
if kwargs_cnt:
_args = args[:kwargs_cnt]
kwargs = {k: v for k, v in zip(
self.kwargs_keys, args[:kwargs_cnt])}
return _args, kwargs
else:
return args, {}
def __call__(self, test_fn):
test_matrix = self
def test_wrap(self):
for args in test_matrix.test_arg_values:
args, kwargs = test_matrix.split_args_kwargs(args)
try:
test_fn(self, *args, **kwargs)
except Exception as e:
# add note to an exception about which test arguments were
# used
# import traceback
# traceback.print_exc()
msg_buff = []
for a in args:
msg_buff.append(repr(a))
for k in test_matrix.kwargs_keys:
msg_buff.append("%s=%r" % (k, kwargs[k]))
raise Exception(
"Test failed %s" % (", ".join(msg_buff)), ) from e
return test_wrap
|
robot-server/tests/test_app.py | anuwrag/opentrons | 235 | 11095791 | <reponame>anuwrag/opentrons
"""Tests for FastAPI application object of the robot server."""
import pytest
from mock import MagicMock, patch
from fastapi import status
from fastapi.testclient import TestClient
from typing import Iterator
from robot_server.versioning import API_VERSION_HEADER, API_VERSION
@pytest.fixture
def mock_log_control() -> Iterator[MagicMock]:
"""Patch out the log retrieval logic."""
with patch("opentrons.system.log_control.get_records_dumb") as p:
p.return_value = b""
yield p
@pytest.mark.parametrize(
argnames="path",
argvalues=[
"/logs/serial.log",
"/logs/api.log",
"/",
],
)
def test_api_versioning_non_versions_endpoints(
api_client: TestClient,
path: str,
mock_log_control: MagicMock,
) -> None:
"""It should not enforce versioning requirements on some endpoints."""
del api_client.headers["Opentrons-Version"]
resp = api_client.get(path)
assert resp.status_code != status.HTTP_422_UNPROCESSABLE_ENTITY
assert resp.headers.get(API_VERSION_HEADER) == str(API_VERSION)
|
tracardi/process_engine/action/v1/connectors/mongo/query/plugin.py | Tracardi/tracardi | 153 | 11095793 | <gh_stars>100-1000
import json
from json import JSONDecodeError
from tracardi.domain.resource import ResourceCredentials
from tracardi.domain.resource_config import ResourceConfig
from tracardi.service.plugin.plugin_endpoint import PluginEndpoint
from tracardi.service.storage.driver import storage
from tracardi.service.plugin.domain.register import Plugin, Spec, MetaData, Form, FormGroup, FormField, FormComponent
from tracardi.service.plugin.runner import ActionRunner
from tracardi.service.plugin.domain.result import Result
from .model.client import MongoClient
from .model.configuration import PluginConfiguration, MongoConfiguration, DatabaseConfig
def validate(config: dict) -> PluginConfiguration:
config = PluginConfiguration(**config)
try:
json.loads(config.query)
except JSONDecodeError as e:
raise ValueError("Can not parse this data as JSON. Error: `{}`".format(str(e)))
return config
class MongoConnectorAction(ActionRunner):
@staticmethod
async def build(**kwargs) -> 'MongoConnectorAction':
config = PluginConfiguration(**kwargs)
resource = await storage.driver.resource.load(config.source.id)
return MongoConnectorAction(config, resource.credentials)
def __init__(self, config: PluginConfiguration, credentials: ResourceCredentials):
mongo_config = credentials.get_credentials(self, output=MongoConfiguration) # type: MongoConfiguration
self.client = MongoClient(mongo_config)
self.config = config
async def run(self, payload):
try:
query = json.loads(self.config.query)
except JSONDecodeError as e:
raise ValueError("Can not parse this data as JSON. Error: `{}`".format(str(e)))
result = await self.client.find(self.config.database.id, self.config.collection.id, query)
return Result(port="payload", value={"result": result})
# async def close(self):
# await self.client.close()
class Endpoint(PluginEndpoint):
@staticmethod
async def fetch_databases(config):
config = ResourceConfig(**config)
resource = await storage.driver.resource.load(config.source.id)
mongo_config = MongoConfiguration(**resource.credentials.production)
client = MongoClient(mongo_config)
databases = await client.dbs()
return {
"total": len(databases),
"result": [{"name": db, "id": db} for db in databases]
}
@staticmethod
async def fetch_collections(config):
config = DatabaseConfig(**config)
resource = await storage.driver.resource.load(config.source.id)
mongo_config = MongoConfiguration(**resource.credentials.production)
client = MongoClient(mongo_config)
collections = await client.collections(config.database.id)
return {
"total": len(collections),
"result": [{"name": item, "id": item} for item in collections]
}
def register() -> Plugin:
return Plugin(
start=False,
spec=Spec(
module=__name__,
className='MongoConnectorAction',
inputs=["payload"],
outputs=['payload'],
version='0.6.2',
license="MIT",
author="<NAME>",
manual="mongo_query_action",
init={
"source": {
"id": None,
},
"database": None,
"collection": None,
"query": "{}"
},
form=Form(groups=[
FormGroup(
name="MongoDB connection settings",
fields=[
FormField(
id="source",
name="MongoDB resource",
description="Select MongoDB resource. Authentication credentials will be used to "
"connect to MongoDB server.",
component=FormComponent(
type="resource",
props={"label": "resource", "tag": "mongo"})
)
]
),
FormGroup(
name="Query settings",
fields=[
FormField(
id="database",
name="Database",
description="Select database URI you want to connect to. If you see error select resource "
"first so we know which resource to connect to fetch a list of databases.",
component=FormComponent(type="autocomplete", props={
"label": "Database URI",
"endpoint": {
"url": Endpoint.url(__name__, "fetch_databases"),
"method": "post"
}
})
),
FormField(
id="collection",
name="Collection",
description="Select collection you would like to fetch data from. If you see error select "
"resource and database first so we know which resource and database to connect "
"to fetch a list of collections.",
component=FormComponent(type="autocomplete", props={
"label": "Collection",
"endpoint": {
"url": Endpoint.url(__name__, "fetch_collections"),
"method": "post"
}
})
),
FormField(
id="query",
name="Query",
description="Type query.",
component=FormComponent(type="json", props={"label": "Query"})
),
])
]),
),
metadata=MetaData(
name='Mongo connector',
desc='Connects to mongodb and reads data.',
icon='mongo',
group=["Connectors"]
)
)
|
tests/blocks/signal/pulseamplitudemodulator_spec.py | grascher-oe8agk/luaradio | 559 | 11095807 | <reponame>grascher-oe8agk/luaradio
import math
import numpy
from generate import *
def generate():
def process(symbol_rate, sample_rate, levels, amplitudes, msb_first, x):
symbol_period = int(sample_rate / symbol_rate)
symbol_bits = int(math.log2(levels))
if amplitudes is None:
scaling = math.sqrt((levels ** 2 - 1) / 3)
amplitudes = {}
for level in range(levels):
gray_level = level ^ (level >> 1)
amplitudes[gray_level] = (2 * level - levels + 1) / scaling
out = []
for i in range(0, (len(x) // symbol_bits) * symbol_bits, symbol_bits):
bits = x[i:i + symbol_bits][::1 if msb_first else -1]
value = sum([bits[j] << (symbol_bits - j - 1) for j in range(symbol_bits)])
out += [amplitudes[value]] * symbol_period
return [numpy.array(out).astype(numpy.float32)]
vectors = []
# Symbol rate of 0.4 with sample rate of 2.0 means we have a symbol period of 5
x = random_bit(256)
vectors.append(TestVector([0.4, 2.0, 2], [x], process(0.4, 2.0, 2, None, True, x), "0.4 symbol rate, 2.0 sample rate, 256 Bit input, 2 levels, 1280 Float32 output"))
vectors.append(TestVector([0.4, 2.0, 4], [x], process(0.4, 2.0, 4, None, True, x), "0.4 symbol rate, 2.0 sample rate, 256 Bit input, 4 levels, 640 Float32 output"))
vectors.append(TestVector([0.4, 2.0, 8], [x], process(0.4, 2.0, 8, None, True, x), "0.4 symbol rate, 2.0 sample rate, 256 Bit input, 8 levels, 425 Float32 output"))
vectors.append(TestVector([0.4, 2.0, 4, "{amplitudes = {[0] = -2, [1] = -1, [3] = 1, [2] = 2}}"], [x], process(0.4, 2.0, 4, {0: -2, 1: -1, 3: 1, 2: 2}, True, x), "0.4 symbol rate, 2.0 sample rate, custom 4 level amplitudes, 256 Bit input, 640 Float32 output"))
vectors.append(TestVector([0.4, 2.0, 8, "{msb_first = false}"], [x], process(0.4, 2.0, 8, None, False, x), "0.4 symbol rate, 2.0 sample rate, 8 levels, lsb first, 256 Bit input, 425 Float32 output"))
return BlockSpec("PulseAmplitudeModulatorBlock", vectors, 1e-6)
|
redisco/models/modelset.py | iamteem/redisco | 110 | 11095822 | """
Handles the queries.
"""
from attributes import IntegerField, DateTimeField
import redisco
from redisco.containers import SortedSet, Set, List, NonPersistentList
from exceptions import AttributeNotIndexed
from utils import _encode_key
from attributes import ZINDEXABLE
# Model Set
class ModelSet(Set):
def __init__(self, model_class):
self.model_class = model_class
self.key = model_class._key['all']
self._db = redisco.get_client()
self._filters = {}
self._exclusions = {}
self._zfilters = []
self._ordering = []
self._limit = None
self._offset = None
#################
# MAGIC METHODS #
#################
def __getitem__(self, index):
if isinstance(index, slice):
return map(lambda id: self._get_item_with_id(id), self._set[index])
else:
id = self._set[index]
if id:
return self._get_item_with_id(id)
else:
raise IndexError
def __repr__(self):
if len(self._set) > 30:
m = self._set[:30]
else:
m = self._set
s = map(lambda id: self._get_item_with_id(id), m)
return "%s" % s
def __iter__(self):
for id in self._set:
yield self._get_item_with_id(id)
def __len__(self):
return len(self._set)
def __contains__(self, val):
return val.id in self._set
##########################################
# METHODS THAT RETURN A SET OF INSTANCES #
##########################################
def get_by_id(self, id):
if self.model_class.exists(id):
return self._get_item_with_id(id)
def first(self):
try:
return self.limit(1).__getitem__(0)
except IndexError:
return None
#####################################
# METHODS THAT MODIFY THE MODEL SET #
#####################################
def filter(self, **kwargs):
clone = self._clone()
if not clone._filters:
clone._filters = {}
clone._filters.update(kwargs)
return clone
def exclude(self, **kwargs):
clone = self._clone()
if not clone._exclusions:
clone._exclusions = {}
clone._exclusions.update(kwargs)
return clone
def zfilter(self, **kwargs):
clone = self._clone()
if not clone._zfilters:
clone._zfilters = []
clone._zfilters.append(kwargs)
return clone
# this should only be called once
def order(self, field):
fname = field.lstrip('-')
if fname not in self.model_class._indices:
raise ValueError("Order parameter should be an indexed attribute.")
alpha = True
if fname in self.model_class._attributes:
v = self.model_class._attributes[fname]
alpha = not isinstance(v, ZINDEXABLE)
clone = self._clone()
if not clone._ordering:
clone._ordering = []
clone._ordering.append((field, alpha,))
return clone
def limit(self, n, offset=0):
clone = self._clone()
clone._limit = n
clone._offset = offset
return clone
def create(self, **kwargs):
instance = self.model_class(**kwargs)
if instance.save():
return instance
else:
return None
def all(self):
return self._clone()
def get_or_create(self, **kwargs):
opts = {}
for k, v in kwargs.iteritems():
if k in self.model_class._indices:
opts[k] = v
o = self.filter(**opts).first()
if o:
return o
else:
return self.create(**kwargs)
#
@property
def db(self):
return self._db
###################
# PRIVATE METHODS #
###################
@property
def _set(self):
# For performance reasons, only one zfilter is allowed.
if hasattr(self, '_cached_set'):
return self._cached_set
if self._zfilters:
self._cached_set = self._add_zfilters()
return self._cached_set
s = Set(self.key)
self._expire_or_delete = []
if self._filters:
s = self._add_set_filter(s)
if self._exclusions:
s = self._add_set_exclusions(s)
n = self._order(s.key)
self._cached_set = list(self._order(s.key))
for key in filter(lambda key: key != self.key, self._expire_or_delete):
del self.db[key]
return self._cached_set
def _add_set_filter(self, s):
indices = []
for k, v in self._filters.iteritems():
index = self._build_key_from_filter_item(k, v)
if k not in self.model_class._indices:
raise AttributeNotIndexed(
"Attribute %s is not indexed in %s class." %
(k, self.model_class.__name__))
indices.append(index)
new_set_key = "~%s.%s" % ("+".join([self.key] + indices), id(self))
s.intersection(new_set_key, *[Set(n) for n in indices])
self._expire_or_delete.append(new_set_key)
return Set(new_set_key)
def _add_set_exclusions(self, s):
indices = []
for k, v in self._exclusions.iteritems():
index = self._build_key_from_filter_item(k, v)
if k not in self.model_class._indices:
raise AttributeNotIndexed(
"Attribute %s is not indexed in %s class." %
(k, self.model_class.__name__))
indices.append(index)
new_set_key = "~%s.%s" % ("-".join([self.key] + indices), id(self))
s.difference(new_set_key, *[Set(n) for n in indices])
self._expire_or_delete.append(new_set_key)
return Set(new_set_key)
def _add_zfilters(self):
k, v = self._zfilters[0].items()[0]
try:
att, op = k.split('__')
except ValueError:
raise ValueError("zfilter should have an operator.")
index = self.model_class._key[att]
desc = self.model_class._attributes[att]
zset = SortedSet(index)
limit, offset = self._get_limit_and_offset()
if isinstance(v, (tuple, list,)):
min, max = v
min = float(desc.typecast_for_storage(min))
max = float(desc.typecast_for_storage(max))
else:
v = float(desc.typecast_for_storage(v))
if op == 'lt':
return zset.lt(v, limit, offset)
elif op == 'gt':
return zset.gt(v, limit, offset)
elif op == 'gte':
return zset.ge(v, limit, offset)
elif op == 'lte':
return zset.le(v, limit, offset)
elif op == 'in':
return zset.between(min, max, limit, offset)
def _order(self, skey):
if self._ordering:
return self._set_with_ordering(skey)
else:
return self._set_without_ordering(skey)
def _set_with_ordering(self, skey):
num, start = self._get_limit_and_offset()
old_set_key = skey
for ordering, alpha in self._ordering:
if ordering.startswith('-'):
desc = True
ordering = ordering.lstrip('-')
else:
desc = False
new_set_key = "%s#%s.%s" % (old_set_key, ordering, id(self))
by = "%s->%s" % (self.model_class._key['*'], ordering)
self.db.sort(old_set_key,
by=by,
store=new_set_key,
alpha=alpha,
start=start,
num=num,
desc=desc)
self._expire_or_delete.append(old_set_key)
self._expire_or_delete.append(new_set_key)
return List(new_set_key)
def _set_without_ordering(self, skey):
# sort by id
num, start = self._get_limit_and_offset()
old_set_key = skey
new_set_key = "%s#.%s" % (old_set_key, id(self))
self.db.sort(old_set_key,
store=new_set_key,
start=start,
num=num)
self._expire_or_delete.append(old_set_key)
self._expire_or_delete.append(new_set_key)
return List(new_set_key)
def _get_limit_and_offset(self):
if (self._limit is not None and self._offset is None) or \
(self._limit is None and self._offset is not None):
raise "Limit and offset must be specified"
if self._limit is None:
return (None, None)
else:
return (self._limit, self._offset)
def _get_item_with_id(self, id):
instance = self.model_class()
instance._id = str(id)
return instance
def _build_key_from_filter_item(self, index, value):
desc = self.model_class._attributes.get(index)
if desc:
value = desc.typecast_for_storage(value)
return self.model_class._key[index][_encode_key(value)]
def _clone(self):
klass = self.__class__
c = klass(self.model_class)
if self._filters:
c._filters = self._filters
if self._exclusions:
c._exclusions = self._exclusions
if self._zfilters:
c._zfilters = self._zfilters
if self._ordering:
c._ordering = self._ordering
c._limit = self._limit
c._offset = self._offset
return c
|
flatdata-py/flatdata/lib/archive_builder.py | heremaps/flatdata | 140 | 11095829 | <gh_stars>100-1000
'''
Copyright (c) 2021 HERE Europe B.V.
See the LICENSE file in the root of this project for license details.
'''
from collections import namedtuple
import os
from .errors import IndexWriterError, MissingFieldError, UnknownFieldError, \
UnknownStructureError, UnknownResourceError, ResourceAlreadySetError
from .resources import Instance, Vector, Multivector, RawData
from .data_access import write_value
_SCHEMA_EXT = ".schema"
ResourceSignature = namedtuple("ResourceSignature",
["container", "initializer", "schema", "is_optional", "doc"])
class IndexWriter:
"""
IndexWriter class. Only applicable when multivector is present in archive schema.
"""
def __init__(self, name, size, resource_storage):
"""
Create IndexWriter class.
All arguments are required.
"""
if not (name and resource_storage and size):
raise IndexWriterError(
f"Either ResourceStorage: {resource_storage} or name: {name} or size:"
"{size} not provided.")
self._name = name
self._index_size = size
self._fout = resource_storage.get(f'{self._name}_index', False)
def add(self, index):
"""
Convert index(number) to bytearray and add to in memory store
"""
index_bytes = int(index).to_bytes(self._index_size,
byteorder="little", signed=False)
self._fout.write(index_bytes)
def finish(self):
"""
Complete index resource by adding size and padding followed by writing to file
"""
self._fout.add_size()
self._fout.add_padding()
self._fout.close()
class ArchiveBuilder:
"""
ArchiveBuilder class. Entry point to writing Flatdata.
Provides methods to create flatdata archives.
"""
def __init__(self, resource_storage, path=""):
"""
Opens archive from a given resource writer.
:param resource_storage: storage manager to store and write to disc
:param path: file path where archive is created
"""
self._path = os.path.join(path, self._NAME)
self._resource_storage = resource_storage
self._write_archive_signature()
self._write_archive_schema()
self._resources_written = [f"{self._NAME}.archive"]
@classmethod
def name(cls):
'''Returns archive name'''
return cls._NAME
@classmethod
def schema(cls):
'''Returns archive schema'''
return cls._SCHEMA
def _write_raw_data(self, name, data):
'''
Helper function to write data
:param name(str): resource name
:param data(bytearray): data to be written to disc
'''
storage = self._resource_storage.get(name)
storage.write(data)
storage.close()
def _write_schema(self, name):
'''
Writes resource schema
:param name: name of resource
'''
self._write_raw_data(f"{name}.schema", bytes(
self._RESOURCES[name].schema, 'utf-8'))
def _write_archive_signature(self):
'''Writes archive's signature'''
self._write_raw_data(f"{self._NAME}.archive", b'\x00' * 16)
def _write_archive_schema(self):
'''Writes archive schema'''
self._write_raw_data(
f"{self._NAME}.archive.schema", bytes(self._SCHEMA, 'utf-8'))
def _write_index_schema(self, resource_name, schema):
self._write_raw_data(
f"{resource_name}_index.schema", bytes(schema, 'utf-8'))
def subarchive(self, name):
"""
Returns an archive builder for the sub-archive `name`.
:raises $name_not_subarchive_error
:param name: name of the sub-archive
"""
NotImplemented
@classmethod
def __validate_structure_fields(cls, name, struct, initializer):
'''
Validates whether passed object has all required fields
:raises MissingFieldError
:raises UnknownFieldError
:param name(str): name of object(struct)
:param struct(object): object to validate
:param initializer(object): provided field keys to validate from
'''
for key in initializer._FIELD_KEYS:
if key not in struct:
raise MissingFieldError(key, name)
for key in struct.keys():
if key not in initializer._FIELD_KEYS:
raise UnknownFieldError(key, name)
def __set_instance(self, storage, name, value):
'''
Creates and writes instance type resource
:param storage(object): handles storage and writing to disc
:param name(str): instance name
:param value(dict): instance object replicates struct
'''
initializer = self._RESOURCES[name].initializer
ArchiveBuilder.__validate_structure_fields(name, value, initializer)
bout = bytearray(initializer._SIZE_IN_BYTES)
for (key, field) in initializer._FIELDS.items():
write_value(bout, field.offset, field.width,
field.is_signed, value[key])
storage.write(bout)
def __set_vector(self, storage, name, vector):
'''
Creates and writes vector resource
:param storage(object): handles storage and writing to disc
:param name(str): resource name
:param vector(list): vector, provided as list of dict ie [{},{}]
'''
initializer = self._RESOURCES[name].initializer
for value in vector:
ArchiveBuilder.__validate_structure_fields(
name, value, initializer)
for value in vector:
bout = bytearray(initializer._SIZE_IN_BYTES)
for (key, field) in initializer._FIELDS.items():
write_value(bout, field.offset, field.width,
field.is_signed, value[key])
storage.write(bout)
def __set_multivector(self, storage, name, value):
'''
Creates and writes multivector resource
:param storage(object): handles storage and writing to disc
:param name(str): resource name
:param value(list): mulitvector, provided as list of list of dict ie [[{},{}],[]]
'''
initializer_list = self._RESOURCES[name].initializer
initializers = {}
for index, obj_type in enumerate(initializer_list[1:]):
initializers[obj_type._NAME] = (index, obj_type)
def valid_structure_name(_obj):
return _obj['name'] in [_initializer._NAME for _initializer in initializer_list[1:]]
def validate_fields(_obj):
matched_obj_list = [
_initializer for _initializer in initializer_list[1:] \
if _initializer._NAME == _obj['name']]
if len(matched_obj_list) == 1:
ArchiveBuilder.__validate_structure_fields(
name, _obj['attributes'], matched_obj_list[0])
for sub_list in value:
for obj in sub_list:
if not valid_structure_name(obj):
raise UnknownStructureError(obj['name'])
validate_fields(obj)
index_data_points = []
data_point = 0
data_size = 0
for sub_list in value:
index_data_points.append(data_point)
if sub_list:
for obj in sub_list:
# find out correct initializer
type_index, matched_initializer = initializers[obj['name']]
size = matched_initializer._SIZE_IN_BYTES + 1
data_size += size
data_point += size
bout = bytearray(size)
bout[0] = int(type_index).to_bytes(
1, byteorder="little", signed=False)[0]
for (key, field) in matched_initializer._FIELDS.items():
write_value(bout, field.offset + 1 * 8, field.width,
field.is_signed, obj['attributes'][key])
storage.write(bout)
index_data_points.append(data_point)
index_writer = IndexWriter(
name, initializer_list[0]._SIZE_IN_BYTES, self._resource_storage)
for index in index_data_points:
index_writer.add(index)
index_writer.finish()
# Write index schema
self._write_index_schema(
name, f'index({self._RESOURCES[name].schema})')
self._resources_written.append(name)
self._resources_written.append(f'{name}_index')
def set(self, name, value):
"""
Write a resource for this archive at once.
Can only be done once. `set` and `start` can't be used for the same resource.
:raises $already_set_error
:raises $unknown_resource_error
:param name: name of the resource
:param value: value to write
"""
if name not in self._RESOURCES:
raise UnknownResourceError(name)
if not self._resources_written.count(name):
self._write_schema(name)
else:
raise ResourceAlreadySetError()
storage = self._resource_storage.get(name, False)
if self._RESOURCES[name].container is Instance:
self.__set_instance(storage, name, value)
elif self._RESOURCES[name].container is Vector:
self.__set_vector(storage, name, value)
elif self._RESOURCES[name].container is Multivector:
self.__set_multivector(storage, name, value)
elif self._RESOURCES[name].container is RawData:
storage.write(value)
else:
NotImplementedError
storage.add_size()
storage.add_padding()
storage.close()
self._resources_written.append(name)
def finish(self):
"""
Closes the storage manager
"""
self._resource_storage.close()
|
zapcli/commands/session.py | kiwi-bop/zap-cli | 196 | 11095837 | """
Group of commands to manage the sessions.
.. moduleauthor:: <NAME> (grunny)
"""
import os
import click
from zapcli.exceptions import ZAPError
from zapcli.helpers import zap_error_handler
from zapcli.log import console
@click.group(name='session', short_help='Manage sessions.')
@click.pass_context
def session_group(ctx):
"""Manage sessions."""
pass
@session_group.command('new')
@click.pass_obj
def new_session(zap_helper):
"""Start a new session."""
console.debug('Starting a new session')
zap_helper.zap.core.new_session()
@session_group.command('save')
@click.argument('file-path')
@click.pass_obj
def save_session(zap_helper, file_path):
"""Save the session."""
console.debug('Saving the session to "{0}"'.format(file_path))
zap_helper.zap.core.save_session(file_path, overwrite='true')
@session_group.command('load')
@click.argument('file-path')
@click.pass_obj
def load_session(zap_helper, file_path):
"""Load a given session."""
with zap_error_handler():
if not os.path.isfile(file_path):
raise ZAPError('No file found at "{0}", cannot load session.'.format(file_path))
console.debug('Loading session from "{0}"'.format(file_path))
zap_helper.zap.core.load_session(file_path)
|
cactus/exceptions.py | danielchasehooper/Cactus | 1,048 | 11095910 | #coding:utf-8
class InvalidCredentials(Exception):
"""
Raised when invalid credentials are used to connect.
"""
pass
|
dmb/modeling/stereo/disp_refinement/__init__.py | jiaw-z/DenseMatchingBenchmark | 160 | 11095912 | <reponame>jiaw-z/DenseMatchingBenchmark
from .builder import build_disp_refinement |
chapter11-detection/model.py | gabrielmahia/obamAI | 1,291 | 11095916 | <gh_stars>1000+
"""SSD model builder
Utilities for building network layers are also provided
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from tensorflow.keras.layers import Activation, Dense, Input
from tensorflow.keras.layers import Conv2D, Flatten
from tensorflow.keras.layers import BatchNormalization, Concatenate
from tensorflow.keras.layers import ELU, MaxPooling2D, Reshape
from tensorflow.keras.models import Model
from tensorflow.keras import backend as K
import numpy as np
def conv2d(inputs,
filters=32,
kernel_size=3,
strides=1,
name=None):
conv = Conv2D(filters=filters,
kernel_size=kernel_size,
strides=strides,
kernel_initializer='he_normal',
name=name,
padding='same')
return conv(inputs)
def conv_layer(inputs,
filters=32,
kernel_size=3,
strides=1,
use_maxpool=True,
postfix=None,
activation=None):
x = conv2d(inputs,
filters=filters,
kernel_size=kernel_size,
strides=strides,
name='conv'+postfix)
x = BatchNormalization(name="bn"+postfix)(x)
x = ELU(name='elu'+postfix)(x)
if use_maxpool:
x = MaxPooling2D(name='pool'+postfix)(x)
return x
def build_ssd(input_shape,
backbone,
n_layers=4,
n_classes=4,
aspect_ratios=(1, 2, 0.5)):
"""Build SSD model given a backbone
Arguments:
input_shape (list): input image shape
backbone (model): Keras backbone model
n_layers (int): Number of layers of ssd head
n_classes (int): Number of obj classes
aspect_ratios (list): annchor box aspect ratios
Returns:
n_anchors (int): Number of anchor boxes per feature pt
feature_shape (tensor): SSD head feature maps
model (Keras model): SSD model
"""
# number of anchor boxes per feature map pt
n_anchors = len(aspect_ratios) + 1
inputs = Input(shape=input_shape)
# no. of base_outputs depends on n_layers
base_outputs = backbone(inputs)
outputs = []
feature_shapes = []
out_cls = []
out_off = []
for i in range(n_layers):
# each conv layer from backbone is used
# as feature maps for class and offset predictions
# also known as multi-scale predictions
conv = base_outputs if n_layers==1 else base_outputs[i]
name = "cls" + str(i+1)
classes = conv2d(conv,
n_anchors*n_classes,
kernel_size=3,
name=name)
# offsets: (batch, height, width, n_anchors * 4)
name = "off" + str(i+1)
offsets = conv2d(conv,
n_anchors*4,
kernel_size=3,
name=name)
shape = np.array(K.int_shape(offsets))[1:]
feature_shapes.append(shape)
# reshape the class predictions, yielding 3D tensors of
# shape (batch, height * width * n_anchors, n_classes)
# last axis to perform softmax on them
name = "cls_res" + str(i+1)
classes = Reshape((-1, n_classes),
name=name)(classes)
# reshape the offset predictions, yielding 3D tensors of
# shape (batch, height * width * n_anchors, 4)
# last axis to compute the (smooth) L1 or L2 loss
name = "off_res" + str(i+1)
offsets = Reshape((-1, 4),
name=name)(offsets)
# concat for alignment with ground truth size
# made of ground truth offsets and mask of same dim
# needed during loss computation
offsets = [offsets, offsets]
name = "off_cat" + str(i+1)
offsets = Concatenate(axis=-1,
name=name)(offsets)
# collect offset prediction per scale
out_off.append(offsets)
name = "cls_out" + str(i+1)
#activation = 'sigmoid' if n_classes==1 else 'softmax'
#print("Activation:", activation)
classes = Activation('softmax',
name=name)(classes)
# collect class prediction per scale
out_cls.append(classes)
if n_layers > 1:
# concat all class and offset from each scale
name = "offsets"
offsets = Concatenate(axis=1,
name=name)(out_off)
name = "classes"
classes = Concatenate(axis=1,
name=name)(out_cls)
else:
offsets = out_off[0]
classes = out_cls[0]
outputs = [classes, offsets]
model = Model(inputs=inputs,
outputs=outputs,
name='ssd_head')
return n_anchors, feature_shapes, model
|
tkinter/label/label-width-font/main.py | whitmans-max/python-examples | 140 | 11095928 | <filename>tkinter/label/label-width-font/main.py
#If you display text in the label, these options define the size of the label in text units. If you display bitmaps or images instead, they define the size in pixels (or other screen units)
import tkinter as tk
root = tk.Tk()
f = None
l1 = tk.Label(root, text='Hello', width=7, fg='white', bg='blue', font=f)
f = ('HelveticaNeue Light', 12)
l2 = tk.Label(root, text='Hello', width=7, fg='white', bg='green', font=f)
f = ('HelveticaNeue Light', 12, 'bold')
l3 = tk.Label(root, text='Hello', width=7, fg='white', bg='red', font=f)
l1.grid()
l2.grid()
l3.grid()
root.mainloop()
|
third_party/tests/Opentitan/util/reggen/version.py | parzival3/Surelog | 156 | 11095973 | <reponame>parzival3/Surelog<gh_stars>100-1000
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
r"""Standard version printing
"""
import os
import subprocess
import sys
import pkg_resources # part of setuptools
def show_and_exit(clitool, packages):
util_path = os.path.dirname(os.path.realpath(clitool))
os.chdir(util_path)
ver = subprocess.run(
["git", "describe", "--always", "--dirty", "--broken"],
stdout=subprocess.PIPE).stdout.strip().decode('ascii')
if (ver == ''):
ver = 'not found (not in Git repository?)'
sys.stderr.write(clitool + " Git version " + ver + '\n')
for p in packages:
sys.stderr.write(p + ' ' + pkg_resources.require(p)[0].version + '\n')
exit(0)
|
my.py | deep-fry/mayo | 110 | 11096003 | <reponame>deep-fry/mayo<filename>my.py
#!/usr/bin/env python3
import os
from importlib.util import spec_from_file_location, module_from_spec
root = os.path.dirname(__file__)
if root == '.':
root = ''
path = os.path.join(root, 'mayo', 'cli.py')
spec = spec_from_file_location('cli', path)
cli = module_from_spec(spec)
spec.loader.exec_module(cli)
cli.CLI().main()
|
examples/showcase/src/demos_panels/absolutePanel.py | takipsizad/pyjs | 739 | 11096018 | """
``ui.AbsolutePanel`` is a panel that positions its children using absolute
pixel positions. This allows the panel's children to overlap.
Note that the AbsolutePanel does not automatically resize itself to fit its
children. There is no straightforward way of doing this unless all the
children are explicitly sized; the easier workaround is just to call
``panel.setWidth(width)`` and ``panel.setHeight(height)`` explicitly after
adding the children, choosing an appropriate width and height based on the
children you have added.
"""
from pyjamas.ui.SimplePanel import SimplePanel
from pyjamas.ui.AbsolutePanel import AbsolutePanel
from pyjamas.ui.VerticalPanel import VerticalPanel
from pyjamas.ui.HTML import HTML
from pyjamas import DOM
class AbsolutePanelDemo(SimplePanel):
def __init__(self):
SimplePanel.__init__(self)
panel = AbsolutePanel(Width="100%", Height="100px")
panel.add(self.makeBox("Child 1"), 20, 10)
panel.add(self.makeBox("Child 2"), 30, 30)
self.add(panel)
def makeBox(self, label):
wrapper = VerticalPanel(BorderWidth=1)
wrapper.add(HTML(label))
DOM.setAttribute(wrapper.getTable(), "cellPadding", "10")
DOM.setAttribute(wrapper.getTable(), "bgColor", "#C3D9FF")
return wrapper
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.