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
calc/urls.py
18F/calc
126
147174
<gh_stars>100-1000 from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView from uaa_client.decorators import staff_login_required import data_explorer.views import contracts.views from .sample_users import login_sample_user from .healthcheck import healthcheck from .robots import robots_txt from .changelog import django_view as view_changelog # Wrap the admin site login with the staff_login_required # decorator, which will raise a PermissionDenied exception if a # logged-in, but non-staff user attempts to access the login page. admin.site.login = staff_login_required(admin.site.login) urlpatterns = [ url(r'^$', data_explorer.views.index, name='index'), url(r'^about/$', data_explorer.views.about, name='about'), url(r'^logout/$', data_explorer.views.logout, name='logout'), url(r'^uaa_logout/$', data_explorer.views.uaa_logout, name='uaa_logout'), url(r'^safe-mode/', include('frontend.safe_mode', namespace='safe_mode')), url(r'^healthcheck/', healthcheck), url(r'^api/', include('api.urls')), url(r'^data-quality-report/$', contracts.views.data_quality_report, name='data_quality_report'), url(r'^data-quality-report/(?P<slug>.+)/$', contracts.views.data_quality_report_detail, name='data_quality_report_detail'), url(r'^data-capture/', include('data_capture.urls', namespace='data_capture')), url(r'^admin/', include(admin.site.urls)), url(r'^styleguide/', include('styleguide.urls', namespace='styleguide')), url(r'^robots.txt$', robots_txt), url(r'^updates/$', view_changelog, name='updates'), url(r'^auth/', include('uaa_client.urls', namespace='uaa_client')), url(r'session_security/', include('session_security.urls')), url(r'^account/', include('user_account.urls', namespace='user_account')), ] tests_url = url(r'^tests/$', TemplateView.as_view(template_name='tests.html'), name="tests") if settings.DEBUG: import debug_toolbar urlpatterns = [ url(r'^admin/doc/', include('django.contrib.admindocs.urls')), ] + urlpatterns + [ url(r'^__debug__/', include(debug_toolbar.urls)), url(r'^login-sample-user/(?P<username>[A-Za-z0-9_\-]+)$', login_sample_user, name='login_sample_user'), tests_url, ]
SimTracker/TrackerMaterialAnalysis/python/trackingMaterialAnalyser_cff.py
ckamtsikis/cmssw
852
147182
import FWCore.ParameterSet.Config as cms # Define arbitrary tracker material groups from RecoTracker.GeometryESProducer.TrackerRecoGeometryESProducer_cfi import * from SimTracker.TrackerMaterialAnalysis.trackingMaterialGroups_cff import * # Analyze and plot the tracking material from SimTracker.TrackerMaterialAnalysis.trackingMaterialAnalyser_cfi import *
dart_fss/api/shareholder/__init__.py
dveamer/dart-fss
243
147215
<reponame>dveamer/dart-fss<filename>dart_fss/api/shareholder/__init__.py from .executive import get_executive_shareholder from .major_shareholder import get_major_shareholder __all__ = ['get_executive_shareholder', 'get_major_shareholder']
tests/test_ec2.py
compose-x/troposphere
4,573
147223
<gh_stars>1000+ import unittest import troposphere.ec2 as ec2 class TestEC2(unittest.TestCase): def test_securitygroupegress(self): egress = ec2.SecurityGroupEgress( "egress", ToPort="80", FromPort="80", IpProtocol="tcp", GroupId="id", CidrIp="0.0.0.0/0", ) egress.to_dict() egress = ec2.SecurityGroupEgress( "egress", ToPort="80", FromPort="80", IpProtocol="tcp", GroupId="id", DestinationPrefixListId="id", ) egress.to_dict() egress = ec2.SecurityGroupEgress( "egress", ToPort="80", FromPort="80", IpProtocol="tcp", GroupId="id", DestinationSecurityGroupId="id", ) egress.to_dict() egress = ec2.SecurityGroupEgress( "egress", IpProtocol="-1", GroupId="id", DestinationSecurityGroupId="id", ) egress.to_dict() egress = ec2.SecurityGroupEgress( "egress", IpProtocol="58", GroupId="id", DestinationSecurityGroupId="id", ) egress.to_dict() egress = ec2.SecurityGroupEgress( "egress", ToPort="80", FromPort="80", IpProtocol="tcp", GroupId="id", CidrIp="0.0.0.0/0", DestinationPrefixListId="id", ) with self.assertRaises(ValueError): egress.to_dict() # Test mutually exclusive fields egress = ec2.SecurityGroupEgress( "egress", ToPort="80", FromPort="80", IpProtocol="tcp", GroupId="id", CidrIp="0.0.0.0/0", DestinationPrefixListId="id", DestinationSecurityGroupId="id", ) with self.assertRaises(ValueError): egress.to_dict() # Test no ToPort egress = ec2.SecurityGroupEgress( "egress", FromPort="80", IpProtocol="tcp", GroupId="id", CidrIp="0.0.0.0/0", ) with self.assertRaises(ValueError): egress.to_dict() # Test no ToPort or FromPort egress = ec2.SecurityGroupEgress( "egress", IpProtocol="tcp", GroupId="id", CidrIp="0.0.0.0/0", ) with self.assertRaises(ValueError): egress.to_dict() def test_vpn_conn_cannot_have_customer_gateway_and_transit_gateway(self): vpn = ec2.VPNConnection( "VPNConnection", CustomerGatewayId="cgw-0e11f167", VpnGatewayId="vgw-9a4cacf3", TransitGatewayId="tgw-b2b84747", Type="ipsec.1", ) with self.assertRaises(ValueError): vpn.to_dict()
src/spring-cloud/azext_spring_cloud/__init__.py
Mannan2812/azure-cli-extensions
207
147247
<gh_stars>100-1000 # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- from azure.cli.core import AzCommandsLoader from azure.cli.core.commands import CliCommandType from azext_spring_cloud._help import helps # pylint: disable=unused-import from azext_spring_cloud._client_factory import cf_spring_cloud from azext_spring_cloud.commands import load_command_table from azext_spring_cloud._params import load_arguments class spring_cloudCommandsLoader(AzCommandsLoader): def __init__(self, cli_ctx=None): spring_cloud_custom = CliCommandType( operations_tmpl='azext_spring_cloud.custom#{}', client_factory=cf_spring_cloud) super(spring_cloudCommandsLoader, self).__init__(cli_ctx=cli_ctx, custom_command_type=spring_cloud_custom) def load_command_table(self, args): load_command_table(self, args) return self.command_table def load_arguments(self, command): load_arguments(self, command) COMMAND_LOADER_CLS = spring_cloudCommandsLoader
tests/torch/quantization/test_quantization_helpers.py
MaximProshin/nncf
136
147256
<reponame>MaximProshin/nncf """ Copyright (c) 2022 Intel Corporation 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 torch from nncf import NNCFConfig from nncf.torch.dynamic_graph.graph_tracer import create_input_infos from tests.torch.helpers import get_empty_config def compare_multi_gpu_dump(config, dump_dir, get_path_by_rank_fn): mismatching = False ref_file_path = get_path_by_rank_fn(dump_dir, 0) with ref_file_path.open('rb') as ref_scale_file: ref_data = torch.load(ref_scale_file) for other_rank in range(1, config.world_size): other_file_path = get_path_by_rank_fn(dump_dir, other_rank) with other_file_path.open('rb') as in_file: data_to_compare = torch.load(in_file) for ref_tuple, tuple_to_compare in zip(ref_data, data_to_compare): for ref_info, info_to_compare in zip(ref_tuple, tuple_to_compare): if torch.tensor(ref_info != info_to_compare).sum(): mismatching = True return mismatching class RankDatasetMock: def __init__(self, input_size, rank, num_samples: int = 10): self.input_size = input_size self.rank = rank self._len = num_samples super().__init__() def __getitem__(self, index): dummy_input = torch.ones(self.input_size) * (self.rank - 1) * 3 return dummy_input, torch.ones(1) def __len__(self): return self._len def get_quantization_config_without_range_init(model_size=4) -> NNCFConfig: config = get_empty_config(input_sample_sizes=[1, 1, model_size, model_size]) config["compression"] = { "algorithm": "quantization", "initializer": { "range": { "num_init_samples": 0 } } } return config def get_squeezenet_quantization_config(image_size=32, batch_size=3): config = get_quantization_config_without_range_init(image_size) config['model'] = 'squeezenet1_1' config['input_info'] = { "sample_size": [batch_size, 3, image_size, image_size], } return config def distributed_init_test_default(gpu, ngpus_per_node, config): config.batch_size = 3 config.workers = 0 # workaround for the pytorch multiprocessingdataloader issue/ config.gpu = gpu config.ngpus_per_node = ngpus_per_node config.rank = gpu config.distributed = True torch.distributed.init_process_group(backend="nccl", init_method='tcp://127.0.0.1:8199', world_size=config.world_size, rank=config.rank) def create_rank_dataloader(config, rank, num_samples=10, batch_size=3): input_infos_list = create_input_infos(config) input_sample_size = input_infos_list[0].shape data_loader = torch.utils.data.DataLoader(RankDatasetMock(input_sample_size[1:], rank, num_samples), batch_size=batch_size, num_workers=0, # workaround shuffle=False, drop_last=True) return data_loader def post_compression_test_distr_init(compression_ctrl, config, ngpus_per_node, quant_model): torch.cuda.set_device(config.gpu) quant_model.cuda(config.gpu) config.batch_size = int(config.batch_size / ngpus_per_node) config.workers = int(config.workers / ngpus_per_node) quant_model = torch.nn.parallel.DistributedDataParallel(quant_model, device_ids=[config.gpu]) compression_ctrl.distributed() return quant_model
plugins/solve_fsm/test_plugin.py
emsec/HAL
407
147269
<gh_stars>100-1000 #!/usr/bin/env python3 import sys, os #some necessary configuration: sys.path.append("/home/simon/projects/hal/build/lib/") #this is where your hal python lib is located os.environ["HAL_BASE_PATH"] = "/home/simon/projects/hal/build" # hal base path import hal_py netlist_to_read = "netlist.v" gate_library_path = "gate_library.lib" #initialize HAL hal_py.plugin_manager.load_all_plugins() #read netlist netlist = hal_py.NetlistFactory.load_netlist(netlist_to_read, gate_library_path) from hal_plugins import solve_fsm pl_fsm = hal_py.plugin_manager.get_plugin_instance("solve_fsm") # UPDATE THE MODULE IDS OR CREATE YOUR OWN LIST OF GATES state_mod = netlist.get_module_by_id(0) transition_mod = netlist.get_module_by_id(0) transition_gates = transition_mod.gates state_gates = state_mod.gates initial_state = {} timeout = 600000 g = pl_fsm.solve_fsm(netlist, state_gates, transition_gates, initial_state, timeout) #unload everything hal related hal_py.plugin_manager.unload_all_plugins()
examples/1d/plot_classif_torch.py
GReguig/kymatio
516
147282
<gh_stars>100-1000 """ Classification of spoken digit recordings ========================================= In this example we use the 1D scattering transform to represent spoken digits, which we then classify using a simple classifier. This shows that 1D scattering representations are useful for this type of problem. This dataset is automatically downloaded and preprocessed from https://github.com/Jakobovski/free-spoken-digit-dataset.git Downloading and precomputing scattering coefficients should take about 5 min. Running the gradient descent takes about 1 min. Results: Training accuracy = 99.7% Testing accuracy = 98.0% """ ############################################################################### # Preliminaries # ------------- # # Since we're using PyTorch to train the model, import `torch`. import torch ############################################################################### # We will be constructing a logistic regression classifier on top of the # scattering coefficients, so we need some of the neural network tools from # `torch.nn` and the Adam optimizer from `torch.optim`. from torch.nn import Linear, NLLLoss, LogSoftmax, Sequential from torch.optim import Adam ############################################################################### # To handle audio file I/O, we import `os` and `scipy.io.wavfile`. We also need # `numpy` for some basic array manipulation. from scipy.io import wavfile import os import numpy as np ############################################################################### # To evaluate our results, we need to form a confusion matrix using # scikit-learn and display them using `matplotlib`. from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt ############################################################################### # Finally, we import the `Scattering1D` class from the `kymatio.torch` package # and the `fetch_fsdd` function from `kymatio.datasets`. The `Scattering1D` # class is what lets us calculate the scattering transform, while the # `fetch_fsdd` function downloads the FSDD, if needed. from kymatio.torch import Scattering1D from kymatio.datasets import fetch_fsdd ############################################################################### # Pipeline setup # -------------- # We start by specifying the dimensions of our processing pipeline along with # some other parameters. # # First, we have signal length. Longer signals are truncated and shorter # signals are zero-padded. The sampling rate is 8000 Hz, so this corresponds to # little over a second. T = 2**13 ############################################################################### # Maximum scale 2**J of the scattering transform (here, about 30 milliseconds) # and the number of wavelets per octave. J = 8 Q = 12 ############################################################################### # We need a small constant to add to the scattering coefficients before # computing the logarithm. This prevents very large values when the scattering # coefficients are very close to zero. log_eps = 1e-6 ############################################################################### # If a GPU is available, let's use it! use_cuda = torch.cuda.is_available() ############################################################################### # For reproducibility, we fix the seed of the random number generator. torch.manual_seed(42) ############################################################################### # Loading the data # ---------------- # Once the parameter are set, we can start loading the data into a format that # can be fed into the scattering transform and then a logistic regression # classifier. # # We first download the dataset. If it's already downloaded, `fetch_fsdd` will # simply return the information corresponding to the dataset that's already # on disk. info_data = fetch_fsdd() files = info_data['files'] path_dataset = info_data['path_dataset'] ############################################################################### # Set up Tensors to hold the audio signals (`x_all`), the labels (`y_all`), and # whether the signal is in the train or test set (`subset`). x_all = torch.zeros(len(files), T, dtype=torch.float32) y_all = torch.zeros(len(files), dtype=torch.int64) subset = torch.zeros(len(files), dtype=torch.int64) ############################################################################### # For each file in the dataset, we extract its label `y` and its index from the # filename. If the index is between 0 and 4, it is placed in the test set, while # files with larger indices are used for training. The actual signals are # normalized to have maximum amplitude one, and are truncated or zero-padded # to the desired length `T`. They are then stored in the `x_all` Tensor while # their labels are in `y_all`. for k, f in enumerate(files): basename = f.split('.')[0] # Get label (0-9) of recording. y = int(basename.split('_')[0]) # Index larger than 5 gets assigned to training set. if int(basename.split('_')[2]) >= 5: subset[k] = 0 else: subset[k] = 1 # Load the audio signal and normalize it. _, x = wavfile.read(os.path.join(path_dataset, f)) x = np.asarray(x, dtype='float') x /= np.max(np.abs(x)) # Convert from NumPy array to PyTorch Tensor. x = torch.from_numpy(x) # If it's too long, truncate it. if x.numel() > T: x = x[:T] # If it's too short, zero-pad it. start = (T - x.numel()) // 2 x_all[k,start:start + x.numel()] = x y_all[k] = y ############################################################################### # Log-scattering transform # ------------------------ # We now create the `Scattering1D` object that will be used to calculate the # scattering coefficients. scattering = Scattering1D(J, T, Q) ############################################################################### # If we are using CUDA, the scattering transform object must be transferred to # the GPU by calling its `cuda()` method. The data is similarly transferred. if use_cuda: scattering.cuda() x_all = x_all.cuda() y_all = y_all.cuda() ############################################################################### # Compute the scattering transform for all signals in the dataset. Sx_all = scattering.forward(x_all) ############################################################################### # Since it does not carry useful information, we remove the zeroth-order # scattering coefficients, which are always placed in the first channel of # the scattering Tensor. Sx_all = Sx_all[:,1:,:] ############################################################################### # To increase discriminability, we take the logarithm of the scattering # coefficients (after adding a small constant to make sure nothing blows up # when scattering coefficients are close to zero). This is known as the # log-scattering transform. Sx_all = torch.log(torch.abs(Sx_all) + log_eps) ############################################################################### # Finally, we average along the last dimension (time) to get a time-shift # invariant representation. Sx_all = torch.mean(Sx_all, dim=-1) ############################################################################### # Training the classifier # ----------------------- # With the log-scattering coefficients in hand, we are ready to train our # logistic regression classifier. # # First, we extract the training data (those for which `subset` equals `0`) # and the associated labels. Sx_tr, y_tr = Sx_all[subset == 0], y_all[subset == 0] ############################################################################### # Standardize the data to have mean zero and unit variance. Note that we need # to apply the same transformation to the test data later, so we save the # mean and standard deviation Tensors. mu_tr = Sx_tr.mean(dim=0) std_tr = Sx_tr.std(dim=0) Sx_tr = (Sx_tr - mu_tr) / std_tr ############################################################################### # Here we define a logistic regression model using PyTorch. We train it using # Adam with a negative log-likelihood loss. num_input = Sx_tr.shape[-1] num_classes = y_tr.cpu().unique().numel() model = Sequential(Linear(num_input, num_classes), LogSoftmax(dim=1)) optimizer = Adam(model.parameters()) criterion = NLLLoss() ############################################################################### # As before, if we're on a GPU, transfer the model and the loss function onto # the device. if use_cuda: model = model.cuda() criterion = criterion.cuda() ############################################################################### # Before training the model, we set some parameters for the optimization # procedure. # Number of signals to use in each gradient descent step (batch). batch_size = 32 # Number of epochs. num_epochs = 50 # Learning rate for Adam. lr = 1e-4 ############################################################################### # Given these parameters, we compute the total number of batches. nsamples = Sx_tr.shape[0] nbatches = nsamples // batch_size ############################################################################### # Now we're ready to train the classifier. for e in range(num_epochs): # Randomly permute the data. If necessary, transfer the permutation to the # GPU. perm = torch.randperm(nsamples) if use_cuda: perm = perm.cuda() # For each batch, calculate the gradient with respect to the loss and take # one step. for i in range(nbatches): idx = perm[i * batch_size : (i+1) * batch_size] model.zero_grad() resp = model.forward(Sx_tr[idx]) loss = criterion(resp, y_tr[idx]) loss.backward() optimizer.step() # Calculate the response of the training data at the end of this epoch and # the average loss. resp = model.forward(Sx_tr) avg_loss = criterion(resp, y_tr) # Try predicting the classes of the signals in the training set and compute # the accuracy. y_hat = resp.argmax(dim=1) accuracy = (y_tr == y_hat).float().mean() print('Epoch {}, average loss = {:1.3f}, accuracy = {:1.3f}'.format( e, avg_loss, accuracy)) ############################################################################### # Now that our network is trained, let's test it! # # First, we extract the test data (those for which `subset` equals `1`) and the # associated labels. Sx_te, y_te = Sx_all[subset == 1], y_all[subset == 1] ############################################################################### # Use the mean and standard deviation calculated on the training data to # standardize the testing data, as well. Sx_te = (Sx_te - mu_tr) / std_tr ############################################################################### # Calculate the response of the classifier on the test data and the resulting # loss. resp = model.forward(Sx_te) avg_loss = criterion(resp, y_te) # Try predicting the labels of the signals in the test data and compute the # accuracy. y_hat = resp.argmax(dim=1) accu = (y_te == y_hat).float().mean() print('TEST, average loss = {:1.3f}, accuracy = {:1.3f}'.format( avg_loss, accu)) ############################################################################### # Plotting the classification accuracy as a confusion matrix # ---------------------------------------------------------- # Let's see what the very few misclassified sounds get misclassified as. We # will plot a confusion matrix which indicates in a 2D histogram how often # one sample was mistaken for another (anything on the diagonal is correctly # classified, anything off the diagonal is wrong). predicted_categories = y_hat.cpu().numpy() actual_categories = y_te.cpu().numpy() confusion = confusion_matrix(actual_categories, predicted_categories) plt.figure() plt.imshow(confusion) tick_locs = np.arange(10) ticks = ['{}'.format(i) for i in range(1, 11)] plt.xticks(tick_locs, ticks) plt.yticks(tick_locs, ticks) plt.ylabel("True number") plt.xlabel("Predicted number") plt.show()
muddery/worldeditor/services/data_edit.py
dongwudanci/muddery
127
147283
<reponame>dongwudanci/muddery """ Battle commands. They only can be used when a character is in a combat. """ from django.db import transaction from django.core.exceptions import ObjectDoesNotExist from muddery.server.utils.exception import MudderyError, ERR from muddery.worldeditor.dao import general_query_mapper from muddery.worldeditor.dao.common_mappers import WORLD_AREAS, WORLD_ROOMS from muddery.worldeditor.dao.system_data_mapper import SYSTEM_DATA from muddery.worldeditor.dao.element_properties_mapper import ELEMENT_PROPERTIES from muddery.worldeditor.mappings.form_set import FORM_SET from muddery.server.mappings.element_set import ELEMENT, ELEMENT_SET from muddery.server.mappings.event_action_set import EVENT_ACTION_SET from muddery.worldeditor.forms.location_field import LocationField from muddery.worldeditor.forms.image_field import ImageField def query_form(table_name, **kwargs): """ Query table's data. Args: table_name: (string) data table's name. kwargs: (dict) conditions. """ form_class = FORM_SET.get(table_name) if not form_class: raise MudderyError(ERR.no_table, "Can not find table: %s" % table_name) form = None record = None if kwargs: try: # Query record's data. record = general_query_mapper.get_record(table_name, **kwargs) form = form_class(instance=record) except Exception as e: form = None if not form: # Get empty data. form = form_class() fields = [] fields.append({ "name": "id", "label": "", "disabled": True, "help_text": "", "type": "Hidden", "value": record.id if record else "", }) for key, field in form.fields.items(): info = { "name": key, "label": field.label, "disabled": field.disabled, "help_text": field.help_text, "type": field.widget.__class__.__name__, } if record: info["value"] = str(record.serializable_value(key)) if info["type"] == "Select": info["choices"] = field.choices if isinstance(field, LocationField): info["type"] = "Location" elif isinstance(field, ImageField): info["type"] = "Image" info["image_type"] = field.get_type() fields.append(info) return fields def save_form(values, table_name, record_id=None): """ Save data to a record. Args: values: (dict) values to save. table_name: (string) data table's name. record_id: (string, optional) record's id. If it is empty, add a new record. """ form_class = FORM_SET.get(table_name) if not form_class: raise MudderyError(ERR.no_table, "Can not find table: %s" % table_name) form = None if record_id: try: # Query record's data. record = general_query_mapper.get_record_by_id(table_name, record_id) form = form_class(values, instance=record) except Exception as e: form = None if not form: # Get empty data. form = form_class(values) # Save data if form.is_valid(): instance = form.save() return instance.pk else: raise MudderyError(ERR.invalid_form, "Invalid form.", data=form.errors) def delete_record(table_name, record_id): """ Delete a record of a table. """ general_query_mapper.delete_record_by_id(table_name, record_id) def delete_records(table_name, **kwargs): """ Delete records by conditions. """ general_query_mapper.delete_records(table_name, **kwargs) def query_element_form(base_element_type, obj_element_type, element_key): """ Query all data of an object. Args: base_element_type: (string) the base element of the object. obj_element_type: (string, optional) object's element type. If it is empty, use the element type of the object or use the base element type. element_key: (string) the element's key. If it is empty, query an empty form. """ candidate_element_types = ELEMENT_SET.get_group(base_element_type) if not candidate_element_types: raise MudderyError(ERR.no_table, "Can not find the element: %s" % base_element_type) element = ELEMENT_SET.get(obj_element_type) if not element: raise MudderyError(ERR.no_table, "Can not get the element: %s" % obj_element_type) table_names = element.get_models() forms = [] for table_name in table_names: if element_key: object_form = query_form(table_name, key=element_key) else: object_form = query_form(table_name) forms.append({ "table": table_name, "fields": object_form }) # add elements if len(forms) > 0: for field in forms[0]["fields"]: if field["name"] == "element_type": # set the element type to the new value field["value"] = obj_element_type field["type"] = "Select" field["choices"] = [(key, element.element_name + " (" + key + ")") for key, element in candidate_element_types.items()] break return forms def save_element_level_properties(element_type, element_key, level, values): """ Save properties of an element. Args: element_type: (string) the element's type. element_key: (string) the element's key. level: (number) object's level. values: (dict) values to save. """ ELEMENT_PROPERTIES.add_properties(element_type, element_key, level, values) def delete_element_level_properties(element_type, element_key, level): """ Delete properties of a level of the element. Args: element_type: (string) the element's type. element_key: (string) the element's key. level: (number) object's level. """ ELEMENT_PROPERTIES.delete_properties(element_type, element_key, level) def save_element_form(tables, element_type, element_key): """ Save all data of an object. Args: tables: (list) a list of table data. [{ "table": (string) table's name. "record": (string, optional) record's id. If it is empty, add a new record. }] element_type: (string) element's type. element_key: (string) current element's key. If it is empty or changed, query an empty form. """ if not tables: raise MudderyError(ERR.invalid_form, "Invalid form.", data="Empty form.") # Get object's new key from the first form. try: new_key = tables[0]["values"]["key"] except KeyError: new_key = element_key if not new_key: # Does not has a new key, generate a new key. index = SYSTEM_DATA.get_object_index() new_key = "%s_auto_%s" % (element_type, index) for table in tables: table["values"]["key"] = new_key forms = [] for table in tables: table_name = table["table"] form_values = table["values"] form_class = FORM_SET.get(table_name) form = None if element_key: try: # Query the current object's data. record = general_query_mapper.get_record_by_key(table_name, element_key) form = form_class(form_values, instance=record) except ObjectDoesNotExist: form = None if not form: # Get empty data. form = form_class(form_values) forms.append(form) # check data for form in forms: if not form.is_valid(): raise MudderyError(ERR.invalid_form, "Invalid form.", data=form.errors) # Save data with transaction.atomic(): for form in forms: form.save() return new_key def save_map_positions(area, rooms): """ Save all data of an object. Args: area: (dict) area's data. rooms: (dict) rooms' data. """ with transaction.atomic(): # area data record = WORLD_AREAS.get(key=area["key"]) record.background = area["background"] record.width = area["width"] record.height = area["height"] record.full_clean() record.save() # rooms for room in rooms: position = "" if len(room["position"]) > 1: position = "(%s,%s)" % (room["position"][0], room["position"][1]) record = WORLD_ROOMS.get(key=room["key"]) record.position = position record.full_clean() record.save() def delete_element(element_key, base_element_type=None): """ Delete an element from all tables under the base element type. """ elements = ELEMENT_SET.get_group(base_element_type) tables = set() for key, value in elements.items(): tables.update(value.get_models()) with transaction.atomic(): for table in tables: try: general_query_mapper.delete_record_by_key(table, element_key) except ObjectDoesNotExist: pass def query_event_action_forms(action_type, event_key): """ Query forms of the event action. Args: action_type: (string) action's type event_key: (string) event's key """ # Get action's data. action = EVENT_ACTION_SET.get(action_type) if not action: raise MudderyError(ERR.no_table, "Can not find action: %s" % action_type) # Get all forms. forms = [] table_name = action.model_name records = general_query_mapper.filter_records(table_name, event_key=event_key) if records: for record in records: forms.append(query_form(table_name, id=record.id)) else: forms.append(query_form(table_name)) return { "forms": forms, "repeatedly": action.repeatedly } def update_element_key(element_type, old_key, new_key): """ Update an element's key in relative tables. Args: element_type: (string) object's element type. old_key: (string) object's old key. new_key: (string) object's new key """ # The object's key has changed. element = ELEMENT(element_type) if issubclass(element, ELEMENT("AREA")): # Update relative room's location. model_name = ELEMENT("ROOM").model_name if model_name: general_query_mapper.filter_records(model_name, area=old_key).update(area=new_key) elif issubclass(element, ELEMENT("ROOM")): # Update relative exit's location. model_name = ELEMENT("EXIT").model_name if model_name: general_query_mapper.filter_records(model_name, location=old_key).update(location=new_key) general_query_mapper.filter_records(model_name, destination=old_key).update(destination=new_key) # Update relative world object's location. model_name = ELEMENT("WORLD_OBJECT").model_name if model_name: general_query_mapper.filter_records(model_name, location=old_key).update(location=new_key) # Update relative world NPC's location. model_name = ELEMENT("WORLD_NPC").model_name if model_name: general_query_mapper.filter_records(model_name, location=old_key).update(location=new_key)
libutils/primes.py
nicknaym530/android_system_core
8,865
147297
#!/usr/bin/env python2.6 # # Copyright (C) 2011 The Android Open Source Project # # 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. # # # Generates a table of prime numbers for use in BasicHashtable.cpp. # # Each prime is chosen such that it is a little more than twice as large as # the previous prime in the table. This makes it easier to choose a new # hashtable size when the underlying array is grown by as nominal factor # of two each time. # def is_odd_prime(n): limit = (n - 1) / 2 d = 3 while d <= limit: if n % d == 0: return False d += 2 return True print "static size_t PRIMES[] = {" n = 5 max = 2**31 - 1 while n < max: print " %d," % (n) n = n * 2 + 1 while not is_odd_prime(n): n += 2 print " 0," print "};"
kik_unofficial/datatypes/exceptions.py
aspwil/kik-bot-api-unofficial
120
147369
class KikErrorException(Exception): def __init__(self, xml_error, message=None): self.message = message self.xml_error = xml_error def __str__(self): return self.__repr__() def __repr__(self): if self.message is not None: return self.message else: if "prettify" in dict(self.xml_error): error_string = self.xml_error.prettify() else: error_string = self.xml_error return "Kik error: \r\n" + error_string class KikCaptchaException(KikErrorException): def __init__(self, xml_error, message, captcha_url): super().__init__(xml_error, message) self.captcha_url = captcha_url class KikLoginException(KikErrorException): pass class KikInvalidAckException(KikErrorException): pass class KikEmptyResponseException(KikErrorException): pass class KikApiException(Exception): pass class KikParsingException(Exception): pass class KikUploadError(Exception): def __init__(self, status_code, reason=None): self.status_code = reason self.reason = reason def __str__(self): return self.__repr__() def __repr__(self): if self.reason is None: return self.status_code return f"[{self.status_code}] {self.reason}"
office365/planner/planner_user.py
theodoriss/Office365-REST-Python-Client
544
147376
from office365.entity import Entity from office365.entity_collection import EntityCollection from office365.planner.plans.plan import PlannerPlan from office365.planner.tasks.task import PlannerTask from office365.runtime.paths.resource_path import ResourcePath class PlannerUser(Entity): """The plannerUser resource provide access to Planner resources for a user. It doesn't contain any usable properties.""" @property def plans(self): """Read-only. Nullable. Returns the plannerTasks assigned to the user. :rtype: EntityCollection """ return self.get_property('plans', EntityCollection(self.context, PlannerPlan, ResourcePath("plans", self.resource_path))) @property def tasks(self): """Read-only. Nullable. Returns the plannerTasks assigned to the user. :rtype: EntityCollection """ return self.get_property('tasks', EntityCollection(self.context, PlannerTask, ResourcePath("tasks", self.resource_path)))
python/GafferSceneUI/InstancerUI.py
ddesmond/gaffer
561
147379
########################################################################## # # Copyright (c) 2015, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above # copyright notice, this list of conditions and the following # disclaimer. # # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided with # the distribution. # # * Neither the name of <NAME> nor the names of # any other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import imath import inspect import IECore import Gaffer import GafferUI import GafferScene # Similar to CompoundDataPlugValueWidget, but different enough that the code can't be shared class _ContextVariableListWidget( GafferUI.PlugValueWidget ) : def __init__( self, plug, **kw ) : self.__column = GafferUI.ListContainer( spacing = 6 ) GafferUI.PlugValueWidget.__init__( self, self.__column, plug, **kw ) with self.__column : _ColumnHeadings( [ "Primitive Variables", "Quantize", "Variations" ] ) self.__layout = GafferUI.PlugLayout( plug ) with GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Horizontal ) as self.__editRow : GafferUI.Spacer( imath.V2i( GafferUI.PlugWidget.labelWidth(), 1 ) ) GafferUI.Button( image = "plus.png", hasFrame = False ).clickedSignal().connect( Gaffer.WeakMethod( self.__addItem ), scoped = False ) GafferUI.Spacer( imath.V2i( 1 ), imath.V2i( 999999, 1 ), parenting = { "expand" : True } ) def hasLabel( self ) : return True def setPlug( self, plug ) : GafferUI.PlugValueWidget.setPlug( self, plug ) self.__layout = GafferUI.PlugLayout( plug ) self.__column[0] = self.__layout def setReadOnly( self, readOnly ) : if readOnly == self.getReadOnly() : return GafferUI.PlugValueWidget.setReadOnly( self, readOnly ) self.__layout.setReadOnly( readOnly ) def childPlugValueWidget( self, childPlug ) : return self.__layout.plugValueWidget( childPlug ) def __addItem( self, button ) : with Gaffer.UndoScope( self.getPlug().ancestor( Gaffer.ScriptNode ) ) : self.getPlug().addChild( GafferScene.Instancer.ContextVariablePlug( "context", flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic ) ) class _ContextVariableWidget( GafferUI.PlugValueWidget ) : def __init__( self, plug, overrideName = None ) : self.__row = GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Horizontal, spacing = 4 ) GafferUI.PlugValueWidget.__init__( self, self.__row, plug ) with self.__row: GafferUI.StringPlugValueWidget( self.getPlug()["name"] ).textWidget()._qtWidget().setFixedWidth( GafferUI.PlugWidget.labelWidth() ) GafferUI.BoolPlugValueWidget( self.getPlug()["enabled"], displayMode = GafferUI.BoolWidget.DisplayMode.Switch ) GafferUI.PlugValueWidget.create( self.getPlug()["quantize"] ) toolTipPrefix = "Number of unique values of this context variable, which contribute to the total number of evaluations of the `prototypes` scene." if overrideName: _VariationsPlugValueWidget( self.getPlug().node()["variations"], overrideName, "", toolTipPrefix ) else: _VariationsPlugValueWidget( self.getPlug().node()["variations"], self.getPlug()["name"], "", toolTipPrefix ) self._updateFromPlugs() def setPlugs( self, plugs ) : GafferUI.PlugValueWidget.setPlugs( self, plugs ) self.__row[0].setPlugs( plugs["name"] ) self.__row[1].setPlugs( plugs["enabled"] ) self.__row[2].setPlugs( plugs["quantize"] ) def hasLabel( self ) : return True def childPlugValueWidget( self, childPlug ) : for w in self.__row : if childPlug in w.getPlugs() : return w return None def setReadOnly( self, readOnly ) : if readOnly == self.getReadOnly() : return GafferUI.PlugValueWidget.setReadOnly( self, readOnly ) for w in self.__row : w.setReadOnly( readOnly ) def _updateFromPlugs( self ) : with self.getContext() : enabled = self.getPlug()["enabled"].getValue() self.__row[0].setEnabled( enabled ) self.__row[2].setEnabled( enabled ) GafferUI.PlugValueWidget.registerType( GafferScene.Instancer.ContextVariablePlug, _ContextVariableWidget ) class _VariationsPlugValueWidget( GafferUI.PlugValueWidget ) : # The variations plug returns a count for each context variable, and a total. This plug can # display any one of these counts - which to display is selected by the "contextName" argument, # which can be either a string literal, or a String plug which will be evaluated to find the # name to access within the variations plug output def __init__( self, plug, contextName, label, toolTipPrefix, **kw ) : toolTip = toolTipPrefix + " " + inspect.cleandoc( """ Varying the context requires extra evaluations of the `prototypes` scene, and can dramatically increase the cost of the Instancer. Note that variations are measured across all locations in the scene where the instancer is filtered. """ ) l = GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Horizontal, spacing = 4, toolTip = toolTip ) GafferUI.PlugValueWidget.__init__( self, l, plug, **kw ) if isinstance( contextName, Gaffer.StringPlug ): self.contextName = None self.contextNamePlug = contextName self.contextNamePlug.node().plugDirtiedSignal().connect( Gaffer.WeakMethod( self.__namePlugDirtied ), scoped = False ) else: self.contextName = contextName self.contextNamePlug = None with l : GafferUI.Spacer( imath.V2i( 0 ), preferredSize = imath.V2i( 0 ) ) if label : GafferUI.Label( "<h4>%s</h4>" % label, toolTip = toolTip ) with GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Horizontal, spacing = 2, borderWidth = 3 ) as h : h._qtWidget().setObjectName( "gafferVariationCount" ) self.__busyWidget = GafferUI.BusyWidget( size = 14 ) self.__countLabel = GafferUI.Label( horizontalAlignment = GafferUI.HorizontalAlignment.Right, toolTip = toolTip ) self.__countLabel._qtWidget().setMinimumWidth( 90 ) self.__updateLabel( -1 ) self._updateFromPlug() def setPlugs( self, plugs ) : # VariationsPlugValueWidget is a special widget that requires both the plug and contextName # to be set in the constructor. Does not support setPlugs. raise NotImplementedError def hasLabel( self ) : return True def __namePlugDirtied( self, plug ) : if plug == self.contextNamePlug : self._updateFromPlug() def _updateFromPlug( self ) : self.__updateLazily() @GafferUI.LazyMethod() def __updateLazily( self ) : with self.getContext() : self.__updateInBackground() @GafferUI.BackgroundMethod() def __updateInBackground( self ) : resultDict = self.getPlug().getValue() contextName = "" if self.contextNamePlug: contextName = self.contextNamePlug.getValue() if contextName == "": return -1 else: contextName = self.contextName if contextName in resultDict: # Success. We have valid infomation to display. return resultDict[contextName].value # Could be that this variable is disabled return -1 @__updateInBackground.preCall def __updateInBackgroundPreCall( self ) : self.__updateLabel( -1 ) self.__busyWidget.setBusy( True ) @__updateInBackground.postCall def __updateInBackgroundPostCall( self, backgroundResult ) : if isinstance( backgroundResult, IECore.Cancelled ) : # Cancellation. This could be due to any of the # following : # # - This widget being hidden. # - A graph edit that will affect the result and will have # triggered a call to _updateFromPlug(). # - A graph edit that won't trigger a call to _updateFromPlug(). # # LazyMethod takes care of all this for us. If we're hidden, # it waits till we're visible. If `updateFromPlug()` has already # called `__updateLazily()`, our call will just replace the # pending call. self.__updateLazily() return elif isinstance( backgroundResult, Exception ) : # Computation error. This will be reported elsewhere # in the UI. self.__updateLabel( -1 ) else : self.__updateLabel( backgroundResult ) self.__busyWidget.setBusy( False ) def __updateLabel( self, count ) : self.__countLabel.setText( str(count) + " " if count >= 0 else " " ) def _variationsPlugValueWidgetWidth() : # Size of the visible part of the _VariationsPlugValueWidget # the busy widget, plus a couple of border widths return 112 class _ColumnHeadings( GafferUI.ListContainer ): def __init__( self, headings, toolTipOverride = "" ) : GafferUI.ListContainer.__init__( self, GafferUI.ListContainer.Orientation.Horizontal, spacing = 4 ) with self: GafferUI.Label( "<h4><b>" + headings[0] + "</b></h4>", toolTip = toolTipOverride )._qtWidget().setFixedWidth( GafferUI.PlugWidget.labelWidth() ) GafferUI.Spacer( imath.V2i( 25, 2 ) ) # approximate width of a BoolWidget Switch self.addChild( GafferUI.Label( "<h4><b>" + headings[1] + "</b></h4>", toolTip = toolTipOverride ), expand = True, horizontalAlignment=GafferUI.HorizontalAlignment.Left ) GafferUI.Label( "<h4><b>" + headings[2] + "</b></h4>", toolTip = toolTipOverride )._qtWidget().setFixedWidth( _variationsPlugValueWidgetWidth() ) # Would be really nice if we could specify constructor arguments for widgets in the metadata, # so we didn't need to declare specializations for different arguments _VariationSpacer = lambda node : GafferUI.Spacer( imath.V2i( _variationsPlugValueWidgetWidth(), 1 ), imath.V2i( _variationsPlugValueWidgetWidth(), 1 ) ) _SeedColumnHeadings = lambda node : _ColumnHeadings( ["Seed", "", "Variations"], toolTipOverride = inspect.cleandoc( """ # Seed Creates a seed context variable based on the id primvar or point index. This hashes the point id to create a persistent integer for each instance. The context variable is available to the upstream prototypes network. """ ) ) _TimeOffsetColumnHeadings = lambda node : _ColumnHeadings( [ "Time Offset", "Quantize", "Variations" ], toolTipOverride = inspect.cleandoc( """ # Time Offset Modify the current time when evaluating the prototypes network, by adding a primvar. """ ) ) _SectionSpacer = lambda node : GafferUI.Spacer( imath.V2i( 1, 5 ), imath.V2i( 1, 5 ) ) _SeedCountSpacer = lambda node : GafferUI.Spacer( imath.V2i( 0 ), imath.V2i( 999999, 0 ) ) _SeedCountWidget = lambda node : _VariationsPlugValueWidget( node["variations"], node["seedVariable"], label = "", toolTipPrefix = "Number of unique values of the seed context variable, which contribute to the total number of evaluations of the `prototypes` scene." ) _TotalCountWidget = lambda plug : _VariationsPlugValueWidget( plug, "", label = "Total Variations", toolTipPrefix = "The total number of unique contexts for evaluating the `prototypes` scene, including all context variables, and different prototype roots." ) _TimeOffsetContextVariableWidget = lambda plug : _ContextVariableWidget( plug, overrideName = "frame" ) ########################################################################## # Metadata ########################################################################## Gaffer.Metadata.registerNode( GafferScene.Instancer, "description", """ Copies from an input scene onto the vertices of a target object, making one copy per vertex. Additional primitive variables on the target object can be used to choose between multiple instances, and to specify their orientation and scale. Note the target object will be removed from the scene. """, "layout:section:Settings.General:collapsed", False, "layout:section:Settings.Transforms:collapsed", False, "layout:section:Settings.Attributes:collapsed", False, "layout:activator:modeIsIndexedRootsList", lambda node : node["prototypeMode"].getValue() == GafferScene.Instancer.PrototypeMode.IndexedRootsList, "layout:activator:modeIsNotIndexedRootsList", lambda node : node["prototypeMode"].getValue() != GafferScene.Instancer.PrototypeMode.IndexedRootsList, "layout:activator:modeIsNotRootPerVertex", lambda node : node["prototypeMode"].getValue() != GafferScene.Instancer.PrototypeMode.RootPerVertex, "layout:activator:seedEnabled", lambda node : node["seedEnabled"].getValue(), "layout:activator:seedParameters", lambda node : not node["rawSeed"].getValue(), "layout:customWidget:seedColumnHeadings:widgetType", "GafferSceneUI.InstancerUI._SeedColumnHeadings", "layout:customWidget:seedColumnHeadings:section", "Context Variations", "layout:customWidget:seedColumnHeadings:index", 18, "layout:customWidget:idContextCountSpacer:widgetType", "GafferSceneUI.InstancerUI._SeedCountSpacer", "layout:customWidget:idContextCountSpacer:section", "Context Variations", "layout:customWidget:idContextCountSpacer:index", 19, "layout:customWidget:idContextCountSpacer:accessory", True, "layout:customWidget:idContextCount:widgetType", "GafferSceneUI.InstancerUI._SeedCountWidget", "layout:customWidget:idContextCount:section", "Context Variations", "layout:customWidget:idContextCount:index", 19, "layout:customWidget:idContextCount:accessory", True, "layout:customWidget:seedVariableSpacer:widgetType", "GafferSceneUI.InstancerUI._VariationSpacer", "layout:customWidget:seedVariableSpacer:section", "Context Variations", "layout:customWidget:seedVariableSpacer:index", 20, "layout:customWidget:seedVariableSpacer:accessory", True, "layout:customWidget:seedsSpacer:widgetType", "GafferSceneUI.InstancerUI._VariationSpacer", "layout:customWidget:seedsSpacer:section", "Context Variations", "layout:customWidget:seedsSpacer:index", 21, "layout:customWidget:seedsSpacer:accessory", True, "layout:customWidget:seedPermutationSpacer:widgetType", "GafferSceneUI.InstancerUI._VariationSpacer", "layout:customWidget:seedPermutationSpacer:section", "Context Variations", "layout:customWidget:seedPermutationSpacer:index", 22, "layout:customWidget:seedPermutationSpacer:accessory", True, "layout:customWidget:seedSpacer:widgetType", "GafferSceneUI.InstancerUI._SectionSpacer", "layout:customWidget:seedSpacer:section", "Context Variations", "layout:customWidget:seedSpacer:index", 23, "layout:customWidget:timeOffsetHeadings:widgetType", "GafferSceneUI.InstancerUI._TimeOffsetColumnHeadings", "layout:customWidget:timeOffsetHeadings:section", "Context Variations", "layout:customWidget:timeOffsetHeadings:index", 24, "layout:customWidget:timeOffsetHeadings:description", "Testing description", "layout:customWidget:timeOffsetSpacer:widgetType", "GafferSceneUI.InstancerUI._SectionSpacer", "layout:customWidget:timeOffsetSpacer:section", "Context Variations", "layout:customWidget:timeOffsetSpacer:index", 25, "layout:customWidget:timeOffsetSpacer:divider", True, "layout:customWidget:totalSpacer:widgetType", "GafferSceneUI.InstancerUI._SectionSpacer", "layout:customWidget:totalSpacer:section", "Context Variations", "layout:customWidget:totalSpacer:index", 26, plugs = { "parent" : [ "description", """ The object on which to make the instances. The position, orientation and scale of the instances are taken from per-vertex primitive variables on this object. This is ignored when a filter is connected, in which case the filter specifies multiple objects to make the instances from. """, "layout:section", "Settings.General", ], "name" : [ "description", """ The name of the location the instances will be generated below. This will be parented directly under the parent location. """, "layout:section", "Settings.General", ], "prototypes" : [ "description", """ The scene containing the prototypes to be applied to each vertex. Use the `prototypeMode` and associated plugs to control the mapping between prototypes and instances. Note that the prototypes are not limited to being a single object - they can have arbitrary child hierarchies. """, "plugValueWidget:type", "", ], "prototypeMode" : [ "description", """ The method used to define how the prototypes map onto each instance. - In "Indexed (Roots List)" mode, the `prototypeIndex` primitive variable must be an integer per-vertex. Optionally, a path in the prototypes scene corresponding to each index can be specified via the `prototypeRootsList` plug. If no roots are specified, an index of 0 applies the first location from the prototypes scene, an index of 1 applies the second, and so on. - In "Indexed (Roots Variable)" mode, the `prototypeIndex` primitive variable must be an integer per-vertex, and the `prototypeRoots` primitive variable must be a separate constant string array specifying a path in the prototypes scene corresponding to each index. - In "Root per Vertex" mode, the `prototypeRoots` primitive variable must be a string per-vertex which will be used to specify a path in the prototypes scene for each instance. > Note : it is advisable to provide an indexed string array in order to limit the number of unique prototypes. """, "preset:Indexed (Roots List)", GafferScene.Instancer.PrototypeMode.IndexedRootsList, "preset:Indexed (Roots Variable)", GafferScene.Instancer.PrototypeMode.IndexedRootsVariable, "preset:Root per Vertex", GafferScene.Instancer.PrototypeMode.RootPerVertex, "plugValueWidget:type", "GafferUI.PresetsPlugValueWidget", "layout:section", "Prototypes", ], "prototypeIndex" : [ "description", """ The name of a per-vertex integer primitive variable used to determine which prototype is applied to the vertex. This plug is used in "Indexed (Roots List)" mode as well as "Indexed (Roots Variable)" mode. """, "userDefault", "prototypeIndex", "layout:section", "Prototypes", "layout:visibilityActivator", "modeIsNotRootPerVertex", ], "prototypeRoots" : [ "description", """ If `prototypeMode` is set to "Indexed (Roots Variable)", then this should specify the name of a constant string array primitive variable used to map between `prototypeIndex` and paths in the prototypes scene. If `prototypeMode` is set to "Root per Vertex", then this should specify the name of a per-vertex string primitive variable used to specify a path in the prototypes scene for each instance. This plug is not used in "Indexed (Roots List)" mode. """, "layout:section", "Prototypes", "layout:visibilityActivator", "modeIsNotIndexedRootsList", ], "prototypeRootsList" : [ "description", """ An explicit list of paths used to map between `prototypeIndex` and paths in the prototypes scene. This plug is only used in "Indexed (Roots List)" mode. """, "layout:section", "Prototypes", "layout:visibilityActivator", "modeIsIndexedRootsList", ], "id" : [ "description", """ The name of a per-vertex integer primitive variable used to give each instance a unique identity. This is useful when points are added and removed over time, as is often the case in a particle simulation. The id is used to name the instance in the output scene. """, "layout:section", "Settings.General", ], "position" : [ "description", """ The name of the per-vertex primitive variable used to specify the position of each instance. """, "layout:section", "Settings.Transforms", ], "orientation" : [ "description", """ The name of the per-vertex primitive variable used to specify the orientation of each instance. This must be provided as a quaternion : use an upstream Orientation node to convert from other representations before instancing. """, "userDefault", "orientation", "layout:section", "Settings.Transforms", ], "scale" : [ "description", """ The name of the per-vertex primitive variable used to specify the scale of each instance. Scale can be provided as a float for uniform scaling, or as a vector to define different scaling in each axis. """, "userDefault", "scale", "layout:section", "Settings.Transforms", ], "attributes" : [ "description", """ The names of per-vertex primitive variables to be turned into per-instance attributes. Names should be separated by spaces and can use Gaffer's standard wildcards. """, "layout:section", "Settings.Attributes", ], "attributePrefix" : [ "description", """ A prefix added to all per-instance attributes specified via the \"attributes\" plug. """, "userDefault", "user:", "layout:section", "Settings.Attributes", ], "encapsulateInstanceGroups" : [ "description", """ Converts each group of instances into a capsule, which won't be expanded until you Unencapsulate or render. When keeping these locations encapsulated, downstream nodes can't see the instance locations, which prevents editing but improves performance. This option should be preferred to a downstream Encapsulate node because it has the following benefits : - Substantially improved performance when the prototypes define sets. - Fewer unnecessary updates during interactive rendering. """, "label", "Instance Groups", "layout:section", "Settings.Encapsulation", ], "seedEnabled" : [ "description", """ Creates a seed context variable based on a hash of the instance ID, which could come from the primitive varable specified in the `id` plug or otherwise the point index. This integer is available to the upstream prototypes network, and might typically be used with a Random node to randomise properties of the prototype. """, "layout:section", "Context Variations", ], "seedVariable" : [ "description", """ Name of the context variable to put the seed value in. """, "layout:section", "Context Variations", "layout:visibilityActivator", "seedEnabled", ], "seeds" : [ "description", """ The number of possible seed values. Increasing this allows for more different variations to be driven by the seed, increasing the total number of variations required. """, "layout:section", "Context Variations", "layout:visibilityActivator", "seedEnabled", "layout:activator", "seedParameters", ], "seedPermutation" : [ "description", """ Changing the seedPermutation changes the mapping of ids to seeds. This results in a different grouping of which instances end up with the same seed. """, "layout:section", "Context Variations", "layout:visibilityActivator", "seedEnabled", "layout:activator", "seedParameters", ], "rawSeed" : [ "description", """ Enable this in rare cases when it is required to pass through every single id directly into the seed context variable. This is very expensive, because every single instance will need a separate context, but is sometimes useful, and may be an acceptable cost if there isn't a huge number of total instances. """, "layout:section", "Context Variations", "layout:visibilityActivator", "seedEnabled", ], "contextVariables" : [ "description", """ Specifies context variables to be created from primitive variables. These variables are available to upstream prototypes network, allowing the prototypes scene to be generated differently depending on the source point. Supports quantization to avoid re-evaluating the prototypes scene too many times. """, "layout:section", "Context Variations", "plugValueWidget:type", "GafferSceneUI.InstancerUI._ContextVariableListWidget", ], "contextVariables.*" : [ "deletable", True ], "contextVariables.*.name" : [ "description", """ Name of the primitive variable to read. The same name will be used for the context variables available to the upstream prototype network. """, ], "contextVariables.*.enabled" : [ "description", """ Puts this variable in the context for the upstream prototypes network. """, ], "contextVariables.*.quantize" : [ "description", """ Quantizing to a large interval reduces the number of variations created. For example, if the primvar varies from 0 to 1, and you quantize to 0.2, then only 6 unique variations will be created, even if there are millions of instances. This dramatically improves performance, but if you need to see more continuous changes in the primvar values, you will need to reduce quantize, or in extreme cases where you need full accuracy and don't care about performance, set it to 0. """, ], "timeOffset" : [ "description", "Modify the current time when evaluating the prototypes network, by adding a primvar.", "layout:section", "Context Variations", "plugValueWidget:type", "GafferSceneUI.InstancerUI._TimeOffsetContextVariableWidget", ], "timeOffset.name" : [ "description", """ Name of a primitive variable to add to the time. Must be a float or int primvar. It will be treated as a number of frames, and can be negative or positive to adjust time forward or back. """, ], "timeOffset.enabled" : [ "description", """ Modifies the current time for the network upstream of the prototypes plug. """, ], "timeOffset.quantize" : [ "description", """ Quantizes the variable value before adding it to the time. Quantizing to a large interval reduces the number of variations created. For example, if the primvar varies from 0 to 1, and you quantize to 0.2, then only 6 unique variations will be created, even if there are millions of instances. This dramatically improves performance, but if you need to see more continuous changes in the primvar values, you will need to reduce quantize, or in extreme cases where you need full accuracy and don't care about performance, set it to 0. """, ], "variations" : [ "description", """ This special output plug returns an CompoundData dictionary with counts about how many variations are being created. For each context variable variable being set ( including "frame" when using Time Offset ), there is an entry with the name of the context variable, with an IntData containing the number of unique values of that context variable. There is also an entry for "", with an IntData for the total number of unique contexts, considering all the context variables being created. Extracting the dictionary values and displaying them to users is handled by _VariationsPlugValueWidget. This information is important to display to users because varying the context requires extra evaluations of the `prototypes` scene, and can dramatically increase the cost of the Instancer. Note that variations are measured across all locations in the scene where the instancer is filtered. """, "layout:section", "Context Variations", "layout:index", 27, "plugValueWidget:type", "GafferSceneUI.InstancerUI._TotalCountWidget", ], } )
saleor/webhook/migrations/0001_initial.py
fairhopeweb/saleor
15,337
147415
# Generated by Django 2.2.4 on 2019-09-26 05:47 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [("account", "0033_serviceaccount")] operations = [ migrations.CreateModel( name="Webhook", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("target_url", models.URLField(max_length=255)), ("is_active", models.BooleanField(default=True)), ("secret_key", models.CharField(blank=True, max_length=255, null=True)), ( "service_account", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="webhooks", to="account.ServiceAccount", ), ), ], options={"permissions": (("manage_webhooks", "Manage webhooks"),)}, ), migrations.CreateModel( name="WebhookEvent", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ( "event_type", models.CharField( db_index=True, max_length=128, verbose_name="Event type" ), ), ( "webhook", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="events", to="webhook.Webhook", ), ), ], ), ]
python/lbann/core/optimizer.py
jonesholger/lbann
194
147441
import abc from lbann import optimizers_pb2 import lbann.core.util class Optimizer(abc.ABC): """Optimization algorithm for a neural network's parameters.""" def export_proto(self): """Construct and return a protobuf message.""" return optimizers_pb2.Optimizer() # Generate Optimizer sub-classes from lbann.proto # Note: The list of skip fields must be updated if any new fields are # added to the Optimizer message in lbann.proto if optimizers_pb2: classes = lbann.core.util.generate_classes_from_protobuf_message( optimizers_pb2.Optimizer, base_class = Optimizer, base_has_export_proto = True) for c in classes: globals()[c.__name__] = c
convlab/modules/nlu/multiwoz/onenet/dataset_reader.py
ngduyanhece/ConvLab
405
147449
<filename>convlab/modules/nlu/multiwoz/onenet/dataset_reader.py # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import json import logging import os import zipfile from typing import Dict, List, Any from allennlp.data.dataset_readers.dataset_reader import DatasetReader from allennlp.data.fields import TextField, SequenceLabelField, LabelField, MetadataField, Field from allennlp.data.instance import Instance from allennlp.data.token_indexers import TokenIndexer, SingleIdTokenIndexer from allennlp.data.tokenizers import Token from overrides import overrides from convlab.lib.file_util import cached_path logger = logging.getLogger(__name__) # pylint: disable=invalid-name @DatasetReader.register("onenet") class OneNetDatasetReader(DatasetReader): """ Reads instances from a pretokenised file where each line and converts it into a ``Dataset`` suitable for sequence tagging. Parameters ---------- """ def __init__(self, token_delimiter: str = None, token_indexers: Dict[str, TokenIndexer] = None, lazy: bool = False) -> None: super().__init__(lazy) self._token_indexers = token_indexers or {'tokens': SingleIdTokenIndexer()} self._token_delimiter = token_delimiter @overrides def _read(self, file_path): # if `file_path` is a URL, redirect to the cache file_path = cached_path(file_path) if file_path.endswith("zip"): archive = zipfile.ZipFile(file_path, "r") data_file = archive.open(os.path.basename(file_path)[:-4]) else: data_file = open(file_path, "r") logger.info("Reading instances from lines in file at: %s", file_path) dialogs = json.load(data_file) for dial_name in dialogs: dialog = dialogs[dial_name]["log"] for turn in dialog: tokens = turn["text"].split() spans = turn["span_info"] tags = [] domain = "None" intent = "None" for i in range(len(tokens)): for span in spans: if i == span[3]: new_domain, new_intent = span[0].split("-", 1) if domain == "None": domain = new_domain elif domain != new_domain: continue if intent == "None": intent = new_intent elif intent != new_intent: continue tags.append("B-"+span[1]) break if i > span[3] and i <= span[4]: new_domain, new_intent = span[0].split("-", 1) if domain != new_domain: continue if intent != new_intent: continue tags.append("I-"+span[1]) break else: tags.append("O") if domain != "None": assert intent != "None", "intent must not be None when domain is not None" elif turn["dialog_act"] != {}: assert intent == "None", "intent must be None when domain is None" di = list(turn["dialog_act"].keys())[0] dai = turn["dialog_act"][di][0] domain = di.split("-")[0] intent = di.split("-", 1)[-1] + "+" + dai[0] + "*" + dai[1] dialog_act = {} for dacts in turn["span_info"]: if dacts[0] not in dialog_act: dialog_act[dacts[0]] = [] dialog_act[dacts[0]].append([dacts[1], " ".join(tokens[dacts[3]: dacts[4]+1])]) for dacts in turn["dialog_act"]: for dact in turn["dialog_act"][dacts]: if dacts not in dialog_act: dialog_act[dacts] = turn["dialog_act"][dacts] break elif dact[0] not in [sv[0] for sv in dialog_act[dacts]]: dialog_act[dacts].append(dact) tokens = [Token(token) for token in tokens] yield self.text_to_instance(tokens, tags, domain, intent, dialog_act) def text_to_instance(self, tokens: List[Token], tags: List[str] = None, domain: str = None, intent: str = None, dialog_act: Dict[str, Any] = None) -> Instance: # type: ignore """ We take `pre-tokenized` input here, because we don't have a tokenizer in this class. """ # pylint: disable=arguments-differ fields: Dict[str, Field] = {} sequence = TextField(tokens, self._token_indexers) fields["tokens"] = sequence if tags: fields["tags"] = SequenceLabelField(tags, sequence) if domain: fields["domain"] = LabelField(domain, label_namespace="domain_labels") if intent: fields["intent"] = LabelField(intent, label_namespace="intent_labels") if dialog_act is not None: fields["metadata"] = MetadataField({"words": [x.text for x in tokens], 'dialog_act': dialog_act}) else: fields["metadata"] = MetadataField({"words": [x.text for x in tokens], 'dialog_act': {}}) return Instance(fields)
tools/bootloader/can/host/bootloader.py
roboterclubaachen/xpcc
161
147469
#!/usr/bin/env python3 """ Bootloader for AVR-Boards connected via CAN bus Format: 11-Bit Identifier 1. Board Identifier 2. Message Type 3. Message Number 4. Message Data Counter 5.-8. Data """ import time import math import Queue import threading import can import message_filter as filter from util import intelhex from util import progressbar __version__ = "1.5" # ------------------------------------------------------------------------------ class BootloaderFilter(filter.BaseFilter): def check(self, message): if message.extended == False and \ message.rtr == False and \ message.id == 0x7fe: return True return False # ----------------------------------------------------------------------------- class BootloaderException(Exception): pass # ----------------------------------------------------------------------------- class MessageSubject: IDENTIFY = 1 SET_ADDRESS = 2 DATA = 3 START_APPLICATION = 4 # only avilable in the "bigger" versions GET_FUSEBITS = 5 CHIP_ERASE = 6 def __init__(self, subject): self.subject = subject def __str__(self): return { 1: "identify", 2: "set_address", 3: "data", 4: "start_app", 5: "get_fusebit", 6: "chip_erase"}[self.subject] # ----------------------------------------------------------------------------- class MessageType: REQUEST = 0 SUCCESS = 1 ERROR = 2 WRONG_NUMBER = 3 def __init__(self, type): self.type = type def __str__(self): return { 0: "request", 1: "success", 2: "error", 3: "wrong_number" }[self.type] # ------------------------------------------------------------------------------ class Message: """ representation of a message for the bootloader """ BOOTLOADER_CAN_IDENTIFIER = 0x7ff START_OF_MESSAGE_MASK = 0x80 # -------------------------------------------------------------------------- def __init__( self, board_id = None, type = MessageType.REQUEST, subject = None, number = 0, data_counter = 0, data = []): # set default values self.board_id = board_id self.type = type self.subject = subject self.number = number self.data_counter = data_counter self.data = data # -------------------------------------------------------------------------- def decode(self, message): if len(message.data) < 4 or message.extended or message.rtr: raise BootloaderException("wrong format of message %s" % message) # convert can-message to a bootloader-message self.board_id = message.data[0] self.type = message.data[1] >> 6 self.subject = message.data[1] & 0x3f self.number = message.data[2] self.data_counter = message.data[3] self.data = message.data[4:] return self # -------------------------------------------------------------------------- def encode(self): """ Convert the bootloader-message to a can-message """ data = [self.board_id, self.type << 6 | self.subject, self.number, self.data_counter] + self.data message = can.Message(self.BOOTLOADER_CAN_IDENTIFIER, data, extended = False, rtr = False) return message # -------------------------------------------------------------------------- def __str__(self): str = "%s.%s id 0x%x [%x] %i >" % (MessageSubject(self.subject).__str__().upper(), MessageType(self.type), self.board_id, self.number, self.data_counter) for data in self.data: str += " %02x" % data return str # ----------------------------------------------------------------------------- class ProgrammeableBoard: """Container class which holds information about an active board""" # -------------------------------------------------------------------------- def __init__(self, id): self.id = id self.connected = False # information about the board we are currently programming self.bootloader_type = None self.version = 0.0 self.pages = 0 self.pagesize = 0 # -------------------------------------------------------------------------- def __str__(self): str = "board id 0x%x" % self.id if self.connected: str += " (T%i) v%1.1f, %i pages [%i Byte]" % (self.bootloader_type, self.version, self.pages, self.pagesize) return str # ------------------------------------------------------------------------------ class Bootloader: WAITING = 0 START = 1 IN_PROGRESS = 2 END = 3 ERROR = 4 # -------------------------------------------------------------------------- def __init__(self, board_id, interface, debug = False): """Constructor""" self.board = ProgrammeableBoard(board_id) # connect to the message dispatcher filter = BootloaderFilter(self._get_message) self.interface = interface self.interface.addFilter(filter) self.debugmode = debug self.msg_number = 0 self.msg_wait_for = threading.Event() self.msg_queue = Queue.Queue() # -------------------------------------------------------------------------- def _start_bootloader_command(self): pass # -------------------------------------------------------------------------- def identify(self): """Send the "Identify" command until it gets a response from the bootloader and decode the returned information """ # send message and wait for a response while True: try: self._start_bootloader_command() response = self._send(subject = MessageSubject.IDENTIFY, timeout = 0.1, attempts = 10) except BootloaderException: pass else: break # split up the message and fill in the board-representation self.board.bootloader_type = response.data[0] >> 4 self.board.version = response.data[0] & 0x0F self.board.pagesize = {0: 32, 1:64, 2:128, 3:256}[response.data[1]] self.board.pages = (response.data[2] << 8) + response.data[3] #print(response.data) self.board.connected = True # -------------------------------------------------------------------------- def program_page(self, page, data, addressAlreadySet = False): """Program a page of the flash memory Tries the send the data in a blocks of 32 messages befor an acknowledge. The blocksize is stepwise reduced to one when there are any errors during the transmission. Raises BootloaderException if the error stil appears then. """ data = [ord(x) for x in data] # amend the data field to a complete page size = len(data) if size < self.board.pagesize: data += [0xff] * (self.board.pagesize - size) remaining = self.board.pagesize / 4 blocksize = 64 offset = 0 while remaining > 0: try: if not addressAlreadySet: # set address in the page buffer self._send( MessageSubject.SET_ADDRESS, [page >> 8, page & 0xff, 0, offset] ) if remaining < blocksize: blocksize = remaining if blocksize == 1: answer = self._send( MessageSubject.DATA, data[offset*4:offset*4 + 4] ) else: i = offset # start of a new block self._send( MessageSubject.DATA, response = False, counter = Message.START_OF_MESSAGE_MASK | (blocksize - 1), data = data[i * 4: i * 4 + 4]) for k in range(blocksize - 2, 0 , -1): i += 1 self._send( MessageSubject.DATA, response = False, counter = k, data = data[i*4:i*4 + 4] ) # wait for the response for the last message of this block i += 1 answer = self._send( MessageSubject.DATA, response = True, counter = 0, data = data[i * 4: i * 4 + 4]) remaining -= blocksize offset += blocksize addressAlreadySet = True except BootloaderException as msg: print("Exception: %s") % msg if blocksize > 1: blocksize /= 2 print(blocksize) # we have to reset the buffer position addressAlreadySet = False time.sleep(0.3) else: raise # check whether the page was written correctly returned_page = answer.data[0] << 8 | answer.data[1] if returned_page != page: raise BootloaderException("Could not write page %i!" % page) # page was completly transmitted => write it to the flash #self._send( MessageSubject.WRITE_PAGE, [page / 0xff, page % 0xff] ) # -------------------------------------------------------------------------- def start_app(self): """Start the written application""" self._send( MessageSubject.START_APPLICATION ) # -------------------------------------------------------------------------- def program(self, segments): """Program the AVR First the function waits for a connection then it will send the data page by page. Finally the written application will be started. """ self._report_progress(self.WAITING) print("connecting ... ",) # try to connect to the bootloader self.identify() print("ok") print(self.board) totalsize = reduce(lambda x,y: x + y, map(lambda x: len(x), segments)) segment_number = 0 pagesize = self.board.pagesize pages = int(math.ceil(float(totalsize) / float(pagesize))) print("write %i pages\n" % pages) if pages > self.board.pages: raise BootloaderException("Programsize exceeds available Flash!") # start progressbar self._report_progress(self.START) starttime = time.time() addressSet = False offset = 0 for i in range(pages): data = segments[segment_number] self.program_page(page = i, data = data[offset:offset+pagesize], addressAlreadySet = addressSet) offset += pagesize if offset >= len(data): offset = 0 segment_number += 1 self.debug("Now starting segment %i" % segment_number) addressSet = True self._report_progress(self.IN_PROGRESS, float(i) / float(pages)) # show a 100% progressbar self._report_progress(self.END) endtime = time.time() print("%.2f seconds\n" % (endtime - starttime)) # start the new application self.start_app() # -------------------------------------------------------------------------- def _send( self, subject, data = [], counter = Message.START_OF_MESSAGE_MASK | 0, response = True, timeout = 0.5, attempts = 2): """Send a message via CAN Bus With default settings the functions waits for the response to the message and retry the transmission after a timeout. After the specifed number of retries it will raise a BootloaderException. Keeps track of the message numbering and restores the correct number in case of a reported error.""" message = Message(board_id = self.board.id, type = MessageType.REQUEST, subject = subject, number = self.msg_number, data_counter = counter, data = data ) if not response: # no response needed, just send the message and return self.interface.send( message.encode() ) self.msg_number = (self.msg_number + 1) & 0xff return None repeats = 0 finished = False # clear message queue to delete messages belonging to another # transmission while True: try: self.msg_queue.get(False, 0) except Queue.Empty: break while not finished: # send the message self.interface.send( message.encode() ) # wait for the response while True: try: response_msg = self.msg_queue.get(True, timeout) except Queue.Empty: break; else: if response_msg.subject == message.subject: if response_msg.type == MessageType.SUCCESS: finished = True # drain message queue to delete answers to repeated transmits while True: try: self.msg_queue.get(False, 0) except Queue.Empty: break break; elif response_msg.type == MessageType.WRONG_NUMBER: print("Warning: Wrong message number detected (board says %x, I have %x)" % (response_msg.number, message.number)) # reset message number only if we just started the communication if message.number == 0: self.msg_number = response_msg.number message.number = self.msg_number # wait a bit for other error message time.sleep(0.1) while True: try: self.msg_queue.get(False, 0.1) except Queue.Empty: break # TODO reset command stack? addressAlreadySet = False # target might have cycled power, so send address for next block break; else: raise BootloaderException("Failure %i while sending '%s'" % (response_msg.type, message)) else: self.debug("Warning: Discarding obviously old message (received %i/%x, I have %i/%x)" % (response_msg.subject, response_msg.number, message.subject, message.number)) repeats += 1 if attempts > 0 and repeats >= attempts: raise BootloaderException("No response after %i attempts and timeout %i while sending '%s'" % (repeats, timeout, message)) # increment the message number self.msg_number = (self.msg_number + 1) & 0xff return response_msg # -------------------------------------------------------------------------- def _get_message(self, can_message): """Receives and checks all messages from the CAN bus""" self.debug("> " + str(can_message)) try: message = Message().decode(can_message) if message.board_id != self.board.id: # message is for someone other return except BootloaderException: # message has an incorrect format return self.msg_queue.put(message) # -------------------------------------------------------------------------- def debug(self, text): if self.debugmode: print(text) # -------------------------------------------------------------------------- def _report_progress(self, state, progress = 0.0): """Called to report the current status Can be overwritten to implement a progressbar for example. """ pass # ------------------------------------------------------------------------------ class CommandlineClient(Bootloader): # -------------------------------------------------------------------------- def __init__(self, board_id, interface, debug): Bootloader.__init__(self, board_id, interface, debug) # create a progressbar to show the progress while programming self.progressbar = progressbar.ProgressBar(max = 1.0, width = 60) # -------------------------------------------------------------------------- def _start_bootloader_command(self): # send a rccp reset command dest = self.board.id source = 0xff id = "0x18%02x%02x%02x" % (dest, source, 0x01) msg = can.Message(int(id, 16), extended = True, rtr = False) self.interface.send(msg) # -------------------------------------------------------------------------- def _report_progress(self, state, progress = 0.0): if state == self.WAITING: pass elif state == self.START: self.progressbar(0) elif state == self.IN_PROGRESS: self.progressbar(progress) elif state == self.END: self.progressbar(1.0) print("") # ------------------------------------------------------------------------------ if __name__ == '__main__': from optparse import OptionParser parser = OptionParser( usage = "%prog [options] -i BOARD_ID -f FILE", version = "%prog version: " + __version__ ) parser.add_option("-f", "--file", dest="filename", metavar="FILE", help="AVR .hex File") parser.add_option("-p", "--port", dest="port", default="/dev/ttyUSB0", help="serial port (default is '/dev/ttyUSB0')") parser.add_option("-b", "--baud", dest="baudrate", default="115200", help="baudrate (default is '115200')") parser.add_option("-i", "--id", dest="id", help="id of the board to program") parser.add_option("-e", "--erase", action="count", help="erase Chip befor programming") parser.add_option("-a", "--application", action="count", dest="start_app", help="start Application (only evaluated if FILE is not specified)") parser.add_option("-c", "--config", action="count", help="prints the configuration of the bootloader") parser.add_option("-d", "--debug", action="count", help="prints additional debug information while sending the programm") parser.add_option("-t", "--type", dest="type", default="can2usb", help="Select type of CAN adapter ('can2usb' or 'shell')") (options, args) = parser.parse_args() if not options.filename or not options.id: print(parser.get_usage()) exit(1) board_id = int(options.id, 0) debug_mode = True if (options.debug) else False print("CAN Bootloader\n") print("Port : %s" % options.port) print("Board Id : %i (0x%02x)" % (board_id, board_id)) if debug_mode: print("debug mode active!") print("File : %s" % options.filename) hexfile = intelhex.IntelHexParser(options.filename) if len(hexfile.segments) > 1: print(" File has %i segments %s bytes" % (len(hexfile.segments), map(lambda x: len(x), hexfile.segments))) print("Size : %i Bytes" % reduce(lambda x,y: x + y, map(lambda x: len(x), hexfile.segments))) # create a connection to the can bus if options.type == "can2usb": print("Interface : CAN2USB\n") interface = can.Usb2Can(port = options.port, baud = int(options.baudrate, 10), debug = debug_mode) elif options.type == "shell": print("Interface : CAN Debugger\n") interface = can.CanDebugger(port = options.port, baud = int(options.baudrate, 10), debug = debug_mode) else: print("Error: Unknown interface type: '%s'" % options.type) exit(1) interface.connect() try: bootloader = CommandlineClient(board_id, interface, debug = debug_mode) bootloader.program(hexfile.segments) except BootloaderException as msg: print("Error: %s" % msg) except KeyboardInterrupt as msg: print("Abort!") finally: interface.disconnect()
chapter5_operations/prediction_monitoring_pattern/src/db/cruds.py
sudabon/ml-system-in-actions
133
147549
from typing import Dict, List from sqlalchemy.orm import Session from src.db import models, schemas def select_prediction_log_all(db: Session) -> List[schemas.PredictionLog]: return db.query(models.PredictionLog).all() def select_prediction_log_between( db: Session, time_before: str, time_later: str, ) -> List[schemas.PredictionLog]: return ( db.query(models.PredictionLog) .filter(models.PredictionLog.created_datetime >= time_before) .filter(models.PredictionLog.created_datetime <= time_later) .all() ) def select_outlier_log_all(db: Session) -> List[schemas.OutlierLog]: return db.query(models.OutlierLog).all() def select_outlier_log_between( db: Session, time_before: str, time_later: str, ) -> List[schemas.OutlierLog]: return ( db.query(models.OutlierLog) .filter(models.OutlierLog.created_datetime >= time_before) .filter(models.OutlierLog.created_datetime <= time_later) .all() ) def add_prediction_log( db: Session, log_id: str, log: Dict, commit: bool = True, ) -> schemas.PredictionLog: data = models.PredictionLog( log_id=log_id, log=log, ) db.add(data) if commit: db.commit() db.refresh(data) return data def add_outlier_log( db: Session, log_id: str, log: Dict, commit: bool = True, ) -> schemas.OutlierLog: data = models.OutlierLog( log_id=log_id, log=log, ) db.add(data) if commit: db.commit() db.refresh(data) return data
yotta/lib/component.py
microbit-foundation/yotta
176
147573
# Copyright 2014 ARM Limited # # Licensed under the Apache License, Version 2.0 # See LICENSE file for details. # standard library modules, , , import os import logging from collections import OrderedDict # access, , get components, internal from yotta.lib import access from yotta.lib import access_common # pool, , shared thread pool, internal #from pool import pool # vcs, , represent version controlled directories, internal from yotta.lib import vcs # fsutils, , misc filesystem utils, internal from yotta.lib import fsutils # Pack, , common parts of Components/Targets, internal from yotta.lib import pack # !!! FIXME: should components lock their description file while they exist? # If not there are race conditions where the description file is modified by # another process (or in the worst case replaced by a symlink) after it has # been opened and before it is re-written # Constants Modules_Folder = 'yotta_modules' Targets_Folder = 'yotta_targets' Component_Description_File = 'module.json' Component_Description_File_Fallback = 'package.json' Component_Definitions_File = 'defines.json' Registry_Namespace = 'modules' Schema_File = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'schema', 'module.json') logger = logging.getLogger('components') VVVERBOSE_DEBUG = logging.DEBUG - 8 def _truthyConfValue(v): ''' Determine yotta-config truthiness. In yotta config land truthiness is different to python or json truthiness (in order to map nicely only preprocessor and CMake definediness): json -> python -> truthy/falsey false -> False -> Falsey null -> None -> Falsey undefined -> None -> Falsey 0 -> 0 -> Falsey "" -> "" -> Truthy (different from python) "0" -> "0" -> Truthy {} -> {} -> Truthy (different from python) [] -> [] -> Truthy (different from python) everything else is truthy ''' if v is False: return False elif v is None: return False elif v == 0: return False else: # everything else is truthy! return True # API class Component(pack.Pack): def __init__( self, path, installed_linked = False, latest_suitable_version = None, test_dependency = False, inherit_shrinkwrap = None ): ''' How to use a Component: Initialise it with the directory into which the component has been downloaded, (or with a symlink that points to a directory containing the component) Check that 'if component:' is true, which indicates that the download is indeed a valid component. Check that component.getVersion() returns the version you think you've downloaded. Use component.getDependencySpecs() to get the names of the dependencies of the component, or component.getDependencies() to get Component objects (which may not be valid unless the dependencies have been installed) for each of the dependencies. ''' self.description = OrderedDict() logger.log(VVVERBOSE_DEBUG, "Component: " + path + ' installed_linked=' + str(installed_linked)) warn_deprecated_filename = False if (not os.path.exists(os.path.join(path, Component_Description_File))) and \ os.path.exists(os.path.join(path, Component_Description_File_Fallback)): warn_deprecated_filename = True description_filename = Component_Description_File_Fallback else: description_filename = Component_Description_File super(Component, self).__init__( path, description_filename = description_filename, installed_linked = installed_linked, schema_filename = Schema_File, latest_suitable_version = latest_suitable_version, inherit_shrinkwrap = inherit_shrinkwrap ) if self.description and inherit_shrinkwrap is not None: # when inheriting a shrinkwrap, check that this module is # listed in the shrinkwrap, otherwise emit a warning: if next((x for x in inherit_shrinkwrap.get('modules', []) if x['name'] == self.getName()), None) is None: logger.warning("%s missing from shrinkwrap", self.getName()) if warn_deprecated_filename: logger.warning( "Component %s uses deprecated %s file, use %s instead." % ( self.getName(), Component_Description_File_Fallback, Component_Description_File ) ) if 'bin' in self.description and 'lib' in self.description: self.error = 'Both "lib" and "bin" are specified in module.json: '+\ 'only one is allowed. If this is an executable module, then '+\ 'it should not specify a "lib" subdirectory, and if this is '+\ 'a re-usable library module, it should not specify a "bin" '+\ 'subdirectory' self.description = OrderedDict() # specified in the description self.installed_dependencies = False self.dependencies_failed = False self.is_test_dependency = test_dependency # read definitions for applications self.defines = {} defines_path = os.path.join(path, Component_Definitions_File) if os.path.isfile(defines_path): if not self.isApplication(): # only applications can have definitions logger.warning("%s ignored in library module '%s'" % (Component_Definitions_File, self.getName())) else: # TODO: define a schema for this file self.defines = pack.tryReadJSON(defines_path, None) def getDependencySpecs(self, target=None): ''' Returns [DependencySpec] These are returned in the order that they are listed in the component description file: this is so that dependency resolution proceeds in a predictable way. ''' deps = [] def specForDependency(name, version_spec, istest): shrinkwrap = self.getShrinkwrapMapping() shrinkwrap_version_req = None if name in shrinkwrap: # exact version, and pull from registry: shrinkwrap_version_req = shrinkwrap[name] logger.debug( 'respecting %s shrinkwrap version %s for %s', self.getName(), shrinkwrap_version_req, name ) return pack.DependencySpec( name, version_spec, istest, shrinkwrap_version_req = shrinkwrap_version_req, specifying_module = self.getName() ) deps += [specForDependency(x[0], x[1], False) for x in self.description.get('dependencies', {}).items()] target_deps = self.description.get('targetDependencies', {}) if target is not None: for conf_key, target_conf_deps in target_deps.items(): if _truthyConfValue(target.getConfigValue(conf_key)) or conf_key in target.getSimilarTo_Deprecated(): logger.debug( 'Adding target-dependent dependency specs for target config %s to component %s' % (conf_key, self.getName()) ) deps += [specForDependency(x[0], x[1], False) for x in target_conf_deps.items()] deps += [specForDependency(x[0], x[1], True) for x in self.description.get('testDependencies', {}).items()] target_deps = self.description.get('testTargetDependencies', {}) if target is not None: for conf_key, target_conf_deps in target_deps.items(): if _truthyConfValue(target.getConfigValue(conf_key)) or conf_key in target.getSimilarTo_Deprecated(): logger.debug( 'Adding test-target-dependent dependency specs for target config %s to component %s' % (conf_key, self.getName()) ) deps += [specForDependency(x[0], x[1], True) for x in target_conf_deps.items()] # remove duplicates (use the first occurrence) seen = set() r = [] for dep in deps: if not dep.name in seen: r.append(dep) seen.add(dep.name) return r def hasDependency(self, name, target=None, test_dependencies=False): ''' Check if this module has any dependencies with the specified name in its dependencies list, or in target dependencies for the specified target ''' if name in self.description.get('dependencies', {}).keys(): return True target_deps = self.description.get('targetDependencies', {}) if target is not None: for conf_key, target_conf_deps in target_deps.items(): if _truthyConfValue(target.getConfigValue(conf_key)) or conf_key in target.getSimilarTo_Deprecated(): if name in target_conf_deps: return True if test_dependencies: if name in self.description.get('testDependencies', {}).keys(): return True if target is not None: test_target_deps = self.description.get('testTargetDependencies', {}) for conf_key, target_conf_deps in test_target_deps.items(): if _truthyConfValue(target.getConfigValue(conf_key)) or conf_key in target.getSimilarTo_Deprecated(): if name in target_conf_deps: return True return False def hasDependencyRecursively(self, name, target=None, test_dependencies=False): ''' Check if this module, or any of its dependencies, have a dependencies with the specified name in their dependencies, or in their targetDependencies corresponding to the specified target. Note that if recursive dependencies are not installed, this test may return a false-negative. ''' # checking dependencies recursively isn't entirely straightforward, so # use the existing method to resolve them all before checking: dependencies = self.getDependenciesRecursive( target = target, test = test_dependencies ) return (name in dependencies) def getDependencies(self, available_components = None, search_dirs = None, target = None, available_only = False, test = False, warnings = True ): ''' Returns {component_name:component} ''' if search_dirs is None: search_dirs = [self.modulesPath()] available_components = self.ensureOrderedDict(available_components) components, errors = self.__getDependenciesWithProvider( available_components = available_components, search_dirs = search_dirs, target = target, update_installed = False, provider = self.provideInstalled, test = test ) if warnings: for error in errors: logger.warning(error) if available_only: components = OrderedDict((k, v) for k, v in components.items() if v) return components def __getDependenciesWithProvider(self, available_components = None, search_dirs = None, target = None, update_installed = False, provider = None, test = False ): ''' Get installed components using "provider" to find (and possibly install) components. See documentation for __getDependenciesRecursiveWithProvider returns (components, errors) ''' # sourceparse, , parse version source urls, internal from yotta.lib import sourceparse errors = [] modules_path = self.modulesPath() def satisfyDep(dspec): try: r = provider( dspec, available_components, search_dirs, modules_path, update_installed, self ) if r and not sourceparse.parseSourceURL(dspec.versionReq()).semanticSpecMatches(r.getVersion()): shrinkwrap_msg = '' if dspec.isShrinkwrapped(): shrinkwrap_msg = 'shrinkwrap on ' msg = 'does not meet specification %s required by %s%s' % ( dspec.versionReq(), shrinkwrap_msg, self.getName() ) logger.debug('%s %s', r.getName(), msg) r.setError(msg) return r except access_common.Unavailable as e: errors.append(e) self.dependencies_failed = True except vcs.VCSError as e: errors.append(e) self.dependencies_failed = True specs = self.getDependencySpecs(target=target) if not test: # filter out things that aren't test dependencies if necessary: specs = [x for x in specs if not x.is_test_dependency] #dependencies = pool.map( dependencies = map( satisfyDep, specs ) self.installed_dependencies = True # stable order is important! return (OrderedDict([((d and d.getName()) or specs[i].name, d) for i, d in enumerate(dependencies)]), errors) def __getDependenciesRecursiveWithProvider(self, available_components = None, search_dirs = None, target = None, traverse_links = False, update_installed = False, provider = None, test = False, _processed = None ): ''' Get installed components using "provider" to find (and possibly install) components. This function is called with different provider functions in order to retrieve a list of all of the dependencies, or install all dependencies. Returns ======= (components, errors) components: dictionary of name:Component errors: sequence of errors Parameters ========== available_components: None (default) or a dictionary of name:component. This is searched before searching directories or fetching remote components search_dirs: None (default), or sequence of directories to search for already installed, (but not yet loaded) components. Used so that manually installed or linked components higher up the dependency tree are found by their users lower down. These directories are searched in order, and finally the current directory is checked. target: None (default), or a Target object. If specified the target name and it's similarTo list will be used in resolving dependencies. If None, then only target-independent dependencies will be installed traverse_links: False (default) or True: whether to recurse into linked dependencies. You normally want to set this to "True" when getting a list of dependencies, and False when installing them (unless the user has explicitly asked dependencies to be installed in linked components). provider: None (default) or function: provider( dependency_spec, available_components, search_dirs, working_directory, update_if_installed ) test: True, False, 'toplevel': should test-only dependencies be included (yes, no, or only at this level, not recursively) ''' def recursionFilter(c): if not c: logger.debug('do not recurse into failed component') # don't recurse into failed components return False if c.getName() in _processed: logger.debug('do not recurse into already processed component: %s' % c) return False if c.installedLinked() and not traverse_links: return False return True available_components = self.ensureOrderedDict(available_components) if search_dirs is None: search_dirs = [] if _processed is None: _processed = set() assert(test in [True, False, 'toplevel']) search_dirs.append(self.modulesPath()) logger.debug('process %s\nsearch dirs:%s' % (self.getName(), search_dirs)) if self.isTestDependency(): logger.debug("won't provide test dependencies recursively for test dependency %s", self.getName()) test = False components, errors = self.__getDependenciesWithProvider( available_components = available_components, search_dirs = search_dirs, update_installed = update_installed, target = target, provider = provider, test = test ) _processed.add(self.getName()) if errors: errors = ['Failed to satisfy dependencies of %s:' % self.path] + errors need_recursion = [x for x in filter(recursionFilter, components.values())] available_components.update(components) logger.debug('processed %s\nneed recursion: %s\navailable:%s\nsearch dirs:%s' % (self.getName(), need_recursion, available_components, search_dirs)) if test == 'toplevel': test = False # NB: can't perform this step in parallel, since the available # components list must be updated in order for c in need_recursion: dep_components, dep_errors = c.__getDependenciesRecursiveWithProvider( available_components = available_components, search_dirs = search_dirs, target = target, traverse_links = traverse_links, update_installed = update_installed, provider = provider, test = test, _processed = _processed ) available_components.update(dep_components) components.update(dep_components) errors += dep_errors return (components, errors) def provideInstalled(self, dspec, available_components, search_dirs, working_directory, update_installed, dep_of ): #logger.info('%s provideInstalled: %s', dep_of.getName(), dspec.name) r = access.satisfyFromAvailable(dspec.name, available_components) if r: if r.isTestDependency() and not dspec.is_test_dependency: logger.debug('test dependency subsequently occurred as real dependency: %s', r.getName()) r.setTestDependency(False) return r update_if_installed = False if update_installed is True: update_if_installed = True elif update_installed: update_if_installed = dspec.name in update_installed r = access.satisfyVersionFromSearchPaths( dspec.name, dspec.versionReq(), search_dirs, update_if_installed, inherit_shrinkwrap = dep_of.getShrinkwrap() ) if r: r.setTestDependency(dspec.is_test_dependency) return r # return a module initialised to the path where we would have # installed this module, so that it's possible to use # getDependenciesRecursive to find a list of failed dependencies, # as well as just available ones # note that this Component object may still be valid (usable to # attempt a build), if a different version was previously installed # on disk at this location (which means we need to check if the # existing version is linked) default_path = os.path.join(self.modulesPath(), dspec.name) r = Component( default_path, test_dependency = dspec.is_test_dependency, installed_linked = fsutils.isLink(default_path), inherit_shrinkwrap = dep_of.getShrinkwrap() ) return r def getDependenciesRecursive(self, available_components = None, processed = None, search_dirs = None, target = None, available_only = False, test = False ): ''' Get available and already installed components, don't check for remotely available components. See also satisfyDependenciesRecursive() Returns {component_name:component} ''' components, errors = self.__getDependenciesRecursiveWithProvider( available_components = available_components, search_dirs = search_dirs, target = target, traverse_links = True, update_installed = False, provider = self.provideInstalled, test = test ) for error in errors: logger.error(error) if available_only: components = OrderedDict((k, v) for k, v in components.items() if v) return components def modulesPath(self): return os.path.join(self.path, Modules_Folder) def targetsPath(self): return os.path.join(self.path, Targets_Folder) def satisfyDependenciesRecursive( self, available_components = None, search_dirs = None, update_installed = False, traverse_links = False, target = None, test = False ): ''' Retrieve and install all the dependencies of this component and its dependencies, recursively, or satisfy them from a collection of available_components or from disk. Returns ======= (components, errors) components: dictionary of name:Component errors: sequence of errors Parameters ========== available_components: None (default) or a dictionary of name:component. This is searched before searching directories or fetching remote components search_dirs: None (default), or sequence of directories to search for already installed, (but not yet loaded) components. Used so that manually installed or linked components higher up the dependency tree are found by their users lower down. These directories are searched in order, and finally the current directory is checked. update_installed: False (default), True, or set(): whether to check the available versions of installed components, and update if a newer version is available. If this is a set(), only update things in the specified set. traverse_links: False (default) or True: whether to recurse into linked dependencies when updating/installing. target: None (default), or a Target object. If specified the target name and it's similarTo list will be used in resolving dependencies. If None, then only target-independent dependencies will be installed test: True, False, or 'toplevel: should test-only dependencies be installed? (yes, no, or only for this module, not its dependencies). ''' def provider( dspec, available_components, search_dirs, working_directory, update_installed, dep_of=None ): r = access.satisfyFromAvailable(dspec.name, available_components) if r: if r.isTestDependency() and not dspec.is_test_dependency: logger.debug('test dependency subsequently occurred as real dependency: %s', r.getName()) r.setTestDependency(False) return r update_if_installed = False if update_installed is True: update_if_installed = True elif update_installed: update_if_installed = dspec.name in update_installed r = access.satisfyVersionFromSearchPaths( dspec.name, dspec.versionReq(), search_dirs, update_if_installed, inherit_shrinkwrap = dep_of.getShrinkwrap() ) if r: r.setTestDependency(dspec.is_test_dependency) return r # before resorting to install this module, check if we have an # existing linked module (which wasn't picked up because it didn't # match the version specification) - if we do, then we shouldn't # try to install, but should return that anyway: default_path = os.path.join(self.modulesPath(), dspec.name) if fsutils.isLink(default_path): r = Component( default_path, test_dependency = dspec.is_test_dependency, installed_linked = fsutils.isLink(default_path), inherit_shrinkwrap = dep_of.getShrinkwrap() ) if r: assert(r.installedLinked()) return r else: logger.error('linked module %s is invalid: %s', dspec.name, r.getError()) return r r = access.satisfyVersionByInstalling( dspec.name, dspec.versionReq(), self.modulesPath(), inherit_shrinkwrap = dep_of.getShrinkwrap() ) if not r: logger.error('could not install %s' % dspec.name) if r is not None: r.setTestDependency(dspec.is_test_dependency) return r return self.__getDependenciesRecursiveWithProvider( available_components = available_components, search_dirs = search_dirs, target = target, traverse_links = traverse_links, update_installed = update_installed, provider = provider, test = test ) def satisfyTarget(self, target_name_and_version, update_installed=False, additional_config=None, install_missing=True): ''' Ensure that the specified target name (and optionally version, github ref or URL) is installed in the targets directory of the current component returns (derived_target, errors) ''' # Target, , represent an installed target, internal from yotta.lib import target application_dir = None if self.isApplication(): application_dir = self.path return target.getDerivedTarget( target_name_and_version, self.targetsPath(), install_missing = install_missing, application_dir = application_dir, update_installed = update_installed, additional_config = additional_config, shrinkwrap = self.getShrinkwrap() ) def getTarget(self, target_name_and_version, additional_config=None): ''' Return a derived target object representing the selected target: if the target is not installed, or is invalid then the returned object will test false in a boolean context. Returns derived_target Errors are not displayed. ''' derived_target, errors = self.satisfyTarget( target_name_and_version, additional_config = additional_config, install_missing = False ) if len(errors): return None else: return derived_target def installedDependencies(self): ''' Return true if satisfyDependencies has been called. Note that this is slightly different to when all of the dependencies are actually satisfied, but can be used as if it means that. ''' return self.installed_dependencies def isApplication(self): ''' Return true if this module is an application instead of a reusable library ''' return bool(len(self.getBinaries())) def getBinaries(self): ''' Return a dictionary of binaries to compile: {"dirname":"exename"}, this is used when automatically generating CMakeLists Note that currently modules may define only a single executable binary or library to be built by the automatic build system, by specifying `"bin": "dir-to-be-built-into-binary"`, or `"lib": "dir-to-be-built-into-library"`, and the bin/lib will always have the same name as the module. The default behaviour if nothing is specified is for the 'source' directory to be built into a library. The module.json syntax may allow for other combinations in the future (and callers of this function should not rely on it returning only a single item). For example, a "bin": {"dirname": "exename"} syntax might be supported, however currently more complex builds must be controlled by custom CMakeLists. ''' # the module.json syntax is a subset of the package.json syntax: a # single string that defines the source directory to use to build an # executable with the same name as the component. This may be extended # to include the rest of the npm syntax in future (map of source-dir to # exe name). if 'bin' in self.description: return {os.path.normpath(self.description['bin']): self.getName()} else: return {} def getLibs(self, explicit_only=False): ''' Return a dictionary of libraries to compile: {"dirname":"libname"}, this is used when automatically generating CMakeLists. If explicit_only is not set, then in the absence of both 'lib' and 'bin' sections in the module.json file, the "source" directory will be returned. Note that currently modules may define only a single executable binary or library to be built by the automatic build system, by specifying `"bin": "dir-to-be-built-into-binary"`, or `"lib": "dir-to-be-built-into-library"`, and the bin/lib will always have the same name as the module. The default behaviour if nothing is specified is for the 'source' directory to be built into a library. The module.json syntax may allow for other combinations in the future (and callers of this function should not rely on it returning only a single item). For example, a "bin": {"dirname": "exename"} syntax might be supported, however currently more complex builds must be controlled by custom CMakeLists. ''' if 'lib' in self.description: return {os.path.normpath(self.description['lib']): self.getName()} elif 'bin' not in self.description and not explicit_only: return {'source': self.getName()} else: return {} def licenses(self): ''' Return a list of licenses that apply to this module. (Strings, which may be SPDX identifiers) ''' if 'license' in self.description: return [self.description['license']] else: return [x['type'] for x in self.description['licenses']] def getExtraIncludes(self): ''' Some components must export whole directories full of headers into the search path. This is really really bad, and they shouldn't do it, but support is provided as a concession to compatibility. ''' if 'extraIncludes' in self.description: return [os.path.normpath(x) for x in self.description['extraIncludes']] else: return [] def getExtraSysIncludes(self): ''' Some components (e.g. libc) must export directories of header files into the system include search path. They do this by adding a 'extraSysIncludes' : [ array of directories ] field in their package description. This function returns the list of directories (or an empty list), if it doesn't exist. ''' if 'extraSysIncludes' in self.description: return [os.path.normpath(x) for x in self.description['extraSysIncludes']] else: return [] def getRegistryNamespace(self): return Registry_Namespace def setTestDependency(self, status): self.is_test_dependency = status def isTestDependency(self): return self.is_test_dependency def __saveSpecForComponent(self, component): version = component.getVersion() if version.isTip(): spec = '*' elif version.major() == 0: # for 0.x.x versions, when we save a dependency we don't use ^0.x.x # a that would peg to the exact version - instead we use ~ to peg # to the same minor version spec = '~' + str(version) else: spec = '^' + str(version) return spec def saveDependency(self, component, spec=None): if not 'dependencies' in self.description: self.description['dependencies'] = OrderedDict() if spec is None: spec = self.__saveSpecForComponent(component) self.description['dependencies'][component.getName()] = spec return spec def removeDependency(self, component): if not component in self.description.get('dependencies', {}): logger.error('%s is not listed as a dependency', component) return False del self.description['dependencies'][component] return True def getDefines(self): return self.defines
qubiter/adv_applications/MeanHamil_rigetti.py
artiste-qb-net/qubiter
129
147607
import copy as cp from qubiter.adv_applications.MeanHamil import * from qubiter.device_specific.Qubiter_to_RigettiPyQuil import * from qubiter.device_specific.RigettiTools import * import qubiter.utilities_gen as utg from openfermion.ops import QubitOperator from pyquil.quil import Program, Pragma from pyquil.gates import * from pyquil.api import WavefunctionSimulator class MeanHamil_rigetti(MeanHamil): """ This class is a child of MeanHamil. This class uses either Rigetti's real hardware or virtual simulator to calculate mean values. `qc` returned by Rigetti's get_qc() method is passed in as an input to the constructor of this class. If num_samples !=0, the class uses qc.run() to calculate mean values. If num_samples=0, the class ignores the `qc` input and uses PyQuil's WavefunctionSimulator to calculate mean values exactly. Attributes ---------- do_resets : bool pg : Program object of PyQuil class `Program` qc : QuantumComputer returned by PyQuil method get_qc() term_to_exec : dict[] maps a term to an executable. QubitOperator from OpenFermion has attribute `terms` which is a dict from a term to a coefficient. An executable is the output of PyQuil's compile() method. translation_line_list : list[str] a list of lines of PyQuil code generated by the translator. The lines all start with "pg +=" translator : Qubiter_to_RigettiPyQuil """ def __init__(self, qc, file_prefix, num_qbits, hamil, all_var_nums, fun_name_to_fun, do_resets=True, **kwargs): """ Constructor Do in constructor as much hamil indep stuff as possible so don't have to redo it with every call to cost fun. Also, when self.num_samples !=0, we store a dict called term_to_exec mapping an executable (output of Rigetti compile() function) to a term, for each term in the hamiltonian hamil. When num_samples=0, term_to_exec={} Parameters ---------- qc : QuantumComputer file_prefix : str num_qbits : int hamil : QubitOperator all_var_nums : list[int] fun_name_to_fun : dict[str, function] do_resets : bool kwargs : dict key-words args of MeanHamilMinimizer constructor Returns ------- """ MeanHamil.__init__(self, file_prefix, num_qbits, hamil, all_var_nums, fun_name_to_fun, **kwargs) self.qc = qc self.do_resets = do_resets # this creates a file with all PyQuil gates that # are independent of hamil. Gates may contain free parameters self.translator = Qubiter_to_RigettiPyQuil( self.file_prefix, self.num_qbits, aqasm_name='RigPyQuil', prelude_str='', ending_str='') with open(utg.preface(self.translator.aqasm_path), 'r') as fi: self.translation_line_list = fi.readlines() pg = Program() self.pg = pg if self.num_samples: # pg prelude pg += Pragma('INITIAL_REWIRING', ['"PARTIAL"']) if self.do_resets: pg += RESET() ro = pg.declare('ro', 'BIT', self.num_qbits) s = '' for var_num in self.all_var_nums: vname = self.translator.vprefix + str(var_num) s += vname s += ' = pg.declare("' s += vname s += '", memory_type="REAL")\n' exec(s) # add to pg the operations that are independent of hamil for line in self.translation_line_list: line = line.strip('\n') if line: exec(line) len_pg_in = len(pg) # hamil loop to store executables for each term in hamil self.term_to_exec = {} for term, coef in self.hamil.terms.items(): # reset pg to initial length. # Temporary work-around to bug # in PyQuil ver 2.5.0. # Slicing was changing # pg from type Program to type list pg = Program(pg[:len_pg_in]) self.pg = pg # add xy measurements coda to pg bit_pos_to_xy_str =\ {bit: action for bit, action in term if action != 'Z'} RigettiTools.add_xy_meas_coda_to_program( pg, bit_pos_to_xy_str) # request measurements for i in range(self.num_qbits): pg += MEASURE(i, ro[i]) pg.wrap_in_numshots_loop(shots=self.num_samples) executable = self.qc.compile(pg) # print(",,,...", executable) self.term_to_exec[term] = executable def get_mean_val(self, var_num_to_rads): """ This method returns the empirically determined Hamiltonian mean value. It takes as input the values of placeholder variables. It passes those values into the Rigetti method run() when num_samples !=0. When num_samples=0, WavefunctionSimulator is used to calculate the output mean value exactly. Parameters ---------- var_num_to_rads : dict[int, float] Returns ------- float """ # hamil loop mean_val = 0 for term, coef in self.hamil.terms.items(): # we have checked before that coef is real coef = complex(coef).real vprefix = self.translator.vprefix var_name_to_rads = {vprefix + str(vnum): [rads] for vnum, rads in var_num_to_rads.items()} if self.num_samples: # send and receive from cloud, get obs_vec bitstrings = self.qc.run(self.term_to_exec[term], memory_map=var_name_to_rads) obs_vec = RigettiTools.obs_vec_from_bitstrings( bitstrings, self.num_qbits, bs_is_array=True) # go from obs_vec to effective state vec counts_dict = StateVec.get_counts_from_obs_vec(self.num_qbits, obs_vec) emp_pd = StateVec.get_empirical_pd_from_counts(self.num_qbits, counts_dict) effective_st_vec = StateVec.get_emp_state_vec_from_emp_pd( self.num_qbits, emp_pd) else: # num_samples = 0 sim = WavefunctionSimulator() pg = Program() # don't know how to declare number of qubits # so do this for k in range(self.num_qbits): pg += I(k) for key, val in var_name_to_rads.items(): exec(key + '=' + str(val[0])) for line in self.translation_line_list: line = line.strip('\n') if line: exec(line) bit_pos_to_xy_str =\ {bit: action for bit, action in term if action != 'Z'} RigettiTools.add_xy_meas_coda_to_program( pg, bit_pos_to_xy_str) st_vec_arr = sim.wavefunction(pg).amplitudes st_vec_arr = st_vec_arr.reshape([2]*self.num_qbits) perm = list(reversed(range(self.num_qbits))) st_vec_arr = np.transpose(st_vec_arr, perm) effective_st_vec = StateVec(self.num_qbits, st_vec_arr) # add contribution to mean real_arr = self.get_real_vec(term) mean_val += coef*effective_st_vec.\ get_mean_value_of_real_diag_mat(real_arr) return mean_val if __name__ == "__main__": def main(): pass
torchbenchmark/score/generate_score_config.py
xuzhao9/benchmark
384
147632
""" Generate a fully specified benchmark configuration file, given a lightweight specification and a complete source of benchmark data. Specification File ------------------ Score hierarchy input intended to be as easy to construct as possible, relying on automatic inference of unspecified weights, benchmark configs, and normalization factors given a particular instance of benchmark data. Structure: Root _ - category | required: - domain | 3 layers of organizational structure - task _| - benchmark name - keyword match for root name in benchmark, omit children unless used _ - train/eval | optional: - device | provide specific weights or - compiler/runtime _| exclude particular configs by omission Rules for describing the weight hierarchy - everything is a dict, since at any level you could specify a weight - if a weight is not specified, it is computed automatically with respect its direct siblings. - if specific benchmark configurations are omitted under a benchmark name, all configurations present in the normalization data json are weighted equally Normalization Data ------------------ Used to 'fill in the gaps' in the human written specification. - particular configurations (train/eval, device, compiler/runtime) present in this data are used to compute benchmark weights - measurements from this data are used as normalization factors in score computation such that new data is scored relative to this data. #### TODO #### - handle multiple normalization files, one for models, one for synthetic, etc - make explicit configuration choice for throughput vs runtime metrics - assert same machine used for all normalization files and freeze that in """ import argparse import json import yaml from collections import defaultdict def generate_bench_cfg(spec, norm, target): cfg = { 'target': target, 'benchmarks': {}, } benchmark_names = [b['name'] for b in norm['benchmarks']] benchmark_norms = {b['name']: b['stats']['mean'] for b in norm['benchmarks']} assert len(spec['hierarchy']) > 0, "Must specify at least one category" category_weight = 1.0 / len(spec['hierarchy']) for category in spec['hierarchy']: category_spec = spec['hierarchy'][category] assert isinstance(category_spec, dict), f"Category {category} in spec must be non-empty" assert 'weight' not in category_spec, "TODO implement manual category weights" domain_weight = 1.0 / len(category_spec) for domain in category_spec: tasks = category_spec[domain] assert isinstance(tasks, dict), f"Domain {category}:{domain} in spec must be non-empty" assert 'weight' not in tasks, "TODO implement manual domain weights" task_weight = 1.0 / len(tasks) for task in tasks: benchmarks = tasks[task] assert isinstance(benchmarks, dict), f"Task {category}:{domain}:{task} in spec must be non-empty" assert 'weight' not in benchmarks, "TODO implement manual task weights" benchmark_weight = 1.0 / len(benchmarks) for benchmark in benchmarks: assert benchmarks[benchmark] is None, "TODO handle benchmark as dict of config specs" # assert 'weight' not in benchmarks[benchmark], "TODO implement manual benchmark weights" found_benchmarks = [name for name in benchmark_names if benchmark in name] assert len(found_benchmarks) > 0, f"No normalization data found for {benchmark}" config_weight = 1.0 / len(found_benchmarks) for b in found_benchmarks: weight = domain_weight * task_weight * benchmark_weight * config_weight cfg['benchmarks'][b] = { 'weight': weight, 'norm': benchmark_norms[b], } return cfg # Support generate a config from benchmark data that runs partial of the spec def generate_bench_cfg_partial(spec, norm, target): benchmark_names = [b['name'] for b in norm['benchmarks']] rec_defaultdict = lambda: defaultdict(rec_defaultdict) partial_spec = rec_defaultdict() def gen_partial_spec(category, domain, task, benchmark): found_benchmarks = [name for name in benchmark_names if benchmark in name] if len(found_benchmarks) > 0: partial_spec['hierarchy'][category][domain][task][benchmark] = None def visit_each_benchmark(spec, func): for category in spec['hierarchy']: category_spec = spec['hierarchy'][category] for domain in category_spec: tasks = category_spec[domain] for task in tasks: benchmarks = tasks[task] for benchmark in benchmarks: func(category, domain, task, benchmark) visit_each_benchmark(spec, gen_partial_spec) return generate_bench_cfg(partial_spec, norm, target) def check(spec): assert len(spec['hierarchy']) > 0, "Must specify at least one category" for category in spec['hierarchy']: category_spec = spec['hierarchy'][category] assert isinstance(category_spec, dict), f"Category {category} in spec must be non-empty" assert 'weight' not in category_spec, "TODO implement manual category weights" for domain in category_spec: tasks = category_spec[domain] assert isinstance(tasks, dict), f"Domain {category}:{domain} in spec must be non-empty" assert 'weight' not in tasks, "TODO implement manual domain weights" for task in tasks: benchmarks = tasks[task] assert isinstance(benchmarks, dict), f"Task {category}:{domain}:{task} in spec must be non-empty" assert 'weight' not in benchmarks, "TODO implement manual task weights" for benchmark in benchmarks: assert benchmarks[benchmark] is None, "TODO handle benchmark as dict of config specs" # assert 'weight' not in benchmarks[benchmark], "TODO implement manual benchmark weights" if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--specification", required=True, help="yaml file describing weight hierarchy") parser.add_argument("--normalization_data", required=True, help="pytest-benchmark json file used for generating normalization " "values and filling in unspecified benchmark configurations") parser.add_argument("--output_file", required=True, help="generated complete benchmark configuration") parser.add_argument("--target_score", default=1000, help="target score value given these normalizations and specifications") parser.add_argument("--partial", action='store_true', help="generates partial config if the benchmark only runs part of the spec." "normally, the spec is supposed to define the set of benchmarks that's expected to exist," "and then the provided json data is expected to provide the norm values to match the spec." "To simplify debugging, and not for normal score runs, we allow a convenience for producing" "a score configuration that matches whatever json data is provided.") args = parser.parse_args() with open(args.specification) as spec_file: spec = yaml.full_load(spec_file) with open(args.normalization_data) as norm_file: norm = json.load(norm_file) with open(args.output_file, 'w') as out_file: check(spec) if args.partial: bench_cfg = generate_bench_cfg_partial(spec, norm, args.target_score) else: bench_cfg = generate_bench_cfg(spec, norm, args.target_score) yaml.dump(bench_cfg, out_file)
fastNLP/modules/encoder/bert.py
ouyhlan/fastNLP
2,693
147636
r"""undocumented 这个页面的代码很大程度上参考(复制粘贴)了https://github.com/huggingface/pytorch-pretrained-BERT的代码, 如果你发现该代码对你 有用,也请引用一下他们。 """ __all__ = [ "BertModel", ] import copy import json import math import os import torch from torch import nn import numpy as np from ...io.file_utils import _get_file_name_base_on_postfix from ...io.file_utils import _get_bert_dir from ...core import logger CONFIG_FILE = 'config.json' WEIGHTS_NAME = 'pytorch_model.bin' BERT_KEY_RENAME_MAP_1 = { 'gamma': 'weight', 'beta': 'bias', 'distilbert.embeddings': 'bert.embeddings', 'distilbert.transformer': 'bert.encoder', } BERT_KEY_RENAME_MAP_2 = { 'q_lin': 'self.query', 'k_lin': 'self.key', 'v_lin': 'self.value', 'out_lin': 'output.dense', 'sa_layer_norm': 'attention.output.LayerNorm', 'ffn.lin1': 'intermediate.dense', 'ffn.lin2': 'output.dense', 'output_layer_norm': 'output.LayerNorm', } class BertConfig(object): r"""Configuration class to store the configuration of a `BertModel`. """ def __init__(self, vocab_size_or_config_json_file, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=2, initializer_range=0.02, layer_norm_eps=1e-12, architectures='bert'): r"""Constructs BertConfig. Args: vocab_size_or_config_json_file: Vocabulary size of `inputs_ids` in `BertModel`. hidden_size: Size of the encoder layers and the pooler layer. num_hidden_layers: Number of hidden layers in the Transformer encoder. num_attention_heads: Number of attention heads for each attention layer in the Transformer encoder. intermediate_size: The size of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. hidden_act: The non-linear activation function (function or string) in the encoder and pooler. If string, "gelu", "relu" and "swish" are supported. hidden_dropout_prob: The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler. attention_probs_dropout_prob: The dropout ratio for the attention probabilities. max_position_embeddings: The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). type_vocab_size: The vocabulary size of the `token_type_ids` passed into `BertModel`. initializer_range: The sttdev of the truncated_normal_initializer for initializing all weight matrices. layer_norm_eps: The epsilon used by LayerNorm. """ if isinstance(vocab_size_or_config_json_file, str): with open(vocab_size_or_config_json_file, "r", encoding='utf-8') as reader: json_config = json.loads(reader.read()) for key, value in json_config.items(): self.__dict__[key] = value elif isinstance(vocab_size_or_config_json_file, int): self.vocab_size = vocab_size_or_config_json_file self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.hidden_act = hidden_act self.intermediate_size = intermediate_size self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.type_vocab_size = type_vocab_size self.initializer_range = initializer_range self.layer_norm_eps = layer_norm_eps self.architectures = architectures else: raise ValueError("First argument must be either a vocabulary size (int)" "or the path to a pretrained model config file (str)") @classmethod def from_dict(cls, json_object): r"""Constructs a `BertConfig` from a Python dictionary of parameters.""" config = BertConfig(vocab_size_or_config_json_file=-1) for key, value in json_object.items(): config.__dict__[key] = value return config @classmethod def from_json_file(cls, json_file): r"""Constructs a `BertConfig` from a json file of parameters.""" with open(json_file, "r", encoding='utf-8') as reader: text = reader.read() return cls.from_dict(json.loads(text)) def __repr__(self): return str(self.to_json_string()) def to_dict(self): r"""Serializes this instance to a Python dictionary.""" output = copy.deepcopy(self.__dict__) return output def to_json_string(self): r"""Serializes this instance to a JSON string.""" return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n" def to_json_file(self, json_file_path): r""" Save this instance to a json file.""" if os.path.isdir(json_file_path): json_file_path = os.path.join(json_file_path, CONFIG_FILE) with open(json_file_path, "w", encoding='utf-8') as writer: writer.write(self.to_json_string()) def save_pretrained(self, save_directory): self.to_json_file(save_directory) def gelu(x): return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0))) def swish(x): return x * torch.sigmoid(x) ACT2FN = {"gelu": gelu, "relu": torch.nn.functional.relu, "swish": swish} BertLayerNorm = torch.nn.LayerNorm class DistilBertEmbeddings(nn.Module): def __init__(self, config): super(DistilBertEmbeddings, self).__init__() def create_sinusoidal_embeddings(n_pos, dim, out): position_enc = np.array([ [pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)] for pos in range(n_pos) ]) out[:, 0::2] = torch.FloatTensor(np.sin(position_enc[:, 0::2])) out[:, 1::2] = torch.FloatTensor(np.cos(position_enc[:, 1::2])) out.detach_() out.requires_grad = False self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=0) self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size) if config.sinusoidal_pos_embds: create_sinusoidal_embeddings(n_pos=config.max_position_embeddings, dim=config.hidden_size, out=self.position_embeddings.weight) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=1e-12) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, input_ids, token_type_ids, position_ids=None): r""" Parameters ---------- input_ids: torch.tensor(bs, max_seq_length) The token ids to embed. token_type_ids: no used. position_ids: no used. Outputs ------- embeddings: torch.tensor(bs, max_seq_length, dim) The embedded tokens (plus position embeddings, no token_type embeddings) """ seq_length = input_ids.size(1) if position_ids is None: position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device) # (max_seq_length) position_ids = position_ids.unsqueeze(0).expand_as(input_ids) # (bs, max_seq_length) word_embeddings = self.word_embeddings(input_ids) # (bs, max_seq_length, dim) position_embeddings = self.position_embeddings(position_ids) # (bs, max_seq_length, dim) embeddings = word_embeddings + position_embeddings # (bs, max_seq_length, dim) embeddings = self.LayerNorm(embeddings) # (bs, max_seq_length, dim) embeddings = self.dropout(embeddings) # (bs, max_seq_length, dim) return embeddings class BertEmbeddings(nn.Module): r"""Construct the embeddings from word, position and token_type embeddings. """ def __init__(self, config): super(BertEmbeddings, self).__init__() self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=0) self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size) self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size) # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load # any TensorFlow checkpoint file self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, input_ids, token_type_ids=None, position_ids=None, words_embeddings=None): seq_length = input_ids.size(1) if position_ids is None: position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device) position_ids = position_ids.unsqueeze(0).expand_as(input_ids) if token_type_ids is None: token_type_ids = torch.zeros_like(input_ids) if words_embeddings is None: words_embeddings = self.word_embeddings(input_ids) else: assert input_ids.size() == words_embeddings.size()[: -1] position_embeddings = self.position_embeddings(position_ids) token_type_embeddings = self.token_type_embeddings(token_type_ids) embeddings = words_embeddings + position_embeddings + token_type_embeddings embeddings = self.LayerNorm(embeddings) embeddings = self.dropout(embeddings) return embeddings class BertSelfAttention(nn.Module): def __init__(self, config): super(BertSelfAttention, self).__init__() if config.hidden_size % config.num_attention_heads != 0: raise ValueError( "The hidden size (%d) is not a multiple of the number of attention " "heads (%d)" % (config.hidden_size, config.num_attention_heads)) self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config.num_attention_heads) self.all_head_size = self.num_attention_heads * self.attention_head_size self.query = nn.Linear(config.hidden_size, self.all_head_size) self.key = nn.Linear(config.hidden_size, self.all_head_size) self.value = nn.Linear(config.hidden_size, self.all_head_size) self.dropout = nn.Dropout(config.attention_probs_dropout_prob) def transpose_for_scores(self, x): new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) x = x.view(*new_x_shape) return x.permute(0, 2, 1, 3) def forward(self, hidden_states, attention_mask): mixed_query_layer = self.query(hidden_states) mixed_key_layer = self.key(hidden_states) mixed_value_layer = self.value(hidden_states) query_layer = self.transpose_for_scores(mixed_query_layer) key_layer = self.transpose_for_scores(mixed_key_layer) value_layer = self.transpose_for_scores(mixed_value_layer) # Take the dot product between "query" and "key" to get the raw attention scores. attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) attention_scores = attention_scores / math.sqrt(self.attention_head_size) # Apply the attention mask is (precomputed for all layers in BertModel forward() function) attention_scores = attention_scores + attention_mask # Normalize the attention scores to probabilities. attention_probs = nn.Softmax(dim=-1)(attention_scores) # This is actually dropping out entire tokens to attend to, which might # seem a bit unusual, but is taken from the original Transformer paper. attention_probs = self.dropout(attention_probs) context_layer = torch.matmul(attention_probs, value_layer) context_layer = context_layer.permute(0, 2, 1, 3).contiguous() new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) context_layer = context_layer.view(*new_context_layer_shape) return context_layer class BertSelfOutput(nn.Module): def __init__(self, config): super(BertSelfOutput, self).__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states class BertAttention(nn.Module): def __init__(self, config): super(BertAttention, self).__init__() self.self = BertSelfAttention(config) self.output = BertSelfOutput(config) def forward(self, input_tensor, attention_mask): self_output = self.self(input_tensor, attention_mask) attention_output = self.output(self_output, input_tensor) return attention_output class BertIntermediate(nn.Module): def __init__(self, config): super(BertIntermediate, self).__init__() self.dense = nn.Linear(config.hidden_size, config.intermediate_size) if isinstance(config.hidden_act, str): self.intermediate_act_fn = ACT2FN[config.hidden_act] else: self.intermediate_act_fn = config.hidden_act def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.intermediate_act_fn(hidden_states) return hidden_states class BertOutput(nn.Module): def __init__(self, config): super(BertOutput, self).__init__() self.dense = nn.Linear(config.intermediate_size, config.hidden_size) self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states class BertLayer(nn.Module): def __init__(self, config): super(BertLayer, self).__init__() self.attention = BertAttention(config) self.intermediate = BertIntermediate(config) self.output = BertOutput(config) def forward(self, hidden_states, attention_mask): attention_output = self.attention(hidden_states, attention_mask) intermediate_output = self.intermediate(attention_output) layer_output = self.output(intermediate_output, attention_output) return layer_output class BertEncoder(nn.Module): def __init__(self, config, num_output_layer=-1): super(BertEncoder, self).__init__() layer = BertLayer(config) self.layer = nn.ModuleList([copy.deepcopy(layer) for _ in range(config.num_hidden_layers)]) num_output_layer = num_output_layer if num_output_layer >= 0 else (len(self.layer) + num_output_layer) self.num_output_layer = max(min(num_output_layer, len(self.layer)), 0) if self.num_output_layer + 1 < len(self.layer): logger.info(f'The transformer encoder will early exit after layer-{self.num_output_layer} ' f'(layer 0 means embedding layer)!') def forward(self, hidden_states, attention_mask, output_all_encoded_layers=True): all_encoder_layers = [] for idx, layer_module in enumerate(self.layer): if idx >= self.num_output_layer: break hidden_states = layer_module(hidden_states, attention_mask) if output_all_encoded_layers: all_encoder_layers.append(hidden_states) if not output_all_encoded_layers: all_encoder_layers.append(hidden_states) return all_encoder_layers class BertPooler(nn.Module): def __init__(self, config): super(BertPooler, self).__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.activation = nn.Tanh() def forward(self, hidden_states): # We "pool" the model by simply taking the hidden state corresponding # to the first token. first_token_tensor = hidden_states[:, 0] pooled_output = self.dense(first_token_tensor) pooled_output = self.activation(pooled_output) return pooled_output class BertModel(nn.Module): r""" BERT(Bidirectional Embedding Representations from Transformers). 用预训练权重矩阵来建立BERT模型:: model = BertModel.from_pretrained(model_dir_or_name) 用随机初始化权重矩阵来建立BERT模型:: model = BertModel() :param int vocab_size: 词表大小,默认值为30522,为BERT English uncase版本的词表大小 :param int hidden_size: 隐层大小,默认值为768,为BERT base的版本 :param int num_hidden_layers: 隐藏层数,默认值为12,为BERT base的版本 :param int num_attention_heads: 多头注意力头数,默认值为12,为BERT base的版本 :param int intermediate_size: FFN隐藏层大小,默认值是3072,为BERT base的版本 :param str hidden_act: FFN隐藏层激活函数,默认值为``gelu`` :param float hidden_dropout_prob: FFN隐藏层dropout,默认值为0.1 :param float attention_probs_dropout_prob: Attention层的dropout,默认值为0.1 :param int max_position_embeddings: 最大的序列长度,默认值为512, :param int type_vocab_size: 最大segment数量,默认值为2 :param int initializer_range: 初始化权重范围,默认值为0.02 """ def __init__(self, config, *inputs, **kwargs): super(BertModel, self).__init__() if not isinstance(config, BertConfig): raise ValueError( "Parameter config in `{}(config)` should be an instance of class `BertConfig`. " "To create a model from a Google pretrained model use " "`model = {}.from_pretrained(PRETRAINED_MODEL_NAME)`".format( self.__class__.__name__, self.__class__.__name__ )) super(BertModel, self).__init__() self.config = config self.hidden_size = self.config.hidden_size self.model_type = 'bert' neg_num_output_layer = kwargs.get('neg_num_output_layer', -1) pos_num_output_layer = kwargs.get('pos_num_output_layer', self.config.num_hidden_layers) self.num_output_layer = max(neg_num_output_layer + 1 + self.config.num_hidden_layers, pos_num_output_layer) if hasattr(config, 'sinusoidal_pos_embds'): self.model_type = 'distilbert' elif 'model_type' in kwargs: self.model_type = kwargs['model_type'].lower() if self.model_type == 'distilbert': self.embeddings = DistilBertEmbeddings(config) else: self.embeddings = BertEmbeddings(config) self.encoder = BertEncoder(config, num_output_layer=self.num_output_layer) if self.model_type != 'distilbert': self.pooler = BertPooler(config) else: logger.info('DistilBert has NOT pooler, will use hidden states of [CLS] token as pooled output.') self.apply(self.init_bert_weights) @property def dtype(self): """ :obj:`torch.dtype`: The dtype of the module (assuming that all the module parameters have the same dtype). """ try: return next(self.parameters()).dtype except StopIteration: # For nn.DataParallel compatibility in PyTorch 1.5 def find_tensor_attributes(module: nn.Module): tuples = [(k, v) for k, v in module.__dict__.items() if torch.is_tensor(v)] return tuples gen = self._named_members(get_members_fn=find_tensor_attributes) first_tuple = next(gen) return first_tuple[1].dtype def init_bert_weights(self, module): r""" Initialize the weights. """ if isinstance(module, (nn.Linear, nn.Embedding)): # Slightly different from the TF version which uses truncated_normal for initialization # cf https://github.com/pytorch/pytorch/pull/5617 module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) elif isinstance(module, BertLayerNorm): module.bias.data.zero_() module.weight.data.fill_(1.0) if isinstance(module, nn.Linear) and module.bias is not None: module.bias.data.zero_() def forward(self, input_ids, token_type_ids=None, attention_mask=None, output_all_encoded_layers=True, position_ids=None): """ :param torch.LongTensor input_ids: bsz x max_len的输入id :param torch.LongTensor token_type_ids: bsz x max_len,如果不输入认为全为0,一般第一个sep(含)及以前为0, 一个sep之后为1 :param attention_mask: 需要attend的为1,不需要为0 :param bool output_all_encoded_layers: 是否输出所有层,默认输出token embedding(包含bpe, position以及type embedding) 及每一层的hidden states。如果为False,只输出最后一层的结果 :param torch.LongTensor position_ids: bsz x max_len, position的id :return: encode_layers: 如果output_all_encoded_layers为True,返回list(共num_layers+1个元素),每个元素为 bsz x max_len x hidden_size否则返回bsz x max_len x hidden_size的tensor; pooled_output: bsz x hidden_size为cls的表示,可以用于句子的分类 """ if attention_mask is None: attention_mask = torch.ones_like(input_ids) if token_type_ids is None: token_type_ids = torch.zeros_like(input_ids) # We create a 3D attention mask from a 2D tensor mask. # Sizes are [batch_size, 1, 1, to_seq_length] # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length] # this attention mask is more simple than the triangular masking of causal attention # used in OpenAI GPT, we just need to prepare the broadcast dimension here. extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2) # Since attention_mask is 1.0 for positions we want to attend and 0.0 for # masked positions, this operation will create a tensor which is 0.0 for # positions we want to attend and -10000.0 for masked positions. # Since we are adding it to the raw scores before the softmax, this is # effectively the same as removing these entirely. # this will case an issue when DataParallel: https://github.com/pytorch/pytorch/issues/40457#issuecomment-648396469 # extended_attention_mask = extended_attention_mask.to(dtype=next(self.parameters()).dtype) # fp16 compatibility extended_attention_mask = extended_attention_mask.to(self.dtype) extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0 embedding_output = self.embeddings(input_ids, token_type_ids=token_type_ids, position_ids=position_ids) encoded_layers = self.encoder(embedding_output, extended_attention_mask, output_all_encoded_layers=output_all_encoded_layers) encoded_layers.insert(0, embedding_output) sequence_output = encoded_layers[-1] if self.model_type != 'distilbert': pooled_output = self.pooler(sequence_output) else: pooled_output = sequence_output[:, 0] if not output_all_encoded_layers: encoded_layers = encoded_layers[-1] return encoded_layers, pooled_output @classmethod def from_pretrained(cls, model_dir_or_name, *inputs, **kwargs): state_dict = kwargs.get('state_dict', None) kwargs.pop('state_dict', None) kwargs.pop('cache_dir', None) kwargs.pop('from_tf', None) # get model dir from name or dir pretrained_model_dir = _get_bert_dir(model_dir_or_name) # Load config config_file = _get_file_name_base_on_postfix(pretrained_model_dir, '.json') config = BertConfig.from_json_file(config_file) if state_dict is None: weights_path = _get_file_name_base_on_postfix(pretrained_model_dir, '.bin') state_dict = torch.load(weights_path, map_location='cpu') else: logger.error(f'Cannot load parameters through `state_dict` variable.') raise RuntimeError(f'Cannot load parameters through `state_dict` variable.') model_type = 'BERT' old_keys = [] new_keys = [] for key in state_dict.keys(): new_key = None if 'bert' not in key: new_key = 'bert.' + key if new_key: old_keys.append(key) new_keys.append(new_key) for old_key, new_key in zip(old_keys, new_keys): state_dict[new_key] = state_dict.pop(old_key) old_keys = [] new_keys = [] for key in state_dict.keys(): new_key = None for key_name in BERT_KEY_RENAME_MAP_1: if key_name in key: new_key = key.replace(key_name, BERT_KEY_RENAME_MAP_1[key_name]) if 'distilbert' in key: model_type = 'DistilBert' break if new_key: old_keys.append(key) new_keys.append(new_key) for old_key, new_key in zip(old_keys, new_keys): state_dict[new_key] = state_dict.pop(old_key) old_keys = [] new_keys = [] for key in state_dict.keys(): new_key = None for key_name in BERT_KEY_RENAME_MAP_2: if key_name in key: new_key = key.replace(key_name, BERT_KEY_RENAME_MAP_2[key_name]) break if new_key: old_keys.append(key) new_keys.append(new_key) for old_key, new_key in zip(old_keys, new_keys): state_dict[new_key] = state_dict.pop(old_key) # Instantiate model. model = cls(config, model_type=model_type, *inputs, **kwargs) missing_keys = [] unexpected_keys = [] error_msgs = [] # copy state_dict so _load_from_state_dict can modify it metadata = getattr(state_dict, '_metadata', None) state_dict = state_dict.copy() if metadata is not None: state_dict._metadata = metadata def load(module, prefix=''): local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {}) module._load_from_state_dict( state_dict, prefix, local_metadata, True, missing_keys, unexpected_keys, error_msgs) for name, child in module._modules.items(): if child is not None: load(child, prefix + name + '.') load(model, prefix='' if hasattr(model, 'bert') else 'bert.') if len(missing_keys) > 0: logger.warning("Weights of {} not initialized from pretrained model: {}".format( model.__class__.__name__, missing_keys)) if len(unexpected_keys) > 0: logger.debug("Weights from pretrained model not used in {}: {}".format( model.__class__.__name__, unexpected_keys)) logger.info(f"Load pre-trained {model_type} parameters from file {weights_path}.") return model def save_pretrained(self, save_directory): """ 保存模型到某个folder """ assert os.path.isdir( save_directory ), "Saving path should be a directory where the model and configuration can be saved" # Only save the model itself if we are using distributed training model_to_save = self.module if hasattr(self, "module") else self # Attach architecture to the config model_to_save.config.architectures = [model_to_save.__class__.__name__] # Save configuration file model_to_save.config.save_pretrained(save_directory) # If we save using the predefined names, we can load using `from_pretrained` output_model_file = os.path.join(save_directory, WEIGHTS_NAME) torch.save(model_to_save.state_dict(), output_model_file) logger.debug("Model weights saved in {}".format(output_model_file))
mlcomp/contrib/criterion/triplet.py
megachester/mlcomp
166
147639
<filename>mlcomp/contrib/criterion/triplet.py<gh_stars>100-1000 import torch import torch.nn.functional as F from catalyst.contrib.nn.criterion.functional import cosine_distance, \ batch_all, _EPS def triplet_loss( embeddings: torch.Tensor, labels: torch.Tensor, margin: float = 0.3, reduction='mean' ) -> torch.Tensor: cosine_dists = cosine_distance(embeddings) mask = batch_all(labels) anchor_positive_dist = cosine_dists.unsqueeze(2) anchor_negative_dist = cosine_dists.unsqueeze(1) triplet_loss_value = \ F.relu(anchor_positive_dist - anchor_negative_dist + margin) triplet_loss_value = torch.mul(triplet_loss_value, mask) if reduction == 'mean': num_positive_triplets = torch.gt( triplet_loss_value, _EPS).sum().float() triplet_loss_value = ( triplet_loss_value.sum() / (num_positive_triplets + _EPS) ) elif reduction == 'none': triplet_loss_value = torch.sum(triplet_loss_value, dim=[1, 2]) else: raise Exception(f'Unknown reduction scheme {reduction}') return triplet_loss_value
snakeeyes/blueprints/page/__init__.py
cprey/boundtofail
881
147646
from snakeeyes.blueprints.page.views import page
djangox/lib/python3.8/site-packages/allauth/socialaccount/providers/facebook/locale.py
DemarcusL/django_wiki_lab
6,342
147650
# Default locale mapping for the Facebook JS SDK # The list of supported locales is at # https://www.facebook.com/translations/FacebookLocales.xml import os from django.utils.translation import get_language, to_locale def _build_locale_table(filename_or_file): """ Parses the FacebookLocales.xml file and builds a dict relating every available language ('en, 'es, 'zh', ...) with a list of available regions for that language ('en' -> 'US', 'EN') and an (arbitrary) default region. """ # Require the XML parser module only if we want the default mapping from xml.dom.minidom import parse dom = parse(filename_or_file) reps = dom.getElementsByTagName("representation") locs = map(lambda r: r.childNodes[0].data, reps) locale_map = {} for loc in locs: lang, _, reg = loc.partition("_") lang_map = locale_map.setdefault(lang, {"regs": [], "default": reg}) lang_map["regs"].append(reg) # Default region overrides (arbitrary) locale_map["en"]["default"] = "US" # Special case: Use es_ES for Spain and es_LA for everything else locale_map["es"]["default"] = "LA" locale_map["zh"]["default"] = "CN" locale_map["fr"]["default"] = "FR" locale_map["pt"]["default"] = "PT" return locale_map def get_default_locale_callable(): """ Wrapper function so that the default mapping is only built when needed """ exec_dir = os.path.dirname(os.path.realpath(__file__)) xml_path = os.path.join(exec_dir, "data", "FacebookLocales.xml") fb_locales = _build_locale_table(xml_path) def default_locale(request): """ Guess an appropriate FB locale based on the active Django locale. If the active locale is available, it is returned. Otherwise, it tries to return another locale with the same language. If there isn't one avaible, 'en_US' is returned. """ chosen = "en_US" language = get_language() if language: locale = to_locale(language) lang, _, reg = locale.partition("_") lang_map = fb_locales.get(lang) if lang_map is not None: if reg in lang_map["regs"]: chosen = lang + "_" + reg else: chosen = lang + "_" + lang_map["default"] return chosen return default_locale
tests/python/ViewTransformTest.py
mjtitchener-fn/OpenColorIO
628
147713
<reponame>mjtitchener-fn/OpenColorIO # SPDX-License-Identifier: BSD-3-Clause # Copyright Contributors to the OpenColorIO Project. import unittest, os, sys import PyOpenColorIO as OCIO class ViewTransformTest(unittest.TestCase): def test_default_contructor(self): """ Test the constructor. """ for ref_type in OCIO.ReferenceSpaceType.__members__.values(): vt = OCIO.ViewTransform(ref_type) self.assertEqual(vt.getReferenceSpaceType(), ref_type) self.assertEqual(vt.getName(), '') self.assertEqual(vt.getFamily(), '') self.assertEqual(vt.getDescription(), '') self.assertEqual(len(vt.getCategories()), 0) for dir in OCIO.ViewTransformDirection.__members__.values(): self.assertEqual(vt.getTransform(dir), None) vt = OCIO.ViewTransform() self.assertEqual(vt.getReferenceSpaceType(), OCIO.REFERENCE_SPACE_SCENE) vt = OCIO.ViewTransform(referenceSpace=OCIO.REFERENCE_SPACE_DISPLAY) self.assertEqual(vt.getReferenceSpaceType(), OCIO.REFERENCE_SPACE_DISPLAY) vt = OCIO.ViewTransform(name='test') self.assertEqual(vt.getName(), 'test') vt = OCIO.ViewTransform(family='family') self.assertEqual(vt.getFamily(), 'family') vt = OCIO.ViewTransform(description='description') self.assertEqual(vt.getDescription(), 'description') vt = OCIO.ViewTransform(categories=['cat1', 'cat2']) cats = vt.getCategories() self.assertEqual(len(cats), 2) self.assertEqual(cats[0], 'cat1') self.assertEqual(cats[1], 'cat2') mat = OCIO.MatrixTransform() vt = OCIO.ViewTransform(toReference=mat) self.assertTrue(vt.getTransform(OCIO.VIEWTRANSFORM_DIR_TO_REFERENCE).equals(mat)) vt = OCIO.ViewTransform(fromReference=mat) self.assertTrue(vt.getTransform(OCIO.VIEWTRANSFORM_DIR_FROM_REFERENCE).equals(mat)) def test_name(self): """ Test get/setName. """ vt = OCIO.ViewTransform() self.assertEqual(vt.getName(), '') vt.setName('test name') self.assertEqual(vt.getName(), 'test name') def test_family(self): """ Test get/setFamily. """ vt = OCIO.ViewTransform() self.assertEqual(vt.getFamily(), '') vt.setFamily('test family') self.assertEqual(vt.getFamily(), 'test family') def test_description(self): """ Test get/setDescription. """ vt = OCIO.ViewTransform() self.assertEqual(vt.getDescription(), '') vt.setDescription('test description') self.assertEqual(vt.getDescription(), 'test description') def test_transform(self): """ Test get/setTransform. """ vt = OCIO.ViewTransform() self.assertEqual(vt.getTransform(OCIO.VIEWTRANSFORM_DIR_TO_REFERENCE), None) self.assertEqual(vt.getTransform(OCIO.VIEWTRANSFORM_DIR_FROM_REFERENCE), None) mat = OCIO.MatrixTransform() vt.setTransform(mat, OCIO.VIEWTRANSFORM_DIR_TO_REFERENCE) self.assertTrue(vt.getTransform(OCIO.VIEWTRANSFORM_DIR_TO_REFERENCE).equals(mat)) vt.setTransform(None, OCIO.VIEWTRANSFORM_DIR_TO_REFERENCE) self.assertEqual(vt.getTransform(OCIO.VIEWTRANSFORM_DIR_TO_REFERENCE), None) vt.setTransform(direction=OCIO.VIEWTRANSFORM_DIR_FROM_REFERENCE, transform=mat) self.assertTrue(vt.getTransform(OCIO.VIEWTRANSFORM_DIR_FROM_REFERENCE).equals(mat)) vt.setTransform(transform=None, direction=OCIO.VIEWTRANSFORM_DIR_FROM_REFERENCE) self.assertEqual(vt.getTransform(OCIO.VIEWTRANSFORM_DIR_FROM_REFERENCE), None) def test_categories(self): """ Test hasCategory, addCategory, removeCategory, getCategories, and clearCategories. """ vt = OCIO.ViewTransform() self.assertEqual(len(vt.getCategories()), 0) vt.addCategory('cat1') self.assertEqual(len(vt.getCategories()), 1) self.assertEqual(vt.getCategories()[0], 'cat1') self.assertTrue(vt.hasCategory('cat1')) # Category is not case sensitive. self.assertTrue(vt.hasCategory('cAt1')) self.assertFalse(vt.hasCategory('cat2')) vt.addCategory('cat1') self.assertEqual(len(vt.getCategories()), 1) vt.addCategory('CAT1') self.assertEqual(len(vt.getCategories()), 1) vt.addCategory('CAT2') cats = vt.getCategories() self.assertEqual(len(cats), 2) # Original case is preserved. self.assertEqual(cats[0], 'cat1') self.assertEqual(cats[1], 'CAT2') vt.removeCategory('cat3') self.assertEqual(len(vt.getCategories()), 2) vt.removeCategory('CAT1') self.assertEqual(len(vt.getCategories()), 1) vt.addCategory('CAT3') vt.addCategory('CAT4') self.assertEqual(len(vt.getCategories()), 3) vt.clearCategories() self.assertEqual(len(vt.getCategories()), 0)
corehq/messaging/smsbackends/trumpia/tests/test_outgoing.py
akashkj/commcare-hq
471
147719
<gh_stars>100-1000 from urllib.parse import urlencode from django.test import SimpleTestCase import requests_mock from corehq.apps.reports.standard.message_event_display import ( get_sms_status_display, ) from corehq.apps.sms.models import QueuedSMS from corehq.messaging.smsbackends.trumpia.models import ( TrumpiaBackend, TrumpiaRetry, ) USERNAME = "testuser" API_KEY = "<KEY>" class TestTrumpiaBackend(SimpleTestCase): """Trumpia SMS backend Error status code reference: https://classic.trumpia.com/api/docs/http/status-code/direct-sms.php """ @classmethod def setUpClass(cls): super().setUpClass() cls.backend = TrumpiaBackend() cls.backend.extra_fields = {"username": USERNAME, "api_key": API_KEY} def test_success(self): msg = self.mock_send() self.assertEqual(msg.backend_message_id, "1234561234567asdf123") self.assertIsNone(msg.system_error_message) self.assertFalse(msg.error) self.assertEqual(get_sms_status_display(msg), "Sent") def test_success_status_pending(self): msg = self.mock_send(report={ "requestID": "1234561234567asdf123", "message": "In progress", }) self.assertEqual(msg.backend_message_id, "1234561234567asdf123") self.assertTrue(msg.is_status_pending()) self.assertEqual(get_sms_status_display(msg), "Sent - message ID: 1234561234567asdf123") def test_fail_missing_requestID(self): msg = self.mock_send(response={"boo": "hoo"}) self.assertIsNone(msg.backend_message_id) self.assertEqual(msg.system_error_message, "Gateway error: {'boo': 'hoo'}") self.assertTrue(msg.error) def test_fail_missing_statuscode(self): msg = self.mock_send(report={"unexpected": "result"}) self.assertEqual(msg.backend_message_id, "1234561234567asdf123") self.assertEqual(msg.system_error_message, "Gateway error: {'unexpected': 'result'}") self.assertTrue(msg.error) def test_generic_failure(self): msg = self.mock_send( response={"requestID": "1234561234567asdf123"}, report={"statuscode": "0", "message": "Did not send."}, ) self.assertEqual(msg.backend_message_id, "1234561234567asdf123") self.assertEqual(msg.system_error_message, "Gateway error: status 0: Did not send.") self.assertTrue(msg.error) def test_fail_MRME0201(self): msg = self.mock_send( response={"requestID": "1234561234567asdf123"}, report={"statuscode": "MRME0201", "message": "Internal Error."}, ) self.assertEqual(msg.backend_message_id, "1234561234567asdf123") self.assertEqual(msg.system_error_message, "Gateway error: status MRME0201: Internal Error.") self.assertTrue(msg.error) def test_errorcode_16(self): msg = self.mock_send( response={"requestID": "1234561234567asdf123"}, report={ "statuscode": "0", "errorcode": "16", "errormessage": "Blocked Number : 15554443333", }, ) self.assertEqual(msg.backend_message_id, "1234561234567asdf123") self.assertEqual(msg.system_error_message, "Gateway error: error 16: Blocked Number : 15554443333") self.assertTrue(msg.error) def test_status_without_message(self): msg = self.mock_send( response={"requestID": "1234561234567asdf123"}, report={"statuscode": "?", "something": "else"}, ) self.assertEqual(msg.backend_message_id, "1234561234567asdf123") self.assertEqual(msg.system_error_message, "Gateway error: {'statuscode': '?', 'something': 'else'}") self.assertTrue(msg.error) def test_405(self): msg = self.mock_send(status_code=405) self.assertEqual(msg.system_error_message, "Gateway error: 405") self.assertTrue(msg.error) def test_500(self): with self.assertRaises(TrumpiaRetry) as err: self.mock_send(status_code=500) self.assertRegex(str(err.exception), "Gateway 500 error") def test_get_message_details(self): request_id = "1234561234567asdf123" report = {"statuscode": "1", "message": "Send Success"} with requests_mock.Mocker() as mock: self.mock_report(mock, request_id, report) self.backend.get_message_details(request_id) def mock_send(self, status_code=200, response=None, report=None): msg = QueuedSMS( phone_number='+15554443333', text="the message", direction="O", ) msg.save = lambda: None # prevent db access in SimpleTestCase query = querystring({ "apikey": API_KEY, "country_code": "0", "mobile_number": msg.phone_number, "message": msg.text, "concat": "TRUE", }) if response is None: response = {"requestID": "1234561234567asdf123"} with requests_mock.Mocker() as mock: mock.get( "http://api.trumpia.com/http/v2/sendverificationsms" + query, request_headers={"Accept": "application/json"}, status_code=status_code, json=(response if status_code == 200 else {}), ) if "requestID" in response: self.mock_report(mock, response["requestID"], report) self.backend.send(msg) return msg def mock_report(self, mock, request_id, report): query = querystring({"request_id": request_id}) if not report: report = { "statuscode": "1", "message": "Send Success", "creditProcessID": "12345", "taskID": "123456", } mock.get( "https://api.trumpia.com/http/v2/checkresponse" + query, request_headers={"Accept": "application/json"}, status_code=200, json=report ) def querystring(data): return "?" + urlencode(data)
dm_env/_environment_test.py
kngwyu/dm_env
235
147722
<filename>dm_env/_environment_test.py # pylint: disable=g-bad-file-header # Copyright 2019 The dm_env 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. # ============================================================================ """Tests for dm_env._environment.""" from absl.testing import absltest from absl.testing import parameterized import dm_env class TimeStepHelpersTest(parameterized.TestCase): @parameterized.parameters(dict(observation=-1), dict(observation=[2., 3.])) def test_restart(self, observation): time_step = dm_env.restart(observation) self.assertIs(dm_env.StepType.FIRST, time_step.step_type) self.assertEqual(observation, time_step.observation) self.assertIsNone(time_step.reward) self.assertIsNone(time_step.discount) @parameterized.parameters( dict(observation=-1., reward=2.0, discount=1.0), dict(observation=(2., 3.), reward=0., discount=0.)) def test_transition(self, observation, reward, discount): time_step = dm_env.transition( reward=reward, observation=observation, discount=discount) self.assertIs(dm_env.StepType.MID, time_step.step_type) self.assertEqual(observation, time_step.observation) self.assertEqual(reward, time_step.reward) self.assertEqual(discount, time_step.discount) @parameterized.parameters( dict(observation=-1., reward=2.0), dict(observation=(2., 3.), reward=0.)) def test_termination(self, observation, reward): time_step = dm_env.termination(reward=reward, observation=observation) self.assertIs(dm_env.StepType.LAST, time_step.step_type) self.assertEqual(observation, time_step.observation) self.assertEqual(reward, time_step.reward) self.assertEqual(0.0, time_step.discount) @parameterized.parameters( dict(observation=-1., reward=2.0, discount=1.0), dict(observation=(2., 3.), reward=0., discount=0.)) def test_truncation(self, reward, observation, discount): time_step = dm_env.truncation(reward, observation, discount) self.assertIs(dm_env.StepType.LAST, time_step.step_type) self.assertEqual(observation, time_step.observation) self.assertEqual(reward, time_step.reward) self.assertEqual(discount, time_step.discount) @parameterized.parameters( dict(step_type=dm_env.StepType.FIRST, is_first=True, is_mid=False, is_last=False), dict(step_type=dm_env.StepType.MID, is_first=False, is_mid=True, is_last=False), dict(step_type=dm_env.StepType.LAST, is_first=False, is_mid=False, is_last=True), ) def test_step_type_helpers(self, step_type, is_first, is_mid, is_last): time_step = dm_env.TimeStep( reward=None, discount=None, observation=None, step_type=step_type) with self.subTest('TimeStep methods'): self.assertEqual(is_first, time_step.first()) self.assertEqual(is_mid, time_step.mid()) self.assertEqual(is_last, time_step.last()) with self.subTest('StepType methods'): self.assertEqual(is_first, time_step.step_type.first()) self.assertEqual(is_mid, time_step.step_type.mid()) self.assertEqual(is_last, time_step.step_type.last()) if __name__ == '__main__': absltest.main()
pykinect_azure/k4arecord/_k4arecord.py
necoxt/pyKinectAzure
170
147733
import ctypes import sys import traceback from ._k4arecordTypes import * from ..k4a._k4atypes import * record_dll = None def setup_library(module_k4arecord_path): global record_dll try: record_dll = ctypes.CDLL(module_k4arecord_path) except Exception as e: print("Failed to load library", e) sys.exit(1) def k4a_record_create(file_path, device, device_config, recording_handle): """ K4ARECORD_EXPORT k4a_result_t k4a_record_create(const char *path, k4a_device_t device, const k4a_device_configuration_t device_config, k4a_record_t *recording_handle); """ _k4a_record_create = record_dll.k4a_record_create _k4a_record_create.restype = k4a_result_t _k4a_record_create.argtypes = (ctypes.POINTER(ctypes.c_char), \ k4a_device_t, \ k4a_device_configuration_t, \ ctypes.POINTER(k4a_record_t),\ ) return _k4a_record_create(file_path, device, device_config, recording_handle) def k4a_record_write_header(recording_handle): # K4ARECORD_EXPORT k4a_result_t k4a_record_write_header(k4a_record_t recording_handle); _k4a_record_write_header = record_dll.k4a_record_write_header _k4a_record_write_header.restype = k4a_result_t _k4a_record_write_header.argtypes = (k4a_record_t,) return _k4a_record_write_header(recording_handle) def k4a_record_write_capture(recording_handle, capture_handle): # K4ARECORD_EXPORT k4a_result_t k4a_record_write_capture(k4a_record_t recording_handle, k4a_capture_t capture_handle); _k4a_record_write_capture = record_dll.k4a_record_write_capture _k4a_record_write_capture.restype = k4a_result_t _k4a_record_write_capture.argtypes = (k4a_record_t, \ k4a_capture_t) return _k4a_record_write_capture(recording_handle, capture_handle) def k4a_record_flush(recording_handle): # K4ARECORD_EXPORT k4a_result_t k4a_record_flush(k4a_record_t recording_handle); _k4a_record_flush = record_dll.k4a_record_flush _k4a_record_flush.restype = k4a_result_t _k4a_record_flush.argtypes = (k4a_record_t,) return _k4a_record_flush(recording_handle) def k4a_record_close(recording_handle): # K4ARECORD_EXPORT void k4a_record_close(k4a_record_t recording_handle); _k4a_record_close = record_dll.k4a_record_close _k4a_record_close.restype = None _k4a_record_close.argtypes = (k4a_record_t,) _k4a_record_close(recording_handle) ########################### ### Playback ### ########################### def k4a_playback_open(file_path, playback_handle): # K4ARECORD_EXPORT k4a_result_t k4a_playback_open(const char *path, k4a_playback_t *playback_handle); _k4a_playback_open = record_dll.k4a_playback_open _k4a_playback_open.restype = k4a_result_t _k4a_playback_open.argtypes = (ctypes.POINTER(ctypes.c_char), \ ctypes.POINTER(k4a_playback_t),) return _k4a_playback_open(file_path, playback_handle) def k4a_playback_close(playback_handle): # K4ARECORD_EXPORT void k4a_playback_close(k4a_playback_t playback_handle); _k4a_playback_close = record_dll.k4a_playback_close _k4a_playback_close.restype = None _k4a_playback_close.argtypes = (k4a_playback_t,) _k4a_playback_close(playback_handle) def k4a_playback_get_raw_calibration(playback_handle, data, data_size): """ K4ARECORD_EXPORT k4a_buffer_result_t k4a_playback_get_raw_calibration(k4a_playback_t playback_handle, uint8_t *data, size_t *data_size); """ _k4a_playback_get_raw_calibration = record_dll.k4a_playback_get_raw_calibration _k4a_playback_get_raw_calibration.restype = k4a_buffer_result_t _k4a_playback_get_raw_calibration.argtypes = (k4a_playback_t, \ ctypes.POINTER(ctypes.c_uint8),\ ctypes.POINTER(ctypes.c_size_t)) return _k4a_playback_get_raw_calibration(playback_handle, data, data_size) def k4a_playback_get_calibration(playback_handle, calibration): """ K4ARECORD_EXPORT k4a_result_t k4a_playback_get_calibration(k4a_playback_t playback_handle, k4a_calibration_t *calibration); """ _k4a_playback_get_calibration = record_dll.k4a_playback_get_calibration _k4a_playback_get_calibration.restype = k4a_result_t _k4a_playback_get_calibration.argtypes = (k4a_playback_t, \ ctypes.POINTER(k4a_calibration_t)) return _k4a_playback_get_calibration(playback_handle, calibration) def k4a_playback_get_record_configuration(playback_handle, config): """ K4ARECORD_EXPORT k4a_result_t k4a_playback_get_record_configuration(k4a_playback_t playback_handle, k4a_record_configuration_t *config); """ _k4a_playback_get_record_configuration = record_dll.k4a_playback_get_record_configuration _k4a_playback_get_record_configuration.restype = k4a_result_t _k4a_playback_get_record_configuration.argtypes = (k4a_playback_t, \ ctypes.POINTER(k4a_record_configuration_t)) return _k4a_playback_get_record_configuration(playback_handle, config) def k4a_playback_check_track_exists(playback_handle, track_name): """ K4ARECORD_EXPORT bool k4a_playback_check_track_exists(k4a_playback_t playback_handle, const char *track_name); """ _k4a_playback_check_track_exists = record_dll.k4a_playback_check_track_exists _k4a_playback_check_track_exists.restype = ctypes.c_bool _k4a_playback_check_track_exists.argtypes = (k4a_playback_t, \ ctypes.POINTER(ctypes.c_char)) return _k4a_playback_check_track_exists(playback_handle, track_name) def k4a_playback_get_track_count(playback_handle): """ K4ARECORD_EXPORT size_t k4a_playback_get_track_count(k4a_playback_t playback_handle); """ _k4a_playback_get_track_count = record_dll.k4a_playback_get_track_count _k4a_playback_get_track_count.restype = ctypes.c_size_t _k4a_playback_get_track_count.argtypes = (k4a_playback_t,) return _k4a_playback_get_track_count(playback_handle) def k4a_playback_get_track_name(playback_handle, track_index, track_name, track_name_size): """ K4ARECORD_EXPORT k4a_buffer_result_t k4a_playback_get_track_name(k4a_playback_t playback_handle, size_t track_index, char *track_name, size_t *track_name_size); """ _k4a_playback_get_track_name = record_dll.k4a_playback_get_track_name _k4a_playback_get_track_name.restype = k4a_buffer_result_t _k4a_playback_get_track_name.argtypes = (k4a_playback_t,\ ctypes.c_size_t,\ ctypes.POINTER(ctypes.c_char),\ ctypes.POINTER(ctypes.c_size_t)) return _k4a_playback_get_track_name(playback_handle, track_index, track_name, track_name_size) def k4a_playbk4a_playback_track_is_builtinack_get_track_name(playback_handle, track_name): """ K4ARECORD_EXPORT bool k4a_playback_track_is_builtin(k4a_playback_t playback_handle, const char *track_name);; """ _k4a_playback_track_is_builtin = record_dll.k4a_playback_track_is_builtin _k4a_playback_track_is_builtin.restype = ctypes.c_bool _k4a_playback_track_is_builtin.argtypes = (k4a_playback_t,\ ctypes.POINTER(ctypes.c_char)) return _k4a_playback_track_is_builtin(playback_handle, track_name) def k4a_playback_track_get_video_settings(playback_handle, track_name, video_settings): """ K4ARECORD_EXPORT k4a_result_t k4a_playback_track_get_video_settings(k4a_playback_t playback_handle, const char *track_name, k4a_record_video_settings_t *video_settings); """ _k4a_playback_track_get_video_settings = record_dll.k4a_playback_track_get_video_settings _k4a_playback_track_get_video_settings.restype = k4a_result_t _k4a_playback_track_get_video_settings.argtypes = (k4a_playback_t,\ ctypes.POINTER(ctypes.c_char),\ ctypes.POINTER(k4a_record_video_settings_t)) return _k4a_playback_track_get_video_settings(playback_handle, track_name, video_settings) def k4a_playback_track_get_codec_id(playback_handle, track_name, codec_id, codec_id_size): """ K4ARECORD_EXPORT k4a_buffer_result_t k4a_playback_track_get_codec_id(k4a_playback_t playback_handle, const char *track_name, char *codec_id, size_t *codec_id_size); """ _k4a_playback_track_get_codec_id = record_dll.k4a_playback_track_get_codec_id _k4a_playback_track_get_codec_id.restype = k4a_buffer_result_t _k4a_playback_track_get_codec_id.argtypes = (k4a_playback_t,\ ctypes.POINTER(ctypes.c_char),\ ctypes.POINTER(ctypes.c_char),\ ctypes.POINTER(ctypes.c_size_t)) return _k4a_playback_track_get_codec_id(playback_handle, track_name, codec_id, codec_id_size) def k4a_playback_track_get_codec_context(playback_handle, track_name, codec_context, codec_context_size): """ K4ARECORD_EXPORT k4a_buffer_result_t k4a_playback_track_get_codec_context(k4a_playback_t playback_handle, const char *track_name, uint8_t *codec_context, size_t *codec_context_size); """ _k4a_playback_track_get_codec_context = record_dll.k4a_playback_track_get_codec_context _k4a_playback_track_get_codec_context.restype = k4a_buffer_result_t _k4a_playback_track_get_codec_context.argtypes = (k4a_playback_t,\ ctypes.POINTER(ctypes.c_char),\ ctypes.POINTER(ctypes.c_uint8),\ ctypes.POINTER(ctypes.c_size_t)) return _k4a_playback_track_get_codec_context(playback_handle, track_name, codec_context, codec_context_size) def k4a_playback_get_tag(playback_handle, name, value, value_size): """ K4ARECORD_EXPORT k4a_buffer_result_t k4a_playback_get_tag(k4a_playback_t playback_handle, const char *name, char *value, size_t *value_size); """ _k4a_playback_get_tag = record_dll.k4a_playback_get_tag _k4a_playback_get_tag.restype = k4a_buffer_result_t _k4a_playback_get_tag.argtypes = (k4a_playback_t,\ ctypes.POINTER(ctypes.c_char),\ ctypes.POINTER(ctypes.c_char),\ ctypes.POINTER(ctypes.c_size_t)) return _k4a_playback_get_tag(playback_handle, name, value, value_size) def k4a_playback_set_color_conversion(playback_handle, target_format): """ K4ARECORD_EXPORT k4a_result_t k4a_playback_set_color_conversion(k4a_playback_t playback_handle, k4a_image_format_t target_format); """ _k4a_playback_set_color_conversion = record_dll.k4a_playback_set_color_conversion _k4a_playback_set_color_conversion.restype = k4a_result_t _k4a_playback_set_color_conversion.argtypes = (k4a_playback_t,\ k4a_image_format_t) return _k4a_playback_set_color_conversion(playback_handle, target_format) def k4a_playback_get_attachment(playback_handle, file_name, data, data_size): """ K4ARECORD_EXPORT k4a_buffer_result_t k4a_playback_get_attachment(k4a_playback_t playback_handle, const char *file_name, uint8_t *data, size_t *data_size); """ _k4a_playback_get_attachment = record_dll.k4a_playback_get_attachment _k4a_playback_get_attachment.restype = k4a_buffer_result_t _k4a_playback_get_attachment.argtypes = (k4a_playback_t,\ ctypes.POINTER(ctypes.c_char),\ ctypes.POINTER(ctypes.c_uint8),\ ctypes.POINTER(ctypes.c_size_t)) return _k4a_playback_get_attachment(playback_handle, file_name, data, data_size) def k4a_playback_get_next_capture(playback_handle, capture_handle): """ K4ARECORD_EXPORT k4a_stream_result_t k4a_playback_get_next_capture(k4a_playback_t playback_handle, k4a_capture_t *capture_handle); """ _k4a_playback_get_next_capture = record_dll.k4a_playback_get_next_capture _k4a_playback_get_next_capture.restype = k4a_stream_result_t _k4a_playback_get_next_capture.argtypes = (k4a_playback_t, \ ctypes.POINTER(k4a_capture_t),) return _k4a_playback_get_next_capture(playback_handle, capture_handle) def k4a_playback_get_previous_capture(playback_handle, capture_handle): """ K4ARECORD_EXPORT k4a_stream_result_t k4a_playback_get_previous_capture(k4a_playback_t playback_handle, k4a_capture_t *capture_handle); """ _k4a_playback_get_previous_capture = record_dll.k4a_playback_get_previous_capture _k4a_playback_get_previous_capture.restype = k4a_stream_result_t _k4a_playback_get_previous_capture.argtypes = (k4a_playback_t, \ ctypes.POINTER(k4a_capture_t),) return _k4a_playback_get_previous_capture(playback_handle, capture_handle) def k4a_playback_get_next_imu_sample(playback_handle, imu_sample): """ K4ARECORD_EXPORT k4a_stream_result_t k4a_playback_get_next_imu_sample(k4a_playback_t playback_handle, k4a_imu_sample_t *imu_sample); """ _k4a_playback_get_next_imu_sample = record_dll.k4a_playback_get_next_imu_sample _k4a_playback_get_next_imu_sample.restype = k4a_stream_result_t _k4a_playback_get_next_imu_sample.argtypes = (k4a_playback_t, \ ctypes.POINTER(k4a_imu_sample_t),) return _k4a_playback_get_next_imu_sample(playback_handle, imu_sample) def k4a_playback_get_previous_imu_sample(playback_handle, imu_sample): """ K4ARECORD_EXPORT k4a_stream_result_t k4a_playback_get_previous_imu_sample(k4a_playback_t playback_handle, k4a_imu_sample_t *imu_sample); """ _k4a_playback_get_previous_imu_sample = record_dll.k4a_playback_get_previous_imu_sample _k4a_playback_get_previous_imu_sample.restype = k4a_stream_result_t _k4a_playback_get_previous_imu_sample.argtypes = (k4a_playback_t, \ ctypes.POINTER(k4a_imu_sample_t),) return _k4a_playback_get_previous_imu_sample(playback_handle, imu_sample) def k4a_playback_get_next_data_block(playback_handle, track_name, data_block_handle): """ K4ARECORD_EXPORT k4a_stream_result_t k4a_playback_get_next_data_block(k4a_playback_t playback_handle, const char *track_name, k4a_playback_data_block_t *data_block_handle); """ _k4a_playback_get_next_data_block = record_dll.k4a_playback_get_next_data_block _k4a_playback_get_next_data_block.restype = k4a_stream_result_t _k4a_playback_get_next_data_block.argtypes = (k4a_playback_t, \ ctypes.POINTER(ctypes.c_char), ctypes.POINTER(k4a_playback_data_block_t),) return _k4a_playback_get_next_data_block(playback_handle, track_name, data_block_handle) def k4a_playback_get_previous_data_block(playback_handle, track_name, data_block_handle): """ K4ARECORD_EXPORT k4a_stream_result_t k4a_playback_get_previous_data_block(k4a_playback_t playback_handle, const char *track_name, k4a_playback_data_block_t *data_block_handle); """ _k4a_playback_get_previous_data_block = record_dll.k4a_playback_get_previous_data_block _k4a_playback_get_previous_data_block.restype = k4a_stream_result_t _k4a_playback_get_previous_data_block.argtypes = (k4a_playback_t, \ ctypes.POINTER(ctypes.c_char), ctypes.POINTER(k4a_playback_data_block_t),) return _k4a_playback_get_previous_data_block(playback_handle, track_name, data_block_handle) def k4a_playback_data_block_get_device_timestamp_usec(data_block_handle): """ K4ARECORD_EXPORT uint64_t k4a_playback_data_block_get_device_timestamp_usec(k4a_playback_data_block_t data_block_handle); """ _k4a_playback_data_block_get_device_timestamp_usec = record_dll.k4a_playback_data_block_get_device_timestamp_usec _k4a_playback_data_block_get_device_timestamp_usec.restype = ctypes.c_uint64 _k4a_playback_data_block_get_device_timestamp_usec.argtypes = (k4a_playback_data_block_t,) return _k4a_playback_data_block_get_device_timestamp_usec(data_block_handle) def k4a_playback_data_block_get_buffer_size(data_block_handle): """ K4ARECORD_EXPORT size_t k4a_playback_data_block_get_buffer_size(k4a_playback_data_block_t data_block_handle); """ _k4a_playback_data_block_get_buffer_size = record_dll.k4a_playback_data_block_get_buffer_size _k4a_playback_data_block_get_buffer_size.restype = ctypes.c_size_t _k4a_playback_data_block_get_buffer_size.argtypes = (k4a_playback_data_block_t,) return _k4a_playback_data_block_get_buffer_size(data_block_handle) def k4a_playback_data_block_get_buffer(data_block_handle): """ K4ARECORD_EXPORT uint8_t *k4a_playback_data_block_get_buffer(k4a_playback_data_block_t data_block_handle); """ _k4a_playback_data_block_get_buffer = record_dll.k4a_playback_data_block_get_buffer _k4a_playback_data_block_get_buffer.restype = ctypes.POINTER(ctypes.c_uint8) _k4a_playback_data_block_get_buffer.argtypes = (k4a_playback_data_block_t,) return _k4a_playback_data_block_get_buffer(data_block_handle) def k4a_playback_data_block_release(data_block_handle): """ K4ARECORD_EXPORT void k4a_playback_data_block_release(k4a_playback_data_block_t data_block_handle); """ _k4a_playback_data_block_release = record_dll.k4a_playback_data_block_release _k4a_playback_data_block_release.restype = None _k4a_playback_data_block_release.argtypes = (k4a_playback_data_block_t,) return _k4a_playback_data_block_release(data_block_handle) def k4a_playback_seek_timestamp(playback_handle, offset_usec, origin): """ K4ARECORD_EXPORT k4a_result_t k4a_playback_seek_timestamp(k4a_playback_t playback_handle, int64_t offset_usec, k4a_playback_seek_origin_t origin); """ _k4a_playback_seek_timestamp = record_dll.k4a_playback_seek_timestamp _k4a_playback_seek_timestamp.restype = k4a_result_t _k4a_playback_seek_timestamp.argtypes = (k4a_playback_t,\ ctypes.c_int64,\ k4a_playback_seek_origin_t) return _k4a_playback_seek_timestamp(playback_handle, offset_usec, origin) def k4a_playback_get_recording_length_usec(playback_handle): """ K4ARECORD_EXPORT uint64_t k4a_playback_get_recording_length_usec(k4a_playback_t playback_handle); """ _k4a_playback_get_recording_length_usec = record_dll.k4a_playback_get_recording_length_usec _k4a_playback_get_recording_length_usec.restype = ctypes.c_uint64 _k4a_playback_get_recording_length_usec.argtypes = (k4a_playback_t,) return _k4a_playback_get_recording_length_usec(playback_handle) def k4a_playback_get_last_timestamp_usec(playback_handle): """ K4ARECORD_DEPRECATED_EXPORT uint64_t k4a_playback_get_last_timestamp_usec(k4a_playback_t playback_handle); """ _k4a_playback_get_last_timestamp_usec = record_dll.k4a_playback_get_last_timestamp_usec _k4a_playback_get_last_timestamp_usec.restype = ctypes.c_uint64 _k4a_playback_get_last_timestamp_usec.argtypes = (k4a_playback_t,) return _k4a_playback_get_last_timestamp_usec(playback_handle) def VERIFY(result, error): if result != K4A_RESULT_SUCCEEDED: print(error) traceback.print_stack() sys.exit(1)
ChasingTrainFramework_GeneralOneClassDetection/loss_layer_farm/mean_squared_error_with_ohem_for_one_class_detection.py
dvt0101/A-Light-and-Fast-Face-Detector-for-Edge-Devices
1,172
147760
<reponame>dvt0101/A-Light-and-Fast-Face-Detector-for-Edge-Devices<filename>ChasingTrainFramework_GeneralOneClassDetection/loss_layer_farm/mean_squared_error_with_ohem_for_one_class_detection.py<gh_stars>1000+ # -*- coding: utf-8 -*- ''' squared error with online hard example mining ''' import mxnet as mx class mean_squared_error_with_ohem_for_one_class_detection(mx.operator.CustomOp): def __init__(self, ohem_ratio): super(mean_squared_error_with_ohem_for_one_class_detection, self).__init__() self.ohem_ratio = ohem_ratio def forward(self, is_train, req, in_data, out_data, aux): pred = in_data[0] self.assign(out_data[0], req[0], pred) def backward(self, req, out_grad, in_data, out_data, in_grad, aux): pred = out_data[0] label = in_data[1] loss = pred - label # perform OHEM num_select = int(label.size * self.ohem_ratio) loss_abs = mx.nd.abs(loss) loss_sort = mx.nd.sort(loss_abs.reshape((1, -1)), is_ascend=False) min_threshold = loss_sort[0][num_select].asnumpy()[0] select_flag = loss_abs >= min_threshold loss *= select_flag loss /= num_select self.assign(in_grad[0], req[0], loss) @mx.operator.register("mean_squared_error_with_ohem_for_one_class_detection") class mean_squared_error_with_ohem_for_one_class_detection_Prop(mx.operator.CustomOpProp): def __init__(self, ohem_ratio=0.25): super(mean_squared_error_with_ohem_for_one_class_detection_Prop, self).__init__(need_top_grad=False) self.ohem_ratio = ohem_ratio def list_arguments(self): return ['pred', 'label'] def list_outputs(self): return ['output'] def infer_shape(self, in_shape): pred_shape = in_shape[0] label_shape = in_shape[0] output_shape = in_shape[0] return [pred_shape, label_shape], [output_shape], [] def create_operator(self, ctx, shapes, dtypes): return mean_squared_error_with_ohem_for_one_class_detection(self.ohem_ratio)
proteinbert/conv_and_global_attention_model.py
akriot/protein_bert
124
147773
<filename>proteinbert/conv_and_global_attention_model.py import numpy as np import tensorflow as tf from tensorflow import keras import tensorflow.keras.backend as K class GlobalAttention(keras.layers.Layer): ''' Recevies two inputs: 1. A global representation (of some fixed dimension) 2. A sequence (of any length, and some fixed dimension) The global representation is used to construct a global query that attends to all the positions in the sequence (independently for any of the heads). ''' def __init__(self, n_heads, d_key, d_value, **kwargs): self.n_heads = n_heads self.d_key = d_key self.sqrt_d_key = np.sqrt(self.d_key) self.d_value = d_value self.d_output = n_heads * d_value super(GlobalAttention, self).__init__(**kwargs) def compute_output_shape(self, input_shapes): # input_shapes: (batch_size, d_global_input), (batch_size, length, d_seq_input) (batch_size, _), _ = input_shapes return (batch_size, self.d_output) def build(self, input_shapes): # input_shapes: (batch_size, d_global_input), (batch_size, length, d_seq_input) (_, self.d_global_input), (_, _, self.d_seq_input) = input_shapes # Wq: (n_heads, d_global_input, d_key) self.Wq = self.add_weight(name = 'Wq', shape = (self.n_heads, self.d_global_input, self.d_key), \ initializer = 'glorot_uniform', trainable = True) # Wk: (n_heads, d_seq_input, d_key) self.Wk = self.add_weight(name = 'Wk', shape = (self.n_heads, self.d_seq_input, self.d_key), \ initializer = 'glorot_uniform', trainable = True) # Wv: (n_heads, d_seq_input, d_value) self.Wv = self.add_weight(name = 'Wv', shape = (self.n_heads, self.d_seq_input, self.d_value), \ initializer = 'glorot_uniform', trainable = True) super(GlobalAttention, self).build(input_shapes) def call(self, inputs): # X: (batch_size, d_global_input) # S: (batch_size, length, d_seq_input) X, S = inputs _, length, _ = K.int_shape(S) # (batch_size, n_heads, length, d_value) VS = K.permute_dimensions(keras.activations.gelu(K.dot(S, self.Wv)), (0, 2, 1, 3)) # (batch_size * n_heads, length, d_value) VS_batched_heads = K.reshape(VS, (-1, length, self.d_value)) Z_batched_heads = self.calculate_attention(inputs) # (batch_size * n_heads, d_value) Y_batched_heads = K.batch_dot(Z_batched_heads, VS_batched_heads) # (batch_size, n_heads * d_value) Y = K.reshape(Y_batched_heads, (-1, self.d_output)) return Y def calculate_attention(self, inputs): # X: (batch_size, d_global_input) # S: (batch_size, length, d_seq_input) X, S = inputs _, length, _ = K.int_shape(S) # (batch_size, n_heads, d_key) QX = K.tanh(K.dot(X, self.Wq)) # (batch_size * n_heads, d_key) QX_batched_heads = K.reshape(QX, (-1, self.d_key)) # (batch_size, n_heads, d_key, length) KS = K.permute_dimensions(K.tanh(K.dot(S, self.Wk)), (0, 2, 3, 1)) # (batch_size * n_heads, d_key, length) KS_batched_heads = K.reshape(KS, (-1, self.d_key, length)) # (batch_size * n_heads, length) Z_batched_heads = K.softmax(K.batch_dot(QX_batched_heads, KS_batched_heads) / self.sqrt_d_key) return Z_batched_heads def create_model(seq_len, vocab_size, n_annotations, d_hidden_seq = 128, d_hidden_global = 512, n_blocks = 6, n_heads = 4, \ d_key = 64, conv_kernel_size = 9, wide_conv_dilation_rate = 5, activation = 'gelu'): ''' seq_len is required to create the model, but all the weights are independent of the length and can be re-used with different lengths. ''' assert d_hidden_global % n_heads == 0 d_value = d_hidden_global // n_heads input_seq = keras.layers.Input(shape = (seq_len,), dtype = np.int32, name = 'input-seq') input_annoatations = keras.layers.Input(shape = (n_annotations,), dtype = np.float32, name = 'input-annotations') hidden_seq = keras.layers.Embedding(vocab_size, d_hidden_seq, name = 'embedding-seq-input')(input_seq) hidden_global = keras.layers.Dense(d_hidden_global, activation = activation, name = 'dense-global-input')(input_annoatations) for block_index in range(1, n_blocks + 1): seqed_global = keras.layers.Dense(d_hidden_seq, activation = activation, name = 'global-to-seq-dense-block%d' % block_index)(hidden_global) seqed_global = keras.layers.Reshape((1, d_hidden_seq), name = 'global-to-seq-reshape-block%d' % block_index)(seqed_global) narrow_conv_seq = keras.layers.Conv1D(filters = d_hidden_seq, kernel_size = conv_kernel_size, strides = 1, \ padding = 'same', dilation_rate = 1, activation = activation, name = 'narrow-conv-block%d' % block_index)(hidden_seq) wide_conv_seq = keras.layers.Conv1D(filters = d_hidden_seq, kernel_size = conv_kernel_size, strides = 1, \ padding = 'same', dilation_rate = wide_conv_dilation_rate, activation = activation, name = 'wide-conv-block%d' % \ block_index)(hidden_seq) hidden_seq = keras.layers.Add(name = 'seq-merge1-block%d' % block_index)([hidden_seq, seqed_global, narrow_conv_seq, wide_conv_seq]) hidden_seq = keras.layers.LayerNormalization(name = 'seq-merge1-norm-block%d' % block_index)(hidden_seq) dense_seq = keras.layers.Dense(d_hidden_seq, activation = activation, name = 'seq-dense-block%d' % block_index)(hidden_seq) hidden_seq = keras.layers.Add(name = 'seq-merge2-block%d' % block_index)([hidden_seq, dense_seq]) hidden_seq = keras.layers.LayerNormalization(name = 'seq-merge2-norm-block%d' % block_index)(hidden_seq) dense_global = keras.layers.Dense(d_hidden_global, activation = activation, name = 'global-dense1-block%d' % block_index)(hidden_global) attention = GlobalAttention(n_heads, d_key, d_value, name = 'global-attention-block%d' % block_index)([hidden_global, hidden_seq]) hidden_global = keras.layers.Add(name = 'global-merge1-block%d' % block_index)([hidden_global, dense_global, attention]) hidden_global = keras.layers.LayerNormalization(name = 'global-merge1-norm-block%d' % block_index)(hidden_global) dense_global = keras.layers.Dense(d_hidden_global, activation = activation, name = 'global-dense2-block%d' % block_index)(hidden_global) hidden_global = keras.layers.Add(name = 'global-merge2-block%d' % block_index)([hidden_global, dense_global]) hidden_global = keras.layers.LayerNormalization(name = 'global-merge2-norm-block%d' % block_index)(hidden_global) output_seq = keras.layers.Dense(vocab_size, activation = 'softmax', name = 'output-seq')(hidden_seq) output_annotations = keras.layers.Dense(n_annotations, activation = 'sigmoid', name = 'output-annotations')(hidden_global) return keras.models.Model(inputs = [input_seq, input_annoatations], outputs = [output_seq, output_annotations]) def get_model_with_hidden_layers_as_outputs(model): _, seq_len, _ = model.outputs[0].shape seq_layers = [layer.output for layer in model.layers if len(layer.output.shape) == 3 and \ tuple(layer.output.shape)[:2] == (None, seq_len) and (layer.name in ['input-seq-encoding', 'dense-seq-input', 'output-seq'] or \ isinstance(layer, keras.layers.LayerNormalization))] global_layers = [layer.output for layer in model.layers if len(layer.output.shape) == 2 and (layer.name in ['input_annoatations', \ 'dense-global-input', 'output-annotations'] or isinstance(layer, keras.layers.LayerNormalization))] concatenated_seq_output = keras.layers.Concatenate(name = 'all-seq-layers')(seq_layers) concatenated_global_output = keras.layers.Concatenate(name = 'all-global-layers')(global_layers) return keras.models.Model(inputs = model.inputs, outputs = [concatenated_seq_output, concatenated_global_output])
TileStache/Geography.py
shoeberto/TileStache
414
147792
""" The geography bits of TileStache. A Projection defines the relationship between the rendered tiles and the underlying geographic data. Generally, just one popular projection is used for most web maps, "spherical mercator". Built-in projections: - spherical mercator - WGS84 Example use projection in a layer definition: "layer-name": { "projection": "spherical mercator", ... } You can define your own projection, with a module and object name as arguments: "layer-name": { ... "projection": "Module:Object" } The object must include methods that convert between coordinates, points, and locations. See the included mercator and WGS84 implementations for example. You can also instantiate a projection class using this syntax: "layer-name": { ... "projection": "Module:Object()" } """ from ModestMaps.Core import Point, Coordinate from ModestMaps.Geo import deriveTransformation, MercatorProjection, LinearProjection, Location from math import log as _log, pi as _pi from . import Core class SphericalMercator(MercatorProjection): """ Spherical mercator projection for most commonly-used web map tile scheme. This projection is identified by the name "spherical mercator" in the TileStache config. The simplified projection used here is described in greater detail at: http://trac.openlayers.org/wiki/SphericalMercator """ srs = '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs +over' def __init__(self): pi = _pi # Transform from raw mercator projection to tile coordinates t = deriveTransformation(-pi, pi, 0, 0, pi, pi, 1, 0, -pi, -pi, 0, 1) MercatorProjection.__init__(self, 0, t) def coordinateProj(self, coord): """ Convert from Coordinate object to a Point object in EPSG:900913 """ # the zoom at which we're dealing with meters on the ground diameter = 2 * _pi * 6378137 zoom = _log(diameter) / _log(2) coord = coord.zoomTo(zoom) # global offsets point = Point(coord.column, coord.row) point.x = point.x - diameter/2 point.y = diameter/2 - point.y return point def projCoordinate(self, point): """ Convert from Point object in EPSG:900913 to a Coordinate object """ # the zoom at which we're dealing with meters on the ground diameter = 2 * _pi * 6378137 zoom = _log(diameter) / _log(2) # global offsets coord = Coordinate(point.y, point.x, zoom) coord.column = coord.column + diameter/2 coord.row = diameter/2 - coord.row return coord def locationProj(self, location): """ Convert from Location object to a Point object in EPSG:900913 """ return self.coordinateProj(self.locationCoordinate(location)) def projLocation(self, point): """ Convert from Point object in EPSG:900913 to a Location object """ return self.coordinateLocation(self.projCoordinate(point)) class WGS84(LinearProjection): """ Unprojected projection for the other commonly-used web map tile scheme. This projection is identified by the name "WGS84" in the TileStache config. """ srs = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs' def __init__(self): p = _pi # Transform from geography in radians to tile coordinates t = deriveTransformation(-p, p/2, 0, 0, p, p/2, 2, 0, -p, -p/2, 0, 1) LinearProjection.__init__(self, 0, t) def coordinateProj(self, coord): """ Convert from Coordinate object to a Point object in EPSG:4326 """ return self.locationProj(self.coordinateLocation(coord)) def projCoordinate(self, point): """ Convert from Point object in EPSG:4326 to a Coordinate object """ return self.locationCoordinate(self.projLocation(point)) def locationProj(self, location): """ Convert from Location object to a Point object in EPSG:4326 """ return Point(location.lon, location.lat) def projLocation(self, point): """ Convert from Point object in EPSG:4326 to a Location object """ return Location(point.y, point.x) def getProjectionByName(name): """ Retrieve a projection object by name. Raise an exception if the name doesn't work out. """ if name.lower() == 'spherical mercator': return SphericalMercator() elif name.lower() == 'wgs84': return WGS84() else: try: return Core.loadClassPath(name) except Exception as e: raise Core.KnownUnknown('Failed projection in configuration: "%s" - %s' % (name, e))
src/utils/version.py
mazurwiktor/albion-online-stats
156
147863
import os import requests from ..version import version latest_url = "https://github.com/mazurwiktor/albion-online-stats/releases/latest" def get_version(): return version def latest_version(): req = requests.get(latest_url) if req.status_code == 200: return os.path.basename(req.url) return None def current_version(): return version
py_stringmatching/tokenizer/tokenizer.py
kvpradap/conda-pysm-appveyor
115
147865
<reponame>kvpradap/conda-pysm-appveyor<filename>py_stringmatching/tokenizer/tokenizer.py class Tokenizer(object): """The root class for tokenizers. Args: return_set (boolean): A flag to indicate whether to return a set of tokens instead of a bag of tokens (defaults to False). Attributes: return_set (boolean): An attribute to store the flag return_set. """ def __init__(self, return_set=False): self.return_set = return_set def get_return_set(self): """Gets the value of the return_set flag. Returns: The boolean value of the return_set flag. """ return self.return_set def set_return_set(self, return_set): """Sets the value of the return_set flag. Args: return_set (boolean): a flag to indicate whether to return a set of tokens instead of a bag of tokens. """ self.return_set = return_set return True
petridish/analysis/model.py
Bhaskers-Blu-Org2/petridishnn
121
147877
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. """ This script is gathers information about a model training run using the log file of the run (or the saved stdout of the run). The information are gathered with `grep` commands on key strings. We assume that the log file contains one single run. A typical usage example: python3 petridish/analysis/model.py \ --log_fn=<model training log.log> The three types of val error, ve_val, ve_train and ve_final, represent the best val error, the val error when training error is the lowest, and the final val error. """ import argparse import os, sys, re from petridish.analysis.model_util import ( verb_print, model_multi_add, model_nparam, model_errors ) from petridish.analysis.philly_util import ( app_dir_log_fns, cust_exp_app_dir, cust_exps_str_to_list ) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--log_fn', type=str, default=None, help='log file path. Can be a comma separated list of files') args = parser.parse_args() l_fn = args.log_fn.split(',') results = [] for fn in l_fn: print('-'*80) print('fn={}'.format(fn)) ma, nparam = None, None (ve_val, ve_train, ve_final, ve_last_5, ve_last_5_std, ve_val_idx, ve_train_idx, ve_final_idx) = [None] * 8 try: ma = model_multi_add(fn) nparam = model_nparam(fn) (ve_val, ve_train, ve_final, ve_last_5, ve_last_5_std, ve_val_idx, ve_train_idx, ve_final_idx) = model_errors(fn) except Exception as e: verb_print('Errors!!!!', verbose=True) verb_print("ma={} nparam={} ve={} ve_last_5={} \\pm {}".format( ma, nparam, ve_final, ve_last_5, ve_last_5_std), verbose=True) verb_print("ve_val={} ve_train={}".format(ve_val, ve_train), verbose=True) verb_print("ve_val_epoch={} ve_train_epoch={} ve_final_epoch={}".format( ve_val_idx, ve_train_idx, ve_final_idx), verbose=True)
tests/extras/logging/test_color_logger.py
daniel-falk/kedro
2,047
147885
import logging from kedro.extras.logging import ColorHandler def test_color_logger(caplog): log = logging.getLogger(__name__) for handler in log.handlers: log.removeHandler(handler) # pragma: no cover log.addHandler(ColorHandler()) log.info("Test") for record in caplog.records: assert record.levelname == "INFO" assert "Test" in record.msg
dfm/net.py
127t6937/chainer-gan-lib
449
147917
<filename>dfm/net.py import chainer.functions as F import chainer.links as L import numpy as np import chainer class Discriminator(chainer.Chain): def __init__(self, bottom_width=2, ch=512, wscale=0.02): w = chainer.initializers.Normal(wscale) super(Discriminator, self).__init__() with self.init_scope(): self.c0 = L.Convolution2D(3, ch // 16, 3, 1, 1, initialW=w) self.c1 = L.Convolution2D(ch // 16, ch // 8, 4, 2, 1, initialW=w) self.c2 = L.Convolution2D(ch // 8, ch // 4, 4, 2, 1, initialW=w) self.c3 = L.Convolution2D(ch // 4, ch // 2, 4, 2, 1, initialW=w) self.c4 = L.Convolution2D(ch // 2, ch // 1, 4, 2, 1, initialW=w) self.l5 = L.Linear(bottom_width * bottom_width * ch, 1, initialW=w) self.bn1 = L.BatchNormalization(ch // 8) self.bn2 = L.BatchNormalization(ch // 4) self.bn3 = L.BatchNormalization(ch // 2) self.bn4 = L.BatchNormalization(ch // 1, use_gamma=False) def __call__(self, x): h = x h = F.leaky_relu(self.c0(h)) h = F.leaky_relu(self.bn1(self.c1(h))) h = F.leaky_relu(self.bn2(self.c2(h))) h = F.leaky_relu(self.bn3(self.c3(h))) feature = self.bn4(self.c4(h)) h = F.leaky_relu(feature) return feature, self.l5(h) class Denoiser(chainer.Chain): def __init__(self): super(Denoiser, self).__init__() with self.init_scope(): self.l0 = L.Linear(2048, 2048) self.l1 = L.Linear(2048, 2048) self.l2 = L.Linear(2048, 2048) self.l3 = L.Linear(2048, 2048) self.l4 = L.Linear(2048, 2048) self.l5 = L.Linear(2048, 2048) self.l6 = L.Linear(2048, 2048) self.l7 = L.Linear(2048, 2048) self.l8 = L.Linear(2048, 2048) self.l9 = L.Linear(2048, 2048) self.bn0 = L.BatchNormalization(2048) self.bn1 = L.BatchNormalization(2048) self.bn2 = L.BatchNormalization(2048) self.bn3 = L.BatchNormalization(2048) self.bn4 = L.BatchNormalization(2048) self.bn5 = L.BatchNormalization(2048) self.bn6 = L.BatchNormalization(2048) self.bn7 = L.BatchNormalization(2048) self.bn8 = L.BatchNormalization(2048) def __call__(self, x): h = F.reshape(x, (len(x), 2048)) h = F.leaky_relu(self.bn0(self.l0(h))) h = F.leaky_relu(self.bn1(self.l1(h))) h = F.leaky_relu(self.bn2(self.l2(h))) h = F.leaky_relu(self.bn3(self.l3(h))) h = F.leaky_relu(self.bn4(self.l4(h))) h = F.leaky_relu(self.bn5(self.l5(h))) h = F.leaky_relu(self.bn6(self.l6(h))) h = F.leaky_relu(self.bn7(self.l7(h))) h = F.leaky_relu(self.bn8(self.l8(h))) return F.reshape(self.l9(h), (len(x), 512, 2, 2))
app/api/__init__.py
cmyui/gulag
187
147927
# type: ignore from . import ava from . import cho from . import map from . import osu
resnet/nsfw_scratch.py
reckonsys/rsnsfw
515
147968
#-*-coding:utf-8-*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import re from absl import app as absl_app from absl import flags import tensorflow as tf # pylint: disable=g-bad-import-order from resnet import resnet_model from resnet import resnet_run_loop _NUM_CHANNELS = 3 _NUM_CLASSES = 5 # The record is the image plus a one-byte label _NUM_IMAGES = { 'train': 230944, 'validation': 19448, } DATASET_NAME = 'nsfw' _IMAGE_SIZE = 64 ############################################################################### # Data processing ############################################################################### def get_filenames(is_training, data_dir): file_names = [] if is_training: pattern = 'nsfw_train_.*.tfrecord' else: pattern = 'nsfw_validation_.*.tfrecord' for top, dis, files in os.walk(data_dir): for name in files: if re.match(pattern, name): file_names.append(os.path.join(top, name)) return file_names def preprocess_image(image, is_training): """Preprocess a single image of layout [height, width, depth].""" if is_training: # Resize the image to add four extra pixels on each side. image = tf.image.resize_image_with_crop_or_pad( image, _IMAGE_SIZE + 8, _IMAGE_SIZE + 8) # Randomly crop a [_HEIGHT, _WIDTH] section of the image. image = tf.random_crop(image, [_IMAGE_SIZE, _IMAGE_SIZE, _NUM_CHANNELS]) # Randomly flip the image horizontally. image = tf.image.random_flip_left_right(image) # Subtract off the mean and divide by the variance of the pixels. image = tf.image.per_image_standardization(image) return image def parse_record(raw_record, is_training ): image_feature_description = { 'image/height': tf.FixedLenFeature([], tf.int64), 'image/width': tf.FixedLenFeature([], tf.int64), 'image/format': tf.FixedLenFeature([], tf.string), 'image/class/label': tf.FixedLenFeature([], tf.int64), 'image/encoded': tf.FixedLenFeature([], tf.string), } parsed = tf.parse_single_example(raw_record, image_feature_description) image = parsed['image/encoded'] image = tf.image.decode_image(image, channels=3) image = tf.image.convert_image_dtype(image, dtype=tf.float32) image.set_shape([None, None, 3]) image = tf.image.resize_images(image, [_IMAGE_SIZE, _IMAGE_SIZE]) image = preprocess_image(image, is_training) label = parsed['image/class/label'] return image, label def process_record_dataset(dataset, is_training, batch_size, shuffle_buffer, parse_record_fn, num_epochs=1, num_gpus=None, examples_per_epoch=None, dtype=tf.float32): dataset = dataset.prefetch(buffer_size=batch_size) if is_training: dataset = dataset.shuffle(buffer_size=shuffle_buffer) dataset = dataset.repeat(num_epochs) if is_training and num_gpus and examples_per_epoch: total_examples = num_epochs * examples_per_epoch # Force the number of batches to be divisible by the number of devices. # This prevents some devices from receiving batches while others do not, # which can lead to a lockup. This case will soon be handled directly by # distribution strategies, at which point this .take() operation will no # longer be needed. total_batches = total_examples // batch_size // num_gpus * num_gpus dataset.take(total_batches * batch_size) # Parse the raw records into images and labels. Testing has shown that setting # num_parallel_batches > 1 produces no improvement in throughput, since # batch_size is almost always much greater than the number of CPU cores. dataset = dataset.apply( tf.contrib.data.map_and_batch( lambda value: parse_record_fn(value, is_training), batch_size=batch_size, num_parallel_batches=1, drop_remainder=False)) # Operations between the final prefetch and the get_next call to the iterator # will happen synchronously during run time. We prefetch here again to # background all of the above processing work and keep it out of the # critical training path. Setting buffer_size to tf.contrib.data.AUTOTUNE # allows DistributionStrategies to adjust how many batches to fetch based # on how many devices are present. dataset = dataset.prefetch(buffer_size=tf.contrib.data.AUTOTUNE) return dataset def input_fn(is_training, data_dir, batch_size, num_epochs=1, num_gpus=None, dtype=tf.float32): filenames = get_filenames(is_training, data_dir) print(filenames) dataset = tf.data.TFRecordDataset(filenames=filenames) dataset = process_record_dataset( dataset=dataset, is_training=is_training, batch_size=batch_size, shuffle_buffer=500, parse_record_fn=parse_record, num_epochs=num_epochs, num_gpus=num_gpus, examples_per_epoch=_NUM_IMAGES['train'] if is_training else None, dtype=dtype ) return dataset ############################################################################### # Running the model ############################################################################### class Model(resnet_model.Model): """Model class with appropriate defaults for CIFAR-10 data.""" def __init__(self, resnet_size, data_format=None, num_classes=_NUM_CLASSES, resnet_version=resnet_model.DEFAULT_VERSION, dtype=resnet_model.DEFAULT_DTYPE): """These are the parameters that work for CIFAR-10 data. Args: resnet_size: The number of convolutional layers needed in the model. data_format: Either 'channels_first' or 'channels_last', specifying which data format to use when setting up the model. num_classes: The number of output classes needed from the model. This enables users to extend the same model to their own datasets. resnet_version: Integer representing which version of the ResNet network to use. See README for details. Valid values: [1, 2] dtype: The TensorFlow dtype to use for calculations. Raises: ValueError: if invalid resnet_size is chosen """ if resnet_size % 6 != 2: raise ValueError('resnet_size must be 6n + 2:', resnet_size) num_blocks = (resnet_size - 2) // 6 super(Model, self).__init__( resnet_size=resnet_size, bottleneck=False, num_classes=num_classes, num_filters=16, kernel_size=3, conv_stride=1, first_pool_size=None, first_pool_stride=None, block_sizes=[num_blocks] * 3, block_strides=[1, 2, 2], final_size=64, resnet_version=resnet_version, data_format=data_format, dtype=dtype ) def cifar10_model_fn(features, labels, mode, params): """Model function for CIFAR-10.""" features = tf.reshape(features, [-1, _IMAGE_SIZE, _IMAGE_SIZE, _NUM_CHANNELS]) learning_rate_fn = resnet_run_loop.learning_rate_with_decay( batch_size=params['batch_size'], batch_denom=128, num_images=_NUM_IMAGES['train'], boundary_epochs=[10, 20, 30], decay_rates=[1, 0.1, 0.01, 0.001]) # We use a weight decay of 0.0002, which performs better # than the 0.0001 that was originally suggested. weight_decay = 2e-4 # Empirical testing showed that including batch_normalization variables # in the calculation of regularized loss helped validation accuracy # for the CIFAR-10 dataset, perhaps because the regularization prevents # overfitting on the small data set. We therefore include all vars when # regularizing and computing loss during training. def loss_filter_fn(_): return True return resnet_run_loop.resnet_model_fn( features=features, labels=labels, mode=mode, model_class=Model, resnet_size=params['resnet_size'], weight_decay=weight_decay, learning_rate_fn=learning_rate_fn, momentum=0.9, data_format=params['data_format'], resnet_version=params['resnet_version'], loss_scale=params['loss_scale'], loss_filter_fn=loss_filter_fn, dtype=params['dtype'], fine_tune=params['fine_tune'] ) def set_defaults(**kwargs): for key, value in kwargs.items(): flags.FLAGS.set_default(name=key, value=value) def define_flower_flags(): resnet_run_loop.define_resnet_flags() flags.adopt_module_key_flags(resnet_run_loop) set_defaults( data_dir='', model_dir='', resnet_size='32', train_epochs=50, epochs_between_evals=50, batch_size=128) def run_flower(flags_obj): """Run ResNet CIFAR-10 training and eval loop. Args: flags_obj: An object containing parsed flag values. """ input_function = input_fn resnet_run_loop.resnet_main( flags_obj, cifar10_model_fn, input_function, DATASET_NAME, shape=[_IMAGE_SIZE, _IMAGE_SIZE, _NUM_CHANNELS]) def main(_): run_flower(flags.FLAGS) if __name__ == '__main__': tf.logging.set_verbosity(tf.logging.INFO) define_flower_flags() absl_app.run(main)
ppci/arch/mcs6500/registers.py
rakati/ppci-mirror
161
147969
from ..registers import Register, RegisterClass from ... import ir class Accumulator(Register): bitsize = 8 # TODO: hack, this is no register but a stack position! class Temporary(Register): """ On stack temporary """ bitsize = 8 A = Accumulator("A", num=0) r0 = Temporary("r0", 0) r1 = Temporary("r1", 1) r2 = Temporary("r2", 2) r3 = Temporary("r3", 3) r4 = Temporary("r4", 4) Temporary.registers = [r0, r1, r2, r3, r4] register_classes = [ RegisterClass( "reg", [ir.i8, ir.u8, ir.ptr], Temporary, Temporary.registers ) ]
eliot/testing.py
tp-la/eliot
598
147975
""" Utilities to aid unit testing L{eliot} and code that uses it. """ from __future__ import unicode_literals from unittest import SkipTest from functools import wraps from pyrsistent import PClass, field from six import text_type from ._action import ( ACTION_STATUS_FIELD, ACTION_TYPE_FIELD, STARTED_STATUS, FAILED_STATUS, SUCCEEDED_STATUS, ) from ._message import MESSAGE_TYPE_FIELD, TASK_LEVEL_FIELD, TASK_UUID_FIELD from ._output import MemoryLogger from . import _output from .json import EliotJSONEncoder COMPLETED_STATUSES = (FAILED_STATUS, SUCCEEDED_STATUS) def issuperset(a, b): """ Use L{assertContainsFields} instead. @type a: C{dict} @type b: C{dict} @return: Boolean indicating whether C{a} has all key/value pairs that C{b} does. """ aItems = a.items() return all(pair in aItems for pair in b.items()) def assertContainsFields(test, message, fields): """ Assert that the given message contains the given fields. @param test: L{unittest.TestCase} being run. @param message: C{dict}, the message we are checking. @param fields: C{dict}, the fields we expect the message to have. @raises AssertionError: If the message doesn't contain the fields. """ messageSubset = dict( [(key, value) for key, value in message.items() if key in fields] ) test.assertEqual(messageSubset, fields) class LoggedAction(PClass): """ An action whose start and finish messages have been logged. @ivar startMessage: A C{dict}, the start message contents. Also available as C{start_message}. @ivar endMessage: A C{dict}, the end message contents (in both success and failure cases). Also available as C{end_message}. @ivar children: A C{list} of direct child L{LoggedMessage} and L{LoggedAction} instances. """ startMessage = field(mandatory=True) endMessage = field(mandatory=True) children = field(mandatory=True) def __new__(cls, startMessage, endMessage, children): return PClass.__new__( cls, startMessage=startMessage, endMessage=endMessage, children=children ) @property def start_message(self): return self.startMessage @property def end_message(self): return self.endMessage @classmethod def fromMessages(klass, uuid, level, messages): """ Given a task uuid and level (identifying an action) and a list of dictionaries, create a L{LoggedAction}. All child messages and actions will be added as L{LoggedAction} or L{LoggedMessage} children. Note that some descendant messages may be missing if you end up logging to two or more different ILogger providers. @param uuid: The uuid of the task (C{unicode}). @param level: The C{task_level} of the action's start message, e.g. C{"/1/2/1"}. @param messages: A list of message C{dict}s. @return: L{LoggedAction} constructed from start and finish messages for this specific action. @raises: L{ValueError} if one or both of the action's messages cannot be found. """ startMessage = None endMessage = None children = [] levelPrefix = level[:-1] for message in messages: if message[TASK_UUID_FIELD] != uuid: # Different task altogether: continue messageLevel = message[TASK_LEVEL_FIELD] if messageLevel[:-1] == levelPrefix: status = message.get(ACTION_STATUS_FIELD) if status == STARTED_STATUS: startMessage = message elif status in COMPLETED_STATUSES: endMessage = message else: # Presumably a message in this action: children.append(LoggedMessage(message)) elif ( len(messageLevel) == len(levelPrefix) + 2 and messageLevel[:-2] == levelPrefix and messageLevel[-1] == 1 ): # If start message level is [1], [1, 2, 1] implies first # message of a direct child. child = klass.fromMessages(uuid, message[TASK_LEVEL_FIELD], messages) children.append(child) if startMessage is None: raise ValueError("Missing start message") if endMessage is None: raise ValueError( "Missing end message of type " + message.get(ACTION_TYPE_FIELD, "unknown") ) return klass(startMessage, endMessage, children) # PEP 8 variant: from_messages = fromMessages @classmethod def of_type(klass, messages, actionType): """ Find all L{LoggedAction} of the specified type. @param messages: A list of message C{dict}s. @param actionType: A L{eliot.ActionType}, the type of the actions to find, or the type as a C{str}. @return: A C{list} of L{LoggedAction}. """ if not isinstance(actionType, text_type): actionType = actionType.action_type result = [] for message in messages: if ( message.get(ACTION_TYPE_FIELD) == actionType and message[ACTION_STATUS_FIELD] == STARTED_STATUS ): result.append( klass.fromMessages( message[TASK_UUID_FIELD], message[TASK_LEVEL_FIELD], messages ) ) return result # Backwards compat: ofType = of_type def descendants(self): """ Find all descendant L{LoggedAction} or L{LoggedMessage} of this instance. @return: An iterable of L{LoggedAction} and L{LoggedMessage} instances. """ for child in self.children: yield child if isinstance(child, LoggedAction): for descendant in child.descendants(): yield descendant @property def succeeded(self): """ Indicate whether this action succeeded. @return: C{bool} indicating whether the action succeeded. """ return self.endMessage[ACTION_STATUS_FIELD] == SUCCEEDED_STATUS def type_tree(self): """Return dictionary of all child action and message types. Actions become dictionaries that look like C{{<action_type>: [<child_message_type>, <child_action_dict>]}} @return: C{dict} where key is action type, and value is list of child types: either strings for messages, or dicts for actions. """ children = [] for child in self.children: if isinstance(child, LoggedAction): children.append(child.type_tree()) else: children.append(child.message[MESSAGE_TYPE_FIELD]) return {self.startMessage[ACTION_TYPE_FIELD]: children} class LoggedMessage(PClass): """ A message that has been logged. @ivar message: A C{dict}, the message contents. """ message = field(mandatory=True) def __new__(cls, message): return PClass.__new__(cls, message=message) @classmethod def of_type(klass, messages, messageType): """ Find all L{LoggedMessage} of the specified type. @param messages: A list of message C{dict}s. @param messageType: A L{eliot.MessageType}, the type of the messages to find, or the type as a L{str}. @return: A C{list} of L{LoggedMessage}. """ result = [] if not isinstance(messageType, text_type): messageType = messageType.message_type for message in messages: if message.get(MESSAGE_TYPE_FIELD) == messageType: result.append(klass(message)) return result # Backwards compat: ofType = of_type class UnflushedTracebacks(Exception): """ The L{MemoryLogger} had some tracebacks logged which were not flushed. This means either your code has a bug and logged an unexpected traceback. If you expected the traceback then you will need to flush it using L{MemoryLogger.flushTracebacks}. """ def check_for_errors(logger): """ Raise exception if logger has unflushed tracebacks or validation errors. @param logger: A L{MemoryLogger}. @raise L{UnflushedTracebacks}: If any tracebacks were unflushed. """ # Check for unexpected tracebacks first, since that indicates business # logic errors: if logger.tracebackMessages: raise UnflushedTracebacks(logger.tracebackMessages) # If those are fine, validate the logging: logger.validate() def swap_logger(logger): """Swap out the global logging sink. @param logger: An C{ILogger}. @return: The current C{ILogger}. """ previous_logger = _output._DEFAULT_LOGGER _output._DEFAULT_LOGGER = logger return previous_logger def validateLogging( assertion, *assertionArgs, encoder_=EliotJSONEncoder, **assertionKwargs ): """ Decorator factory for L{unittest.TestCase} methods to add logging validation. 1. The decorated test method gets a C{logger} keyword argument, a L{MemoryLogger}. 2. All messages logged to this logger will be validated at the end of the test. 3. Any unflushed logged tracebacks will cause the test to fail. For example: from unittest import TestCase from eliot.testing import assertContainsFields, validateLogging class MyTests(TestCase): def assertFooLogging(self, logger): assertContainsFields(self, logger.messages[0], {"key": 123}) @param assertion: A callable that will be called with the L{unittest.TestCase} instance, the logger and C{assertionArgs} and C{assertionKwargs} once the actual test has run, allowing for extra logging-related assertions on the effects of the test. Use L{None} if you want the cleanup assertions registered but no custom assertions. @param assertionArgs: Additional positional arguments to pass to C{assertion}. @param assertionKwargs: Additional keyword arguments to pass to C{assertion}. @param encoder_: C{json.JSONEncoder} subclass to use when validating JSON. """ def decorator(function): @wraps(function) def wrapper(self, *args, **kwargs): skipped = False kwargs["logger"] = logger = MemoryLogger(encoder=encoder_) self.addCleanup(check_for_errors, logger) # TestCase runs cleanups in reverse order, and we want this to # run *before* tracebacks are checked: if assertion is not None: self.addCleanup( lambda: skipped or assertion(self, logger, *assertionArgs, **assertionKwargs) ) try: return function(self, *args, **kwargs) except SkipTest: skipped = True raise return wrapper return decorator # PEP 8 variant: validate_logging = validateLogging def capture_logging( assertion, *assertionArgs, encoder_=EliotJSONEncoder, **assertionKwargs ): """ Capture and validate all logging that doesn't specify a L{Logger}. See L{validate_logging} for details on the rest of its behavior. """ def decorator(function): @validate_logging( assertion, *assertionArgs, encoder_=encoder_, **assertionKwargs ) @wraps(function) def wrapper(self, *args, **kwargs): logger = kwargs["logger"] previous_logger = swap_logger(logger) def cleanup(): swap_logger(previous_logger) self.addCleanup(cleanup) return function(self, *args, **kwargs) return wrapper return decorator def assertHasMessage(testCase, logger, messageType, fields=None): """ Assert that the given logger has a message of the given type, and the first message found of this type has the given fields. This can be used as the assertion function passed to L{validateLogging} or as part of a unit test. @param testCase: L{unittest.TestCase} instance. @param logger: L{eliot.MemoryLogger} whose messages will be checked. @param messageType: L{eliot.MessageType} indicating which message we're looking for. @param fields: The first message of the given type found must have a superset of the given C{dict} as its fields. If C{None} then fields are not checked. @return: The first found L{LoggedMessage} of the given type, if field validation succeeded. @raises AssertionError: No message was found, or the fields were not superset of given fields. """ if fields is None: fields = {} messages = LoggedMessage.ofType(logger.messages, messageType) testCase.assertTrue(messages, "No messages of type %s" % (messageType,)) loggedMessage = messages[0] assertContainsFields(testCase, loggedMessage.message, fields) return loggedMessage def assertHasAction( testCase, logger, actionType, succeeded, startFields=None, endFields=None ): """ Assert that the given logger has an action of the given type, and the first action found of this type has the given fields and success status. This can be used as the assertion function passed to L{validateLogging} or as part of a unit test. @param testCase: L{unittest.TestCase} instance. @param logger: L{eliot.MemoryLogger} whose messages will be checked. @param actionType: L{eliot.ActionType} or C{str} indicating which message we're looking for. @param succeeded: Expected success status of the action, a C{bool}. @param startFields: The first action of the given type found must have a superset of the given C{dict} as its start fields. If C{None} then fields are not checked. @param endFields: The first action of the given type found must have a superset of the given C{dict} as its end fields. If C{None} then fields are not checked. @return: The first found L{LoggedAction} of the given type, if field validation succeeded. @raises AssertionError: No action was found, or the fields were not superset of given fields. """ if startFields is None: startFields = {} if endFields is None: endFields = {} actions = LoggedAction.ofType(logger.messages, actionType) testCase.assertTrue(actions, "No actions of type %s" % (actionType,)) action = actions[0] testCase.assertEqual(action.succeeded, succeeded) assertContainsFields(testCase, action.startMessage, startFields) assertContainsFields(testCase, action.endMessage, endFields) return action
fhirclient/models/medicinalproductindication_tests.py
carolinarsm/client-py
418
147976
<filename>fhirclient/models/medicinalproductindication_tests.py #!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR 4.0.0-a53ec6ee1b on 2019-05-07. # 2019, SMART Health IT. import os import io import unittest import json from . import medicinalproductindication from .fhirdate import FHIRDate class MedicinalProductIndicationTests(unittest.TestCase): def instantiate_from(self, filename): datadir = os.environ.get('FHIR_UNITTEST_DATADIR') or '' with io.open(os.path.join(datadir, filename), 'r', encoding='utf-8') as handle: js = json.load(handle) self.assertEqual("MedicinalProductIndication", js["resourceType"]) return medicinalproductindication.MedicinalProductIndication(js) def testMedicinalProductIndication1(self): inst = self.instantiate_from("medicinalproductindication-example.json") self.assertIsNotNone(inst, "Must have instantiated a MedicinalProductIndication instance") self.implMedicinalProductIndication1(inst) js = inst.as_json() self.assertEqual("MedicinalProductIndication", js["resourceType"]) inst2 = medicinalproductindication.MedicinalProductIndication(js) self.implMedicinalProductIndication1(inst2) def implMedicinalProductIndication1(self, inst): self.assertEqual(inst.comorbidity[0].coding[0].code, "Hipsurgery") self.assertEqual(inst.comorbidity[0].coding[0].system, "http://ema.europa.eu/example/comorbidity") self.assertEqual(inst.diseaseSymptomProcedure.coding[0].code, "Venousthromboembolismprophylaxis") self.assertEqual(inst.diseaseSymptomProcedure.coding[0].system, "http://ema.europa.eu/example/indicationasdisease-symptom-procedure") self.assertEqual(inst.id, "example") self.assertEqual(inst.intendedEffect.coding[0].code, "PRYLX") self.assertEqual(inst.intendedEffect.coding[0].system, "http://ema.europa.eu/example/intendedeffect") self.assertEqual(inst.meta.tag[0].code, "HTEST") self.assertEqual(inst.meta.tag[0].display, "test health data") self.assertEqual(inst.meta.tag[0].system, "http://terminology.hl7.org/CodeSystem/v3-ActReason") self.assertEqual(inst.population[0].ageRange.low.unit, "a") self.assertEqual(inst.population[0].ageRange.low.value, 18) self.assertEqual(inst.text.status, "generated")
backend/db/test/friend_test.py
sleepingAnt/viewfinder
645
147994
# Copyright 2011 Viewfinder Inc. All Rights Reserved. """Tests for Friend data object. """ __author__ = '<EMAIL> (<NAME>)' import logging import unittest from functools import partial from viewfinder.backend.base import util from viewfinder.backend.base.testing import async_test from viewfinder.backend.db.friend import Friend from base_test import DBBaseTestCase class FriendTestCase(DBBaseTestCase): def testMakeFriends(self): """Creates a bidirectional friendship between two users.""" friend, reverse_friend = self._RunAsync(Friend.MakeFriends, self._client, self._user.user_id, self._user2.user_id) # Check the friends returned from make friends. self.assertEqual(friend.user_id, self._user.user_id) self.assertEqual(friend.friend_id, self._user2.user_id) self.assertEqual(reverse_friend.user_id, self._user2.user_id) self.assertEqual(reverse_friend.friend_id, self._user.user_id) def testOneSidedFriends(self): """Test friendships that are only recognized by one of the users.""" # Create one-sided friendship. self._RunAsync(Friend.MakeFriendAndUpdate, self._client, self._user.user_id, {'user_id': self._user2.user_id, 'nickname': 'Slick'}) # Forward friend should exist. forward_friend = self._RunAsync(Friend.Query, self._client, self._user.user_id, self._user2.user_id, None, must_exist=False) self.assertIsNotNone(forward_friend) # Reverse friend should not exist. reverse_friend = self._RunAsync(Friend.Query, self._client, self._user2.user_id, self._user.user_id, None, must_exist=False) self.assertIsNone(reverse_friend) # MakeFriends should add the bi-directional friendship. forward_friend, reverse_friend = self._RunAsync(Friend.MakeFriends, self._client, self._user.user_id, self._user2.user_id) self.assertIsNotNone(forward_friend) self.assertIsNotNone(reverse_friend)
rpmvenv/extensions/files/__init__.py
oleynikandrey/rpmvenv
150
147999
<reponame>oleynikandrey/rpmvenv """Extensions which provide a files block segment.""" from __future__ import division from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals
plugins/modules/oci_database_management_execution_plan_stats_comparision_facts.py
slmjy/oci-ansible-collection
108
148005
#!/usr/bin/python # Copyright (c) 2020, 2021 Oracle and/or its affiliates. # This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0 # See LICENSE.TXT for details. # GENERATED FILE - DO NOT EDIT - MANUAL CHANGES WILL BE OVERWRITTEN from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["preview"], "supported_by": "community", } DOCUMENTATION = """ --- module: oci_database_management_execution_plan_stats_comparision_facts short_description: Fetches details about a ExecutionPlanStatsComparision resource in Oracle Cloud Infrastructure description: - Fetches details about a ExecutionPlanStatsComparision resource in Oracle Cloud Infrastructure - A SQL tuning task may suggest new execution plan for a SQL. The API returns the stats comparison report for the plans. version_added: "2.9.0" author: Oracle (@oracle) options: managed_database_id: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the Managed Database. type: str required: true sql_tuning_advisor_task_id: description: - The SQL tuning task identifier. This is not the L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm). type: int aliases: ["id"] required: true sql_object_id: description: - The SQL object id for the SQL tuning task. This is not the L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm). type: int required: true execution_id: description: - The execution id for an execution of a SQL tuning task. This is not the L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm). type: int required: true extends_documentation_fragment: [ oracle.oci.oracle ] """ EXAMPLES = """ - name: Get a specific execution_plan_stats_comparision oci_database_management_execution_plan_stats_comparision_facts: # required managed_database_id: "ocid1.manageddatabase.oc1..xxxxxxEXAMPLExxxxxx" sql_tuning_advisor_task_id: 56 sql_object_id: 56 execution_id: 56 """ RETURN = """ execution_plan_stats_comparision: description: - ExecutionPlanStatsComparision resource returned: on success type: complex contains: original: description: - "" returned: on success type: complex contains: plan_type: description: - The type of the plan for the original or the new plan with profile/index etc. returned: on success type: str sample: plan_type_example plan_stats: description: - A map contains the statistics for the SQL execution using the plan. The key of the map is the metric's name. The value of the map is the metric's value. returned: on success type: dict sample: {} plan_status: description: - The status of the execution using the plan. returned: on success type: str sample: COMPLETE modified: description: - "" returned: on success type: complex contains: plan_type: description: - The type of the plan for the original or the new plan with profile/index etc. returned: on success type: str sample: plan_type_example plan_stats: description: - A map contains the statistics for the SQL execution using the plan. The key of the map is the metric's name. The value of the map is the metric's value. returned: on success type: dict sample: {} plan_status: description: - The status of the execution using the plan. returned: on success type: str sample: COMPLETE sample: { "original": { "plan_type": "plan_type_example", "plan_stats": {}, "plan_status": "COMPLETE" }, "modified": { "plan_type": "plan_type_example", "plan_stats": {}, "plan_status": "COMPLETE" } } """ from ansible.module_utils.basic import AnsibleModule from ansible_collections.oracle.oci.plugins.module_utils import oci_common_utils from ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils import ( OCIResourceFactsHelperBase, get_custom_class, ) try: from oci.database_management import SqlTuningClient HAS_OCI_PY_SDK = True except ImportError: HAS_OCI_PY_SDK = False class ExecutionPlanStatsComparisionFactsHelperGen(OCIResourceFactsHelperBase): """Supported operations: get""" def get_required_params_for_get(self): return [ "managed_database_id", "sql_tuning_advisor_task_id", "sql_object_id", "execution_id", ] def get_resource(self): return oci_common_utils.call_with_backoff( self.client.get_execution_plan_stats_comparision, managed_database_id=self.module.params.get("managed_database_id"), sql_tuning_advisor_task_id=self.module.params.get( "sql_tuning_advisor_task_id" ), sql_object_id=self.module.params.get("sql_object_id"), execution_id=self.module.params.get("execution_id"), ) ExecutionPlanStatsComparisionFactsHelperCustom = get_custom_class( "ExecutionPlanStatsComparisionFactsHelperCustom" ) class ResourceFactsHelper( ExecutionPlanStatsComparisionFactsHelperCustom, ExecutionPlanStatsComparisionFactsHelperGen, ): pass def main(): module_args = oci_common_utils.get_common_arg_spec() module_args.update( dict( managed_database_id=dict(type="str", required=True), sql_tuning_advisor_task_id=dict(aliases=["id"], type="int", required=True), sql_object_id=dict(type="int", required=True), execution_id=dict(type="int", required=True), ) ) module = AnsibleModule(argument_spec=module_args) if not HAS_OCI_PY_SDK: module.fail_json(msg="oci python sdk required for this module.") resource_facts_helper = ResourceFactsHelper( module=module, resource_type="execution_plan_stats_comparision", service_client_class=SqlTuningClient, namespace="database_management", ) result = [] if resource_facts_helper.is_get(): result = resource_facts_helper.get() else: resource_facts_helper.fail() module.exit_json(execution_plan_stats_comparision=result) if __name__ == "__main__": main()
update_readme.py
kasetty/til
450
148017
<gh_stars>100-1000 "Run this after build_database.py - it needs tils.db" import pathlib import sqlite_utils import sys import re root = pathlib.Path(__file__).parent.resolve() index_re = re.compile(r"<!\-\- index starts \-\->.*<!\-\- index ends \-\->", re.DOTALL) count_re = re.compile(r"<!\-\- count starts \-\->.*<!\-\- count ends \-\->", re.DOTALL) COUNT_TEMPLATE = "<!-- count starts -->{}<!-- count ends -->" if __name__ == "__main__": db = sqlite_utils.Database(root / "tils.db") by_topic = {} for row in db["til"].rows_where(order_by="created_utc"): by_topic.setdefault(row["topic"], []).append(row) index = ["<!-- index starts -->"] for topic, rows in by_topic.items(): index.append("## {}\n".format(topic)) for row in rows: index.append( "* [{title}]({url}) - {date}".format( date=row["created"].split("T")[0], **row ) ) index.append("") if index[-1] == "": index.pop() index.append("<!-- index ends -->") if "--rewrite" in sys.argv: readme = root / "README.md" index_txt = "\n".join(index).strip() readme_contents = readme.open().read() rewritten = index_re.sub(index_txt, readme_contents) rewritten = count_re.sub(COUNT_TEMPLATE.format(db["til"].count), rewritten) readme.open("w").write(rewritten) else: print("\n".join(index))
proxy/quickstart/send-message/send-message.6.x.py
Tshisuaka/api-snippets
234
148020
# Get the Python helper library from https://twilio.com/docs/libraries/python import os from twilio.rest import Client # Get your Account SID and Auth Token from https://twilio.com/console # To set up environmental variables, see http://twil.io/secure account = os.environ['TWILIO_ACCOUNT_SID'] token = os.environ['TWILIO_AUTH_TOKEN'] client = Client(account, token) message_interaction = client.proxy \ .services("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ .sessions("KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ .participants("KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ .message_interactions.create(body="Reply to this message to chat!") print(message_interaction.sid)
tests/test_star_wars_connections.py
artofhuman/graphql-relay-py
124
148091
<reponame>artofhuman/graphql-relay-py from graphql import graphql_sync from .star_wars_schema import StarWarsSchema as schema def describe_star_wars_connections(): def fetches_the_first_ship_of_the_rebels(): source = """ { rebels { name, ships(first: 1) { edges { node { name } } } } } """ expected = { "rebels": { "name": "Alliance to Restore the Republic", "ships": {"edges": [{"node": {"name": "X-Wing"}}]}, } } result = graphql_sync(schema, source) assert result == (expected, None) def fetches_the_first_two_ships_of_the_rebels_with_a_cursor(): source = """ { rebels { name, ships(first: 2) { edges { cursor, node { name } } } } } """ expected = { "rebels": { "name": "Alliance to Restore the Republic", "ships": { "edges": [ { "cursor": "YXJyYXljb25uZWN0aW9uOjA=", "node": {"name": "X-Wing"}, }, { "cursor": "YXJyYXljb25uZWN0aW9uOjE=", "node": {"name": "Y-Wing"}, }, ] }, } } result = graphql_sync(schema, source) assert result == (expected, None) def fetches_the_next_three_ships_of_the_rebels_with_a_cursor(): source = """ { rebels { name, ships(first: 3 after: "YXJyYXljb25uZWN0aW9uOjE=") { edges { cursor, node { name } } } } } """ expected = { "rebels": { "name": "Alliance to Restore the Republic", "ships": { "edges": [ { "cursor": "YXJyYXljb25uZWN0aW9uOjI=", "node": {"name": "A-Wing"}, }, { "cursor": "YXJyYXljb25uZWN0aW9uOjM=", "node": {"name": "Millenium Falcon"}, }, { "cursor": "YXJyYXljb25uZWN0aW9uOjQ=", "node": {"name": "Home One"}, }, ] }, } } result = graphql_sync(schema, source) assert result == (expected, None) def fetches_no_ships_of_the_rebels_at_the_end_of_connection(): source = """ { rebels { name, ships(first: 3 after: "YXJyYXljb25uZWN0aW9uOjQ=") { edges { cursor, node { name } } } } } """ expected = { "rebels": { "name": "Alliance to Restore the Republic", "ships": {"edges": []}, } } result = graphql_sync(schema, source) assert result == (expected, None) def identifies_the_end_of_the_list(): source = """ { rebels { name, originalShips: ships(first: 2) { edges { node { name } } pageInfo { hasNextPage } } moreShips: ships(first: 3 after: "YXJyYXljb25uZWN0aW9uOjE=") { edges { node { name } } pageInfo { hasNextPage } } } } """ expected = { "rebels": { "name": "Alliance to Restore the Republic", "originalShips": { "edges": [ { "node": {"name": "X-Wing"}, }, { "node": {"name": "Y-Wing"}, }, ], "pageInfo": {"hasNextPage": True}, }, "moreShips": { "edges": [ { "node": {"name": "A-Wing"}, }, { "node": {"name": "<NAME>"}, }, { "node": {"name": "Home One"}, }, ], "pageInfo": {"hasNextPage": False}, }, }, } result = graphql_sync(schema, source) assert result == (expected, None)
setup.py
xeddmc/transformationInvariantImageSearch
285
148110
<reponame>xeddmc/transformationInvariantImageSearch<gh_stars>100-1000 #!/usr/bin/env python from setuptools import setup, find_packages """ TODO - copy or link `python` folder to `transformation_invariant_image_search` """ def readme(): with open('README.md') as f: return f.read() setup( name='transformation-invariant-image-search', version='0.0.1', description='a reverse image search algorithm which performs 2D affine ' 'transformation-invariant partial image-matching in sublinear time with ' 'respect to the number of images in our database.', long_description=readme(), long_description_content_type="text/markdown", author='<NAME>', author_email='<EMAIL>', maintainer='<NAME>', maintainer_email='<EMAIL>', license='MIT', url='https://github.com/pippy360/transformationInvariantImageSearch', packages=find_packages(), include_package_data=True, zip_safe=False, python_requires='>=3.6', install_requires=[ 'hiredis', 'numpy', 'redis', 'scikit-learn', 'scipy', 'tqdm>=4.29.1', ], entry_points={ 'console_scripts': [ 'transformation-invariant-image-search = transformation_invariant_image_search.main:main'] }, classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Internet :: WWW/HTTP :: Indexing/Search', 'Topic :: Utilities' ] )
release/stubs.min/Autodesk/Revit/DB/Analysis_parts/EnergyAnalysisDetailModelOptions.py
htlcnn/ironpython-stubs
182
148112
class EnergyAnalysisDetailModelOptions(object,IDisposable): """ Options that govern the calculations for the generation of the energy analysis detail model. EnergyAnalysisDetailModelOptions() """ def Dispose(self): """ Dispose(self: EnergyAnalysisDetailModelOptions) """ pass def ReleaseUnmanagedResources(self,*args): """ ReleaseUnmanagedResources(self: EnergyAnalysisDetailModelOptions,disposing: bool) """ pass def __enter__(self,*args): """ __enter__(self: IDisposable) -> object """ pass def __exit__(self,*args): """ __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """ pass def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __repr__(self,*args): """ __repr__(self: object) -> str """ pass EnergyModelType=property(lambda self: object(),lambda self,v: None,lambda self: None) """It indicates whether the energy model is based on rooms/spaces or building elements. Get: EnergyModelType(self: EnergyAnalysisDetailModelOptions) -> EnergyModelType Set: EnergyModelType(self: EnergyAnalysisDetailModelOptions)=value """ ExportMullions=property(lambda self: object(),lambda self,v: None,lambda self: None) """Indicates if to specify the setting for exporting mullions. Get: ExportMullions(self: EnergyAnalysisDetailModelOptions) -> bool Set: ExportMullions(self: EnergyAnalysisDetailModelOptions)=value """ IncludeShadingSurfaces=property(lambda self: object(),lambda self,v: None,lambda self: None) """Indicates if to set and get the setting for if shading surfaces should be included. Get: IncludeShadingSurfaces(self: EnergyAnalysisDetailModelOptions) -> bool Set: IncludeShadingSurfaces(self: EnergyAnalysisDetailModelOptions)=value """ IsValidObject=property(lambda self: object(),lambda self,v: None,lambda self: None) """Specifies whether the .NET object represents a valid Revit entity. Get: IsValidObject(self: EnergyAnalysisDetailModelOptions) -> bool """ SimplifyCurtainSystems=property(lambda self: object(),lambda self,v: None,lambda self: None) """Indicates if to specify the setting for simplified curtain systems. Get: SimplifyCurtainSystems(self: EnergyAnalysisDetailModelOptions) -> bool Set: SimplifyCurtainSystems(self: EnergyAnalysisDetailModelOptions)=value """ Tier=property(lambda self: object(),lambda self,v: None,lambda self: None) """Level of computation for energy analysis model. Get: Tier(self: EnergyAnalysisDetailModelOptions) -> EnergyAnalysisDetailModelTier Set: Tier(self: EnergyAnalysisDetailModelOptions)=value """
controle_estoque/Crud/CrudCatAReceber.py
jucimar1/controleEstoque
134
148115
# -*- coding: utf-8 -*- from sqlalchemy.exc import IntegrityError from sqlalchemy import desc from Crud.core import Conexao from Crud.Models import CatAReceber class CrudCatAReceber(object): def __init__(self, id="", categoriaReceber="", query=""): self.id = id self.categoriaReceber = categoriaReceber self.query = query # Recebendo ultimo Id inserido def lastIdCatAReceber(self): try: # Abrindo Sessao conecta = Conexao() sessao = conecta.Session() # Query ultimo = sessao.query(CatAReceber.id).order_by( desc(CatAReceber.id)).limit(1).first() self.id = ultimo.id + 1 # Fechando a conexao sessao.close() except: self.id = 1 return self.id # Cadastrando categoria a receber def inseriCatAReceber(self): try: # Abrindo Sessao conecta = Conexao() sessao = conecta.Session() # Query row = CatAReceber( id=self.id, categoria_a_receber=self.categoriaReceber ) # Add Query na sessao sessao.add(row) # Executando a query sessao.commit() # Fechando a Conexao sessao.close() except IntegrityError: self.updateCatAReceber() # Update categoria a Pagar def updateCatAReceber(self): try: # Abrindo Sessao conecta = Conexao() sessao = conecta.Session() # Selecionando id row = sessao.query(CatAReceber).get(self.id) # Novos Valores row.categoria_a_receber = self.categoriaReceber # Executando a query sessao.commit() # Fechando a Conexao sessao.close() except IntegrityError as err: print(err) # Listando todas as categorias def listaCatAReceber(self): try: # Abrindo Sessao conecta = Conexao() sessao = conecta.Session() # Query self.query = sessao.query(CatAReceber).all() # Convertendo variaveis em lista self.id = [] self.categoriaReceber = [] # Salvando resultado em suas lisats for row in self.query: self.id.append(row.id) self.categoriaReceber.append(row.categoria_a_receber) # Fechando a Conexao sessao.close() except IntegrityError as err: print(err)
Chapter02/Python 2.7/single_neuron_model_1.py
littlealexchen/Deep-Learning-with-TensorFlow-master
194
148123
import tensorflow as tf weight = tf.Variable(1.0,name="weight") input_value = tf.constant(0.5,name="input_value") expected_output = tf.constant(0.0,name="expected_output") model = tf.multiply(input_value,weight,"model") loss_function = tf.pow(expected_output - model,2,name="loss_function") optimizer = tf.train.GradientDescentOptimizer(0.025).minimize(loss_function) for value in [input_value,weight,expected_output,model,loss_function]: tf.summary.scalar(value.op.name,value) summaries = tf.summary.merge_all() sess = tf.Session() summary_writer = tf.summary.FileWriter('log_simple_stats',sess.graph) sess.run(tf.global_variables_initializer()) for i in range(100): summary_writer.add_summary(sess.run(summaries),i) sess.run(optimizer)
load.py
pjialin/pyproxy-async
133
148140
<filename>load.py<gh_stars>100-1000 """ 从文件中加载 IP 列表 """ import asyncio import os import sys import aiohttp from src.app.ip_get import IPGet from src.app.main import Logger async def main(): argv = None if len(sys.argv) > 1: argv = sys.argv[1] if argv and argv.find('://') > 0: return await load_from_url(argv) res = os.listdir('.') ip_file_lists = [name for name in res if name.find('.ip.txt') > 0] if argv: if argv not in ip_file_lists: Logger.error('file %s doesn\'t exists' % argv) return else: ip_file_lists = [argv] for fn in ip_file_lists: await load_file(fn) async def load_file(f_path): with open(f_path) as f: ips = [] for ip in f.readlines(): if ip and ip.find(':') and ip.find('#') < 0: ip = ip.strip() ips.append(ip) if ips: Logger.info('Find ip count %d' % len(ips)) await IPGet.push_to_pool(ips) async def load_from_url(url: str): import re headers = { 'User-Agent': get_user_agent() } async with aiohttp.ClientSession(headers=headers) as session: async with session.get(url) as resp: text = await resp.text() matched = re.findall(r'(?:\d{1,3}\.){3}\d{1,3}:\d+', text) ips = [] for ip in matched: if ip and ip.find(':') and ip.find('#') < 0: ip = ip.strip() ips.append(ip) if ips: Logger.info('Find ip count %d' % len(ips)) await IPGet.push_to_pool(ips) def get_user_agent() -> str: import random return 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%d.0.3770.80 Safari/537.36' % random.randint( 70, 76) if __name__ == '__main__': loop = asyncio.get_event_loop() tasks = [main()] loop.run_until_complete(asyncio.wait(tasks))
EC2 Auto Clean Room Forensics/Lambda-Functions/sendIsolationNotification.py
ir4n6/aws-security-automation
535
148155
<reponame>ir4n6/aws-security-automation # MIT No Attribution # 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. # 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. import boto3 import json import logging import os from base64 import b64decode from urllib.request import Request, urlopen from urllib.error import URLError, HTTPError client = boto3.client('s3') HOOK_URL = os.environ['HookUrl'] # The Slack channel to send a message to stored in the slackChannel environment variable SLACK_CHANNEL = os.environ['SlackChannel'] logger = logging.getLogger() logger.setLevel(logging.INFO) def lambda_handler(event, context): instanceID = event['instanceID'] targetGroupArn = event['targetGroupArn'] slack_message_text = formatMyMessage(instanceID, targetGroupArn) # slack_message_text = response req = Request(HOOK_URL, json.dumps(slack_message_text).encode('utf-8')) try: response = urlopen(req) response.read() logger.info("Message posted to %s", SLACK_CHANNEL) except HTTPError as e: logger.error("Request failed: %d %s", e.code, e.reason) except URLError as e: logger.error("Server connection failed: %s", e.reason) return event def formatMyMessage(instanceID, targetGroupArn): slack_message = { "attachments": [ { "fallback": "Required plain-text summary of the attachment.", "color": "#b7121a", "title": "High Alert!! \n Security Incident detected \n Instance Isolated due to security incident detected by guard duty from ALB : " + instanceID , "text": "", "fields":[{ "value": "Next Steps : " + '\n 1. Snapshot of the volume will be created \n 2. Snapshot will be mounted into volume for Forsensic Analysis \n 3. New Forensic Instance will be created and the volume will be mounted for forensic analysis \n 4. Forensic report will sent to security channel' }, { "value": "Instance under isolation: " + instanceID }, { "value": "TargetGroup ARN where instance is drained from : " + targetGroupArn }] } ] } return slack_message
Tensile/ReplacementKernels.py
cgmb/Tensile
116
148166
<filename>Tensile/ReplacementKernels.py<gh_stars>100-1000 ################################################################################ # Copyright 2020 Advanced Micro Devices, Inc. All rights reserved. # # 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 cop- # ies 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 IM- # PLIED, 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 CONNE- # CTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ################################################################################ from .Common import globalParameters import os class ReplacementKernels: def __init__(self, dirpath, codeObjectVersion): self.dirpath = dirpath self.codeObjectVersion = codeObjectVersion self._cache = None @property def marker(self): if self.codeObjectVersion == 'V3': return '.amdhsa_kernel' return '.amdgpu_hsa_kernel' def getKernelName(self, filename): marker = self.marker try: with open(filename, 'r') as f: for line in f: if line.startswith(marker): return line[len(marker):].strip() except Exception: print(filename) raise raise RuntimeError("Could not parse kernel name from {}".format(filename)) @property def cache(self): if not self._cache: self._cache = self.generateCache() return self._cache def populateCache(self): _ = self.cache def generateCache(self): cache = {} for filename in os.listdir(self.dirpath): if filename.endswith('.txt'): filepath = os.path.join(self.dirpath, filename) kernelName = self.getKernelName(filepath) if kernelName in cache: raise RuntimeError("Duplicate replacement kernels. Kernel name: {}, file names: {}, {}".format(kernelName, cache[kernelName], filepath)) cache[kernelName] = filepath return cache def get(self, kernelName): if kernelName in self.cache: return self.cache[kernelName] return None @classmethod def Directory(cls): scriptDir = os.path.dirname(os.path.realpath(__file__)) dirName = 'ReplacementKernels' if globalParameters['CodeObjectVersion'] == 'V3': dirName += '-cov3' return os.path.join(scriptDir, dirName) _instance = None @classmethod def Instance(cls): if cls._instance: return cls._instance return cls(cls.Directory(), globalParameters["CodeObjectVersion"]) @classmethod def Get(cls, kernelName): return cls.Instance().get(kernelName)
malwareconfig/decoders/blackshades.py
BA7JCM/RATDecoders
905
148172
<filename>malwareconfig/decoders/blackshades.py import re import binascii from malwareconfig import crypto from malwareconfig.common import Decoder from malwareconfig.common import string_printable prng_seed = 0 class BlackShades(Decoder): decoder_name = "BlackShades" decoder__version = 1 decoder_author = "@botnet_hunter, @kevthehermit" decoder_description = "BlackShades Decoder" def __init__(self): self.config = {} @staticmethod def is_valid_config(config): if config[:3] != "\x0c\x0c\x0c": return False if config.count("\x0C\x0C\x0C") < 15: return False return True @staticmethod def get_next_rng_value(): global prng_seed prng_seed = ((prng_seed * 1140671485 + 12820163) & 0xffffff) return int(prng_seed / 65536) @staticmethod def decrypt_configuration(hex): global prng_seed hex = hex.decode('utf-8') ascii = binascii.unhexlify(hex) tail = ascii[0x20:] pre_check = [] for x in range(3): pre_check.append(tail[x] ^ 0x0c) for x in range(0xffffff): prng_seed = x if BlackShades.get_next_rng_value() != pre_check[0] or BlackShades.get_next_rng_value() != pre_check[1] or BlackShades.get_next_rng_value() != pre_check[2]: continue prng_seed = x config_bytes = [] for c in tail: config_bytes.append(chr(c ^ int(BlackShades.get_next_rng_value()))) config = "".join(config_bytes) if BlackShades.is_valid_config(config): return config.split("\x0c\x0c\x0c") return None def extract_config(self): file_data = self.file_info.file_data config_pattern = re.findall(b'[0-9a-fA-F]{154,}', file_data) for s in config_pattern: if (len(s) % 2) == 1: s = s[:-1] return s @staticmethod def config_parser(config): config_dict = {} config_dict['Domain'] = config[1] config_dict['Client Control Port'] = config[2] config_dict['Client Transfer Port'] = config[3] config_dict['Campaign ID'] = config[4] config_dict['File Name'] = config[5] config_dict['Install Path'] = config[6] config_dict['Registry Key'] = config[7] config_dict['ActiveX Key'] = config[8] config_dict['Install Flag'] = config[9] config_dict['Hide File'] = config[10] config_dict['Melt File'] = config[11] config_dict['Delay'] = config[12] config_dict['USB Spread'] = config[13] config_dict['Mutex'] = config[14] config_dict['Log File'] = config[15] config_dict['Folder Name'] = config[16] config_dict['Smart DNS'] = config[17] config_dict['Protect Process'] = config[18] return config_dict def get_config(self): """ This is the main entry :return: """ # Extract Config config_data = self.extract_config() # Decrypt The Config clear_config = self.decrypt_configuration(config_data) # Parse Config config_dict = BlackShades.config_parser(clear_config) # Set the config to the class for use self.config = config_dict
source-of-truth/get_from_netbox.py
fallenfuzz/netdevops_demos
104
148174
import pynetbox import os import ipaddress netbox_token = os.getenv("NETBOX_TOKEN") netbox_url = os.getenv("NETBOX_URL") site_name = os.getenv("NETBOX_SITE") tenant_name = os.getenv("NETBOX_TENANT") netbox = pynetbox.api(netbox_url, token=netbox_token) tenant = netbox.tenancy.tenants.get(name=tenant_name) mgmt_tenant = netbox.tenancy.tenants.get(name="Management") site = netbox.dcim.sites.get(name=site_name) prod_vlan_group = netbox.ipam.vlan_groups.get( site_id=site.id, name="Production" ) # Get devices for site devices = netbox.dcim.devices.filter(site_id=site.id, tenant_id=tenant.id) # Fill in details for device in devices: device.interfaces = netbox.dcim.interfaces.filter(device_id=device.id) for interface in device.interfaces: interface.ip_addresses = netbox.ipam.ip_addresses.filter( interface_id=interface.id ) for ip_address in interface.ip_addresses: ip_address.ip = ipaddress.ip_address( ip_address.address.split("/")[0] ) ip_address.network = ipaddress.ip_network( ip_address.address, strict=False ) # Get VLAN Info from Netbox vlans = netbox.ipam.vlans.filter(site_id=site.id, group_id=prod_vlan_group.id) # Retrieve Prefixes for VLANs for vlan in vlans: try: vlan.prefix = netbox.ipam.prefixes.get(vlan_id=vlan.id) except Exception as e: print(e) # print("VLAN ID: {} Name {}".format(vlan.vid, vlan.name))
tests/r/test_animals.py
hajime9652/observations
199
148175
from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.animals import animals def test_animals(): """Test module animals.py by downloading animals.csv and testing shape of extracted data has 20 rows and 6 columns """ test_path = tempfile.mkdtemp() x_train, metadata = animals(test_path) try: assert x_train.shape == (20, 6) except: shutil.rmtree(test_path) raise()
conanfile.py
MasterMann/argparse
1,101
148256
<reponame>MasterMann/argparse from conans import ConanFile class ArgparseConan(ConanFile): name = "argparse" version = "1.0" exports_sources = "include/argparse.hpp" no_copy_source = True def package(self): self.copy("argparse.hpp")
pydis_site/apps/resources/utils.py
ethansocal/site
700
148264
import typing as t from pathlib import Path import yaml def get_resources(path: Path) -> t.List[t.Dict]: """Loads resource YAMLs from provided path.""" resources = [] for item in path.iterdir(): if item.is_file() and item.suffix == ".yaml" and item.name != "_category_info.yaml": resources.append(yaml.safe_load(item.read_text())) return resources def get_subcategories(path: Path) -> t.List[t.Dict]: """Loads resources subcategories with their resources by provided path.""" subcategories = [] for item in path.iterdir(): if item.is_dir() and item.joinpath("_category_info.yaml").exists(): subcategories.append({ "category_info": { **yaml.safe_load( item.joinpath("_category_info.yaml").read_text() ), "raw_name": item.name }, "resources": [ yaml.safe_load(subitem.read_text()) for subitem in item.iterdir() if ( subitem.is_file() and subitem.suffix == ".yaml" and subitem.name != "_category_info.yaml" ) ] }) return subcategories
ibis/backends/pandas/__init__.py
rohankumardubey/ibis
986
148270
import pandas as pd import toolz import ibis.common.exceptions as com import ibis.config import ibis.expr.schema as sch import ibis.expr.types as ir from ibis.backends.base import BaseBackend from .client import PandasDatabase, PandasTable, ibis_schema_to_pandas class BasePandasBackend(BaseBackend): """ Base class for backends based on pandas. """ def do_connect(self, dictionary): """Construct a client from a dictionary of DataFrames. Parameters ---------- dictionary : dict Returns ------- Backend """ # register dispatchers from . import execution # noqa F401 from . import udf # noqa F401 self.dictionary = dictionary def from_dataframe(self, df, name='df', client=None): """ convenience function to construct an ibis table from a DataFrame Parameters ---------- df : DataFrame name : str, default 'df' client : Backend, optional client dictionary will be mutated with the name of the DataFrame, if not provided a new client is created Returns ------- Table """ if client is None: return self.connect({name: df}).table(name) client.dictionary[name] = df return client.table(name) def register_options(self): ibis.config.register_option( 'enable_trace', False, f'Whether enable tracing for {self.name} execution. ' 'See ibis.{self.name}.trace for details.', validator=ibis.config.is_bool, ) @property def version(self) -> str: return pd.__version__ @property def current_database(self): raise NotImplementedError('pandas backend does not support databases') def list_databases(self, like=None): raise NotImplementedError('pandas backend does not support databases') def list_tables(self, like=None, database=None): return self._filter_with_like(list(self.dictionary.keys()), like) def table(self, name: str, schema: sch.Schema = None): df = self.dictionary[name] schema = sch.infer(df, schema=schema) return self.table_class(name, schema, self).to_expr() def database(self, name=None): return self.database_class(name, self) def load_data(self, table_name, obj, **kwargs): # kwargs is a catch all for any options required by other backends. self.dictionary[table_name] = obj def get_schema(self, table_name, database=None): return sch.infer(self.dictionary[table_name]) def compile(self, expr, *args, **kwargs): return expr class Backend(BasePandasBackend): name = 'pandas' database_class = PandasDatabase table_class = PandasTable def execute(self, query, params=None, limit='default', **kwargs): from .core import execute_and_reset if limit != 'default': raise ValueError( 'limit parameter to execute is not yet implemented in the ' 'pandas backend' ) if not isinstance(query, ir.Expr): raise TypeError( "`query` has type {!r}, expected ibis.expr.types.Expr".format( type(query).__name__ ) ) return execute_and_reset(query, params=params, **kwargs) def create_table(self, table_name, obj=None, schema=None): """Create a table.""" if obj is None and schema is None: raise com.IbisError('Must pass expr or schema') if obj is not None: df = pd.DataFrame(obj) else: dtypes = ibis_schema_to_pandas(schema) df = schema.apply_to( pd.DataFrame(columns=list(map(toolz.first, dtypes))) ) self.dictionary[table_name] = df
tests/test-cases/basic/mnode_case.py
SMAT-Lab/Scalpel
102
148323
<reponame>SMAT-Lab/Scalpel<gh_stars>100-1000 from X import A from X import B from X.C import C2 from Y import D as d from .. import Test def main(a, b): #def main(a, b, x=10, y=10, z = 10): AA(a,b) return 0 def AA(a,b): BB() CC() x = d.xx() return 0 def BB(a,b): CC() y = 10 return 0 def CC(a,b): Test.fun(a,b) z = 10 return 0 class Test2(Test): def __init__(self, a, b, x=10, y=10, z=10): return 0 def fun(self, x,y,k=10, s=10): A.xx(x,y) return 0 class Test3: class Test4: def __init__(self, a, b, x=10, y=10, z=10): return 0 def __init__(self, a, b, x=10, y=10, z=10): return 0 def fun2(self, x,y,k=10, s=10): Test4(1,2) return 0
RecoVertex/BeamSpotProducer/test/BeamFit_LumiBased_NewAlignWorkflow.py
ckamtsikis/cmssw
852
148337
import FWCore.ParameterSet.Config as cms process = cms.Process("BSworkflow") process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring( "/store/express/Run2015A/StreamExpress/ALCARECO/TkAlMinBias-Express-v1/000/246/959/00000/14174DF2-490A-E511-9862-02163E0143E9.root", ) ) process.load("FWCore.MessageLogger.MessageLogger_cfi") process.MessageLogger.cerr.FwkReport = cms.untracked.PSet( reportEvery = cms.untracked.int32(10000), ) process.MessageLogger.debugModules = ['BeamSpotAnalyzer'] process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) process.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) ) process.load("RecoVertex.BeamSpotProducer.BeamSpot_cfi") process.load("Configuration.StandardSequences.MagneticField_cff") process.load('Configuration.Geometry.GeometryRecoDB_cff') process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff") # this GT is for the Express, to be consistent with the file above # in general this GT should be for the ReReco process.GlobalTag.globaltag = 'GR_E_V48' ## Track refit process.load("RecoTracker.TrackProducer.TrackRefitters_cff") # remove the following lines if you run on RECO files process.TrackRefitter.src = 'ALCARECOTkAlMinBias' process.TrackRefitter.NavigationSchool = '' ## PV refit process.load("TrackingTools.TransientTrack.TransientTrackBuilder_cfi") from RecoVertex.PrimaryVertexProducer.OfflinePrimaryVertices_cfi import offlinePrimaryVertices process.offlinePrimaryVerticesFromRefittedTrks = offlinePrimaryVertices.clone() process.offlinePrimaryVerticesFromRefittedTrks.TrackLabel = cms.InputTag("TrackRefitter") process.offlinePrimaryVerticesFromRefittedTrks.vertexCollections.maxDistanceToBeam = 1 process.offlinePrimaryVerticesFromRefittedTrks.TkFilterParameters.maxNormalizedChi2 = 20 process.offlinePrimaryVerticesFromRefittedTrks.TkFilterParameters.minSiliconLayersWithHits = 5 process.offlinePrimaryVerticesFromRefittedTrks.TkFilterParameters.maxD0Significance = 5.0 process.offlinePrimaryVerticesFromRefittedTrks.TkFilterParameters.minPixelLayersWithHits = 2 ## BeamSpot fit process.load("RecoVertex.BeamSpotProducer.d0_phi_analyzer_cff") process.d0_phi_analyzer.BeamFitter.WriteAscii = True process.d0_phi_analyzer.BeamFitter.AsciiFileName = 'BeamFit_LumiBased_NewAlignWorkflow_alcareco.txt' process.d0_phi_analyzer.BeamFitter.AppendRunToFileName = False process.d0_phi_analyzer.BeamFitter.InputBeamWidth = -1 process.d0_phi_analyzer.BeamFitter.MaximumImpactParameter = 1.0 process.d0_phi_analyzer.BeamFitter.MaximumNormChi2 = 10 process.d0_phi_analyzer.BeamFitter.MinimumInputTracks = 50 process.d0_phi_analyzer.BeamFitter.MinimumPixelLayers = -1 process.d0_phi_analyzer.BeamFitter.MinimumPt = 1.0 process.d0_phi_analyzer.BeamFitter.MinimumTotalLayers = 6 process.d0_phi_analyzer.BeamFitter.OutputFileName = 'BeamFit_LumiBased_Workflow_alcareco.root' process.d0_phi_analyzer.BeamFitter.TrackAlgorithm = cms.untracked.vstring() process.d0_phi_analyzer.BeamFitter.TrackCollection = 'TrackRefitter' process.d0_phi_analyzer.BeamFitter.SaveFitResults = True process.d0_phi_analyzer.BeamFitter.SaveNtuple = False process.d0_phi_analyzer.BeamFitter.SavePVVertices = True process.d0_phi_analyzer.PVFitter.Apply3DFit = True process.d0_phi_analyzer.PVFitter.minNrVerticesForFit = 10 process.d0_phi_analyzer.PVFitter.nSigmaCut = 50.0 process.d0_phi_analyzer.PVFitter.VertexCollection = 'offlinePrimaryVerticesFromRefittedTrks' process.d0_phi_analyzer.BSAnalyzerParameters.fitEveryNLumi = 1 process.d0_phi_analyzer.BSAnalyzerParameters.resetEveryNLumi = 1 process.p = cms.Path(process.offlineBeamSpot + process.TrackRefitter + process.offlinePrimaryVerticesFromRefittedTrks + process.d0_phi_analyzer)
rig/utils.py
fsanges/glTools
165
148340
<reponame>fsanges/glTools import maya.cmds as mc import glTools.utils.channelState import glTools.utils.defaultAttrState import glTools.utils.attribute import glTools.utils.base import glTools.utils.cleanup import glTools.utils.colorize import glTools.utils.component import glTools.utils.connection import glTools.utils.deformer import glTools.utils.joint import glTools.utils.mathUtils import glTools.utils.matrix import glTools.utils.mesh import glTools.utils.namespace import glTools.utils.primvar import glTools.utils.reference import glTools.utils.selection import glTools.utils.shape import glTools.utils.skinCluster import glTools.utils.stringUtils import glTools.utils.transform import types import ast def tagCtrl(control,ctrlLod='primary',module=None,category=None): ''' Tag transform with control data. Also sets the "rotateOrder" attribute as keyable. @param control: Control to tag @type control: str @param ctrlLod: Control LOD. Valid values include "primary", "secondary", "tertiary" and "costume". @type ctrlLod: str @param module: Control module. If empty, module attribute is skipped. @type module: str or None @param category: Control category classification. Used to specify general purpose multi module class groupings (ie "face"). If empty, module attribute is skipped. @type category: str or None ''' # ========== # - Checks - # ========== # Check Control if not mc.objExists(control): raise Exception('Control object "'+control+'" does not exist!') # Check Control LOD ctrlLodList = ['primary','secondary','tertiary','allTrans','face','costume','hair','prop','misc'] if not ctrlLod in ctrlLodList: raise Exception('Invalid control LOD "'+ctrlLod+'"!') ctrlLodIndex = ctrlLodList.index(ctrlLod) # =================== # - Tag Control LOD - # =================== lodAttr = 'ctrlLod' if not mc.objExists(control+'.'+lodAttr): mc.addAttr(control,ln=lodAttr,at='enum',en=':'.join(ctrlLodList)) mc.setAttr(control+'.'+lodAttr,ctrlLodIndex) # ====================== # - Tag Control Module - # ====================== if module: moduleAttr = 'ctrlModule' if not mc.objExists(control+'.'+moduleAttr): mc.addAttr(control,ln=moduleAttr,dt='string') else: mc.setAttr(control+'.'+moduleAttr,l=False) mc.setAttr(control+'.'+moduleAttr,module,type='string') mc.setAttr(control+'.'+moduleAttr,l=True) # ======================== # - Tag Control Category - # ======================== if category: categoryAttr = 'ctrlCategory' if not mc.objExists(control+'.'+categoryAttr): mc.addAttr(control,ln=categoryAttr,dt='string') mc.setAttr(control+'.'+categoryAttr,category,type='string') mc.setAttr(control+'.'+categoryAttr,l=True) # ================= # - Clean Control - # ================= # Set Rotate Order Keyable try: mc.setAttr(control+'.ro',cb=True) except: pass # Hide Joint Attrs if mc.objExists(control+'.radius'): mc.setAttr(control+'.radius',k=False,cb=False) if mc.objExists(control+'.liw'): mc.setAttr(control+'.liw',k=False,cb=False) # ================= # - Return Result - # ================= return control def tagBindJoint(joint,bind=True): ''' Tag joint as a skinCluster influence. @param joint: Joint to tag and bind influence @type joint: str @param bind: Bind state. @type bind: bool ''' # ========== # - Checks - # ========== if not mc.objExists(joint): raise Exception('Joint "'+joint+'" does not exist!') if mc.objectType(joint) != 'joint': raise Exception('Object "'+joint+'" is not a valid joint!') # ============= # - Tag Joint - # ============= if not mc.objExists(joint+'.bindJoint'): mc.addAttr(joint,ln='bindJoint',at='bool',dv=True) # =============== # - Clean Joint - # =============== if mc.objExists(joint+'.radius'): mc.setAttr(joint+'.radius',k=False,cb=False) if mc.objExists(joint+'.liw'): mc.setAttr(joint+'.liw',k=False,cb=False) def offsetGroup( ctrl, pivot = None, orientTo = None, prefix = None ): ''' Create offset group node. Optionally, set custom pivot and orientation. @param ctrl: Control or control group to create offset group for. @type ctrl: str @param pivot: Transform for pivot match. If None, use control pivot. @type pivot: str or None @param orientTo: Transform for orient match. If None, use world orientation. @type orientTo: str or None @param prefix: Naming prefix. @type prefix: str or None ''' # ========== # - Checks - # ========== # Control if not mc.objExists(ctrl): raise Exception('Control "'+ctrl+'" does not exist!') # Pivot if not pivot: pivot = ctrl if not mc.objExists(pivot): raise Exception('Pivot "'+pivot+'" does not exist!') # Orient To if orientTo: if not mc.objExists(orientTo): raise Exception('Orient target "'+orientTo+'" does not exist!') # Prefix if not prefix: prefix = glTools.utils.stringUtils.stripSuffix(ctrl) # ====================== # - Build Offset Group - # ====================== # Create Offset Group offsetGrp = mc.group(em=True,n=prefix+'_offsetGrp') # Set Pivot piv = mc.xform(pivot,q=True,ws=True,rp=True) mc.xform(offsetGrp,ws=True,piv=piv) # Orient Offset Group if orientTo: mc.delete(mc.orientConstraint(orientTo,offsetGrp)) # Parent Control mc.parent(ctrl,offsetGrp) # ================= # - Return Result - # ================= return offsetGrp def negateTransform( ctrl, negateGrp = None, translate = False, rotate = False, scale = False, prefix = None ): ''' Setup transform negation node network. @param ctrl: Control to create transform negation for. @type ctrl: str @param negateGrp: Negate transform. If None, create group from control. @type negateGrp: str or None @param translate: Negate transform translate. @type translate: bool @param rotate: Negate transform rotate. @type rotate: bool @param scale: Negate transform scale. @type scale: bool @param prefix: Naming prefix. @type prefix: str or None ''' # ========== # - Checks - # ========== # Control if not mc.objExists(ctrl): raise Exception('Control "'+ctrl+'" does not exist!') # Negate Group if negateGrp: if not mc.objExists(negateGrp): raise Exception('Control "'+ctrl+'" does not exist!') # Prefix if not prefix: prefix = glTools.utils.stringUtils.stripSuffix(ctrl) # ====================== # - Build Negate Group - # ====================== if not negateGrp: negateGrp = mc.duplicate(ctrl,po=True,n=prefix+'_negate')[0] glTools.utils.attribute.deleteUserAttrs(negateGrp) mc.parent(ctrl,negateGrp) # ====================== # - Build Negate Nodes - # ====================== if translate: tNegate = mc.createNode('multiplyDivide',n=prefix+'_translateNegate_multiplyDivide') mc.connectAttr(ctrl+'.t',tNegate+'.input1',f=True) mc.setAttr(tNegate+'.input2',-1,-1,-1) mc.connectAttr(tNegate+'.output',negateGrp+'.t',f=True) if rotate: rNegate = mc.createNode('multiplyDivide',n=prefix+'_rotateNegate_multiplyDivide') mc.connectAttr(ctrl+'.r',rNegate+'.input1',f=True) mc.setAttr(rNegate+'.input2',-1,-1,-1) mc.connectAttr(rNegate+'.output',negateGrp+'.r',f=True) # Reverse Rotate Order rotOrderMap = [5,3,4,1,2,0] mc.setAttr(negateGrp+'.ro',rotOrderMap[mc.getAttr(ctrl+'.ro')]) if scale: sNegate = mc.createNode('multiplyDivide',n=prefix+'_scaleNegate_multiplyDivide') mc.connectAttr(ctrl+'.s',sNegate+'.input2',f=True) mc.setAttr(sNegate+'.input1',1,1,1) mc.setAttr(sNegate+'.operation',2) # Divide mc.connectAttr(sNegate+'.output',negateGrp+'.s',f=True) # ================= # - Return Result - # ================= return negateGrp def lockJointAttrs(jointList=[]): ''' Lock joint attributes on the specified list of joints @param jointList: List of joints to lock joint attributes on. @type jointList: list ''' # ========== # - Checks - # ========== if not jointList: jointList = mc.ls(type='joint') or [] # ========================= # - Lock Joint Attributes - # ========================= for joint in jointList: # Lock Joint Orient if mc.getAttr(joint+'.jointOrient',se=True): mc.setAttr(joint+'.jointOrient',l=True) # Lock Preferred Angle Attr if mc.getAttr(joint+'.preferredAngle',se=True): mc.setAttr(joint+'.preferredAngle',l=True) # ================= # - Return Result - # ================= return jointList def setToDefault(ctrl): ''' Set the attributes of the specified control to default values @param ctrl: The control to set default attribute values for @type ctrl: str ''' # ================= # - Check Control - # ================= if not mc.objExists(ctrl): raise Exception('Control "'+ctrl+'" does not exist!') # ============================== # - Define Transform Constants - # ============================== tAttr = ['tx','ty','tz'] rAttr = ['rx','ry','rz'] sAttr = ['sx','sy','sz'] # ======================= # - Get User Attributes - # ======================= udAttr = mc.listAttr(ctrl,ud=True,k=True) if not udAttr: udAttr = [] cbAttr = mc.listAttr(ctrl,ud=True,cb=True) if not cbAttr: cbAttr = [] # ===================== # - Reset to Defaults - # ===================== for attr in tAttr: if mc.getAttr(ctrl+'.'+attr,se=True): mc.setAttr(ctrl+'.'+attr,0.0) for attr in rAttr: if mc.getAttr(ctrl+'.'+attr,se=True): mc.setAttr(ctrl+'.'+attr,0.0) for attr in sAttr: if mc.getAttr(ctrl+'.'+attr,se=True): mc.setAttr(ctrl+'.'+attr,1.0) for attr in udAttr: dv = mc.addAttr(ctrl+'.'+attr,q=True,dv=True) if mc.getAttr(ctrl+'.'+attr,se=True): mc.setAttr(ctrl+'.'+attr,dv) for attr in cbAttr: dv = mc.addAttr(ctrl+'.'+attr,q=True,dv=True) if mc.getAttr(ctrl+'.'+attr,se=True): mc.setAttr(ctrl+'.'+attr,dv) def isCtrlZeroed(ctrl,tol=0.00001,skipLocked=True,skipNonkeyable=False,verbose=False): ''' Check the attributes of the specified control are set to default values. @param ctrl: The control to check default attribute values on. @type ctrl: str @param tol: The tolerance within which the current value must be to the default value to be considered as zeroed. @type tol: float @param skipLocked: Skip locked or connected channels. @type skipLocked: bool @param skipNonkeyable: Skip non-keyable channels. @type skipNonkeyable: bool @param verbose: Print details of which attribute was determined an not zeroed. @type verbose: bool ''' # Check Control if not mc.objExists(ctrl): raise Exception('Control "'+ctrl+'" does not exist!') # Define standard transform controls tAttr = ['tx','ty','tz'] rAttr = ['rx','ry','rz'] sAttr = ['sx','sy','sz'] # Get user defined attrs udAttr = mc.listAttr(ctrl,ud=True,k=True) if not udAttr: udAttr = [] cbAttr = mc.listAttr(ctrl,ud=True,cb=True) if not cbAttr: cbAttr = [] # ============================ # - Check Attribute Defaults - # ============================ # Translate for attr in tAttr: if not mc.getAttr(ctrl+'.'+attr,se=True) and skipLocked: continue if not mc.getAttr(ctrl+'.'+attr,k=True) and skipNonkeyable: continue if not glTools.utils.mathUtils.isEqual(mc.getAttr(ctrl+'.'+attr),0.0,tol): if verbose: print ('Attribute "'+ctrl+'.'+attr+'" is not zeroed ('+str(mc.getAttr(ctrl+'.'+attr))+')!') return False # Rotate for attr in rAttr: if not mc.getAttr(ctrl+'.'+attr,se=True) and skipLocked: continue if not mc.getAttr(ctrl+'.'+attr,k=True) and skipNonkeyable: continue if not glTools.utils.mathUtils.isEqual(mc.getAttr(ctrl+'.'+attr),0.0,tol): if verbose: print ('Attribute "'+ctrl+'.'+attr+'" is not zeroed ('+str(mc.getAttr(ctrl+'.'+attr))+')!') return False # Scale for attr in sAttr: if not mc.getAttr(ctrl+'.'+attr,se=True) and skipLocked: continue if not mc.getAttr(ctrl+'.'+attr,k=True) and skipNonkeyable: continue if not glTools.utils.mathUtils.isEqual(mc.getAttr(ctrl+'.'+attr),1.0,tol): if verbose: print ('Attribute "'+ctrl+'.'+attr+'" is not zeroed ('+str(mc.getAttr(ctrl+'.'+attr))+')!') return False # User Defined (Keyable) for attr in udAttr: if not mc.getAttr(ctrl+'.'+attr,se=True) and skipLocked: continue dv = mc.addAttr(ctrl+'.'+attr,q=True,dv=True) if not glTools.utils.mathUtils.isEqual(mc.getAttr(ctrl+'.'+attr),dv,tol): if verbose: print ('Attribute "'+ctrl+'.'+attr+'" is not zeroed ('+str(mc.getAttr(ctrl+'.'+attr))+')!') return False # Channel Box (Non-Keyable) if not skipNonkeyable: for attr in cbAttr: if not mc.getAttr(ctrl+'.'+attr,se=True) and skipLocked: continue dv = mc.addAttr(ctrl+'.'+attr,q=True,dv=True) if not glTools.utils.mathUtils.isEqual(mc.getAttr(ctrl+'.'+attr),dv,tol): if verbose: print ('Attribute "'+ctrl+'.'+attr+'" is not zeroed ('+str(mc.getAttr(ctrl+'.'+attr))+')!') return False # ================= # - Return Result - # ================= return True def poleVectorPosition(startJoint,midJoint,endJoint,distance=1.0): ''' Calculate the pole vector position based on input arguments @param startJoint: The start joint of the ik chain @type startJoint: str @param midJoint: The middle joint of the ik chain @type midJoint: str @param endJoint: The end joint of the ik chain @type endJoint: str @param distance: The distance factor for the pole vector position based on chain length @type distance: float ''' # Check joint if not mc.objExists(startJoint): raise Exception('Start joint "'+startJoint+'" does not exist!') if not mc.objExists(midJoint): raise Exception('Middle joint "'+midJoint+'" does not exist!') if not mc.objExists(endJoint): raise Exception('End joint "'+endJoint+'" does not exist!') # Get joint positions stPt = glTools.utils.base.getPosition(startJoint) mdPt = glTools.utils.base.getPosition(midJoint) enPt = glTools.utils.base.getPosition(endJoint) # Get Joint lengths stLen = glTools.utils.joint.length(startJoint) mdLen = glTools.utils.joint.length(midJoint) pvLen = glTools.utils.mathUtils.distanceBetween(stPt,enPt) * distance wt = stLen/(stLen+mdLen) # Calculate Center Point ctPt = glTools.utils.mathUtils.averagePosition(stPt,enPt,wt) # Calculate Pole Vector Offset pvOffset = glTools.utils.mathUtils.offsetVector(ctPt,mdPt) # Check Center Point Offset if glTools.utils.mathUtils.mag(pvOffset) < 0.001: stRotate = [i/abs(i) if (abs(i)>0) else 0 for i in mc.getAttr(startJoint+'.preferredAngle')[0]] mdRotate = [i/abs(i) if (abs(i)>0) else 0 for i in mc.getAttr(midJoint+'.preferredAngle')[0]] mc.setAttr(startJoint+'.r',*stRotate) mc.setAttr(midJoint+'.r',*mdRotate) mdPt = glTools.utils.base.getPosition(midJoint) enPt = glTools.utils.base.getPosition(endJoint) cnPt = glTools.utils.mathUtils.averagePosition(stPt,enPt,wt) pvOffset = glTools.utils.mathUtils.offsetVector(cnPt,mdPt) mc.setAttr(startJoint+'.r',0,0,0) mc.setAttr(midJoint+'.r',0,0,0) # Calculate poleVector poleVec = glTools.utils.mathUtils.normalizeVector(pvOffset) # Calculate poleVector position pvPt = [ctPt[0]+(poleVec[0]*pvLen),ctPt[1]+(poleVec[1]*pvLen),ctPt[2]+(poleVec[2]*pvLen)] # Return result return pvPt def ikFkBlend( blendJoints, fkJoints, ikJoints, blendAttr, translate = True, rotate = True, scale = True, skipEnd = True, useConstraints = False, prefix = ''): ''' Setup IK/FK joint blending using blendColor nodes @param blendJoints: The joint chain to blend between IK and FK chains @type blendJoints: list @param fkJoints: Target FK joint chain @type fkJoints: list @param ikJoints: Target IK joint chain @type ikJoints: list @param blendAttr: FK to IK blend attribute @type blendAttr: str @param translate: Blend translate channels @type translate: bool @param rotate: Blend rotate channels @type rotate: bool @param scale: Blend scale channels @type scale: bool @param skipEnd: Skip chain end joint @type skipEnd: bool @param useConstraints: Use blended constraints instead of blendColor nodes for rotations @type useConstraints: bool @param prefix: Name prefix for created nodes @type prefix: str ''' # Check blend attribute if not mc.objExists(blendAttr): ctrl = blendAttr.split('.')[0] attr = blendAttr.split('.')[-1] if not mc.objExists(ctrl): raise Exception('Blend control "'+ctrl+'" does not exist!') mc.addAttr(ctrl,ln=attr,min=0,max=1,dv=0,k=True) # Check joint chains if (len(blendJoints) != len(fkJoints)) or (len(blendJoints) != len(ikJoints)): raise Exception('Chain length mis-match!!') # Check Skip End if skipEnd: blendJoints = blendJoints[:-1] fkJoints = fkJoints[:-1] ikJoints = ikJoints[:-1] # Blend Joint Translate/Rotate/Scale tBlendNode = '' rBlendNode = '' sBlendNode = '' # Blend Attribute Reverse blendRevNode = '' if useConstraints: blendRevNode = mc.createNode('reverse',n=prefix+'_blendAttr_reverse') mc.connectAttr(blendAttr,blendRevNode+'.inputX',f=True) mc.connectAttr(blendAttr,blendRevNode+'.inputY',f=True) mc.connectAttr(blendAttr,blendRevNode+'.inputZ',f=True) for i in range(len(blendJoints)): # Naming index ind = glTools.utils.stringUtils.alphaIndex(i,upper=True) # Translate if translate: # Create blend node tBlendNode = mc.createNode('blendColors',n=prefix+'_tr'+ind+'_blendColors') # Connect blend node mc.connectAttr(fkJoints[i]+'.tx',tBlendNode+'.color1R',f=True) mc.connectAttr(fkJoints[i]+'.ty',tBlendNode+'.color1G',f=True) mc.connectAttr(fkJoints[i]+'.tz',tBlendNode+'.color1B',f=True) mc.setAttr(tBlendNode+'.color2',0,0,0) mc.connectAttr(blendAttr,tBlendNode+'.blender',f=True) # Connect to joint mc.connectAttr(tBlendNode+'.outputR',blendJoints[i]+'.tx',f=True) mc.connectAttr(tBlendNode+'.outputG',blendJoints[i]+'.ty',f=True) mc.connectAttr(tBlendNode+'.outputB',blendJoints[i]+'.tz',f=True) # Rotate if rotate: if useConstraints: # Create orientConstraint node rBlendNode = mc.orientConstraint(fkJoints[i],ikJoints[i],blendJoints[i],n=prefix+'_rt'+ind+'_orientConstraint')[0] rBlendAlias = mc.orientConstraint(rBlendNode,q=True,wal=True) mc.connectAttr(blendAttr,rBlendNode+'.'+rBlendAlias[0],f=True) mc.connectAttr(blendRevNode+'.outputY',rBlendNode+'.'+rBlendAlias[1],f=True) else: # Create blend node rBlendNode = mc.createNode('blendColors',n=prefix+'_rt'+ind+'_blendColors') # Connect blend node mc.connectAttr(fkJoints[i]+'.rx',rBlendNode+'.color1R',f=True) mc.connectAttr(fkJoints[i]+'.ry',rBlendNode+'.color1G',f=True) mc.connectAttr(fkJoints[i]+'.rz',rBlendNode+'.color1B',f=True) mc.connectAttr(ikJoints[i]+'.rx',rBlendNode+'.color2R',f=True) mc.connectAttr(ikJoints[i]+'.ry',rBlendNode+'.color2G',f=True) mc.connectAttr(ikJoints[i]+'.rz',rBlendNode+'.color2B',f=True) mc.connectAttr(blendAttr,rBlendNode+'.blender',f=True) # Connect to joint mc.connectAttr(rBlendNode+'.outputR',blendJoints[i]+'.rx',f=True) mc.connectAttr(rBlendNode+'.outputG',blendJoints[i]+'.ry',f=True) mc.connectAttr(rBlendNode+'.outputB',blendJoints[i]+'.rz',f=True) # Scale if scale: #if useConstraints: # # # Create scaleConstraint node # sBlendNode = mc.scaleConstraint(fkJoints[i],ikJoints[i],blendJoints[i],n=prefix+'_sc'+ind+'_scaleConstraint')[0] # sBlendAlias = mc.scaleConstraint(sBlendNode,q=True,wal=True) # mc.connectAttr(blendAttr,sBlendNode+'.'+sBlendAlias[0],f=True) # mc.connectAttr(blendRevNode+'.outputZ',sBlendNode+'.'+sBlendAlias[1],f=True) # #else: # Create blend node sBlendNode = mc.createNode('blendColors',n=prefix+'_sc'+ind+'_blendColors') # Connect blend node mc.connectAttr(fkJoints[i]+'.sx',sBlendNode+'.color1R',f=True) mc.connectAttr(fkJoints[i]+'.sy',sBlendNode+'.color1G',f=True) mc.connectAttr(fkJoints[i]+'.sz',sBlendNode+'.color1B',f=True) mc.connectAttr(ikJoints[i]+'.sx',sBlendNode+'.color2R',f=True) mc.connectAttr(ikJoints[i]+'.sy',sBlendNode+'.color2G',f=True) mc.connectAttr(ikJoints[i]+'.sz',sBlendNode+'.color2B',f=True) mc.connectAttr(blendAttr,sBlendNode+'.blender',f=True) # Connect to joint mc.connectAttr(sBlendNode+'.outputR',blendJoints[i]+'.sx',f=True) mc.connectAttr(sBlendNode+'.outputG',blendJoints[i]+'.sy',f=True) mc.connectAttr(sBlendNode+'.outputB',blendJoints[i]+'.sz',f=True) # Return Result return [tBlendNode,rBlendNode,sBlendNode] def getAllCtrls(all='all'): ''' ''' # Check all exists if not mc.objExists(all): raise Exception('All node '+all+' does not exist!') # Get comtrols list return mc.getAttr(all+'.allCtrls') def setAllCtrls(all='all',ctrlList=[],append=False): ''' Add a multi string attribute to a specified node to store a list of all rig control names @param all: The node to add the control name list atribute to. Generally, the top node of the rig. ("all") @type all: str @param ctrlList: The list of control names to add to the multi string attribute. @type ctrlList: list @param append: Append to the mulit string attribute, if it already exists. Oterwise, replace. @type append: bool ''' # Check all exists if not mc.objExists(all): raise Exception('All node '+all+' does not exist!') # Check All Controls Attribute if not mc.objExists(all+'.allCtrls'): mc.addAttr(all,ln='allCtrls',dt='string',multi=True,hidden=True) # Check append if append: allCtrls = getAllCtrls(all) allCtrls.extend(ctrlList) ctrlList = allCtrls # Set all controls attribute array values for i in range(len(ctrlList)): mc.setAttr(all+'.allCtrls['+str(i)+']',ctrlList[i],type='string') def connectControlVisOld(ctrlLodAttr=['all.primaryCtrlVis','all.secondaryCtrlVis','all.tertiaryCtrlVis']): ''' Connect tagged control shape visibility based on the specified list of source attributes. The control ".ctrlLod" attribute value is used as an index into the incoming source attribute list. @param ctrlLodAttr: List of visibility control source attributes. @type ctrlLodAttr: list ''' # Get Control LOD node ctrlLodNode = mc.ls(ctrlLodAttr[0],o=True)[0] # Get Control List ctrlList = mc.ls('*.ctrlLod',o=True) ctrlList.sort() # Connect Control Visibility for ctrl in ctrlList: # Get Control Shapes ctrlShapes = mc.listRelatives(ctrl,s=True,ni=True,pa=True,type='nurbsCurve') if not ctrlShapes: continue # Get Control Lod ctrlLod = mc.getAttr(ctrl+'.ctrlLod') # Connect to Visibility for ctrlShape in ctrlShapes: # Check Existing Connections shapeVisConn = mc.listConnections(ctrlShape+'.v',s=True,d=False,skipConversionNodes=True) if shapeVisConn and not (shapeVisConn[0] == ctrlLodNode): # Double check intermediate visibility connection # !! This is a little more messy than I would like. But will keep until it breaks !! - (10/15/12) shapeVisConnCheck = mc.listConnections(shapeVisConn[0],s=True,d=False,skipConversionNodes=True,p=True) if not shapeVisConnCheck: shapeVisConnCheck = [] for shapeVisNodeCheck in shapeVisConnCheck: if ctrlLodAttr.count(shapeVisNodeCheck): mc.delete(shapeVisConn[0]) # Get connections with plug information shapeVisConn = mc.listConnections(ctrlShape+'.v',s=True,d=False,p=True) # Merge visibility inputs shapePrefix = glTools.utils.stringUtils.stripSuffix(ctrlShape) shapeVisNode = mc.createNode('multDoubleLinear',n=shapePrefix+'_allVis_multDoubleLinear') mc.connectAttr(shapeVisConn[0],shapeVisNode+'.input1',f=True) mc.connectAttr(ctrlLodAttr[ctrlLod],shapeVisNode+'.input2',f=True) mc.connectAttr(shapeVisNode+'.output',ctrlShape+'.v',f=True) else: # No existing connection - Direct connection try: mc.connectAttr(ctrlLodAttr[ctrlLod],ctrlShape+'.v',f=True) except: pass def connectControlVis( ctrlList = None, ctrlLodNode = 'all', ctrlLodAttr = ['primaryCtrlVis','secondaryCtrlVis','tertiaryCtrlVis'] ): ''' Connect tagged control LOD visibility based on the specified list of source attributes. The control ".ctrlLod" attribute value is used as an index into the incoming source attribute list. @param ctrlList: List of controls to connect visibility for. If None, select by "ctrlLod" attribute. @type ctrlList: list @param ctrlLodNode: Control LOD toggle node. @type ctrlLodNode: str @param ctrlLodAttr: List of control LOD toggle attributes. @type ctrlLodAttr: list ''' # ========== # - Checks - # ========== # Control LOD Toggle Node if not mc.objExists(ctrlLodNode): raise Exception('Control LOD toggle node "'+ctrlLodNode+'" does not exist!') # Control List if not ctrlList: ctrlList = mc.ls('*.ctrlLod',o=True,r=True) # ============================== # - Connect Control Visibility - # ============================== for ctrl in ctrlList: # Get Control Lod if not mc.attributeQuery('ctrlLod',n=ctrl,ex=True): continue ctrlLod = mc.getAttr(ctrl+'.ctrlLod') if ctrlLod >= len(ctrlLodAttr): continue # Get Control Shapes ctrlShapes = mc.listRelatives(ctrl,s=True,ni=True,pa=True,type='nurbsCurve') # ------------------------------------------------------------------------------- # !!! If No Shapes, Show Display Handle and LOD Override (Normal/BoundingBox) !!! # ------------------------------------------------------------------------------- if not ctrlShapes: # Show Display Handle mc.setAttr(ctrl+'.displayHandle',True) # Get/Create LOD Switch Reverse Node rev = mc.ls(mc.listConnections(ctrlLodNode+'.'+ctrlLodAttr[ctrlLod],s=False,d=True) or [],type='reverse') or [] if not rev: rev = mc.createNode('reverse',n=ctrlLodAttr[ctrlLod]+'_reverse') mc.connectAttr(ctrlLodNode+'.'+ctrlLodAttr[ctrlLod],rev+'.inputX',f=True) else: rev = rev[0] # Set/Connect Display Overrides mc.setAttr(ctrl+'.overrideEnabled',1) mc.connectAttr(rev+'.outputX',ctrl+'.overrideLevelOfDetail',f=True) # Connect Control Shape Visibility else: for ctrlShape in ctrlShapes: # Check Existing Connections lodVisConn = mc.listConnections(ctrlShape+'.lodVisibility',s=True,d=False) if lodVisConn: # Disconnect Attribute lodVisConn = mc.listConnections(ctrlShape+'.lodVisibility',s=True,d=False,p=True) mc.disconnectAttr(lodVisConn[0],ctrlShape+'.lodVisibility') # Connect LOD Visibility try: mc.connectAttr(ctrlLodNode+'.'+ctrlLodAttr[ctrlLod],ctrlShape+'.lodVisibility',f=True) except: print('Error connecting ctrl LOD attr to "'+ctrlShape+'.lodVisibility"!') # ================= # - Return Result - # ================= return ctrlList def connectCostumeCtrlVis( ctrlList = None, ctrlVisNode = 'all', ctrlVisAttr = 'costumeCtrlVis', useCategory = True ): ''' Connect costume control visibility. @param ctrlList: List of controls to connect visibility for. @type ctrlList: list @param ctrlLodNode: Control LOD toggle node. @type ctrlLodNode: str @param ctrlLodAttr: List of control LOD toggle attributes. @type ctrlLodAttr: list ''' # ========== # - Checks - # ========== # Control Vis Toggle Node if not mc.objExists(ctrlVisNode): raise Exception('Visibility control toggle node "'+ctrlVisNode+'" does not exist!') # Control List if not ctrlList: if useCategory: ctrlList = mc.ls('*.ctrlCategory',o=True,r=True) else: ctrlList = mc.ls('*.ctrlLod',o=True,r=True) # ====================================== # - Connect Costume Control Visibility - # ====================================== # Add Control Attribute if not mc.attributeQuery(ctrlVisAttr,n=ctrlVisNode,ex=True): mc.addAttr(ctrlVisNode,ln=ctrlVisAttr,at='enum',en='Off:On',dv=0) mc.setAttr(ctrlVisNode+'.'+ctrlVisAttr,cb=True) # Connect Control Visibility for ctrl in ctrlList: ctrlTag = mc.getAttr(ctrl+'.ctrlLod') if useCategory: ctrlTag = mc.getAttr(ctrl+'.ctrlCategory') if ctrlTag != 'costume': continue # Connect Control Shapes ctrlShapes = mc.listRelatives(ctrl,s=True,ni=True,pa=True,type='nurbsCurve') for ctrlShape in ctrlShapes: # Check Existing Connections lodVisConn = mc.listConnections(ctrlShape+'.lodVisibility',s=True,d=False) if lodVisConn: # Disconnect Attribute lodVisConn = mc.listConnections(ctrlShape+'.lodVisibility',s=True,d=False,p=True) mc.disconnectAttr(lodVisConn[0],ctrlShape+'.lodVisibility') # Connect LOD Visibility try: mc.connectAttr(ctrlVisNode+'.'+ctrlVisAttr,ctrlShape+'.lodVisibility',f=True) except: print('Error connecting ctrl LOD attr to "'+ctrlShape+'.lodVisibility"!') # Print Msg print('Costume Control Shape "'+ctrlShape+'" connected to "'+ctrlVisNode+'.'+ctrlVisAttr+'"...') def connectLoresVis(toggleAttr='all.loGeoVis'): ''' Connect lores geometry visibility to the specified visibility toggle attribute @param toggleAttr: Visibility toggle attribute @type toggleAttr: str ''' # Check visibility toggle attribute if not mc.objExists(toggleAttr): raise Exception('Visibility toggle attribute "'+toggleAttr+'" does not exist!') # Get all joint list jointList = mc.ls(type='joint') if not jointList: return # Iterate over all joints for joint in jointList: # Get all joint mesh shapes allShapes = mc.listRelatives(joint,s=True,pa=True) if not allShapes: continue meshShapes = mc.ls(allShapes,type='mesh') if not meshShapes: continue # Connect mesh shape visibility to vis toggle attr for meshShape in meshShapes: mc.connectAttr(toggleAttr,meshShape+'.v',f=True) def connectVisOld(objList=[],toggleAttr='all.hiGeoVis',attrName='',defaultValue=0): ''' Connect node visibility to the specified visibility toggle attribute @param objList: List of objects to toggle visibility for @type objList: list @param toggleAttr: Visibility toggle attribute @type toggleAttr: str @param attrName: Attribute nice name for UI @type attrName: str @param defaultValue: Default value for the visibility toggle attribute @type defaultValue: int ''' #### DEPRECATED WARNING print('#### - DEPRECATED (glTools.rig.utils.connectVisOld) - ####') # Check Object List if type(objList) == str or type(objList) == unicode: objList = [str(objList)] for obj in objList: if not mc.objExists(obj): raise Exception('Object "'+obj+'" does not exist!') # Check Visibility Toggle Attribute if not mc.objExists(toggleAttr): node = toggleAttr.split('.')[0] if not mc.objExists(node): raise Exception('Visibility control node "'+node+'" does not exist!') attr = toggleAttr.split('.')[-1] mc.addAttr(node,ln=attr,nn=attrName,at='enum',en='Off:On',dv=defaultValue) mc.setAttr(node+'.'+attr,cb=True) else: mc.addAttr(toggleAttr,e=True,dv=defaultValue) # Connect Visibility for obj in objList: visConn = mc.listConnections(obj+'.v',s=True,d=False,p=True) if not visConn: visConn = [] if not visConn.count(toggleAttr): try: mc.connectAttr(toggleAttr,obj+'.v',f=True) except: print 'Unable to connect "'+obj+'" visibility!' # Return Result return toggleAttr def connectVis( objList, toggleNode, toggleAttr, toggleName='', defaultValue=0, force=True, enumStr='Off:On' ): ''' Connect node visibility to the specified visibility toggle node and attribute. If toggle attribute doesn't exist, a new enum attr of the specified name will be created. @param objList: List of objects to toggle visibility for @type objList: list @param toggleNode: Visibility toggle attribute @type toggleNode: str @param toggleAttr: Visibility toggle attribute @type toggleAttr: str @param toggleName: Attribute nice name for UI @type toggleName: str @param defaultValue: Default value for the visibility toggle attribute @type defaultValue: int @param force: Force visibility connection if incoming connection already exists. @type force: bool @param enumStr: Visibility toggle enum string. @type enumStr: str ''' # ========== # - Checks - # ========== if not objList: raise Exception('Invalid or empty object list argument! (objList)') if not toggleNode: raise Exception('Invalid or empty toggle node argument! (toggleNode)') if not toggleAttr: raise Exception('Invalid or empty toggle attribute argument! (toggleAttr)') # Check Object List if isinstance(objList,types.StringTypes): objList = [str(objList)] if not isinstance(objList,types.ListType): raise Exception('Invalid object list!') for obj in objList: if not mc.objExists(obj): raise Exception('Object "'+obj+'" does not exist!') # Check Toggle Node if not mc.objExists(toggleNode): raise Exception('Visibility control node "'+obj+'" does not exist!') # Check Toggle Name if not toggleName: toggleName = toggleAttr # Check Visibility Toggle Attribute if not mc.attributeQuery(toggleAttr,n=toggleNode,ex=True): mc.addAttr(toggleNode,ln=toggleAttr,nn=toggleName,at='enum',en=enumStr,dv=defaultValue) mc.setAttr(toggleNode+'.'+toggleAttr,cb=True) else: mc.addAttr(toggleNode+'.'+toggleAttr,e=True,nn=toggleName,dv=defaultValue) toggleNodeAttr = toggleNode+'.'+toggleAttr # ====================== # - Connect Visibility - # ====================== for obj in objList: # Check Incoming Connections nodeVisConn = mc.listConnections(obj+'.v',s=True,d=False) if nodeVisConn: if force: # Connect Visibility (Force Override) try: mc.connectAttr(toggleNodeAttr,obj+'.v',f=True) except: pass # print('Problem overriding visibility connection! ('+toggleNodeAttr+' >> '+obj+'.v)') else: raise Exception('Existing visibility connection already exists! Use force=True to override...') else: # Connect Visibility try: mc.connectAttr(toggleNodeAttr,obj+'.v',f=True) except: raise Exception('Problem connecting visibility! ('+toggleNodeAttr+' >> '+obj+'.v)') # ================= # - Return Result - # ================= return toggleNodeAttr def connectDisplayTypeOld(objList,toggleAttr='all.meshDisplayType',defaultValue=0): ''' Connect object display type to the specified enum attribute @param objList: List of objects to toggle display type for @type objList: list @param toggleAttr: Display type toggle attribute @type toggleAttr: str @param defaultValue: Default value for the visibility toggle attribute @type defaultValue: int ''' #### DEPRECATED WARNING print('#### - DEPRECATED (glTools.rig.utils.connectDisplayTypeOld) - ####') # Check Object List if type(objList) == str or type(objList) == unicode: objList = [str(objList)] for obj in objList: if not mc.objExists(obj): raise Exception('Object "'+obj+'" does not exist!') # Check visibility toggle attribute if not mc.objExists(toggleAttr): node = toggleAttr.split('.')[0] if not node: raise Exception('Visibility control node "'+node+'" does not exist!') attr = toggleAttr.split('.')[-1] mc.addAttr(node,ln=attr,at='enum',en=':Normal:Template:Reference:',dv=defaultValue) mc.setAttr(node+'.'+attr,cb=True) else: mc.addAttr(toggleAttr,e=True,dv=defaultValue) # Connect Display Type for obj in objList: mc.setAttr(obj+'.overrideEnabled',1) try: mc.connectAttr(toggleAttr,obj+'.overrideDisplayType',f=True) except: objConn = mc.listConnections(obj+'.overrideDisplayType',s=True,d=False,p=True) if objConn.count(toggleAttr): print('Attribute "'+toggleAttr+'" is already connect to "'+obj+'.overrideDisplayType"! Skipping connectAttr...') else: print('Unable to connect "'+toggleAttr+'" to "'+obj+'.overrideDisplayType"!') # Return Result return toggleAttr def connectDisplayType( objList, toggleNode, toggleAttr, toggleName='', defaultValue=0, force=True, enumStr='Normal:Template:Reference' ): ''' Connect object display type to the specified enum attribute @param objList: List of objects to toggle display type for @type objList: list @param toggleNode: Display type toggle node @type toggleNode: str @param toggleAttr: Display type toggle attribute name @type toggleAttr: str @param toggleName: Display type toggle attribute nice name for UI @type toggleName: str @param defaultValue: Default value for the display type toggle attribute @type defaultValue: int @param force: Force display type connection if incoming connection already exists. @type force: bool @param enumStr: Display type toggle enum string. @type enumStr: str ''' # ========== # - Checks - # ========== if not objList: raise Exception('Invalid or empty object list argument! (objList)') if not toggleNode: raise Exception('Invalid or empty toggle node argument! (toggleNode)') if not toggleAttr: raise Exception('Invalid or empty toggle attribute argument! (toggleAttr)') # Check Object List if isinstance(objList,types.StringTypes): objList = [str(objList)] if not isinstance(objList,types.ListType): raise Exception('Invalid object list!') for obj in objList: if not mc.objExists(obj): raise Exception('Object "'+obj+'" does not exist!') # Check Toggle Node if not mc.objExists(toggleNode): raise Exception('Display type control node "'+obj+'" does not exist!') # Check Toggle Name if not toggleName: toggleName = toggleAttr # Check Visibility Toggle Attribute if not mc.attributeQuery(toggleAttr,n=toggleNode,ex=True): mc.addAttr(toggleNode,ln=toggleAttr,nn=toggleName,at='enum',en=enumStr,dv=defaultValue) mc.setAttr(toggleNode+'.'+toggleAttr,cb=True) else: mc.addAttr(toggleNode+'.'+toggleAttr,e=True,nn=toggleName,dv=defaultValue) toggleNodeAttr = toggleNode+'.'+toggleAttr # ======================== # - Connect Display Type - # ======================== for obj in objList: # Enable Display Overrides mc.setAttr(obj+'.overrideEnabled',1) # Check Incoming Connections nodeDispAttr = 'overrideDisplayType' nodeDispConn = mc.listConnections(obj+'.'+nodeDispAttr,s=True,d=False) if nodeDispConn: if force: # Connect Display Type (Force Override) try: mc.connectAttr(toggleNodeAttr,obj+'.'+nodeDispAttr,f=True) except: pass # print('Problem overriding visibility connection! ('+toggleNodeAttr+' >> '+obj+'.'+nodeDispAttr+')') else: raise Exception('Existing display type connection already exists! Use force=True to override...') else: # Connect Visibility try: mc.connectAttr(toggleNodeAttr,obj+'.'+nodeDispAttr,f=True) except: raise Exception('Problem connecting visibility! ('+toggleNodeAttr+' >> '+obj+'.'+nodeDispAttr+')') # ================= # - Return Result - # ================= return toggleNodeAttr def connectAttr(targetNode,targetAttr,sourceNode,sourceAttr,force=True): ''' Connect specified source and target attributes @param targetNode: Target node @type targetNode: str @param targetAttr: Target attribute @type targetAttr: str @param sourceNode: Source node @type sourceNode: str @param sourceAttr: Source attribute @type sourceAttr: str @param force: Force connection if incoming connection already exists @type force: bool ''' # ========== # - Checks - # ========== if not targetNode: raise Exception('Invalid or empty target node argument! (targetNode)') if not targetAttr: raise Exception('Invalid or empty target attribute argument! (targetAttr)') if not sourceNode: raise Exception('Invalid or empty source node argument! (sourceNode)') if not sourceAttr: raise Exception('Invalid or empty source attribute argument! (sourceAttr)') if not mc.objExists(targetNode): raise Exception('Target node "'+targetNode+'" does not exist!') if not mc.objExists(sourceNode): raise Exception('Source node "'+targetNode+'" does not exist!') if not mc.attributeQuery(targetAttr,n=targetNode,ex=True): raise Exception('Target attribute "'+targetNode+'.'+targetAttr+'" does not exist!') if not mc.attributeQuery(sourceAttr,n=sourceNode,ex=True): raise Exception('Source attribute "'+sourceNode+'.'+sourceAttr+'" does not exist!') sourceNodeAttr = sourceNode+'.'+sourceAttr targetNodeAttr = targetNode+'.'+targetAttr # Check Existing Connection to Target existingConn = mc.listConnections(targetNodeAttr,s=True,d=False,p=True) or [] if existingConn: for srcConn in existingConn: print('Breaking existing connection - "'+srcConn+'" >< "'+targetNodeAttr+'"...') mc.disconnectAttr(srcConn,targetNodeAttr) # ===================== # - Connect Attribute - # ===================== try: mc.connectAttr(sourceNodeAttr,targetNodeAttr,f=force) except Exception, e: raise Exception('Error connecting attribute "'+sourceNodeAttr+'" >> "'+targetNodeAttr+'"! Exception Msg: '+str(e)) else: print('Connecting attributes - "'+sourceNodeAttr+'" >> "'+targetNodeAttr+'"...') # ================= # - Return Result - # ================= return sourceNodeAttr,targetNodeAttr def nonRenderableFaceSet(facelist,buildStandin=False): ''' Define a list of faces to be ignored/deleted at render time. Creates a nonRenderable preview mesh with the specified polygon faces deleted. The original mesh is unchanged except for an ABC primvar attr that lists the face IDs to be ignored at render time. @param facelist: List of faces to ignore during render. @type facelist: list @param buildStandin: Build standin geometry with faces removed, set original visibility off. @type buildStandin: bool ''' # ========== # - Checks - # ========== facelist = mc.filterExpand(facelist,sm=34) if not facelist: raise Exception('Invalid face list!') # =================== # - Get Set Members - # =================== # Sort Faces by Object faceObjList = glTools.utils.selection.componentListByObject(facelist) # For Each Object in Set meshPreviewList = [] for faceList in faceObjList: # Get Mesh faceMesh = mc.ls(faceList[0],o=True)[0] if not glTools.utils.transform.isTransform(faceMesh): faceMesh = mc.listRelatives(faceMesh,p=True,pa=True)[0] # Get Face Id List faceIdList = glTools.utils.component.singleIndexList(faceList) faceIdStr = str(faceIdList)[1:-1] # ======================== # - Add ABC PrimVar Attr - # ======================== attrName = 'deleteFaceSet' if mc.objExists(faceMesh+'.ABC_'+attrName): try: mc.setAttr(faceMesh+'.ABC_'+attrName,l=False) except: pass mc.deleteAttr(faceMesh+'.ABC_'+attrName) glTools.utils.primvar.addAbcPrimVarStr( geo = faceMesh, attrName = attrName, stringVal = faceIdStr, lock = False ) # ================= # - Build Standin - # ================= if buildStandin: # Duplicate Original (with Connections) meshPreview = mc.polyDuplicateAndConnect(faceMesh)[0] meshPreview = mc.rename(meshPreview,faceMesh+'_standin') # Reparent Object try: mc.parent(meshPreview,w=True) except: pass # Delete Unused Shapes meshPreviewShapes = mc.listRelatives(meshPreview,s=True,pa=True) if meshPreviewShapes: meshPreviewIntShapes = mc.ls(meshPreviewShapes,intermediateObjects=True) if meshPreviewIntShapes: mc.delete(meshPreviewIntShapes) # Rename Shape meshPreviewShapes = mc.listRelatives(meshPreview,s=True,pa=True) if meshPreviewShapes: meshPreviewShape = mc.rename(meshPreviewShapes[0],meshPreview+'Shape') # Delete Faces mc.delete([meshPreview+'.f['+str(i)+']' for i in faceIdList]) # Append Output List meshPreviewList.append(meshPreview) # ================= # - Return Result - # ================= return meshPreviewList def selectNonRenderableFaces(geo): ''' Select non-renderable faces for selected geometry ''' # ========== # - Checks - # ========== # Check Mesh if not glTools.utils.mesh.isMesh(geo): mc.warning('Object "'+geo+'" is not a valid mesh! Unable to select non-renderable faces...') return [] # Check Attribute attrName = 'ABC_deleteFaceSet' if not mc.attributeQuery(attrName,n=geo,ex=True): mc.warning('Attribute "'+geo+'.'+attrName+'" does not exist! Unable to select non-renderable faces...') return [] # ================ # - Select Faces - # ================ faceIdStr = mc.getAttr(geo+'.'+attrName) faceIdList = ast.literal_eval(faceIdStr) faceList = [geo+'.f['+str(i)+']' for i in faceIdList] try: mc.select(faceList) except: mc.warning('Problem selecting face list! '+str(faceList)) # ================= # - Return Result - # ================= return faceList def checkNonReferencedInputShape(geo): ''' Check if the input shape on the specified referenced geometry is a referenced node. @param geo: Geometry to check referenced input shape on. @type geo: str ''' # ========== # - Checks - # ========== # Check Geometry Exists if not mc.objExists(geo): raise Exception('Geometry "'+geo+'" does not exist!') # Check Geometry is Referenced if not glTools.utils.reference.isReferenced(geo): raise Exception('Geometry "'+geo+'" is not referenced! No referenced shapes under nonReference parent...') # Get Geometry Shapes shapes = mc.listRelatives(geo,s=True,pa=True) if not shapes: raise Exception('No shapes found under geometry "'+geo+'"!') if len(shapes) == 1: print('Geometry "'+geo+'" has only one shape! Nothing to do here, skipping...') return False # Check for Referenced Shapes refShapes = [shape for shape in shapes if glTools.utils.reference.isReferenced(shape)] if not refShapes: raise Exception('No referenced shapes found under geometry "'+geo+'"!') # Get Output Shape resultShape = mc.listRelatives(geo,s=True,ni=True,pa=True) if not resultShape: raise Exception('No non-intermediate shapes under geometry "'+geo+'"!') if len(resultShape) != 1: print('Multiple non-intermediate shapes! Checking first shape ("'+resultShape[0]+'") for input connections... ') # Get Input Shape inputShape = glTools.utils.shape.findInputShape(resultShape[0],recursive=True) if not inputShape: raise Exception('Unable to determine input shape for "'+resultShape[0]+'"!') if inputShape == resultShape[0]: if mc.listHistory(inputShape): print('WARNING: Input shape is same as output shape for geometry "'+geo+'"! Check graph for cyclic dependancy...') else: print('Output shape "'+resultShape[0]+'" has no incoming connections! Nothing to do, skipping...') return False # Check Input Shape is Referenced return not glTools.utils.reference.isReferenced(inputShape) def fixNonReferencedInputShape(geo): ''' Ensure the input shape on the specified referenced geometry is a referenced shape node. @param geo: Geometry to fix referenced input shape on. @type geo: str ''' # ========== # - Checks - # ========== # Check Geometry Exists if not mc.objExists(geo): raise Exception('Geometry "'+geo+'" does not exist!') # Check Geometry is Referenced if not glTools.utils.reference.isReferenced(geo): raise Exception('Geometry "'+geo+'" is not referenced! No referenced shapes under nonReference parent...') # Get Geometry Shapes shapes = mc.listRelatives(geo,s=True,pa=True) if not shapes: raise Exception('No shapes found under geometry "'+geo+'"!') if len(shapes) == 1: print('Geometry "'+geo+'" has only one shape! Nothing to do here, skipping...') return '' # Check for Referenced Shapes refShapes = [shape for shape in shapes if glTools.utils.reference.isReferenced(shape)] if not refShapes: raise Exception('No referenced shapes found under geometry "'+geo+'"!') if len(refShapes) > 1: print('Found multiple referenced shapes under geometry transform "'+geo+'"! Using first shape "'+refShapes[0]+'" for input connections...') # Get Output Shape resultShape = mc.listRelatives(geo,s=True,ni=True,pa=True) if not resultShape: raise Exception('No non-intermediate shapes found under geometry "'+geo+'"!') if len(resultShape) != 1: print('Found multiple non-intermediate shapes! Using first shape "'+resultShape[0]+'" for input connections...') # Get Input Shape inputShape = glTools.utils.shape.findInputShape(resultShape[0],recursive=True) if not inputShape: raise Exception('No input shape found for "'+resultShape[0]+'"!') if inputShape == resultShape[0]: if mc.listHistory(inputShape): print('WARNING: Input shape is same as output shape for geometry "'+geo+'"! Check graph for cyclic dependancy...') else: print('Output shape "'+resultShape[0]+'" has no incoming connections! Nothing to do, skipping...') return '' # Check Input Shape is Referenced if glTools.utils.reference.isReferenced(inputShape): print('Input shape is referenced! Skipping...') return '' # ============================================= # - Replace Input Shape with Referenced Shape - # ============================================= # Check Reference Shape is Output if resultShape[0] == refShapes[0]: # Swap Input/Output Node Conections print('References shape is output (result) shape! Rearranging geometry graph...') glTools.utils.connection.swap(inputShape,refShapes[0]) # Set Intermediate Object Status mc.setAttr(inputShape+'.intermediateObject',0) mc.setAttr(refShapes[0]+'.intermediateObject',1) # Fix Shape Names if 'Orig' in inputShape: if 'Deformed' in inputShape: inputShape = mc.rename(inputShape,inputShape.replace('Orig','')) else: inputShape = mc.rename(inputShape,inputShape.replace('Orig','Deformed')) else: # Check inMesh Connections to Referenced Shape if mc.listConnections(refShapes[0]+'.inMesh',s=True,d=False): # Swap Input/Output Node Conections glTools.utils.connection.swap(inputShape,refShapes[0]) else: # Replace Input/Output Node Conections glTools.utils.connection.replace(inputShape,refShapes[0],inputs=True,outputs=True) # ================= # - Return Result - # ================= return refShapes[0] def cleanUnusedIntermediateShapes(geo): ''' ''' # Check Geometry Exists if not mc.objExists(geo): raise Exception('Geometry "'+geo+'" does not exist!') # Get Geometry Shapes shapes = mc.listRelatives(geo,s=True,pa=True) if not shapes: raise Exception('No shapes found under geometry "'+geo+'"!') if len(shapes) == 1: print('Geometry "'+geo+'" has only one shape! Nothing to do here, skipping...') return None # Get Output Shape resultShapes = mc.listRelatives(geo,s=True,ni=True,pa=True) if not resultShapes: raise Exception('No non-intermediate shapes found under geometry "'+geo+'"!') if len(resultShapes) != 1: print('Found multiple non-intermediate shapes!') # For Each Output Shape for resultShape in resultShapes: # Get Input Shape inputShape = glTools.utils.shape.findInputShape(resultShape,recursive=True) if not inputShape: print('No input shape found for "'+resultShape+'"! Skipping') continue if inputShape == resultShape: if mc.listHistory(inputShape): print('WARNING: Input shape is same as output shape for geometry "'+geo+'"! Check graph for cyclic dependancy...') else: print('Output shape "'+resultShape+'" has no incoming connections! Nothing to do, skipping...') continue # Replace Unused Intermediate Shapes Connections intermediateShape = glTools.utils.shape.findInputShape(resultShape) while(intermediateShape != inputShape): # Store Next Intermediate Shape intShape = intermediateShape intermediateShape = glTools.utils.shape.findInputShape(intShape) # MESH if mc.objectType(intShape) == 'mesh': inMeshConn = mc.listConnections(intShape+'.inMesh',s=True,d=False,p=True) if inMeshConn: outMeshConn = mc.listConnections([intShape+'.outMesh',intShape+'.worldMesh'],s=False,d=True,p=True) or [] for outConn in outMeshConn: mc.connectAttr(inMeshConn[0],outConn,f=True) # NURBS elif mc.objectType(intShape) in ['nurbsCurve','nurbsSurface']: inNurbConn = mc.listConnections(intShape+'.create',s=True,d=False,p=True) if inNurbConn: outNurbConn = mc.listConnections([intShape+'.local',intShape+'.worldSpace'],s=False,d=True,p=True) or [] for outConn in outNurbConn: mc.connectAttr(inNurbConn[0],outConn,f=True) # UNSUPPORTED else: print('Unsupported shape type! ('+mc.objectType(intShape)+')! Skipping geometry...') break # Replace Generic Connections #glTools.utils.connection.replace(intShape,inputShape,inputs=True,outputs=True) # Delete Unused Intermediate Shape mc.delete(intShape) # Print Shape Result print('# DELETED Intermediate Shape: '+intShape)
zhaquirks/yale/realliving.py
WolfRevo/zha-device-handlers
213
148347
"""Device handler for Yale Real Living.""" from zigpy.profiles import zha from zigpy.quirks import CustomDevice from zigpy.zcl.clusters.closures import DoorLock from zigpy.zcl.clusters.general import Alarms, Basic, Identify, Ota, PollControl, Time from zhaquirks import DoublingPowerConfigurationCluster from zhaquirks.const import ( DEVICE_TYPE, ENDPOINTS, INPUT_CLUSTERS, MODELS_INFO, OUTPUT_CLUSTERS, PROFILE_ID, ) class YRD210PBDB220TSLL(CustomDevice): """Yale YRD210 PB BP and Yale YRL220 TS LL Locks.""" signature = { # <SimpleDescriptor endpoint=1 profile=260 device_type=10 # device_version=0 # input_clusters=[0, 1, 3, 9, 10, 257, 32] # output_clusters=[10, 25]> MODELS_INFO: [("Yale", "YRD210 PB DB"), ("Yale", "YRL220 TS LL")], ENDPOINTS: { 1: { PROFILE_ID: zha.PROFILE_ID, DEVICE_TYPE: zha.DeviceType.DOOR_LOCK, INPUT_CLUSTERS: [ Basic.cluster_id, DoublingPowerConfigurationCluster.cluster_id, Identify.cluster_id, Alarms.cluster_id, Time.cluster_id, DoorLock.cluster_id, PollControl.cluster_id, ], OUTPUT_CLUSTERS: [Time.cluster_id, Ota.cluster_id], } }, } replacement = { ENDPOINTS: { 1: { PROFILE_ID: zha.PROFILE_ID, DEVICE_TYPE: zha.DeviceType.DOOR_LOCK, INPUT_CLUSTERS: [ Basic.cluster_id, DoublingPowerConfigurationCluster, Identify.cluster_id, Alarms.cluster_id, Time.cluster_id, DoorLock.cluster_id, PollControl.cluster_id, ], OUTPUT_CLUSTERS: [DoorLock.cluster_id, Ota.cluster_id], } } } class YRD220240TSDB(CustomDevice): """Yale YRD220/240 TSDB Lock.""" signature = { # <SimpleDescriptor endpoint=1 profile=260 device_type=10 # device_version=0 # input_clusters=[0, 1, 9, 10, 32, 257] # output_clusters=[10, 25]> MODELS_INFO: [("Yale", "YRD220/240 TSDB")], ENDPOINTS: { 1: { PROFILE_ID: zha.PROFILE_ID, DEVICE_TYPE: zha.DeviceType.DOOR_LOCK, INPUT_CLUSTERS: [ Basic.cluster_id, DoublingPowerConfigurationCluster.cluster_id, Alarms.cluster_id, Time.cluster_id, PollControl.cluster_id, DoorLock.cluster_id, ], OUTPUT_CLUSTERS: [Time.cluster_id, Ota.cluster_id], } }, } replacement = { ENDPOINTS: { 1: { PROFILE_ID: zha.PROFILE_ID, DEVICE_TYPE: zha.DeviceType.DOOR_LOCK, INPUT_CLUSTERS: [ Basic.cluster_id, DoublingPowerConfigurationCluster, Alarms.cluster_id, Time.cluster_id, PollControl.cluster_id, DoorLock.cluster_id, ], OUTPUT_CLUSTERS: [DoorLock.cluster_id, Ota.cluster_id], } } }
Scripts/CI/README_Metadata_StyleCheck/metadata_style_checker.py
pgruenler/arcgis-runtime-samples-ios
292
148351
#!/usr/bin/env python3 import os import re import json import typing import argparse # region Global sets # A set of category folder names in current sample viewer. categories = { 'Maps', 'Layers', 'Features', 'Display information', 'Search', 'Edit data', 'Geometry', 'Route and directions', 'Analysis', 'Cloud and portal', 'Scenes', 'Utility network', 'Augmented reality' } # endregion # region Static functions def sub_special_char(string: str) -> str: """ Check and substitute if a string contains special characters. :param string: The input string. :return: A new string without special characters. """ # regex = re.compile('[@_!#$%^&*()<>?/\\|}{~:]') regex = re.compile(r'[@_!#$%^&*<>?|/\\}{~:]') return re.sub(regex, '', string) def parse_head(head_string: str) -> (str, str): """ Parse the `Title` section of README file and get the title and description. :param head_string: A string containing title, description and images. :return: Stripped title and description strings. """ parts = list(filter(bool, head_string.splitlines())) if len(parts) < 3: raise Exception('README description parse failure!') title = parts[0].lstrip('# ').rstrip() description = parts[1].strip() return title, description def parse_apis(apis_string: str) -> typing.List[str]: """ Parse the `Relevant API` section and get a list of APIs. :param apis_string: A string containing all APIs. :return: A sorted list of stripped API names. """ apis = list(filter(bool, apis_string.splitlines())) if not apis: raise Exception('README Relevant API parse failure!') return sorted([api.lstrip('*- ').rstrip() for api in apis]) def parse_tags(tags_string: str) -> typing.List[str]: """ Parse the `Tags` section and get a list of tags. :param tags_string: A string containing all tags, with comma as delimiter. :return: A sorted list of stripped tags. """ tags = tags_string.split(',') if not tags: raise Exception('README Tags parse failure!') return sorted([tag.strip() for tag in tags]) def get_folder_name_from_path(path: str, index: int = -1) -> str: """ Get the folder name from a full path. :param path: A string of a full/absolute path to a folder. :param index: The index of path parts. Default to -1 to get the most trailing folder in the path; set to certain index to get other parts. :return: The folder name. """ return os.path.normpath(path).split(os.path.sep)[index] # endregion class MetadataCreator: def __init__(self, folder_path: str): """ The standard format of metadata.json for iOS platform. Read more at: /common-samples/wiki/README.metadata.json """ self.category = '' # Populate from path. self.description = '' # Populate from README. self.ignore = False # Default to False. self.images = [] # Populate from paths. self.keywords = [] # Populate from README. self.redirect_from = [] # Default to empty list. self.relevant_apis = [] # Populate from README. self.snippets = [] # Populate from paths. self.title = '' # Populate from README. self.folder_path = folder_path self.folder_name = get_folder_name_from_path(folder_path) self.readme_path = os.path.join(folder_path, 'README.md') self.json_path = os.path.join(folder_path, 'README.metadata.json') def get_source_code_paths(self) -> typing.List[str]: """ Traverse the directory and get all filenames for source code. :return: A list of swift source code filenames. """ results = [] for file in os.listdir(self.folder_path): if os.path.splitext(file)[1] in ['.swift']: results.append(file) if not results: raise Exception('Unable to get swift source code paths.') return sorted(results) def get_images_paths(self): """ Traverse the directory and get all filenames for images. :return: A list of image filenames. """ results = [] for file in os.listdir(self.folder_path): if os.path.splitext(file)[1].lower() in ['.png', '.gif']: results.append(file) if not results: raise Exception('Unable to get images paths.') return sorted(results) def populate_from_readme(self) -> None: """ Read and parse the sections from README, and fill in the 'title', 'description', 'relevant_apis' and 'keywords' fields in the dictionary for output json. """ try: readme_file = open(self.readme_path, 'r') # read the readme content into a string readme_contents = readme_file.read() except Exception as err: print(f"Error reading README - {self.readme_path} - {err}.") raise err else: readme_file.close() # Use regex to split the README by exactly 2 pound marks, so that they # are separated into paragraphs. pattern = re.compile(r'^#{2}(?!#)\s(.*)', re.MULTILINE) readme_parts = re.split(pattern, readme_contents) try: api_section_index = readme_parts.index('Relevant API') + 1 tags_section_index = readme_parts.index('Tags') + 1 self.title, self.description = parse_head(readme_parts[0]) self.relevant_apis = parse_apis(readme_parts[api_section_index]) keywords = parse_tags(readme_parts[tags_section_index]) # De-duplicate API names in README's Tags section. self.keywords = [w for w in keywords if w not in self.relevant_apis] # "It combines the Tags and the Relevant APIs in the README." # See /runtime/common-samples/wiki/README.metadata.json#keywords self.keywords += self.relevant_apis # self.keywords.sort(key=str.casefold) except Exception as err: print(f'Error parsing README - {self.readme_path} - {err}.') raise err def populate_from_paths(self) -> None: """ Populate category name, source code and image filenames from a sample's folder. """ self.category = get_folder_name_from_path(self.folder_path, -2) try: self.images = self.get_images_paths() self.snippets = self.get_source_code_paths() except Exception as err: print(f"Error parsing paths - {self.folder_name} - {err}.") raise err def flush_to_json_string(self) -> str: """ Write the metadata to a json string. """ data = dict() data["category"] = self.category data["description"] = self.description data["ignore"] = self.ignore data["images"] = self.images data["keywords"] = self.keywords data["redirect_from"] = self.redirect_from data["relevant_apis"] = self.relevant_apis data["snippets"] = self.snippets data["title"] = self.title return json.dumps(data, indent=4, sort_keys=True) def compare_one_metadata(folder_path: str): """ A handy helper function to create 1 sample's metadata by running the script without passing in arguments, and write to a separate json for comparison. The path may look like '~/arcgis-runtime-samples-ios/arcgis-ios-sdk-samples/Maps/Display a map' """ single_updater = MetadataCreator(folder_path) try: single_updater.populate_from_readme() single_updater.populate_from_paths() except Exception as err: print(f'Error populate failed for - {single_updater.folder_name}.') raise err json_path = os.path.join(folder_path, 'README.metadata.json') try: json_file = open(json_path, 'r') json_data = json.load(json_file) except Exception as err: print(f'Error reading JSON - {folder_path} - {err}') raise err else: json_file.close() # The special rule not to compare the redirect_from. single_updater.redirect_from = json_data['redirect_from'] # The special rule to be lenient on shortened description. # If the original json has a shortened/special char purged description, # then no need to raise an error. if json_data['description'] in sub_special_char(single_updater.description): single_updater.description = json_data['description'] # The special rule to ignore the order of src filenames. # If the original json has all the filenames, then it is good. if sorted(json_data['snippets']) == single_updater.snippets: single_updater.snippets = json_data['snippets'] new = single_updater.flush_to_json_string() original = json.dumps(json_data, indent=4, sort_keys=True) if new != original: raise Exception(f'Error inconsistent metadata - {folder_path}') def all_samples(path: str): """ Run the check on all samples. :param path: The path to 'arcgis-ios-sdk-samples' folder. :return: None. Throws if exception occurs. """ exception_count = 0 for root, dirs, files in os.walk(path): # Get parent folder name. parent_folder_name = get_folder_name_from_path(root) # If parent folder name is a valid category name. if parent_folder_name in categories: for dir_name in dirs: sample_path = os.path.join(root, dir_name) # Omit empty folders - they are omitted by Git. if len([f for f in os.listdir(sample_path) if not f.startswith('.DS_Store')]) == 0: continue try: compare_one_metadata(sample_path) except Exception as err: exception_count += 1 print(f'{exception_count}. {err}') # Throw once if there are exceptions. if exception_count > 0: raise Exception('Error(s) occurred during checking all samples.') def main(): # Initialize parser. msg = 'Check metadata style. Run it against the /arcgis-ios-sdk-samples ' \ 'folder or a single sample folder. ' \ 'On success: Script will exit with zero. ' \ 'On failure: Title inconsistency will print to console and the ' \ 'script will exit with non-zero code.' parser = argparse.ArgumentParser(description=msg) parser.add_argument('-a', '--all', help='path to arcgis-ios-sdk-samples ' 'folder') parser.add_argument('-s', '--single', help='path to a single sample') args = parser.parse_args() if args.all: try: all_samples(args.all) except Exception as err: raise err elif args.single: try: compare_one_metadata(args.single) except Exception as err: raise err else: raise Exception('Invalid arguments, abort.') if __name__ == '__main__': try: main() except Exception as error: print(f'{error}') exit(1)
common/py_utils/py_utils/retry_util.py
tingshao/catapult
1,894
148366
<filename>common/py_utils/py_utils/retry_util.py<gh_stars>1000+ # Copyright 2018 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. from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import logging import time from six.moves import range # pylint: disable=redefined-builtin def RetryOnException(exc_type, retries): """Decorator to retry running a function if an exception is raised. Implements exponential backoff to wait between each retry attempt, starting with 1 second. Note: the default number of retries is defined on the decorator, the decorated function *must* also receive a "retries" argument (although its assigned default value is ignored), and clients of the funtion may override the actual number of retries at the call site. The "unused" retries argument on the decorated function must be given to keep pylint happy and to avoid breaking the Principle of Least Astonishment if the decorator were to change the signature of the function. For example: @retry_util.RetryOnException(OSError, retries=3) # default no. of retries def ProcessSomething(thing, retries=None): # this default value is ignored del retries # Unused. Handled by the decorator. # Do your thing processing here, maybe sometimes raising exeptions. ProcessSomething(a_thing) # retries 3 times. ProcessSomething(b_thing, retries=5) # retries 5 times. Args: exc_type: An exception type (or a tuple of them), on which to retry. retries: Default number of extra attempts to try, the caller may also override this number. If an exception is raised during the last try, then the exception is not caught and passed back to the caller. """ def Decorator(f): @functools.wraps(f) def Wrapper(*args, **kwargs): wait = 1 kwargs.setdefault('retries', retries) for _ in range(kwargs['retries']): try: return f(*args, **kwargs) except exc_type as exc: logging.warning( '%s raised %s, will retry in %d second%s ...', f.__name__, type(exc).__name__, wait, '' if wait == 1 else 's') time.sleep(wait) wait *= 2 # Last try with no exception catching. return f(*args, **kwargs) return Wrapper return Decorator
util/minorview/model.py
qianlong4526888/haha
135
148368
# Copyright (c) 2013 ARM Limited # All rights reserved # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implementation of the functionality of the software # licensed hereunder. You may use the software subject to the license # terms below provided that you ensure that this notice is replicated # unmodified and in its entirety in all distributions of the software, # modified or unmodified, in source code or in binary form. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer; # redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution; # neither the name of the copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Authors: <NAME> import parse import colours from colours import unknownColour from point import Point import re import blobs from time import time as wall_time import os id_parts = "TSPLFE" all_ids = set(id_parts) no_ids = set([]) class BlobDataSelect(object): """Represents which data is displayed for Ided object""" def __init__(self): # Copy all_ids self.ids = set(all_ids) def __and__(self, rhs): """And for filtering""" ret = BlobDataSelect() ret.ids = self.ids.intersection(rhs.ids) return ret class BlobVisualData(object): """Super class for block data colouring""" def to_striped_block(self, select): """Return an array of colours to use for a striped block""" return unknownColour def get_inst(self): """Get an instruction Id (if any) from this data""" return None def get_line(self): """Get a line Id (if any) from this data""" return None def __repr__(self): return self.__class__.__name__ + '().from_string(' + \ self.__str__() + ')' def __str__(self): return '' class Id(BlobVisualData): """A line or instruction id""" def __init__(self): self.isFault = False self.threadId = 0 self.streamSeqNum = 0 self.predictionSeqNum = 0 self.lineSeqNum = 0 self.fetchSeqNum = 0 self.execSeqNum = 0 def as_list(self): return [self.threadId, self.streamSeqNum, self.predictionSeqNum, self.lineSeqNum, self.fetchSeqNum, self.execSeqNum] def __cmp__(self, right): return cmp(self.as_list(), right.as_list()) def from_string(self, string): m = re.match('^(F;)?(\d+)/(\d+)\.(\d+)/(\d+)(/(\d+)(\.(\d+))?)?', string) def seqnum_from_string(string): if string is None: return 0 else: return int(string) if m is None: print 'Invalid Id string', string else: elems = m.groups() if elems[0] is not None: self.isFault = True else: self.isFault = False self.threadId = seqnum_from_string(elems[1]) self.streamSeqNum = seqnum_from_string(elems[2]) self.predictionSeqNum = seqnum_from_string(elems[3]) self.lineSeqNum = seqnum_from_string(elems[4]) self.fetchSeqNum = seqnum_from_string(elems[6]) self.execSeqNum = seqnum_from_string(elems[8]) return self def get_inst(self): if self.fetchSeqNum != 0: return self else: return None def get_line(self): return self def __str__(self): """Returns the usual id T/S.P/L/F.E string""" return ( str(self.threadId) + '/' + str(self.streamSeqNum) + '.' + str(self.predictionSeqNum) + '/' + str(self.lineSeqNum) + '/' + str(self.fetchSeqNum) + '.' + str(self.execSeqNum)) def to_striped_block(self, select): ret = [] if self.isFault: ret.append(colours.faultColour) if 'T' in select.ids: ret.append(colours.number_to_colour(self.threadId)) if 'S' in select.ids: ret.append(colours.number_to_colour(self.streamSeqNum)) if 'P' in select.ids: ret.append(colours.number_to_colour(self.predictionSeqNum)) if 'L' in select.ids: ret.append(colours.number_to_colour(self.lineSeqNum)) if self.fetchSeqNum != 0 and 'F' in select.ids: ret.append(colours.number_to_colour(self.fetchSeqNum)) if self.execSeqNum != 0 and 'E' in select.ids: ret.append(colours.number_to_colour(self.execSeqNum)) if len(ret) == 0: ret = [colours.unknownColour] if self.isFault: ret.append(colours.faultColour) return ret class Branch(BlobVisualData): """Branch data new stream and prediction sequence numbers, a branch reason and a new PC""" def __init__(self): self.newStreamSeqNum = 0 self.newPredictionSeqNum = 0 self.newPC = 0 self.reason = "NoBranch" self.id = Id() def from_string(self, string): m = re.match('^(\w+);(\d+)\.(\d+);([0-9a-fA-Fx]+);(.*)$', string) if m is not None: self.reason, newStreamSeqNum, newPredictionSeqNum, \ newPC, id = m.groups() self.newStreamSeqNum = int(newStreamSeqNum) self.newPredictionSeqNum = int(newPredictionSeqNum) self.newPC = int(newPC, 0) self.id = special_view_decoder(Id)(id) # self.branch = special_view_decoder(Branch)(branch) else: print "Bad Branch data:", string return self def to_striped_block(self, select): return [colours.number_to_colour(self.newStreamSeqNum), colours.number_to_colour(self.newPredictionSeqNum), colours.number_to_colour(self.newPC)] class Counts(BlobVisualData): """Treat the input data as just a /-separated list of count values (or just a single value)""" def __init__(self): self.counts = [] def from_string(self, string): self.counts = map(int, re.split('/', string)) return self def to_striped_block(self, select): return map(colours.number_to_colour, self.counts) class Colour(BlobVisualData): """A fixed colour block, used for special colour decoding""" def __init__(self, colour): self.colour = colour def to_striped_block(self, select): return [self.colour] class DcacheAccess(BlobVisualData): """Data cache accesses [RW];id""" def __init__(self): self.direc = 'R' self.id = Id() def from_string(self, string): self.direc, id = re.match('^([RW]);([^;]*);.*$', string).groups() self.id.from_string(id) return self def get_inst(self): return self.id def to_striped_block(self, select): if self.direc == 'R': direc_colour = colours.readColour elif self.direc == 'R': direc_colour = colours.writeColour else: direc_colour = colours.errorColour return [direc_colour] + self.id.to_striped_block(select) class ColourPattern(object): """Super class for decoders that make 2D grids rather than just single striped blocks""" def elems(self): return [] def to_striped_block(self, select): return [[[colours.errorColour]]] def special_view_decoder(class_): """Generate a decode function that checks for special character arguments first (and generates a fixed colour) before building a BlobVisualData of the given class""" def decode(symbol): if symbol in special_state_colours: return Colour(special_state_colours[symbol]) else: return class_().from_string(symbol) return decode class TwoDColours(ColourPattern): """A 2D grid pattern decoder""" def __init__(self, blockss): self.blockss = blockss @classmethod def decoder(class_, elemClass, dataName): """Factory for making decoders for particular block types""" def decode(pairs): if dataName not in pairs: print 'TwoDColours: no event data called:', \ dataName, 'in:', pairs return class_([[Colour(colours.errorColour)]]) else: parsed = parse.list_parser(pairs[dataName]) return class_(parse.map2(special_view_decoder(elemClass), \ parsed)) return decode @classmethod def indexed_decoder(class_, elemClass, dataName, picPairs): """Factory for making decoders for particular block types but where the list elements are pairs of (index, data) and strip and stripelems counts are picked up from the pair data on the decoder's picture file. This gives a 2D layout of the values with index 0 at strip=0, elem=0 and index 1 at strip=0, elem=1""" def decode(pairs): if dataName not in pairs: print 'TwoDColours: no event data called:', \ dataName, 'in:', pairs return class_([[Colour(colours.errorColour)]]) else: strips = int(picPairs['strips']) strip_elems = int(picPairs['stripelems']) raw_iv_pairs = pairs[dataName] parsed = parse.parse_indexed_list(raw_iv_pairs) array = [[Colour(colours.emptySlotColour) for i in xrange(0, strip_elems)] for j in xrange(0, strips)] for index, value in parsed: try: array[index % strips][index / strips] = \ special_view_decoder(elemClass)(value) except: print "Element out of range strips: %d," \ " stripelems %d, index: %d" % (strips, strip_elems, index) # return class_(array) return class_(array) return decode def elems(self): """Get a flat list of all elements""" ret = [] for blocks in self.blockss: ret += blocks return ret def to_striped_block(self, select): return parse.map2(lambda d: d.to_striped_block(select), self.blockss) class FrameColours(ColourPattern): """Decode to a 2D grid which has a single occupied row from the event data and some blank rows forming a frame with the occupied row as a 'title' coloured stripe""" def __init__(self, block, numBlankSlots): self.numBlankSlots = numBlankSlots self.block = block @classmethod def decoder(class_, elemClass, numBlankSlots, dataName): """Factory for element type""" def decode(pairs): if dataName not in pairs: print 'FrameColours: no event data called:', dataName, \ 'in:', pairs return class_([Colour(colours.errorColour)]) else: parsed = parse.list_parser(pairs[dataName]) return class_(special_view_decoder(elemClass) (parsed[0][0]), numBlankSlots) return decode def elems(self): return [self.block] def to_striped_block(self, select): return ([[self.block.to_striped_block(select)]] + (self.numBlankSlots * [[[colours.backgroundColour]]])) special_state_colours = { 'U': colours.unknownColour, 'B': colours.blockedColour, '-': colours.bubbleColour, '': colours.emptySlotColour, 'E': colours.emptySlotColour, 'R': colours.reservedSlotColour, 'X': colours.errorColour, 'F': colours.faultColour, 'r': colours.readColour, 'w': colours.writeColour } special_state_names = { 'U': '(U)nknown', 'B': '(B)locked', '-': '(-)Bubble', '': '()Empty', 'E': '(E)mpty', 'R': '(R)eserved', 'X': '(X)Error', 'F': '(F)ault', 'r': '(r)ead', 'w': '(w)rite' } special_state_chars = special_state_colours.keys() # The complete set of available block data types decoder_element_classes = { 'insts': Id, 'lines': Id, 'branch': Branch, 'dcache': DcacheAccess, 'counts': Counts } indexed_decoder_element_classes = { 'indexedCounts' : Counts } def find_colour_decoder(stripSpace, decoderName, dataName, picPairs): """Make a colour decoder from some picture file blob attributes""" if decoderName == 'frame': return FrameColours.decoder(Counts, stripSpace, dataName) elif decoderName in decoder_element_classes: return TwoDColours.decoder(decoder_element_classes[decoderName], dataName) elif decoderName in indexed_decoder_element_classes: return TwoDColours.indexed_decoder( indexed_decoder_element_classes[decoderName], dataName, picPairs) else: return None class IdedObj(object): """An object identified by an Id carrying paired data. The super class for Inst and Line""" def __init__(self, id, pairs={}): self.id = id self.pairs = pairs def __cmp__(self, right): return cmp(self.id, right.id) def table_line(self): """Represent the object as a list of table row data""" return [] # FIXME, add a table column titles? def __repr__(self): return ' '.join(self.table_line()) class Inst(IdedObj): """A non-fault instruction""" def __init__(self, id, disassembly, addr, pairs={}): super(Inst,self).__init__(id, pairs) if 'nextAddr' in pairs: self.nextAddr = int(pairs['nextAddr'], 0) del pairs['nextAddr'] else: self.nextAddr = None self.disassembly = disassembly self.addr = addr def table_line(self): if self.nextAddr is not None: addrStr = '0x%x->0x%x' % (self.addr, self.nextAddr) else: addrStr = '0x%x' % self.addr ret = [addrStr, self.disassembly] for name, value in self.pairs.iteritems(): ret.append("%s=%s" % (name, str(value))) return ret class InstFault(IdedObj): """A fault instruction""" def __init__(self, id, fault, addr, pairs={}): super(InstFault,self).__init__(id, pairs) self.fault = fault self.addr = addr def table_line(self): ret = ["0x%x" % self.addr, self.fault] for name, value in self.pairs: ret.append("%s=%s", name, str(value)) return ret class Line(IdedObj): """A fetched line""" def __init__(self, id, vaddr, paddr, size, pairs={}): super(Line,self).__init__(id, pairs) self.vaddr = vaddr self.paddr = paddr self.size = size def table_line(self): ret = ["0x%x/0x%x" % (self.vaddr, self.paddr), "%d" % self.size] for name, value in self.pairs: ret.append("%s=%s", name, str(value)) return ret class LineFault(IdedObj): """A faulting line""" def __init__(self, id, fault, vaddr, pairs={}): super(LineFault,self).__init__(id, pairs) self.vaddr = vaddr self.fault = fault def table_line(self): ret = ["0x%x" % self.vaddr, self.fault] for name, value in self.pairs: ret.append("%s=%s", name, str(value)) return ret class BlobEvent(object): """Time event for a single blob""" def __init__(self, unit, time, pairs = {}): # blob's unit name self.unit = unit self.time = time # dict of picChar (blob name) to visual data self.visuals = {} # Miscellaneous unparsed MinorTrace line data self.pairs = pairs # Non-MinorTrace debug printout for this unit at this time self.comments = [] def find_ided_objects(self, model, picChar, includeInstLines): """Find instructions/lines mentioned in the blob's event data""" ret = [] if picChar in self.visuals: blocks = self.visuals[picChar].elems() def find_inst(data): instId = data.get_inst() lineId = data.get_line() if instId is not None: inst = model.find_inst(instId) line = model.find_line(instId) if inst is not None: ret.append(inst) if includeInstLines and line is not None: ret.append(line) elif lineId is not None: line = model.find_line(lineId) if line is not None: ret.append(line) map(find_inst, blocks) return sorted(ret) class BlobModel(object): """Model bringing together blob definitions and parsed events""" def __init__(self, unitNamePrefix=''): self.blobs = [] self.unitNameToBlobs = {} self.unitEvents = {} self.clear_events() self.picSize = Point(20,10) self.lastTime = 0 self.unitNamePrefix = unitNamePrefix def clear_events(self): """Drop all events and times""" self.lastTime = 0 self.times = [] self.insts = {} self.lines = {} self.numEvents = 0 for unit, events in self.unitEvents.iteritems(): self.unitEvents[unit] = [] def add_blob(self, blob): """Add a parsed blob to the model""" self.blobs.append(blob) if blob.unit not in self.unitNameToBlobs: self.unitNameToBlobs[blob.unit] = [] self.unitNameToBlobs[blob.unit].append(blob) def add_inst(self, inst): """Add a MinorInst instruction definition to the model""" # Is this a non micro-op instruction. Microops (usually) get their # fetchSeqNum == 0 varient stored first macroop_key = (inst.id.fetchSeqNum, 0) full_key = (inst.id.fetchSeqNum, inst.id.execSeqNum) if inst.id.execSeqNum != 0 and macroop_key not in self.insts: self.insts[macroop_key] = inst self.insts[full_key] = inst def find_inst(self, id): """Find an instruction either as a microop or macroop""" macroop_key = (id.fetchSeqNum, 0) full_key = (id.fetchSeqNum, id.execSeqNum) if full_key in self.insts: return self.insts[full_key] elif macroop_key in self.insts: return self.insts[macroop_key] else: return None def add_line(self, line): """Add a MinorLine line to the model""" self.lines[line.id.lineSeqNum] = line def add_unit_event(self, event): """Add a single event to the model. This must be an event at a time >= the current maximum time""" if event.unit in self.unitEvents: events = self.unitEvents[event.unit] if len(events) > 0 and events[len(events)-1].time > event.time: print "Bad event ordering" events.append(event) self.numEvents += 1 self.lastTime = max(self.lastTime, event.time) def extract_times(self): """Extract a list of all the times from the seen events. Call after reading events to give a safe index list to use for time indices""" times = {} for unitEvents in self.unitEvents.itervalues(): for event in unitEvents: times[event.time] = 1 self.times = times.keys() self.times.sort() def find_line(self, id): """Find a line by id""" key = id.lineSeqNum return self.lines.get(key, None) def find_event_bisection(self, unit, time, events, lower_index, upper_index): """Find an event by binary search on time indices""" while lower_index <= upper_index: pivot = (upper_index + lower_index) / 2 pivotEvent = events[pivot] event_equal = (pivotEvent.time == time or (pivotEvent.time < time and (pivot == len(events) - 1 or events[pivot + 1].time > time))) if event_equal: return pivotEvent elif time > pivotEvent.time: if pivot == upper_index: return None else: lower_index = pivot + 1 elif time < pivotEvent.time: if pivot == lower_index: return None else: upper_index = pivot - 1 else: return None return None def find_unit_event_by_time(self, unit, time): """Find the last event for the given unit at time <= time""" if unit in self.unitEvents: events = self.unitEvents[unit] ret = self.find_event_bisection(unit, time, events, 0, len(events)-1) return ret else: return None def find_time_index(self, time): """Find a time index close to the given time (where times[return] <= time and times[return+1] > time""" ret = 0 lastIndex = len(self.times) - 1 while ret < lastIndex and self.times[ret + 1] <= time: ret += 1 return ret def add_minor_inst(self, rest): """Parse and add a MinorInst line to the model""" pairs = parse.parse_pairs(rest) other_pairs = dict(pairs) id = Id().from_string(pairs['id']) del other_pairs['id'] addr = int(pairs['addr'], 0) del other_pairs['addr'] if 'inst' in other_pairs: del other_pairs['inst'] # Collapse unnecessary spaces in disassembly disassembly = re.sub(' *', ' ', re.sub('^ *', '', pairs['inst'])) inst = Inst(id, disassembly, addr, other_pairs) self.add_inst(inst) elif 'fault' in other_pairs: del other_pairs['fault'] inst = InstFault(id, pairs['fault'], addr, other_pairs) self.add_inst(inst) def add_minor_line(self, rest): """Parse and add a MinorLine line to the model""" pairs = parse.parse_pairs(rest) other_pairs = dict(pairs) id = Id().from_string(pairs['id']) del other_pairs['id'] vaddr = int(pairs['vaddr'], 0) del other_pairs['vaddr'] if 'paddr' in other_pairs: del other_pairs['paddr'] del other_pairs['size'] paddr = int(pairs['paddr'], 0) size = int(pairs['size'], 0) self.add_line(Line(id, vaddr, paddr, size, other_pairs)) elif 'fault' in other_pairs: del other_pairs['fault'] self.add_line(LineFault(id, pairs['fault'], vaddr, other_pairs)) def load_events(self, file, startTime=0, endTime=None): """Load an event file and add everything to this model""" def update_comments(comments, time): # Add a list of comments to an existing event, if there is one at # the given time, or create a new, correctly-timed, event from # the last event and attach the comments to that for commentUnit, commentRest in comments: event = self.find_unit_event_by_time(commentUnit, time) # Find an event to which this comment can be attached if event is None: # No older event, make a new empty one event = BlobEvent(commentUnit, time, {}) self.add_unit_event(event) elif event.time != time: # Copy the old event and make a new one with the right # time and comment newEvent = BlobEvent(commentUnit, time, event.pairs) newEvent.visuals = dict(event.visuals) event = newEvent self.add_unit_event(event) event.comments.append(commentRest) self.clear_events() # A negative time will *always* be different from an event time time = -1 time_events = {} last_time_lines = {} minor_trace_line_count = 0 comments = [] default_colour = [[colours.unknownColour]] next_progress_print_event_count = 1000 if not os.access(file, os.R_OK): print 'Can\'t open file', file exit(1) else: print 'Opening file', file f = open(file) start_wall_time = wall_time() # Skip leading events still_skipping = True l = f.readline() while l and still_skipping: match = re.match('^\s*(\d+):', l) if match is not None: event_time = match.groups() if int(event_time[0]) >= startTime: still_skipping = False else: l = f.readline() else: l = f.readline() match_line_re = re.compile( '^\s*(\d+):\s*([\w\.]+):\s*(Minor\w+:)?\s*(.*)$') # Parse each line of the events file, accumulating comments to be # attached to MinorTrace events when the time changes reached_end_time = False while not reached_end_time and l: match = match_line_re.match(l) if match is not None: event_time, unit, line_type, rest = match.groups() event_time = int(event_time) unit = re.sub('^' + self.unitNamePrefix + '\.?(.*)$', '\\1', unit) # When the time changes, resolve comments if event_time != time: if self.numEvents > next_progress_print_event_count: print ('Parsed to time: %d' % event_time) next_progress_print_event_count = ( self.numEvents + 1000) update_comments(comments, time) comments = [] time = event_time if line_type is None: # Treat this line as just a 'comment' comments.append((unit, rest)) elif line_type == 'MinorTrace:': minor_trace_line_count += 1 # Only insert this event if it's not the same as # the last event we saw for this unit if last_time_lines.get(unit, None) != rest: event = BlobEvent(unit, event_time, {}) pairs = parse.parse_pairs(rest) event.pairs = pairs # Try to decode the colour data for this event blobs = self.unitNameToBlobs.get(unit, []) for blob in blobs: if blob.visualDecoder is not None: event.visuals[blob.picChar] = ( blob.visualDecoder(pairs)) self.add_unit_event(event) last_time_lines[unit] = rest elif line_type == 'MinorInst:': self.add_minor_inst(rest) elif line_type == 'MinorLine:': self.add_minor_line(rest) if endTime is not None and time > endTime: reached_end_time = True l = f.readline() update_comments(comments, time) self.extract_times() f.close() end_wall_time = wall_time() print 'Total events:', minor_trace_line_count, 'unique events:', \ self.numEvents print 'Time to parse:', end_wall_time - start_wall_time def add_blob_picture(self, offset, pic, nameDict): """Add a parsed ASCII-art pipeline markup to the model""" pic_width = 0 for line in pic: pic_width = max(pic_width, len(line)) pic_height = len(pic) # Number of horizontal characters per 'pixel'. Should be 2 charsPerPixel = 2 # Clean up pic_width to a multiple of charsPerPixel pic_width = (pic_width + charsPerPixel - 1) // 2 self.picSize = Point(pic_width, pic_height) def pic_at(point): """Return the char pair at the given point. Returns None for characters off the picture""" x, y = point.to_pair() x *= 2 if y >= len(pic) or x >= len(pic[y]): return None else: return pic[y][x:x + charsPerPixel] def clear_pic_at(point): """Clear the chars at point so we don't trip over them again""" line = pic[point.y] x = point.x * charsPerPixel pic[point.y] = line[0:x] + (' ' * charsPerPixel) + \ line[x + charsPerPixel:] def skip_same_char(start, increment): """Skip characters which match pic_at(start)""" char = pic_at(start) hunt = start while pic_at(hunt) == char: hunt += increment return hunt def find_size(start): """Find the size of a rectangle with top left hand corner at start consisting of (at least) a -. shaped corner describing the top right corner of a rectangle of the same char""" char = pic_at(start) hunt_x = skip_same_char(start, Point(1,0)) hunt_y = skip_same_char(start, Point(0,1)) off_bottom_right = (hunt_x * Point(1,0)) + (hunt_y * Point(0,1)) return off_bottom_right - start def point_return(point): """Carriage return, line feed""" return Point(0, point.y + 1) def find_arrow(start): """Find a simple 1-char wide arrow""" def body(endChar, contChar, direc): arrow_point = start arrow_point += Point(0, 1) clear_pic_at(start) while pic_at(arrow_point) == contChar: clear_pic_at(arrow_point) arrow_point += Point(0, 1) if pic_at(arrow_point) == endChar: clear_pic_at(arrow_point) self.add_blob(blobs.Arrow('_', start + offset, direc = direc, size = (Point(1, 1) + arrow_point - start))) else: print 'Bad arrow', start char = pic_at(start) if char == '-\\': body('-/', ' :', 'right') elif char == '/-': body('\\-', ': ', 'left') blank_chars = [' ', ' :', ': '] # Traverse the picture left to right, top to bottom to find blobs seen_dict = {} point = Point(0,0) while pic_at(point) is not None: while pic_at(point) is not None: char = pic_at(point) if char == '->': self.add_blob(blobs.Arrow('_', point + offset, direc = 'right')) elif char == '<-': self.add_blob(blobs.Arrow('_', point + offset, direc = 'left')) elif char == '-\\' or char == '/-': find_arrow(point) elif char in blank_chars: pass else: if char not in seen_dict: size = find_size(point) topLeft = point + offset if char not in nameDict: # Unnamed blobs self.add_blob(blobs.Block(char, nameDict.get(char, '_'), topLeft, size = size)) else: # Named blobs, set visual info. blob = nameDict[char] blob.size = size blob.topLeft = topLeft self.add_blob(blob) seen_dict[char] = True point = skip_same_char(point, Point(1,0)) point = point_return(point) def load_picture(self, filename): """Load a picture file into the model""" def parse_blob_description(char, unit, macros, pairsList): # Parse the name value pairs in a blob-describing line def expand_macros(pairs, newPairs): # Recursively expand macros for name, value in newPairs: if name in macros: expand_macros(pairs, macros[name]) else: pairs[name] = value return pairs pairs = expand_macros({}, pairsList) ret = None typ = pairs.get('type', 'block') colour = colours.name_to_colour(pairs.get('colour', 'black')) if typ == 'key': ret = blobs.Key(char, unit, Point(0,0), colour) elif typ == 'block': ret = blobs.Block(char, unit, Point(0,0), colour) else: print "Bad picture blog type:", typ if 'hideId' in pairs: hide = pairs['hideId'] ret.dataSelect.ids -= set(hide) if typ == 'block': ret.displayName = pairs.get('name', unit) ret.nameLoc = pairs.get('nameLoc', 'top') ret.shape = pairs.get('shape', 'box') ret.stripDir = pairs.get('stripDir', 'horiz') ret.stripOrd = pairs.get('stripOrd', 'LR') ret.blankStrips = int(pairs.get('blankStrips', '0')) ret.shorten = int(pairs.get('shorten', '0')) if 'decoder' in pairs: decoderName = pairs['decoder'] dataElement = pairs.get('dataElement', decoderName) decoder = find_colour_decoder(ret.blankStrips, decoderName, dataElement, pairs) if decoder is not None: ret.visualDecoder = decoder else: print 'Bad visualDecoder requested:', decoderName if 'border' in pairs: border = pairs['border'] if border == 'thin': ret.border = 0.2 elif border == 'mid': ret.border = 0.5 else: ret.border = 1.0 elif typ == 'key': ret.colours = pairs.get('colours', ret.colours) return ret def line_is_comment(line): """Returns true if a line starts with #, returns False for lines which are None""" return line is not None \ and re.match('^\s*#', line) is not None def get_line(f): """Get a line from file f extending that line if it ends in '\' and dropping lines that start with '#'s""" ret = f.readline() # Discard comment lines while line_is_comment(ret): ret = f.readline() if ret is not None: extend_match = re.match('^(.*)\\\\$', ret) while extend_match is not None: new_line = f.readline() if new_line is not None and not line_is_comment(new_line): line_wo_backslash, = extend_match.groups() ret = line_wo_backslash + new_line extend_match = re.match('^(.*)\\\\$', ret) else: extend_match = None return ret # Macros are recursively expanded into name=value pairs macros = {} if not os.access(filename, os.R_OK): print 'Can\'t open file', filename exit(1) else: print 'Opening file', filename f = open(filename) l = get_line(f) picture = [] blob_char_dict = {} self.unitEvents = {} self.clear_events() # Actually parse the file in_picture = False while l: l = parse.remove_trailing_ws(l) l = re.sub('#.*', '', l) if re.match("^\s*$", l) is not None: pass elif l == '<<<': in_picture = True elif l == '>>>': in_picture = False elif in_picture: picture.append(re.sub('\s*$', '', l)) else: line_match = re.match( '^([a-zA-Z0-9][a-zA-Z0-9]):\s+([\w.]+)\s*(.*)', l) macro_match = re.match('macro\s+(\w+):(.*)', l) if macro_match is not None: name, defn = macro_match.groups() macros[name] = parse.parse_pairs_list(defn) elif line_match is not None: char, unit, pairs = line_match.groups() blob = parse_blob_description(char, unit, macros, parse.parse_pairs_list(pairs)) blob_char_dict[char] = blob # Setup the events structure self.unitEvents[unit] = [] else: print 'Problem with Blob line:', l l = get_line(f) self.blobs = [] self.add_blob_picture(Point(0,1), picture, blob_char_dict)
social_auth/backends/contrib/yammer_staging.py
merutak/django-social-auth
863
148373
<reponame>merutak/django-social-auth from social.backends.yammer import YammerStagingOAuth2 as YammerStagingBackend
tests/stl_corruption.py
Gjacquenot/numpy-stl
464
148381
from __future__ import print_function import sys import numpy import pytest import struct from stl import mesh _STL_FILE = ''' solid test.stl facet normal -0.014565 0.073223 -0.002897 outer loop vertex 0.399344 0.461940 1.044090 vertex 0.500000 0.500000 1.500000 vertex 0.576120 0.500000 1.117320 endloop endfacet endsolid test.stl '''.lstrip() def test_valid_ascii(tmpdir, speedups): tmp_file = tmpdir.join('tmp.stl') with tmp_file.open('w+') as fh: fh.write(_STL_FILE) fh.seek(0) mesh.Mesh.from_file(str(tmp_file), fh=fh, speedups=speedups) def test_ascii_with_missing_name(tmpdir, speedups): tmp_file = tmpdir.join('tmp.stl') with tmp_file.open('w+') as fh: # Split the file into lines lines = _STL_FILE.splitlines() # Remove everything except solid lines[0] = lines[0].split()[0] # Join the lines to test files that start with solid without space fh.write('\n'.join(lines)) fh.seek(0) mesh.Mesh.from_file(str(tmp_file), fh=fh, speedups=speedups) def test_ascii_with_blank_lines(tmpdir, speedups): _stl_file = ''' solid test.stl facet normal -0.014565 0.073223 -0.002897 outer loop vertex 0.399344 0.461940 1.044090 vertex 0.500000 0.500000 1.500000 vertex 0.576120 0.500000 1.117320 endloop endfacet endsolid test.stl '''.lstrip() tmp_file = tmpdir.join('tmp.stl') with tmp_file.open('w+') as fh: fh.write(_stl_file) fh.seek(0) mesh.Mesh.from_file(str(tmp_file), fh=fh, speedups=speedups) def test_incomplete_ascii_file(tmpdir, speedups): tmp_file = tmpdir.join('tmp.stl') with tmp_file.open('w+') as fh: fh.write('solid some_file.stl') fh.seek(0) with pytest.raises(AssertionError): mesh.Mesh.from_file(str(tmp_file), fh=fh, speedups=speedups) for offset in (-20, 82, 100): with tmp_file.open('w+') as fh: fh.write(_STL_FILE[:-offset]) fh.seek(0) with pytest.raises(AssertionError): mesh.Mesh.from_file(str(tmp_file), fh=fh, speedups=speedups) def test_corrupt_ascii_file(tmpdir, speedups): tmp_file = tmpdir.join('tmp.stl') with tmp_file.open('w+') as fh: fh.write(_STL_FILE) fh.seek(40) print('####\n' * 100, file=fh) fh.seek(0) if speedups and sys.version_info.major != 2: with pytest.raises(AssertionError): mesh.Mesh.from_file(str(tmp_file), fh=fh, speedups=speedups) with tmp_file.open('w+') as fh: fh.write(_STL_FILE) fh.seek(40) print(' ' * 100, file=fh) fh.seek(80) fh.write(struct.pack('<i', 10).decode('utf-8')) fh.seek(0) with pytest.raises(AssertionError): mesh.Mesh.from_file(str(tmp_file), fh=fh, speedups=speedups) def test_corrupt_binary_file(tmpdir, speedups): tmp_file = tmpdir.join('tmp.stl') with tmp_file.open('w+') as fh: fh.write('#########\n' * 8) fh.write('#\0\0\0') fh.seek(0) mesh.Mesh.from_file(str(tmp_file), fh=fh, speedups=speedups) with tmp_file.open('w+') as fh: fh.write('#########\n' * 9) fh.seek(0) with pytest.raises(AssertionError): mesh.Mesh.from_file(str(tmp_file), fh=fh, speedups=speedups) with tmp_file.open('w+') as fh: fh.write('#########\n' * 8) fh.write('#\0\0\0') fh.seek(0) fh.write('solid test.stl') fh.seek(0) mesh.Mesh.from_file(str(tmp_file), fh=fh, speedups=speedups) def test_duplicate_polygons(): data = numpy.zeros(3, dtype=mesh.Mesh.dtype) data['vectors'][0] = numpy.array([[0, 0, 0], [1, 0, 0], [0, 1, 1.]]) data['vectors'][0] = numpy.array([[0, 0, 0], [2, 0, 0], [0, 2, 1.]]) data['vectors'][0] = numpy.array([[0, 0, 0], [3, 0, 0], [0, 3, 1.]]) assert not mesh.Mesh(data, remove_empty_areas=False).check()
Python/tdw/collisions.py
felixbinder/tdw
307
148423
<filename>Python/tdw/collisions.py from typing import List, Dict import numpy as np from tdw.output_data import OutputData, Collision, EnvironmentCollision from tdw.int_pair import IntPair class CollisionObjObj: """ A collision between two objects. """ def __init__(self, collision: Collision): """ :param collision: The collision output data. """ """:field The contact point positions. """ self.points: List[np.array] = list() """:field The contact point normals. """ self.normals: List[np.array] = list() for i in range(collision.get_num_contacts()): self.points.append(np.array(collision.get_contact_point(i))) self.normals.append(np.array(collision.get_contact_normal(i))) """:field The relative velocity of the objects. """ self.relative_velocity: np.array = np.array(collision.get_relative_velocity()) """:field The state of the collision. """ self.state: str = collision.get_state() class CollisionObjEnv: """ A collision between an object and the environment. """ def __init__(self, collision: EnvironmentCollision): """ :param collision: The collision output data. """ """:field The contact point positions. """ self.points: List[np.array] = list() """:field The contact point normals. """ self.normals: List[np.array] = list() for i in range(collision.get_num_contacts()): self.points.append(np.array(collision.get_contact_point(i))) self.normals.append(np.array(collision.get_contact_normal(i))) """:field The state of the collision. """ self.state: str = collision.get_state() """:field True if this is a collision with the floor. """ self.floor: bool = collision.get_floor() class Collisions: """ A wrapper class for the output data of all collisions from a frame. """ def __init__(self, resp: List[bytes]): """ :param resp: The response from the build. """ """:field All collisions between two objects that occurred on the frame. Key = An `IntPair` (a pair of object IDs). Value = The collision. """ self.obj_collisions: Dict[IntPair, CollisionObjObj] = dict() """:field All collisions between an object and the environment that occurred on the frame. Key = the object ID. Value = The collision. """ self.env_collisions: Dict[int, CollisionObjEnv] = dict() for i in range(len(resp) - 1): r_id = OutputData.get_data_type_id(resp[i]) if r_id == "coll": collision = Collision(resp[i]) # Get the pair of IDs in this collision and use it as a key. ids = IntPair(int1=collision.get_collider_id(), int2=collision.get_collidee_id()) coo = CollisionObjObj(collision=collision) self.obj_collisions[ids] = coo elif r_id == "enco": collision = EnvironmentCollision(resp[i]) coe = CollisionObjEnv(collision=collision) self.env_collisions[collision.get_object_id()] = coe
nzbhydra/searchmodules/jackett.py
Sparklingx/nzbhydra
674
148450
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging import xml.etree.ElementTree as ET import arrow from builtins import * from nzbhydra.categories import getByNewznabCats from nzbhydra.exceptions import IndexerResultParsingException from nzbhydra.nzb_search_result import NzbSearchResult from nzbhydra.search_module import IndexerProcessingResult from nzbhydra.searchmodules import newznab logger = logging.getLogger('root') class Jackett(newznab.NewzNab): # todo feature: read caps from server on first run and store them in the config/database def __init__(self, settings): super(newznab.NewzNab, self).__init__(settings) super(Jackett, self).__init__(settings) self.settings = settings # Already done by super.__init__ but this way PyCharm knows the correct type self.module = "jackett" self.category_search = True self.supportedFilters = ["maxage"] self.supportsNot = False def get_details_link(self, guid): return guid def get_entry_by_id(self, guid, title): self.error("Function not supported") return None def get_search_urls(self, search_request, search_type="search"): f = self.build_base_url(search_type, search_request.category, offset=search_request.offset) query = search_request.query if query: f = f.add({"q": query}) if search_request.maxage: f = f.add({"maxage": search_request.maxage}) return [f.url] def process_query_result(self, xml_response, searchRequest, maxResults=None): self.debug("Started processing results") countRejected = self.getRejectedCountDict() acceptedEntries = [] entries, total, offset = self.parseXml(xml_response, maxResults) for entry in entries: accepted, reason,ri = self.accept_result(entry, searchRequest, self.supportedFilters) if accepted: acceptedEntries.append(entry) else: countRejected[ri] += 1 self.debug("Rejected search result. Reason: %s" % reason) if total == 0 or len(acceptedEntries) == 0: self.info("Query returned no results") return IndexerProcessingResult(entries=acceptedEntries, queries=[], total=0, total_known=True, has_more=False, rejected=countRejected) else: return IndexerProcessingResult(entries=acceptedEntries, queries=[], total=total, total_known=True, has_more=False, rejected=countRejected) def parseXml(self, xmlResponse, maxResults=None): entries = [] try: tree = ET.fromstring(xmlResponse.encode('utf-8')) except Exception: self.exception("Error parsing XML: %s..." % xmlResponse[:500]) raise IndexerResultParsingException("Error parsing XML", self) for item in tree.find("channel").findall("item"): entry = self.parseItem(item) entries.append(entry) if maxResults is not None and len(entries) == maxResults: break return entries, len(entries), 0 def parseItem(self, item): entry = self.create_nzb_search_result() # These are the values that absolutely must be contained in the response entry.title = item.find("title").text entry.title = self.cleanUpTitle(entry.title) entry.link = item.find("link").text entry.details_link = item.find("comments").text entry.indexerguid = item.find("guid").text entry.comments = 0 size = item.find("size") if size is not None: entry.size = int(size.text) entry.attributes = [] entry.has_nfo = NzbSearchResult.HAS_NFO_NO categories = item.find("category") if categories is not None: categories = categories.text entry.category = getByNewznabCats(categories) attributes = item.findall("torznab:attr", {"torznab": "http://torznab.com/schemas/2015/feed"}) attributes.extend(item.findall("newznab:attr", {"newznab": "http://www.newznab.com/DTD/2010/feeds/attributes/"})) for i in attributes: attribute_name = i.attrib["name"] attribute_value = i.attrib["value"] entry.attributes.append({"name": attribute_name, "value": attribute_value}) if attribute_name == "size": entry.size = int(attribute_value) if attribute_name == "grabs": entry.grabs = int(attribute_value) entry.pubDate = item.find("pubDate").text pubDate = arrow.get(entry.pubDate, 'ddd, DD MMM YYYY HH:mm:ss Z') self.getDates(entry, pubDate) entry.downloadType = "torrent" # For some trackers several results with the same ID are returned (e.g. PTP so we need to make sure the ID is unique) entry.indexerguid += str(entry.size) return entry def get_nfo(self, guid): return False, None, "NFOs not supported by indexer" def get_instance(indexer): return Jackett(indexer)
src/projects/tags/tests/test_models.py
augustuswm/flagsmith-api
1,259
148469
<filename>src/projects/tags/tests/test_models.py import pytest from django.test import TestCase from organisations.models import Organisation from projects.models import Project from projects.tags.models import Tag @pytest.mark.django_db class TagsTestCase(TestCase): def setUp(self) -> None: self.organisation = Organisation.objects.create(name="Test Org") self.project = Project.objects.create( name="Test Project", organisation=self.organisation ) def test_create_tag(self): # When tag = Tag.objects.create( label="Test Tag", color="#fffff", description="Test Tag description", project=self.project, ) # Then assert tag.project.id == self.project.id
src/elastic/azext_elastic/tests/latest/test_elastic_scenario.py
haroonf/azure-cli-extensions
207
148485
<filename>src/elastic/azext_elastic/tests/latest/test_elastic_scenario.py # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- import os from azure.cli.testsdk import ScenarioTest from azure.cli.testsdk import ResourceGroupPreparer from .example_steps import step_monitor_create from .example_steps import step_monitor_show from .example_steps import step_monitor_list from .example_steps import step_monitor_list2 from .example_steps import step_monitor_update from .example_steps import step_deployment_info_list from .example_steps import step_monitored_resource_list from .example_steps import step_tag_rule_create from .example_steps import step_tag_rule_show from .example_steps import step_tag_rule_list from .example_steps import step_tag_rule_delete from .example_steps import step_vm_collection_update from .example_steps import step_vm_host_list from .example_steps import step_vm_ingestion_detail from .example_steps import step_monitor_delete from .. import ( try_manual, raise_if, calc_coverage ) TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..')) # Env setup_scenario @try_manual def setup_scenario(test): pass # Env cleanup_scenario @try_manual def cleanup_scenario(test): pass # Testcase: Scenario @try_manual def call_scenario(test): setup_scenario(test) step_monitor_create(test, checks=[ test.check("name", "{myMonitor}", case_sensitive=False), test.check("location", "westus2", case_sensitive=False), test.check("sku.name", "ess-monthly-consumption_Monthly", case_sensitive=False), test.check("tags.Environment", "Dev", case_sensitive=False), ]) step_monitor_show(test, checks=[ test.check("name", "{myMonitor}", case_sensitive=False), test.check("location", "westus2", case_sensitive=False), test.check("tags.Environment", "Dev", case_sensitive=False), ]) step_monitor_list(test, checks=[ test.check('length(@)', 37), ]) step_monitor_list2(test, checks=[ test.check('length(@)', 1), ]) step_monitor_update(test, checks=[ test.check("name", "{myMonitor}", case_sensitive=False), test.check("location", "westus2", case_sensitive=False), test.check("sku.name", "ess-monthly-consumption_Monthly", case_sensitive=False), test.check("tags.Environment", "Dev", case_sensitive=False), ]) step_deployment_info_list(test, checks=[]) step_monitored_resource_list(test, checks=[]) step_tag_rule_create(test, checks=[]) step_tag_rule_show(test, checks=[]) step_tag_rule_list(test, checks=[]) # Error (ResourceDeletionFailed) Resource deletion failed as RP returned status code: 'UnprocessableEntity' # step_tag_rule_delete(test, checks=[]) step_vm_collection_update(test, checks=[]) step_vm_host_list(test, checks=[]) step_vm_ingestion_detail(test, checks=[]) step_monitor_delete(test, checks=[]) cleanup_scenario(test) # Test class for Scenario @try_manual class ElasticScenarioTest(ScenarioTest): def __init__(self, *args, **kwargs): super(ElasticScenarioTest, self).__init__(*args, **kwargs) self.kwargs.update({ 'subscription_id': self.get_subscription_id() }) self.kwargs.update({ 'myMonitor': 'myMonitor', }) @ResourceGroupPreparer(name_prefix='clitestelastic_myResourceGroup'[:7], key='rg', parameter_name='rg') def test_elastic_Scenario(self, rg): call_scenario(self) calc_coverage(__file__) raise_if()
lektor/types/base.py
yagebu/lektor
4,104
148513
from jinja2 import Undefined from lektor.constants import PRIMARY_ALT class BadValue(Undefined): __slots__ = () def get_undefined_info(undefined): if isinstance(undefined, Undefined): try: undefined._fail_with_undefined_error() except Exception as e: return str(e) return "defined value" class RawValue: __slots__ = ("name", "value", "field", "pad") def __init__(self, name, value=None, field=None, pad=None): self.name = name self.value = value self.field = field self.pad = pad def _get_hint(self, prefix, reason): if self.field is not None: return "%s in field '%s': %s" % (prefix, self.field.name, reason) return "%s: %s" % (prefix, reason) def bad_value(self, reason): return BadValue(hint=self._get_hint("Bad value", reason), obj=self.value) def missing_value(self, reason): return Undefined(hint=self._get_hint("Missing value", reason), obj=self.value) class _NameDescriptor: def __get__(self, obj, type): rv = type.__name__ if rv.endswith("Type"): rv = rv[:-4] return rv.lower() class Type: widget = "multiline-text" def __init__(self, env, options): self.env = env self.options = options @property def size(self): size = self.options.get("size") or "normal" if size not in ("normal", "small", "large"): size = "normal" return size @property def width(self): return self.options.get("width") or "1/1" name = _NameDescriptor() def to_json(self, pad, record=None, alt=PRIMARY_ALT): return { "name": self.name, "widget": self.widget, "size": self.size, "width": self.width, } def value_from_raw(self, raw): # pylint: disable=no-self-use return raw def value_from_raw_with_default(self, raw): value = self.value_from_raw(raw) if ( isinstance(value, Undefined) and raw.field is not None and raw.field.default is not None ): return self.value_from_raw( RawValue(raw.name, raw.field.default, field=raw.field, pad=raw.pad) ) return value def __repr__(self): return "%s()" % self.__class__.__name__
tools/build/bazel/angular_workspace.bzl
MohiK98/onos
1,091
148536
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@npm//@bazel/protractor:package.bzl", "npm_bazel_protractor_dependencies") load("@npm//@bazel/karma:package.bzl", "npm_bazel_karma_dependencies") load("@io_bazel_rules_webtesting//web:repositories.bzl", "web_test_repositories") load("@io_bazel_rules_webtesting//web/versioned:browsers-0.3.2.bzl", "browser_repositories") load("@io_bazel_rules_sass//sass:sass_repositories.bzl", "sass_repositories") def load_angular(): npm_bazel_protractor_dependencies() npm_bazel_karma_dependencies() web_test_repositories() browser_repositories( chromium = True, firefox = True, ) sass_repositories()
seahub/repo_api_tokens/utils.py
weimens/seahub
101
148538
import os import logging import posixpath import stat from django.utils.http import urlquote from seaserv import seafile_api from seahub.base.models import UserStarredFiles from seahub.base.templatetags.seahub_tags import email2nickname, email2contact_email from seahub.settings import ENABLE_VIDEO_THUMBNAIL, THUMBNAIL_ROOT from seahub.thumbnail.utils import get_thumbnail_src from seahub.utils import is_pro_version, FILEEXT_TYPE_MAP, IMAGE, XMIND, VIDEO from seahub.utils.file_tags import get_files_tags_in_dir from seahub.utils.repo import is_group_repo_staff, is_repo_owner from seahub.utils.timeutils import timestamp_to_isoformat_timestr logger = logging.getLogger(__name__) json_content_type = 'application/json; charset=utf-8' HTTP_520_OPERATION_FAILED = 520 def permission_check_admin_owner(request, username, repo_id): # maybe add more complex logic in the future """ if repo is owned by user return true or check whether repo is owned by group and whether user is group's staff so finally the code is: check user == repo's owner else check user is the such group's staff """ if is_repo_owner(request, repo_id, username): return True else: return is_group_repo_staff(request, repo_id, username) def get_dir_file_recursively(repo_id, path, all_dirs): is_pro = is_pro_version() path_id = seafile_api.get_dir_id_by_path(repo_id, path) dirs = seafile_api.list_dir_by_path(repo_id, path, -1, -1) for dirent in dirs: entry = {} if stat.S_ISDIR(dirent.mode): entry["type"] = 'dir' else: entry["type"] = 'file' entry['modifier_email'] = dirent.modifier entry["size"] = dirent.size if is_pro: entry["is_locked"] = dirent.is_locked entry["lock_owner"] = dirent.lock_owner if dirent.lock_owner: entry["lock_owner_name"] = email2nickname(dirent.lock_owner) entry["lock_time"] = dirent.lock_time entry["parent_dir"] = path entry["id"] = dirent.obj_id entry["name"] = dirent.obj_name entry["mtime"] = timestamp_to_isoformat_timestr(dirent.mtime) all_dirs.append(entry) # Use dict to reduce memcache fetch cost in large for-loop. file_list = [item for item in all_dirs if item['type'] == 'file'] contact_email_dict = {} nickname_dict = {} modifiers_set = {x['modifier_email'] for x in file_list} for e in modifiers_set: if e not in contact_email_dict: contact_email_dict[e] = email2contact_email(e) if e not in nickname_dict: nickname_dict[e] = email2nickname(e) for e in file_list: e['modifier_contact_email'] = contact_email_dict.get(e['modifier_email'], '') e['modifier_name'] = nickname_dict.get(e['modifier_email'], '') if stat.S_ISDIR(dirent.mode): sub_path = posixpath.join(path, dirent.obj_name) get_dir_file_recursively(repo_id, sub_path, all_dirs) return all_dirs def get_dir_file_info_list(username, request_type, repo_obj, parent_dir, with_thumbnail, thumbnail_size): repo_id = repo_obj.id dir_info_list = [] file_info_list = [] # get dirent(folder and file) list parent_dir_id = seafile_api.get_dir_id_by_path(repo_id, parent_dir) dir_file_list = seafile_api.list_dir_with_perm(repo_id, parent_dir, parent_dir_id, username, -1, -1) try: starred_items = UserStarredFiles.objects.filter(email=username, repo_id=repo_id, path__startswith=parent_dir, org_id=-1) starred_item_path_list = [f.path.rstrip('/') for f in starred_items] except Exception as e: logger.error(e) starred_item_path_list = [] # only get dir info list if not request_type or request_type == 'd': dir_list = [dirent for dirent in dir_file_list if stat.S_ISDIR(dirent.mode)] for dirent in dir_list: dir_info = {} dir_info["type"] = "dir" dir_info["id"] = dirent.obj_id dir_info["name"] = dirent.obj_name dir_info["mtime"] = timestamp_to_isoformat_timestr(dirent.mtime) dir_info["permission"] = dirent.permission dir_info["parent_dir"] = parent_dir dir_info_list.append(dir_info) # get star info dir_info['starred'] = False dir_path = posixpath.join(parent_dir, dirent.obj_name) if dir_path.rstrip('/') in starred_item_path_list: dir_info['starred'] = True # only get file info list if not request_type or request_type == 'f': file_list = [dirent for dirent in dir_file_list if not stat.S_ISDIR(dirent.mode)] # Use dict to reduce memcache fetch cost in large for-loop. nickname_dict = {} contact_email_dict = {} modifier_set = {x.modifier for x in file_list} lock_owner_set = {x.lock_owner for x in file_list} for e in modifier_set | lock_owner_set: if e not in nickname_dict: nickname_dict[e] = email2nickname(e) if e not in contact_email_dict: contact_email_dict[e] = email2contact_email(e) try: files_tags_in_dir = get_files_tags_in_dir(repo_id, parent_dir) except Exception as e: logger.error(e) files_tags_in_dir = {} for dirent in file_list: file_name = dirent.obj_name file_path = posixpath.join(parent_dir, file_name) file_obj_id = dirent.obj_id file_info = {} file_info["type"] = "file" file_info["id"] = file_obj_id file_info["name"] = file_name file_info["mtime"] = timestamp_to_isoformat_timestr(dirent.mtime) file_info["permission"] = dirent.permission file_info["parent_dir"] = parent_dir file_info["size"] = dirent.size modifier_email = dirent.modifier file_info['modifier_email'] = modifier_email file_info['modifier_name'] = nickname_dict.get(modifier_email, '') file_info['modifier_contact_email'] = contact_email_dict.get(modifier_email, '') # get lock info if is_pro_version(): file_info["is_locked"] = dirent.is_locked file_info["lock_time"] = dirent.lock_time lock_owner_email = dirent.lock_owner or '' file_info["lock_owner"] = lock_owner_email file_info['lock_owner_name'] = nickname_dict.get(lock_owner_email, '') file_info['lock_owner_contact_email'] = contact_email_dict.get(lock_owner_email, '') if username == lock_owner_email: file_info["locked_by_me"] = True else: file_info["locked_by_me"] = False # get star info file_info['starred'] = False if file_path.rstrip('/') in starred_item_path_list: file_info['starred'] = True # get tag info file_tags = files_tags_in_dir.get(file_name, []) if file_tags: file_info['file_tags'] = [] for file_tag in file_tags: file_info['file_tags'].append(file_tag) # get thumbnail info if with_thumbnail and not repo_obj.encrypted: # used for providing a way to determine # if send a request to create thumbnail. fileExt = os.path.splitext(file_name)[1][1:].lower() file_type = FILEEXT_TYPE_MAP.get(fileExt) if file_type in (IMAGE, XMIND) or \ file_type == VIDEO and ENABLE_VIDEO_THUMBNAIL: # if thumbnail has already been created, return its src. # Then web browser will use this src to get thumbnail instead of # recreating it. thumbnail_file_path = os.path.join(THUMBNAIL_ROOT, str(thumbnail_size), file_obj_id) if os.path.exists(thumbnail_file_path): src = get_thumbnail_src(repo_id, thumbnail_size, file_path) file_info['encoded_thumbnail_src'] = urlquote(src) file_info_list.append(file_info) dir_info_list.sort(key=lambda x: x['name'].lower()) file_info_list.sort(key=lambda x: x['name'].lower()) return dir_info_list, file_info_list
src/tensorflow2.x-python-tutorial/keras-lambda.py
pepure/SciSharp-Stack-Examples
197
148546
import tensorflow as tf from tensorflow.keras.layers import Input, Dense, Add, Subtract, Lambda from tensorflow.keras.models import Model from tensorflow.keras.optimizers import RMSprop import tensorflow.keras.backend as K c = tf.constant(['a', 'b']) e = tf.math.erf([1.0, -0.5, 3.4, -2.1, 0.0, -6.5]) input = tf.keras.Input(shape=(28, 28, 1), name="img") x = tf.keras.layers.Conv2DTranspose(16, 3, activation="relu")(input) inputs = Input(24) x = Dense(128, activation = "relu")(inputs) value = Dense(24)(x) adv = Dense(1)(x) # meam = Lambda(lambda x: K.mean(x, axis = 1, keepdims = True))(adv) meam = adv - tf.reduce_mean(adv, axis = 1, keepdims = True) adv = Subtract()([adv, meam]) outputs = Add()([value, adv]) model = Model(inputs, outputs) model.compile(loss = "mse", optimizer = RMSprop(1e-3)) model.summary() debug = 1
distributed/__init__.py
merlinarer/scrl
102
148556
<reponame>merlinarer/scrl from .launch import launch from .getters import get_dist_url, scatter_values
hyppo/time_series/tests/test_mgcx.py
zdbzdb1212/hyppo
116
148560
<gh_stars>100-1000 import numpy as np from numpy.testing import assert_almost_equal, assert_array_less from ...tools import nonlinear_process from .. import MGCX class TestMGCXStat: def test_multiple_lags(self): n = 10 x = np.arange(1, n + 1).reshape(n, 1) y = np.arange(1, n + 1).reshape(n, 1) pvalue = MGCX(max_lag=3).test(x, y)[1] assert_almost_equal(pvalue, 1 / 1000, decimal=2) def test_nonlinear(self): np.random.seed(123456789) x, y = nonlinear_process(120, lag=1) _, pvalue, mgcx_dict = MGCX(max_lag=1).test(x, y) opt_lag = mgcx_dict["opt_lag"] assert_almost_equal(pvalue, 1 / 1000, decimal=2) assert_almost_equal(opt_lag, 1, decimal=0) # TO DO: Fix when repeated values are fixed in classic MGC. # def test_lag0(self): # x, y = cross_corr_ar(20, lag=1, phi=0.9) # stat1 = MGC().test(x, y)[0] # stat2 = MGCX(max_lag=0).test(x, y)[0] # assert_almost_equal(stat1, stat2, decimal=0) def test_optimal_scale_linear(self): n = 10 x = np.arange(n) y = x mgcx_dict = MGCX().test(x, y, reps=100)[2] opt_scale = mgcx_dict["opt_scale"] assert_almost_equal(opt_scale[0], n, decimal=0) assert_almost_equal(opt_scale[1], n, decimal=0) def test_optimal_scale_nonlinear(self): n = 7 x = np.arange(n) y = x ** 2 mgcx_dict = MGCX().test(x, y, reps=100)[2] opt_scale = mgcx_dict["opt_scale"] assert_array_less(opt_scale[0], n) assert_array_less(opt_scale[1], n) def test_rep_linear(self): n = 10 x = np.arange(n) y = x mgcx_dict = MGCX().test(x, y, reps=100, random_state=2)[2] opt_scale = mgcx_dict["opt_scale"] mgcx_dict2 = MGCX().test(x, y, reps=100, random_state=2)[2] opt_scale2 = mgcx_dict2["opt_scale"] assert opt_scale == opt_scale2 def test_rep_nonlinear(self): n = 7 x = np.arange(n) y = x ** 2 mgcx_dict = MGCX().test(x, y, reps=100, random_state=2)[2] opt_scale = mgcx_dict["opt_scale"] mgcx_dict2 = MGCX().test(x, y, reps=100, random_state=2)[2] opt_scale2 = mgcx_dict2["opt_scale"] assert opt_scale == opt_scale2
packstack/installer/core/arch.py
lkpdn/packstack
190
148598
<gh_stars>100-1000 # -*- coding: utf-8 -*- # 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. """ Simple routines to map host architectures as expected by various components. """ import os def kernel_arch(): """Return the kernel arch.""" return os.uname()[4] def dib_arch(): """Return the kernel arch or the more appropriate DiB arch.""" DIB_MAP = { 'x86_64': 'amd64', 'aarch64': 'arm64', } return DIB_MAP.get(kernel_arch(), kernel_arch()) def cirros_arch(): """Return the kernel arch or the more appropriate cirros arch.""" CIRROS_MAP = { 'ppc64le': 'powerpc', 'aarch64': 'arm', } return CIRROS_MAP.get(kernel_arch(), kernel_arch())
examples/bench/cgt_gru.py
rohanraja/cgt_distributed
698
148603
<reponame>rohanraja/cgt_distributed<gh_stars>100-1000 import cgt from gru import GRUCell import time from cgt.utils import Message import numpy as np if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("--horizon",type=int) args = parser.parse_args() horizon = args.horizon assert horizon is not None size=128 batchsize=64 cell = GRUCell([size],size) X = cgt.tensor3() init = cgt.matrix() prev_h = init for i in xrange(horizon): prev_h = cell(X[i], prev_h) loss = prev_h.sum() with Message("compiling"): f = cgt.function([X, init],cgt.grad(loss, cell.params())) with Message("running"): xval = np.zeros((horizon,batchsize,size),cgt.floatX) initval = np.zeros((batchsize, size), cgt.floatX) for i in xrange(100): f(xval, initval) # # No speedup -- why? # with Message("split loss. compiling"): # from cgt import nn # m = cgt.nn.Module([X, init], [loss]) # split_loss = 0 # X1 = cgt.tensor3() # init1 = cgt.matrix() # for start in xrange(0, batchsize, batchsize//4): # sli = slice(start, start+batchsize//4) # split_loss += m([X1[:, sli], init1[sli]])[0] # f = cgt.function([X1, init1],cgt.grad(split_loss, cell.params())) # with Message("running"): # for i in xrange(100): # f(xval,initval)
language/question_answering/decatt_docreader/datasets/nq_short_pipeline_dataset.py
naveenjafer/language
1,199
148609
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # 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. """Creates a tf.Dataset for short answer prediction given the gold context. Fields: `question`: <string> [question_len]; tokens in the question. `context`: <string> [context_len]; tokens in the gold context. `answer_start`: <int32> []; the gold answer start w.r.t the gold context. `answer_end`: <int32> []; the gold answer end w.r.t the gold context. TODO(kentonl): Add the expected results from our baseline on this dataset. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import flags import tensorflow.compat.v1 as tf flags.DEFINE_string("nq_short_pipeline_train_pattern", None, "Path to NQ short answer training data.") flags.DEFINE_string("nq_short_pipeline_eval_pattern", None, "Path to NQ short answer eval data.") FLAGS = flags.FLAGS def split_on_whitespace(str_tensor): return tf.string_split(tf.expand_dims(str_tensor, -1)).values def parse_example(serialized_example): """Parse example.""" features = tf.parse_single_example( serialized_example, features={ "question": tf.FixedLenFeature([], tf.string), "context": tf.FixedLenFeature([], tf.string), "answer_start": tf.FixedLenFeature([], tf.int64), "answer_end": tf.FixedLenFeature([], tf.int64), }) features["question"] = split_on_whitespace(features["question"]) features["context"] = split_on_whitespace(features["context"]) features["answer_start"] = tf.to_int32(features["answer_start"]) features["answer_end"] = tf.to_int32(features["answer_end"]) return features def get_dataset(is_train): """Gets a tf.data.Dataset representing the NQ data.""" if is_train: data_pattern = FLAGS.nq_short_pipeline_train_pattern else: data_pattern = FLAGS.nq_short_pipeline_eval_pattern data_files = tf.gfile.Glob(data_pattern) assert data_files def _load_records(filenames): return tf.data.TFRecordDataset(filenames, buffer_size=16 * 1024 * 1024) if is_train: # During training, read from all files in parallel to improve the speed of # the input pipeline. dataset = tf.data.Dataset.from_tensor_slices(tf.constant(data_files)) dataset = dataset.apply( tf.contrib.data.shuffle_and_repeat(buffer_size=len(data_files))) dataset = dataset.apply( tf.contrib.data.parallel_interleave( _load_records, sloppy=is_train, cycle_length=len(data_files))) dataset = dataset.shuffle(buffer_size=1000) else: dataset = _load_records(data_files) dataset = dataset.map(parse_example, num_parallel_calls=6) return dataset
google/datalab/notebook/__init__.py
freyrsae/pydatalab
198
148621
<reponame>freyrsae/pydatalab<gh_stars>100-1000 # Copyright 2016 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. """Google Cloud Datalab - notebook extension functionality.""" try: import IPython as _ except ImportError: raise Exception('This package requires an IPython notebook installation') __all__ = ['_'] def _jupyter_nbextension_paths(): return [dict(section="notebook", src="static", dest="gcpdatalab")]
vcr/modules/resnet_vlbert_for_vcr.py
xiling42/VL-BERT
671
148625
<gh_stars>100-1000 import os import torch import torch.nn as nn import torch.nn.functional as F from external.pytorch_pretrained_bert import BertTokenizer from common.module import Module from common.fast_rcnn import FastRCNN from common.nlp.time_distributed import TimeDistributed from common.visual_linguistic_bert import VisualLinguisticBert, VisualLinguisticBertMVRCHeadTransform from common.nlp.roberta import RobertaTokenizer BERT_WEIGHTS_NAME = 'pytorch_model.bin' class ResNetVLBERT(Module): def __init__(self, config): super(ResNetVLBERT, self).__init__(config) self.enable_cnn_reg_loss = config.NETWORK.ENABLE_CNN_REG_LOSS self.cnn_loss_top = config.NETWORK.CNN_LOSS_TOP if not config.NETWORK.BLIND: self.image_feature_extractor = FastRCNN(config, average_pool=True, final_dim=config.NETWORK.IMAGE_FINAL_DIM, enable_cnn_reg_loss=(self.enable_cnn_reg_loss and not self.cnn_loss_top)) if config.NETWORK.VLBERT.object_word_embed_mode == 1: self.object_linguistic_embeddings = nn.Embedding(81, config.NETWORK.VLBERT.hidden_size) elif config.NETWORK.VLBERT.object_word_embed_mode == 2: self.object_linguistic_embeddings = nn.Embedding(1, config.NETWORK.VLBERT.hidden_size) elif config.NETWORK.VLBERT.object_word_embed_mode == 3: self.object_linguistic_embeddings = None else: raise NotImplementedError if self.enable_cnn_reg_loss and self.cnn_loss_top: self.cnn_loss_reg = nn.Sequential( VisualLinguisticBertMVRCHeadTransform(config.NETWORK.VLBERT), nn.Dropout(config.NETWORK.CNN_REG_DROPOUT, inplace=False), nn.Linear(config.NETWORK.VLBERT.hidden_size, 81) ) self.image_feature_bn_eval = config.NETWORK.IMAGE_FROZEN_BN if 'roberta' in config.NETWORK.BERT_MODEL_NAME: self.tokenizer = RobertaTokenizer.from_pretrained(config.NETWORK.BERT_MODEL_NAME) else: self.tokenizer = BertTokenizer.from_pretrained(config.NETWORK.BERT_MODEL_NAME) language_pretrained_model_path = None if config.NETWORK.BERT_PRETRAINED != '': language_pretrained_model_path = '{}-{:04d}.model'.format(config.NETWORK.BERT_PRETRAINED, config.NETWORK.BERT_PRETRAINED_EPOCH) elif os.path.isdir(config.NETWORK.BERT_MODEL_NAME): weight_path = os.path.join(config.NETWORK.BERT_MODEL_NAME, BERT_WEIGHTS_NAME) if os.path.isfile(weight_path): language_pretrained_model_path = weight_path if language_pretrained_model_path is None: print("Warning: no pretrained language model found, training from scratch!!!") self.vlbert = TimeDistributed( VisualLinguisticBert(config.NETWORK.VLBERT, language_pretrained_model_path=language_pretrained_model_path) ) self.for_pretrain = config.NETWORK.FOR_MASK_VL_MODELING_PRETRAIN assert not self.for_pretrain, "Not implement pretrain mode now!" if not self.for_pretrain: dim = config.NETWORK.VLBERT.hidden_size if config.NETWORK.CLASSIFIER_TYPE == "2fc": self.final_mlp = torch.nn.Sequential( torch.nn.Dropout(config.NETWORK.CLASSIFIER_DROPOUT, inplace=False), torch.nn.Linear(dim, config.NETWORK.CLASSIFIER_HIDDEN_SIZE), torch.nn.ReLU(inplace=True), torch.nn.Dropout(config.NETWORK.CLASSIFIER_DROPOUT, inplace=False), torch.nn.Linear(config.NETWORK.CLASSIFIER_HIDDEN_SIZE, 1), ) elif config.NETWORK.CLASSIFIER_TYPE == "1fc": self.final_mlp = torch.nn.Sequential( torch.nn.Dropout(config.NETWORK.CLASSIFIER_DROPOUT, inplace=False), torch.nn.Linear(dim, 1) ) else: raise ValueError("Not support classifier type: {}!".format(config.NETWORK.CLASSIFIER_TYPE)) # init weights self.init_weight() self.fix_params() def init_weight(self): if not self.config.NETWORK.BLIND: self.image_feature_extractor.init_weight() if self.object_linguistic_embeddings is not None: self.object_linguistic_embeddings.weight.data.normal_(mean=0.0, std=0.02) if self.enable_cnn_reg_loss and self.cnn_loss_top: self.cnn_loss_reg.apply(self.vlbert._module.init_weights) if not self.for_pretrain: for m in self.final_mlp.modules(): if isinstance(m, torch.nn.Linear): torch.nn.init.xavier_uniform_(m.weight) torch.nn.init.constant_(m.bias, 0) def train(self, mode=True): super(ResNetVLBERT, self).train(mode) # turn some frozen layers to eval mode if (not self.config.NETWORK.BLIND) and self.image_feature_bn_eval: self.image_feature_extractor.bn_eval() def fix_params(self): if self.config.NETWORK.BLIND: self.vlbert._module.visual_scale_text.requires_grad = False self.vlbert._module.visual_scale_object.requires_grad = False def _collect_obj_reps(self, span_tags, object_reps): """ Collect span-level object representations :param span_tags: [batch_size, ..leading_dims.., L] :param object_reps: [batch_size, max_num_objs_per_batch, obj_dim] :return: """ span_tags_fixed = torch.clamp(span_tags, min=0) # In case there were masked values here row_id = span_tags_fixed.new_zeros(span_tags_fixed.shape) row_id_broadcaster = torch.arange(0, row_id.shape[0], step=1, device=row_id.device)[:, None] # Add extra diminsions to the row broadcaster so it matches row_id leading_dims = len(span_tags.shape) - 2 for i in range(leading_dims): row_id_broadcaster = row_id_broadcaster[..., None] row_id += row_id_broadcaster return object_reps[row_id.view(-1), span_tags_fixed.view(-1)].view(*span_tags_fixed.shape, -1) def prepare_text_from_qa(self, question, question_tags, question_mask, answers, answers_tags, answers_mask): batch_size, max_q_len = question.shape _, num_choices, max_a_len = answers.shape max_len = (question_mask.sum(1) + answers_mask.sum(2).max(1)[0]).max() + 3 cls_id, sep_id = self.tokenizer.convert_tokens_to_ids(['[CLS]', '[SEP]']) question = question.repeat(1, num_choices).view(-1, num_choices, max_q_len) question_mask = question_mask.repeat(1, num_choices).view(-1, num_choices, max_q_len) q_end = 1 + question_mask.sum(2, keepdim=True) a_end = q_end + 1 + answers_mask.sum(2, keepdim=True) input_ids = torch.zeros((batch_size, num_choices, max_len), dtype=question.dtype, device=question.device) input_mask = torch.ones((batch_size, num_choices, max_len), dtype=torch.uint8, device=question.device) input_type_ids = torch.zeros((batch_size, num_choices, max_len), dtype=question.dtype, device=question.device) text_tags = input_type_ids.new_zeros((batch_size, num_choices, max_len)) grid_i, grid_j, grid_k = torch.meshgrid(torch.arange(batch_size, device=question.device), torch.arange(num_choices, device=question.device), torch.arange(max_len, device=question.device)) input_mask[grid_k > a_end] = 0 input_type_ids[(grid_k > q_end) & (grid_k <= a_end)] = 1 q_input_mask = (grid_k > 0) & (grid_k < q_end) a_input_mask = (grid_k > q_end) & (grid_k < a_end) input_ids[:, :, 0] = cls_id input_ids[grid_k == q_end] = sep_id input_ids[grid_k == a_end] = sep_id input_ids[q_input_mask] = question[question_mask] input_ids[a_input_mask] = answers[answers_mask] text_tags[q_input_mask] = question_tags[question_mask] text_tags[a_input_mask] = answers_tags[answers_mask] return input_ids, input_type_ids, text_tags, input_mask def prepare_text_from_qa_onesent(self, question, question_tags, question_mask, answers, answers_tags, answers_mask): batch_size, max_q_len = question.shape _, num_choices, max_a_len = answers.shape max_len = (question_mask.sum(1) + answers_mask.sum(2).max(1)[0]).max() + 2 cls_id, sep_id = self.tokenizer.convert_tokens_to_ids(['[CLS]', '[SEP]']) question = question.repeat(1, num_choices).view(-1, num_choices, max_q_len) question_mask = question_mask.repeat(1, num_choices).view(-1, num_choices, max_q_len) q_end = 1 + question_mask.sum(2, keepdim=True) a_end = q_end + answers_mask.sum(2, keepdim=True) input_ids = torch.zeros((batch_size, num_choices, max_len), dtype=question.dtype, device=question.device) input_mask = torch.ones((batch_size, num_choices, max_len), dtype=torch.uint8, device=question.device) input_type_ids = torch.zeros((batch_size, num_choices, max_len), dtype=question.dtype, device=question.device) text_tags = input_type_ids.new_zeros((batch_size, num_choices, max_len)) grid_i, grid_j, grid_k = torch.meshgrid(torch.arange(batch_size, device=question.device), torch.arange(num_choices, device=question.device), torch.arange(max_len, device=question.device)) input_mask[grid_k > a_end] = 0 q_input_mask = (grid_k > 0) & (grid_k < q_end) a_input_mask = (grid_k >= q_end) & (grid_k < a_end) input_ids[:, :, 0] = cls_id input_ids[grid_k == a_end] = sep_id input_ids[q_input_mask] = question[question_mask] input_ids[a_input_mask] = answers[answers_mask] text_tags[q_input_mask] = question_tags[question_mask] text_tags[a_input_mask] = answers_tags[answers_mask] return input_ids, input_type_ids, text_tags, input_mask def prepare_text_from_aq(self, question, question_tags, question_mask, answers, answers_tags, answers_mask): batch_size, max_q_len = question.shape _, num_choices, max_a_len = answers.shape max_len = (question_mask.sum(1) + answers_mask.sum(2).max(1)[0]).max() + 3 cls_id, sep_id = self.tokenizer.convert_tokens_to_ids(['[CLS]', '[SEP]']) question = question.repeat(1, num_choices).view(-1, num_choices, max_q_len) question_mask = question_mask.repeat(1, num_choices).view(-1, num_choices, max_q_len) a_end = 1 + answers_mask.sum(2, keepdim=True) q_end = a_end + 1 + question_mask.sum(2, keepdim=True) input_ids = torch.zeros((batch_size, num_choices, max_len), dtype=question.dtype, device=question.device) input_mask = torch.ones((batch_size, num_choices, max_len), dtype=torch.uint8, device=question.device) input_type_ids = torch.zeros((batch_size, num_choices, max_len), dtype=question.dtype, device=question.device) text_tags = input_type_ids.new_zeros((batch_size, num_choices, max_len)) grid_i, grid_j, grid_k = torch.meshgrid(torch.arange(batch_size, device=question.device), torch.arange(num_choices, device=question.device), torch.arange(max_len, device=question.device)) input_mask[grid_k > q_end] = 0 input_type_ids[(grid_k > a_end) & (grid_k <= q_end)] = 1 q_input_mask = (grid_k > a_end) & (grid_k < q_end) a_input_mask = (grid_k > 0) & (grid_k < a_end) input_ids[:, :, 0] = cls_id input_ids[grid_k == a_end] = sep_id input_ids[grid_k == q_end] = sep_id input_ids[q_input_mask] = question[question_mask] input_ids[a_input_mask] = answers[answers_mask] text_tags[q_input_mask] = question_tags[question_mask] text_tags[a_input_mask] = answers_tags[answers_mask] return input_ids, input_type_ids, text_tags, input_mask def train_forward(self, image, boxes, masks, question, question_align_matrix, answer_choices, answer_align_matrix, answer_label, im_info, mask_position=None, mask_type=None, mask_label=None): ########################################### # visual feature extraction images = image objects = boxes[:, :, -1] segms = masks boxes = boxes[:, :, :4] box_mask = (boxes[:, :, -1] > - 0.5) max_len = int(box_mask.sum(1).max().item()) objects = objects[:, :max_len] box_mask = box_mask[:, :max_len] boxes = boxes[:, :max_len] segms = segms[:, :max_len] if self.config.NETWORK.BLIND: obj_reps = {'obj_reps': boxes.new_zeros((*boxes.shape[:-1], self.config.NETWORK.IMAGE_FINAL_DIM))} else: obj_reps = self.image_feature_extractor(images=images, boxes=boxes, box_mask=box_mask, im_info=im_info, classes=objects, segms=segms) num_choices = answer_choices.shape[1] question_ids = question[:, :, 0] question_tags = question[:, :, 1] question_tags = question_tags.repeat(1, num_choices).view(question_tags.shape[0], num_choices, -1) question_mask = (question[:, :, 0] > 0.5) answer_ids = answer_choices[:, :, :,0] answer_tags = answer_choices[:, :, :, 1] answer_mask = (answer_choices[:, :, :, 0] > 0.5) ############################################ # prepare text if self.config.NETWORK.ANSWER_FIRST: if self.config.NETWORK.QA_ONE_SENT: raise NotImplemented else: text_input_ids, text_token_type_ids, text_tags, text_mask = self.prepare_text_from_aq( question_ids, question_tags, question_mask, answer_ids, answer_tags, answer_mask) else: if self.config.NETWORK.QA_ONE_SENT: text_input_ids, text_token_type_ids, text_tags, text_mask = self.prepare_text_from_qa_onesent( question_ids, question_tags, question_mask, answer_ids, answer_tags, answer_mask) else: text_input_ids, text_token_type_ids, text_tags, text_mask = self.prepare_text_from_qa( question_ids, question_tags, question_mask, answer_ids, answer_tags, answer_mask) if self.config.NETWORK.NO_GROUNDING: text_tags.zero_() text_visual_embeddings = self._collect_obj_reps(text_tags, obj_reps['obj_reps']) if self.config.NETWORK.BLIND: object_linguistic_embeddings = boxes.new_zeros((*boxes.shape[:-1], self.config.NETWORK.VLBERT.hidden_size)) object_linguistic_embeddings = object_linguistic_embeddings.unsqueeze(1).repeat(1, num_choices, 1, 1) else: if self.config.NETWORK.VLBERT.object_word_embed_mode in [1, 2]: object_linguistic_embeddings = self.object_linguistic_embeddings( objects.long().clamp(min=0, max=self.object_linguistic_embeddings.weight.data.shape[0] - 1) ) object_linguistic_embeddings = object_linguistic_embeddings.unsqueeze(1).repeat(1, num_choices, 1, 1) elif self.config.NETWORK.VLBERT.object_word_embed_mode == 3: cls_id, sep_id = self.tokenizer.convert_tokens_to_ids(['[CLS]', '[SEP]']) global_context_mask = text_mask & (text_input_ids != cls_id) & (text_input_ids != sep_id) word_embedding = self.vlbert._module.word_embeddings(text_input_ids) word_embedding[global_context_mask == 0] = 0 object_linguistic_embeddings = word_embedding.sum(dim=2) / global_context_mask.sum(dim=2, keepdim=True).to(dtype=word_embedding.dtype) object_linguistic_embeddings = object_linguistic_embeddings.unsqueeze(2).repeat((1, 1, max_len, 1)) object_vl_embeddings = torch.cat((obj_reps['obj_reps'].unsqueeze(1).repeat(1, num_choices, 1, 1), object_linguistic_embeddings), -1) ########################################### # Visual Linguistic BERT if self.config.NETWORK.NO_OBJ_ATTENTION or self.config.NETWORK.BLIND: box_mask.zero_() hidden_states_text, hidden_states_objects, pooled_rep = self.vlbert(text_input_ids, text_token_type_ids, text_visual_embeddings, text_mask, object_vl_embeddings, box_mask.unsqueeze(1).repeat(1, num_choices, 1), output_all_encoded_layers=False, output_text_and_object_separately=True) ########################################### outputs = {} # classifier logits = self.final_mlp(pooled_rep).squeeze(2) # loss if self.config.NETWORK.CLASSIFIER_SIGMOID: _, choice_ind = torch.meshgrid(torch.arange(logits.shape[0], device=logits.device), torch.arange(num_choices, device=logits.device)) label_binary = (choice_ind == answer_label.unsqueeze(1)) if mask_type is not None and self.config.NETWORK.REPLACE_OBJECT_CHANGE_LABEL: label_binary = label_binary * (mask_type != 1).unsqueeze(1) weight = logits.new_zeros(logits.shape).fill_(1.0) weight[label_binary == 1] = self.config.NETWORK.CLASSIFIER_SIGMOID_LOSS_POSITIVE_WEIGHT rescale = (self.config.NETWORK.CLASSIFIER_SIGMOID_LOSS_POSITIVE_WEIGHT + 1.0) \ / (2.0 * self.config.NETWORK.CLASSIFIER_SIGMOID_LOSS_POSITIVE_WEIGHT) ans_loss = rescale * F.binary_cross_entropy_with_logits(logits, label_binary.to(dtype=logits.dtype), weight=weight) outputs['positive_fraction'] = label_binary.to(dtype=logits.dtype).sum() / label_binary.numel() else: ans_loss = F.cross_entropy(logits, answer_label.long().view(-1)) outputs.update({'label_logits': logits, 'label': answer_label.long().view(-1), 'ans_loss': ans_loss}) loss = ans_loss.mean() * self.config.NETWORK.ANS_LOSS_WEIGHT if mask_position is not None: assert False, "Todo: align to original position." _batch_ind = torch.arange(images.shape[0], dtype=torch.long, device=images.device) mask_pos_rep = hidden_states[_batch_ind, answer_label, mask_position] mask_pred_logits = (obj_reps['obj_reps'] @ mask_pos_rep.unsqueeze(-1)).squeeze(-1) mask_pred_logits[1 - box_mask] -= 10000.0 mask_object_loss = F.cross_entropy(mask_pred_logits, mask_label, ignore_index=-1) logits_padded = mask_pred_logits.new_zeros((mask_pred_logits.shape[0], origin_len)).fill_(-10000.0) logits_padded[:, :mask_pred_logits.shape[1]] = mask_pred_logits mask_pred_logits = logits_padded outputs.update({ 'mask_object_loss': mask_object_loss, 'mask_object_logits': mask_pred_logits, 'mask_object_label': mask_label}) loss = loss + mask_object_loss.mean() * self.config.NETWORK.MASK_OBJECT_LOSS_WEIGHT if self.enable_cnn_reg_loss: if not self.cnn_loss_top: loss = loss + obj_reps['cnn_regularization_loss'].mean() * self.config.NETWORK.CNN_LOSS_WEIGHT outputs['cnn_regularization_loss'] = obj_reps['cnn_regularization_loss'] else: objects = objects.unsqueeze(1).repeat(1, num_choices, 1) box_mask = box_mask.unsqueeze(1).repeat(1, num_choices, 1) cnn_reg_logits = self.cnn_loss_reg(hidden_states_objects[box_mask]) cnn_reg_loss = F.cross_entropy(cnn_reg_logits, objects[box_mask].long()) loss = loss + cnn_reg_loss.mean() * self.config.NETWORK.CNN_LOSS_WEIGHT outputs['cnn_regularization_loss'] = cnn_reg_loss return outputs, loss def inference_forward(self, image, boxes, masks, question, question_align_matrix, answer_choices, answer_align_matrix, *args): if self.for_pretrain: answer_label, im_info, mask_position, mask_type = args else: assert len(args) == 1 im_info = args[0] ########################################### # visual feature extraction images = image objects = boxes[:, :, -1] segms = masks boxes = boxes[:, :, :4] box_mask = (boxes[:, :, -1] > - 0.5) max_len = int(box_mask.sum(1).max().item()) objects = objects[:, :max_len] box_mask = box_mask[:, :max_len] boxes = boxes[:, :max_len] segms = segms[:, :max_len] if self.config.NETWORK.BLIND: obj_reps = {'obj_reps': boxes.new_zeros((*boxes.shape[:-1], self.config.NETWORK.IMAGE_FINAL_DIM))} else: obj_reps = self.image_feature_extractor(images=images, boxes=boxes, box_mask=box_mask, im_info=im_info, classes=objects, segms=segms) num_choices = answer_choices.shape[1] question_ids = question[:, :, 0] question_tags = question[:, :, 1] question_tags = question_tags.repeat(1, num_choices).view(question_tags.shape[0], num_choices, -1) question_mask = (question[:, :, 0] > 0.5) answer_ids = answer_choices[:, :, :, 0] answer_tags = answer_choices[:, :, :, 1] answer_mask = (answer_choices[:, :, :, 0] > 0.5) ############################################ # prepare text if self.config.NETWORK.ANSWER_FIRST: if self.config.NETWORK.QA_ONE_SENT: raise NotImplemented else: text_input_ids, text_token_type_ids, text_tags, text_mask = self.prepare_text_from_aq( question_ids, question_tags, question_mask, answer_ids, answer_tags, answer_mask) else: if self.config.NETWORK.QA_ONE_SENT: text_input_ids, text_token_type_ids, text_tags, text_mask = self.prepare_text_from_qa_onesent( question_ids, question_tags, question_mask, answer_ids, answer_tags, answer_mask) else: text_input_ids, text_token_type_ids, text_tags, text_mask = self.prepare_text_from_qa( question_ids, question_tags, question_mask, answer_ids, answer_tags, answer_mask) if self.config.NETWORK.NO_GROUNDING: text_tags.zero_() text_visual_embeddings = self._collect_obj_reps(text_tags, obj_reps['obj_reps']) if self.config.NETWORK.BLIND: object_linguistic_embeddings = boxes.new_zeros( (*boxes.shape[:-1], self.config.NETWORK.VLBERT.hidden_size)) object_linguistic_embeddings = object_linguistic_embeddings.unsqueeze(1).repeat(1, num_choices, 1, 1) else: if self.config.NETWORK.VLBERT.object_word_embed_mode in [1, 2]: object_linguistic_embeddings = self.object_linguistic_embeddings( objects.long().clamp(min=0, max=self.object_linguistic_embeddings.weight.data.shape[0] - 1) ) object_linguistic_embeddings = object_linguistic_embeddings.unsqueeze(1).repeat(1, num_choices, 1, 1) elif self.config.NETWORK.VLBERT.object_word_embed_mode == 3: cls_id, sep_id = self.tokenizer.convert_tokens_to_ids(['[CLS]', '[SEP]']) global_context_mask = text_mask & (text_input_ids != cls_id) & (text_input_ids != sep_id) word_embedding = self.vlbert._module.word_embeddings(text_input_ids) word_embedding[global_context_mask == 0] = 0 object_linguistic_embeddings = word_embedding.sum(dim=2) / global_context_mask.sum(dim=2, keepdim=True).to( dtype=word_embedding.dtype) object_linguistic_embeddings = object_linguistic_embeddings.unsqueeze(2).repeat((1, 1, max_len, 1)) object_vl_embeddings = torch.cat((obj_reps['obj_reps'].unsqueeze(1).repeat(1, num_choices, 1, 1), object_linguistic_embeddings), -1) ########################################### # Visual Linguistic BERT if self.config.NETWORK.NO_OBJ_ATTENTION or self.config.NETWORK.BLIND: box_mask.zero_() hidden_states_text, hidden_states_objects, pooled_rep = self.vlbert(text_input_ids, text_token_type_ids, text_visual_embeddings, text_mask, object_vl_embeddings, box_mask.unsqueeze(1).repeat(1, num_choices, 1), output_all_encoded_layers=False, output_text_and_object_separately=True) ########################################### # classifier logits = self.final_mlp(pooled_rep).squeeze(2) outputs = {'label_logits': logits} return outputs
src/research/PTDF/ACPTDF_research2.py
mzy2240/GridCal
284
148665
# This file is part of GridCal. # # GridCal is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # GridCal is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GridCal. If not, see <http://www.gnu.org/licenses/>. import numpy as np import pandas as pd import numba as nb import time from warnings import warn import scipy.sparse as sp from scipy.sparse import coo_matrix, csc_matrix from scipy.sparse import hstack as hs, vstack as vs from scipy.sparse.linalg import factorized, spsolve, inv from matplotlib import pyplot as plt from GridCal.Engine import * def SysMat(Y, Ys, pq, pvpq): """ Computes the system Jacobian matrix in polar coordinates Args: Ybus: Admittance matrix V: Array of nodal voltages Ibus: Array of nodal current injections pq: Array with the indices of the PQ buses pvpq: Array with the indices of the PV and PQ buses Returns: The system Jacobian matrix """ A11 = -Ys.imag[np.ix_(pvpq, pvpq)] A12 = Y.real[np.ix_(pvpq, pq)] A21 = -Ys.real[np.ix_(pq, pvpq)] A22 = -Y.imag[np.ix_(pq, pq)] Asys = sp.vstack([sp.hstack([A11, A12]), sp.hstack([A21, A22])], format="csc") return Asys def compute_acptdf(Ybus, Yseries, Yf, Yt, Cf, V, pq, pv, distribute_slack): """ Compute the AC-PTDF :param Ybus: admittance matrix :param Yf: Admittance matrix of the buses "from" :param Yt: Admittance matrix of the buses "to" :param Cf: Connectivity branch - bus "from" :param V: voltages array :param Ibus: array of currents :param pq: array of pq node indices :param pv: array of pv node indices :return: AC-PTDF matrix (branches, buses) """ n = len(V) pvpq = np.r_[pv, pq] npq = len(pq) # compute the Jacobian J = SysMat(Ybus, Yseries, pq, pvpq) if distribute_slack: dP = np.ones((n, n)) * (-1 / (n - 1)) for i in range(n): dP[i, i] = 1.0 else: dP = np.eye(n, n) # compose the compatible array (the Q increments are considered zero dQ = np.zeros((npq, n)) # dQ = np.eye(n, n)[pq, :] dS = np.r_[dP[pvpq, :], dQ] # solve the voltage increments dx = spsolve(J, dS) # compute branch derivatives If = Yf * V E = V / np.abs(V) Vdiag = sp.diags(V) Vdiag_conj = sp.diags(np.conj(V)) Ediag = sp.diags(E) Ediag_conj = sp.diags(np.conj(E)) If_diag_conj = sp.diags(np.conj(If)) Yf_conj = Yf.copy() Yf_conj.data = np.conj(Yf_conj.data) Yt_conj = Yt.copy() Yt_conj.data = np.conj(Yt_conj.data) dSf_dVa = 1j * (If_diag_conj * Cf * Vdiag - sp.diags(Cf * V) * Yf_conj * Vdiag_conj) dSf_dVm = If_diag_conj * Cf * Ediag - sp.diags(Cf * V) * Yf_conj * Ediag_conj # compose the final AC-PTDF dPf_dVa = dSf_dVa.real[:, pvpq] dPf_dVm = dSf_dVm.real[:, pq] PTDF = sp.hstack((dPf_dVa, dPf_dVm)) * dx return PTDF def make_lodf(circuit: SnapshotCircuit, PTDF, correct_values=True): """ :param circuit: :param PTDF: PTDF matrix in numpy array form :return: """ nl = circuit.nbr # compute the connectivity matrix Cft = circuit.C_branch_bus_f - circuit.C_branch_bus_t H = PTDF * Cft.T # old code # h = sp.diags(H.diagonal()) # LODF = H / (np.ones((nl, nl)) - h * np.ones(nl)) # divide each row of H by the vector 1 - H.diagonal # LODF = H / (1 - H.diagonal()) # replace possible nan and inf # LODF[LODF == -np.inf] = 0 # LODF[LODF == np.inf] = 0 # LODF = np.nan_to_num(LODF) # this loop avoids the divisions by zero # in those cases the LODF column should be zero LODF = np.zeros((nl, nl)) div = 1 - H.diagonal() for j in range(H.shape[1]): if div[j] != 0: LODF[:, j] = H[:, j] / div[j] # replace the diagonal elements by -1 # old code # LODF = LODF - sp.diags(LODF.diagonal()) - sp.eye(nl, nl), replaced by: for i in range(nl): LODF[i, i] = - 1.0 if correct_values: i1, j1 = np.where(LODF > 1) for i, j in zip(i1, j1): LODF[i, j] = 1 i2, j2 = np.where(LODF < -1) for i, j in zip(i2, j2): LODF[i, j] = -1 return LODF def get_branch_time_series(circuit: TimeCircuit, PTDF): """ :param grid: :return: """ # option 2: call the power directly P = circuit.Sbus.real Pbr = np.dot(PTDF, P).T * circuit.Sbase return Pbr def multiple_failure_old(flows, LODF, beta, delta, alpha): """ :param flows: array of all the pre-contingency flows :param LODF: Line Outage Distribution Factors Matrix :param beta: index of the first failed line :param delta: index of the second failed line :param alpha: index of the line where you want to see the effects :return: post contingency flow in the line alpha """ # multiple contingency matrix M = np.ones((2, 2)) M[0, 1] = -LODF[beta, delta] M[1, 0] = -LODF[delta, beta] # normal flows of the lines beta and delta F = flows[[beta, delta]] # contingency flows after failing the ines beta and delta Ff = np.linalg.solve(M, F) # flow delta in the line alpha after the multiple contingency of the lines beta and delta L = LODF[alpha, :][[beta, delta]] dFf_alpha = np.dot(L, Ff) return F[alpha] + dFf_alpha def multiple_failure(flows, LODF, failed_idx): """ From the paper: Multiple Element Contingency Screening IEEE TRANSACTIONS ON POWER SYSTEMS, VOL. 26, NO. 3, AUGUST 2011 <NAME> and <NAME> :param flows: array of all the pre-contingency flows (the base flows) :param LODF: Line Outage Distribution Factors Matrix :param failed_idx: indices of the failed lines :return: all post contingency flows """ # multiple contingency matrix M = -LODF[np.ix_(failed_idx, failed_idx)] for i in range(len(failed_idx)): M[i, i] = 1.0 # normal flows of the failed lines indicated by failed_idx F = flows[failed_idx] # Affected flows after failing the lines indicated by failed_idx Ff = np.linalg.solve(M, F) # flow delta in the line alpha after the multiple contingency of the lines indicated by failed_idx L = LODF[:, failed_idx] dFf_alpha = np.dot(L, Ff) # return the final contingency flow as the base flow plus the contingency flow delta return flows + dFf_alpha def get_n_minus_1_flows(circuit: MultiCircuit): opt = PowerFlowOptions() branches = circuit.get_branches() m = circuit.get_branch_number() Pmat = np.zeros((m, m)) # monitored, contingency for c, branch in enumerate(branches): if branch.active: branch.active = False pf = PowerFlowDriver(circuit, opt) pf.run() Pmat[:, c] = pf.results.Sbranch.real branch.active = True return Pmat def check_lodf(grid: MultiCircuit): flows_n1_nr = get_n_minus_1_flows(grid) # assume 1 island nc = compile_snapshot_circuit(grid) islands = split_into_islands(nc) circuit = islands[0] pf_driver = PowerFlowDriver(grid, PowerFlowOptions()) pf_driver.run() PTDF = compute_acptdf(Ybus=circuit.Ybus, Yseries=circuit.Yseries, Yf=circuit.Yf, Yt=circuit.Yt, Cf=circuit.C_branch_bus_f, V=pf_driver.results.voltage, pq=circuit.pq, pv=circuit.pv, distribute_slack=True) LODF = make_lodf(circuit, PTDF) Pbus = circuit.get_injections(False).real flows_n = np.dot(PTDF, Pbus) nl = circuit.nbr flows_n1 = np.zeros((nl, nl)) for c in range(nl): # branch that fails (contingency) # for m in range(nl): # branch to monitor # flows_n1[m, c] = flows_n[m] + LODF[m, c] * flows_n[c] flows_n1[:, c] = flows_n[:] + LODF[:, c] * flows_n[c] return flows_n, flows_n1_nr, flows_n1 def test_ptdf(grid): """ Sigma-distances test :param grid: :return: """ nc = compile_snapshot_circuit(grid) islands = split_into_islands(nc) circuit = islands[0] # pick the first island pf_driver = PowerFlowDriver(grid, PowerFlowOptions()) pf_driver.run() PTDF = compute_acptdf(Ybus=circuit.Ybus, Yseries=circuit.Yseries, Yf=circuit.Yf, Yt=circuit.Yt, Cf=circuit.C_branch_bus_f, V=pf_driver.results.voltage, pq=circuit.pq, pv=circuit.pv, distribute_slack=False) print('PTDF:') print(PTDF) if __name__ == '__main__': from GridCal.Engine import FileOpen import pandas as pd np.set_printoptions(threshold=sys.maxsize, linewidth=200000000) # np.set_printoptions(linewidth=2000, suppress=True) pd.set_option('display.max_rows', 500) pd.set_option('display.max_columns', 500) pd.set_option('display.width', 1000) # fname = '/home/santi/Documentos/GitHub/GridCal/Grids_and_profiles/grids/IEEE39_1W.gridcal' # fname = '/home/santi/Documentos/GitHub/GridCal/Grids_and_profiles/grids/IEEE 14.xlsx' # fname = '/home/santi/Documentos/GitHub/GridCal/Grids_and_profiles/grids/lynn5buspv.xlsx' # fname = '/home/santi/Documentos/GitHub/GridCal/Grids_and_profiles/grids/IEEE 118.xlsx' fname = '/home/santi/Documentos/GitHub/GridCal/Grids_and_profiles/grids/1354 Pegase.xlsx' # fname = 'helm_data1.gridcal' # fname = '/home/santi/Documentos/GitHub/GridCal/Grids_and_profiles/grids/IEEE 14 PQ only.gridcal' # fname = 'IEEE 14 PQ only full.gridcal' # fname = '/home/santi/Descargas/matpower-fubm-master/data/case5.m' # fname = '/home/santi/Descargas/matpower-fubm-master/data/case30.m' # fname = '/home/santi/Documentos/GitHub/GridCal/Grids_and_profiles/grids/PGOC_6bus.gridcal' grid_ = FileOpen(fname).open() test_ptdf(grid_) name = os.path.splitext(fname.split(os.sep)[-1])[0] method = 'ACPTDF (No Jacobian, V=Vpf)' nc_ = compile_snapshot_circuit(grid_) islands_ = split_into_islands(nc_) circuit_ = islands_[0] pf_driver_ = PowerFlowDriver(grid_, PowerFlowOptions()) pf_driver_.run() H_ = compute_acptdf(Ybus=circuit_.Ybus, Yseries=circuit_.Yseries, Yf=circuit_.Yf, Yt=circuit_.Yt, Cf=circuit_.C_branch_bus_f, V=pf_driver_.results.voltage, pq=circuit_.pq, pv=circuit_.pv, distribute_slack=False) LODF_ = make_lodf(circuit_, H_) if H_.shape[0] < 50: print('PTDF:\n', H_) print('LODF:\n', LODF_) flows_n_, flows_n1_nr_, flows_n1_ = check_lodf(grid_) # in the case of the grid PGOC_6bus flows_multiple = multiple_failure(flows=flows_n_, LODF=LODF_, failed_idx=[1, 5]) # failed lines 2 and 6 Pn1_nr_df = pd.DataFrame(data=flows_n1_nr_, index=nc_.branch_names, columns=nc_.branch_names) flows_n1_df = pd.DataFrame(data=flows_n1_, index=nc_.branch_names, columns=nc_.branch_names) # plot N-1 fig = plt.figure(figsize=(12, 8)) title = 'N-1 with ' + method + ' (' + name + ')' fig.suptitle(title) ax1 = fig.add_subplot(221) ax2 = fig.add_subplot(222) ax3 = fig.add_subplot(223) Pn1_nr_df.plot(ax=ax1, legend=False) flows_n1_df.plot(ax=ax2, legend=False) diff = Pn1_nr_df - flows_n1_df diff.plot(ax=ax3, legend=False) ax1.set_title('Newton-Raphson N-1 flows') ax2.set_title('PTDF N-1 flows') ax3.set_title('Difference') fig.savefig(title + '.png') # ------------------------------------------------------------------------------------------------------------------ # Perform real time series # ------------------------------------------------------------------------------------------------------------------ if grid_.time_profile is not None: grid_.ensure_profiles_exist() nc_ts = compile_time_circuit(grid_) islands_ts = split_time_circuit_into_islands(nc_ts) circuit_ts = islands_ts[0] pf_options = PowerFlowOptions() ts_driver = TimeSeries(grid=grid_, options=pf_options) ts_driver.run() Pbr_nr = ts_driver.results.Sbranch.real df_Pbr_nr = pd.DataFrame(data=Pbr_nr, columns=circuit_ts.branch_names, index=circuit_ts.time_array) # Compute the PTDF based flows Pbr_ptdf = get_branch_time_series(circuit=circuit_ts, PTDF=H_) df_Pbr_ptdf = pd.DataFrame(data=Pbr_ptdf, columns=circuit_ts.branch_names, index=circuit_ts.time_array) # plot fig = plt.figure(figsize=(12, 8)) title = 'Flows with ' + method + ' (' + name + ')' fig.suptitle(title) ax1 = fig.add_subplot(221) ax2 = fig.add_subplot(222) ax3 = fig.add_subplot(223) df_Pbr_nr.plot(ax=ax1, legend=False) df_Pbr_ptdf.plot(ax=ax2, legend=False) diff = df_Pbr_nr - df_Pbr_ptdf diff.plot(ax=ax3, legend=False) ax1.set_title('Newton-Raphson flows') ax2.set_title('PTDF flows') ax3.set_title('Difference') fig.savefig(title + '.png') plt.show()
panda/tests/location_listener.py
BoneE562/openpilot
114
148666
<gh_stars>100-1000 #!/usr/bin/env python3 import os import time import sys sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")) from panda import Panda, PandaSerial def add_nmea_checksum(msg): d = msg[1:] cs = 0 for i in d: cs ^= ord(i) return msg + "*%02X" % cs if __name__ == "__main__": panda = Panda() ser = PandaSerial(panda, 1, 9600) # power cycle by toggling reset print("resetting") panda.set_esp_power(0) time.sleep(0.5) panda.set_esp_power(1) time.sleep(0.5) print("done") print(ser.read(1024)) # upping baud rate baudrate = 460800 print("upping baud rate") msg = add_nmea_checksum("$PUBX,41,1,0007,0003,%d,0" % baudrate)+"\r\n" print(msg) ser.write(msg) time.sleep(0.1) # needs a wait for it to actually send # new panda serial ser = PandaSerial(panda, 1, baudrate) while True: ret = ser.read(1024) if len(ret) > 0: sys.stdout.write(ret.decode('ascii', 'ignore')) sys.stdout.flush() #print str(ret).encode("hex")
src/ralph/virtual/tests/test_api.py
elubik/ralph
1,668
148684
<filename>src/ralph/virtual/tests/test_api.py from ddt import data, ddt, unpack from django.core.urlresolvers import reverse from rest_framework import status from ralph.api.tests._base import RalphAPITestCase from ralph.assets.models.assets import ServiceEnvironment from ralph.assets.models.choices import ComponentType from ralph.assets.models.components import ComponentModel from ralph.assets.tests.factories import ( EnvironmentFactory, EthernetFactory, ServiceEnvironmentFactory, ServiceFactory ) from ralph.data_center.tests.factories import ( ClusterFactory, DataCenterAssetFactory ) from ralph.networks.tests.factories import IPAddressFactory from ralph.virtual.models import ( CloudFlavor, CloudHost, CloudProject, CloudProvider, VirtualComponent, VirtualServer, VirtualServerType ) from ralph.virtual.tests.factories import ( CloudFlavorFactory, CloudHostFactory, CloudProjectFactory, CloudProviderFactory, VirtualServerFullFactory ) @ddt class OpenstackModelsTestCase(RalphAPITestCase): def setUp(self): super().setUp() self.envs = EnvironmentFactory.create_batch(2) self.services = ServiceFactory.create_batch(2) self.service_env = [] for i in range(0, 2): self.service_env.append(ServiceEnvironment.objects.create( service=self.services[i], environment=self.envs[i] )) self.service_env[0].service.business_owners = [self.user1] self.service_env[0].service.technical_owners = [self.user2] self.service_env[0].save() self.cloud_provider = CloudProviderFactory(name='openstack') self.cloud_flavor = CloudFlavorFactory() self.cloud_project = CloudProjectFactory( service_env=self.service_env[0] ) self.cloud_host = CloudHostFactory( parent=self.cloud_project, cloudflavor=self.cloud_flavor ) self.cloud_host2 = CloudHostFactory() self.test_cpu = ComponentModel.objects.create( name='vcpu1', cores=5, family='vCPU', type=ComponentType.processor, ) self.test_mem = ComponentModel.objects.create( name='2000 MiB vMEM', size='2000', type=ComponentType.memory, ) self.test_disk = ComponentModel.objects.create( name='4 GiB vDISK', size='4096', type=ComponentType.disk, ) VirtualComponent.objects.create( base_object=self.cloud_flavor, model=self.test_cpu, ) VirtualComponent.objects.create( base_object=self.cloud_flavor, model=self.test_mem, ) VirtualComponent.objects.create( base_object=self.cloud_flavor, model=self.test_disk, ) @data('cloudflavor', 'cloudproject', 'cloudprovider') def test_get_list(self, field): url = reverse(field + '-list') response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) def test_get_cloudhost_list(self): url = reverse('cloudhost-list') with self.assertNumQueries(12): response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['count'], 2) @unpack @data( ('cores', 5), ('memory', 2000), ('disk', 4096), ) def test_get_cloudflavor_detail(self, field, value): url = reverse('cloudflavor-detail', args=(self.cloud_flavor.id,)) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data[field], value) def test_get_cloudhost_detail(self): url = reverse('cloudhost-detail', args=(self.cloud_host.id,)) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['host_id'], self.cloud_host.host_id) self.assertEqual(response.data['hostname'], self.cloud_host.hostname) self.assertEqual(response.data['service_env']['id'], self.cloud_host.service_env.id) self.assertEqual(response.data['parent']['name'], self.cloud_project.name) self.assertEqual(response.data['cloudflavor']['cores'], self.cloud_flavor.cores) self.assertEqual(response.data['cloudflavor']['memory'], self.cloud_flavor.memory) self.assertEqual(response.data['cloudflavor']['disk'], self.cloud_flavor.disk) self.assertEqual(response.data['cloudflavor']['name'], self.cloud_flavor.name) self.assertEqual( response.data['business_owners'][0]['username'], 'user1' ) self.assertEqual( response.data['technical_owners'][0]['username'], 'user2' ) def test_filter_cloudhost_by_service_uid(self): cloud_host = CloudHostFactory() url = ( reverse('cloudhost-list') + '?service_env__service__uid={}'.format(cloud_host.service_env.service.uid) ) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data['count'], 1 ) def test_get_cloudproject_detail(self): url = reverse('cloudproject-detail', args=(self.cloud_project.id,)) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['id'], self.cloud_project.id) self.assertEqual(response.data['name'], self.cloud_project.name) self.assertEqual(response.data['service_env']['id'], self.cloud_project.service_env.id) def test_get_cloudprovider_detail(self): url = reverse('cloudprovider-detail', args=(self.cloud_provider.id,)) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['name'], self.cloud_provider.name) def test_create_cloudhost(self): url = reverse('cloudhost-list') args = { 'cloudprovider': self.cloud_provider.id, 'host_id': 'id_1', 'hostname': 'name_1', 'parent': self.cloud_project.id, 'ip_addresses': ['10.0.0.1', '10.0.0.2'], 'cloudflavor': self.cloud_flavor.id, 'tags': ['prod', 'db'], } response = self.client.post(url, args, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) host = CloudHost.objects.get(host_id=args['host_id']) self.assertEqual(host.cloudprovider, self.cloud_provider) self.assertEqual(host.host_id, args['host_id']) self.assertEqual(host.hostname, args['hostname']) self.assertEqual(host.parent.id, self.cloud_project.id) self.assertEqual(host.cloudflavor, self.cloud_flavor) self.assertEqual(set(host.tags.names()), set(args['tags'])) self.assertEqual(host.service_env, self.service_env[0]) self.assertEqual(set(host.ip_addresses), set(args['ip_addresses'])) def test_create_cloudflavor(self): url = reverse('cloudflavor-list') args = { 'flavor_id': 'id1', 'name': 'name_2', 'cores': 4, 'memory': 1024, 'disk': 10240, 'tags': ['prod', 'db'], 'cloudprovider': self.cloud_provider.id, } response = self.client.post(url, args, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) flavor = CloudFlavor.objects.get(name=args['name']) self.assertEqual(flavor.cloudprovider, self.cloud_provider) self.assertEqual(flavor.flavor_id, args['flavor_id']) self.assertEqual(flavor.name, args['name']) self.assertEqual(flavor.cores, args['cores']) self.assertEqual(flavor.memory, args['memory']) self.assertEqual(flavor.disk, args['disk']) self.assertEqual(set(flavor.tags.names()), set(args['tags'])) def test_create_cloudproject(self): url = reverse('cloudproject-list') args = { 'cloudprovider': self.cloud_provider.id, 'project_id': 'id_1', 'name': 'name_1', 'service_env': self.service_env[0].id, 'tags': ['prod', 'db'], } response = self.client.post(url, args, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) project = CloudProject.objects.get(project_id=args['project_id']) self.assertEqual(project.cloudprovider, self.cloud_provider) self.assertEqual(project.project_id, args['project_id']) self.assertEqual(project.name, args['name']) self.assertEqual(set(project.tags.names()), set(args['tags'])) self.assertEqual(project.service_env, self.service_env[0]) def test_create_cloudprovider(self): url = reverse('cloudprovider-list') args = {'name': 'test1'} response = self.client.post(url, args, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) provider = CloudProvider.objects.get(name=args['name']) self.assertEqual(provider.name, args['name']) def test_patch_cloudhost(self): url = reverse('cloudhost-detail', args=(self.cloud_host.id,)) args = { 'cloudprovider': self.cloud_provider.id, 'host_id': 'id_1', 'hostname': 'name_1', 'parent': self.cloud_project.id, 'ip_addresses': ['10.0.0.1', '10.0.0.2'], 'cloudflavor': self.cloud_flavor.id, 'tags': ['prod', 'db'], } response = self.client.patch(url, args, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) host = CloudHost.objects.get(host_id=args['host_id']) self.assertEqual(host.cloudprovider, self.cloud_provider) self.assertEqual(host.host_id, args['host_id']) self.assertEqual(host.hostname, args['hostname']) self.assertEqual(host.parent.id, self.cloud_project.id) self.assertEqual(host.cloudflavor, self.cloud_flavor) self.assertEqual(set(host.tags.names()), set(args['tags'])) self.assertEqual(set(host.ip_addresses), set(args['ip_addresses'])) def test_patch_cloudflavor(self): url = reverse('cloudflavor-detail', args=(self.cloud_flavor.id,)) args = { 'flavor_id': 'id1', 'name': 'name_2', 'cores': 4, 'memory': 1024, 'disk': 10240, 'tags': ['prod', 'db'], 'cloudprovider': self.cloud_provider.id, } response = self.client.patch(url, args, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) flavor = CloudFlavor.objects.get(name=args['name']) self.assertEqual(flavor.cloudprovider, self.cloud_provider) self.assertEqual(flavor.flavor_id, args['flavor_id']) self.assertEqual(flavor.name, args['name']) self.assertEqual(flavor.cores, args['cores']) self.assertEqual(flavor.memory, args['memory']) self.assertEqual(flavor.disk, args['disk']) self.assertEqual(set(flavor.tags.names()), set(args['tags'])) def test_patch_cloudproject(self): url = reverse('cloudproject-detail', args=(self.cloud_project.id,)) args = { 'cloudprovider': self.cloud_provider.id, 'project_id': 'id_1', 'name': 'name_1', 'service_env': self.service_env[1].id, 'tags': ['prod', 'db'], } response = self.client.patch(url, args, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) project = CloudProject.objects.get(project_id=args['project_id']) self.assertEqual(project.cloudprovider, self.cloud_provider) self.assertEqual(project.project_id, args['project_id']) self.assertEqual(project.name, args['name']) self.assertEqual(set(project.tags.names()), set(args['tags'])) self.assertEqual(project.service_env, self.service_env[1]) def test_patch_cloudprovider(self): url = reverse('cloudprovider-detail', args=(self.cloud_provider.id,)) args = {'name': 'test1'} response = self.client.patch(url, args, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) provider = CloudProvider.objects.get(name=args['name']) self.assertEqual(provider.name, args['name']) def test_delete_cloud_flavor_returns_409_if_is_used_by_cloud_hosts(self): # given cloud_flavor = CloudFlavorFactory() CloudHostFactory(cloudflavor=cloud_flavor) # when url = reverse('cloudflavor-detail', args=(cloud_flavor.pk,)) resp = self.client.delete(url) # then self.assertEqual(resp.status_code, status.HTTP_409_CONFLICT) self.assertIn( 'Cloud flavor is in use and hence is not deletable.', resp.data['detail'] ) self.assertTrue( CloudFlavor.objects.filter(pk=cloud_flavor.pk).exists() ) def test_unused_cloud_flavor_can_be_deleted(self): # given cloud_flavor = CloudFlavorFactory() # when url = reverse('cloudflavor-detail', args=(cloud_flavor.pk,)) resp = self.client.delete(url) # then self.assertEqual(resp.status_code, status.HTTP_204_NO_CONTENT) self.assertRaises( CloudFlavor.DoesNotExist, cloud_flavor.refresh_from_db ) def test_used_cloud_flavor_can_be_deleted_with_force(self): # given cloud_flavor = CloudFlavorFactory() CloudHostFactory(cloudflavor=cloud_flavor) # when url = reverse('cloudflavor-detail', args=(cloud_flavor.pk,)) data = {'force': True} resp = self.client.delete(url, data=data) # then self.assertEqual(resp.status_code, status.HTTP_204_NO_CONTENT) self.assertRaises( CloudFlavor.DoesNotExist, cloud_flavor.refresh_from_db ) @data(CloudFlavorFactory, CloudHostFactory, CloudProjectFactory) def test_delete_cloud_provider_returns_409_if_has_child_objects( self, child_type ): # given cloud_provider = CloudProviderFactory(name="test-cloud-provider") child_type(cloudprovider=cloud_provider) # when url = reverse('cloudprovider-detail', args=(cloud_provider.pk,)) resp = self.client.delete(url) # then self.assertEqual(resp.status_code, status.HTTP_409_CONFLICT) self.assertIn( 'Cloud provider is in use and hence is not deletable.', resp.data['detail'] ) self.assertTrue( CloudProvider.objects.filter(pk=cloud_provider.pk).exists() ) def test_empty_cloud_provider_can_be_deleted(self): # given cloud_provider = CloudProviderFactory(name="test-cloud-provider") # when url = reverse('cloudprovider-detail', args=(cloud_provider.pk,)) resp = self.client.delete(url) # then self.assertEqual(resp.status_code, status.HTTP_204_NO_CONTENT) self.assertRaises( CloudProvider.DoesNotExist, cloud_provider.refresh_from_db ) @data(CloudFlavorFactory, CloudHostFactory, CloudProjectFactory) def test_non_empty_cloud_provider_can_be_deleted_with_force( self, child_type ): # given cloud_provider = CloudProviderFactory(name="test-cloud-provider") child_type(cloudprovider=cloud_provider) # when url = reverse('cloudprovider-detail', args=(cloud_provider.pk,)) data = {'force': True} resp = self.client.delete(url, data=data) # then self.assertEqual(resp.status_code, status.HTTP_204_NO_CONTENT) self.assertRaises( CloudProvider.DoesNotExist, cloud_provider.refresh_from_db ) def test_inheritance_of_service_env_on_change_in_a_cloud_project(self): url = reverse('cloudproject-detail', args=(self.cloud_project.id,)) args = { 'service_env': self.service_env[1].id, } response = self.client.patch(url, args, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) host = CloudHost.objects.get(host_id=self.cloud_host.host_id) self.assertEqual(host.service_env, self.service_env[1]) class VirtualServerAPITestCase(RalphAPITestCase): def setUp(self): super().setUp() self.hypervisor = DataCenterAssetFactory() self.cloud_hypervisor = CloudHostFactory() self.cluster = ClusterFactory() self.type = VirtualServerType.objects.create(name='XEN') self.virtual_server = VirtualServerFullFactory( service_env__environment__name='some_env', ) self.virtual_server.parent.service_env.service.uid = 's-12345' self.virtual_server.parent.service_env.service.save() self.virtual_server.service_env.service.business_owners = [self.user1] self.virtual_server.service_env.service.technical_owners = [self.user2] self.virtual_server.service_env.save() self.virtual_server2 = VirtualServerFullFactory() self.ip = IPAddressFactory( ethernet=EthernetFactory(base_object=self.virtual_server2) ) def test_get_virtual_server_list(self): url = reverse('virtualserver-list') with self.assertNumQueries(13): response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['count'], 2) def test_get_virtual_server_details(self): url = reverse('virtualserver-detail', args=(self.virtual_server.id,)) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data['hostname'], self.virtual_server.hostname ) self.assertEqual(len(response.data['ethernet']), 2) self.assertCountEqual( [ eth['ipaddress']['address'] for eth in response.data['ethernet'] if eth['ipaddress'] ], self.virtual_server.ipaddresses.values_list('address', flat=True) ) self.assertEqual(len(response.data['memory']), 2) self.assertEqual(response.data['memory'][0]['speed'], 1600) self.assertEqual(response.data['memory'][0]['size'], 8192) self.assertEqual( response.data['business_owners'][0]['username'], 'user1' ) self.assertEqual( response.data['technical_owners'][0]['username'], 'user2' ) def test_create_virtual_server(self): virtual_server_count = VirtualServer.objects.count() url = reverse('virtualserver-list') data = { 'hostname': 's1234.local', 'type': self.type.id, 'sn': '143ed36a-3e86-457d-9e19-3dcfe4d5ed26', 'hypervisor': self.hypervisor.id, } response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual( VirtualServer.objects.count(), virtual_server_count + 1 ) virtual_server = VirtualServer.objects.get(pk=response.data['id']) self.assertEqual(virtual_server.hostname, data['hostname']) self.assertEqual(virtual_server.parent.id, self.hypervisor.id) self.assertEqual(virtual_server.sn, data['sn']) def test_create_virtual_server_with_cloud_host_as_parent(self): virtual_server_count = VirtualServer.objects.count() url = reverse('virtualserver-list') data = { 'hostname': 's1234.local', 'type': self.type.id, 'sn': '143ed36a-3e86-457d-9e19-3dcfe4d5ed26', 'hypervisor': self.cloud_hypervisor.id, } response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual( VirtualServer.objects.count(), virtual_server_count + 1 ) virtual_server = VirtualServer.objects.get(pk=response.data['id']) self.assertEqual(virtual_server.hostname, data['hostname']) self.assertEqual(virtual_server.parent.id, self.cloud_hypervisor.id) self.assertEqual(virtual_server.sn, data['sn']) def test_patch_virtual_server(self): url = reverse('virtualserver-detail', args=(self.virtual_server.id,)) data = { 'hostname': 's111111.local' } response = self.client.patch(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.virtual_server.refresh_from_db() self.assertEqual(self.virtual_server.hostname, 's111111.local') def test_filter_by_configuration_path(self): url = reverse('virtualserver-list') + '?configuration_path={}'.format( self.virtual_server.configuration_path.path, ) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data['count'], 1 ) def test_filter_by_hostname(self): url = reverse('virtualserver-list') + '?hostname={}'.format( self.virtual_server.hostname, ) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data['count'], 1 ) def test_filter_by_ip_address(self): url = reverse('virtualserver-list') + '?ip={}'.format( self.ip.address, ) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data['count'], 1 ) def test_filter_by_service_uid(self): url = reverse('virtualserver-list') + '?service={}'.format( self.virtual_server.service_env.service.uid, ) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data['count'], 1 ) def test_filter_by_service_uid2(self): url = ( reverse('virtualserver-list') + '?service_env__service__uid={}'.format( self.virtual_server.service_env.service.uid, ) ) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data['count'], 1 ) def test_filter_by_service_id(self): url = ( reverse('virtualserver-list') + '?service_env__service__id={}'.format( self.virtual_server.service_env.service.id, ) ) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data['count'], 1 ) def test_filter_by_service_name(self): url = reverse('virtualserver-list') + '?service={}'.format( self.virtual_server.service_env.service.name, ) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data['count'], 1 ) def test_filter_by_service_name2(self): url = ( reverse('virtualserver-list') + '?service_env__service__name={}'.format( self.virtual_server.service_env.service.name, ) ) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data['count'], 1 ) def test_filter_by_env_name(self): url = reverse('virtualserver-list') + '?env=some_env' response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data['count'], 1 ) def test_filter_by_hypervisor_service(self): url = reverse('virtualserver-list') + '?hypervisor_service=s-12345' response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data['count'], 1 ) self.assertEqual( response.data['results'][0]['id'], self.virtual_server.id )
web/server/codechecker_server/permissions.py
ryankurte/codechecker
1,601
148689
<reponame>ryankurte/codechecker # ------------------------------------------------------------------------- # # Part of the CodeChecker project, under the Apache License v2.0 with # LLVM Exceptions. See LICENSE for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # # ------------------------------------------------------------------------- """ This module defines the list of permissions of a CodeChecker server, and provides the handling of permission matching and databases. """ from abc import ABCMeta from abc import abstractmethod from sqlalchemy import and_, func from codechecker_api_shared.ttypes import Permission as PermissionEnum from codechecker_common.logger import get_logger LOG = get_logger('server') config_db_model = None # Module will be loaded later... class Permission(metaclass=ABCMeta): """ The base class for a permission declaration. """ def __init__(self, name, default_enable=True, inherited_from=None, managed_by=None, manages_self=False): """ Creates the definition of a new permission. :param name: The name of the permission :param default_enable: If False, only the people explicitly given this permission are marked as having it. If True, an empty list of people given the permission means that everyone has the permission, if the server is running in authentication ENABLED mode. :param inherited_from: The list of permissions which automatically imply this permission. (Disjunctive list, i.e. if the user has either of these permissions specified, they have the current one too.) Permissions can only be inherited from another permission in the same, or a broader scope. :param managed_by: The list of permissions from which the user must have at least one to manage other users' authorisation on this permission. Permissions can only be managed by having permissions in the same, or a broader scope. :param manages_self: If True, people who have this permission also can manage this permission. """ self.name = name self.default_enable = default_enable if inherited_from is None: inherited_from = [] if managed_by is None: managed_by = [] # Permission can be managed by itself. if manages_self: managed_by = [self] + managed_by # The SUPERUSER permission is a hardcoded special case. if name == 'SUPERUSER': # SUPERUSER is the maximum rank, it cannot be inherited. self.inherited_from = [] else: # Granting SUPERUSER automatically grants every other permission. if SUPERUSER not in inherited_from: inherited_from = [SUPERUSER] + inherited_from # SUPERUSERs can manage every permission by default. if SUPERUSER not in managed_by: managed_by = [SUPERUSER] + managed_by self.inherited_from = inherited_from self.managed_by = managed_by # Contains the list of arguments required by __call__ to initialise a # permission handler. # (Unfortunately, inspect.getargspec() doesn't seem to work when # called from the API handler.) CALL_ARGS = [] @abstractmethod def __call__(self, *args, **kwargs): """ Instantiate a PermissionHandler class for the current permission. This instantiated object can be used to query and manage permissions. This method is overridden in subclasses so that permissions of different scopes can create an appropriate handler. The amount of arguments for this function may vary, depending on the scope of the permission. """ pass class PermissionHandler(metaclass=ABCMeta): """ The abstract base class for an object that interfaces with the permission database to query and manage permissions. """ def __init__(self, permission): """ Create the Permission Handler. :param permission: The Permission object that instantiated this handler. """ self._permission = permission self._perm_name = permission.name # The actual database managing methods (beginning with __) need the # database model to be available, but we cannot say # "import config_db_model" at the top of this file because the database # module needs this module to be fully loaded (permissions constants # defined) to set up the schema. # # Thus, a deferred loading is used here, the first time a permission # handler is initialized. Most likely this import does nothing, # as the server already executed loading the config_db_model, # so we just set the name to properly point to the module object. global config_db_model if config_db_model is None: LOG.debug("Handler initiated for first time, loading ORM...") from .database import config_db_model as ConfigDB config_db_model = ConfigDB # These high-level methods are used by client code. These contain # control flow that are shared for every permission handler # (such as handling default_enabled), but these don't access any # database backend. def add_permission(self, auth_name, is_group=False, user_name='Anonymous'): """ Registers the current permission for the given authentication identifier, which is either a username, or a group name, depending on is_group. """ if auth_name == "*": raise ValueError("'*' is a special token which can NOT be " "directly added to the permission table.") added = self._add_perm_impl(auth_name, is_group) if added: LOG.info("Permission '%s' added for %s '%s' by '%s'.", self._perm_name, 'group' if is_group else 'user', auth_name, user_name) # Set the invariant for default_enable. if self._permission.default_enable: users, groups = self.list_permitted() # If a user was added (and this is the first add to a default # enabled permission) the table must contain '*' and the user, # otherwise a '*' and the currently added group. if (not is_group and len(users) == 2 and not groups) or \ (is_group and len(users) == 1 and len(groups) == 1): self._rem_perm_impl("*", False) else: LOG.info("Permission '%s' already added for %s '%s'!", self._perm_name, 'group' if is_group else 'user', auth_name) def remove_permission(self, auth_name, is_group=False, user_name='Anonymous'): """ Removes the current permission from the given authentication identifier. """ if auth_name == "*": raise ValueError("'*' is a special token which can NOT be " "directly removed from the permission table.") removed = self._rem_perm_impl(auth_name, is_group) if removed: LOG.info("Permission '%s' removed from %s '%s' by '%s'.", self._perm_name, 'group' if is_group else 'user', auth_name, user_name) # Set the invariant for default_enable. if self._permission.default_enable: users, groups = self.list_permitted() if not users and not groups: self._add_perm_impl("*", False) else: LOG.info("Permission '%s' already removed from %s '%s'!", self._perm_name, 'group' if is_group else 'user', auth_name) def has_permission(self, auth_session): """ Returns whether or not the given authenticated user session (or None, if authentication is disabled on the server!) is given the current permission. """ if not auth_session: # If the user does not have an auth_session it means it is a guest # and the server is running in authentication disabled mode. # All permissions are automatically granted in this case. return True elif auth_session.is_root and self._perm_name == 'SUPERUSER': # The special master superuser (root) automatically has the # SUPERUSER permission. return True name = self._has_perm_impl([auth_session.user], False) groups = self._has_perm_impl(auth_session.groups, True) if not name and not groups and self._permission.default_enable: # Default enabled permission work in a way that if no one has the # permission, everyone has it. # ("No-one has the permission" is represented as a * user having # the permission, this invariant kept up by add() and remove().) return self._has_perm_impl(["*"], False) return name or groups def list_permitted(self): """ Returns a pair of usernames and groups that are given the current permission. """ records = self._list_authorised_impl() users = [] groups = [] for name, is_group in records: if is_group: groups.append(name) else: users.append(name) return users, groups # These abstract methods are overridden in the subclasses to interface # with some database backend in a particular way, depending on the # permission's scope. @abstractmethod def _add_perm_impl(self, auth_name, is_group=False): pass @abstractmethod def _rem_perm_impl(self, auth_name, is_group=False): pass @abstractmethod def _has_perm_impl(self, auth_names, are_groups=False): pass @abstractmethod def _list_authorised_impl(self): pass class SystemPermission(Permission): """ Represents a permission which scope is the entire configuration database, essentially the full server. """ class Handler(PermissionHandler): """ This class is used to query server-wide permissions. """ def __init__(self, permission, config_db_session): """ Create a new system-wide permission handler. :param permission: The Permission object that instantiated this handler. :param config_db_session: A database session that refers to the configuration database of the server. """ super(SystemPermission.Handler, self).__init__(permission) self.__session = config_db_session def __get_perm_record(self, auth_name, is_group): SysPerm = config_db_model.SystemPermission record = self.__session. \ query(SysPerm). \ filter(and_( SysPerm.permission == self._perm_name, func.lower(SysPerm.name) == auth_name.lower(), SysPerm.is_group == is_group )).one_or_none() return record def __get_stored_auth_name_and_permissions(self, auth_name, is_group): """ Query user or group system permission set. :param auth_name: User's name or name of group name case insensitive pattern. :param is_group: Determines that the previous name either a user's name or a group name. :returns: A touple in (name, permission_set) structure. """ SysPerm = config_db_model.SystemPermission stored_auth_name = auth_name permissions = set() for name, permission in self.__session.query( SysPerm.name, SysPerm.permission).filter(and_( func.lower(SysPerm.name) == auth_name.lower(), SysPerm.is_group == is_group)): stored_auth_name = name permissions.add(permission) return (stored_auth_name, permissions) def _add_perm_impl(self, auth_name, is_group=False): if not auth_name: return False stored_auth_name, permissions = \ self.__get_stored_auth_name_and_permissions( auth_name, is_group) if not permissions: # This account have not got permission yet. new_permission_record = config_db_model.SystemPermission( self._permission.name, auth_name, is_group) else: # There are at least one permission of the user. if self._permission.name in permissions: return False # Required permission already granted new_permission_record = config_db_model.SystemPermission( self._permission.name, stored_auth_name, is_group) self.__session.add(new_permission_record) return True def _rem_perm_impl(self, auth_name, is_group=False): if not auth_name: return False perm_record = self.__get_perm_record(auth_name, is_group) if perm_record: self.__session.delete(perm_record) return True def _has_perm_impl(self, auth_names, are_groups=False): if not auth_names: return False auth_names_lower = [name.lower() for name in auth_names] SysPerm = config_db_model.SystemPermission query = self.__session. \ query(SysPerm). \ filter(and_( SysPerm.permission == self._perm_name, func.lower(SysPerm.name).in_(auth_names_lower), SysPerm.is_group == are_groups )) exists = self.__session.query(query.exists()).scalar() return exists def _list_authorised_impl(self): SysPerm = config_db_model.SystemPermission result = self.__session. \ query(SysPerm). \ filter(SysPerm.permission == self._perm_name).all() return [(p.name, p.is_group) for p in result] def __init__(self, name, **kwargs): super(SystemPermission, self).__init__(name, **kwargs) CALL_ARGS = ['config_db_session'] def __call__(self, config_db_session): """ Create the permission handler for this system-wide permission, for the given configuration database session. """ return SystemPermission.Handler(self, config_db_session) class ProductPermission(Permission): """ Represents a permission which scope is a particular product. """ class Handler(PermissionHandler): """ This class is used to query product-wide permissions. """ def __init__(self, permission, config_db_session, product_id): """ Create a new product-wide permission handler. :param permission: The Permission object that instantiated this handler. :param config_db_session: A database session that refers to the configuration database of the server. :param product_id: The ID of the product for which the permission is instantiated. """ super(ProductPermission.Handler, self).__init__(permission) self.__session = config_db_session self.__product_id = product_id def __get_perm_record(self, auth_name, is_group): ProdPerm = config_db_model.ProductPermission record = self.__session. \ query(ProdPerm). \ filter(and_( ProdPerm.permission == self._perm_name, ProdPerm.product_id == self.__product_id, func.lower(ProdPerm.name) == auth_name.lower(), ProdPerm.is_group == is_group )).one_or_none() return record def __get_stored_auth_name_and_permissions(self, auth_name, is_group): """ Query user or group product permission set. :param auth_name: User's name or name of group name case insensitive pattern. :param is_group: Determines that the previous name either a user's name or a group name. :returns: A touple in (name, permission_set) structure. """ ProdPerm = config_db_model.ProductPermission stored_auth_name = auth_name permissions = set() for name, permission in self.__session.query( ProdPerm.name, ProdPerm.permission).filter(and_( ProdPerm.product_id == self.__product_id, func.lower(ProdPerm.name) == auth_name.lower(), ProdPerm.is_group == is_group)): stored_auth_name = name permissions.add(permission) return (stored_auth_name, permissions) def _add_perm_impl(self, auth_name, is_group=False): if not auth_name: return False stored_auth_name, permission_set = \ self.__get_stored_auth_name_and_permissions( auth_name, is_group) if not permission_set: # This account have not got permission yet. new_permission_record = config_db_model.ProductPermission( self._permission.name, self.__product_id, auth_name, is_group) else: # There are at least one permission of the user. if self._permission.name in permission_set: return False # Required permission already granted new_permission_record = config_db_model.ProductPermission( self._permission.name, self.__product_id, stored_auth_name, is_group) self.__session.add(new_permission_record) return True def _rem_perm_impl(self, auth_name, is_group=False): if not auth_name: return False perm_record = self.__get_perm_record(auth_name, is_group) if perm_record: self.__session.delete(perm_record) return True def _has_perm_impl(self, auth_names, are_groups=False): if not auth_names: return False # Compare authorization names in a case insensitive way. auth_names_lower = [name.lower() for name in auth_names] ProdPerm = config_db_model.ProductPermission query = self.__session. \ query(ProdPerm). \ filter(and_( ProdPerm.permission == self._perm_name, ProdPerm.product_id == self.__product_id, func.lower(ProdPerm.name).in_(auth_names_lower), ProdPerm.is_group.is_(are_groups) )) exists = self.__session.query(query.exists()).scalar() return exists def _list_authorised_impl(self): ProdPerm = config_db_model.ProductPermission result = self.__session. \ query(ProdPerm). \ filter(and_( ProdPerm.permission == self._perm_name, ProdPerm.product_id == self.__product_id )).all() return [(p.name, p.is_group) for p in result] def __init__(self, name, **kwargs): super(ProductPermission, self).__init__(name, **kwargs) CALL_ARGS = ['config_db_session', 'productID'] def __call__(self, config_db_session, productID): """ Create the permission handler for this product-wide permission on a particular product, managed through the given configuration database session. """ return ProductPermission.Handler(self, config_db_session, productID) # --------------------------------------------------------------------------- PERMISSION_SCOPES = { 'SYSTEM': SystemPermission, 'PRODUCT': ProductPermission } __PERM_TO_API = {} __API_TO_PERM = {} def _create_permission(clazz, name, **kwargs): """ Create a new permission and register it. :param clazz: The subclass of Permission which will be instantiated. :param name: The name of the permission. This is corresponding to the enum value over the API, usually in full capitals. :param kwargs: The rest of the argument dict will be passed as-is to the constructor of clazz. :return: The created permission instance. """ permission = clazz(name, **kwargs) enum_value = PermissionEnum._NAMES_TO_VALUES[name] __PERM_TO_API[permission] = enum_value __API_TO_PERM[enum_value] = permission return permission def get_permissions(scope=None): """ Returns a list of permissions. :param scope: One of the Permission class strings (e.g. 'SYSTEM'), which if given, filters the returned list of permissions to only definitions of the given scope. """ if scope is not None and scope not in PERMISSION_SCOPES: return [] ret = [] for _, perm in sorted(__API_TO_PERM.items()): if scope is not None and \ not isinstance(perm, PERMISSION_SCOPES[scope]): continue ret.append(perm) return ret def permission_from_api_enum(key): """ Returns the Permission object for the associated API enum value. """ return __API_TO_PERM[key] def api_enum_for_permission(permission): """ Return the API enum value for the given permission object. """ return __PERM_TO_API[permission] def handler_from_scope_params(permission, extra_params): """ Construct the given permission's handler using the scope-specific extra arguments (received from the API). This method filters the extra_params to the values actually needed by the handler constructor. """ # Filter the list of arguments of the handler factory __call__() # with the arguments given by the API. args_to_pass = set(extra_params).intersection(permission.CALL_ARGS) kwargs = {key: extra_params[key] for key in args_to_pass} return permission(**kwargs) def initialise_defaults(scope, extra_params): """ Helper function which creates the default-permission records in the database for a given scope and for the scope-specific extra params. This is usually used at server start (for SYSTEM permissions) and the creation of a new product (for PRODUCT permissions), etc. """ perms = [perm for perm in get_permissions(scope)] for perm in perms: handler = handler_from_scope_params(perm, extra_params) users, groups = handler.list_permitted() if perm.default_enable and not users and not groups: # Calling the implementation method directly as this call is # needed to set an invariant which the interface method would # presume to be already standing. handler._add_perm_impl('*', False) elif not perm.default_enable and '*' in users: # If a permission changed meanwhile (this should NOT be a usual # case!), do not let the '*' be locked into the database forever. handler._rem_perm_impl('*', False) def require_permission(permission, extra_params, user): """ Returns whether or not the given user has the given permission. :param extra_params: The scope-specific argument dict, which already contains a valid database session. """ handler = handler_from_scope_params(permission, extra_params) if handler.has_permission(user): return True # If the user for some reason does not have the permission directly # (or by default), we need to walk the inheritance chain of the permission. ancestors = permission.inherited_from while ancestors: handler = handler_from_scope_params(ancestors[0], extra_params) if handler.has_permission(user): return True else: ancestors = ancestors[1:] + ancestors[0].inherited_from return False def require_manager(permission, extra_params, user): """ Returns whether or not the given user has rights to manage the given permission. :param extra_params: The scope-specific argument dict, which already contains a valid database session. """ for manager in permission.managed_by: manager_handler = handler_from_scope_params(manager, extra_params) if manager_handler.has_permission(user): return True return False # --------------------------------------------------------------------------- # Define the permissions available. # Please refer to the user guide and the API documentation on which actions # require which permission in particular. # -- System-level permissions -- SUPERUSER = _create_permission(SystemPermission, 'SUPERUSER', default_enable=False, manages_self=True) # -- Product-level permissions -- PRODUCT_ADMIN = _create_permission(ProductPermission, 'PRODUCT_ADMIN', default_enable=False, managed_by=[SUPERUSER], manages_self=True) PRODUCT_STORE = _create_permission(ProductPermission, 'PRODUCT_STORE', default_enable=False, inherited_from=[PRODUCT_ADMIN], managed_by=[PRODUCT_ADMIN]) PRODUCT_ACCESS = _create_permission(ProductPermission, 'PRODUCT_ACCESS', default_enable=False, inherited_from=[PRODUCT_ADMIN, PRODUCT_STORE], managed_by=[PRODUCT_ADMIN]) PRODUCT_VIEW = _create_permission(ProductPermission, 'PRODUCT_VIEW', default_enable=False, inherited_from=[PRODUCT_ACCESS, PRODUCT_ADMIN, PRODUCT_STORE], managed_by=[PRODUCT_ADMIN])
holoviews/tests/plotting/matplotlib/test_plot.py
TheoMathurin/holoviews
864
148725
<reponame>TheoMathurin/holoviews<gh_stars>100-1000 from unittest import SkipTest from param import concrete_descendents from holoviews.core.options import Store from holoviews.element.comparison import ComparisonTestCase import pyviz_comms as comms try: from holoviews.plotting.mpl.element import ElementPlot import matplotlib.pyplot as plt mpl_renderer = Store.renderers['matplotlib'] except: mpl_renderer = None from .. import option_intersections class TestPlotDefinitions(ComparisonTestCase): known_clashes = [(('Arrow',), {'fontsize'})] def test_matplotlib_plot_definitions(self): self.assertEqual(option_intersections('matplotlib'), self.known_clashes) class TestMPLPlot(ComparisonTestCase): def setUp(self): self.previous_backend = Store.current_backend self.comm_manager = mpl_renderer.comm_manager mpl_renderer.comm_manager = comms.CommManager if not mpl_renderer: raise SkipTest("Matplotlib required to test plot instantiation") Store.set_current_backend('matplotlib') self._padding = {} for plot in concrete_descendents(ElementPlot).values(): self._padding[plot] = plot.padding plot.padding = 0 def tearDown(self): Store.current_backend = self.previous_backend mpl_renderer.comm_manager = self.comm_manager plt.close(plt.gcf()) for plot, padding in self._padding.items(): plot.padding = padding
pytradfri/command.py
ggravlingen/ikeatradfri
726
148738
<gh_stars>100-1000 """Command implementation.""" from __future__ import annotations from collections.abc import Callable from typing import Any, Generic, TypeVar T = TypeVar("T") class Command(Generic[T]): """The object for coap commands.""" def __init__( self, method: str, path: list[str], data: Any | None = None, *, parse_json: bool = True, observe: bool = False, observe_duration: int = 0, process_result: Callable[..., T] | None = None, err_callback: Callable[[Exception], None] | None = None, ) -> None: """Create object of class.""" self._method = method self._path = path self._data = data self._parse_json = parse_json self._process_result = process_result self._err_callback = err_callback self._observe = observe self._observe_duration = observe_duration self._raw_result: list[Any] | dict[Any, Any] | str | None = None # If there's no process_result callback, the result will always be None. # And in that case T will also be None. self._result: T = None # type: ignore[assignment] @property def method(self) -> str: """Return method.""" return self._method @property def path(self) -> list[str]: """Return path.""" return self._path @property def data(self) -> dict[str, Any] | None: """Return data.""" return self._data @property def parse_json(self) -> bool: """Json parsing result.""" return self._parse_json def process_result(self, result: list[Any] | dict[Any, Any] | str | None) -> T: """Process and set result.""" if self._process_result: self._result = self._process_result(result) self._raw_result = result return self._result @property def err_callback(self) -> Callable[[Exception], None] | None: """Will be fired when an observe request fails.""" return self._err_callback @property def observe(self) -> bool: """Observe function.""" return self._observe @property def observe_duration(self) -> int: """Return duration period of observations.""" return self._observe_duration @property def raw_result(self) -> list[Any] | dict[Any, Any] | str | None: """Return raw result.""" return self._raw_result @property def result(self) -> T: """Return result.""" return self._result @property def path_str(self) -> str: """Return coap path.""" return "/".join(str(v) for v in self._path) def url(self, host: str) -> str: """Generate url for coap client.""" return f"coaps://{host}:5684/{self.path_str}" def __repr__(self) -> str: """Return the representation.""" if self.data is None: template = "<Command {} {}{}>" else: template = "<Command {} {}: {}>" return template.format(self.method, self.path, self.data or "")
bagnets/keras.py
tanimutomo/bag-of-local-features-models
320
148744
<reponame>tanimutomo/bag-of-local-features-models import keras from keras.models import load_model __all__ = ['bagnet9', 'bagnet17', 'bagnet33'] model_urls = { 'bagnet9': 'https://bitbucket.org/wielandbrendel/bag-of-feature-pretrained-models/raw/d413271344758455ac086992beb579e256447839/bagnet8.h5', 'bagnet17': 'https://bitbucket.org/wielandbrendel/bag-of-feature-pretrained-models/raw/d413271344758455ac086992beb579e256447839/bagnet16.h5', 'bagnet33': 'https://bitbucket.org/wielandbrendel/bag-of-feature-pretrained-models/raw/d413271344758455ac086992beb579e256447839/bagnet32.h5', } def bagnet9(): model_path = keras.utils.get_file( 'bagnet8.h5', model_urls['bagnet9'], cache_subdir='models', file_hash='5b70adc7c4ff77d932dbba485a5ea1d333a65e777a45511010f22e304a2fdd69') return load_model(model_path) def bagnet17(): model_path = keras.utils.get_file( 'bagnet16.h5', model_urls['bagnet17'], cache_subdir='models', file_hash='b262dfee15a86c91e6aa21bfd86505ecd20a539f7f7c72439d5b1d352dd98a1d') return load_model(model_path) def bagnet33(): model_path = keras.utils.get_file( 'bagnet32.h5', model_urls['bagnet33'], cache_subdir='models', file_hash='96d8842eec8b8ce5b3bc6a5f4ff3c8c0278df3722c12bc84408e1487811f8f0f') return load_model(model_path)
apps/user/templatetags/oauth_tags.py
aosky/blog
335
148757
# 创建了新的tags标签文件后必须重启服务器 from django import template from ..models import Ouser from comment.models import CommentUser register = template.Library() @register.simple_tag() def get_user_data(uid): """返回用户的信息""" user = Ouser.objects.filter(id=uid) if user: return user[0] else: return '' @register.simple_tag() def get_tourist_data(uid): """返回评论者的信息""" user = CommentUser.objects.filter(id=uid) if user: return user[0] else: return ''
seahub/share/views.py
samuelduann/seahub
420
148758
# Copyright (c) 2012-2016 Seafile Ltd. # encoding: utf-8 import os import logging import json from django.core.cache import cache from django.http import HttpResponse, HttpResponseRedirect, Http404, \ HttpResponseBadRequest from django.utils.translation import ugettext as _, activate from django.contrib import messages from django.utils.html import escape import seaserv from seaserv import seafile_api from pysearpc import SearpcError from seahub.share.forms import FileLinkShareForm, \ UploadLinkShareForm from seahub.share.models import FileShare, UploadLinkShare from seahub.share.signals import share_repo_to_user_successful from seahub.auth.decorators import login_required, login_required_ajax from seahub.base.decorators import require_POST from seahub.contacts.signals import mail_sended from seahub.views import is_registered_user, check_folder_permission from seahub.utils import string2list, IS_EMAIL_CONFIGURED, check_filename_with_rename, \ is_valid_username, is_valid_email, send_html_email, is_org_context, \ gen_token, normalize_cache_key, get_site_name from seahub.utils.mail import send_html_email_with_dj_template from seahub.settings import SITE_ROOT, REPLACE_FROM_EMAIL, \ ADD_REPLY_TO_HEADER, SHARE_LINK_EMAIL_LANGUAGE, \ SHARE_LINK_AUDIT_CODE_TIMEOUT from seahub.profile.models import Profile # Get an instance of a logger logger = logging.getLogger(__name__) # rpc wrapper def is_org_repo_owner(username, repo_id): owner = seaserv.seafserv_threaded_rpc.get_org_repo_owner(repo_id) return True if owner == username else False def org_share_repo(org_id, repo_id, from_user, to_user, permission): return seaserv.seafserv_threaded_rpc.org_add_share(org_id, repo_id, from_user, to_user, permission) def org_remove_share(org_id, repo_id, from_user, to_user): return seaserv.seafserv_threaded_rpc.org_remove_share(org_id, repo_id, from_user, to_user) # functions def share_to_group(request, repo, group, permission): """Share repo to group with given permission. """ repo_id = repo.id group_id = group.id from_user = request.user.username if is_org_context(request): org_id = request.user.org.org_id group_repo_ids = seafile_api.get_org_group_repoids(org_id, group.id) else: group_repo_ids = seafile_api.get_group_repoids(group.id) if repo.id in group_repo_ids: return False try: if is_org_context(request): org_id = request.user.org.org_id seafile_api.add_org_group_repo(repo_id, org_id, group_id, from_user, permission) else: seafile_api.set_group_repo(repo_id, group_id, from_user, permission) return True except Exception as e: logger.error(e) return False def share_to_user(request, repo, to_user, permission): """Share repo to a user with given permission. """ repo_id = repo.id from_user = request.user.username if from_user == to_user: return False # permission check org_id = None if is_org_context(request): org_id = request.user.org.org_id if not seaserv.ccnet_threaded_rpc.org_user_exists(org_id, to_user): return False else: if not is_registered_user(to_user): return False try: if is_org_context(request): org_id = request.user.org.org_id org_share_repo(org_id, repo_id, from_user, to_user, permission) else: seafile_api.share_repo(repo_id, from_user, to_user, permission) except SearpcError as e: logger.error(e) return False else: # send a signal when sharing repo successful share_repo_to_user_successful.send(sender=None, from_user=from_user, to_user=to_user, repo=repo, path='/', org_id=org_id) return True # share link @login_required_ajax def send_shared_link(request): """ Handle ajax post request to send file shared link. """ if not request.method == 'POST': raise Http404 content_type = 'application/json; charset=utf-8' if not IS_EMAIL_CONFIGURED: data = json.dumps({'error': _('Failed to send email, email service is not properly configured, please contact administrator.')}) return HttpResponse(data, status=500, content_type=content_type) form = FileLinkShareForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] file_shared_link = form.cleaned_data['file_shared_link'] file_shared_name = form.cleaned_data['file_shared_name'] file_shared_type = form.cleaned_data['file_shared_type'] extra_msg = escape(form.cleaned_data['extra_msg']) to_email_list = string2list(email) send_success, send_failed = [], [] # use contact_email, if present username = Profile.objects.get_contact_email_by_user(request.user.username) for to_email in to_email_list: if not is_valid_email(to_email): send_failed.append(to_email) continue if SHARE_LINK_EMAIL_LANGUAGE: activate(SHARE_LINK_EMAIL_LANGUAGE) # Add email to contacts. mail_sended.send(sender=None, user=request.user.username, email=to_email) c = { 'email': request.user.username, 'to_email': to_email, 'file_shared_link': file_shared_link, 'file_shared_name': file_shared_name, } if extra_msg: c['extra_msg'] = extra_msg if REPLACE_FROM_EMAIL: from_email = username else: from_email = None # use default from email if ADD_REPLY_TO_HEADER: reply_to = username else: reply_to = None try: if file_shared_type == 'f': c['file_shared_type'] = _("file") send_html_email(_('A file is shared to you on %s') % get_site_name(), 'shared_link_email.html', c, from_email, [to_email], reply_to=reply_to ) else: c['file_shared_type'] = _("directory") send_html_email(_('A directory is shared to you on %s') % get_site_name(), 'shared_link_email.html', c, from_email, [to_email], reply_to=reply_to) send_success.append(to_email) except Exception: send_failed.append(to_email) if len(send_success) > 0: data = json.dumps({"send_success": send_success, "send_failed": send_failed}) return HttpResponse(data, status=200, content_type=content_type) else: data = json.dumps({"error": _("Internal server error, or please check the email(s) you entered")}) return HttpResponse(data, status=400, content_type=content_type) else: return HttpResponseBadRequest(json.dumps(form.errors), content_type=content_type) @login_required def save_shared_link(request): """Save public share link to one's library. """ username = request.user.username token = request.GET.get('t', '') dst_repo_id = request.POST.get('dst_repo', '') dst_path = request.POST.get('dst_path', '') next_page = request.META.get('HTTP_REFERER', None) if not next_page: next_page = SITE_ROOT if not dst_repo_id or not dst_path: messages.error(request, _('Please choose a directory.')) return HttpResponseRedirect(next_page) if check_folder_permission(request, dst_repo_id, dst_path) != 'rw': messages.error(request, _('Permission denied')) return HttpResponseRedirect(next_page) try: fs = FileShare.objects.get(token=token) except FileShare.DoesNotExist: raise Http404 src_repo_id = fs.repo_id src_path = os.path.dirname(fs.path) obj_name = os.path.basename(fs.path) new_obj_name = check_filename_with_rename(dst_repo_id, dst_path, obj_name) seafile_api.copy_file(src_repo_id, src_path, obj_name, dst_repo_id, dst_path, new_obj_name, username, need_progress=0) messages.success(request, _('Successfully saved.')) return HttpResponseRedirect(next_page) @login_required_ajax def send_shared_upload_link(request): """ Handle ajax post request to send shared upload link. """ if not request.method == 'POST': raise Http404 content_type = 'application/json; charset=utf-8' if not IS_EMAIL_CONFIGURED: data = json.dumps({'error': _('Failed to send email, email service is not properly configured, please contact administrator.')}) return HttpResponse(data, status=500, content_type=content_type) form = UploadLinkShareForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] shared_upload_link = form.cleaned_data['shared_upload_link'] extra_msg = escape(form.cleaned_data['extra_msg']) to_email_list = string2list(email) send_success, send_failed = [], [] # use contact_email, if present username = Profile.objects.get_contact_email_by_user(request.user.username) for to_email in to_email_list: if not is_valid_email(to_email): send_failed.append(to_email) continue # Add email to contacts. mail_sended.send(sender=None, user=request.user.username, email=to_email) c = { 'email': request.user.username, 'to_email': to_email, 'shared_upload_link': shared_upload_link, } if extra_msg: c['extra_msg'] = extra_msg if REPLACE_FROM_EMAIL: from_email = username else: from_email = None # use default from email if ADD_REPLY_TO_HEADER: reply_to = username else: reply_to = None try: send_html_email(_('An upload link is shared to you on %s') % get_site_name(), 'shared_upload_link_email.html', c, from_email, [to_email], reply_to=reply_to) send_success.append(to_email) except Exception: send_failed.append(to_email) if len(send_success) > 0: data = json.dumps({"send_success": send_success, "send_failed": send_failed}) return HttpResponse(data, status=200, content_type=content_type) else: data = json.dumps({"error": _("Internal server error, or please check the email(s) you entered")}) return HttpResponse(data, status=400, content_type=content_type) else: return HttpResponseBadRequest(json.dumps(form.errors), content_type=content_type) @login_required_ajax @require_POST def ajax_private_share_dir(request): content_type = 'application/json; charset=utf-8' repo_id = request.POST.get('repo_id', '') path = request.POST.get('path', '') username = request.user.username result = {} repo = seafile_api.get_repo(repo_id) if not repo: result['error'] = _('Library does not exist.') return HttpResponse(json.dumps(result), status=400, content_type=content_type) if seafile_api.get_dir_id_by_path(repo_id, path) is None: result['error'] = _('Directory does not exist.') return HttpResponse(json.dumps(result), status=400, content_type=content_type) if path != '/': # if share a dir, check sub-repo first try: if is_org_context(request): org_id = request.user.org.org_id sub_repo = seaserv.seafserv_threaded_rpc.get_org_virtual_repo( org_id, repo_id, path, username) else: sub_repo = seafile_api.get_virtual_repo(repo_id, path, username) except SearpcError as e: result['error'] = e.msg return HttpResponse(json.dumps(result), status=500, content_type=content_type) if not sub_repo: name = os.path.basename(path) # create a sub-lib try: # use name as 'repo_name' & 'repo_desc' for sub_repo if is_org_context(request): org_id = request.user.org.org_id sub_repo_id = seaserv.seafserv_threaded_rpc.create_org_virtual_repo( org_id, repo_id, path, name, name, username) else: sub_repo_id = seafile_api.create_virtual_repo(repo_id, path, name, name, username) sub_repo = seafile_api.get_repo(sub_repo_id) except SearpcError as e: result['error'] = e.msg return HttpResponse(json.dumps(result), status=500, content_type=content_type) shared_repo_id = sub_repo.id shared_repo = sub_repo else: shared_repo_id = repo_id shared_repo = repo emails_string = request.POST.get('emails', '') groups_string = request.POST.get('groups', '') perm = request.POST.get('perm', '') emails = string2list(emails_string) groups = string2list(groups_string) # Test whether user is the repo owner. if not seafile_api.is_repo_owner(username, shared_repo_id) and \ not is_org_repo_owner(username, shared_repo_id): result['error'] = _('Only the owner of the library has permission to share it.') return HttpResponse(json.dumps(result), status=500, content_type=content_type) # Parsing input values. # no 'share_to_all' share_to_groups, share_to_users, shared_success, shared_failed = [], [], [], [] for email in emails: email = email.lower() if is_valid_username(email): share_to_users.append(email) else: shared_failed.append(email) for group_id in groups: share_to_groups.append(seaserv.get_group(group_id)) for email in share_to_users: # Add email to contacts. mail_sended.send(sender=None, user=request.user.username, email=email) if share_to_user(request, shared_repo, email, perm): shared_success.append(email) else: shared_failed.append(email) for group in share_to_groups: if share_to_group(request, shared_repo, group, perm): shared_success.append(group.group_name) else: shared_failed.append(group.group_name) if len(shared_success) > 0: return HttpResponse(json.dumps({ "shared_success": shared_success, "shared_failed": shared_failed }), content_type=content_type) else: # for case: only share to users and the emails are not valid data = json.dumps({"error": _("Please check the email(s) you entered")}) return HttpResponse(data, status=400, content_type=content_type) def ajax_get_link_audit_code(request): """ Generate a token, and record that token with email in cache, expires in one hour, send token to that email address. User provide token and email at share link page, if the token and email are valid, record that email in session. """ content_type = 'application/json; charset=utf-8' token = request.POST.get('token') email = request.POST.get('email') if not is_valid_email(email): return HttpResponse(json.dumps({ 'error': _('Email address is not valid') }), status=400, content_type=content_type) dfs = FileShare.objects.get_valid_file_link_by_token(token) ufs = UploadLinkShare.objects.get_valid_upload_link_by_token(token) fs = dfs if dfs else ufs if fs is None: return HttpResponse(json.dumps({ 'error': _('Share link is not found') }), status=400, content_type=content_type) cache_key = normalize_cache_key(email, 'share_link_audit_') code = gen_token(max_length=6) cache.set(cache_key, code, SHARE_LINK_AUDIT_CODE_TIMEOUT) # send code to user via email subject = _("Verification code for visiting share links") c = {'code': code} send_success = send_html_email_with_dj_template(email, subject=subject, dj_template='share/audit_code_email.html', context=c) if not send_success: logger.error('Failed to send audit code via email to %s') return HttpResponse(json.dumps({ "error": _("Failed to send a verification code, please try again later.") }), status=500, content_type=content_type) return HttpResponse(json.dumps({'success': True}), status=200, content_type=content_type)
cvxpy/reductions/flip_objective.py
hashstat/cvxpy
3,285
148764
""" Copyright 2017 <NAME> 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. """ from cvxpy.expressions import cvxtypes from cvxpy.problems.objective import Maximize, Minimize from cvxpy.reductions.reduction import Reduction class FlipObjective(Reduction): """Flip a minimization objective to a maximization and vice versa. """ def accepts(self, problem) -> bool: return True def apply(self, problem): """:math:`\\max(f(x)) = -\\min(-f(x))` Parameters ---------- problem : Problem The problem whose objective is to be flipped. Returns ------- Problem A problem with a flipped objective. list The inverse data. """ is_maximize = type(problem.objective) == Maximize objective = Minimize if is_maximize else Maximize problem = cvxtypes.problem()(objective(-problem.objective.expr), problem.constraints) return problem, [] def invert(self, solution, inverse_data): """Map the solution of the flipped problem to that of the original. Parameters ---------- solution : Solution A solution object. inverse_data : list The inverse data returned by an invocation to apply. Returns ------- Solution A solution to the original problem. """ if solution.opt_val is not None: solution.opt_val = -solution.opt_val return solution
tests/unit_tests.py
VamshiKrishnaUM/flask-social
173
148781
<gh_stars>100-1000 from unittest import TestCase from flask_social.core import _SocialState class FlaskSocialUnitTests(TestCase): def test_social_state_raises_attribute_error(self): state = _SocialState(providers={}) self.assertRaises(AttributeError, lambda: state.something)
tests/test_sparse_unet.py
BB88Lee/mmdetection3d
217
148796
import torch from mmdet3d.ops import SparseBasicBlock from mmdet3d.ops import spconv as spconv def test_SparseUNet(): from mmdet3d.models.middle_encoders.sparse_unet import SparseUNet self = SparseUNet(in_channels=4, sparse_shape=[41, 1600, 1408]) # test encoder layers assert len(self.encoder_layers) == 4 assert self.encoder_layers.encoder_layer1[0][0].in_channels == 16 assert self.encoder_layers.encoder_layer1[0][0].out_channels == 16 assert isinstance(self.encoder_layers.encoder_layer1[0][0], spconv.conv.SubMConv3d) assert isinstance(self.encoder_layers.encoder_layer1[0][1], torch.nn.modules.batchnorm.BatchNorm1d) assert isinstance(self.encoder_layers.encoder_layer1[0][2], torch.nn.modules.activation.ReLU) assert self.encoder_layers.encoder_layer4[0][0].in_channels == 64 assert self.encoder_layers.encoder_layer4[0][0].out_channels == 64 assert isinstance(self.encoder_layers.encoder_layer4[0][0], spconv.conv.SparseConv3d) assert isinstance(self.encoder_layers.encoder_layer4[2][0], spconv.conv.SubMConv3d) # test decoder layers assert isinstance(self.lateral_layer1, SparseBasicBlock) assert isinstance(self.merge_layer1[0], spconv.conv.SubMConv3d) assert isinstance(self.upsample_layer1[0], spconv.conv.SubMConv3d) assert isinstance(self.upsample_layer2[0], spconv.conv.SparseInverseConv3d) voxel_features = torch.tensor([[6.56126, 0.9648336, -1.7339306, 0.315], [6.8162713, -2.480431, -1.3616394, 0.36], [11.643568, -4.744306, -1.3580885, 0.16], [23.482342, 6.5036807, 0.5806964, 0.35]], dtype=torch.float32) # n, point_features coordinates = torch.tensor( [[0, 12, 819, 131], [0, 16, 750, 136], [1, 16, 705, 232], [1, 35, 930, 469]], dtype=torch.int32) # n, 4(batch, ind_x, ind_y, ind_z) unet_ret_dict = self.forward(voxel_features, coordinates, 2) seg_features = unet_ret_dict['seg_features'] spatial_features = unet_ret_dict['spatial_features'] assert seg_features.shape == torch.Size([4, 16]) assert spatial_features.shape == torch.Size([2, 256, 200, 176]) def test_SparseBasicBlock(): voxel_features = torch.tensor([[6.56126, 0.9648336, -1.7339306, 0.315], [6.8162713, -2.480431, -1.3616394, 0.36], [11.643568, -4.744306, -1.3580885, 0.16], [23.482342, 6.5036807, 0.5806964, 0.35]], dtype=torch.float32) # n, point_features coordinates = torch.tensor( [[0, 12, 819, 131], [0, 16, 750, 136], [1, 16, 705, 232], [1, 35, 930, 469]], dtype=torch.int32) # n, 4(batch, ind_x, ind_y, ind_z) # test input_sp_tensor = spconv.SparseConvTensor(voxel_features, coordinates, [41, 1600, 1408], 2) self = SparseBasicBlock( 4, 4, conv_cfg=dict(type='SubMConv3d', indice_key='subm1'), norm_cfg=dict(type='BN1d', eps=1e-3, momentum=0.01)) # test conv and bn layer assert isinstance(self.conv1, spconv.conv.SubMConv3d) assert self.conv1.in_channels == 4 assert self.conv1.out_channels == 4 assert isinstance(self.conv2, spconv.conv.SubMConv3d) assert self.conv2.out_channels == 4 assert self.conv2.out_channels == 4 assert self.bn1.eps == 1e-3 assert self.bn1.momentum == 0.01 out_features = self(input_sp_tensor) assert out_features.features.shape == torch.Size([4, 4]) def test_make_sparse_convmodule(): from mmdet3d.ops import make_sparse_convmodule voxel_features = torch.tensor([[6.56126, 0.9648336, -1.7339306, 0.315], [6.8162713, -2.480431, -1.3616394, 0.36], [11.643568, -4.744306, -1.3580885, 0.16], [23.482342, 6.5036807, 0.5806964, 0.35]], dtype=torch.float32) # n, point_features coordinates = torch.tensor( [[0, 12, 819, 131], [0, 16, 750, 136], [1, 16, 705, 232], [1, 35, 930, 469]], dtype=torch.int32) # n, 4(batch, ind_x, ind_y, ind_z) # test input_sp_tensor = spconv.SparseConvTensor(voxel_features, coordinates, [41, 1600, 1408], 2) sparse_block0 = make_sparse_convmodule( 4, 16, 3, 'test0', stride=1, padding=0, conv_type='SubMConv3d', norm_cfg=dict(type='BN1d', eps=1e-3, momentum=0.01), order=('conv', 'norm', 'act')) assert isinstance(sparse_block0[0], spconv.SubMConv3d) assert sparse_block0[0].in_channels == 4 assert sparse_block0[0].out_channels == 16 assert isinstance(sparse_block0[1], torch.nn.BatchNorm1d) assert sparse_block0[1].eps == 0.001 assert sparse_block0[1].momentum == 0.01 assert isinstance(sparse_block0[2], torch.nn.ReLU) # test forward out_features = sparse_block0(input_sp_tensor) assert out_features.features.shape == torch.Size([4, 16]) sparse_block1 = make_sparse_convmodule( 4, 16, 3, 'test1', stride=1, padding=0, conv_type='SparseInverseConv3d', norm_cfg=dict(type='BN1d', eps=1e-3, momentum=0.01), order=('norm', 'act', 'conv')) assert isinstance(sparse_block1[0], torch.nn.BatchNorm1d) assert isinstance(sparse_block1[1], torch.nn.ReLU) assert isinstance(sparse_block1[2], spconv.SparseInverseConv3d)
src/cowrie/output/greynoise.py
uwacyber/cowrie
2,316
148822
""" Send attackers IP to GreyNoise """ from __future__ import annotations import treq from twisted.internet import defer, error from twisted.python import log import cowrie.core.output from cowrie.core.config import CowrieConfig COWRIE_USER_AGENT = "Cowrie Honeypot" GNAPI_URL = "https://api.greynoise.io/v3/community/" class Output(cowrie.core.output.Output): """ greynoise output """ def start(self): """ Start output plugin """ self.apiKey = CowrieConfig.get("output_greynoise", "api_key", fallback=None) self.debug = CowrieConfig.getboolean( "output_greynoise", "debug", fallback=False ) def stop(self): """ Stop output plugin """ pass def write(self, entry): if entry["eventid"] == "cowrie.session.connect": self.scanip(entry) @defer.inlineCallbacks def scanip(self, entry): """ Scan IP against GreyNoise API """ def message(query): if query["noise"]: log.msg( eventid="cowrie.greynoise.result", session=entry["session"], format=f"GreyNoise: {query['ip']} has been observed scanning the Internet. GreyNoise " f"classification is {query['classification']} and the believed owner is {query['name']}", ) if query["riot"]: log.msg( eventid="cowrie.greynoise.result", session=entry["session"], format=f"GreyNoise: {query['ip']} belongs to a benign service or provider. " f"The owner is {query['name']}.", ) gn_url = f"{GNAPI_URL}{entry['src_ip']}".encode() headers = {"User-Agent": [COWRIE_USER_AGENT], "key": self.apiKey} try: response = yield treq.get(url=gn_url, headers=headers, timeout=10) except ( defer.CancelledError, error.ConnectingCancelledError, error.DNSLookupError, ): log.msg("GreyNoise requests timeout") return if response.code == 404: rsp = yield response.json() log.err(f"GreyNoise: {rsp['ip']} - {rsp['message']}") return if response.code != 200: rsp = yield response.text() log.err(f"GreyNoise: got error {rsp}") return j = yield response.json() if self.debug: log.msg("GreyNoise: debug: " + repr(j)) if j["message"] == "Success": message(j) else: log.msg("GreyNoise: no results for for IP {}".format(entry["src_ip"]))
basic_code/load.py
Soapy-Salted-Fish-King/Emotion-FAN
275
148838
<filename>basic_code/load.py from __future__ import print_function import torch print(torch.__version__) import torch.utils.data import torchvision.transforms as transforms from basic_code import data_generator cate2label = {'CK+':{0: 'Happy', 1: 'Angry', 2: 'Disgust', 3: 'Fear', 4: 'Sad', 5: 'Contempt', 6: 'Surprise', 'Angry': 1,'Disgust': 2,'Fear': 3,'Happy': 0,'Contempt': 5,'Sad': 4,'Surprise': 6}, 'AFEW':{0: 'Happy',1: 'Angry',2: 'Disgust',3: 'Fear',4: 'Sad',5: 'Neutral',6: 'Surprise', 'Angry': 1,'Disgust': 2,'Fear': 3,'Happy': 0,'Neutral': 5,'Sad': 4,'Surprise': 6}} def ckplus_faces_baseline(video_root, video_list, fold, batchsize_train, batchsize_eval): train_dataset = data_generator.TenFold_VideoDataset( video_root=video_root, video_list=video_list, rectify_label=cate2label['CK+'], transform=transforms.Compose([transforms.Resize(224), transforms.RandomHorizontalFlip(), transforms.ToTensor()]), fold=fold, run_type='train' ) val_dataset = data_generator.TenFold_VideoDataset( video_root=video_root, video_list=video_list, rectify_label=cate2label['CK+'], transform=transforms.Compose([transforms.Resize(224), transforms.ToTensor()]), fold=fold, run_type='test' ) train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=batchsize_train, shuffle=True, num_workers=8,pin_memory=True) val_loader = torch.utils.data.DataLoader( val_dataset, batch_size=batchsize_eval, shuffle=False, num_workers=8, pin_memory=True) return train_loader, val_loader def ckplus_faces_fan(video_root, video_list, fold, batchsize_train, batchsize_eval): train_dataset = data_generator.TenFold_TripleImageDataset( video_root=video_root, video_list=video_list, rectify_label=cate2label['CK+'], transform=transforms.Compose([ transforms.Resize(224), transforms.RandomHorizontalFlip(), transforms.ToTensor()]), fold=fold, run_type='train', ) val_dataset = data_generator.TenFold_VideoDataset( video_root=video_root, video_list=video_list, rectify_label=cate2label['CK+'], transform=transforms.Compose([transforms.Resize(224), transforms.ToTensor()]), fold=fold, run_type='test' ) train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=batchsize_train, shuffle=True, num_workers=8,pin_memory=True) val_loader = torch.utils.data.DataLoader( val_dataset, batch_size=batchsize_eval, shuffle=False, num_workers=8, pin_memory=True) return train_loader, val_loader def afew_faces_baseline(root_train, list_train, batchsize_train, root_eval, list_eval, batchsize_eval): train_dataset = data_generator.VideoDataset( video_root=root_train, video_list=list_train, rectify_label=cate2label['AFEW'], transform=transforms.Compose([transforms.Resize(224), transforms.RandomHorizontalFlip(), transforms.ToTensor()]), ) val_dataset = data_generator.VideoDataset( video_root=root_eval, video_list=list_eval, rectify_label=cate2label['AFEW'], transform=transforms.Compose([transforms.Resize(224), transforms.ToTensor()]), csv=False) train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=batchsize_train, shuffle=True, num_workers=8, pin_memory=True) val_loader = torch.utils.data.DataLoader( val_dataset, batch_size=batchsize_eval, shuffle=False, num_workers=8, pin_memory=True) return train_loader, val_loader def afew_faces_fan(root_train, list_train, batchsize_train, root_eval, list_eval, batchsize_eval): train_dataset = data_generator.TripleImageDataset( video_root=root_train, video_list=list_train, rectify_label=cate2label['AFEW'], transform=transforms.Compose([transforms.Resize(224), transforms.RandomHorizontalFlip(), transforms.ToTensor()]), ) val_dataset = data_generator.VideoDataset( video_root=root_eval, video_list=list_eval, rectify_label=cate2label['AFEW'], transform=transforms.Compose([transforms.Resize(224), transforms.ToTensor()]), csv=False) train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=batchsize_train, shuffle=True, num_workers=8, pin_memory=True, drop_last=True) val_loader = torch.utils.data.DataLoader( val_dataset, batch_size=batchsize_eval, shuffle=False, num_workers=8, pin_memory=True) return train_loader, val_loader def model_parameters(_structure, _parameterDir): checkpoint = torch.load(_parameterDir) pretrained_state_dict = checkpoint['state_dict'] model_state_dict = _structure.state_dict() for key in pretrained_state_dict: if ((key == 'module.fc.weight') | (key == 'module.fc.bias')): pass else: model_state_dict[key.replace('module.', '')] = pretrained_state_dict[key] _structure.load_state_dict(model_state_dict) model = torch.nn.DataParallel(_structure).cuda() return model
Face-Detection/Deep Dense Face Detection/face/datasets/celeb.py
swapnilgarg7/Face-X
175
148859
""" Code for working with Celeb+ dataset """ import os import shutil import subprocess import glob import face.download import face.utilities import face.geometry class DatasetBuilder: """ Class for downloading Celeb+ data and preparing datasets from it. """ def __init__(self, data_directory): self.data_directory = data_directory self.bounding_boxes_path = os.path.join(self.data_directory, "all_bounding_boxes.txt") def build_datasets(self): shutil.rmtree(self.data_directory, ignore_errors=True) os.makedirs(self.data_directory, exist_ok=True) self._get_images() self._get_bounding_boxes() image_paths = self._get_image_paths(self.data_directory) bounding_boxes_map = self._get_bounding_boxes_map(self.bounding_boxes_path) datasets_dirs = ["large_dataset", "medium_dataset", "small_dataset"] large_dataset_split = [0, 180000, 190000, len(image_paths)] medium_dataset_split = [0, 10000, 20000, 30000] small_dataset_split = [0, 1000, 2000, 3000] splits = [large_dataset_split, medium_dataset_split, small_dataset_split] for dataset_dir, splits in zip(datasets_dirs, splits): directory = os.path.join(self.data_directory, dataset_dir) DataSubsetBuilder(directory, image_paths, bounding_boxes_map, splits).build() def _get_images(self): image_archives_urls = [ "https://www.dropbox.com/sh/8oqt9vytwxb3s4r/AABQwEE5YX5jTFGXjo0f9glIa/Img/img_celeba.7z/img_celeba.7z.001?dl=1", "https://www.dropbox.com/sh/8oqt9vytwxb3s4r/AADxKopMA7g_Ka2o7X7B8jiHa/Img/img_celeba.7z/img_celeba.7z.002?dl=1", "https://www.dropbox.com/sh/8oqt9vytwxb3s4r/AABSqeGALxGo1sXZ-ZizRFa5a/Img/img_celeba.7z/img_celeba.7z.003?dl=1", "https://www.dropbox.com/sh/8oqt9vytwxb3s4r/AADBal8W3N9AYwYuqwTtA_fQa/Img/img_celeba.7z/img_celeba.7z.004?dl=1", "https://www.dropbox.com/sh/8oqt9vytwxb3s4r/AACJaDb7rWNFcCKqcFjFjUlHa/Img/img_celeba.7z/img_celeba.7z.005?dl=1", "https://www.dropbox.com/sh/8oqt9vytwxb3s4r/AACcD0ZMO36zVaIfLGLKtrq4a/Img/img_celeba.7z/img_celeba.7z.006?dl=1", "https://www.dropbox.com/sh/8oqt9vytwxb3s4r/AAAhuX-S5ULmy8GII6jlZFb9a/Img/img_celeba.7z/img_celeba.7z.007?dl=1", "https://www.dropbox.com/sh/8oqt9vytwxb3s4r/AAAUtign0NJIV8fRK7xt6TIEa/Img/img_celeba.7z/img_celeba.7z.008?dl=1", "https://www.dropbox.com/sh/8oqt9vytwxb3s4r/AACJsmneLOU5xMB2qmnJA0AGa/Img/img_celeba.7z/img_celeba.7z.009?dl=1", "https://www.dropbox.com/sh/8oqt9vytwxb3s4r/AAAfZVSjBlkPr5e5GYMek50_a/Img/img_celeba.7z/img_celeba.7z.010?dl=1", "https://www.dropbox.com/sh/8oqt9vytwxb3s4r/AAA6-edxuJyMBoGZqTdl28bpa/Img/img_celeba.7z/img_celeba.7z.011?dl=1", "https://www.dropbox.com/sh/8oqt9vytwxb3s4r/AABMLOgnvv8DKxt4UvULSAoha/Img/img_celeba.7z/img_celeba.7z.012?dl=1", "https://www.dropbox.com/sh/8oqt9vytwxb3s4r/AABOeeqqAzZEY6jDwTdOUTqRa/Img/img_celeba.7z/img_celeba.7z.013?dl=1", "https://www.dropbox.com/sh/8oqt9vytwxb3s4r/AADuEM2h2qG_L0UbUTViRH5Da/Img/img_celeba.7z/img_celeba.7z.014?dl=1" ] filenames = [os.path.basename(url).split("?")[0] for url in image_archives_urls] paths = [os.path.join(self.data_directory, filename) for filename in filenames] # Download image archives for url, path in zip(image_archives_urls, paths): face.download.Downloader(url, path).download() # Extract images subprocess.call(["7z", "x", paths[0], "-o" + self.data_directory]) # Delete image archives for path in paths: os.remove(path) def _get_bounding_boxes(self): url = "https://www.dropbox.com/sh/8oqt9vytwxb3s4r/AACL5lLyHMAHvFA8W17JDahma/Anno/list_bbox_celeba.txt?dl=1" face.download.Downloader(url, self.bounding_boxes_path).download() def _get_image_paths(self, data_directory): image_paths = glob.glob(os.path.join(data_directory, "**/*.jpg"), recursive=True) image_paths = [os.path.abspath(path) for path in image_paths] return image_paths def _get_bounding_boxes_map(self, bounding_boxes_path): bounding_boxes_lines = face.utilities.get_file_lines(bounding_boxes_path)[2:] bounding_boxes_map = {} for line in bounding_boxes_lines: tokens = line.split() filename = tokens[0] integer_tokens = [round(token) for token in tokens[1:]] bounding_box = face.geometry.get_bounding_box(*integer_tokens) bounding_boxes_map[filename] = bounding_box return bounding_boxes_map class DataSubsetBuilder: """ A helper class for DatasetBuilder """ def __init__(self, directory, image_paths, bounding_boxes_map, splits): self.data_directory = directory self.image_paths = image_paths self.bounding_boxes_map = bounding_boxes_map self.splits = splits def build(self): shutil.rmtree(self.data_directory, ignore_errors=True) os.makedirs(self.data_directory, exist_ok=True) training_image_paths = self.image_paths[self.splits[0]:self.splits[1]] validation_image_paths = self.image_paths[self.splits[1]:self.splits[2]] test_image_paths = self.image_paths[self.splits[2]:self.splits[3]] splitted_image_paths = [training_image_paths, validation_image_paths, test_image_paths] prefixes = ["training_", "validation_", "test_"] images_list_file_names = [prefix + "image_paths.txt" for prefix in prefixes] images_list_file_paths = [os.path.join(self.data_directory, filename) for filename in images_list_file_names] # Create files with image paths for image_list_path, image_paths in zip(images_list_file_paths, splitted_image_paths): self._create_paths_file(image_list_path, image_paths) bounding_boxes_list_file_names = [prefix + "bounding_boxes_list.txt" for prefix in prefixes] bounding_boxes_list_file_paths = [os.path.join(self.data_directory, filename) for filename in bounding_boxes_list_file_names] # Create files with bounding boxes lists for bounding_box_list_path, image_paths in zip(bounding_boxes_list_file_paths, splitted_image_paths): self._create_bounding_boxes_file(bounding_box_list_path, image_paths, self.bounding_boxes_map) def _create_paths_file(self, file_path, image_paths): paths = [path + "\n" for path in image_paths] with open(file_path, "w") as file: file.writelines(paths) def _create_bounding_boxes_file(self, file_path, image_paths, bounding_boxes_map): image_paths = [os.path.basename(path) for path in image_paths] header = str(len(image_paths)) + "\nimage_id x_1 y_1 width height\n" with open(file_path, "w") as file: file.write(header) for image_path in image_paths: bounds = [round(value) for value in bounding_boxes_map[image_path].bounds] x = bounds[0] y = bounds[1] width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] line = "{}\t{} {} {} {}\n".format(image_path, x, y, width, height) file.write(line)