repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
---|---|---|
dongdong1018645785/touch-air-mall | mall-member/src/main/java/com/touch/air/mall/member/dao/MemberCollectSpuDao.java | <reponame>dongdong1018645785/touch-air-mall
package com.touch.air.mall.member.dao;
import com.touch.air.mall.member.entity.MemberCollectSpuEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 会员收藏的商品
*
* @author bin.wang
* @email <EMAIL>
* @date 2020-12-04 14:18:41
*/
@Mapper
public interface MemberCollectSpuDao extends BaseMapper<MemberCollectSpuEntity> {
}
|
noear/luffy | luffy.executor.m.velocity/src/main/java/org/noear/luffy/executor/m/velocity/XPluginImp.java | <gh_stars>1-10
package org.noear.luffy.executor.m.velocity;
import org.apache.velocity.runtime.directive.Directive;
import org.noear.solon.Solon;
import org.noear.solon.SolonApp;
import org.noear.solon.core.Aop;
import org.noear.solon.core.Plugin;
import org.noear.luffy.executor.ExecutorFactory;
public class XPluginImp implements Plugin {
@Override
public void start(SolonApp app) {
VelocityJtExecutor executor = VelocityJtExecutor.singleton();
Aop.beanOnloaded(() -> {
Aop.beanForeach((k, v) -> {
if (k.startsWith("view:")) { //java view widget
if (v.raw() instanceof Directive) {
executor.tagReg(v.raw());
}
return;
}
if(k.startsWith("share:")){ //java share object
executor.sharedSet(k.split(":")[1], v.raw());
return;
}
});
});
ExecutorFactory.register(executor);
}
}
|
asplos2020/DRTest | generate_adv/pure.py | <filename>generate_adv/pure.py<gh_stars>1-10
import sys
sys.path.append('../')
from tensorflow.python.platform import flags
from nmutant_model.model_operation import model_load
from nmutant_data.mnist import data_mnist
import tensorflow as tf
from nmutant_data.data import get_shape
from nmutant_util.utils_file import get_data_file
from nmutant_util.utils_tf import model_prediction
from nmutant_util.utils_imgproc import deprocess_image_1, preprocess_image_1
import math
import os
from scipy.misc import imsave, imread
import numpy as np
FLAGS = flags.FLAGS
def pure(datasets='mnist', attack='fgsm', model_name='lenet1'):
tf.reset_default_graph()
samples_path='../adv_result/'+datasets+'/'+attack+'/'+model_name+'/pure'
if not os.path.isdir(samples_path):
os.makedirs(samples_path+'/train')
os.makedirs(samples_path+'/test')
samples_path_train='../adv_result/'+datasets+'/'+attack+'/'+model_name+'/train_data'
samples_path_test='../adv_result/'+datasets+'/'+attack+'/'+model_name+'/test_data'
sess, preds, x, y, model, feed_dict = model_load(datasets, model_name)
[image_list_train, image_files_train, real_labels_train, predicted_labels_train] = get_data_file(samples_path_train)
[image_list_test, image_files_test, real_labels_test, predicted_labels_test] = get_data_file(samples_path_test)
#samples_train = np.asarray([preprocess_image_1(image.astype('float64')) for image in image_list_train])
#samples_test = np.asarray([preprocess_image_1(image.astype('float64')) for image in image_list_test])
samples_train = np.asarray(image_list_train)
samples_test = np.asarray(image_list_test)
probabilities_train = model_prediction(sess, x, preds, samples_train, feed=feed_dict)
probabilities_test = model_prediction(sess, x, preds, samples_test, feed=feed_dict)
for i in range(0, samples_train.shape[0]):
if predicted_labels_train[i]==np.argmax(probabilities_train[i]):
pure_train =samples_path+'/train/'+image_files_train[i]
#imsave(pure_train, image_list_train[i])
np.save(pure_train, image_list_train[i])
for i in range(0, samples_test.shape[0]):
if predicted_labels_test[i]==np.argmax(probabilities_test[i]):
pure_test =samples_path+'/test/'+image_files_test[i]
#imsave(pure_test, image_list_test[i])
np.save(pure_test, image_list_test[i])
def main(argv=None):
datasets='cifar10'
attacks=['cw']
model_names=['resnet101']
for attack in attacks:
for model_name in model_names:
pure(datasets=datasets, attack=attack, model_name=model_name)
#choose_test(datasets = FLAGS.datasets,
# attack=FLAGS.attack,
# model_name=FLAGS.model_name)
if __name__ == '__main__':
flags.DEFINE_string('datasets', 'cifar10', 'The target datasets.')
flags.DEFINE_string('attack', 'cw', 'attack_method')#'../mt_result/mnist_jsma/adv_jsma'
flags.DEFINE_string('model_name', 'resnet101', 'model_name')
tf.app.run()
|
shimmeringbee/zda | persistence.go | package zda
import (
"encoding/json"
"fmt"
"github.com/shimmeringbee/da"
"github.com/shimmeringbee/da/capabilities"
"github.com/shimmeringbee/zigbee"
"sort"
)
type State struct {
Nodes map[zigbee.IEEEAddress]StateNode
}
type StateNode struct {
Devices map[uint8]StateDevice
Endpoints []zigbee.EndpointDescription
Description zigbee.NodeDescription
SupportsAPSAck bool
}
type StateDevice struct {
DeviceID uint16
DeviceVersion uint8
Endpoints []zigbee.Endpoint
Capabilities []da.Capability
CapabilityData map[string]interface{}
}
func internalDeviceToCapabilityDevice(iDev *internalDevice) Device {
endpoints := map[zigbee.Endpoint]zigbee.EndpointDescription{}
for _, endpoint := range iDev.endpoints {
endpoints[endpoint] = iDev.node.endpointDescriptions[endpoint]
}
return Device{
Identifier: IEEEAddressWithSubIdentifier{
IEEEAddress: iDev.node.ieeeAddress,
SubIdentifier: iDev.subidentifier,
},
Capabilities: iDev.capabilities,
Endpoints: endpoints,
}
}
func (z *ZigbeeGateway) SaveState() State {
state := State{
Nodes: map[zigbee.IEEEAddress]StateNode{},
}
for _, iNode := range z.nodeTable.getNodes() {
iNode.mutex.RLock()
endpointDescriptions := make([]zigbee.EndpointDescription, 0)
for _, endpointDescription := range iNode.endpointDescriptions {
endpointDescriptions = append(endpointDescriptions, endpointDescription)
}
sort.Slice(endpointDescriptions, func(i, j int) bool {
return endpointDescriptions[i].Endpoint < endpointDescriptions[j].Endpoint
})
stateDevices := map[uint8]StateDevice{}
for subId, iDev := range iNode.devices {
iDev.mutex.RLock()
capabilityData := map[string]interface{}{}
for _, capability := range iDev.capabilities {
persistingCapability, ok := z.CapabilityManager.Get(capability).(PersistableCapability)
if ok {
data, err := persistingCapability.Save(internalDeviceToCapabilityDevice(iDev))
if err == nil {
capabilityData[persistingCapability.Name()] = data
}
}
}
sDevice := StateDevice{
DeviceID: iDev.deviceID,
DeviceVersion: iDev.deviceVersion,
Endpoints: iDev.endpoints,
Capabilities: iDev.capabilities,
CapabilityData: capabilityData,
}
stateDevices[subId] = sDevice
iDev.mutex.RUnlock()
}
sNode := StateNode{
Devices: stateDevices,
Endpoints: endpointDescriptions,
SupportsAPSAck: iNode.supportsAPSAck,
Description: iNode.nodeDesc,
}
state.Nodes[iNode.ieeeAddress] = sNode
iNode.mutex.RUnlock()
}
return state
}
func (z *ZigbeeGateway) LoadState(state State) error {
keyToCapability := z.CapabilityManager.PersistingCapabilities()
for ieee, stateNode := range state.Nodes {
iNode, _ := z.nodeTable.createNode(ieee)
iNode.mutex.Lock()
for _, ed := range stateNode.Endpoints {
iNode.endpointDescriptions[ed.Endpoint] = ed
iNode.endpoints = append(iNode.endpoints, ed.Endpoint)
}
iNode.nodeDesc = stateNode.Description
iNode.supportsAPSAck = stateNode.SupportsAPSAck
iNode.mutex.Unlock()
for subId, stateDev := range stateNode.Devices {
iDev, _ := z.nodeTable.createDevice(IEEEAddressWithSubIdentifier{IEEEAddress: iNode.ieeeAddress, SubIdentifier: subId})
iDev.mutex.Lock()
iDev.deviceID = stateDev.DeviceID
iDev.deviceVersion = stateDev.DeviceVersion
iDev.endpoints = stateDev.Endpoints
iDev.capabilities = stateDev.Capabilities
if !isCapabilityInSlice(iDev.capabilities, capabilities.EnumerateDeviceFlag) {
iDev.capabilities = append(iDev.capabilities, capabilities.EnumerateDeviceFlag)
}
if !isCapabilityInSlice(iDev.capabilities, capabilities.DeviceRemovalFlag) {
iDev.capabilities = append(iDev.capabilities, capabilities.DeviceRemovalFlag)
}
iDev.mutex.Unlock()
for key, data := range stateDev.CapabilityData {
capability, found := keyToCapability[key]
if found {
if err := capability.Load(internalDeviceToCapabilityDevice(iDev), data); err != nil {
return fmt.Errorf("failed to load data for %s: %w", iDev.generateIdentifier(), err)
}
} else {
return fmt.Errorf("failed to load data for %s: state has unknown capability data", iDev.generateIdentifier())
}
}
z.sendEvent(da.DeviceLoaded{Device: iDev.toDevice(z)})
}
}
return nil
}
func JSONMarshalState(state State) ([]byte, error) {
return json.Marshal(state)
}
func JSONUnmarshalState(z *ZigbeeGateway, data []byte) (State, error) {
state := &State{}
if err := json.Unmarshal(data, state); err != nil {
return *state, fmt.Errorf("failed to unmarshal state, stage 1: %w", err)
}
keyToCapability := z.CapabilityManager.PersistingCapabilities()
for _, node := range state.Nodes {
for _, device := range node.Devices {
for key, anonymousData := range device.CapabilityData {
capability, found := keyToCapability[key]
if !found {
return *state, fmt.Errorf("failed to find capability to unmarshal: %s", key)
}
data, err := json.Marshal(anonymousData)
if err != nil {
return *state, fmt.Errorf("failed to find remarshal capability data for key %s: %w", key, err)
}
capabilityState := capability.DataStruct()
if err := json.Unmarshal(data, capabilityState); err != nil {
return *state, fmt.Errorf("failed to find unmarshal capability data into data struct for key %s: %w", key, err)
}
device.CapabilityData[key] = capabilityState
}
}
}
return *state, nil
}
|
customweb/sass-compiler | src/test/java/com/customweb/sass/testcases/scss/AutomaticSassTestsBroken.java | <filename>src/test/java/com/customweb/sass/testcases/scss/AutomaticSassTestsBroken.java
/*
* Copyright 2000-2014 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.customweb.sass.testcases.scss;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import org.junit.Assert;
import org.junit.runner.RunWith;
import org.w3c.css.sac.CSSException;
import com.customweb.sass.testcases.scss.SassTestRunner.TestFactory;
@RunWith(SassTestRunner.class)
public class AutomaticSassTestsBroken extends AbstractDirectoryScanningSassTests {
@Override
protected URL getResourceURL(String path) {
return getResourceURLInternal(path);
}
private static URL getResourceURLInternal(String path) {
return AutomaticSassTestsBroken.class.getResource("/automaticbroken"
+ path);
}
@TestFactory
public static Collection<String> getScssResourceNames()
throws URISyntaxException, IOException {
URL directoryUrl = getResourceURLInternal("");
if (directoryUrl != null) {
return getScssResourceNames(directoryUrl);
} else {
return Collections.emptyList();
}
}
@Override
public void compareScssWithCss(String scssResourceName) throws Exception {
boolean success = false;
try {
super.compareScssWithCss(scssResourceName);
success = true;
} catch (CSSException e) {
// this is an expected outcome
} catch (AssertionError e) {
// this is an expected outcome
}
if (success) {
Assert.fail("Test "
+ scssResourceName
+ " from automaticbroken that was expected to fail has been fixed. Please move the corresponding CSS and SCSS files to automatic.");
}
}
}
|
zhangkn/iOS14Header | System/Library/PrivateFrameworks/TextToSpeech.framework/Frameworks/TextToSpeechBundleSupport.framework/TTSRegexHelper.h | /*
* This header is generated by classdump-dyld 1.0
* on Sunday, September 27, 2020 at 11:52:02 AM Mountain Standard Time
* Operating System: Version 14.0 (Build 18A373)
* Image Source: /System/Library/PrivateFrameworks/TextToSpeech.framework/Frameworks/TextToSpeechBundleSupport.framework/TextToSpeechBundleSupport
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
@protocol OS_dispatch_queue;
#import <TextToSpeechBundleSupport/TextToSpeechBundleSupport-Structs.h>
@class NSMutableArray, NSMutableSet, NSObject, NSMutableDictionary, NSRegularExpression;
@interface TTSRegexHelper : NSObject {
vector<boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >, std::__1::allocator<boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > > > >* _boostRegexes;
NSMutableArray* _nsRegexes;
NSMutableSet* _duplicateChecker;
NSObject*<OS_dispatch_queue> _ttsRegexQueue;
NSMutableDictionary* _nsRules;
NSMutableDictionary* _boostRules;
NSRegularExpression* _escapeStripper;
int _regexStyle;
}
@property (assign,nonatomic) int regexStyle; //@synthesize regexStyle=_regexStyle - In the implementation block
+(id)sharedInstance;
-(id)init;
-(void)setRegexStyle:(int)arg1 ;
-(void)_addRules:(id)arg1 ;
-(int)regexStyle;
-(void)_addNSRule:(id)arg1 ruleApplication:(id)arg2 caseInsensitive:(BOOL)arg3 ;
-(id)_boostApplyRulesForText:(id)arg1 rangeAdjustments:(id)arg2 ;
-(id)_nsApplyRulesForText:(id)arg1 rangeAdjustments:(id)arg2 ;
-(id)_calculatedUTF8Offsets:(id)arg1 ;
-(id)_boostApplyMatches:(id)arg1 rangeAdjustments:(id)arg2 text:(id)arg3 logging:(id)arg4 ;
-(id)_processReplacementStringForSpecialCharacters:(id)arg1 ;
-(void)addRules:(id)arg1 ;
-(id)applyRulesForText:(id)arg1 rangeAdjustments:(id)arg2 ;
-(id)regexRules;
-(id)boostRules;
-(BOOL)hasStoredRules;
-(void)resetStoredRules;
@end
|
YarosJ/prestige-of-districts | tests/graphQL/task/schemas.js | import { gql } from 'apollo-server-express';
export default {
GET_TAGS: gql`
query {
tags
}
`,
ADD_TARGET: gql`
mutation($URL: String!, $tagPaths: [String], $freq: Int, $city: String, $country: String) {
addTarget(URL: $URL, tagPaths: $tagPaths, freq: $freq, city: $city, country: $country) {
URL
freq
}
}
`,
UPDATE_TARGET: gql`
mutation($URL: String!, $tagPaths: [String], $freq: Int, $city: String, $country: String) {
updateTarget(URL: $URL, tagPaths: $tagPaths, freq: $freq, city: $city, country: $country) {
URL
tagPaths
freq
city
country
}
}
`,
REMOVE_TARGET: gql`
mutation($URL: String!) {
removeTarget(URL: $URL) {
URL
}
}
`,
}; |
charitha306/twister2 | twister2/resource-scheduler/src/java/edu/iu/dsc/tws/rsched/schedulers/k8s/mpi/MPIWorkerStarter.java | // 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.
package edu.iu.dsc.tws.rsched.schedulers.k8s.mpi;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import edu.iu.dsc.tws.common.config.Config;
import edu.iu.dsc.tws.common.logging.LoggingHelper;
import edu.iu.dsc.tws.common.resource.NodeInfoUtils;
import edu.iu.dsc.tws.common.resource.WorkerInfoUtils;
import edu.iu.dsc.tws.common.util.ReflectionUtils;
import edu.iu.dsc.tws.common.worker.IPersistentVolume;
import edu.iu.dsc.tws.common.worker.IWorker;
import edu.iu.dsc.tws.master.JobMasterContext;
import edu.iu.dsc.tws.master.worker.JMWorkerAgent;
import edu.iu.dsc.tws.proto.jobmaster.JobMasterAPI;
import edu.iu.dsc.tws.proto.system.job.JobAPI;
import edu.iu.dsc.tws.rsched.core.SchedulerContext;
import edu.iu.dsc.tws.rsched.schedulers.k8s.KubernetesConstants;
import edu.iu.dsc.tws.rsched.schedulers.k8s.KubernetesContext;
import edu.iu.dsc.tws.rsched.schedulers.k8s.PodWatchUtils;
import edu.iu.dsc.tws.rsched.schedulers.k8s.worker.K8sPersistentVolume;
import edu.iu.dsc.tws.rsched.schedulers.k8s.worker.K8sVolatileVolume;
import edu.iu.dsc.tws.rsched.schedulers.k8s.worker.K8sWorkerUtils;
import edu.iu.dsc.tws.rsched.utils.JobUtils;
import mpi.MPI;
import mpi.MPIException;
import static edu.iu.dsc.tws.common.config.Context.JOB_ARCHIVE_DIRECTORY;
import static edu.iu.dsc.tws.rsched.schedulers.k8s.KubernetesConstants.KUBERNETES_CLUSTER_TYPE;
import static edu.iu.dsc.tws.rsched.schedulers.k8s.KubernetesConstants.POD_MEMORY_VOLUME;
public final class MPIWorkerStarter {
private static final Logger LOG = Logger.getLogger(MPIWorkerStarter.class.getName());
private static Config config = null;
private static int workerID = -1; // -1 means, not initialized
private static int numberOfWorkers = -1; // -1 means, not initialized
private static JobMasterAPI.WorkerInfo workerInfo;
private static JMWorkerAgent jobMasterAgent;
private static String jobName = null;
private static JobAPI.Job job = null;
private static JobAPI.ComputeResource computeResource = null;
private MPIWorkerStarter() { }
public static void main(String[] args) {
// we can not initialize the logger fully yet,
// but we need to set the format as the first thing
LoggingHelper.setLoggingFormat(LoggingHelper.DEFAULT_FORMAT);
String jobMasterIP = MPIMasterStarter.getJobMasterIPCommandLineArgumentValue(args[0]);
jobName = args[1];
String encodedNodeInfoList = args[2];
if (jobMasterIP == null) {
throw new RuntimeException("JobMasterIP address is null");
}
if (jobName == null) {
throw new RuntimeException("jobName is null");
}
// remove the first and the last single quotas from encodedNodeInfoList
encodedNodeInfoList = encodedNodeInfoList.replaceAll("'", "");
// load the configuration parameters from configuration directory
String configDir = POD_MEMORY_VOLUME + "/" + JOB_ARCHIVE_DIRECTORY + "/"
+ KUBERNETES_CLUSTER_TYPE;
config = K8sWorkerUtils.loadConfig(configDir);
// initialize MPI
try {
MPI.Init(args);
workerID = MPI.COMM_WORLD.getRank();
numberOfWorkers = MPI.COMM_WORLD.getSize();
} catch (MPIException e) {
LOG.log(Level.SEVERE, "Could not get rank or size from MPI.COMM_WORLD", e);
throw new RuntimeException(e);
}
// initialize persistent volume
K8sPersistentVolume pv = null;
if (KubernetesContext.persistentVolumeRequested(config)) {
// create persistent volume object
String persistentJobDir = KubernetesConstants.PERSISTENT_VOLUME_MOUNT;
pv = new K8sPersistentVolume(persistentJobDir, workerID);
}
// initialize persistent logging
K8sWorkerUtils.initWorkerLogger(workerID, pv, config);
// read job description file
String jobDescFileName = SchedulerContext.createJobDescriptionFileName(jobName);
jobDescFileName = POD_MEMORY_VOLUME + "/" + JOB_ARCHIVE_DIRECTORY + "/" + jobDescFileName;
job = JobUtils.readJobFile(null, jobDescFileName);
LOG.info("Job description file is loaded: " + jobDescFileName);
// add any configuration from job file to the config object
// if there are the same config parameters in both,
// job file configurations will override
config = JobUtils.overrideConfigs(job, config);
config = JobUtils.updateConfigs(job, config);
config = K8sWorkerUtils.unsetWorkerIDAssigment(config);
InetAddress localHost = null;
String podName = null;
try {
localHost = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
LOG.log(Level.SEVERE, "Cannot get localHost.", e);
}
String podIP = localHost.getHostAddress();
podName = localHost.getHostName();
int workerPort = KubernetesContext.workerBasePort(config)
+ workerID * (SchedulerContext.numberOfAdditionalPorts(config) + 1);
String nodeIP = PodWatchUtils.getNodeIP(KubernetesContext.namespace(config), jobName, podIP);
JobMasterAPI.NodeInfo nodeInfo = null;
if (nodeIP == null) {
LOG.warning("Could not get nodeIP for this pod. Using podIP as nodeIP.");
nodeInfo = NodeInfoUtils.createNodeInfo(podIP, null, null);
} else {
nodeInfo = KubernetesContext.nodeLocationsFromConfig(config)
? KubernetesContext.getNodeInfo(config, nodeIP)
: K8sWorkerUtils.getNodeInfoFromEncodedStr(encodedNodeInfoList, nodeIP);
}
LOG.info("NodeInfoUtils for this worker: " + nodeInfo);
computeResource = K8sWorkerUtils.getComputeResource(job, podName);
// generate additional ports if requested
Map<String, Integer> additionalPorts =
K8sWorkerUtils.generateAdditionalPorts(config, workerPort);
workerInfo = WorkerInfoUtils.createWorkerInfo(
workerID, podIP, workerPort, nodeInfo, computeResource, additionalPorts);
LOG.info("Worker information summary: \n"
+ "MPI Rank(workerID): " + workerID + "\n"
+ "MPI Size(number of workers): " + numberOfWorkers + "\n"
+ "POD_IP: " + podIP + "\n"
+ "HOSTNAME(podname): " + podName
);
// construct JMWorkerAgent
jobMasterAgent = JMWorkerAgent.createJMWorkerAgent(config, workerInfo, jobMasterIP,
JobMasterContext.jobMasterPort(config), job.getNumberOfWorkers());
// start JMWorkerAgent
jobMasterAgent.startThreaded();
// we will be running the Worker, send running message
jobMasterAgent.sendWorkerRunningMessage();
// start the worker
startWorker(jobMasterAgent, pv, podName);
// finalize MPI
try {
MPI.Finalize();
} catch (MPIException ignore) { }
// close the worker
closeWorker();
}
/**
* start the Worker class specified in conf files
*/
public static void startWorker(JMWorkerAgent jmWorkerAgent,
IPersistentVolume pv, String podName) {
String workerClass = SchedulerContext.workerClass(config);
IWorker worker;
try {
Object object = ReflectionUtils.newInstance(workerClass);
worker = (IWorker) object;
LOG.info("loaded worker class: " + workerClass);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
LOG.severe(String.format("failed to load the worker class %s", workerClass));
throw new RuntimeException(e);
}
K8sVolatileVolume volatileVolume = null;
if (computeResource.getDiskGigaBytes() > 0) {
volatileVolume = new K8sVolatileVolume(jobName, workerID);
}
worker.execute(config, workerID, jmWorkerAgent.getJMWorkerController(), pv, volatileVolume);
}
/**
* last method to call to close the worker
*/
public static void closeWorker() {
// send worker completed message to the Job Master and finish
// Job master will delete the StatefulSet object
jobMasterAgent.sendWorkerCompletedMessage();
jobMasterAgent.close();
}
}
|
Maxul/sgx_vmx_protocol | Sandbox/qemu-sgx-master/qapi/qapi-clone-visitor.c | <filename>Sandbox/qemu-sgx-master/qapi/qapi-clone-visitor.c<gh_stars>1-10
/*
* Copy one QAPI object to another
*
* Copyright (C) 2016 Red Hat, Inc.
*
* This work is licensed under the terms of the GNU GPL, version 2 or later.
* See the COPYING file in the top-level directory.
*
*/
#include "qemu/osdep.h"
#include "qapi/clone-visitor.h"
#include "qapi/visitor-impl.h"
#include "qapi/error.h"
struct QapiCloneVisitor {
Visitor visitor;
size_t depth;
};
static QapiCloneVisitor *to_qcv(Visitor *v)
{
return container_of(v, QapiCloneVisitor, visitor);
}
static void qapi_clone_start_struct(Visitor *v, const char *name, void **obj,
size_t size, Error **errp)
{
QapiCloneVisitor *qcv = to_qcv(v);
if (!obj) {
assert(qcv->depth);
/* Only possible when visiting an alternate's object
* branch. Nothing further to do here, since the earlier
* visit_start_alternate() already copied memory. */
return;
}
*obj = g_memdup(*obj, size);
qcv->depth++;
}
static void qapi_clone_end(Visitor *v, void **obj)
{
QapiCloneVisitor *qcv = to_qcv(v);
assert(qcv->depth);
if (obj) {
qcv->depth--;
}
}
static void qapi_clone_start_list(Visitor *v, const char *name,
GenericList **listp, size_t size,
Error **errp)
{
qapi_clone_start_struct(v, name, (void **)listp, size, errp);
}
static GenericList *qapi_clone_next_list(Visitor *v, GenericList *tail,
size_t size)
{
QapiCloneVisitor *qcv = to_qcv(v);
assert(qcv->depth);
/* Unshare the tail of the list cloned by g_memdup() */
tail->next = g_memdup(tail->next, size);
return tail->next;
}
static void qapi_clone_start_alternate(Visitor *v, const char *name,
GenericAlternate **obj, size_t size,
bool promote_int, Error **errp)
{
qapi_clone_start_struct(v, name, (void **)obj, size, errp);
}
static void qapi_clone_type_int64(Visitor *v, const char *name, int64_t *obj,
Error **errp)
{
QapiCloneVisitor *qcv = to_qcv(v);
assert(qcv->depth);
/* Value was already cloned by g_memdup() */
}
static void qapi_clone_type_uint64(Visitor *v, const char *name,
uint64_t *obj, Error **errp)
{
QapiCloneVisitor *qcv = to_qcv(v);
assert(qcv->depth);
/* Value was already cloned by g_memdup() */
}
static void qapi_clone_type_bool(Visitor *v, const char *name, bool *obj,
Error **errp)
{
QapiCloneVisitor *qcv = to_qcv(v);
assert(qcv->depth);
/* Value was already cloned by g_memdup() */
}
static void qapi_clone_type_str(Visitor *v, const char *name, char **obj,
Error **errp)
{
QapiCloneVisitor *qcv = to_qcv(v);
assert(qcv->depth);
/*
* Pointer was already cloned by g_memdup; create fresh copy.
* Note that as long as qobject-output-visitor accepts NULL instead of
* "", then we must do likewise. However, we want to obey the
* input visitor semantics of never producing NULL when the empty
* string is intended.
*/
*obj = g_strdup(*obj ?: "");
}
static void qapi_clone_type_number(Visitor *v, const char *name, double *obj,
Error **errp)
{
QapiCloneVisitor *qcv = to_qcv(v);
assert(qcv->depth);
/* Value was already cloned by g_memdup() */
}
static void qapi_clone_type_null(Visitor *v, const char *name, Error **errp)
{
QapiCloneVisitor *qcv = to_qcv(v);
assert(qcv->depth);
/* Nothing to do */
}
static void qapi_clone_free(Visitor *v)
{
g_free(v);
}
static Visitor *qapi_clone_visitor_new(void)
{
QapiCloneVisitor *v;
v = g_malloc0(sizeof(*v));
v->visitor.type = VISITOR_CLONE;
v->visitor.start_struct = qapi_clone_start_struct;
v->visitor.end_struct = qapi_clone_end;
v->visitor.start_list = qapi_clone_start_list;
v->visitor.next_list = qapi_clone_next_list;
v->visitor.end_list = qapi_clone_end;
v->visitor.start_alternate = qapi_clone_start_alternate;
v->visitor.end_alternate = qapi_clone_end;
v->visitor.type_int64 = qapi_clone_type_int64;
v->visitor.type_uint64 = qapi_clone_type_uint64;
v->visitor.type_bool = qapi_clone_type_bool;
v->visitor.type_str = qapi_clone_type_str;
v->visitor.type_number = qapi_clone_type_number;
v->visitor.type_null = qapi_clone_type_null;
v->visitor.free = qapi_clone_free;
return &v->visitor;
}
void *qapi_clone(const void *src, void (*visit_type)(Visitor *, const char *,
void **, Error **))
{
Visitor *v;
void *dst = (void *) src; /* Cast away const */
if (!src) {
return NULL;
}
v = qapi_clone_visitor_new();
visit_type(v, NULL, &dst, &error_abort);
visit_free(v);
return dst;
}
|
alchemz/mission-peace | [Tree]307. Range Sum Query - Mutable.cpp | class NumArray {
public:
NumArray(vector<int> &nums) {
num.resize(nums.size() + 1);
bit.resize(nums.size() + 1);
for (int i = 0; i < nums.size(); ++i) {
update(i, nums[i]);
}
}
void update(int i, int val) {
int diff = val - num[i + 1];
for (int j = i + 1; j < num.size(); j += (j&-j)) {
bit[j] += diff;
}
num[i + 1] = val;
}
int sumRange(int i, int j) {
return getSum(j + 1) - getSum(i);
}
int getSum(int i) {
int res = 0;
for (int j = i; j > 0; j -= (j&-j)) {
res += bit[j];
}
return res;
}
private:
vector<int> num;
vector<int> bit;
};
// http://www.cnblogs.com/grandyang/p/4985506.html
// https://leetcode.com/problems/range-sum-query-mutable/description/ |
arnoSCC/allmark | services/converter/markdowntohtml/preprocessor/imagegallery.go | <filename>services/converter/markdowntohtml/preprocessor/imagegallery.go
// Copyright 2014 <NAME>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package preprocessor
import (
"github.com/arnoSCC/allmark/common/paths"
"github.com/arnoSCC/allmark/common/route"
"github.com/arnoSCC/allmark/model"
"github.com/arnoSCC/allmark/services/converter/markdowntohtml/imageprovider"
"fmt"
"regexp"
"strings"
)
var (
// imagegallery: [*description text*](*folder path*)
imageGalleryExtensionPattern = regexp.MustCompile(`imagegallery: \[([^\]]*)\]\(([^)]+)\)`)
)
func newImageGalleryExtension(pathProvider paths.Pather, baseRoute route.Route, files []*model.File, imageProvider *imageprovider.ImageProvider) *imageGalleryExtension {
return &imageGalleryExtension{
pathProvider: pathProvider,
base: baseRoute,
files: files,
imageProvider: imageProvider,
}
}
type imageGalleryExtension struct {
pathProvider paths.Pather
base route.Route
files []*model.File
imageProvider *imageprovider.ImageProvider
}
func (converter *imageGalleryExtension) Convert(markdown string) (convertedContent string, converterError error) {
convertedContent = markdown
for _, match := range imageGalleryExtensionPattern.FindAllStringSubmatch(convertedContent, -1) {
if len(match) != 3 {
continue
}
// parameters
originalText := strings.TrimSpace(match[0])
title := strings.TrimSpace(match[1])
path := strings.TrimSpace(match[2])
// get the code
renderedCode := converter.getGalleryCode(title, path)
// replace markdown
convertedContent = strings.Replace(convertedContent, originalText, renderedCode, 1)
}
return convertedContent, nil
}
func (converter *imageGalleryExtension) getGalleryCode(galleryTitle, path string) string {
imageLinks := converter.getImageLinksByPath(path)
var code string
if galleryTitle != "" {
code += fmt.Sprintf("**%s**\n\n", galleryTitle)
}
code += strings.Join(imageLinks, "\n")
return code
}
func (converter *imageGalleryExtension) getImageLinksByPath(path string) []string {
baseRoute := converter.base
galleryRoute := route.NewFromRequest(path)
fullGalleryRoute := route.Combine(baseRoute, galleryRoute)
numberOfFiles := len(converter.files)
imagelinks := make([]string, 0, numberOfFiles)
for _, file := range converter.files {
// skip files which are not a child of the supplied path
if !file.Route().IsChildOf(fullGalleryRoute) {
continue
}
// skip files which are not images
if !model.IsImageFile(file) {
continue
}
// image title
imageTitle := file.Route().LastComponentName() // use the file name for the title
// calculate the image code
imagePath := converter.imageProvider.GetImagePath(converter.pathProvider, file.Route())
imageCode := fmt.Sprintf(`<img %s alt="%s"/>`, imagePath, imageTitle)
// link the image to the original
fullSizeImagePath := converter.pathProvider.Path(file.Route().Value())
imageWithLink := fmt.Sprintf(`<a href="%s" title="%s">%s</a>`, fullSizeImagePath, imageTitle, imageCode)
imagelinks = append(imagelinks, imageWithLink)
}
return imagelinks
}
|
ivelin1936/Studing-SoftUni- | Programing Basic/Programming Basics - Exams/ProgrammingBasicsExam-19March2017-Evening/src/com/company/bills.java | package com.company;
import java.util.Scanner;
public class bills {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int months = Integer.parseInt(scanner.nextLine());
double electric = 0.00;
double water = 0.00;
double internet = 0.00;
double other = 0.00;
for (int i = 1; i <= months ; i++) {
double el = Double.parseDouble(scanner.nextLine());
electric += el;
water += 20;
internet += 15;
other += (el + 35) + (el + 35) * 0.2;
}
double avarage = (electric + water + internet + other) / months;
System.out.printf("Electricity: %.2f lv%n", electric);
System.out.printf("Water: %.2f lv%n", water);
System.out.printf("Internet: %.2f lv%n", internet);
System.out.printf("Other: %.2f lv%n", other);
System.out.printf("Average: %.2f lv%n", avarage);
}
}
|
StepanMelnik/Java8Patterns | src/test/java/com/sme/java8/patterns/design/creational/builder/MapBuilderTest.java | <reponame>StepanMelnik/Java8Patterns
package com.sme.java8.patterns.design.creational.builder;
import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
/**
* Unit tests of {@link MapBuilder}.
*/
public class MapBuilderTest
{
@Test
public void testMapBuilder() throws Exception
{
Map<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
Map<Integer, String> map1 = new MapBuilder<Integer, String>(false)
.put(1, "One")
.put(2, "Two")
.put(3, "Three")
.build();
assertEquals(map, map1);
}
}
|
banli17/blog | 60-function-programming/14-lodash-fp.js | const fp = require('lodash/fp')
// fp 会返回 curry 后的函数,参数:数据置后
const f = fp.flowRight(fp.join('_'), fp.map(fp.toLower), fp.split(' '))
// 需求: HELLO WORLD -> hello-world
console.log(f(['HELLO WORLD']))
|
omegabyte/gaboom | gaboom/src/main/java/org/omegabyte/gaboom/transforms/model/ModelGenerational.java | <reponame>omegabyte/gaboom
package org.omegabyte.gaboom.transforms.model;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.omegabyte.gaboom.Individuals;
import org.omegabyte.gaboom.transforms.Crossover;
import org.omegabyte.gaboom.transforms.Mutate;
import org.omegabyte.gaboom.transforms.Select;
import java.io.Serializable;
public class ModelGenerational<GenomeT extends Serializable> extends ModelTransform<GenomeT> {
private final Select.SelectFn<GenomeT> selectFn;
private final Crossover.CrossoverTransform<GenomeT> crossoverTransform;
private final Mutate.MutateTransform<GenomeT> mutateTransform;
public ModelGenerational(Select.SelectFn<GenomeT> selectFn, Crossover.CrossoverTransform<GenomeT> crossoverTransform, Mutate.MutateTransform<GenomeT> mutateTransform) {
this.selectFn = selectFn;
this.crossoverTransform = crossoverTransform;
this.mutateTransform = mutateTransform;
}
@Override
public PCollection<KV<String, Individuals<GenomeT>>> expand(PCollection<KV<String, Individuals<GenomeT>>> input) {
return input.apply(ParDo.of(new IndividualsToSelectorFn<>()))
.apply(GenerateOffspringsTransform.of(selectFn, crossoverTransform, mutateTransform));
}
}
|
chenyuhan1/Learning_record | Interview/js/offer.js | <gh_stars>0
function offer() {
}
console.log(parseInt(1101, 2)) |
Communitarian-Network/communitarian-discourse-plugin | lib/communitarian/engine.rb | # frozen_string_literal: true
module Communitarian
class Engine < ::Rails::Engine
engine_name "Communitarian".freeze
isolate_namespace Communitarian
config.after_initialize do
Discourse::Application.routes.append do
mount ::Communitarian::Engine, at: "/communitarian"
end
end
end
end
|
raffaelecarelle/platform-1 | src/Oro/Bundle/FormBundle/Resources/public/js/app/views/form-loading-view.js | <filename>src/Oro/Bundle/FormBundle/Resources/public/js/app/views/form-loading-view.js
define(function(require) {
'use strict';
const BaseView = require('oroui/js/app/views/base/view');
const FormSectionLoadingView = require('oroform/js/app/views/form-section-loading-view');
const $ = require('jquery');
const _ = require('underscore');
const mediator = require('oroui/js/mediator');
const FormLoadingView = BaseView.extend({
autoRender: true,
/**
* @inheritdoc
*/
constructor: function FormLoadingView(options) {
FormLoadingView.__super__.constructor.call(this, options);
},
/**
* @inheritdoc
*/
initialize: function(options) {
const self = this;
// TODO: uncomment when scrol to section will be fixed
// var index = this.$(window.location.hash).parents('.responsive-section').index();
//
// index = index !== -1 ? index : 0;
const index = 0;
this.$('.responsive-section').not(':nth-child(' + (index + 1) + ')').each(function(index, el) {
self.subview('form-section-loading-' + index, new FormSectionLoadingView({
el: $(el)
}));
});
FormLoadingView.__super__.initialize.call(this, options);
},
render: function() {
FormLoadingView.__super__.render.call(this);
this.$el.removeAttr('data-skip-input-widgets');
this.$el.addClass('lazy-loading');
this.initLayout()
.then(function() {
const $buttons = this._getNavButtons();
$buttons.addClass('disabled');
this._loadSubviews().then(this._afterLoadSubviews.bind(this, $buttons));
}.bind(this));
return this;
},
_afterLoadSubviews: function($buttons) {
$buttons.removeClass('disabled');
mediator.trigger('page:afterPagePartChange');
this.$el.removeClass('lazy-loading');
},
_loadSubviews: function() {
const promises = _.map(this.subviews, function(view) {
return view.startLoading();
});
return $.when(...promises);
},
_getNavButtons: function() {
return this.$('.title-buttons-container').find(':button, [role="button"]');
}
});
return FormLoadingView;
});
|
otienodominic/kemunto | react-ui/src/Components/Posts/ShowPost/ShowPost.js | import Axios from 'axios'
import React, { useState, useEffect } from 'react'
import { useHistory } from 'react-router-dom';
import { Link } from 'react-router-dom'
import ToText from '../../../utils/ToText'
import './ShowPost.css'
import avtar from '../../../assets/avtar.jpg'
import Spinner from '../../../Containers/Spinner/Spinner';
function ShowPost(props) {
const [post, setpost] = useState(props)
const [loading, setLoading] = useState(false)
const [errmsg, setErrorMsg] = useState()
const [errcode, setErrorCode] = useState()
const history = useHistory()
const pathname = history.location.pathname
useEffect(() => {
setLoading(true)
Axios.get("/profile/bycreator/" + props.creator).then(data => {
setLoading(false)
setpost({ ...props, user: data.data.profile })
})
.catch(e => {
setLoading(false)
})
}, [props])
return (<>
{errcode ?
<div className="container error container-short">
<div className="mar-20">
<h5>Error Code - {errcode}</h5>
<h4>Error Message - {errmsg}</h4>
</div>
</div>
: null}
{loading ?
<div className="container loading">
<div className="mar-20">
<Spinner />
</div>
</div>
: null}
<div className="col-md-6 col-sm-6 col-xs-12 showblog mb-3">
<div className="showblog_card card">
<div className="showblog_card_image"
style={{ backgroundImage: `url(${props.imagePath})` }}>
<div className="show_auth_img">
<Link to={"/public/" + post.user?.username} style={{ backgroundImage: `url(${post.user?.imagePath ? post.user.imagePath : avtar})` }}>By Mehul</Link>
</div>
</div>
<div className="card-body">
<h5 className="card-title pt-3">
{pathname === "/mypost" ?
<Link
to={'/mypost/' + props._id}
className="title">
{props.title}
</Link> :
<Link
to={'/post/' + props._id}
className="title">
{props.title}
</Link>
}
</h5>
<p className="showblog_content">
{`${ToText(
props.content.substring(0, 80)
)}...`}<span> <b>Read More</b></span>
</p>
</div>
</div>
</div>
</>
)
}
export default ShowPost
|
alexsmn/opcuapp | opcuapp/string.h | <reponame>alexsmn/opcuapp
#pragma once
#include <opcuapp/helpers.h>
#include <opcuapp/status_code.h>
#include <algorithm>
inline bool operator<(const OpcUa_String& a, const OpcUa_String& b) {
return std::strcmp(OpcUa_String_GetRawString(&a),
OpcUa_String_GetRawString(&b)) < 0;
}
namespace opcua {
OPCUA_DEFINE_METHODS(String);
inline void Copy(const OpcUa_String& source, OpcUa_String& target) {
Initialize(target);
if (!OpcUa_String_IsNull(&source))
Check(
::OpcUa_String_AttachCopy(&target, OpcUa_String_GetRawString(&source)));
}
class String {
public:
String() { Initialize(value_); }
String(const char* str) {
Initialize(value_);
if (str)
Check(::OpcUa_String_AttachCopy(&value_,
const_cast<const OpcUa_StringA>(str)));
}
String(const OpcUa_StringA str) {
Initialize(value_);
if (str)
Check(::OpcUa_String_AttachCopy(&value_, str));
}
String(const OpcUa_String& source) { Copy(source, value_); }
String(OpcUa_String&& source) {
value_ = source;
Initialize(source);
}
String(const String& source) { Copy(source.value_, value_); }
String(String&& source) {
value_ = source.value_;
Initialize(source.value_);
}
~String() { Clear(); }
void Clear() {
if (!is_null())
opcua::Clear(value_);
}
const OpcUa_StringA raw_string() const {
return OpcUa_String_GetRawString(&value_);
}
OpcUa_String* pass() const { return const_cast<OpcUa_String*>(&value_); }
void release(OpcUa_String& value) {
value = value_;
Initialize(value_);
}
String& operator=(const String& source) {
if (&source != this) {
Clear();
Copy(source.value_, value_);
}
return *this;
}
bool empty() const { return ::OpcUa_String_IsEmpty(&value_) != OpcUa_False; }
bool is_null() const { return ::OpcUa_String_IsNull(&value_) != OpcUa_False; }
OpcUa_String& get() { return value_; }
const OpcUa_String& get() const { return value_; }
private:
OpcUa_String value_;
};
inline bool operator<(const String& a, const String& b) {
return a.get() < b.get();
}
} // namespace opcua
|
DxBillGates/FrogAdventure2 | GatesEngine/Header/Graphics/ShaderResourceHeap.h | <reponame>DxBillGates/FrogAdventure2
#pragma once
#include "..\Util\Math\Vector3.h"
#include "IShaderResourceHeap.h"
#include <d3d12.h>
namespace GE
{
class ShaderResourceHeap : public IShaderResourceHeap
{
private:
ID3D12Device* device;
ID3D12GraphicsCommandList* cmdList;
ID3D12DescriptorHeap* heap;
Math::Vector3 usedShaderResourceCount;
int nextUseSrvDescriptorNumber;
int nextUseUavDescriptorNumber;
public:
ShaderResourceHeap();
~ShaderResourceHeap();
void SetGraphicsDevice(ID3D12Device* device, ID3D12GraphicsCommandList* cmdList);
void Create(const Math::Vector3& count);
void Set();
// interface
D3D12_CPU_DESCRIPTOR_HANDLE GetCPUHandle() override;
D3D12_GPU_DESCRIPTOR_HANDLE GetGPUHandle() override;
D3D12_GPU_DESCRIPTOR_HANDLE GetGPUHandleForCBV(int value) override;
D3D12_GPU_DESCRIPTOR_HANDLE GetGPUHandleForSRV(int value) override;
D3D12_GPU_DESCRIPTOR_HANDLE GetGPUHandleForUAV(int value) override;
int GetDescriptorHandleIncrementSize() override;
const Math::Vector3& GetWillUseShaderResourceCount() override;
int GetNextSRVNumber() override;
int GetNextUAVNumber() override;
void CreateCBV(const D3D12_CONSTANT_BUFFER_VIEW_DESC& cbvDesc, D3D12_CPU_DESCRIPTOR_HANDLE handle) override;
void CreateSRV(ID3D12Resource* buffer, const D3D12_SHADER_RESOURCE_VIEW_DESC& srvDesc) override;
void CreateUAV(ID3D12Resource* buffer, const D3D12_UNORDERED_ACCESS_VIEW_DESC& uavDesc) override;
};
} |
boost-entropy-repos-org/metasfresh | backend/de.metas.adempiere.adempiere/base/src/main/java/de/metas/event/ForwardingEventBus.java | <reponame>boost-entropy-repos-org/metasfresh
package de.metas.event;
import java.util.function.Consumer;
import org.slf4j.MDC.MDCCloseable;
import de.metas.event.impl.EventMDC;
import lombok.NonNull;
/**
* Forwarding {@link IEventBus} template implementation.
*
* @author tsa
*
*/
abstract class ForwardingEventBus implements IEventBus
{
private final IEventBus delegate;
public ForwardingEventBus(@NonNull final IEventBus delegate)
{
this.delegate = delegate;
}
protected final IEventBus delegate()
{
return delegate;
}
@Override
public String toString()
{
return delegate().toString();
}
@Override
public String getTopicName()
{
return delegate().getTopicName();
}
@Override
public Type getType()
{
return delegate().getType();
}
@Override
public void subscribe(final IEventListener listener)
{
delegate().subscribe(listener);
}
@Override
public void subscribe(final Consumer<Event> eventConsumer)
{
delegate().subscribe(eventConsumer);
}
@Override
public <T> void subscribeOn(final Class<T> type, final Consumer<T> eventConsumer)
{
delegate().subscribeOn(type, eventConsumer);
}
@Override
public void unsubscribe(final IEventListener listener)
{
delegate().unsubscribe(listener);
}
@Override
public void postEvent(final Event event)
{
try (final MDCCloseable mdc = EventMDC.putEvent(event))
{
delegate().postEvent(event);
}
}
@Override
public void postObject(final Object obj)
{
delegate().postObject(obj);
}
@Override
public boolean isDestroyed()
{
return delegate().isDestroyed();
}
@Override
public boolean isAsync()
{
return delegate().isAsync();
}
@Override
public EventBusStats getStats()
{
return delegate().getStats();
}
}
|
sirAgg/nebula | tests/mathtest/bboxtest.cc | <filename>tests/mathtest/bboxtest.cc
//------------------------------------------------------------------------------
// bboxtest.cc
// (C) 2020 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "bboxtest.h"
#include "math/vec4.h"
#include "math/mat4.h"
#include "math/bbox.h"
#include "mathtestutil.h"
#include "stackalignment.h"
#include "testbase/stackdebug.h"
using namespace Math;
namespace Test
{
__ImplementClass(Test::BBoxTest, 'BBTS', Test::TestCase);
//------------------------------------------------------------------------------
/**
*/
void
BBoxTest::Run()
{
STACK_CHECKPOINT("Test::BBoxTest::Run()");
Math::mat4 cam = Math::perspfovlh(60.0f, 16.0f / 9.0f, 0.0001f, 1000.0f);
static const int NumBoxes = 100;
for (IndexT i = -NumBoxes; i < NumBoxes; i+=10)
{
for (IndexT j = -NumBoxes; j < NumBoxes; j+=10)
{
Math::bbox box;
box.set(Math::scaling(10, 10, 10) * Math::translation(j, 0, i));
}
}
}
} |
grujicbr/aws-sdk-cpp | aws-cpp-sdk-ec2/source/model/EnableFastSnapshotRestoreSuccessItem.cpp | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
#include <aws/ec2/model/EnableFastSnapshotRestoreSuccessItem.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <utility>
using namespace Aws::Utils::Xml;
using namespace Aws::Utils;
namespace Aws
{
namespace EC2
{
namespace Model
{
EnableFastSnapshotRestoreSuccessItem::EnableFastSnapshotRestoreSuccessItem() :
m_snapshotIdHasBeenSet(false),
m_availabilityZoneHasBeenSet(false),
m_state(FastSnapshotRestoreStateCode::NOT_SET),
m_stateHasBeenSet(false),
m_stateTransitionReasonHasBeenSet(false),
m_ownerIdHasBeenSet(false),
m_ownerAliasHasBeenSet(false),
m_enablingTimeHasBeenSet(false),
m_optimizingTimeHasBeenSet(false),
m_enabledTimeHasBeenSet(false),
m_disablingTimeHasBeenSet(false),
m_disabledTimeHasBeenSet(false)
{
}
EnableFastSnapshotRestoreSuccessItem::EnableFastSnapshotRestoreSuccessItem(const XmlNode& xmlNode) :
m_snapshotIdHasBeenSet(false),
m_availabilityZoneHasBeenSet(false),
m_state(FastSnapshotRestoreStateCode::NOT_SET),
m_stateHasBeenSet(false),
m_stateTransitionReasonHasBeenSet(false),
m_ownerIdHasBeenSet(false),
m_ownerAliasHasBeenSet(false),
m_enablingTimeHasBeenSet(false),
m_optimizingTimeHasBeenSet(false),
m_enabledTimeHasBeenSet(false),
m_disablingTimeHasBeenSet(false),
m_disabledTimeHasBeenSet(false)
{
*this = xmlNode;
}
EnableFastSnapshotRestoreSuccessItem& EnableFastSnapshotRestoreSuccessItem::operator =(const XmlNode& xmlNode)
{
XmlNode resultNode = xmlNode;
if(!resultNode.IsNull())
{
XmlNode snapshotIdNode = resultNode.FirstChild("snapshotId");
if(!snapshotIdNode.IsNull())
{
m_snapshotId = Aws::Utils::Xml::DecodeEscapedXmlText(snapshotIdNode.GetText());
m_snapshotIdHasBeenSet = true;
}
XmlNode availabilityZoneNode = resultNode.FirstChild("availabilityZone");
if(!availabilityZoneNode.IsNull())
{
m_availabilityZone = Aws::Utils::Xml::DecodeEscapedXmlText(availabilityZoneNode.GetText());
m_availabilityZoneHasBeenSet = true;
}
XmlNode stateNode = resultNode.FirstChild("state");
if(!stateNode.IsNull())
{
m_state = FastSnapshotRestoreStateCodeMapper::GetFastSnapshotRestoreStateCodeForName(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(stateNode.GetText()).c_str()).c_str());
m_stateHasBeenSet = true;
}
XmlNode stateTransitionReasonNode = resultNode.FirstChild("stateTransitionReason");
if(!stateTransitionReasonNode.IsNull())
{
m_stateTransitionReason = Aws::Utils::Xml::DecodeEscapedXmlText(stateTransitionReasonNode.GetText());
m_stateTransitionReasonHasBeenSet = true;
}
XmlNode ownerIdNode = resultNode.FirstChild("ownerId");
if(!ownerIdNode.IsNull())
{
m_ownerId = Aws::Utils::Xml::DecodeEscapedXmlText(ownerIdNode.GetText());
m_ownerIdHasBeenSet = true;
}
XmlNode ownerAliasNode = resultNode.FirstChild("ownerAlias");
if(!ownerAliasNode.IsNull())
{
m_ownerAlias = Aws::Utils::Xml::DecodeEscapedXmlText(ownerAliasNode.GetText());
m_ownerAliasHasBeenSet = true;
}
XmlNode enablingTimeNode = resultNode.FirstChild("enablingTime");
if(!enablingTimeNode.IsNull())
{
m_enablingTime = DateTime(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(enablingTimeNode.GetText()).c_str()).c_str(), DateFormat::ISO_8601);
m_enablingTimeHasBeenSet = true;
}
XmlNode optimizingTimeNode = resultNode.FirstChild("optimizingTime");
if(!optimizingTimeNode.IsNull())
{
m_optimizingTime = DateTime(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(optimizingTimeNode.GetText()).c_str()).c_str(), DateFormat::ISO_8601);
m_optimizingTimeHasBeenSet = true;
}
XmlNode enabledTimeNode = resultNode.FirstChild("enabledTime");
if(!enabledTimeNode.IsNull())
{
m_enabledTime = DateTime(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(enabledTimeNode.GetText()).c_str()).c_str(), DateFormat::ISO_8601);
m_enabledTimeHasBeenSet = true;
}
XmlNode disablingTimeNode = resultNode.FirstChild("disablingTime");
if(!disablingTimeNode.IsNull())
{
m_disablingTime = DateTime(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(disablingTimeNode.GetText()).c_str()).c_str(), DateFormat::ISO_8601);
m_disablingTimeHasBeenSet = true;
}
XmlNode disabledTimeNode = resultNode.FirstChild("disabledTime");
if(!disabledTimeNode.IsNull())
{
m_disabledTime = DateTime(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(disabledTimeNode.GetText()).c_str()).c_str(), DateFormat::ISO_8601);
m_disabledTimeHasBeenSet = true;
}
}
return *this;
}
void EnableFastSnapshotRestoreSuccessItem::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const
{
if(m_snapshotIdHasBeenSet)
{
oStream << location << index << locationValue << ".SnapshotId=" << StringUtils::URLEncode(m_snapshotId.c_str()) << "&";
}
if(m_availabilityZoneHasBeenSet)
{
oStream << location << index << locationValue << ".AvailabilityZone=" << StringUtils::URLEncode(m_availabilityZone.c_str()) << "&";
}
if(m_stateHasBeenSet)
{
oStream << location << index << locationValue << ".State=" << FastSnapshotRestoreStateCodeMapper::GetNameForFastSnapshotRestoreStateCode(m_state) << "&";
}
if(m_stateTransitionReasonHasBeenSet)
{
oStream << location << index << locationValue << ".StateTransitionReason=" << StringUtils::URLEncode(m_stateTransitionReason.c_str()) << "&";
}
if(m_ownerIdHasBeenSet)
{
oStream << location << index << locationValue << ".OwnerId=" << StringUtils::URLEncode(m_ownerId.c_str()) << "&";
}
if(m_ownerAliasHasBeenSet)
{
oStream << location << index << locationValue << ".OwnerAlias=" << StringUtils::URLEncode(m_ownerAlias.c_str()) << "&";
}
if(m_enablingTimeHasBeenSet)
{
oStream << location << index << locationValue << ".EnablingTime=" << StringUtils::URLEncode(m_enablingTime.ToGmtString(DateFormat::ISO_8601).c_str()) << "&";
}
if(m_optimizingTimeHasBeenSet)
{
oStream << location << index << locationValue << ".OptimizingTime=" << StringUtils::URLEncode(m_optimizingTime.ToGmtString(DateFormat::ISO_8601).c_str()) << "&";
}
if(m_enabledTimeHasBeenSet)
{
oStream << location << index << locationValue << ".EnabledTime=" << StringUtils::URLEncode(m_enabledTime.ToGmtString(DateFormat::ISO_8601).c_str()) << "&";
}
if(m_disablingTimeHasBeenSet)
{
oStream << location << index << locationValue << ".DisablingTime=" << StringUtils::URLEncode(m_disablingTime.ToGmtString(DateFormat::ISO_8601).c_str()) << "&";
}
if(m_disabledTimeHasBeenSet)
{
oStream << location << index << locationValue << ".DisabledTime=" << StringUtils::URLEncode(m_disabledTime.ToGmtString(DateFormat::ISO_8601).c_str()) << "&";
}
}
void EnableFastSnapshotRestoreSuccessItem::OutputToStream(Aws::OStream& oStream, const char* location) const
{
if(m_snapshotIdHasBeenSet)
{
oStream << location << ".SnapshotId=" << StringUtils::URLEncode(m_snapshotId.c_str()) << "&";
}
if(m_availabilityZoneHasBeenSet)
{
oStream << location << ".AvailabilityZone=" << StringUtils::URLEncode(m_availabilityZone.c_str()) << "&";
}
if(m_stateHasBeenSet)
{
oStream << location << ".State=" << FastSnapshotRestoreStateCodeMapper::GetNameForFastSnapshotRestoreStateCode(m_state) << "&";
}
if(m_stateTransitionReasonHasBeenSet)
{
oStream << location << ".StateTransitionReason=" << StringUtils::URLEncode(m_stateTransitionReason.c_str()) << "&";
}
if(m_ownerIdHasBeenSet)
{
oStream << location << ".OwnerId=" << StringUtils::URLEncode(m_ownerId.c_str()) << "&";
}
if(m_ownerAliasHasBeenSet)
{
oStream << location << ".OwnerAlias=" << StringUtils::URLEncode(m_ownerAlias.c_str()) << "&";
}
if(m_enablingTimeHasBeenSet)
{
oStream << location << ".EnablingTime=" << StringUtils::URLEncode(m_enablingTime.ToGmtString(DateFormat::ISO_8601).c_str()) << "&";
}
if(m_optimizingTimeHasBeenSet)
{
oStream << location << ".OptimizingTime=" << StringUtils::URLEncode(m_optimizingTime.ToGmtString(DateFormat::ISO_8601).c_str()) << "&";
}
if(m_enabledTimeHasBeenSet)
{
oStream << location << ".EnabledTime=" << StringUtils::URLEncode(m_enabledTime.ToGmtString(DateFormat::ISO_8601).c_str()) << "&";
}
if(m_disablingTimeHasBeenSet)
{
oStream << location << ".DisablingTime=" << StringUtils::URLEncode(m_disablingTime.ToGmtString(DateFormat::ISO_8601).c_str()) << "&";
}
if(m_disabledTimeHasBeenSet)
{
oStream << location << ".DisabledTime=" << StringUtils::URLEncode(m_disabledTime.ToGmtString(DateFormat::ISO_8601).c_str()) << "&";
}
}
} // namespace Model
} // namespace EC2
} // namespace Aws
|
jsdelivrbot/alize | src/lib/helper/option.js | <gh_stars>0
'use strict';
import format from 'errors/format';
export function assertJSON(json, config, path = '') {
for (const prop in config) {
if (!config.hasOwnProperty(prop)
|| typeof config[prop] !== 'object' || config[prop] === null) {
continue;
}
const { type, checks, children } = config[prop];
const propPath = path.length > 0 ? `${path}.${prop}` : prop;
// type check
if (type && json[prop] !== void(0) && typeof json[prop] !== type) {
throw new TypeError(format.typeError(propPath, type, json[prop]));
}
// other checks
if (checks) {
if (checks.enum) {
assertEnum(json, prop, checks.enum, propPath);
}
if (checks.require) {
assertRequire(json, prop, checks.require, propPath);
}
if (checks.forbid) {
assertForbid(json, prop, checks.forbid, propPath);
}
}
if (children && json[prop] && typeof json[prop] === 'object') {
assertJSON(json[prop], children, propPath);
}
}
}
export function assertEnum(obj, prop, { array = [], error }, path) {
if (obj == null) {
return;
}
if (obj[prop] == null) {
return;
}
if (array) {
if (Reflect.apply(Array.prototype.includes, array, [obj[prop]])) {
return;
}
if (error) {
throw new Error(error(obj, prop, path));
}
throw new Error(format.enumError(path, array, obj[prop]));
} else {
throw new Error('Invalid enum config: property "array" is missing');
}
}
export function checkCondition(obj, { absent, present }) {
if (obj == null) {
return false;
}
if (absent && typeof absent === 'object') {
for (const p of absent) {
if (obj[p] != null) {
continue;
}
return true;
}
}
if (present && typeof present === 'object') {
for (const p of present) {
if (obj[p] != null) {
return true;
}
}
}
return false;
}
export function assertRequire(obj, prop, { when, error }, path) {
let condition = true;
if (when) {
if (typeof when !== 'object' || when === null) {
throw new TypeError(format.typeError('when', 'object', when));
}
condition = checkCondition(obj, when);
}
if (condition) {
if (obj[prop] != null) {
return;
}
if (error) {
throw new Error(error(obj, prop, path));
}
throw new Error(format.missingParam(path));
}
}
export function assertForbid(obj, prop, { when, error }, path) {
let condition = true;
if (when) {
if (typeof when !== 'object' || when === null) {
throw new TypeError(format.typeError('when', 'object', when));
}
condition = checkCondition(obj, when);
}
if (condition) {
if (obj[prop] == null) {
return;
}
if (error) {
throw new Error(error(obj, prop, path));
}
throw new Error(format.extraParam(path));
}
}
export function calcAccessPath(urlConfig, root = 'root') {
if (urlConfig.path) {
return urlConfig.path;
}
return urlToAccessPath(urlConfig.url);
function urlToAccessPath(urlStr) {
let accessPath = urlStr.split('/')
.filter(x => x.length && x[0] !== ':')
.join('.');
if (accessPath.length > 0 && accessPath[0] === '.') {
accessPath = accessPath.substr(1);
}
return accessPath.length > 0 ? accessPath : root;
}
}
export function injectParamsToUrl(urlStr, params = {}) {
return urlStr.split('/').map(str => {
if (str.length > 1 && str[0] === ':') {
const paramKey = str.substr(1);
if (paramKey in params) {
return params[paramKey];
}
// TODO: obscure error message
throw new Error(format.missingParam(paramKey));
}
return str;
}).join('/');
}
export default {
assertJSON,
assertEnum,
checkCondition,
assertRequire,
assertForbid,
calcAccessPath,
injectParamsToUrl,
};
|
scalamolecule/molecule-admin | server/src/main/scala/moleculeadmin/server/schema/Partition.scala | <reponame>scalamolecule/molecule-admin<gh_stars>1-10
package moleculeadmin.server.schema
import java.util
import java.util.{List => jList, Map => jMap}
import datomic.{Peer, Util}
import db.admin.dsl.moleculeAdmin._
import molecule.api.out15._
import molecule.facade.Conn
import moleculeadmin.server.Base
import moleculeadmin.shared.ast.metaSchema._
import moleculeadmin.server.utils.DefFile
object Partition extends SchemaBase with Base{
def create(schema: MetaSchema, db: String, part: String, descr: Option[String], pos0: Int): Either[String, MetaSchema] = {
if (part.isEmpty) {
Left("Empty partition name.")
} else if (reservedPartitionNames.contains(part)) {
Left("Partition can't have reserved name `tx` or `db`.")
} else if (part.head.isUpper) {
Left("Partition name should start with lowercase letter and match `[a-z][a-zA-Z0-9]*`.")
} else if (!part.matches("[a-z][a-zA-Z0-9]*")) {
Left("Partition name should match `[a-z][a-zA-Z0-9]*`.")
} else {
implicit val moleculeAdminConn = Conn(base + "/MoleculeAdmin")
withTransactor {
meta_Db.e.name_(db).get match {
case Seq(dbE) => {
val liveConn = Conn(base + "/" + db)
val curPartitions = meta_Db.name_(db).Partitions.e.pos.name.get
val pos = if (pos0 == 0) curPartitions.length + 1 else pos0
var newPartitionE: Long = 0L
if (curPartitions.exists(_._3 == part)) {
Left(s"Partition `$part` already exists in database `$db`. Please choose another partition name.")
} else try {
// Add partition to live schema
liveConn.transact(Util.list(
Util.map(
":db/ident", s":$part",
":db/id", Peer.tempid(":db.part/db"),
":db.install/_partition", ":db.part/db"
)
).asInstanceOf[util.List[AnyRef]])
// Add partition to meta db
newPartitionE = meta_Partition.pos(pos).name(part).descr$(descr).save.eid
meta_Db(dbE).partitions.assert(newPartitionE).update
// Increase pos index for partitions after new partition
curPartitions.filter(_._2 >= pos).foreach { case (e, n, _) =>
val incrPos = n + 1
meta_Partition(e).pos(incrPos).update
}
// Add partition to client schema
val newPartition : MetaPart = MetaPart(pos, part, descr, None, Nil)
val updatedSchema: MetaSchema = MetaSchema(
if (schema.parts.isEmpty) {
Seq(newPartition)
} else {
schema.parts.flatMap {
case p if p.pos == 1 && pos == 1 => Seq(newPartition, p.copy(pos = p.pos + 1))
case p if p.pos == pos - 1 => Seq(p, newPartition)
case p if p.pos < pos - 1 => Seq(p)
case p => Seq(p.copy(pos = p.pos + 1))
}
}
)
DefFile(db).recreateFrom(updatedSchema)
} catch {
case error: Throwable => try {
// Restore partition order
curPartitions.filter(_._2 >= pos).foreach { case (e, n, _) => meta_Partition(e).pos(n).update }
// Delete obsolete new meta partition entity (for some reason we seem allowed to retract partition entities)
if (newPartitionE > 0L) newPartitionE.retract
// Restore def file
DefFile(db).recreateFrom(schema)
Left("Successfully rolled back from error: " + error.getMessage)
} catch {
case rollbackError: Throwable => Left("Unsuccessfully tried to roll back from error! " +
"Please check meta db that might be in an invalid state. Unexpected rollback error: " + rollbackError.getMessage)
}
}
}
case Nil => Left(s"Couldn't find database `$db`.")
case databaseCount => Left(s"Unexpectedly found $databaseCount databases named `$db`.")
}
}
}
}
def update(schema0: MetaSchema, db: String, curPart: String, newPart: String, descr: Option[String], pos0: Int): Either[String, MetaSchema] = {
if (newPart.isEmpty) {
Left("Empty partition name.")
} else if (reservedPartitionNames.contains(newPart)) {
Left("Partition can't have reserved name `tx` or `db`.")
} else if (newPart.head.isUpper) {
Left("Partition name should start with lowercase letter and match `[a-z][a-zA-Z0-9]*`.")
} else if (!newPart.matches("[a-z][a-zA-Z0-9]*")) {
Left("Partition name should match `[a-z][a-zA-Z0-9]*`.")
} else {
implicit val moleculeAdminConn = Conn(base + "/MoleculeAdmin")
withTransactor {
meta_Db.e.name_(db).get.size match {
case 1 => meta_Db.name_(db).Partitions.e.pos.name_(curPart).descr$.namespaces$.get match {
// Current partition data
case Seq((partE, curPos, curDescrOpt, nss)) => {
val liveConn = Conn(base + "/" + db)
val curPartitions = meta_Db.name_(db).Partitions.e.pos.name.get
val pos = if (pos0 == 0) curPos else pos0
val partitionEntities: Map[String, Long] = curPartitions.map(a => a._3 -> a._1).toMap
val rollbackRefNss = new collection.mutable.ListBuffer[(Long, String)]
val rollbackAttrStmtsMap = new java.util.ArrayList[jMap[_, _]]()
if (curPart != newPart && curPartitions.exists(_._3 == newPart)) {
Left(s"Partition `$newPart` already exists in database `$db`. Please choose another partition name.")
} else try {
// Modifying partition definition for each change
var updatedPartDef: MetaPart = schema0.parts.find(_.name == curPart).get
// partition pos ....................................................
var schema: MetaSchema = if (pos > 0 && pos != curPos) {
MetaSchema(schema0.parts.map {
case partDef@MetaPart(_, `curPart`, _, _, _) =>
// meta
meta_Partition(partE).pos(pos).update
// client
val partDef1 = partDef.copy(pos = pos)
updatedPartDef = partDef1
partDef1
case partDef@MetaPart(otherPos, otherPart, _, _, _) if otherPos > curPos && otherPos <= pos =>
// meta
val otherPartE = partitionEntities(otherPart)
val newPos = otherPos - 1
meta_Partition(otherPartE).pos(newPos).update
// client
partDef.copy(pos = newPos)
case partDef@MetaPart(otherPos, otherPart, _, _, _) if otherPos < curPos && otherPos >= pos =>
// meta
val otherPartE = partitionEntities(otherPart)
val newPos = otherPos + 1
meta_Partition(otherPartE).pos(newPos).update
// client
partDef.copy(pos = newPos)
case partDef =>
partDef
}.sortBy(_.pos)) // Save partition definitions in new order
} else schema0
def updateSchema = {
schema = MetaSchema(schema.parts.map {
case MetaPart(_, `curPart`, _, _, _) => updatedPartDef
case partDef => partDef
})
}
// partition description ....................................................
if (curDescrOpt != descr) {
descr match {
case None | Some("") =>
meta_Partition(partE).descr().update
updatedPartDef = updatedPartDef.copy(descr$ = None)
case Some(txt) =>
meta_Partition(partE).descr(txt).update
updatedPartDef = updatedPartDef.copy(descr$ = descr)
}
updateSchema
}
// partition name ....................................................
if (curPart != newPart) {
// Alter ident of all attributes in partition (!!)
val txMaps = for {
MetaNs(_, ns, _, _, _, attrs) <- updatedPartDef.nss
MetaAttr(_, attr, _, _, _, _, _, _, _, _, _, _, _) <- attrs
} yield {
val (curAttr, newAttr) = (getFullAttr(curPart, ns, attr), getFullAttr(newPart, ns, attr))
rollbackAttrStmtsMap.add(
Util.map(":db/id", newAttr, ":db/ident", curAttr)
)
Util.map(":db/id", curAttr, ":db/ident", newAttr)
}
liveConn.transact(Util.list(txMaps: _*).asInstanceOf[util.List[AnyRef]])
// Rename live partition entity itself
renameIdent(db, curPart, newPart)
// meta
meta_Partition(partE).name(newPart).update
// update references to all namespaces in this partition
val partPrefix: String = curPart + "_"
schema = MetaSchema(schema.parts.map {
case partDef@MetaPart(_, part, _, _, nss) => {
val nsDefs: Seq[MetaNs] = nss.map {
case nsDef@MetaNs(_, ns, _, _, _, attrs) => {
// Update ref attributes
val attrDefs: Seq[MetaAttr] = attrs.map {
// Ref attribute with reference to old partition name
case refAttr@MetaAttr(_, attr, _, _, _, Some(curFullRefNs), _, _, _, _, _, _, _) if curFullRefNs.startsWith(partPrefix) =>
// Replace old partition name with new name in reference
val newRefNs: String = newPart + "_" + curFullRefNs.split("_")(1)
// update meta
val attrE: Long = getAttrE(moleculeAdminConn, db, part, ns, attr)
// Save original meta refNs for rollback
rollbackRefNss += attrE -> curFullRefNs
// Save new meta refNs
meta_Attribute(attrE).refNs(newRefNs).update
// update client
refAttr.copy(refNs$ = Some(newRefNs))
case otherAttr => otherAttr
}
nsDef.copy(attrs = attrDefs)
}
}
partDef.copy(nss = nsDefs)
}
})
// re-load updated part with refNss
updatedPartDef = schema.parts.find(_.name == curPart).get
// client (catch refNs updates too)
val nsDefs = updatedPartDef.nss.map(ns => ns.copy(nameFull = s"${newPart}_${ns.name}"))
updatedPartDef = updatedPartDef.copy(name = newPart, nss = nsDefs)
updateSchema
}
// Update def file
DefFile(db).recreateFrom(schema)
} catch {
case error: Throwable => try {
// Restore order of meta partitions
curPartitions.foreach { case (e, pos1, _) => meta_Partition(e).pos(pos1).update }
// Restore meta partition data
meta_Partition(partE).name(curPart).descr$(curDescrOpt).update
// Restore refNss
rollbackRefNss.foreach { case (attrE, refNs) => meta_Attribute(attrE).refNs(refNs).update }
// Restore live attribute names
if (rollbackAttrStmtsMap.size > 0) {
liveConn.transact(rollbackAttrStmtsMap.asInstanceOf[jList[AnyRef]])
}
// Restore def file
DefFile(db).recreateFrom(schema0)
Left("Successfully rolled back from error: " + error.getMessage)
} catch {
case rollbackError: Throwable => Left("Unsuccessfully tried to roll back from error! " +
"Please check meta db that might be in an invalid state. Unexpected rollback error: " + rollbackError.getMessage)
}
}
}
case Nil => Left(s"Couldn't find partition `$curPart` in database `$db`.")
case morePartitions => Left(s"Unexpectedly found ${morePartitions.size} partitions named `$curPart` in database `$db`.")
}
case 0 => Left(s"Couldn't find database `$db`.")
case databaseCount => Left(s"Unexpectedly found $databaseCount databases named `$db`.")
}
}
}
}
def delete(schema: MetaSchema, db: String, part: String): Either[String, MetaSchema] = {
if (db.isEmpty) {
Left("Empty db name.")
} else if (part.isEmpty) {
Left("Empty partition name.")
} else {
implicit val moleculeAdminConn = Conn(base + "/MoleculeAdmin")
withTransactor {
meta_Db.name(db).get.size match {
case 1 => meta_Db.name_(db).Partitions.e.pos.name_(part).descr$.entityCount$.namespaces$.molecules$.get match {
// Current partition meta data
case Seq((partE, pos, optDescr, optEntityCound, optNss, optMolecules)) => {
val liveConn = Conn(base + "/" + db)
val metaPartitions = meta_Db.name_(db).Partitions.e.pos.>(pos).get
val rollbackPartStmtsMap = new java.util.ArrayList[jMap[_, _]]()
val rollbackAttrStmtsMap = new java.util.ArrayList[jMap[_, _]]()
try {
if (optNss.isDefined && optNss.get.nonEmpty) {
// Partition has namespace(s)
val nss = optNss.get
if (meta_Namespace(nss).nameFull.Attrs.name.get.collectFirst {
case (nsFull, attr) if getEntityCount(liveConn, s":$nsFull/$attr") > 0 => true
}.getOrElse(false)) {
// Attribute has attribute with value
throw new RuntimeException(
s"Couldn't delete partition `$part` in database `$db` having attributes with values. Please delete values first.")
}
// No values asserted - "park"/rename all attributes in partition (!!)
val txMaps = for {
MetaPart(_, part1, _, _, nss) <- schema.parts if part1 == part
MetaNs(_, _, nsFull, _, _, attrs) <- nss
MetaAttr(_, attr, _, _, _, _, _, _, _, _, _, _, _) <- attrs
} yield {
rollbackAttrStmtsMap.add(
Util.map(":db/id", s":-$nsFull/$attr", ":db/ident", s":$nsFull/$attr")
)
Util.map(":db/id", s":$nsFull/$attr", ":db/ident", s":-$nsFull/$attr")
}
liveConn.transact(Util.list(txMaps: _*).asInstanceOf[util.List[AnyRef]])
}
// Find live partition entity
val livePartitionId = liveConn.q(
s"""[:find ?livePartId
| :where [_ :db.install/partition ?livePartId]
| [?livePartId :db/ident :$part]]""".stripMargin)
// retract live partition entity if it exists
if (livePartitionId.nonEmpty)
retract(Seq(livePartitionId.head.head.asInstanceOf[Long]))(liveConn)
rollbackPartStmtsMap.add(Util.map(
":db/ident", s":$part",
":db/id", Peer.tempid(":db.part/db"),
":db.install/_partition", ":db.part/db"
))
// retract meta partition
partE.retract
// Shift partition positions af deleted partition
metaPartitions.foreach { case (e, o) =>
val decrPos = o - 1
meta_Partition(e).pos(decrPos).update
}
// client
val updatedSchema: MetaSchema = MetaSchema(schema.parts.flatMap {
case p if p.pos == pos => Nil
case p if p.pos > pos => Seq(p.copy(pos = p.pos - 1))
case p => Seq(p)
})
// Def file
DefFile(db).recreateFrom(updatedSchema)
} catch {
// Roll-back ==================================================================================
case error: Throwable => try {
// Rollback meta positions for shifted partitions
metaPartitions.foreach { case (e, p) => meta_Partition(e).pos(p).update }
// Recreate deleted meta partition
meta_Partition(partE).pos(pos).name(part).descr$(optDescr).entityCount$(optEntityCound).namespaces$(optNss).molecules$(optMolecules).update
// Re-create live partition
if (rollbackPartStmtsMap.size > 0) {
liveConn.transact(rollbackPartStmtsMap.asInstanceOf[jList[AnyRef]])
}
// "Un-park" live attribute names
if (rollbackAttrStmtsMap.size > 0) {
liveConn.transact(rollbackAttrStmtsMap.asInstanceOf[jList[AnyRef]])
}
// Rollback def file
DefFile(db).recreateFrom(schema)
Left("Successfully rolled back from error: " + error.getMessage)
} catch {
case rollbackError: Throwable => Left("Unsuccessfully tried to roll back from error! " +
"Please check meta db that might be in an invalid state. Unexpected rollback error: " + rollbackError.getMessage)
}
}
}
case Nil => Left(s"Couldn't find partition `$part` in database `$db`.")
case morePartitions => Left(s"Unexpectedly found ${morePartitions.size} partitions named `$part` in database `$db`.")
}
case 0 => Left(s"Couldn't find database `$db`.")
case databasesCount => Left(s"Unexpectedly found $databasesCount databases named `$db`.")
}
}
}
}
def renameIdent(db: String, from: String, to: String): Unit = Conn(base + "/" + db).transact(Util.list(
Util.map(
":db/id", s":$from",
":db/ident", s":$to"
)
).asInstanceOf[util.List[AnyRef]])
}
|
windows-development/Windows-classic-samples | Samples/Win7Samples/Touch/MTGestures/cpp/MyGestureEngine.h | <reponame>windows-development/Windows-classic-samples
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// CMyGestureEngine.h
//
// Definition of derived class that handles gesture operations. This
// class gets pointer to the rectangle object through constructor and
// then it just invokes coresponding function from CDrawingObject class
#pragma once
#include "GestureEngine.h"
#include "DrawingObject.h"
class CMyGestureEngine : public CGestureEngine
{
public:
CMyGestureEngine(CDrawingObject* pcRect);
~CMyGestureEngine();
// Functions that are handling gesture commands
virtual void ProcessPressAndTap();
virtual void ProcessTwoFingerTap();
virtual void ProcessMove(const LONG ldx, const LONG ldy);
virtual void ProcessZoom(const double dZoomFactor, const LONG lZx, const LONG lZy);
virtual void ProcessRotate(const double dAngle, const LONG lOx, const LONG lOy);
private:
CDrawingObject* _pcRect;
};
|
zOadT/planck.js | example/ShapeEditing.js | <filename>example/ShapeEditing.js<gh_stars>1000+
/*
* MIT License
* Copyright (c) 2019 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
planck.testbed('ShapeEditing', function(testbed) {
testbed.info('C: Create a shape, X: Destroy a shape, Z: Sensor');
var pl = planck, Vec2 = pl.Vec2;
var world = new pl.World(Vec2(0, -10));
var sensor = true;
var ground = world.createBody();
ground.createFixture(pl.Edge(Vec2(-40.0, 0.0), Vec2(40.0, 0.0)), 0.0);
var body = world.createDynamicBody(Vec2(0.0, 10.0));
var fixture1 = body.createFixture(pl.Box(4.0, 4.0, Vec2(0.0, 0.0), 0.0), 10.0);
var fixture2 = null;
testbed.keydown = function(code, char) {
switch (char) {
case 'C':
if (fixture2 == null) {
var shape = pl.Circle(Vec2(0.5, -4.0), 3.0);
fixture2 = body.createFixture(shape, 10.0);
body.setAwake(true);
fixture2.setSensor(sensor);
}
break;
case 'X':
if (fixture2 != null) {
body.destroyFixture(fixture2);
fixture2 = null;
body.setAwake(true);
}
break;
case 'Z':
if (fixture2 != null) {
sensor = !sensor;
fixture2.setSensor(sensor);
}
break;
}
updateStatus();
};
function updateStatus() {
testbed.status('Sensor', sensor);
}
updateStatus();
return world;
});
|
iAmHades/node_web_basic | server/service/baseService.js | /**
* Created by Hades on 15/3/19.
* 基础服务类,其他服务类,请继承它
*/
'use strict'
const mongodbDao = require('../storage/mongodbDao').getWorkInstance()
class BaseService {
constructor (tableName) {
this.TABLE_NAME = tableName
}
/*
* 保存
* @prams:newData object对象
* @return:Object 保存的对象
*/
save (newData) {
return mongodbDao.save(this.TABLE_NAME, newData)
}
/*
* 获取数量
* @prams:selector 查询条件的数据,可以直接为id的字符串,也可以用object
* @return:int 数据总数
*/
getCount (selector) {
return mongodbDao.getCount(this.TABLE_NAME, selector)
}
/*
* 根据查询条件获取一条信息
* @prams:selector 查询条件的数据,可以直接为id的字符串,也可以用object
* @return:Object
*/
findOne (selector) {
return mongodbDao.findOne(this.TABLE_NAME, selector)
}
/*
* 根据查询条件获取信息
* @prams:selector string/object 查询条件的数据,可以直接为id的字符串,也可以用object
* @prams:sort object 排序参数
* @return:[Object]
*/
query (selector, sort) {
return mongodbDao.query(this.TABLE_NAME, selector, sort)
}
/*
* 删除
* @prams:selector string/object 查询条件的数据,可以直接为id的字符串,也可以用object
* @return: int 被删除的数量
*/
remove (selector) {
return mongodbDao.remove(this.TABLE_NAME, selector)
}
/*
* 普通更新 .方式为$set
* @prams:selector string/object 查询条件的数据,可以直接为id的字符串,也可以用object
* @prams:newData object 需要更新的数据 ,该处的newData,会被内部$set,所以高级的更新需要借助updateAdv来实现�更新,,,f
* @prams:multi boolean 是否批量更新
* @return: int 被更新的数量 ,成功就为1, 没有查到就为0。
*/
update (selector, newData, multi) {
if (multi) {
return mongodbDao.updateBatch(this.TABLE_NAME, selector, newData)
} else {
return mongodbDao.update(this.TABLE_NAME, selector, newData)
}
}
/*
* 高级更新,可以运用mongodb的各种高级更新方法
* @prams:selector string/object 查询条件的数据,可以直接为id的字符串,也可以用object
* @prams:newData object 需要更新的数据,以及高级更新方法,比如:$inc,$addToSet,$pull等
* @return: int 被更新的数量 ,成功就为1, 没有查到就为0。
*/
updateAdv (selector, newData) {
return mongodbDao.updateAdv(this.TABLE_NAME, selector, newData)
}
/*
* 获取分页查询
* @prams:selector string/object 查询条件的数据,可以直接为id的字符串,也可以用object
* @prams:sort object 排序
* @prams:start int 开始的数据下标
* @prams:limit int 每页的数据数量
* @return: object.total int 总数据数
* @return: object.records [Object] 返回的数据
*/
findPagingData (selector, start, limit, sort) {
var pageRequest = {}
pageRequest.start = start
pageRequest.limit = limit
pageRequest.sort = sort || {createTime: -1}
return mongodbDao.findPagingData(this.TABLE_NAME, selector, pageRequest)
}
/*
* 查找并删除, 原子操作
* @prams:selector string/object 查询条件的数据,可以直接为id的字符串,也可以用object
* @prams:newData object 更新的数据
* @prams:sort object 排序
* @return:[Object] 返回的更新数据
*/
findAndModify (selector, newData, sort) {
return mongodbDao.findAndModify(this.TABLE_NAME, selector, newData, sort)
}
/*
* 查找并删除, 原子操作
* @prams:selector string/object 查询条件的数据,可以直接为id的字符串,也可以用object
* @prams:newData object 更新的数据
* @prams:sort object 排序
* @return:[Object] 返回的更新数据
*/
findAndRemove (selector, sort) {
return mongodbDao.findAndRemove(this.TABLE_NAME, selector, sort)
}
/*
* 按组查询
* @prams: keys object 分组键
* @prams: selector object 查询条件的数据
* @prams: initial object 表示$reduce函数参数prev的初始值。每个组都有一份该初始值
* @prams: reduce function 该函数接受两个参数,doc表示正在迭代的当前文档,prev表示累加器文档
* @return:[Object] 返回查询后的数据
*/
group (keys, selector, initial, reduce) {
return mongodbDao.group(this.TABLE_NAME, keys, selector, initial, reduce)
}
/*
* 去重查询
* @prams: field [string] 需要去重的字段数组
* @return:[Object] 返回查询后的数据
*/
distinct (field) {
return mongodbDao.distinct(this.TABLE_NAME, field)
}
}
module.exports = BaseService
|
lu-plus-plus/ama | test/test_define.cpp | /*
@ama
let nd_root=ParseCurrentFile({parse_indent_as_scope:1});
console.log(JSON.stringify(nd_root,null,1));
*/
#define A
#define B()
#define C 1
#define D -1
#define E (3)
#define F (a)(b)
|
tilemoon/tiga | lib/esbuild/build.js | const { build }= require('esbuild')
const fs = require('fs-extra')
const path = require('path')
const { createEsbuildHtml } = require('../html/html')
const { paramRequired } = require('../util')
const createConfig = require('./config')
const esBuild = async ({
entry = paramRequired('entry'),
outDir = paramRequired('outDir'),
mode,
}) => {
const config = createConfig({
entry,
outDir,
mode,
})
fs.emptyDirSync(outDir)
const result = await build(config)
result.outputFiles.forEach(({ path: fpath, contents }) => {
fs.writeFileSync(fpath, Buffer.from(contents).toString())
})
fs.writeFileSync(path.resolve(outDir, 'index.html'), createEsbuildHtml({
outDir,
outputFiles: result.outputFiles,
}))
}
module.exports = esBuild
|
ucl-exoplanets/TauREx3_public | taurex/cache/ciaacache.py | <reponame>ucl-exoplanets/TauREx3_public<filename>taurex/cache/ciaacache.py
"""
Contains caching class for Collisionally Induced Absorption files
"""
from taurex.core import Singleton
from taurex.log import Logger
class CIACache(Singleton):
"""
Implements a lazy load of collisionally induced absorpiton cross-sections
Supports pickle files and HITRAN cia files. Functionally behaves the same
as :class:`~taurex.cache.opacitycache.OpacityCache` except the keys are
now cia pairs
e.g:
>>> CIACache()['H2-H2']
<taurex.cia.picklecia.PickleCIA at 0x107a60be0>
Pickle ``.db`` and HITRAN ``.cia`` files are supported and automatically
loaded. with priority given to ``.db`` files
"""
def init(self):
self.cia_dict = {}
self._cia_path = None
self.log = Logger('CIACache')
def set_cia_path(self, cia_path):
"""
Sets the path to search for CIA files
Parameters
----------
cia_path : str or :obj:`list` of str
Either a single path or a list of paths that contain CIA files
"""
self._cia_path = cia_path
def __getitem__(self, key):
"""
For a CIA pair, load from the set path and return the
relevant :class:`~taurex.cia.cia.CIA` object
Parameter
---------
key : str
cia pair name
Returns
-------
:class:`~taurex.cia.picklecia.PickleCIA` or :class:`~taurex.cia.hitrancia.HitranCIA`
Desire CIA object, format depends on what is found
in the path set by :func:`set_cia_path`
Raise
-----
Exception
If desired CIA pair could not be loaded
"""
if key in self.cia_dict:
return self.cia_dict[key]
else:
# Try a load of the cia
self.load_cia(pair_filter=[key])
# If we have it after a load then good job boys
if key in self.cia_dict:
return self.cia_dict[key]
else:
# Otherwise throw an error
self.log.error('CIA for pair %s could not be loaded', key)
self.log.error('It could not be found in the local dictionary '
' %s', list(self.cia_dict.keys()))
self.log.error('Or paths %s', self._cia_path)
self.log.error('Try loading it manually/ putting it in a path')
raise Exception('cia could notn be loaded')
def add_cia(self, cia, pair_filter=None):
"""
Adds a :class:`~taurex.cia.cia.CIA` object to the cache to then be
used by Taurex 3
Parameters
----------
cia : :class:`~taurex.cia.cia.CIA`
CIA object to add to the cache
pair_filter : :obj:`list` of str , optional
If provided, the cia object will only be included
if its pairname is in the list. Mostly used by the
:func:`__getitem__` for filtering
"""
self.log.info('Loading cia %s into model', cia.pairName)
if cia.pairName in self.cia_dict:
self.log.error('cia with name %s already in '
'opactiy dictionary %s', cia.pairName,
self.cia_dict.keys())
raise Exception('cia for molecule %s already exists')
if pair_filter is not None:
if cia.pairName in pair_filter:
self.log.info('Loading cia %s into model', cia.pairName)
self.cia_dict[cia.pairName] = cia
self.cia_dict[cia.pairName] = cia
def load_cia_from_path(self, path, pair_filter=None):
"""
Searches path for CIA files, creates and loads them into the cache
``.db`` will be loaded as :class:`~taurex.cia.picklecia.PickleCIA` and
``.cia`` files will be loaded as
:class:`~taurex.cia.hitrancia.HitranCIA`
Parameters
----------
path : str
Path to search for CIA files
pair_filter : :obj:`list` of str , optional
If provided, the cia will only be loaded
if its pairname is in the list. Mostly used by the
:func:`__getitem__` for filtering
"""
from glob import glob
from pathlib import Path
import os
from taurex.cia import PickleCIA
# Find .db files
glob_path = os.path.join(path, '*.db')
file_list = glob(glob_path)
self.log.debug('Glob list: %s', glob_path)
self.log.debug('File list FOR CIA %s', file_list)
for files in file_list:
pairname = Path(files).stem.split('_')[0]
self.log.debug('pairname found %s', pairname)
if pair_filter is not None:
if pairname not in pair_filter:
continue
op = PickleCIA(files, pairname)
self.add_cia(op)
# Find .cia files
glob_path = os.path.join(path, '*.cia')
file_list = glob(glob_path)
self.log.debug('File list %s', file_list)
for files in file_list:
from taurex.cia import HitranCIA
pairname = Path(files).stem.split('_')[0]
if pair_filter is not None:
if pairname not in pair_filter:
continue
op = HitranCIA(files)
self.add_cia(op)
def load_cia(self, cia_xsec=None, cia_path=None, pair_filter=None):
"""
Main function to use when loading CIA files. Handles both
cross sections and paths. Handles lists of either so lists of
:class:`~taurex.cia.cia.CIA` objects or lists of paths can be used
to load multiple files/objects
Parameters
----------
cia_xsec : :class:`~taurex.cia.cia.CIA` or :obj:`list` of :class:`~taurex.cia.cia.CIA` , optional
Object(s) to include in cache
cia_path : str or :obj:`list` of str, optional
search path(s) to look for cias
pair_filter : :obj:`list` of str , optional
If provided, the cia will only be loaded
if its pair name is in this list. Mostly used by the
:func:`__getitem__` for filtering
"""
from taurex.cia import CIA
if cia_path is None:
cia_path = self._cia_path
self.log.debug('CIA XSEC, CIA_PATH %s %s', cia_xsec, cia_path)
if cia_xsec is not None:
if isinstance(cia_xsec, (list,)):
self.log.debug('cia passed is list')
for xsec in cia_xsec:
self.add_cia(xsec, pair_filter=pair_filter)
elif isinstance(cia_xsec, CIA):
self.add_cia(cia_xsec, pair_filter=pair_filter)
else:
self.log.error('Unknown type %s passed into cia, should be a list, single \
cia or None if reading a path', type(xsec))
raise Exception('Unknown type passed into cia')
if cia_path is not None:
if isinstance(cia_path, str):
self.load_cia_from_path(cia_path, pair_filter=pair_filter)
elif isinstance(cia_path, (list,)):
for path in cia_path:
self.load_cia_from_path(path, pair_filter=pair_filter)
|
terry-texas-us/Eo | GripPoints/OdGripPointsModule.h | #pragma once
#include "RxModule.h"
#include "StaticRxObject.h"
#include "Db2LineAngularDimGripPoints.h"
#include "Db3PointAngularDimGripPoints.h"
#include "DbAlignedDimGripPoints.h"
#include "DbArcGripPoints.h"
#include "DbArcDimGripPoints.h"
#include "DbDiametricDimGripPoints.h"
#include "DbLineGripPoints.h"
#include "DbPolylineGripPoints.h"
#include "DbEntityGripPoints.h"
#include "DbMlineGripPoints.h"
#include "DbBlockReferenceGripPoints.h"
#include "DbMleaderGripPoints.h"
#include "DbOrdinateDimGripPoints.h"
#include "DbPolygonMeshGripPoints.h"
#include "DbPdfUnderlayGripPoints.h"
#include "DbRadialDimGripPoints.h"
#include "DbRadialDimLargeGripPoints.h"
#include "DbRotatedDimGripPoints.h"
#include "DbViewportGripPoints.h"
#include "Db2dPolylineGripPoints.h"
#include "DbRasterImageGripPoints.h"
#include "DbSolidGripPoints.h"
#include "DbTraceGripPoints.h"
#include "Db3dPolylineGripPoints.h"
#include "DbCameraGripPoints.h"
#include "DbCircleGripPoints.h"
#include "DbEllipseGripPoints.h"
#include "DbTextGripPoints.h"
#include "DbGeoPositionMarkerGripPoints.h"
#include "DbDgnUnderlayGripPoints.h"
#include "DbOleGripPoints.h"
#include "DbWipeOutGripPoints.h"
#include "DbFaceGripPoints.h"
/**
* \brief Declaration of the OdGeGripPointsPE interface. Drawings SDK attempts to use this interface for grip points operations; OdDbEntity::getGripPoints, etc.
*/
class OdGripPointsModule : public OdRxModule {
OdStaticRxObject<OdDbLineGripPointsPE> m_LineGripPoints;
OdStaticRxObject<OdDbMlineGripPointsPE> m_MlineGripPoints;
OdStaticRxObject<OdDbMleaderGripPointsPE> m_MleaderGripPoints;
OdStaticRxObject<OdDbPolygonMeshGripPointsPE> m_PolygonMeshGripPoints;
OdStaticRxObject<OdDbArcGripPointsPE> m_ArcGripPoints;
OdStaticRxObject<OdDbPolylineGripPointsPE> m_PolylineGripPoints;
OdStaticRxObject<OdDbEntityGripPointsPE> m_EntityGripPoints;
OdStaticRxObject<OdDbRotatedDimGripPointsPE> m_RotatedDimGripPoints;
OdStaticRxObject<OdDbAlignedDimGripPointsPE> m_AlignedDimGripPoints;
OdStaticRxObject<OdDbRadialDimGripPointsPE> m_RadialDimGripPoints;
OdStaticRxObject<OdDbDiametricDimGripPointsPE> m_DiametricDimGripPoints;
OdStaticRxObject<OdDb3PointAngularDimGripPointsPE> m_3PointAngularDimGripPoints;
OdStaticRxObject<OdDbOrdinateDimGripPointsPE> m_OrdinateDimGripPoints;
OdStaticRxObject<OdDb2LineAngularDimGripPointsPE> m_2LineAngularDimGripPoints;
OdStaticRxObject<OdDbArcDimGripPointsPE> m_ArcDimGripPoints;
OdStaticRxObject<OdDbRadialDimLargeGripPointsPE> m_RadialDimLargeGripPoints;
OdStaticRxObject<OdDbBlockReferenceGripPointsPE> m_BlockReferenceGripPoints;
OdStaticRxObject<OdDbPdfUnderlayGripPointsPE> m_PdfUnderlayGripPoints;
OdStaticRxObject<OdDbViewportGripPointsPE> m_ViewportGripPoints;
OdStaticRxObject<OdDb2dPolylineGripPointsPE> m_2dPolylineGripPoints;
OdStaticRxObject<OdDbRasterImageGripPointsPE> m_RasterImageGripPoints;
OdStaticRxObject<OdDbTraceGripPointsPE> m_TraceGripPoints;
OdStaticRxObject<OdDbSolidGripPointsPE> m_SolidGripPoints;
OdStaticRxObject<OdDb3dPolylineGripPointsPE> m_3dPolylineGripPoints;
OdStaticRxObject<OdDbCameraGripPointsPE> m_CameraGripPoints;
OdStaticRxObject<OdDbCircleGripPointsPE> m_CircleGripPoints;
OdStaticRxObject<OdDbEllipseGripPointsPE> m_EllipseGripPoints;
OdStaticRxObject<OdDbTextGripPointsPE> m_TextGripPoints;
OdStaticRxObject<OdDbGeoPositionMarkerPE> m_GeoPositionMarkerGripPoints;
OdStaticRxObject<OdDbDgnUnderlayGripPointsPE> m_DgnUnderlayGripPoints;
OdStaticRxObject<OdDbOleGripPointsPE> m_OleGripPoints;
OdStaticRxObject<OdDbWipeOutGripPointsPE> m_WipeOutGripPoints;
OdStaticRxObject<OdDbFaceGripPointsPE> m_FaceGripPoints;
protected:
OdGripPointsModule();
void initApp() override;
void uninitApp() override;
public:
~OdGripPointsModule();
};
/**
* \brief For 2D object projects given offset vector on object's plane defined by normal in current view direction.
* \param database
* \param normal
* \param offset
* \return true on success. If current view direction is perpendicular to normal returns false and does not modify offset
*/
bool ProjectOffset(const OdDbDatabase* database, const OdGeVector3d& normal, OdGeVector3d& offset);
|
scala-steward-bot/rediscala | src/main/scala/redis/RedisCluster.scala | package redis
import java.util.concurrent.ThreadLocalRandom
import java.util.concurrent.TimeUnit
import akka.actor.ActorRef
import akka.actor.ActorSystem
import akka.event.Logging
import akka.util.ByteString
import redis.api.clusters.ClusterNode
import redis.api.clusters.ClusterSlot
import redis.protocol.RedisReply
import redis.util.CRC16
import scala.concurrent.duration.Duration
import scala.concurrent.stm.Ref
import scala.concurrent.Await
import scala.concurrent.Future
import scala.concurrent.Promise
import scala.util.control.NonFatal
case class RedisCluster(redisServers: Seq[RedisServer], name: String = "RedisClientPool")(implicit
_system: ActorSystem,
redisDispatcher: RedisDispatcher = Redis.dispatcher
) extends RedisClientPoolLike(_system, redisDispatcher)
with RedisCommands {
val log = Logging.getLogger(_system, this)
val clusterSlotsRef: Ref[Option[Map[ClusterSlot, RedisConnection]]] = Ref(Option.empty[Map[ClusterSlot, RedisConnection]])
val lockClusterSlots = Ref(true)
override val redisServerConnections = {
redisServers.map { server =>
makeRedisConnection(server, defaultActive = true)
}.toMap
}
refreshConnections()
def equalsHostPort(clusterNode: ClusterNode, server: RedisServer) = {
clusterNode.host == server.host && clusterNode.port == server.port
}
override def onConnectStatus(server: RedisServer, active: Ref[Boolean]): (Boolean) => Unit = { (status: Boolean) =>
{
if (active.single.compareAndSet(!status, status)) {
refreshConnections()
}
clusterSlotsRef.single.get.map { clusterSlots =>
if (clusterSlots.keys.exists(cs => equalsHostPort(cs.master, server))) {
log.info("one master is still dead => refresh clusterSlots")
asyncRefreshClusterSlots()
}
}
}
}
def getClusterSlots(): Future[Map[ClusterSlot, RedisConnection]] = {
def resolveClusterSlots(retry: Int): Future[Map[ClusterSlot, RedisConnection]] = {
clusterSlots().map { clusterSlots =>
clusterSlots.flatMap { clusterSlot =>
val maybeServerConnection = redisServerConnections.find { case (server, _) => equalsHostPort(clusterSlot.master, server) }
maybeServerConnection.map { case (_, redisConnection) => (clusterSlot, redisConnection) }
}.toMap
}.recoverWith { case e =>
if (retry - 1 == 0) {
Future.failed(e)
} else {
resolveClusterSlots(retry - 1)
}
}
}
resolveClusterSlots(3) // retry 3 times
}
def asyncRefreshClusterSlots(force: Boolean = false): Future[Unit] = {
if (force || lockClusterSlots.single.compareAndSet(false, true)) {
try {
getClusterSlots().map { clusterSlot =>
log.info("refreshClusterSlots: " + clusterSlot.toString())
clusterSlotsRef.single.set(Some(clusterSlot))
lockClusterSlots.single.compareAndSet(true, false)
()
}.recoverWith { case NonFatal(e) =>
log.error("refreshClusterSlots:", e)
lockClusterSlots.single.compareAndSet(true, false)
Future.failed(e)
}
} catch {
case NonFatal(e) =>
lockClusterSlots.single.compareAndSet(true, false)
throw e
}
} else {
Future.successful(clusterSlotsRef.single.get)
}
}
protected def send[T](redisConnection: ActorRef, redisCommand: RedisCommand[_ <: RedisReply, T]): Future[T] = {
val promise = Promise[T]()
redisConnection ! Operation(redisCommand, promise)
promise.future
}
def getRedisConnection(slot: Int): Option[RedisConnection] = {
getClusterAndConnection(slot).map { case (_, redisConnection) => redisConnection }
}
def getClusterAndConnection(slot: Int): Option[(ClusterSlot, RedisConnection)] = {
clusterSlotsRef.single.get.flatMap { clusterSlots =>
clusterSlots.find { case (clusterSlot, _) =>
val result = clusterSlot.begin <= slot && slot <= clusterSlot.end
if (result) {
log.debug(s"slot $slot => " + clusterSlot.master.toString)
}
result
}
}
}
val redirectMessagePattern = """(MOVED|ASK) \d+ (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d+)""".r
override def send[T](redisCommand: RedisCommand[_ <: RedisReply, T]): Future[T] = {
val maybeRedisActor: Option[ActorRef] = getRedisActor(redisCommand)
maybeRedisActor.map { redisConnection =>
send(redisConnection, redisCommand).recoverWith {
case e: redis.actors.ReplyErrorException if e.message.startsWith("MOVED") || e.message.startsWith("ASK") =>
e.message match {
// folow the redirect
case redirectMessagePattern(opt, host, port) =>
log.debug("Redirect:" + e.message)
if (opt == "MOVED") {
redisCommand match {
case _: ClusterKey => asyncRefreshClusterSlots()
case _ => log.info(s"Command do not implement ClusterKey : ${redisCommand}")
}
}
redisServerConnections.find { case (server, redisConnection) =>
server.host == host && server.port.toString == port && redisConnection.active.single.get
}.map { case (_, redisConnection) =>
send(redisConnection.actor, redisCommand)
}.getOrElse(Future.failed(new Exception(s"server not found: $host:$port")))
case _ => Future.failed(new Exception("bad exception format:" + e.message))
}
case error => Future.failed(error)
}
}.getOrElse(Future.failed(new RuntimeException("server not found: no server available")))
}
def getRedisActor[T](redisCommand: RedisCommand[_ <: RedisReply, T]): Option[ActorRef] = {
redisCommand match {
case clusterKey: ClusterKey =>
getRedisConnection(clusterKey.getSlot()).filter { _.active.single.get }.map(_.actor)
case _ =>
val redisActors = redisConnectionPool
if (redisActors.nonEmpty) {
// if it is not a cluster command => random connection
// TODO use RoundRobinPoolRequest
Some(redisActors(ThreadLocalRandom.current().nextInt(redisActors.length)))
} else {
None
}
}
}
def groupByCluserServer(keys: Seq[String]): Seq[Seq[String]] = {
keys.groupBy { key =>
getRedisConnection(RedisComputeSlot.hashSlot(key))
}.values.toSeq
}
Await.result(asyncRefreshClusterSlots(force = true), Duration(10, TimeUnit.SECONDS))
}
object RedisComputeSlot {
val MAX_SLOTS = 16384
def hashSlot(key: String) = {
val indexBegin = key.indexOf("{")
val keytag = if (indexBegin != -1) {
val indexEnd = key.indexOf("}", indexBegin)
if (indexEnd != -1) {
key.substring(indexBegin + 1, indexEnd)
} else {
key
}
} else {
key
}
CRC16.crc16(keytag) % MAX_SLOTS
}
}
trait ClusterKey {
def getSlot(): Int
}
object MultiClusterKey {
def getHeadSlot[K](redisKey: ByteStringSerializer[K], keys: Seq[K]): Int = {
RedisComputeSlot.hashSlot(redisKey.serialize(keys.headOption.getOrElse(throw new RuntimeException("operation has not keys"))).utf8String)
}
}
abstract class SimpleClusterKey[K](implicit redisKey: ByteStringSerializer[K]) extends ClusterKey {
val key: K
val keyAsString: ByteString = redisKey.serialize(key)
def getSlot(): Int = RedisComputeSlot.hashSlot(keyAsString.utf8String)
}
abstract class MultiClusterKey[K](implicit redisKey: ByteStringSerializer[K]) extends ClusterKey {
val keys: Seq[K]
def getSlot(): Int = MultiClusterKey.getHeadSlot(redisKey, keys)
}
|
PeterAhern/final-project-start-kit-practice | client/src/Components/Header/Navbar/DropdownItem.styles.js | <filename>client/src/Components/Header/Navbar/DropdownItem.styles.js
import styled from "styled-components";
export const DropdownItemStyles = styled.div`
height: 50px;
display: flex;
align-items: center;
border-radius: var(--border-radius);
transition: background var(--speed);
padding: 0.5rem;
text-decoration: none;
.menuItem:hover {
background-color: #525357;
}
.iconRight {
margin-left: auto;
}
.navIcon {
--button-size: calc(var(--nav-size) * 0.8);
width: var(--button-size);
height: var(--button-size);
background-color: rgba(209, 46, 46, 0.685);
border-radius: 50%;
padding: 5px;
margin: 2px;
display: flex;
align-items: center;
justify-content: center;
transition: filter 300ms;
}
`;
|
6freeair2016/incubator-shenyu | shenyu-examples/shenyu-examples-websocket/shenyu-example-spring-native-websocket/src/main/java/org/apache/shenyu/examples/websocket/handler/HttpAuthHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package org.apache.shenyu.examples.websocket.handler;
import org.apache.shenyu.examples.websocket.config.WsSessionManager;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.time.LocalDateTime;
/**
* HttpAuthHandler.
*/
@Component
public class HttpAuthHandler extends TextWebSocketHandler {
/**
* socket create a success event.
*
* @param session
* @throws Exception
*/
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
Object token = session.getAttributes().get("token");
if (token != null) {
// The user is successfully connected and put into the online user cache.
WsSessionManager.add(token.toString(), session);
} else {
throw new RuntimeException("User login has expired!");
}
}
/**
* Receive message events.
*
* @param session
* @param message
* @throws Exception
*/
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// Get the message from the client.
String payload = message.getPayload();
Object token = session.getAttributes().get("token");
System.out.println("server received " + token + " sent " + payload);
session.sendMessage(new TextMessage("apache shenyu server send to " + token + " message : -> " + payload));
}
/**
* when socket disconnected.
*
* @param session
* @param status
* @throws Exception
*/
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
Object token = session.getAttributes().get("token");
if (token != null) {
// The user exits and removes the cache.
WsSessionManager.remove(token.toString());
}
}
} |
jiangjianli/qianyueweb | vue-element-admin/node_modules/vue-loader/lib/loaders/pitcher.js | const qs = require('querystring')
const loaderUtils = require('loader-utils')
const hash = require('hash-sum')
const selfPath = require.resolve('../index')
const templateLoaderPath = require.resolve('./templateLoader')
const stylePostLoaderPath = require.resolve('./stylePostLoader')
const isESLintLoader = l => /(\/|\\|@)eslint-loader/.test(l.path)
const isNullLoader = l => /(\/|\\|@)null-loader/.test(l.path)
const isCSSLoader = l => /(\/|\\|@)css-loader/.test(l.path)
const isPitcher = l => l.path !== __filename
const dedupeESLintLoader = loaders => {
const res = []
let seen = false
loaders.forEach(l => {
if (!isESLintLoader(l)) {
res.push(l)
} else if (!seen) {
seen = true
res.push(l)
}
})
return res
}
module.exports = code => code
// This pitching loader is responsible for intercepting all vue block requests
// and transform it into appropriate requests.
module.exports.pitch = function (remainingRequest) {
const options = loaderUtils.getOptions(this)
const { cacheDirectory, cacheIdentifier } = options
const query = qs.parse(this.resourceQuery.slice(1))
let loaders = this.loaders
// if this is a language block request, eslint-loader may get matched
// multiple times
if (query.type) {
// if this is an inline block, since the whole file itself is being linted,
// remove eslint-loader to avoid duplicate linting.
if (/\.vue$/.test(this.resourcePath)) {
loaders = loaders.filter(l => !isESLintLoader(l))
} else {
// This is a src import. Just make sure there's not more than 1 instance
// of eslint present.
loaders = dedupeESLintLoader(loaders)
}
}
// remove self
loaders = loaders.filter(isPitcher)
// do not inject if user uses null-loader to void the type (#1239)
if (loaders.some(isNullLoader)) {
return
}
const genRequest = loaders => {
// Important: dedupe since both the original rule
// and the cloned rule would match a source import request.
// also make sure to dedupe based on loader path.
// assumes you'd probably never want to apply the same loader on the same
// file twice.
const seen = new Map()
const loaderStrings = []
loaders.forEach(loader => {
const type = typeof loader === 'string' ? loader : loader.path
const request = typeof loader === 'string' ? loader : loader.request
if (!seen.has(type)) {
seen.set(type, true)
// loader.request contains both the resolved loader path and its options
// query (e.g. ??ref-0)
loaderStrings.push(request)
}
})
return loaderUtils.stringifyRequest(this, '-!' + [
...loaderStrings,
this.resourcePath + this.resourceQuery
].join('!'))
}
// Inject style-post-loader before css-loader for scoped CSS and trimming
if (query.type === `style`) {
const cssLoaderIndex = loaders.findIndex(isCSSLoader)
if (cssLoaderIndex > -1) {
const afterLoaders = loaders.slice(0, cssLoaderIndex + 1)
const beforeLoaders = loaders.slice(cssLoaderIndex + 1)
const request = genRequest([
...afterLoaders,
stylePostLoaderPath,
...beforeLoaders
])
// console.log(request)
return `import mod from ${request}; export default mod; export * from ${request}`
}
}
// for templates: inject the template compiler & optional cache
if (query.type === `template`) {
const path = require('path')
const cacheLoader = cacheDirectory && cacheIdentifier
? [`cache-loader?${JSON.stringify({
// For some reason, webpack fails to generate consistent hash if we
// use absolute paths here, even though the path is only used in a
// comment. For now we have to ensure cacheDirectory is a relative path.
cacheDirectory: path.isAbsolute(cacheDirectory)
? path.relative(process.cwd(), cacheDirectory)
: cacheDirectory,
cacheIdentifier: hash(cacheIdentifier) + '-vue-loader-template'
})}`]
: []
const request = genRequest([
...cacheLoader,
templateLoaderPath + `??vue-loader-options`,
...loaders
])
// console.log(request)
// the template compiler uses esm exports
return `export * from ${request}`
}
// if a custom block has no other matching loader other than vue-loader itself,
// we should ignore it
if (query.type === `custom` &&
loaders.length === 1 &&
loaders[0].path === selfPath) {
return ``
}
// When the user defines a rule that has only resourceQuery but no test,
// both that rule and the cloned rule will match, resulting in duplicated
// loaders. Therefore it is necessary to perform a dedupe here.
const request = genRequest(loaders)
return `import mod from ${request}; export default mod; export * from ${request}`
}
|
UranusBlockStack/ovirt-engine | backend/manager/modules/builtin-extensions/src/main/java/org/ovirt/engine/extensions/aaa/builtin/kerberosldap/SearchLangageLDAPTokens.java | <reponame>UranusBlockStack/ovirt-engine
package org.ovirt.engine.extensions.aaa.builtin.kerberosldap;
public enum SearchLangageLDAPTokens {
$GIVENNAME,
$USER_ACCOUNT_TYPE,
$PRINCIPAL_NAME,
$LDAP_GROUP_CATEGORY,
$CN,
$USER_ACCOUNT_NAME,
$SAMACCOUNTNAME,
$SN,
$DEPARTMENT,
$TITLE,
$USER_ID,
$GROUP_ID,
}
|
Graph-ICS/Graph-ICS | src/nodes/image.h | #ifndef IMAGE_H
#define IMAGE_H
#include "node.h"
class Image : public Node
{
Q_OBJECT
public:
explicit Image();
bool retrieveResult();
};
#endif // IMAGE_H
|
pec1985/go-clubhouse | api/models/Group.go | <reponame>pec1985/go-clubhouse
package models
// Group a Group.
type Group struct {
// AppURL the Clubhouse application url for the Group.
AppURL string `json:"app_url,omitempty"`
// Archived whether or not the Group is archived.
Archived bool `json:"archived,omitempty"`
// Description the description of the Group.
Description string `json:"description,omitempty"`
DisplayIcon *Icon `json:"display_icon,omitempty"`
// EntityType a string description of this resource.
EntityType string `json:"entity_type,omitempty"`
// ID the id of the Group.
ID string `json:"id,omitempty"`
// MemberIDs the Member IDs contain within the Group.
MemberIDs []string `json:"member_ids,omitempty"`
// MentionName the mention name of the Group.
MentionName string `json:"mention_name,omitempty"`
// Name the name of the Group.
Name string `json:"name,omitempty"`
}
func (m *Group) Stringify() string {
b, _ := toPayload(m, false)
return string(b)
}
func (m *Group) StringifyPretty() string {
b, _ := toPayload(m, true)
return string(b)
}
|
TOT0RoKR/tensorflow | tensorflow/core/data/service/test_util.cc | /* Copyright 2020 The TensorFlow 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.
==============================================================================*/
#include "tensorflow/core/data/service/test_util.h"
#include <string>
#include <vector>
#include "tensorflow/core/data/dataset_test_base.h"
#include "tensorflow/core/data/service/common.pb.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/path.h"
#include "tensorflow/core/platform/statusor.h"
namespace tensorflow {
namespace data {
namespace testing {
namespace {
constexpr char kTestdataDir[] =
"tensorflow/core/data/service/testdata";
// Proto content generated by
//
// import tensorflow as tf
//
// ds = tf.data.Dataset.range(10)
// ds = ds.map(lambda x: x*x)
// g = tf.compat.v1.GraphDef()
// g.ParseFromString(ds._as_serialized_graph().numpy())
// print(g)
// TODO(yangchen): Make proto generation dynamic.
constexpr char kMapGraphDefFile[] = "map_graph_def.pbtxt";
} // namespace
StatusOr<DatasetDef> RangeSquareDataset(const int64 range) {
DatasetDef dataset_def;
std::string filepath = io::JoinPath(kTestdataDir, kMapGraphDefFile);
TF_RETURN_IF_ERROR(
ReadTextProto(Env::Default(), filepath, dataset_def.mutable_graph()));
(*dataset_def.mutable_graph()->mutable_node(1)->mutable_attr())["value"]
.mutable_tensor()
->set_int64_val(0, range);
return dataset_def;
}
} // namespace testing
} // namespace data
} // namespace tensorflow
|
ipublic/marketplace | app/models/determinations/pfl_liability_determination.rb | class Determinations::PflLiabilityDetermination
include Mongoid::Document
end
|
wallamejorge/WirelessSensorGas | rtl/wirelessUSBDrivers/Linux/2010_0709_RT2870_Linux_STA_v2.4.0.1/include/crypt_aes.h | <reponame>wallamejorge/WirelessSensorGas
/*
*************************************************************************
* Ralink Tech Inc.
* 5F., No.36, Taiyuan St., Jhubei City,
* Hsinchu County 302,
* Taiwan, R.O.C.
*
* (c) Copyright 2002-2007, Ralink Technology, Inc.
*
* This program 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 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
*************************************************************************/
#ifndef __CRYPT_AES_H__
#define __CRYPT_AES_H__
#include "rt_config.h"
/*
//#undef SWAP32
//#define SWAP32(x) \
// ((unsigned long)( \
// (((unsigned long)(x) & (unsigned long) 0x000000ffUL) << 24) | \
// (((unsigned long)(x) & (unsigned long) 0x0000ff00UL) << 8) | \
// (((unsigned long)(x) & (unsigned long) 0x00ff0000UL) >> 8) | \
// (((unsigned long)(x) & (unsigned long) 0xff000000UL) >> 24) ))
*/
#define GETU32(p) cpu2be32(get_unaligned((u32 *) (p)))
#define PUTU32(ct, st) put_unaligned(cpu2be32(st), (u32*)(ct)) //{ *((u32 *)(ct)) = cpu2be32((st)); }
#define AES_ENCRYPT 1
#define AES_DECRYPT 0
/* Because array size can't be a const in C, the following two are macros.
Both sizes are in bytes. */
#define AES_MAXNR 14
#define AES_BLOCK_SIZE 16
/* This should be a hidden type, but EVP requires that the size be known */
struct aes_key_st {
#ifdef AES_LONG
unsigned long rd_key[4 *(AES_MAXNR + 1)];
#else
unsigned int rd_key[4 *(AES_MAXNR + 1)];
#endif
int rounds;
};
typedef struct aes_key_st AES_KEY;
typedef struct _EVP_CIPHER_CTX_ {
unsigned long flag;
unsigned long type;
unsigned long encrypt; //1: Encrypt 0: Decrypt,
unsigned char key[16];
unsigned char iv[8 + 16];
unsigned long bufferlen;
unsigned char buffer[AES_BLOCK_SIZE];
AES_KEY aesKey;
} EVP_CIPHER_CTX, *PEVP_CIPHER_CTX;
void evp_aes_encrypt(const unsigned char *in, unsigned char *out, const AES_KEY *key);
void evp_aes_decrypt(const unsigned char *in, unsigned char *out, const AES_KEY *key);
int AES_set_encrypt_key(const unsigned char *userKey, const int bits, AES_KEY *key);
int AES_set_decrypt_key(const unsigned char *userKey, const int bits, AES_KEY *key);
int EVP_aes_128_cbc(void);
int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, int type, unsigned char *key, unsigned char *iv);
int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *outbuf, int *outlen, unsigned char *inbuf, int inlen);
int EVP_EncryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *outbuf, int *outlen);
int EVP_DecryptInit(EVP_CIPHER_CTX *ctx, int type, unsigned char *key, unsigned char *iv);
int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *outbuf, int *outlen, unsigned char *inbuf, int inlen);
int EVP_DecryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *outbuf, int *outlen);
void evp_aes_cbc_encrypt(const unsigned char *in, unsigned char *out,
const unsigned long length, const AES_KEY *key,
unsigned char *ivec, const int enc);
void WscEncryptData(
unsigned char *plainText, int ptx_len,
unsigned char *key, unsigned char *iv,
unsigned char *cipherText, int *ctx_len);
void WscDecryptData(
unsigned char *cipherText, int ctx_len,
unsigned char *key, unsigned char *iv,
unsigned char *plainText, int *ptx_len);
#define AES_CBC_Encrypt(Plain, PlainL, Key, KeyL, IV, IVL, Cipher, CipherL) \
WscEncryptData((Plain), (PlainL), (Key), (IV), (Cipher), (int *) (CipherL));
#define AES_CBC_Decrypt(Cipher, CipherL, Key, KeyL, IV, IVL, Plain, PlainL) \
WscDecryptData((Cipher), (CipherL), (Key), (IV), (Plain), (int *) (PlainL));
typedef struct
{
uint32 erk[64]; /* encryption round keys */
uint32 drk[64]; /* decryption round keys */
int nr; /* number of rounds */
}
aes_context;
int rtmp_aes_set_key( aes_context *ctx, uint8 *key, int nbits );
void rtmp_aes_encrypt( aes_context *ctx, uint8 input[16], uint8 output[16] );
void rtmp_aes_decrypt( aes_context *ctx, uint8 input[16], uint8 output[16] );
VOID AES_GTK_KEY_WRAP(
IN UCHAR *key,
IN UCHAR *plaintext,
IN UINT p_len,
OUT UCHAR *ciphertext,
OUT UINT *c_len);
VOID AES_GTK_KEY_UNWRAP(
IN UCHAR *key,
OUT UCHAR *plaintext,
OUT UINT *p_len,
IN UCHAR *ciphertext,
IN UINT c_len);
#define AES_Key_Wrap(Plain, PlainL, Key, KeyL, Cipher, CipherL) \
AES_GTK_KEY_WRAP((Key), (Plain), (PlainL), (Cipher), (CipherL))
#define AES_Key_Unwrap(Cipher, CipherL, Key, KeyL, Plain, PlainL) \
AES_GTK_KEY_UNWRAP((Key), (Plain), (PlainL), (Cipher), (CipherL))
/* AES definition & structure */
#define AES_STATE_ROWS 4 /* Block size: 4*4*8 = 128 bits */
#define AES_STATE_COLUMNS 4
#define AES_BLOCK_SIZES AES_STATE_ROWS*AES_STATE_COLUMNS
#define AES_KEY_ROWS 4
#define AES_KEY_COLUMNS 8 /*Key length: 4*{4,6,8}*8 = 128, 192, 256 bits */
#define AES_KEY128_LENGTH 16
#define AES_KEY192_LENGTH 24
#define AES_KEY256_LENGTH 32
#define AES_CBC_IV_LENGTH 16
typedef struct {
UINT8 State[AES_STATE_ROWS][AES_STATE_COLUMNS];
UINT8 KeyWordExpansion[AES_KEY_ROWS][AES_KEY_ROWS*((AES_KEY256_LENGTH >> 2) + 6 + 1)];
} AES_CTX_STRUC, *PAES_CTX_STRUC;
/* AES operations */
VOID RT_AES_KeyExpansion (
IN UINT8 Key[],
IN UINT KeyLength,
INOUT AES_CTX_STRUC *paes_ctx);
VOID RT_AES_Encrypt (
IN UINT8 PlainBlock[],
IN UINT PlainBlockSize,
IN UINT8 Key[],
IN UINT KeyLength,
OUT UINT8 CipherBlock[],
INOUT UINT *CipherBlockSize);
VOID RT_AES_Decrypt (
IN UINT8 CipherBlock[],
IN UINT CipherBlockSize,
IN UINT8 Key[],
IN UINT KeyLength,
OUT UINT8 PlainBlock[],
INOUT UINT *PlainBlockSize);
/* AES Counter with CBC-MAC operations */
VOID AES_CCM_MAC (
IN UINT8 Payload[],
IN UINT PayloadLength,
IN UINT8 Key[],
IN UINT KeyLength,
IN UINT8 Nonce[],
IN UINT NonceLength,
IN UINT8 AAD[],
IN UINT AADLength,
IN UINT MACLength,
OUT UINT8 MACText[]);
INT AES_CCM_Encrypt (
IN UINT8 PlainText[],
IN UINT PlainTextLength,
IN UINT8 Key[],
IN UINT KeyLength,
IN UINT8 Nonce[],
IN UINT NonceLength,
IN UINT8 AAD[],
IN UINT AADLength,
IN UINT MACLength,
OUT UINT8 CipherText[],
INOUT UINT *CipherTextLength);
INT AES_CCM_Decrypt (
IN UINT8 CipherText[],
IN UINT CipherTextLength,
IN UINT8 Key[],
IN UINT KeyLength,
IN UINT8 Nonce[],
IN UINT NonceLength,
IN UINT8 AAD[],
IN UINT AADLength,
IN UINT MACLength,
OUT UINT8 PlainText[],
INOUT UINT *PlainTextLength);
/* AES-CMAC operations */
VOID AES_CMAC_GenerateSubKey (
IN UINT8 Key[],
IN UINT KeyLength,
OUT UINT8 SubKey1[],
OUT UINT8 SubKey2[]);
VOID AES_CMAC (
IN UINT8 PlainText[],
IN UINT PlainTextLength,
IN UINT8 Key[],
IN UINT KeyLength,
OUT UINT8 MACText[],
INOUT UINT *MACTextLength);
#endif /* __CRYPT_AES_H__ */
|
rafidude/100DaysOfCode | 1Library/csvFileParser.go | <reponame>rafidude/100DaysOfCode<filename>1Library/csvFileParser.go
package main
import (
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
)
func main() {
ReadCSVFile("LifeTable.csv", ",")
}
// The objective of this function is to read a CSV file into memory
// Then parse each line by a separator and output data as an
// array of arrays
func ReadCSVFileMemory(fileName, separator string) [][]float64 {
dat, err := ioutil.ReadFile(fileName)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
larr := make([]string, 120)
male := make([]float64, 120)
female := make([]float64, 120)
darr := strings.Split(string(dat), "\n")
for i, v := range darr {
larr = strings.Split(v, ",")
male[i], _ = strconv.ParseFloat(larr[3], 64)
female[i], _ = strconv.ParseFloat(larr[6], 64)
}
return male, female
}
|
gregmolnar/energy-sparks | db/migrate/2019-phase-3-milestone-9/20190918141133_add_pupil_analysis_to_school_configuration.rb | <filename>db/migrate/2019-phase-3-milestone-9/20190918141133_add_pupil_analysis_to_school_configuration.rb
class AddPupilAnalysisToSchoolConfiguration < ActiveRecord::Migration[6.0]
def change
add_column :configurations, :pupil_analysis_charts, :json, default: {}, null: false
end
end
|
jmittert/cpp-docs | docs/mfc/codesnippet/CPP/cdaorecordset-class_7.cpp | <gh_stars>10-100
SetFieldDirty(&m_strParam); |
sotaoverride/backup | openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/util-linux/2.33.2-r0/util-linux-2.33.2/libblkid/src/partitions/atari.c | /*
* atari partitions parsing code
*
* Copyright (C) 2018 <NAME> <<EMAIL>>
*
* This file may be redistributed under the terms of the
* GNU Lesser General Public License.
*
* Based on Linux kernel implementation and atari-fdisk
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "partitions.h"
struct atari_part_def
{
/*
* flags:
* 0 (LSB): active
* 1-6: (reserved)
* 7 (MSB): bootable
*/
unsigned char flags;
char id[3];
uint32_t start;
uint32_t size;
} __attribute__((packed));
struct atari_rootsector
{
char unused0[0x156]; /* boot code */
struct atari_part_def icd_part[8]; /* ICD partition entries */
char unused1[0xc];
uint32_t hd_size;
struct atari_part_def part[4]; /* primary partition entries */
uint32_t bsl_start; /* bad sector list start */
uint32_t bsl_len; /* bad sector list length */
uint16_t checksum;
} __attribute__((packed));
/*
* Generated using linux kernel ctype.{c,h}
*
* Since kernel uses isalnum() to detect whether it is Atari PT, we need same
* definition of alnum character to be consistent with kernel.
*/
static const unsigned char _linux_isalnum[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1};
static int linux_isalnum(unsigned char c)
{
return _linux_isalnum[c];
}
#define isalnum linux_isalnum
#define IS_ACTIVE(partdef) ((partdef).flags & 1)
#define IS_PARTDEF_VALID(partdef, hdsize) \
((partdef).flags & 1 && isalnum((partdef).id[0]) && \
isalnum((partdef).id[1]) && isalnum((partdef).id[2]) && \
be32_to_cpu((partdef).start) <= (hdsize) && \
be32_to_cpu((partdef).start) + be32_to_cpu((partdef).size) <= (hdsize))
static int is_id_common(char* id)
{
const char* ids[] = {
"GEM", "BGM", "LNX", "SWP", "RAW",
};
unsigned i;
for (i = 0; i < ARRAY_SIZE(ids); i++)
{
if (!memcmp(ids[i], id, 3))
return 1;
}
return 0;
}
static int parse_partition(blkid_partlist ls, blkid_parttable tab,
struct atari_part_def* part, uint32_t offset)
{
blkid_partition par;
uint32_t start;
uint32_t size;
start = be32_to_cpu(part->start) + offset;
size = be32_to_cpu(part->size);
if (blkid_partlist_get_partition_by_start(ls, start))
{
/* Don't increment partno for extended parts */
if (!offset)
blkid_partlist_increment_partno(ls);
return 0;
}
par = blkid_partlist_add_partition(ls, tab, start, size);
if (!par)
return -ENOMEM;
blkid_partition_set_type_string(par, (unsigned char*)part->id,
sizeof(part->id));
return 1;
}
/*
* \return 1: OK, 0: bad format or -errno
*/
static int parse_extended(blkid_probe pr, blkid_partlist ls,
blkid_parttable tab, struct atari_part_def* part)
{
uint32_t x0start, xstart;
unsigned i = 0;
int rc;
x0start = xstart = be32_to_cpu(part->start);
while (1)
{
struct atari_rootsector* xrs;
xrs = (struct atari_rootsector*)blkid_probe_get_sector(pr, xstart);
if (!xrs)
{
if (errno)
return -errno;
return 0;
}
/*
* There must be data partition followed by reference to next
* XGM or inactive entry.
*/
for (i = 0;; i++)
{
if (i >= ARRAY_SIZE(xrs->part) - 1)
return 0;
if (IS_ACTIVE(xrs->part[i]))
break;
}
if (!memcmp(xrs->part[i].id, "XGM", 3))
return 0;
rc = parse_partition(ls, tab, &xrs->part[i], xstart);
if (rc <= 0)
return rc;
if (!IS_ACTIVE(xrs->part[i + 1]))
break;
if (memcmp(xrs->part[i + 1].id, "XGM", 3))
return 0;
xstart = x0start + be32_to_cpu(xrs->part[i + 1].start);
}
return 1;
}
static int probe_atari_pt(blkid_probe pr, const struct blkid_idmag* mag
__attribute__((__unused__)))
{
struct atari_rootsector* rs;
blkid_parttable tab = NULL;
blkid_partlist ls;
unsigned i;
int has_xgm = 0;
int rc = 0;
off_t hdsize;
/* Atari partition is not defined for other sector sizes */
if (blkid_probe_get_sectorsize(pr) != 512)
goto nothing;
rs = (struct atari_rootsector*)blkid_probe_get_sector(pr, 0);
if (!rs)
{
if (errno)
return -errno;
goto nothing;
}
hdsize = blkid_probe_get_size(pr) / 512;
/* Look for validly looking primary partition */
for (i = 0;; i++)
{
if (i >= ARRAY_SIZE(rs->part))
goto nothing;
if (IS_PARTDEF_VALID(rs->part[i], hdsize))
{
blkid_probe_set_magic(
pr, offsetof(struct atari_rootsector, part[i]),
sizeof(rs->part[i].flags) + sizeof(rs->part[i].id),
(unsigned char*)&rs->part[i]);
break;
}
}
if (blkid_partitions_need_typeonly(pr))
/* caller does not ask for details about partitions */
return BLKID_PROBE_OK;
ls = blkid_probe_get_partlist(pr);
if (!ls)
goto nothing;
tab = blkid_partlist_new_parttable(ls, "atari", 0);
if (!tab)
goto err;
for (i = 0; i < ARRAY_SIZE(rs->part); i++)
{
struct atari_part_def* p = &rs->part[i];
if (!IS_ACTIVE(*p))
{
blkid_partlist_increment_partno(ls);
continue;
}
if (!memcmp(p->id, "XGM", 3))
{
has_xgm = 1;
rc = parse_extended(pr, ls, tab, p);
}
else
{
rc = parse_partition(ls, tab, p, 0);
}
if (rc < 0)
return rc;
}
/* if there are no XGM partitions, we can try ICD format */
/* if first ICD partition ID is not valid, assume no ICD format */
if (!has_xgm && is_id_common(rs->icd_part[0].id))
{
for (i = 0; i < ARRAY_SIZE(rs->icd_part); i++)
{
struct atari_part_def* p = &rs->icd_part[i];
if (!IS_ACTIVE(*p) || !is_id_common(p->id))
{
blkid_partlist_increment_partno(ls);
continue;
}
rc = parse_partition(ls, tab, p, 0);
if (rc < 0)
return rc;
}
}
return BLKID_PROBE_OK;
nothing:
return BLKID_PROBE_NONE;
err:
return -ENOMEM;
}
const struct blkid_idinfo atari_pt_idinfo = {
.name = "atari", .probefunc = probe_atari_pt, .magics = BLKID_NONE_MAGIC};
|
MrDeym/DesInventar | src/org/lared/desinventar/webobject/MetadataNationalValues.java | //PACKAGE NAME
package org.lared.desinventar.webobject;
import java.io.*;
import java.util.*;
import java.sql.*;
import java.math.*;
import java.text.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
//CLASS NAME
// generated by WebObjectGenerator...
public class MetadataNationalValues extends webObject
{
// public int dbType=Sys.iDatabaseType;
// DATA MEMBERS OF THE CLASS. THEY ARE EXACT MAPPING OF DB. RECORD.
public int metadata_key;
public String metadata_country;
public int metadata_year;
public double metadata_value;
public double metadata_value_us;
/**
* creates a hash table with field values of the data members
*
*/
public void updateHashTable() {
// FIELD NAMES VECTOR
asFieldNames.put("metadata_key", String.valueOf(metadata_key));
asFieldNames.put("metadata_country", metadata_country);
asFieldNames.put("metadata_year", String.valueOf(metadata_year));
asFieldNames.put("metadata_value", String.valueOf(metadata_value));
asFieldNames.put("metadata_value_us", String.valueOf(metadata_value_us));
}
/**
* update data members with values stored in hash table
*
*/
public void updateMembersFromHashTable() {
// REVERSE FIELD NAMES VECTOR
setMetadata_key((String)asFieldNames.get("metadata_key"));
setMetadata_country((String)asFieldNames.get("metadata_country"));
setMetadata_year((String)asFieldNames.get("metadata_year"));
setMetadata_value((String)asFieldNames.get("metadata_value"));
setMetadata_value_us((String)asFieldNames.get("metadata_value_us"));
}
/**
* constructor of the class. it initialises the object variables
*
*/
// CONSTRUCTOR
public void init() {
lastError="No errors detected";
metadata_key = 0;
metadata_country = "";
metadata_year = 0;
metadata_value = 0;
metadata_value_us = 0;
updateHashTable();
}
public MetadataNationalValues() {
super("MetadataNationalValues object");
init();
}
//--------------------------------------------------------------------------------
// getter and setter methods of the elements of the class
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// Access methods for database field 'metadata_key'
public String getMetadata_key() {
return Integer.toString(metadata_key);
}
public void setMetadata_key(String sParameter) {
metadata_key = extendedParseInt(sParameter);
}
public void setMetadata_key(int sParameter) {
metadata_key = sParameter;
}
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// Access methods for database field 'metadata_country'
public String getMetadata_country() {
return metadata_country;
}
public void setMetadata_country(String sParameter) {
metadata_country = sParameter;
}
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// Access methods for database field 'metadata_year'
public String getMetadata_year() {
return Integer.toString(metadata_year);
}
public void setMetadata_year(String sParameter) {
metadata_year = extendedParseInt(sParameter);
}
public void setMetadata_year(int sParameter) {
metadata_year = sParameter;
}
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// Access methods for database field 'metadata_value'
public String getMetadata_value() {
return Double.toString(metadata_value);
}
public void setMetadata_value(String sParameter) {
metadata_value = extendedParseDouble(sParameter);
}
public void setMetadata_value(double sParameter) {
metadata_value = sParameter;
}
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// Access methods for database field 'metadata_value_us'
public String getMetadata_value_us() {
return Double.toString(metadata_value_us);
}
public void setMetadata_value_us(String sParameter) {
metadata_value_us = extendedParseDouble(sParameter);
}
public void setMetadata_value_us(double sParameter) {
metadata_value_us = sParameter;
}
//--------------------------------------------------------------------------------
//----------------------------------------------------------------
// Operational methods any webObject must have. Abstract class
// provides templates and default behaviour (return error)
//----------------------------------------------------------------
/**
* retrieves object info from HTML form fields
*
*/
public int getForm(HttpServletRequest req, HttpServletResponse resp, Connection con) {
// GET_FORM()
setMetadata_key(req.getParameter(assignName("metadata_key")));
setMetadata_country(not_null(req.getParameter(assignName("metadata_country"))));
setMetadata_year(req.getParameter(assignName("metadata_year")));
setMetadata_value(req.getParameter(assignName("metadata_value")));
setMetadata_value_us(req.getParameter(assignName("metadata_value_us")));
updateHashTable();
return 0;
}
/**
* retrieves object info from HTML form fields
*
*/
public int getForm(ServletRequest req, ServletResponse resp, Connection con) {
// GET_FORM()
setMetadata_key(req.getParameter(assignName("metadata_key")));
setMetadata_country(not_null(req.getParameter(assignName("metadata_country"))));
setMetadata_year(req.getParameter(assignName("metadata_year")));
setMetadata_value(req.getParameter(assignName("metadata_value")));
setMetadata_value_us(req.getParameter(assignName("metadata_value_us")));
updateHashTable();
return 0;
}
/**
* loads an object from a record read from database
*
*/
public void loadWebObject(ResultSet rset) {
try {
// SQL_LOAD
try {
metadata_key = rset.getInt("metadata_key");
} catch (Exception ex) {
lastError = "<-- error attempting to access field metadata_key -->";
System.out.println(ex.toString());
}
try {
metadata_country = not_null(rset.getString("metadata_country"));
} catch (Exception ex) {
lastError = "<-- error attempting to access field metadata_country -->";
System.out.println(ex.toString());
}
try {
metadata_year = rset.getInt("metadata_year");
} catch (Exception ex) {
lastError = "<-- error attempting to access field metadata_year -->";
System.out.println(ex.toString());
}
try {
metadata_value = rset.getDouble("metadata_value");
} catch (Exception ex) {
lastError = "<-- error attempting to access field metadata_value -->";
System.out.println(ex.toString());
}
try {
metadata_value_us = rset.getDouble("metadata_value_us");
} catch (Exception ex) {
lastError = "<-- error attempting to access field metadata_value_us -->";
System.out.println(ex.toString());
}
} catch (Exception e) {
lastError = "<!-- Error loading WebObject: " + e.toString() + " : " + sSql + " -->";
}
updateHashTable();
}
/**
* reads an object from the database
*
*/
public int getWebObject(Connection con)
{
int nrows = 0;
try {
// SQL_GET
int f=1;
sSql = "SELECT * FROM metadata_national_values";
sSql += " WHERE (metadata_key = ?) AND (metadata_country = ?) AND (metadata_year = ?)";
pstmt = con.prepareStatement(sSql);
pstmt.setInt(f++, metadata_key);
if (metadata_country==null || metadata_country.length() == 0)
pstmt.setNull(f++, Types.VARCHAR);
else
pstmt.setString(f++, metadata_country);
pstmt.setInt(f++, metadata_year); rset = pstmt.executeQuery();
if (rset.next()) {
loadWebObject(rset);
nrows = 1;
}
// releases the statement object
rset.close();
pstmt.close();
lastError = ""; // "NO ERROR. sql="+sSql;
} catch (Exception ex) {
//Trap and report SQL errors
lastError = "<!-- Error getting webObject: " + ex.toString() + " : " + sSql + " -->";
nrows = -1;
}
finally {
// releases the statement object
try { pstmt.close(); } catch (Exception ignrd) {}
}
return nrows;
}
/**
* checks the lengths of strings are <= to what is defined in the database
*
*/
public void checkLengths()
{
// CHECK_LENGTHS
if (metadata_country.length()>10)
metadata_country=metadata_country.substring(0,10);
}
/**
* adds a new object to the database
*
*/
public int addWebObject(Connection con)
{
int nrows = 0;
try {
// SQL_INSERT
int f=1;
sSql = "insert into metadata_national_values (";
sSql += "metadata_key, metadata_country, metadata_year, metadata_value";
sSql += ", metadata_value_us)";
sSql += "VALUES (?, ?, ?, ?, ?)";
pstmt = con.prepareStatement(sSql);
pstmt.setInt(f++, metadata_key);
if (metadata_country==null || metadata_country.length()==0)
pstmt.setNull(f++, java.sql.Types.VARCHAR);
else
pstmt.setString(f++, metadata_country);
pstmt.setInt(f++, metadata_year);
pstmt.setDouble(f++, metadata_value);
pstmt.setDouble(f++, metadata_value_us);
nrows = pstmt.executeUpdate();
lastError = ""; // "NO ERROR. sql="+sSql;
} catch (Exception ex) {
//Trap and report SQL errors
System.out.println("ERROR (adding web object): "+ex.toString());
lastError = "<!-- Error adding webObject: " + ex.toString() + " : " + sSql + " -->";
nrows=-1;
}
finally {
// releases the statement object
try { pstmt.close(); } catch (Exception ignrd) {}
}
return nrows;
}
/**
* updates an existing object in the database
*
*/
public int updateWebObject(Connection con)
{
int nrows = 0;
try {
// SQL_UPDATE
int f=1;
sSql = "UPDATE metadata_national_values SET ";
sSql += "metadata_value = ?";
sSql += ", metadata_value_us = ?";
sSql += " WHERE (metadata_key = ?) AND (metadata_country = ?) AND (metadata_year = ?)";
pstmt = con.prepareStatement(sSql);
pstmt.setDouble(f++, metadata_value);
pstmt.setDouble(f++, metadata_value_us);
pstmt.setInt(f++, metadata_key);
if (metadata_country==null || metadata_country.length() == 0)
pstmt.setNull(f++, Types.VARCHAR);
else
pstmt.setString(f++, metadata_country);
pstmt.setInt(f++, metadata_year);
nrows = pstmt.executeUpdate();
lastError = ""; // "NO ERROR. sql="+sSql;
} catch (Exception ex) {
//Trap and report SQL errors
lastError = "<!-- Error updating webObject: " + ex.toString() + " : " + sSql + " -->";
nrows=-1;
}
finally {
// releases the statement object
try { pstmt.close(); } catch (Exception ignrd) {}
}
return nrows;
}
/**
* deletes an existing object in the database
*
*/
public int deleteWebObject(Connection con)
{
int nrows = 0;
try {
// SQL_DELETE
int f=1;
sSql = "DELETE FROM metadata_national_values";
sSql += " WHERE (metadata_key = ?) AND (metadata_country = ?) AND (metadata_year = ?)";
pstmt = con.prepareStatement(sSql);
pstmt.setInt(f++, metadata_key);
if (metadata_country==null || metadata_country.length() == 0)
pstmt.setNull(f++, Types.VARCHAR);
else
pstmt.setString(f++, metadata_country);
pstmt.setInt(f++, metadata_year);
nrows = pstmt.executeUpdate();
lastError = ""; // "NO ERROR. sql="+sSql;
} catch (Exception ex) {
//Trap and report SQL errors
lastError = "<!-- Error deleting webObject: " + ex.toString() + " : " + sSql + " -->";
nrows=-1;
}
finally {
// releases the statement object
try { pstmt.close(); } catch (Exception ignrd) {}
}
return nrows;
}
}
/* HTML TEMPLATE
<table border=0 cellspacing=0 cellpadding=0>
<tr><td>metadata_key:</td><td> <INPUT type='TEXT' size='5' maxlength='11' name='metadata_key' VALUE="<%=beanName.metadata_key%>"></td></tr>
<tr><td>metadata_country:</td><td> <INPUT type='TEXT' size='11' maxlength='10' name='metadata_country' VALUE="<%=beanName.metadata_country%>"></td></tr>
<tr><td>metadata_year:</td><td> <INPUT type='TEXT' size='5' maxlength='11' name='metadata_year' VALUE="<%=beanName.metadata_year%>"></td></tr>
<tr><td>metadata_value:</td><td> <INPUT type='TEXT' size='15' maxlength='22' name='metadata_value' VALUE="<%=beanName.metadata_value%>"></td></tr>
<tr><td>metadata_value_us:</td><td> <INPUT type='TEXT' size='15' maxlength='22' name='metadata_value_us' VALUE="<%=beanName.metadata_value_us%>"></td></tr>
</table>
END HTML TEMPLATE */
|
novatel/novatel_edie | src/decoders/novatel/src/filters/timefilter.cpp | ////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2020 NovAtel Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////
// Includes
#include "filters/timefilter.hpp"
// code
// ---------------------------------------------------------
TimeFilter::TimeFilter()
{
dFilterCount = 0;
bMyIsNegativeTimeFilter = FALSE;
ulMyStartPair.clear();
ulMyEndPair.clear();
}
// ---------------------------------------------------------
TimeFilter::~TimeFilter()
{
ulMyStartPair.clear();
ulMyEndPair.clear();
}
// ---------------------------------------------------------
BOOL TimeFilter::Filter(BaseMessageData& clBaseMessageData)
{
ULONG ulGnssWeek = clBaseMessageData.getMessageTimeWeek();
ULONG ulMilliSeconds = clBaseMessageData.getMessageTimeMilliSeconds();
// By default, messages with unknown and sattime statuses will always be passed.
if ( (clBaseMessageData.getMessageTimeStatus() == MessageTimeStatusEnum::TIME_UNKNOWN) ||
(clBaseMessageData.getMessageTimeStatus() == MessageTimeStatusEnum::TIME_SATTIME) )
return TRUE;
if(ulMyStartPair[0].second == 0)
{
ulMyStartPair[0].second = ulGnssWeek;
}
if(ulMyEndPair[0].second == 0)
{
ulMyEndPair[0].second = ulMyStartPair[0].second;
}
// Case of size 0 will generate exception, because we will be trying to access vector without initialization.
if ((ulMyStartPair.size() != 0) && (ulMyEndPair.size() != 0))
{
// If end pair is less then start pair
if( (ulMyStartPair[0].first > ulMyEndPair[0].first) && (ulMyStartPair[0].second == ulMyEndPair[0].second) )
{
return FALSE;
}
// If Configured pair and start pair is same or less then
// If Configured pair and end pair is same or greater then
else if( ((ulMilliSeconds <= ulMyStartPair[0].first) && (ulGnssWeek <= ulMyStartPair[0].second))
|| ((ulMilliSeconds >= ulMyEndPair[0].first) && (ulGnssWeek >= ulMyEndPair[0].second)) )
{
if (bMyIsNegativeTimeFilter == FALSE)
{
return FALSE;
}
else
{
SetFilterCount();
return TRUE;
}
}
// If in b/w
else if( ((ulMilliSeconds > ulMyStartPair[0].first) && (ulGnssWeek >= ulMyStartPair[0].second))
|| ((ulMilliSeconds < ulMyEndPair[0].first) &&(ulGnssWeek <= ulMyEndPair[0].second)) )
{
if(ulMilliSeconds > ulMyEndPair[0].first && ulGnssWeek >= ulMyEndPair[0].second)
{
if (bMyIsNegativeTimeFilter == FALSE)
{
return FALSE;
}
else
{
SetFilterCount();
return TRUE;
}
}
else
{
if (bMyIsNegativeTimeFilter == FALSE)
{
SetFilterCount();
return TRUE;
}
else
{
return FALSE;
}
}
}
// If in b/w
else if( ((ulMilliSeconds < ulMyStartPair[0].first) && (ulGnssWeek >= ulMyStartPair[0].second))
&& ((ulMilliSeconds < ulMyEndPair[0].first) &&(ulGnssWeek == ulMyEndPair[0].second)) )
{
if (bMyIsNegativeTimeFilter == FALSE)
{
SetFilterCount();
return TRUE;
}
else
{
return FALSE;
}
}
else
{
return FALSE;
}
}
else
{
throw nExcept("Time pair is not valid");
}
}
// ---------------------------------------------------------
void TimeFilter::ConfigureFilter(FilterConfig& stFilterConfig)
{
copy(stFilterConfig.ulStartTimePair.begin(), stFilterConfig.ulStartTimePair.end(), back_inserter(ulMyStartPair));
copy(stFilterConfig.ulEndTimePair.begin(), stFilterConfig.ulEndTimePair.end(), back_inserter(ulMyEndPair));
bMyIsNegativeTimeFilter = stFilterConfig.bIsNegTimeFilter;
}
// ---------------------------------------------------------
DOUBLE TimeFilter::GetFilterCount()
{
return dFilterCount;
}
// ---------------------------------------------------------
void TimeFilter::SetFilterCount()
{
dFilterCount = dFilterCount + 1;
}
// ---------------------------------------------------------
void TimeFilter::Reset()
{
dFilterCount = 0;
}
|
ifm/ifm3d | modules/tools/include/ifm3d/tools/reboot_app.h | <filename>modules/tools/include/ifm3d/tools/reboot_app.h<gh_stars>10-100
// -*- c++ -*-
/*
* Copyright 2018-present ifm electronic, gmbh
* Copyright 2017 Love Park Robotics, LLC
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef __IFM3D_TOOLS_REBOOT_APP_H__
#define __IFM3D_TOOLS_REBOOT_APP_H__
#include <string>
#include <ifm3d/tools/cmdline_app.h>
namespace ifm3d
{
/**
* Concrete implementation of the `reboot` subcommand to the `ifm3d`
* command-line utility.
*/
class RebootApp : public ifm3d::CmdLineApp
{
public:
RebootApp(int argc, const char** argv, const std::string& name = "reboot");
int Run();
}; // end: class RebootApp
} // end: namespace ifm3d
#endif // __IFM3D_TOOLS_REBOOT_APP_H__
|
nashsibanda/dancey | validation/seller.joiSchema.js | const Joi = require("@hapi/joi");
Joi.objectId = require("joi-objectid")(Joi);
const countries = require("./countries");
const sellerValidation = Joi.object({
sellerName: Joi.string()
.max(200)
.label("Seller name")
.alter({ new: schema => schema.required() }),
adminUserIds: Joi.array()
.min(1)
.label("Admin User IDs")
.items(Joi.objectId())
.alter({ new: schema => schema.required() }),
location: Joi.string()
.label("Location")
.valid(...Object.keys(countries))
.messages({
"any.only": '"Location" must be a valid country',
})
.alter({ new: schema => schema.required() }),
});
const newSellerValidation = sellerValidation.tailor("new");
module.exports = { newSellerValidation, sellerValidation };
|
pulibrary/figgy | app/validators/source_metadata_identifier_or_title_validator.rb | # frozen_string_literal: true
class SourceMetadataIdentifierOrTitleValidator < ActiveModel::Validator
def validate(record)
return if record.source_metadata_identifier.present? || Array.wrap(record.title).first.present?
record.errors.add(:title, "You must provide a source metadata id or a title")
record.errors.add(:source_metadata_identifier, "You must provide a source metadata id or a title")
end
end
|
walkdianzi/DSCategories | Categories/Foundation/NSString/NSString+Code.h | //
// NSString+Code.h
// zhefengle
//
// Created by dasheng on 16/7/2.
// Copyright © 2016年 vanwell. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSString (Code)
//URLEncode
/**
* URLEncode
*
* @param unencodedString
*
* @return
*/
- (NSString *)encodeString;
//URLDEcode
- (NSString *)decodeString;
@end
|
yosuperdope/OpenPype | openpype/modules/default_modules/project_manager_action.py | from openpype.modules import OpenPypeModule
from openpype_interfaces import ITrayAction
class ProjectManagerAction(OpenPypeModule, ITrayAction):
label = "Project Manager (beta)"
name = "project_manager"
admin_action = True
def initialize(self, modules_settings):
enabled = False
module_settings = modules_settings.get(self.name)
if module_settings:
enabled = module_settings.get("enabled", enabled)
self.enabled = enabled
# Tray attributes
self.project_manager_window = None
def connect_with_modules(self, *_a, **_kw):
return
def tray_init(self):
"""Initialization in tray implementation of ITrayAction."""
self.create_project_manager_window()
def on_action_trigger(self):
"""Implementation for action trigger of ITrayAction."""
self.show_project_manager_window()
def create_project_manager_window(self):
"""Initializa Settings Qt window."""
if self.project_manager_window:
return
from openpype.tools.project_manager import ProjectManagerWindow
self.project_manager_window = ProjectManagerWindow()
def show_project_manager_window(self):
"""Show project manager tool window.
Raises:
AssertionError: Window must be already created. Call
`create_project_manager_window` before calling this method.
"""
if not self.project_manager_window:
raise AssertionError("Window is not initialized.")
# Store if was visible
was_minimized = self.project_manager_window.isMinimized()
# Show settings gui
self.project_manager_window.show()
if was_minimized:
self.project_manager_window.showNormal()
# Pull window to the front.
self.project_manager_window.raise_()
self.project_manager_window.activateWindow()
|
skvl/TermOx | include/termox/widget/widgets/cycle_stack.hpp | <filename>include/termox/widget/widgets/cycle_stack.hpp
#ifndef TERMOX_WIDGET_WIDGETS_CYCLE_STACK_HPP
#define TERMOX_WIDGET_WIDGETS_CYCLE_STACK_HPP
#include <memory>
#include <type_traits>
#include <utility>
#include <termox/painter/brush.hpp>
#include <termox/painter/color.hpp>
#include <termox/painter/glyph_string.hpp>
#include <termox/painter/trait.hpp>
#include <termox/widget/layouts/horizontal.hpp>
#include <termox/widget/layouts/stack.hpp>
#include <termox/widget/layouts/vertical.hpp>
#include <termox/widget/pipe.hpp>
#include <termox/widget/widget.hpp>
#include <termox/widget/widgets/button.hpp>
#include <termox/widget/widgets/cycle_box.hpp>
namespace ox {
/// A layout::Stack with an interface to cycle through each Widget in the stack.
template <typename Child = Widget>
class Cycle_stack : public layout::Vertical<> {
private:
/// User interface to cycle through the pages of the Stack.
class Top_row : public layout::Horizontal<> {
public:
Button& left_btn = this->make_child<Button>(L"<");
Cycle_box& cycle_box = this->make_child<Cycle_box>();
Button& right_btn = this->make_child<Button>(L">");
public:
Top_row()
{
using namespace pipe;
*this | fixed_height(1) | children() | bg(Color::Light_gray) |
fg(Color::Black);
left_btn | fixed_width(1) | on_press(slot::previous(cycle_box));
right_btn | fixed_width(1) | on_press(slot::next(cycle_box));
cycle_box | Trait::Bold;
}
};
public:
Top_row& top_row = this->make_child<Top_row>();
layout::Stack<Child>& stack = this->make_child<layout::Stack<Child>>();
public:
/// Construct a new Widget_t object and add it to the end of the Stack.
/** Returns a reference to this newly created page. \p title is passed to
* the Cycle_box to display when this page is active. */
template <typename Widget_t = Child, typename... Args>
auto make_page(Glyph_string title, Args&&... args) -> Widget_t&
{
static_assert(std::is_base_of<Child, Widget_t>::value,
"Cycle_stack::make_page: Widget_t must be a Child type");
auto child = std::make_unique<Widget_t>(std::forward<Args>(args)...);
return static_cast<Widget_t&>(
this->append_page(std::move(title), std::move(child)));
}
/// Append a page to the Stack.
/** \p title is passed to the Cycle_box associated with this page. */
auto append_page(Glyph_string title, std::unique_ptr<Child> widget)
-> Child&
{
auto& signal = top_row.cycle_box.add_option(std::move(title));
signal.connect(slot::set_active_page(stack, stack.size()));
auto& child = stack.append_page(std::move(widget));
if (stack.size() == 1)
stack.set_active_page(0);
return child;
}
};
/// Helper function to create an instance.
template <typename Child = Widget, typename... Args>
auto cycle_stack(Args&&... args) -> std::unique_ptr<Cycle_stack<Child>>
{
return std::make_unique<Cycle_stack<Child>>(std::forward<Args>(args)...);
}
} // namespace ox
#endif // TERMOX_WIDGET_WIDGETS_CYCLE_STACK_HPP
|
dimchat/sdk-java | Plugins/src/test/java/CryptoRSATest.java | <reponame>dimchat/sdk-java<filename>Plugins/src/test/java/CryptoRSATest.java<gh_stars>1-10
import org.junit.Assert;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import chat.dim.crypto.DecryptKey;
import chat.dim.crypto.EncryptKey;
import chat.dim.crypto.PrivateKey;
import chat.dim.crypto.PublicKey;
import chat.dim.format.UTF8;
public class CryptoRSATest {
@Test
public void testRSA() {
PrivateKey sk = PrivateKey.generate(PrivateKey.RSA);
Log.info("RSA private key: " + sk);
PublicKey pk = sk.getPublicKey();
Log.info("RSA public key: " + pk);
String text = "moky";
byte[] plaintext = UTF8.encode(text);
byte[] ciphertext = ((EncryptKey) pk).encrypt(plaintext);
Log.info("RSA encrypt(\"" + text + "\") = " + Utils.hexEncode(ciphertext));
byte[] data = ((DecryptKey) sk).decrypt(ciphertext);
String decrypt = new String(data);
Log.info("decrypt to " + decrypt);
Assert.assertEquals(text, decrypt);
byte[] signature = sk.sign(plaintext);
Log.info("signature(\"" + text + "\") = " + Utils.hexEncode(signature));
boolean ok = pk.verify(plaintext, signature);
Assert.assertTrue(ok);
}
@Test
public void testPublicKey() {
Map<String, Object> dictionary = new HashMap<>();
dictionary.put("algorithm", "RSA");
dictionary.put("data", "-----BEGIN PUBLIC KEY-----\n" +
"<KEY>" +
"-----END PUBLIC KEY-----");
PublicKey key = PublicKey.parse(dictionary);
Log.info("public key: " + key);
}
@Test
public void testPrivateKey() {
Map<String, Object> dictionary = new HashMap<>();
dictionary.put("algorithm", "RSA");
dictionary.put("data", "-----BEGIN RSA PRIVATE KEY-----\n" +
"<KEY>" +
"-----END RSA PRIVATE KEY-----");
PrivateKey sk = PrivateKey.parse(dictionary);
Log.info("private key: " + sk);
}
}
|
ButuzGOL/constructor | src/scripts/list.js | import React from 'react';
import Radium from 'radium';
import variables from './styles/variables';
@Radium
export default class List extends React.Component {
static propTypes = {
type: React.PropTypes.oneOf(['unordered', 'ordered']),
items: React.PropTypes.array.isRequired,
line: React.PropTypes.bool,
striped: React.PropTypes.bool,
space: React.PropTypes.bool
};
static defaultProps = {
type: 'unordered',
line: false,
striped: false,
space: false
};
getStyles() {
return {
base: {
margin: `0 0 ${variables.baseMarginVertical}px 0`,
listStyle: 'none',
padding: 0
},
line: {
marginTop: variables.listLineMarginTop,
paddingTop: variables.listLineMarginTop,
borderTop: `${variables.listLineBorderWidth}px solid ${variables.listLineBorder}`
},
striped: {
padding: `${variables.listStripedPaddingVertical}px ${variables.listStripedPaddingHorizontal}px`
},
stripedItem: {
background: variables.listStripedBackground
},
space: {
marginTop: variables.listSpaceMarginTop
},
sub: {
margin: 0
}
};
}
render() {
const styles = this.getStyles();
const props = this.props;
const attrs = {
tagName: (props.type === 'unordered') ? 'ul' : 'ol'
};
return (
<attrs.tagName style={[
styles.base,
props.style
]}>
{props.items.map((item, index) => {
return (
<li style={[
index && props.line && styles.line,
props.striped && styles.striped,
!(index % 2) && props.striped && styles.stripedItem,
index && props.space && styles.space
]}>
{item.label}
{(item.children && item.children.length) ? (
<List
type={props.type}
line={props.line}
striped={props.striped}
space={props.space}
style={styles.sub}
items={item.children} />) : null
}
</li>
);
})}
</attrs.tagName>
);
}
}
|
daybreak/daybreak | vendor/plugins/.freehand_templates/lib/freehand_templates.rb | $: << '/work/plugins/freehand/lib'
$: << '/work/gems/local_variable_set/lib'
require 'freehand'
require 'local_variable_set'
require 'action_view'
require 'action_view/base'
require 'iwish/blank_slate'
class Object
# The hidden singleton lurks behind everyone
def metaclass; class << self; self; end; end
def meta_eval &blk; metaclass.instance_eval &blk; end
# Adds methods to a metaclass
def meta_def( name, &blk )
meta_eval { define_method name, &blk }
end
# Defines an instance method within a class
def class_def( name, &blk )
class_eval { define_method name, &blk }
end
end
ActionView::Base.class_eval do
alias render_without_freehand render
end
module Freehand
class Renderer < Object
def initialize(view)
@view = view
@view.instance_variables.each do |var|
self.instance_variable_set(var, @view.instance_variable_get(var))
end
end
def method_missing(method, *args, &block)
puts "Transferring #{method}"
@view.send(method, *args, &block)
end
def render(*args)
puts "Rendering"
@view.text{@view.render(*args)}
end
end
class TemplateHandler < ActionView::TemplateHandler
def render(template, locals)
body = [Binding::Cache.cache_locals(locals).restore_locals_script, 'nil', template.source].join("\n")
#@proxy = Freehand::Renderer.new(@view)
#def @view.render(*args)
# text @render_without_freehand.call(*args)
#end
@view.instance_eval{extend Freehand::Taggify}
@proxy.instance_eval body
#def @view.render(*args)
# @render_without_freehand.call(*args)
#end
@view.markup
end
end
end
|
isabella232/tessapi | 3.05.02/a03469.js | var a03469 =
[
[ "base", "a03469.html#a5576d395de768c5a8d9e51a5fa040cef", null ],
[ "FunctionSignature", "a03469.html#a66a656b92a72e6dc74bf03934c3542ff", null ],
[ "_TessFunctionResultCallback_5_2", "a03469.html#a068dff747fbc555cf55c0bfe3409a64c", null ],
[ "Run", "a03469.html#ad80b1e2faa86f396a492e72d8f76fa42", null ]
]; |
alicexuji/vueshop | myspringboot/src/main/java/com/zb/model/TokenResult.java | package com.zb.model;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
/**
* @Author: zhenwei.xu
* @Date: 2020/12/7 14:07
*/
@Getter
@Setter
public class TokenResult implements Serializable {
private static final long serialVersionUID = -4242865174080706499L;
private String tokenHead = "Bearer ";
private String token;
public TokenResult(String token) {
this.token = token;
}
}
|
pouk/monocular | packages/types/src/Rectangle/scale.js | <gh_stars>0
const create = require('./create')
/**
* Scale rectangle by given coefficient
*
* @param {Number} n
* @param {Rectangle} rect
*
* @returns {Rectangle}
*/
function scale (n, rect) {
const { origin, width, height } = rect
return create(origin, width * n, height * n)
}
module.exports = scale
|
CanadaHealthInfoway/message-builder | message-builder-demiftifier/src/test/java/ca/infoway/demiftifier/svgifier/ChoiceShapeTest.java | <reponame>CanadaHealthInfoway/message-builder
/**
* Copyright 2013 Canada Health Infoway, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: $LastChangedBy: tmcgrady $
* Last modified: $LastChangedDate: 2013-01-02 17:05:34 -0500 (Wed, 02 Jan 2013) $
* Revision: $LastChangedRevision: 6471 $
*/
package ca.infoway.demiftifier.svgifier;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import ca.infoway.demiftifier.LogicalDimensions;
import ca.infoway.demiftifier.MessagePartLayoutItem;
// WARNING: the build machine calculates font heights differently than my dev box
@RunWith(MockitoJUnitRunner.class)
public class ChoiceShapeTest {
@Mock
MessagePartLayoutItem choiceItem;
@Mock
ShapeFactory shapeFactory;
@Mock
Shape shape1;
@Mock
MessagePartLayoutItem item1;
@Mock
Shape shape2;
@Mock
MessagePartLayoutItem item2;
@Mock
CoordinateSpace coordinateSpace;
@Before
public void setUp() throws Exception {
Mockito.when(this.shapeFactory.getShape(this.item1)).thenReturn(this.shape1);
Mockito.when(this.shapeFactory.getShape(this.item2)).thenReturn(this.shape2);
Mockito.when(this.shape1.getItem()).thenReturn(this.item1);
Mockito.when(this.shape1.getBounds()).thenReturn(new BoundingBox(0, 0, 30, 100));
Mockito.when(this.shape2.getItem()).thenReturn(this.item2);
Mockito.when(this.shape2.getBounds()).thenReturn(new BoundingBox(0, 0, 20, 100));
Mockito.when(this.item1.getLabel()).thenReturn("Item1");
Mockito.when(this.item2.getLabel()).thenReturn("Item2");
Mockito.when(this.choiceItem.getLabel()).thenReturn("ChoiceItem");
Mockito.when(this.choiceItem.getSpecializationChilds()).thenReturn(Arrays.asList(this.item1, this.item2));
}
@Test
public void shouldExpandRowToAccommodateTrivialSpecializations() {
Mockito.when(this.item1.getHeight()).thenReturn(0);
Mockito.when(this.item1.isTrivial()).thenReturn(true);
Mockito.when(this.item2.getHeight()).thenReturn(1);
Mockito.when(this.item1.getLogicalY()).thenReturn(4);
Mockito.when(this.item2.getLogicalY()).thenReturn(5);
Mockito.when(this.choiceItem.getLogicalY()).thenReturn(4);
ChoiceShape choiceShape = new ChoiceShape(this.choiceItem, new StyleProvider(), this.shapeFactory);
int baseHeight = choiceShape.calculateContentHeight();
int height = choiceShape.getMinimalHeightForRow(this.coordinateSpace, 4);
assertEquals("minimal height -- needs extra height for item1", baseHeight + 50, height);
int fullHeight = choiceShape.getBounds().getHeight();
assertEquals("full height -- includes shapes", baseHeight + 85, fullHeight);
}
@Test
public void shouldExpandRowToAccommodateTrivialSpecializationsThatCanFitInMoreThanOneRow() {
Mockito.when(this.item1.getHeight()).thenReturn(0);
Mockito.when(this.item1.isTrivial()).thenReturn(true);
Mockito.when(this.item2.getHeight()).thenReturn(1);
Mockito.when(this.item1.getLogicalY()).thenReturn(4);
Mockito.when(this.item2.getLogicalY()).thenReturn(6);
Mockito.when(this.choiceItem.getLogicalY()).thenReturn(4);
Mockito.when(this.coordinateSpace.getCoordinates(Mockito.any(LogicalDimensions.class))).thenReturn(new BoundingBox(0, 0, 10, 80));
ChoiceShape choiceShape = new ChoiceShape(this.choiceItem, new StyleProvider(), this.shapeFactory);
int baseHeight = choiceShape.calculateContentHeight();
int height = choiceShape.getMinimalHeightForRow(this.coordinateSpace, 4);
assertEquals("minimal height of row 4 -- basic height for label and margins", baseHeight + 10, height);
int height2 = choiceShape.getMinimalHeightForRow(this.coordinateSpace, 5);
assertEquals("minimal height of row 5 -- needs extra height for item1", 30, height2);
int fullHeight = choiceShape.getBounds().getHeight();
assertEquals("full height -- includes shapes", baseHeight + 85, fullHeight);
}
@Test
public void shouldIndicateABaseSize() {
Mockito.when(this.item1.getHeight()).thenReturn(0);
Mockito.when(this.item2.getHeight()).thenReturn(0);
Mockito.when(this.item1.getLogicalY()).thenReturn(4);
Mockito.when(this.item2.getLogicalY()).thenReturn(4);
Mockito.when(this.choiceItem.getLogicalY()).thenReturn(4);
ChoiceShape choiceShape = new ChoiceShape(this.choiceItem, new StyleProvider(), this.shapeFactory);
int baseHeight = choiceShape.calculateContentHeight();
int height = choiceShape.getMinimalHeightForRow(this.coordinateSpace, 4);
assertEquals("minimal height -- doesn't include shapes", baseHeight + 10, height);
int fullHeight = choiceShape.getBounds().getHeight();
assertEquals("full height -- includes shapes", baseHeight + 85, fullHeight);
}
}
|
m991339394/xw | src/main/java/io/renren/modules/app/dao/UserUserRelationDao.java | package io.renren.modules.app.dao;
import io.renren.modules.app.model.po.UserUserRelationPO;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author jgl
* @since 2019-12-06
*/
@Mapper
public interface UserUserRelationDao extends BaseMapper<UserUserRelationPO> {
}
|
MrRisoni/commercify | src/main/java/pojo/JsonStringResponse.java | package pojo;
import com.fasterxml.jackson.annotation.JsonRawValue;
import com.fasterxml.jackson.annotation.JsonValue;
public class JsonStringResponse {
@JsonValue
@JsonRawValue
private String value;
public JsonStringResponse(String value) {
this.value = value;
}
}
|
IdoiaRojoLazaro/blockchain-developer-bootcamp-final-project | client/src/actions/auth.js | import { types } from '../types/types';
export const logout = () => ({ type: types.authLogout });
export const startChecking = () => {
const isAuthenticated = localStorage.getItem('isAuthenticated') || null;
return async dispatch => {
if (isAuthenticated) {
dispatch({
type: types.authLogin,
payload: {
isAuthenticated: true
}
});
} else {
dispatch(checkingFinish());
}
};
};
const checkingFinish = () => ({ type: types.authCheckingFinish });
|
open-garden/garden | Zipc_Webplatform/src/com/zipc/garden/webplatform/client/editor/cb/CBEditorKeyEventHolder.java | <gh_stars>1-10
package com.zipc.garden.webplatform.client.editor.cb;
import com.smartgwt.client.types.KeyNames;
import com.smartgwt.client.widgets.events.KeyPressEvent;
import com.smartgwt.client.widgets.events.KeyPressHandler;
import com.smartgwt.client.widgets.menu.events.MenuItemClickEvent;
/**
* Manage SCSS editor shortcut key events
*/
public class CBEditorKeyEventHolder {
/**
* Event when the keyboard is operated. <br>
* Occurs when the canvas has focus.
* @param editor Main class of "scenarioset-setting editor"
* @return Key Press Handler
*/
protected static KeyPressHandler createShortcutKeyEvent(CBEditor editor) {
return new KeyPressHandler() {
@Override
public void onKeyPress(KeyPressEvent event) {
// delete key
if (KeyNames.DEL.equals(event.getKeyName())) {
editor.onDelete();
}
// Ctrl + S
else if (event.isCtrlKeyDown() && "S".equals(event.getKeyName())) {
event.cancel();
editor.getSaveItem().fireEvent(new MenuItemClickEvent(editor.getSaveItem().getJsObj()));
}
// Ctrl + Z
else if (event.isCtrlKeyDown() && "Z".equals(event.getKeyName())) {
event.cancel();
editor.getEditManager().undo();
editor.refresh();
}
// Ctrl + Y
else if (event.isCtrlKeyDown() && "Y".equals(event.getKeyName())) {
event.cancel();
editor.getEditManager().redo();
editor.refresh();
}
}
};
}
}
|
HaoZhang95/PythonAndMachineLearning | 04WebServer/day02/basic03.py | """
io多路复用,好处在于单个process进程可以同时处理**多个网络连接**的io操作
单进程,单线程,一般只能实现一个io发收操作,多路io复用在windows使用的是IOCP,在Linux上使用的就是epoll
1- basic02.py我们使用的是for循环遍历服务器的client_socket列表去一一查看recv有没有数据,**不知道哪个socket收到信息**效率差,体验不好
2- 在epoll模型中,每个socket都是由操作系统来监控,recv到信息,操作系统就会通知**用户进程**,不需要**一一查看**
3- epoll的两种通知进程的模式
LT模式:当epoll检测到描述的时间发生并将事件通知该进程,该应用程序可以**不立即处理**
只要有数据就一直通知,直到没有数据
ET模式:当epoll检测到描述的时间发生并将事件通知该进程,该应用程序**必须立即处理**
只在有数据的一瞬进通知一次
4- epoll只能认识文件描述符,EPOLLIN代表监听可读时间,EPOLLOUT可写事件
5- 默认不设置就是LT模式
"""
"""
因为epoll只能发在unix/linux下使用,所以windows下会出现module 'select' has no attribute 'epoll',所以本代码不能被测试
UNIX,LINUX中"一切皆文件",文件描述符就是对**进程内部(才会有效)**所拥有文件资源的一种描述的符号
1- 是一个无符号整数(0,1,2,3.。。)0(input),1(output),2(标准错误)默认被系统占有,通过sock.fileno()获取文件描述符
2- 一个进程默认打开0,1,2三个文件,自己的socket就是为3的文件描述符
"""
"""
epoll模式的服务器, epoll需要导入select模块
"""
import socket
import select
def testEpollServer():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.setblocking(False)
server_socket.bind(("", 8888))
server_socket.listen(128)
# 创建epoll对象
epoll = select.epoll()
# 将服务器的socket添加到epoll的监听列表, fd = file descriptor文件描述符,
# ET模式: select.EPOLLIN | select.EPOLLET
epoll.register(server_socket.fileno(), select.EPOLLIN)
# 保存客户端的socket字典, {fd: socket}
client_socket_list = {}
client_address_list = {}
while True:
# 死循环中向epoll对象获取监听结果
epoll_list = epoll.poll()
# 遍历列表,获取fd和是件
for fd, events in epoll_list:
# 服务器socket accept()
if fd == server_socket.fileno():
new_client_socket, new_client_address = server_socket.accept()
print("收到了来自%s的链接请求" % (str(new_client_address)))
# 设置客户端socket非阻塞
new_client_socket.setblocking(False)
# 添加到epoll监听列表
epoll.register(new_client_socket.fileno(), epoll.EPOLLIN)
# 添加到集合
client_socket_list[new_client_socket.fileno()] = new_client_socket
client_address_list[new_client_socket.fileno()] = new_client_address
# 客户端的socket recv()
elif events == select.EPOLLIN:
recv_data = client_socket_list[fd].recv(4096)
if recv_data:
print("收到了来自%s的数据:%s" % (str(client_address_list[fd]), recv_data.decode()))
else:
print("收到了来自%s的断开请求" % (str(client_address_list[fd])))
# 从监听列表中移除
epoll.unregister(fd)
# 从字典中移除
del client_socket_list[fd]
del client_address_list[fd]
def main():
testEpollServer()
if __name__ == '__main__':
main() |
hmajid2301/banter-bus-core-api | app/player/player_exceptions.py | from app.core.exceptions import ExistsException, NotFoundException
class PlayerExistsException(ExistsException):
pass
class PlayerNotFound(NotFoundException):
pass
class PlayerHasNoRoomError(NotFoundException):
pass
class PlayerNotHostError(NotFoundException):
def __init__(self, msg: str, player_id: str, host_player_id) -> None:
self.msg = msg
self.player_id = player_id
self.host_player_id = host_player_id
class NicknameExistsException(ExistsException):
def __init__(self, msg: str, nickname: str) -> None:
self.msg = msg
self.nickname = nickname
|
vsosrc/jruby | bench/bench_tempfile.rb | require 'benchmark'
require 'tempfile'
COUNT = 1_000
WRITE_COUNT = 30
puts "#{COUNT} Tempfile.new(file)"
10.times {
puts Benchmark.measure {
i = 0
while i < COUNT
tf = Tempfile.new("heh")
i = i + 1
end
}
}
puts "#{COUNT} Tempfile.new(file);write;close"
10.times {
puts Benchmark.measure {
i = 0
while i < COUNT
tf = Tempfile.new("heh")
j = 0
while j < WRITE_COUNT
tf.write "hehheheheheheheehehe\n"
j = j + 1
end
tf.close
i = i + 1
end
}
}
|
xzhan96/chromium.src | net/socket/fuzzed_socket_factory.cc | // Copyright 2016 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.
#include "net/socket/fuzzed_socket_factory.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/test/fuzzed_data_provider.h"
#include "net/base/address_list.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_errors.h"
#include "net/base/network_change_notifier.h"
#include "net/log/net_log_with_source.h"
#include "net/socket/client_socket_handle.h"
#include "net/socket/connection_attempts.h"
#include "net/socket/fuzzed_datagram_client_socket.h"
#include "net/socket/fuzzed_socket.h"
#include "net/socket/ssl_client_socket.h"
namespace net {
class NetLog;
namespace {
// SSLClientSocket implementation that always fails to connect.
class FailingSSLClientSocket : public SSLClientSocket {
public:
FailingSSLClientSocket() {}
~FailingSSLClientSocket() override {}
// Socket implementation:
int Read(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) override {
NOTREACHED();
return ERR_UNEXPECTED;
}
int Write(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) override {
NOTREACHED();
return ERR_UNEXPECTED;
}
int SetReceiveBufferSize(int32_t size) override { return OK; }
int SetSendBufferSize(int32_t size) override { return OK; }
// StreamSocket implementation:
int Connect(const CompletionCallback& callback) override {
return ERR_FAILED;
}
void Disconnect() override {}
bool IsConnected() const override { return false; }
bool IsConnectedAndIdle() const override { return false; }
int GetPeerAddress(IPEndPoint* address) const override {
return ERR_SOCKET_NOT_CONNECTED;
}
int GetLocalAddress(IPEndPoint* address) const override {
return ERR_SOCKET_NOT_CONNECTED;
}
const NetLogWithSource& NetLog() const override { return net_log_; }
void SetSubresourceSpeculation() override {}
void SetOmniboxSpeculation() override {}
bool WasEverUsed() const override { return false; }
void EnableTCPFastOpenIfSupported() override {}
bool WasNpnNegotiated() const override { return false; }
NextProto GetNegotiatedProtocol() const override { return kProtoUnknown; }
bool GetSSLInfo(SSLInfo* ssl_info) override { return false; }
void GetConnectionAttempts(ConnectionAttempts* out) const override {
out->clear();
}
void ClearConnectionAttempts() override {}
void AddConnectionAttempts(const ConnectionAttempts& attempts) override {}
int64_t GetTotalReceivedBytes() const override { return 0; }
// SSLSocket implementation:
int ExportKeyingMaterial(const base::StringPiece& label,
bool has_context,
const base::StringPiece& context,
unsigned char* out,
unsigned int outlen) override {
NOTREACHED();
return 0;
}
// SSLClientSocket implementation:
void GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info) override {}
ChannelIDService* GetChannelIDService() const override {
NOTREACHED();
return nullptr;
}
Error GetTokenBindingSignature(crypto::ECPrivateKey* key,
TokenBindingType tb_type,
std::vector<uint8_t>* out) override {
NOTREACHED();
return ERR_UNEXPECTED;
}
crypto::ECPrivateKey* GetChannelIDKey() const override {
NOTREACHED();
return nullptr;
}
private:
NetLogWithSource net_log_;
DISALLOW_COPY_AND_ASSIGN(FailingSSLClientSocket);
};
} // namespace
FuzzedSocketFactory::FuzzedSocketFactory(
base::FuzzedDataProvider* data_provider)
: data_provider_(data_provider) {}
FuzzedSocketFactory::~FuzzedSocketFactory() {}
std::unique_ptr<DatagramClientSocket>
FuzzedSocketFactory::CreateDatagramClientSocket(
DatagramSocket::BindType bind_type,
const RandIntCallback& rand_int_cb,
NetLog* net_log,
const NetLogSource& source) {
return base::MakeUnique<FuzzedDatagramClientSocket>(data_provider_);
}
std::unique_ptr<StreamSocket> FuzzedSocketFactory::CreateTransportClientSocket(
const AddressList& addresses,
std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,
NetLog* net_log,
const NetLogSource& source) {
std::unique_ptr<FuzzedSocket> socket(
new FuzzedSocket(data_provider_, net_log));
socket->set_fuzz_connect_result(true);
// Just use the first address.
socket->set_remote_address(*addresses.begin());
return std::move(socket);
}
std::unique_ptr<SSLClientSocket> FuzzedSocketFactory::CreateSSLClientSocket(
std::unique_ptr<ClientSocketHandle> transport_socket,
const HostPortPair& host_and_port,
const SSLConfig& ssl_config,
const SSLClientSocketContext& context) {
return base::MakeUnique<FailingSSLClientSocket>();
}
void FuzzedSocketFactory::ClearSSLSessionCache() {}
} // namespace net
|
daojianyanying/ClassExhibit | ClassExhibit/ClassExhibitSDK/src/main/java/com/common/people/klass/exhibit/entity/attribute/LocalVariableTypeAttribute.java | package com.common.people.klass.exhibit.entity.attribute;
import com.common.people.klass.exhibit.entity.trunk.Attribute;
import java.util.ArrayList;
public class LocalVariableTypeAttribute extends Attribute implements AttributeInfo {
private Integer nameIndex;
private Integer length;
private Integer localVariableTypeTableLength;
private ArrayList<LocalVariableTypeTable> localVariableTypeTables;
@Override
public LocalVariableTypeAttribute setNameIndex(Integer nameIndex) {
this.nameIndex = nameIndex;
return this;
}
@Override
public LocalVariableTypeAttribute setLength(Integer length) {
this.length = length;
return this;
}
public LocalVariableTypeAttribute setLocalVariableTypeTableLength(Integer localVariableTypeTableLength) {
this.localVariableTypeTableLength = localVariableTypeTableLength;
return this;
}
@Override
public Integer getNameIndex() {
return nameIndex;
}
@Override
public Integer getLength() {
return length;
}
public Integer getLocalVariableTypeTableLength() {
return localVariableTypeTableLength;
}
public ArrayList<LocalVariableTypeTable> getLocalVariableTypeTables() {
return localVariableTypeTables;
}
public LocalVariableTypeAttribute setLocalVariableTypeTables(ArrayList<LocalVariableTypeTable> localVariableTypeTables) {
this.localVariableTypeTables = localVariableTypeTables;
return this;
}
}
|
aasensio/DeepLearning | DNHazel/mdn.py | import matplotlib.pyplot as pl
import numpy as np
import tensorflow as tf
import seaborn as sns
from ipdb import set_trace as stop
import os
os.environ["KERAS_BACKEND"] = "tensorflow"
from keras import backend as K
from keras.layers import Dense, Input, merge
from keras.models import Model
from sklearn.cross_validation import train_test_split
def build_toy_dataset(nsample=40000):
y_data = np.float32(np.random.uniform(-10.5, 10.5, (1, nsample))).T
r_data = np.float32(np.random.normal(size=(nsample,1))) # random noise
x_data = np.float32(np.sin(0.75*y_data)*7.0+y_data*0.5+r_data*1.0)
return train_test_split(x_data, y_data, random_state=42, train_size=0.1)
def log_sum_exp(x, axis=None):
"""Log-sum-exp trick implementation"""
x_max = K.max(x, axis=axis, keepdims=True)
return K.log(K.sum(K.exp(x - x_max),
axis=axis, keepdims=True))+x_max
class MixtureDensityNetwork:
"""
Mixture density network for outputs y on inputs x.
p((x,y), (z,theta))
= sum_{k=1}^K pi_k(x; theta) Normal(y; mu_k(x; theta), sigma_k(x; theta))
where pi, mu, sigma are the output of a neural network taking x
as input and with parameters theta. There are no latent variables
z, which are hidden variables we aim to be Bayesian about.
"""
def __init__(self, m):
self.m = m # here K is the amount of Mixtures
self.X_train, self.X_test, self.y_train, self.y_test = build_toy_dataset()
def mapping(self, X):
"""pi, mu, sigma = NN(x; theta)"""
hidden1 = Dense(15, activation='relu')(X) # fully-connected layer with 15 hidden units
hidden2 = Dense(15, activation='relu')(hidden1)
self.mus = Dense(self.K)(hidden2) # the means
self.sigmas = Dense(self.K, activation=K.exp)(hidden2) # the variance
self.pi = Dense(self.K, activation=K.softmax)(hidden2) # the mixture components
def neg_log_normal_mixture(self, true, parameters):
means = parameters[:,0*self.m:1*self.m]
sigmas = parameters[:,1*self.m:2*self.m]
pi = parameters[:,2*self.m:3*self.m]
# true_repeated = K.repeat_elements(true, self.m, axis=-1)
exponent = -0.5 * (true - means)**2 / sigmas
max_exponent = K.max(exponent, axis=-1, keepdims=True)
max_exponent_repeated = K.repeat_elements(max_exponent, self.m, axis=-1)
likelihood = pi * K.exp(exponent - max_exponent_repeated)
return K.mean(log_sum_exp(likelihood, axis=1))
def gen_model(self):
# The network
inputs = Input(shape=(1,))
hidden1 = Dense(15, activation='relu')(inputs) # fully-connected layer with 15 hidden units
hidden2 = Dense(15, activation='relu')(hidden1)
mus = Dense(self.m)(hidden2) # the means
sigmas = Dense(self.m, activation=K.exp)(hidden2) # the variance
pi = Dense(self.m, activation=K.softmax)(hidden2) # the mixture components
parameters = merge([mus, sigmas, pi], mode='concat')
self.model = Model(input=inputs, output=parameters)
self.model.compile(loss=self.neg_log_normal_mixture, optimizer='adam')
def fit_model(self):
self.model.fit(self.X_train, self.y_train,verbose=2)
if (__name__ == '__main__'):
out = MixtureDensityNetwork(5)
out.gen_model()
out.fit_model() |
wietseligthart/keycloak | model/map/src/main/java/org/keycloak/models/map/authSession/MapAuthenticationSessionEntity.java | /*
* Copyright 2020 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.
*/
package org.keycloak.models.map.authSession;
import org.keycloak.sessions.AuthenticationSessionModel;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
public class MapAuthenticationSessionEntity {
private String clientUUID;
private String authUserId;
private String redirectUri;
private String action;
private Set<String> clientScopes = new HashSet<>();
private Map<String, AuthenticationSessionModel.ExecutionStatus> executionStatus = new ConcurrentHashMap<>();
private String protocol;
private Map<String, String> clientNotes= new ConcurrentHashMap<>();;
private Map<String, String> authNotes = new ConcurrentHashMap<>();;
private Set<String> requiredActions = new HashSet<>();
private Map<String, String> userSessionNotes = new ConcurrentHashMap<>();
public Map<String, String> getUserSessionNotes() {
return userSessionNotes;
}
public void setUserSessionNotes(Map<String, String> userSessionNotes) {
this.userSessionNotes = userSessionNotes;
}
public String getClientUUID() {
return clientUUID;
}
public void setClientUUID(String clientUUID) {
this.clientUUID = clientUUID;
}
public String getAuthUserId() {
return authUserId;
}
public void setAuthUserId(String authUserId) {
this.authUserId = authUserId;
}
public String getRedirectUri() {
return redirectUri;
}
public void setRedirectUri(String redirectUri) {
this.redirectUri = redirectUri;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public Set<String> getClientScopes() {
return clientScopes;
}
public void setClientScopes(Set<String> clientScopes) {
this.clientScopes = clientScopes;
}
public Set<String> getRequiredActions() {
return requiredActions;
}
public void setRequiredActions(Set<String> requiredActions) {
this.requiredActions = requiredActions;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public Map<String, String> getClientNotes() {
return clientNotes;
}
public void setClientNotes(Map<String, String> clientNotes) {
this.clientNotes = clientNotes;
}
public Map<String, String> getAuthNotes() {
return authNotes;
}
public void setAuthNotes(Map<String, String> authNotes) {
this.authNotes = authNotes;
}
public Map<String, AuthenticationSessionModel.ExecutionStatus> getExecutionStatus() {
return executionStatus;
}
public void setExecutionStatus(Map<String, AuthenticationSessionModel.ExecutionStatus> executionStatus) {
this.executionStatus = executionStatus;
}
}
|
TForce1/pcg_gazebo | tests/test_model_factory.py | #!/usr/bin/env python
# Copyright (c) 2019 - The Procedural Generation for Gazebo authors
# For information on the respective copyright owner see the NOTICE file
#
# 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 unittest
import numpy as np
import os
import shutil
from pcg_gazebo import random
from pcg_gazebo.utils import generate_random_string
from pcg_gazebo.generators.creators import create_models_from_config, extrude
from pcg_gazebo.simulation.properties import Material, Pose
from pcg_gazebo.simulation import SimulationModel
from pcg_gazebo.path import Path
from shapely.geometry import Polygon, MultiPoint, LineString
def _get_colors():
color_names = list(Material.get_xkcd_colors_list().keys())
return [None, 'xkcd', 'random'] + \
[color_names[random.choice(range(len(color_names)))]
for _ in range(2)] + \
[[random.rand() for _ in range(4)] for _ in range(2)]
def _delete_generated_meshes(sdf):
for i in range(len(sdf.links)):
for j in range(len(sdf.links[i].collisions)):
if sdf.links[i].collisions[j].geometry.mesh is not None:
uri = Path(sdf.links[i].collisions[j].geometry.mesh.uri.value)
if os.path.isfile(uri.absolute_uri):
os.remove(uri.absolute_uri)
for j in range(len(sdf.links[i].visuals)):
if sdf.links[i].visuals[j].geometry.mesh is not None:
uri = Path(sdf.links[i].visuals[j].geometry.mesh.uri.value)
if os.path.isfile(uri.absolute_uri):
os.remove(uri.absolute_uri)
class TestModelFactory(unittest.TestCase):
def test_box_after_random_seed(self):
box_name = generate_random_string(5)
seed = random.randint(0, 10000)
random.init_random_state(seed)
random_box = dict(
type='box',
args=dict(
size="__import__('pcg_gazebo').random.rand(3)",
mass="__import__('pcg_gazebo').random.rand()",
name=box_name
)
)
ref = create_models_from_config([random_box])[0]
for _ in range(3):
random.init_random_state(seed)
model = create_models_from_config([random_box])[0]
self.assertEqual(ref.to_sdf(), model.to_sdf())
random.init_random_state(seed)
refs = create_models_from_config(
[random_box for _ in range(3)])
for _ in range(3):
random.init_random_state(seed)
models = create_models_from_config(
[random_box for _ in range(3)])
for r, m in zip(refs, models):
self.assertEqual(r.to_sdf(), m.to_sdf())
def test_sphere_after_random_seed(self):
sphere_name = generate_random_string(5)
seed = random.randint(0, 10000)
random.init_random_state(seed)
random_sphere = dict(
type='sphere',
args=dict(
radius="__import__('pcg_gazebo').random.rand()",
mass="__import__('pcg_gazebo').random.rand()",
name=sphere_name
)
)
ref = create_models_from_config([random_sphere])[0]
for _ in range(3):
random.init_random_state(seed)
model = create_models_from_config([random_sphere])[0]
self.assertEqual(ref.to_sdf(), model.to_sdf())
random.init_random_state(seed)
refs = create_models_from_config(
[random_sphere for _ in range(3)])
for _ in range(3):
random.init_random_state(seed)
models = create_models_from_config(
[random_sphere for _ in range(3)])
for r, m in zip(refs, models):
self.assertEqual(r.to_sdf(), m.to_sdf())
def test_cylinder_after_random_seed(self):
cyl_name = generate_random_string(5)
seed = random.randint(0, 10000)
random.init_random_state(seed)
random_cyl = dict(
type='cylinder',
args=dict(
radius="__import__('pcg_gazebo').random.rand()",
length="__import__('pcg_gazebo').random.rand()",
mass="__import__('pcg_gazebo').random.rand()",
name=cyl_name
)
)
ref = create_models_from_config([random_cyl])[0]
for _ in range(3):
random.init_random_state(seed)
model = create_models_from_config([random_cyl])[0]
self.assertEqual(ref.to_sdf(), model.to_sdf())
random.init_random_state(seed)
refs = create_models_from_config(
[random_cyl for _ in range(3)])
for _ in range(3):
random.init_random_state(seed)
models = create_models_from_config(
[random_cyl for _ in range(3)])
for r, m in zip(refs, models):
self.assertEqual(r.to_sdf(), m.to_sdf())
def test_static_box_model(self):
for color in _get_colors():
name = generate_random_string(3)
pose = [random.rand() for _ in range(6)]
size = [random.rand() for _ in range(3)]
model_config = [
dict(
type='box',
args=dict(
size=size,
name=name,
pose=pose,
color=color,
collision_parameters=dict(
mu=random.uniform(0, 10),
mu2=random.uniform(0, 10),
friction=random.uniform(0, 10),
friction2=random.uniform(0, 10),
slip1=random.uniform(0, 1),
slip2=random.uniform(0, 1),
rolling_friction=random.uniform(0, 1),
fdir1=[0, 0, 0],
max_contacts=1,
soft_cfm=random.uniform(0, 10),
soft_erp=random.uniform(0, 10),
kp=random.uniform(0, 100000),
kd=random.uniform(0, 10),
max_vel=random.uniform(0, 0.1),
min_depth=random.uniform(0, 0.1),
split_impulse=False,
split_impulse_penetration_threshold=-0.01,
restitution_coefficient=random.uniform(0, 1),
threshold=random.uniform(0, 1)
)
))
]
models = create_models_from_config(model_config)
self.assertEqual(len(models), 1)
self.assertIsInstance(models[0], SimulationModel)
# Test pose of the model
self.assertEqual(models[0].pose.position.tolist(), pose[0:3])
q = Pose.rpy2quat(*pose[3::])
diff = Pose.get_transform(models[0].pose.quat, q)
# Test model properties
self.assertAlmostEqual(np.sum(diff[0:3]), 0)
self.assertTrue(models[0].static)
self.assertEqual(len(models[0].links), 1)
link_name = models[0].link_names[0]
# Test visual element
self.assertEqual(len(models[0].links[link_name].visuals), 1)
geometry = models[0].links[link_name].visuals[0].geometry
self.assertEqual(geometry.get_type(), 'box')
self.assertEqual(geometry.get_param('size'), size)
# Test collision element
self.assertEqual(len(models[0].links[link_name].collisions), 1)
collision = models[0].links[link_name].get_collision_by_name(
'collision')
tags = ['mu', 'mu2', 'slip1', 'slip2', 'fdir1']
for tag in tags:
self.assertEqual(
collision.get_ode_friction_param(tag),
model_config[0]['args']['collision_parameters'][tag])
tags = ['friction', 'friction2', 'rolling_friction', 'fdir1']
for tag in tags:
self.assertEqual(
collision.get_bullet_friction_param(tag),
model_config[0]['args']['collision_parameters'][tag])
tags = ['soft_cfm', 'soft_erp', 'kp', 'kd', 'max_vel', 'min_depth']
for tag in tags:
self.assertEqual(
collision.get_ode_contact_param(tag),
model_config[0]['args']['collision_parameters'][tag])
tags = ['soft_cfm', 'soft_erp', 'kp', 'kd', 'split_impulse',
'split_impulse_penetration_threshold']
for tag in tags:
self.assertEqual(
collision.get_bullet_contact_param(tag),
model_config[0]['args']['collision_parameters'][tag])
tags = ['restitution_coefficient', 'threshold']
print(collision.sdf)
for tag in tags:
self.assertEqual(
collision.get_bounce_param(tag),
model_config[0]['args']['collision_parameters'][tag])
geometry = collision.geometry
self.assertEqual(geometry.get_type(), 'box')
self.assertEqual(geometry.get_param('size'), size)
# Test color exists
material = models[0].links[link_name].visuals[0].material
self.assertIsNotNone(material)
self.assertIsNotNone(material.ambient)
self.assertIsNotNone(material.diffuse)
if not isinstance(
color, str) and isinstance(
color, list) and color is not None:
self.assertEqual(material.ambient.value, color)
self.assertEqual(material.diffuse.value, color)
def test_dynamic_box_model(self):
for color in _get_colors():
name = generate_random_string(3)
pose = [random.rand() for _ in range(6)]
size = [random.rand() for _ in range(3)]
mass = random.rand()
model_config = [
dict(
type='box',
args=dict(
size=size,
name=name,
pose=pose,
mass=mass,
color=color,
collision_parameters=dict(
mu=random.uniform(0, 10),
mu2=random.uniform(0, 10),
friction=random.uniform(0, 10),
friction2=random.uniform(0, 10),
slip1=random.uniform(0, 1),
slip2=random.uniform(0, 1),
rolling_friction=random.uniform(0, 1),
fdir1=[0, 0, 0],
max_contacts=1,
soft_cfm=random.uniform(0, 10),
soft_erp=random.uniform(0, 10),
kp=random.uniform(0, 100000),
kd=random.uniform(0, 10),
max_vel=random.uniform(0, 0.1),
min_depth=random.uniform(0, 0.1),
split_impulse=False,
split_impulse_penetration_threshold=-0.01,
restitution_coefficient=random.uniform(0, 1),
threshold=random.uniform(0, 1)
)
))
]
models = create_models_from_config(model_config)
self.assertEqual(len(models), 1)
self.assertIsInstance(models[0], SimulationModel)
# Test pose of the model
self.assertEqual(models[0].pose.position.tolist(), pose[0:3])
q = Pose.rpy2quat(*pose[3::])
diff = Pose.get_transform(models[0].pose.quat, q)
# Test model properties
self.assertAlmostEqual(np.sum(diff[0:3]), 0)
self.assertFalse(models[0].static)
self.assertEqual(len(models[0].links), 1)
link_name = models[0].link_names[0]
# Test link properties
link = models[0].links[link_name]
self.assertEqual(link.inertial.mass, mass)
self.assertAlmostEqual(link.inertial.ixx,
1. / 12 * mass * (size[1]**2 + size[2]**2))
self.assertAlmostEqual(link.inertial.iyy,
1. / 12 * mass * (size[0]**2 + size[2]**2))
self.assertAlmostEqual(link.inertial.izz,
1. / 12 * mass * (size[0]**2 + size[1]**2))
self.assertEqual(link.inertial.ixy, 0)
self.assertEqual(link.inertial.ixz, 0)
self.assertEqual(link.inertial.iyz, 0)
# Test visual element
self.assertEqual(len(link.visuals), 1)
geometry = link.visuals[0].geometry
self.assertEqual(geometry.get_type(), 'box')
self.assertEqual(geometry.get_param('size'), size)
# Test collision element
self.assertEqual(len(link.collisions), 1)
collision = link.get_collision_by_name('collision')
tags = ['mu', 'mu2', 'slip1', 'slip2', 'fdir1']
for tag in tags:
self.assertEqual(
collision.get_ode_friction_param(tag),
model_config[0]['args']['collision_parameters'][tag])
tags = ['friction', 'friction2', 'rolling_friction', 'fdir1']
for tag in tags:
self.assertEqual(
collision.get_bullet_friction_param(tag),
model_config[0]['args']['collision_parameters'][tag])
tags = ['soft_cfm', 'soft_erp', 'kp', 'kd', 'max_vel', 'min_depth']
for tag in tags:
self.assertEqual(
collision.get_ode_contact_param(tag),
model_config[0]['args']['collision_parameters'][tag])
tags = ['soft_cfm', 'soft_erp', 'kp', 'kd', 'split_impulse',
'split_impulse_penetration_threshold']
for tag in tags:
self.assertEqual(
collision.get_bullet_contact_param(tag),
model_config[0]['args']['collision_parameters'][tag])
tags = ['restitution_coefficient', 'threshold']
for tag in tags:
self.assertEqual(
collision.get_bounce_param(tag),
model_config[0]['args']['collision_parameters'][tag])
geometry = collision.geometry
self.assertEqual(geometry.get_type(), 'box')
self.assertEqual(geometry.get_param('size'), size)
# Test color exists
material = models[0].links[link_name].visuals[0].material
self.assertIsNotNone(material)
self.assertIsNotNone(material.ambient)
self.assertIsNotNone(material.diffuse)
if not isinstance(
color, str) and isinstance(
color, list) and color is not None:
self.assertEqual(material.ambient.value, color)
self.assertEqual(material.diffuse.value, color)
def test_box_factory_fixed_args_with_permutation(self):
for color in _get_colors():
n_sizes = random.randint(2, 5)
n_masses = random.randint(2, 5)
name = generate_random_string(3)
sizes = [[random.rand() for _ in range(3)]
for _ in range(n_sizes)]
pose = [random.rand() for _ in range(6)]
masses = [random.rand() for _ in range(n_masses)]
model_config = [
dict(
type='box_factory',
args=dict(
name=name,
size=sizes,
mass=masses,
pose=pose,
use_permutation=True,
color=color
))
]
models = create_models_from_config(model_config)
self.assertEqual(len(models), n_sizes * n_masses)
for i in range(len(models)):
# Check the name generator with counter
self.assertIn(name + '_', models[i].name)
self.assertTrue(models[i].name.split('_')[-1].isdigit())
self.assertIsInstance(models[i], SimulationModel)
# Test pose of the model
self.assertEqual(models[i].pose.position.tolist(), pose[0:3])
q = Pose.rpy2quat(*pose[3::])
diff = Pose.get_transform(models[i].pose.quat, q)
# Test model properties
self.assertAlmostEqual(np.sum(diff[0:3]), 0)
self.assertFalse(models[i].static)
self.assertEqual(len(models[i].links), 1)
link_name = models[i].link_names[0]
self.assertIn(models[i].links[link_name].inertial.mass, masses)
# Test visual element
self.assertEqual(len(models[i].links[link_name].visuals), 1)
geometry = models[i].links[link_name].visuals[0].geometry
self.assertEqual(geometry.get_type(), 'box')
self.assertIn(geometry.get_param('size'), sizes)
# Test collision element
self.assertEqual(len(models[i].links[link_name].collisions), 1)
geometry = models[i].links[link_name].collisions[0].geometry
self.assertEqual(geometry.get_type(), 'box')
self.assertIn(geometry.get_param('size'), sizes)
# Test color exists
material = models[i].links[link_name].visuals[0].material
self.assertIsNotNone(material)
self.assertIsNotNone(material.ambient)
self.assertIsNotNone(material.diffuse)
if not isinstance(
color, str) and isinstance(
color, list) and color is not None:
self.assertEqual(material.ambient.value, color)
self.assertEqual(material.diffuse.value, color)
def test_box_factory_fixed_args_no_permutation(self):
for color in _get_colors():
n_models = random.randint(2, 5)
name = generate_random_string(3)
sizes = [[random.rand() for _ in range(3)]
for _ in range(n_models)]
pose = [random.rand() for _ in range(6)]
masses = [random.rand() for _ in range(n_models)]
model_config = [
dict(
type='box_factory',
args=dict(
name=name,
size=sizes,
mass=masses,
pose=pose,
use_permutation=False,
color=color
))
]
models = create_models_from_config(model_config)
self.assertEqual(len(models), n_models)
for i in range(len(models)):
# Check the name generator with counter
self.assertIn(name + '_', models[i].name)
self.assertTrue(models[i].name.split('_')[-1].isdigit())
self.assertIsInstance(models[i], SimulationModel)
# Test pose of the model
self.assertEqual(models[i].pose.position.tolist(), pose[0:3])
q = Pose.rpy2quat(*pose[3::])
diff = Pose.get_transform(models[i].pose.quat, q)
# Test model properties
self.assertAlmostEqual(np.sum(diff[0:3]), 0)
self.assertFalse(models[i].static)
self.assertEqual(len(models[i].links), 1)
link_name = models[i].link_names[0]
self.assertIn(models[i].links[link_name].inertial.mass, masses)
# Test visual element
self.assertEqual(len(models[i].links[link_name].visuals), 1)
geometry = models[i].links[link_name].visuals[0].geometry
self.assertEqual(geometry.get_type(), 'box')
self.assertIn(geometry.get_param('size'), sizes)
# Test collision element
self.assertEqual(len(models[i].links[link_name].collisions), 1)
geometry = models[i].links[link_name].collisions[0].geometry
self.assertEqual(geometry.get_type(), 'box')
self.assertIn(geometry.get_param('size'), sizes)
# Test color exists
material = models[i].links[link_name].visuals[0].material
self.assertIsNotNone(material)
self.assertIsNotNone(material.ambient)
self.assertIsNotNone(material.diffuse)
if not isinstance(
color, str) and isinstance(
color, list) and color is not None:
self.assertEqual(material.ambient.value, color)
self.assertEqual(material.diffuse.value, color)
def test_box_factory_lambda_args_with_permutation(self):
for color in _get_colors():
n_sizes = random.randint(2, 5)
n_masses = random.randint(2, 5)
name = generate_random_string(3)
sizes = "__import__('numpy').random.random(({}, 3))".format(
n_sizes)
masses = "__import__('numpy').linspace(1, 10, {})".format(n_masses)
pose = [random.rand() for _ in range(6)]
model_config = [
dict(
type='box_factory',
args=dict(
name=name,
size=sizes,
mass=masses,
pose=pose,
use_permutation=True,
color=color
))
]
models = create_models_from_config(model_config)
self.assertEqual(len(models), n_sizes * n_masses)
for i in range(len(models)):
# Check the name generator with counter
self.assertIn(name + '_', models[i].name)
self.assertTrue(models[i].name.split('_')[-1].isdigit())
self.assertIsInstance(models[i], SimulationModel)
# Test pose of the model
self.assertEqual(models[i].pose.position.tolist(), pose[0:3])
q = Pose.rpy2quat(*pose[3::])
diff = Pose.get_transform(models[i].pose.quat, q)
# Test model properties
self.assertAlmostEqual(np.sum(diff[0:3]), 0)
self.assertFalse(models[i].static)
self.assertEqual(len(models[i].links), 1)
link_name = models[i].link_names[0]
# Test visual element
self.assertEqual(len(models[i].links[link_name].visuals), 1)
geometry = models[i].links[link_name].visuals[0].geometry
self.assertEqual(geometry.get_type(), 'box')
# Test collision element
self.assertEqual(len(models[i].links[link_name].collisions), 1)
geometry = models[i].links[link_name].collisions[0].geometry
self.assertEqual(geometry.get_type(), 'box')
# Test color exists
material = models[i].links[link_name].visuals[0].material
self.assertIsNotNone(material)
self.assertIsNotNone(material.ambient)
self.assertIsNotNone(material.diffuse)
if not isinstance(
color, str) and isinstance(
color, list) and color is not None:
self.assertEqual(material.ambient.value, color)
self.assertEqual(material.diffuse.value, color)
def text_box_forced_permutation(self):
n_sizes = 2
n_masses = 3
name = generate_random_string(3)
# Test with lambda functions
sizes = "__import__('numpy').random.random(({}, 3))".format(n_sizes)
masses = "__import__('numpy').linspace(1, 10, {})".format(n_masses)
pose = [random.rand() for _ in range(6)]
model_config = [
dict(
type='box_factory',
args=dict(
name=name,
size=sizes,
mass=masses,
pose=pose,
use_permutation=False,
color=None
))
]
models = create_models_from_config(model_config)
self.assertEqual(len(models), n_sizes * n_masses)
# Test with fixed arguments
sizes = [[random.rand() for _ in range(3)] for _ in range(n_sizes)]
masses = [random.rand() for _ in range(n_masses)]
pose = [random.rand() for _ in range(6)]
model_config = [
dict(
type='box_factory',
args=dict(
name=name,
size=sizes,
mass=masses,
pose=pose,
use_permutation=False,
color=None
))
]
models = create_models_from_config(model_config)
self.assertEqual(len(models), n_sizes * n_masses)
def test_static_cylinder_model(self):
for color in _get_colors():
name = generate_random_string(3)
pose = [random.rand() for _ in range(6)]
radius = random.rand()
length = random.rand()
model_config = [
dict(
type='cylinder',
args=dict(
radius=radius,
length=length,
name=name,
pose=pose,
color=color,
collision_parameters=dict(
mu=random.uniform(0, 10),
mu2=random.uniform(0, 10),
friction=random.uniform(0, 10),
friction2=random.uniform(0, 10),
slip1=random.uniform(0, 1),
slip2=random.uniform(0, 1),
rolling_friction=random.uniform(0, 1),
fdir1=[0, 0, 0],
max_contacts=1,
soft_cfm=random.uniform(0, 10),
soft_erp=random.uniform(0, 10),
kp=random.uniform(0, 100000),
kd=random.uniform(0, 10),
max_vel=random.uniform(0, 0.1),
min_depth=random.uniform(0, 0.1),
split_impulse=False,
split_impulse_penetration_threshold=-0.01,
restitution_coefficient=random.uniform(0, 1),
threshold=random.uniform(0, 1)
)
))
]
models = create_models_from_config(model_config)
self.assertEqual(len(models), 1)
self.assertIsInstance(models[0], SimulationModel)
# Test pose of the model
self.assertEqual(models[0].pose.position.tolist(), pose[0:3])
q = Pose.rpy2quat(*pose[3::])
diff = Pose.get_transform(models[0].pose.quat, q)
# Test model properties
self.assertAlmostEqual(np.sum(diff[0:3]), 0)
self.assertTrue(models[0].static)
self.assertEqual(len(models[0].links), 1)
link_name = models[0].link_names[0]
# Test visual element
self.assertEqual(len(models[0].links[link_name].visuals), 1)
geometry = models[0].links[link_name].visuals[0].geometry
self.assertEqual(geometry.get_type(), 'cylinder')
self.assertEqual(geometry.get_param('radius'), radius)
self.assertEqual(geometry.get_param('length'), length)
# Test collision element
self.assertEqual(len(models[0].links[link_name].collisions), 1)
collision = models[0].links[link_name].get_collision_by_name(
'collision')
tags = ['mu', 'mu2', 'slip1', 'slip2', 'fdir1']
for tag in tags:
self.assertEqual(
collision.get_ode_friction_param(tag),
model_config[0]['args']['collision_parameters'][tag])
tags = ['friction', 'friction2', 'rolling_friction', 'fdir1']
for tag in tags:
self.assertEqual(
collision.get_bullet_friction_param(tag),
model_config[0]['args']['collision_parameters'][tag])
tags = ['soft_cfm', 'soft_erp', 'kp', 'kd', 'max_vel', 'min_depth']
for tag in tags:
self.assertEqual(
collision.get_ode_contact_param(tag),
model_config[0]['args']['collision_parameters'][tag])
tags = ['soft_cfm', 'soft_erp', 'kp', 'kd', 'split_impulse',
'split_impulse_penetration_threshold']
for tag in tags:
self.assertEqual(
collision.get_bullet_contact_param(tag),
model_config[0]['args']['collision_parameters'][tag])
tags = ['restitution_coefficient', 'threshold']
for tag in tags:
self.assertEqual(
collision.get_bounce_param(tag),
model_config[0]['args']['collision_parameters'][tag])
geometry = models[0].links[link_name].collisions[0].geometry
self.assertEqual(geometry.get_type(), 'cylinder')
self.assertEqual(geometry.get_param('radius'), radius)
self.assertEqual(geometry.get_param('length'), length)
# Test color exists
material = models[0].links[link_name].visuals[0].material
self.assertIsNotNone(material)
self.assertIsNotNone(material.ambient)
self.assertIsNotNone(material.diffuse)
if not isinstance(
color, str) and isinstance(
color, list) and color is not None:
self.assertEqual(material.ambient.value, color)
self.assertEqual(material.diffuse.value, color)
def test_dynamic_cylinder_model(self):
for color in _get_colors():
name = generate_random_string(3)
pose = [random.rand() for _ in range(6)]
radius = random.rand()
length = random.rand()
mass = random.rand()
model_config = [
dict(
type='cylinder',
args=dict(
radius=radius,
length=length,
mass=mass,
name=name,
pose=pose,
color=color,
collision_parameters=dict(
mu=random.uniform(0, 10),
mu2=random.uniform(0, 10),
friction=random.uniform(0, 10),
friction2=random.uniform(0, 10),
slip1=random.uniform(0, 1),
slip2=random.uniform(0, 1),
rolling_friction=random.uniform(0, 1),
fdir1=[0, 0, 0],
max_contacts=1,
soft_cfm=random.uniform(0, 10),
soft_erp=random.uniform(0, 10),
kp=random.uniform(0, 100000),
kd=random.uniform(0, 10),
max_vel=random.uniform(0, 0.1),
min_depth=random.uniform(0, 0.1),
split_impulse=False,
split_impulse_penetration_threshold=-0.01,
restitution_coefficient=random.uniform(0, 1),
threshold=random.uniform(0, 1)
)
))
]
models = create_models_from_config(model_config)
self.assertEqual(len(models), 1)
self.assertIsInstance(models[0], SimulationModel)
# Test pose of the model
self.assertEqual(models[0].pose.position.tolist(), pose[0:3])
q = Pose.rpy2quat(*pose[3::])
diff = Pose.get_transform(models[0].pose.quat, q)
# Test model properties
self.assertAlmostEqual(np.sum(diff[0:3]), 0)
self.assertFalse(models[0].static)
self.assertEqual(len(models[0].links), 1)
link_name = models[0].link_names[0]
# Test link properties
link = models[0].links[link_name]
self.assertEqual(link.inertial.mass, mass)
self.assertAlmostEqual(
link.inertial.ixx,
1. / 12 * mass * (3 * radius**2 + length**2))
self.assertAlmostEqual(
link.inertial.iyy,
1. / 12 * mass * (3 * radius**2 + length**2))
self.assertAlmostEqual(link.inertial.izz, 0.5 * mass * radius**2)
self.assertEqual(link.inertial.ixy, 0)
self.assertEqual(link.inertial.ixz, 0)
self.assertEqual(link.inertial.iyz, 0)
# Test visual element
self.assertEqual(len(models[0].links[link_name].visuals), 1)
geometry = models[0].links[link_name].visuals[0].geometry
self.assertEqual(geometry.get_type(), 'cylinder')
self.assertEqual(geometry.get_param('radius'), radius)
self.assertEqual(geometry.get_param('length'), length)
# Test collision element
self.assertEqual(len(models[0].links[link_name].collisions), 1)
collision = models[0].links[link_name].get_collision_by_name(
'collision')
tags = ['mu', 'mu2', 'slip1', 'slip2', 'fdir1']
for tag in tags:
self.assertEqual(
collision.get_ode_friction_param(tag),
model_config[0]['args']['collision_parameters'][tag])
tags = ['friction', 'friction2', 'rolling_friction', 'fdir1']
for tag in tags:
self.assertEqual(
collision.get_bullet_friction_param(tag),
model_config[0]['args']['collision_parameters'][tag])
tags = ['soft_cfm', 'soft_erp', 'kp', 'kd', 'max_vel', 'min_depth']
for tag in tags:
self.assertEqual(
collision.get_ode_contact_param(tag),
model_config[0]['args']['collision_parameters'][tag])
tags = ['soft_cfm', 'soft_erp', 'kp', 'kd', 'split_impulse',
'split_impulse_penetration_threshold']
for tag in tags:
self.assertEqual(
collision.get_bullet_contact_param(tag),
model_config[0]['args']['collision_parameters'][tag])
tags = ['restitution_coefficient', 'threshold']
for tag in tags:
self.assertEqual(
collision.get_bounce_param(tag),
model_config[0]['args']['collision_parameters'][tag])
geometry = models[0].links[link_name].collisions[0].geometry
self.assertEqual(geometry.get_type(), 'cylinder')
self.assertEqual(geometry.get_param('radius'), radius)
self.assertEqual(geometry.get_param('length'), length)
# Test color exists
material = models[0].links[link_name].visuals[0].material
self.assertIsNotNone(material)
self.assertIsNotNone(material.ambient)
self.assertIsNotNone(material.diffuse)
if not isinstance(
color, str) and isinstance(
color, list) and color is not None:
self.assertEqual(material.ambient.value, color)
self.assertEqual(material.diffuse.value, color)
def test_cylinder_factory_fixed_args_with_permutation(self):
for color in _get_colors():
n_radius = random.randint(2, 4)
n_length = random.randint(2, 4)
n_masses = random.randint(2, 4)
name = generate_random_string(3)
radius = [random.rand() for _ in range(n_radius)]
length = [random.rand() for _ in range(n_length)]
pose = [random.rand() for _ in range(6)]
masses = [random.rand() for _ in range(n_masses)]
model_config = [
dict(
type='cylinder_factory',
args=dict(
name=name,
radius=radius,
length=length,
mass=masses,
pose=pose,
use_permutation=True,
color=color
))
]
models = create_models_from_config(model_config)
self.assertEqual(len(models), n_radius * n_length * n_masses)
for i in range(len(models)):
# Check the name generator with counter
self.assertIn(name + '_', models[i].name)
self.assertTrue(models[i].name.split('_')[-1].isdigit())
self.assertIsInstance(models[i], SimulationModel)
# Test pose of the model
self.assertEqual(models[i].pose.position.tolist(), pose[0:3])
q = Pose.rpy2quat(*pose[3::])
diff = Pose.get_transform(models[i].pose.quat, q)
# Test model properties
self.assertAlmostEqual(np.sum(diff[0:3]), 0)
self.assertFalse(models[i].static)
self.assertEqual(len(models[i].links), 1)
link_name = models[i].link_names[0]
self.assertIn(models[i].links[link_name].inertial.mass, masses)
# Test visual element
self.assertEqual(len(models[i].links[link_name].visuals), 1)
geometry = models[i].links[link_name].visuals[0].geometry
self.assertEqual(geometry.get_type(), 'cylinder')
self.assertIn(geometry.get_param('radius'), radius)
self.assertIn(geometry.get_param('length'), length)
# Test collision element
self.assertEqual(len(models[i].links[link_name].collisions), 1)
geometry = models[i].links[link_name].collisions[0].geometry
self.assertEqual(geometry.get_type(), 'cylinder')
self.assertIn(geometry.get_param('radius'), radius)
self.assertIn(geometry.get_param('length'), length)
# Test color exists
material = models[i].links[link_name].visuals[0].material
self.assertIsNotNone(material)
self.assertIsNotNone(material.ambient)
self.assertIsNotNone(material.diffuse)
if not isinstance(
color, str) and isinstance(
color, list) and color is not None:
self.assertEqual(material.ambient.value, color)
self.assertEqual(material.diffuse.value, color)
def test_cylinder_factory_fixed_args_no_permutation(self):
for color in _get_colors():
n_models = random.randint(2, 4)
name = generate_random_string(3)
radius = [random.rand() for _ in range(n_models)]
length = [random.rand() for _ in range(n_models)]
pose = [random.rand() for _ in range(6)]
masses = [random.rand() for _ in range(n_models)]
model_config = [
dict(
type='cylinder_factory',
args=dict(
name=name,
radius=radius,
length=length,
mass=masses,
pose=pose,
use_permutation=False,
color=color
))
]
models = create_models_from_config(model_config)
self.assertEqual(len(models), n_models)
for i in range(len(models)):
# Check the name generator with counter
self.assertIn(name + '_', models[i].name)
self.assertTrue(models[i].name.split('_')[-1].isdigit())
self.assertIsInstance(models[i], SimulationModel)
# Test pose of the model
self.assertEqual(models[i].pose.position.tolist(), pose[0:3])
q = Pose.rpy2quat(*pose[3::])
diff = Pose.get_transform(models[i].pose.quat, q)
# Test model properties
self.assertAlmostEqual(np.sum(diff[0:3]), 0)
self.assertFalse(models[i].static)
self.assertEqual(len(models[i].links), 1)
link_name = models[i].link_names[0]
self.assertIn(models[i].links[link_name].inertial.mass, masses)
# Test visual element
self.assertEqual(len(models[i].links[link_name].visuals), 1)
geometry = models[i].links[link_name].visuals[0].geometry
self.assertEqual(geometry.get_type(), 'cylinder')
self.assertIn(geometry.get_param('radius'), radius)
self.assertIn(geometry.get_param('length'), length)
# Test collision element
self.assertEqual(len(models[i].links[link_name].collisions), 1)
geometry = models[i].links[link_name].collisions[0].geometry
self.assertEqual(geometry.get_type(), 'cylinder')
self.assertIn(geometry.get_param('radius'), radius)
self.assertIn(geometry.get_param('length'), length)
# Test color exists
material = models[i].links[link_name].visuals[0].material
self.assertIsNotNone(material)
self.assertIsNotNone(material.ambient)
self.assertIsNotNone(material.diffuse)
if not isinstance(
color, str) and isinstance(
color, list) and color is not None:
self.assertEqual(material.ambient.value, color)
self.assertEqual(material.diffuse.value, color)
def test_cylinder_factory_lambda_args_with_permutation(self):
for color in _get_colors():
n_radius = random.randint(2, 4)
n_length = random.randint(2, 4)
n_masses = random.randint(2, 4)
name = generate_random_string(3)
radius = "__import__('numpy').random.random({})".format(n_radius)
length = "__import__('numpy').linspace(1, 10, {})".format(n_length)
masses = "__import__('numpy').linspace(1, 10, {})".format(n_masses)
pose = [random.rand() for _ in range(6)]
model_config = [
dict(
type='cylinder_factory',
args=dict(
name=name,
radius=radius,
length=length,
mass=masses,
pose=pose,
use_permutation=True,
color=color
))
]
models = create_models_from_config(model_config)
self.assertEqual(len(models), n_radius * n_length * n_masses)
for i in range(len(models)):
# Check the name generator with counter
self.assertIn(name + '_', models[i].name)
self.assertTrue(models[i].name.split('_')[-1].isdigit())
self.assertIsInstance(models[i], SimulationModel)
# Test pose of the model
self.assertEqual(models[i].pose.position.tolist(), pose[0:3])
q = Pose.rpy2quat(*pose[3::])
diff = Pose.get_transform(models[i].pose.quat, q)
# Test model properties
self.assertAlmostEqual(np.sum(diff[0:3]), 0)
self.assertFalse(models[i].static)
self.assertEqual(len(models[i].links), 1)
link_name = models[i].link_names[0]
# Test visual element
self.assertEqual(len(models[i].links[link_name].visuals), 1)
geometry = models[i].links[link_name].visuals[0].geometry
self.assertEqual(geometry.get_type(), 'cylinder')
# Test collision element
self.assertEqual(len(models[i].links[link_name].collisions), 1)
geometry = models[i].links[link_name].collisions[0].geometry
self.assertEqual(geometry.get_type(), 'cylinder')
# Test color exists
material = models[i].links[link_name].visuals[0].material
self.assertIsNotNone(material)
self.assertIsNotNone(material.ambient)
self.assertIsNotNone(material.diffuse)
if not isinstance(
color, str) and isinstance(
color, list) and color is not None:
self.assertEqual(material.ambient.value, color)
self.assertEqual(material.diffuse.value, color)
def test_cylinder_forced_permutation(self):
n_radius = 1
n_masses = 2
n_length = 3
name = generate_random_string(3)
# Test with lambda functions
radius = "__import__('numpy').random.random({})".format(n_radius)
length = "__import__('numpy').random.random({})".format(n_length)
masses = "__import__('numpy').linspace(1, 10, {})".format(n_masses)
pose = [random.rand() for _ in range(6)]
model_config = [
dict(
type='cylinder_factory',
args=dict(
name=name,
radius=radius,
length=length,
mass=masses,
pose=pose,
use_permutation=False,
color=None
))
]
models = create_models_from_config(model_config)
self.assertEqual(len(models), n_radius * n_length * n_masses)
# Test with fixed arguments
radius = [random.rand() for _ in range(n_radius)]
length = [random.rand() for _ in range(n_length)]
masses = [random.rand() for _ in range(n_masses)]
pose = [random.rand() for _ in range(6)]
model_config = [
dict(
type='cylinder_factory',
args=dict(
name=name,
radius=radius,
length=length,
mass=masses,
pose=pose,
use_permutation=False,
color=None
))
]
models = create_models_from_config(model_config)
self.assertEqual(len(models), n_radius * n_length * n_masses)
def test_static_sphere_model(self):
for color in _get_colors():
name = generate_random_string(3)
pose = [random.rand() for _ in range(6)]
radius = random.rand()
model_config = [
dict(
type='sphere',
args=dict(
radius=radius,
name=name,
pose=pose,
color=color,
collision_parameters=dict(
mu=random.uniform(0, 10),
mu2=random.uniform(0, 10),
friction=random.uniform(0, 10),
friction2=random.uniform(0, 10),
slip1=random.uniform(0, 1),
slip2=random.uniform(0, 1),
rolling_friction=random.uniform(0, 1),
fdir1=[0, 0, 0],
max_contacts=1,
soft_cfm=random.uniform(0, 10),
soft_erp=random.uniform(0, 10),
kp=random.uniform(0, 100000),
kd=random.uniform(0, 10),
max_vel=random.uniform(0, 0.1),
min_depth=random.uniform(0, 0.1),
split_impulse=False,
split_impulse_penetration_threshold=-0.01,
restitution_coefficient=random.uniform(0, 1),
threshold=random.uniform(0, 1)
)
))
]
models = create_models_from_config(model_config)
self.assertEqual(len(models), 1)
self.assertIsInstance(models[0], SimulationModel)
# Test pose of the model
self.assertEqual(models[0].pose.position.tolist(), pose[0:3])
q = Pose.rpy2quat(*pose[3::])
diff = Pose.get_transform(models[0].pose.quat, q)
# Test model properties
self.assertAlmostEqual(np.sum(diff[0:3]), 0)
self.assertTrue(models[0].static)
self.assertEqual(len(models[0].links), 1)
link_name = models[0].link_names[0]
# Test visual element
self.assertEqual(len(models[0].links[link_name].visuals), 1)
geometry = models[0].links[link_name].visuals[0].geometry
self.assertEqual(geometry.get_type(), 'sphere')
self.assertEqual(geometry.get_param('radius'), radius)
# Test collision element
self.assertEqual(len(models[0].links[link_name].collisions), 1)
collision = models[0].links[link_name].get_collision_by_name(
'collision')
tags = ['mu', 'mu2', 'slip1', 'slip2', 'fdir1']
for tag in tags:
self.assertEqual(
collision.get_ode_friction_param(tag),
model_config[0]['args']['collision_parameters'][tag])
tags = ['friction', 'friction2', 'rolling_friction', 'fdir1']
for tag in tags:
self.assertEqual(
collision.get_bullet_friction_param(tag),
model_config[0]['args']['collision_parameters'][tag])
tags = ['soft_cfm', 'soft_erp', 'kp', 'kd', 'max_vel', 'min_depth']
for tag in tags:
self.assertEqual(
collision.get_ode_contact_param(tag),
model_config[0]['args']['collision_parameters'][tag])
tags = ['soft_cfm', 'soft_erp', 'kp', 'kd', 'split_impulse',
'split_impulse_penetration_threshold']
for tag in tags:
self.assertEqual(
collision.get_bullet_contact_param(tag),
model_config[0]['args']['collision_parameters'][tag])
tags = ['restitution_coefficient', 'threshold']
for tag in tags:
self.assertEqual(
collision.get_bounce_param(tag),
model_config[0]['args']['collision_parameters'][tag])
geometry = models[0].links[link_name].collisions[0].geometry
self.assertEqual(geometry.get_type(), 'sphere')
self.assertEqual(geometry.get_param('radius'), radius)
# Test color exists
material = models[0].links[link_name].visuals[0].material
self.assertIsNotNone(material)
self.assertIsNotNone(material.ambient)
self.assertIsNotNone(material.diffuse)
if not isinstance(
color, str) and isinstance(
color, list) and color is not None:
self.assertEqual(material.ambient.value, color)
self.assertEqual(material.diffuse.value, color)
def test_dynamic_sphere_model(self):
for color in _get_colors():
name = generate_random_string(3)
pose = [random.rand() for _ in range(6)]
radius = random.rand()
mass = random.rand()
model_config = [
dict(
type='sphere',
args=dict(
radius=radius,
mass=mass,
name=name,
pose=pose,
color=color,
collision_parameters=dict(
mu=random.uniform(0, 10),
mu2=random.uniform(0, 10),
friction=random.uniform(0, 10),
friction2=random.uniform(0, 10),
slip1=random.uniform(0, 1),
slip2=random.uniform(0, 1),
rolling_friction=random.uniform(0, 1),
fdir1=[0, 0, 0],
max_contacts=1,
soft_cfm=random.uniform(0, 10),
soft_erp=random.uniform(0, 10),
kp=random.uniform(0, 100000),
kd=random.uniform(0, 10),
max_vel=random.uniform(0, 0.1),
min_depth=random.uniform(0, 0.1),
split_impulse=True,
split_impulse_penetration_threshold=-0.01,
restitution_coefficient=random.uniform(0, 1),
threshold=random.uniform(0, 1)
)
))
]
models = create_models_from_config(model_config)
self.assertEqual(len(models), 1)
self.assertIsInstance(models[0], SimulationModel)
# Test pose of the model
self.assertEqual(models[0].pose.position.tolist(), pose[0:3])
q = Pose.rpy2quat(*pose[3::])
diff = Pose.get_transform(models[0].pose.quat, q)
# Test model properties
self.assertAlmostEqual(np.sum(diff[0:3]), 0)
self.assertFalse(models[0].static)
self.assertEqual(len(models[0].links), 1)
link_name = models[0].link_names[0]
# Test link properties
link = models[0].links[link_name]
self.assertEqual(link.inertial.mass, mass)
inertia = 2. / 5 * mass * radius**2
self.assertAlmostEqual(link.inertial.ixx, inertia)
self.assertAlmostEqual(link.inertial.iyy, inertia)
self.assertAlmostEqual(link.inertial.izz, inertia)
self.assertEqual(link.inertial.ixy, 0)
self.assertEqual(link.inertial.ixz, 0)
self.assertEqual(link.inertial.iyz, 0)
# Test visual element
self.assertEqual(len(models[0].links[link_name].visuals), 1)
geometry = models[0].links[link_name].visuals[0].geometry
self.assertEqual(geometry.get_type(), 'sphere')
self.assertEqual(geometry.get_param('radius'), radius)
# Test collision element
self.assertEqual(len(models[0].links[link_name].collisions), 1)
collision = models[0].links[link_name].get_collision_by_name(
'collision')
tags = ['mu', 'mu2', 'slip1', 'slip2', 'fdir1']
for tag in tags:
self.assertEqual(
collision.get_ode_friction_param(tag),
model_config[0]['args']['collision_parameters'][tag])
tags = ['friction', 'friction2', 'rolling_friction', 'fdir1']
for tag in tags:
self.assertEqual(
collision.get_bullet_friction_param(tag),
model_config[0]['args']['collision_parameters'][tag])
tags = ['soft_cfm', 'soft_erp', 'kp', 'kd', 'max_vel', 'min_depth']
for tag in tags:
self.assertEqual(
collision.get_ode_contact_param(tag),
model_config[0]['args']['collision_parameters'][tag])
tags = ['soft_cfm', 'soft_erp', 'kp', 'kd', 'split_impulse',
'split_impulse_penetration_threshold']
for tag in tags:
self.assertEqual(
collision.get_bullet_contact_param(tag),
model_config[0]['args']['collision_parameters'][tag])
tags = ['restitution_coefficient', 'threshold']
for tag in tags:
self.assertEqual(
collision.get_bounce_param(tag),
model_config[0]['args']['collision_parameters'][tag])
geometry = models[0].links[link_name].collisions[0].geometry
self.assertEqual(geometry.get_type(), 'sphere')
self.assertEqual(geometry.get_param('radius'), radius)
# Test color exists
material = models[0].links[link_name].visuals[0].material
self.assertIsNotNone(material)
self.assertIsNotNone(material.ambient)
self.assertIsNotNone(material.diffuse)
if not isinstance(
color, str) and isinstance(
color, list) and color is not None:
self.assertEqual(material.ambient.value, color)
self.assertEqual(material.diffuse.value, color)
def test_sphere_factory_fixed_args_with_permutation(self):
for color in _get_colors():
n_radius = random.randint(2, 4)
n_masses = random.randint(2, 4)
name = generate_random_string(3)
radius = [random.rand() for _ in range(n_radius)]
pose = [random.rand() for _ in range(6)]
masses = [random.rand() for _ in range(n_masses)]
model_config = [
dict(
type='sphere_factory',
args=dict(
name=name,
radius=radius,
mass=masses,
pose=pose,
use_permutation=True,
color=color
))
]
models = create_models_from_config(model_config)
self.assertEqual(len(models), n_radius * n_masses)
for i in range(len(models)):
# Check the name generator with counter
self.assertIn(name + '_', models[i].name)
self.assertTrue(models[i].name.split('_')[-1].isdigit())
self.assertIsInstance(models[i], SimulationModel)
# Test pose of the model
self.assertEqual(models[i].pose.position.tolist(), pose[0:3])
q = Pose.rpy2quat(*pose[3::])
diff = Pose.get_transform(models[i].pose.quat, q)
# Test model properties
self.assertAlmostEqual(np.sum(diff[0:3]), 0)
self.assertFalse(models[i].static)
self.assertEqual(len(models[i].links), 1)
link_name = models[i].link_names[0]
self.assertIn(models[i].links[link_name].inertial.mass, masses)
# Test visual element
self.assertEqual(len(models[i].links[link_name].visuals), 1)
geometry = models[i].links[link_name].visuals[0].geometry
self.assertEqual(geometry.get_type(), 'sphere')
self.assertIn(geometry.get_param('radius'), radius)
# Test collision element
self.assertEqual(len(models[i].links[link_name].collisions), 1)
geometry = models[i].links[link_name].collisions[0].geometry
self.assertEqual(geometry.get_type(), 'sphere')
self.assertIn(geometry.get_param('radius'), radius)
# Test color exists
material = models[i].links[link_name].visuals[0].material
self.assertIsNotNone(material)
self.assertIsNotNone(material.ambient)
self.assertIsNotNone(material.diffuse)
if not isinstance(
color, str) and isinstance(
color, list) and color is not None:
self.assertEqual(material.ambient.value, color)
self.assertEqual(material.diffuse.value, color)
def test_sphere_factory_fixed_args_no_permutation(self):
for color in _get_colors():
n_models = random.randint(2, 4)
name = generate_random_string(3)
radius = [random.rand() for _ in range(n_models)]
pose = [random.rand() for _ in range(6)]
masses = [random.rand() for _ in range(n_models)]
model_config = [
dict(
type='sphere_factory',
args=dict(
name=name,
radius=radius,
mass=masses,
pose=pose,
use_permutation=False,
color=color
))
]
models = create_models_from_config(model_config)
self.assertEqual(len(models), n_models)
for i in range(len(models)):
# Check the name generator with counter
self.assertIn(name + '_', models[i].name)
self.assertTrue(models[i].name.split('_')[-1].isdigit())
self.assertIsInstance(models[i], SimulationModel)
# Test pose of the model
self.assertEqual(models[i].pose.position.tolist(), pose[0:3])
q = Pose.rpy2quat(*pose[3::])
diff = Pose.get_transform(models[i].pose.quat, q)
# Test model properties
self.assertAlmostEqual(np.sum(diff[0:3]), 0)
self.assertFalse(models[i].static)
self.assertEqual(len(models[i].links), 1)
link_name = models[i].link_names[0]
self.assertIn(models[i].links[link_name].inertial.mass, masses)
# Test visual element
self.assertEqual(len(models[i].links[link_name].visuals), 1)
geometry = models[i].links[link_name].visuals[0].geometry
self.assertEqual(geometry.get_type(), 'sphere')
self.assertIn(geometry.get_param('radius'), radius)
# Test collision element
self.assertEqual(len(models[i].links[link_name].collisions), 1)
geometry = models[i].links[link_name].collisions[0].geometry
self.assertEqual(geometry.get_type(), 'sphere')
self.assertIn(geometry.get_param('radius'), radius)
# Test color exists
material = models[i].links[link_name].visuals[0].material
self.assertIsNotNone(material)
self.assertIsNotNone(material.ambient)
self.assertIsNotNone(material.diffuse)
if not isinstance(
color, str) and isinstance(
color, list) and color is not None:
self.assertEqual(material.ambient.value, color)
self.assertEqual(material.diffuse.value, color)
def test_sphere_factory_lambda_args_with_permutation(self):
for color in _get_colors():
n_radius = random.randint(2, 4)
n_masses = random.randint(2, 4)
name = generate_random_string(3)
radius = "__import__('numpy').random.random({})".format(n_radius)
masses = "__import__('numpy').linspace(1, 10, {})".format(n_masses)
pose = [random.rand() for _ in range(6)]
model_config = [
dict(
type='sphere_factory',
args=dict(
name=name,
radius=radius,
mass=masses,
pose=pose,
use_permutation=True,
color=color
))
]
models = create_models_from_config(model_config)
self.assertEqual(len(models), n_radius * n_masses)
for i in range(len(models)):
# Check the name generator with counter
self.assertIn(name + '_', models[i].name)
self.assertTrue(models[i].name.split('_')[-1].isdigit())
self.assertIsInstance(models[i], SimulationModel)
# Test pose of the model
self.assertEqual(models[i].pose.position.tolist(), pose[0:3])
q = Pose.rpy2quat(*pose[3::])
diff = Pose.get_transform(models[i].pose.quat, q)
# Test model properties
self.assertAlmostEqual(np.sum(diff[0:3]), 0)
self.assertFalse(models[i].static)
self.assertEqual(len(models[i].links), 1)
link_name = models[i].link_names[0]
# Test visual element
self.assertEqual(len(models[i].links[link_name].visuals), 1)
geometry = models[i].links[link_name].visuals[0].geometry
self.assertEqual(geometry.get_type(), 'sphere')
# Test collision element
self.assertEqual(len(models[i].links[link_name].collisions), 1)
geometry = models[i].links[link_name].collisions[0].geometry
self.assertEqual(geometry.get_type(), 'sphere')
# Test color exists
material = models[i].links[link_name].visuals[0].material
self.assertIsNotNone(material)
self.assertIsNotNone(material.ambient)
self.assertIsNotNone(material.diffuse)
if not isinstance(
color, str) and isinstance(
color, list) and color is not None:
self.assertEqual(material.ambient.value, color)
self.assertEqual(material.diffuse.value, color)
def test_sphere_forced_permutation(self):
n_radius = random.randint(2, 3)
n_masses = 2 * n_radius
name = generate_random_string(3)
# Test with lambda functions
radius = "__import__('numpy').random.random({})".format(n_radius)
masses = "__import__('numpy').linspace(1, 10, {})".format(n_masses)
pose = [random.rand() for _ in range(6)]
model_config = [
dict(
type='sphere_factory',
args=dict(
name=name,
radius=radius,
mass=masses,
pose=pose,
use_permutation=False,
color=None
))
]
models = create_models_from_config(model_config)
self.assertEqual(len(models), n_radius * n_masses)
# Test with fixed arguments
radius = [random.rand() for _ in range(n_radius)]
masses = [random.rand() for _ in range(n_masses)]
pose = [random.rand() for _ in range(6)]
model_config = [
dict(
type='sphere_factory',
args=dict(
name=name,
radius=radius,
mass=masses,
pose=pose,
use_permutation=False,
color=None
))
]
models = create_models_from_config(model_config)
self.assertEqual(len(models), n_radius * n_masses)
def test_extrude_polygon(self):
# Create mesh by extruding a polygon
vertices = [(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)]
poly = Polygon(vertices)
name = generate_random_string(3)
pose = [random.rand() for _ in range(6)]
mass = random.rand()
height = random.rand()
model_config = [
dict(
type='extrude',
args=dict(
polygon=poly,
name=name,
mass=mass,
height=height,
pose=pose,
color=None
)
)
]
models = create_models_from_config(model_config)
self.assertEqual(len(models), 1)
for model in models:
_delete_generated_meshes(model.to_sdf())
# Extrude only the boundaries
cap_style = ['round', 'flat', 'square']
join_style = ['round', 'mitre', 'bevel']
for cs in cap_style:
for js in join_style:
model_config = [
dict(
type='extrude',
args=dict(
polygon=poly,
name=name,
mass=mass,
height=height,
pose=pose,
color=None,
extrude_boundaries=True,
thickness=random.rand(),
cap_style=cs,
join_style=js
)
)
]
models = create_models_from_config(model_config)
self.assertEqual(len(models), 1)
for model in models:
_delete_generated_meshes(model.to_sdf())
# Create a mesh by dilating point
vertices = [(random.rand() * 5, random.rand() * 5)]
poly = MultiPoint(vertices)
name = generate_random_string(3)
pose = [random.rand() for _ in range(6)]
mass = random.rand()
height = random.rand()
model_config = [
dict(
type='extrude',
args=dict(
polygon=poly,
name=name,
mass=mass,
height=height,
pose=pose,
color=None,
thickness=random.rand()
)
)
]
models = create_models_from_config(model_config)
self.assertEqual(len(models), 1)
for model in models:
_delete_generated_meshes(model.to_sdf())
# Create a mesh by dilating a line
vertices = [(random.rand() * 5, random.rand() * 5)
for _ in range(5)]
poly = LineString(vertices)
name = generate_random_string(3)
pose = [random.rand() for _ in range(6)]
mass = random.rand()
height = random.rand()
for cs in cap_style:
for js in join_style:
model_config = [
dict(
type='extrude',
args=dict(
polygon=poly,
name=name,
mass=mass,
height=height,
pose=pose,
color=None,
cap_style=cs,
join_style=js,
thickness=random.rand()
)
)
]
models = create_models_from_config(model_config)
self.assertEqual(len(models), 1)
for model in models:
_delete_generated_meshes(model.to_sdf())
def test_invalid_polygon_extrude_inputs(self):
vertices = [(random.rand() * 5, random.rand() * 5)]
model_config = [
dict(
type='extrude',
args=dict(
polygon=MultiPoint(vertices),
thickness=0,
height=random.rand()
)
)
]
with self.assertRaises(AssertionError):
create_models_from_config(model_config)
def test_export_to_gazebo_model(self):
# Create mesh by extruding a polygon
vertices = [(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)]
poly = Polygon(vertices)
name = generate_random_string(3)
pose = [random.rand() for _ in range(6)]
mass = random.rand()
height = 10 * random.rand()
model_config = dict(
polygon=poly,
name=name,
mass=mass,
height=height,
pose=pose,
color=None
)
model = extrude(**model_config)
model_dir = model.to_gazebo_model()
self.assertTrue(os.path.isdir(model_dir))
shutil.rmtree(model_dir)
if __name__ == '__main__':
unittest.main()
|
bvisness/allwpilib | wpilibc/src/main/native/cpp/simulation/Mechanism2D.cpp | /*----------------------------------------------------------------------------*/
/* Copyright (c) 2020 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "frc/simulation/Mechanism2D.h"
#include <wpi/SmallString.h>
#include <wpi/Twine.h>
#include <wpi/raw_ostream.h>
using namespace frc;
Mechanism2D::Mechanism2D() : m_device{"Mechanism2D"} {}
void Mechanism2D::SetLigamentAngle(const wpi::Twine& ligamentPath,
float angle) {
if (m_device) {
wpi::SmallString<64> fullPathBuf;
wpi::StringRef fullPath =
(ligamentPath + "/angle").toNullTerminatedStringRef(fullPathBuf);
if (!createdItems.count(fullPath)) {
createdItems[fullPath] =
m_device.CreateDouble(fullPath.data(), false, angle);
}
createdItems[fullPath].Set(angle);
}
}
void Mechanism2D::SetLigamentLength(const wpi::Twine& ligamentPath,
float length) {
if (m_device) {
wpi::SmallString<64> fullPathBuf;
wpi::StringRef fullPath =
(ligamentPath + "/length").toNullTerminatedStringRef(fullPathBuf);
if (!createdItems.count(fullPath)) {
createdItems[fullPath] =
m_device.CreateDouble(fullPath.data(), false, length);
}
createdItems[fullPath].Set(length);
}
}
|
oferreira/react-boilerplate-restarted | src/features/CancelRules/actions/index.js | import {
HOTEL_GET_CANCELLATION_RULES,
HOTEL_GET_CANCELLATION_RULES_SUCCESS,
HOTEL_GET_WORDING_RULES,
HOTEL_GET_WORDING_RULES_SUCCESS,
HOTEL_GET_RULES_ERROR,
} from '../constants'
export const requestCancelRules = (resortId, rateCode) => ({
type: HOTEL_GET_CANCELLATION_RULES,
resortId,
rateCode,
})
export const requestWordingRules = (key, locale) => ({
type: HOTEL_GET_WORDING_RULES,
key,
locale,
})
export const requestCancelRulesSuccess = (values) => ({
type: HOTEL_GET_CANCELLATION_RULES_SUCCESS,
values,
})
export const requestWordingRulesSuccess = (values) => ({
type: HOTEL_GET_WORDING_RULES_SUCCESS,
values,
})
export const requestWordingRulesError = (error) => ({
type: HOTEL_GET_RULES_ERROR,
error,
})
|
mojmir-svoboda/BlackBoxTT | plugins/bbFoomp/src/foobar2000.cpp | <reponame>mojmir-svoboda/BlackBoxTT<gh_stars>10-100
#if 0
#include <3rd_party/foobar2000/SDK/foobar2000.h>
#include <3rd_party/foobar2000/helpers/helpers.h>
//#include "m_listeningto.h"
#include <windows.h>
#include <process.h>
#define MIRANDA_DW_PROTECTION 0x8754
#define DATA_SIZE 1024
UINT timer = 0;
WCHAR lastSongData[DATA_SIZE] = L"";
static bool g_off = true; //global state for sending listeningto infos
// Functions ////////////////////////////////////////////////////////////////////////////
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
// Find the windows
TCHAR class_name[256];
if (GetClassName(hwnd, class_name, 256))
{
class_name[255] = _T('\0');
if (lstrcmpi(MIRANDA_WINDOWCLASS, class_name) == 0)
{
COPYDATASTRUCT *cds = (COPYDATASTRUCT *) lParam;
SendMessage(hwnd, WM_COPYDATA, (WPARAM) NULL, (LPARAM) cds);
}
}
return TRUE;
}
inline void SendData(WCHAR *text)
{
static WCHAR lastMsg[DATA_SIZE] = L"";
if (wcscmp(lastMsg, text) == 0)
return;
// Prepare the struct
COPYDATASTRUCT cds;
cds.dwData = MIRANDA_DW_PROTECTION;
cds.lpData = text;
cds.cbData = (wcslen(text) + 1) * sizeof(WCHAR);
EnumWindows(EnumWindowsProc, (LPARAM) &cds);
wcsncpy(lastMsg, text, DATA_SIZE);
lastMsg[DATA_SIZE-1] = L'\0';
}
void Concat(WCHAR *data, size_t &size, const char *str, size_t len = 0)
{
if (size < 3 * sizeof(WCHAR))
return;
if (str != NULL)
{
if (len == 0)
len = strlen(str);
if (size >= len + 3)
{
size -= MultiByteToWideChar(CP_UTF8, 0, str, len * sizeof(char), &data[DATA_SIZE - size], size * sizeof(WCHAR));
data[DATA_SIZE - size] = L'\0';
}
}
wcscat(data, L"\\0");
size -= 2;
}
void Concat(WCHAR *data, size_t &size)
{
if (size < 3 * sizeof(WCHAR))
return;
wcscat(data, L"\\0");
size -= 2;
}
void Concat(WCHAR *data, size_t &size, const WCHAR *str, size_t len = 0)
{
if (size < 3 * sizeof(WCHAR))
return;
if (str != NULL)
{
if (len == 0)
len = wcslen(str);
if (size >= len + 3)
{
wcscpy(&data[DATA_SIZE - size], str);
size -= len;
data[DATA_SIZE - size] = L'\0';
}
}
wcscat(data, L"\\0");
size -= 2;
}
void GetMetadata(const file_info *info, char *field, WCHAR *data, size_t &size)
{
const char *val = info->meta_get(field, 0);
if (val != NULL && val[0] != '\0')
{
Concat(data, size, val);
}
else
{
Concat(data, size);
}
}
void KillTimer(UINT id = 0)
{
if (id != 0)
{
KillTimer(NULL, id);
}
if (timer != 0)
{
if (timer != id)
KillTimer(NULL, timer);
timer = 0;
}
}
void CALLBACK SendEmptyData(HWND hWnd = 0, UINT nMsg = 0, UINT nIDEvent = 0, DWORD dwTime = 0)
{
KillTimer(nIDEvent);
// L"<Status 0-stoped 1-playing>\\0<Player>\\0<Type>\\0<Title>\\0<Artist>\\0<Album>\\0<Track>\\0<Year>\\0<Genre>\\0<Length (secs)>\\0\\0"
SendData(L"0\\0foobar2000\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0");
}
void SetTimer()
{
KillTimer();
timer = SetTimer(NULL, 1, 1000, SendEmptyData);
}
BOOL IsRadio(metadb_handle_ptr p_track)
{
const char *filename = p_track->get_path();
return (filename != NULL && strstr(filename, "://") != 0 && strncmp(filename, "file://", 7) != 0);
}
void SendDataMusic(const char *filename, const file_info *info)
{
WCHAR data[DATA_SIZE];
size_t size = DATA_SIZE;
data[0] = L'\0';
// L"<Status 0-stoped 1-playing>\\0<Player>\\0<Type>\\0<Title>\\0<Artist>\\0<Album>\\0<Track>\\0<Year>\\0<Genre>\\0<Length (secs)>\\0\\0"
Concat(data, size, "1");
Concat(data, size, "foobar2000");
Concat(data, size, "Music");
const char *val = info->meta_get("TITLE", 0);
if (val != NULL && val[0] != '\0')
{
Concat(data, size, val);
}
else if (filename != NULL && filename[0] != '\0')
{
const char *name = strrchr(filename, '\\');
if (name == NULL)
strrchr(filename, '/');
if (name == NULL)
{
Concat(data, size);
}
else
{
const char *dot = strrchr(name, '.');
Concat(data, size, name + 1, dot == NULL ? 0 : dot - name - 1);
}
}
else
{
Concat(data, size);
}
GetMetadata(info, "ARTIST", data, size);
GetMetadata(info, "ALBUM", data, size);
GetMetadata(info, "TRACKNUMBER", data, size);
GetMetadata(info, "DATE", data, size);
GetMetadata(info, "GENRE", data, size);
int len = (int) info->get_length();
if (len > 0)
{
char tmp[10];
Concat(data, size, itoa(len, tmp, 10));
}
else
{
Concat(data, size);
}
Concat(data, size);
SendData(data);
wcsncpy(lastSongData, data, DATA_SIZE);
lastSongData[DATA_SIZE-1] = L'\0';
}
void SendDataRadio(const file_info *info, const file_info *info2)
{
WCHAR data[DATA_SIZE];
size_t size = DATA_SIZE;
data[0] = L'\0';
// L"<Status 0-stoped 1-playing>\\0<Player>\\0<Type>\\0<Title>\\0<Artist>\\0<Album>\\0<Track>\\0<Year>\\0<Genre>\\0<Length (secs)>\\0<Station name>\\0"
Concat(data, size, "1");
Concat(data, size, "foobar2000");
Concat(data, size, "Radio");
GetMetadata(info, "TITLE", data, size);
GetMetadata(info, "ARTIST", data, size);
GetMetadata(info, "ALBUM", data, size);
GetMetadata(info, "TRACKNUMBER", data, size);
GetMetadata(info, "DATE", data, size);
GetMetadata(info2, "GENRE", data, size);
int len = (int) info->get_length();
if (len > 0)
{
char tmp[10];
Concat(data, size, itoa(len, tmp, 10));
}
else
{
Concat(data, size);
}
// Station name
GetMetadata(info2, "TITLE", data, size);
SendData(data);
wcsncpy(lastSongData, data, DATA_SIZE);
lastSongData[DATA_SIZE-1] = L'\0';
}
// Foobar ////////////////////////////////////////////////////////////////////////////
class play_callback_miranda : public play_callback_static
{
virtual void on_playback_starting(play_control::t_track_command p_command, bool p_paused) {}
virtual void on_playback_new_track(metadb_handle_ptr p_track)
{
if (g_off) return;
KillTimer();
if (IsRadio(p_track))
return;
in_metadb_sync_fromhandle l_sync(p_track);
const file_info *info;
if (p_track->get_info_locked(info))
SendDataMusic(p_track->get_path(), info);
}
virtual void on_playback_stop(play_control::t_stop_reason p_reason)
{
if (g_off) return;
SetTimer();
}
virtual void on_playback_seek(double p_time) {}
virtual void on_playback_pause(bool p_state)
{
if (g_off) return;
if (p_state)
{
SetTimer();
}
else
{
KillTimer();
if (lastSongData[0] != L'\0')
SendData(lastSongData);
}
}
virtual void on_playback_edited(metadb_handle_ptr p_track) {}
virtual void on_playback_dynamic_info(const file_info & info) {}
virtual void on_playback_dynamic_info_track(const file_info & info)
{
if (g_off) return;
metadb_handle_ptr p_track;
static_api_ptr_t<play_control>()->get_now_playing(p_track);
if (p_track.is_valid())
{
if (IsRadio(p_track))
{
in_metadb_sync_fromhandle l_sync(p_track);
const file_info *info2;
if (!p_track->get_info_locked(info2))
return;
SendDataRadio(&info, info2);
}
p_track.release();
}
}
virtual void on_playback_time(double p_time) {}
virtual void on_volume_change(float p_new_val) {};
virtual unsigned get_flags()
{
return flag_on_playback_new_track | flag_on_playback_pause | flag_on_playback_stop | flag_on_playback_dynamic_info_track;
}
};
static play_callback_static_factory_t<play_callback_miranda> miranda_callback_factory;
class myinitquit : public initquit {
public:
void on_init()
{
//check if foo_comserver2 is present and set g_off to false if foo_mlt go active
//TODO:detect foo_comserver2 from component list (can also check for other plugins)
CLSID clsid;
if(S_OK != CLSIDFromProgID(L"Foobar2000.Application.0.7", &clsid)) {
g_off = false;
SetTimer();
}
}
void on_quit()
{
if (!g_off && FindWindow(MIRANDA_WINDOWCLASS, NULL) != NULL)
SendData(L"0\\0foobar2000\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0");
}
};
#endif
|
youpy-org/youpy | youpy/test/functional/sprite_api/Ball/Ball.py | <gh_stars>0
from youpy.code.english.control import console
from youpy.code.english.control import wait
from youpy.code.english.motion import change_y_by
def when_program_start(sprite):
console.print(f"Hello from Sprite '{sprite.name}'")
sprite.go_to(0, 0)
def when_space_key_pressed():
change_y_by(10)
wait(0.5)
change_y_by(-10)
|
byzaneo/sdn-rx | examples/docs/src/test/java/org/neo4j/doc/springframework/data/docs/repositories/populators/PopulatorConfig.java | package org.neo4j.doc.springframework.data.docs.repositories.populators;
// tag::populators[]
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.repository.init.Jackson2RepositoryPopulatorFactoryBean;
import org.springframework.data.repository.init.ResourceReaderRepositoryPopulator;
import com.fasterxml.jackson.databind.ObjectMapper;
// end::populators[]
/**
* An example how to configure a repository populator.
*
* @author <NAME>
* @soundtrack Rammstein - Reise Reise
*/
// tag::populators[]
@Configuration
public class PopulatorConfig {
@Bean
public FactoryBean<ResourceReaderRepositoryPopulator> respositoryPopulator(
ObjectMapper objectMapper, // <1>
ResourceLoader resourceLoader) {
Jackson2RepositoryPopulatorFactoryBean factory = new Jackson2RepositoryPopulatorFactoryBean();
factory.setMapper(objectMapper);
factory.setResources(new Resource[] { resourceLoader.getResource("classpath:data.json") }); // <2>
return factory;
}
}
// end::populators[]
|
Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo | REDSI_1160929_1161573/boost_1_67_0/libs/hof/test/protect.cpp | /*=============================================================================
Copyright (c) 2017 <NAME>
protect.cpp
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#include <boost/hof/protect.hpp>
#include <boost/hof/lazy.hpp>
#include <boost/hof/placeholders.hpp>
#include <memory>
#include "test.hpp"
#include <boost/hof/function.hpp>
int f(int x)
{
return x;
}
int& g(int& x)
{
return x;
}
template<class T>
const T& constify(const T& arg)
{
return arg;
}
BOOST_HOF_TEST_CASE()
{
int i[9] = {0,1,2,3,4,5,6,7,8};
// non-const
// test nullary
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(1))() == 1);
// test lvalues
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_1))(i[0]) == &i[0]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_1))(i[0], i[1]) == &i[0]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_2))(i[0], i[1]) == &i[1]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_1))(i[0], i[1], i[2]) == &i[0]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_2))(i[0], i[1], i[2]) == &i[1]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_3))(i[0], i[1], i[2]) == &i[2]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_1))(i[0], i[1], i[2], i[3]) == &i[0]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_2))(i[0], i[1], i[2], i[3]) == &i[1]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_3))(i[0], i[1], i[2], i[3]) == &i[2]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_4))(i[0], i[1], i[2], i[3]) == &i[3]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_1))(i[0], i[1], i[2], i[3], i[4]) == &i[0]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_2))(i[0], i[1], i[2], i[3], i[4]) == &i[1]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_3))(i[0], i[1], i[2], i[3], i[4]) == &i[2]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_4))(i[0], i[1], i[2], i[3], i[4]) == &i[3]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_5))(i[0], i[1], i[2], i[3], i[4]) == &i[4]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_1))(i[0], i[1], i[2], i[3], i[4], i[5]) == &i[0]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_2))(i[0], i[1], i[2], i[3], i[4], i[5]) == &i[1]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_3))(i[0], i[1], i[2], i[3], i[4], i[5]) == &i[2]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_4))(i[0], i[1], i[2], i[3], i[4], i[5]) == &i[3]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_5))(i[0], i[1], i[2], i[3], i[4], i[5]) == &i[4]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_6))(i[0], i[1], i[2], i[3], i[4], i[5]) == &i[5]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_1))(i[0], i[1], i[2], i[3], i[4], i[5], i[6]) == &i[0]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_2))(i[0], i[1], i[2], i[3], i[4], i[5], i[6]) == &i[1]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_3))(i[0], i[1], i[2], i[3], i[4], i[5], i[6]) == &i[2]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_4))(i[0], i[1], i[2], i[3], i[4], i[5], i[6]) == &i[3]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_5))(i[0], i[1], i[2], i[3], i[4], i[5], i[6]) == &i[4]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_6))(i[0], i[1], i[2], i[3], i[4], i[5], i[6]) == &i[5]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_7))(i[0], i[1], i[2], i[3], i[4], i[5], i[6]) == &i[6]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_1))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7]) == &i[0]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_2))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7]) == &i[1]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_3))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7]) == &i[2]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_4))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7]) == &i[3]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_5))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7]) == &i[4]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_6))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7]) == &i[5]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_7))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7]) == &i[6]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_8))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7]) == &i[7]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_1))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]) == &i[0]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_2))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]) == &i[1]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_3))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]) == &i[2]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_4))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]) == &i[3]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_5))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]) == &i[4]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_6))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]) == &i[5]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_7))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]) == &i[6]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_8))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]) == &i[7]);
BOOST_HOF_TEST_CHECK(&boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_9))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]) == &i[8]);
// test rvalues
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_1))(0) == 0);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_1))(0, 1) == 0);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_2))(0, 1) == 1);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_1))(0, 1, 2) == 0);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_2))(0, 1, 2) == 1);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_3))(0, 1, 2) == 2);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_1))(0, 1, 2, 3) == 0);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_2))(0, 1, 2, 3) == 1);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_3))(0, 1, 2, 3) == 2);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_4))(0, 1, 2, 3) == 3);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_1))(0, 1, 2, 3, 4) == 0);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_2))(0, 1, 2, 3, 4) == 1);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_3))(0, 1, 2, 3, 4) == 2);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_4))(0, 1, 2, 3, 4) == 3);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_5))(0, 1, 2, 3, 4) == 4);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_1))(0, 1, 2, 3, 4, 5) == 0);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_2))(0, 1, 2, 3, 4, 5) == 1);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_3))(0, 1, 2, 3, 4, 5) == 2);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_4))(0, 1, 2, 3, 4, 5) == 3);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_5))(0, 1, 2, 3, 4, 5) == 4);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_6))(0, 1, 2, 3, 4, 5) == 5);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_1))(0, 1, 2, 3, 4, 5, 6) == 0);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_2))(0, 1, 2, 3, 4, 5, 6) == 1);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_3))(0, 1, 2, 3, 4, 5, 6) == 2);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_4))(0, 1, 2, 3, 4, 5, 6) == 3);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_5))(0, 1, 2, 3, 4, 5, 6) == 4);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_6))(0, 1, 2, 3, 4, 5, 6) == 5);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_7))(0, 1, 2, 3, 4, 5, 6) == 6);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_1))(0, 1, 2, 3, 4, 5, 6, 7) == 0);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_2))(0, 1, 2, 3, 4, 5, 6, 7) == 1);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_3))(0, 1, 2, 3, 4, 5, 6, 7) == 2);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_4))(0, 1, 2, 3, 4, 5, 6, 7) == 3);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_5))(0, 1, 2, 3, 4, 5, 6, 7) == 4);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_6))(0, 1, 2, 3, 4, 5, 6, 7) == 5);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_7))(0, 1, 2, 3, 4, 5, 6, 7) == 6);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_8))(0, 1, 2, 3, 4, 5, 6, 7) == 7);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_1))(0, 1, 2, 3, 4, 5, 6, 7, 8) == 0);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_2))(0, 1, 2, 3, 4, 5, 6, 7, 8) == 1);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_3))(0, 1, 2, 3, 4, 5, 6, 7, 8) == 2);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_4))(0, 1, 2, 3, 4, 5, 6, 7, 8) == 3);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_5))(0, 1, 2, 3, 4, 5, 6, 7, 8) == 4);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_6))(0, 1, 2, 3, 4, 5, 6, 7, 8) == 5);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_7))(0, 1, 2, 3, 4, 5, 6, 7, 8) == 6);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_8))(0, 1, 2, 3, 4, 5, 6, 7, 8) == 7);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_9))(0, 1, 2, 3, 4, 5, 6, 7, 8) == 8);
// test mixed perfect forwarding
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_1))(i[0], 1) == 0);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_2))(i[0], 1) == 1);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_1))(0, i[1]) == 0);
BOOST_HOF_TEST_CHECK(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_2))(0, i[1]) == 1);
// const
// test nullary
BOOST_HOF_TEST_CHECK(constify(constify(boost::hof::protect(boost::hof::lazy(f)(1))))() == 1);
// test lvalues
BOOST_HOF_TEST_CHECK(&constify(constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_1))))(i[0]) == &i[0]);
BOOST_HOF_TEST_CHECK(&constify(constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_1))))(i[0], i[1]) == &i[0]);
BOOST_HOF_TEST_CHECK(&constify(constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_2))))(i[0], i[1]) == &i[1]);
BOOST_HOF_TEST_CHECK(&constify(constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_1))))(i[0], i[1], i[2]) == &i[0]);
BOOST_HOF_TEST_CHECK(&constify(constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_2))))(i[0], i[1], i[2]) == &i[1]);
BOOST_HOF_TEST_CHECK(&constify(constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_3))))(i[0], i[1], i[2]) == &i[2]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_1)))(i[0], i[1], i[2], i[3]) == &i[0]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_2)))(i[0], i[1], i[2], i[3]) == &i[1]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_3)))(i[0], i[1], i[2], i[3]) == &i[2]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_4)))(i[0], i[1], i[2], i[3]) == &i[3]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_1)))(i[0], i[1], i[2], i[3], i[4]) == &i[0]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_2)))(i[0], i[1], i[2], i[3], i[4]) == &i[1]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_3)))(i[0], i[1], i[2], i[3], i[4]) == &i[2]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_4)))(i[0], i[1], i[2], i[3], i[4]) == &i[3]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_5)))(i[0], i[1], i[2], i[3], i[4]) == &i[4]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_1)))(i[0], i[1], i[2], i[3], i[4], i[5]) == &i[0]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_2)))(i[0], i[1], i[2], i[3], i[4], i[5]) == &i[1]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_3)))(i[0], i[1], i[2], i[3], i[4], i[5]) == &i[2]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_4)))(i[0], i[1], i[2], i[3], i[4], i[5]) == &i[3]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_5)))(i[0], i[1], i[2], i[3], i[4], i[5]) == &i[4]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_6)))(i[0], i[1], i[2], i[3], i[4], i[5]) == &i[5]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_1)))(i[0], i[1], i[2], i[3], i[4], i[5], i[6]) == &i[0]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_2)))(i[0], i[1], i[2], i[3], i[4], i[5], i[6]) == &i[1]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_3)))(i[0], i[1], i[2], i[3], i[4], i[5], i[6]) == &i[2]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_4)))(i[0], i[1], i[2], i[3], i[4], i[5], i[6]) == &i[3]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_5)))(i[0], i[1], i[2], i[3], i[4], i[5], i[6]) == &i[4]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_6)))(i[0], i[1], i[2], i[3], i[4], i[5], i[6]) == &i[5]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_7)))(i[0], i[1], i[2], i[3], i[4], i[5], i[6]) == &i[6]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_1)))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7]) == &i[0]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_2)))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7]) == &i[1]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_3)))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7]) == &i[2]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_4)))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7]) == &i[3]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_5)))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7]) == &i[4]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_6)))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7]) == &i[5]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_7)))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7]) == &i[6]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_8)))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7]) == &i[7]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_1)))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]) == &i[0]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_2)))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]) == &i[1]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_3)))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]) == &i[2]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_4)))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]) == &i[3]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_5)))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]) == &i[4]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_6)))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]) == &i[5]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_7)))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]) == &i[6]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_8)))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]) == &i[7]);
BOOST_HOF_TEST_CHECK(&constify(boost::hof::protect(boost::hof::lazy(g)(std::placeholders::_9)))(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]) == &i[8]);
// test rvalues
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_1)))(0) == 0);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_1)))(0, 1) == 0);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_2)))(0, 1) == 1);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_1)))(0, 1, 2) == 0);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_2)))(0, 1, 2) == 1);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_3)))(0, 1, 2) == 2);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_1)))(0, 1, 2, 3) == 0);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_2)))(0, 1, 2, 3) == 1);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_3)))(0, 1, 2, 3) == 2);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_4)))(0, 1, 2, 3) == 3);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_1)))(0, 1, 2, 3, 4) == 0);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_2)))(0, 1, 2, 3, 4) == 1);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_3)))(0, 1, 2, 3, 4) == 2);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_4)))(0, 1, 2, 3, 4) == 3);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_5)))(0, 1, 2, 3, 4) == 4);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_1)))(0, 1, 2, 3, 4, 5) == 0);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_2)))(0, 1, 2, 3, 4, 5) == 1);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_3)))(0, 1, 2, 3, 4, 5) == 2);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_4)))(0, 1, 2, 3, 4, 5) == 3);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_5)))(0, 1, 2, 3, 4, 5) == 4);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_6)))(0, 1, 2, 3, 4, 5) == 5);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_1)))(0, 1, 2, 3, 4, 5, 6) == 0);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_2)))(0, 1, 2, 3, 4, 5, 6) == 1);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_3)))(0, 1, 2, 3, 4, 5, 6) == 2);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_4)))(0, 1, 2, 3, 4, 5, 6) == 3);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_5)))(0, 1, 2, 3, 4, 5, 6) == 4);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_6)))(0, 1, 2, 3, 4, 5, 6) == 5);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_7)))(0, 1, 2, 3, 4, 5, 6) == 6);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_1)))(0, 1, 2, 3, 4, 5, 6, 7) == 0);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_2)))(0, 1, 2, 3, 4, 5, 6, 7) == 1);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_3)))(0, 1, 2, 3, 4, 5, 6, 7) == 2);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_4)))(0, 1, 2, 3, 4, 5, 6, 7) == 3);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_5)))(0, 1, 2, 3, 4, 5, 6, 7) == 4);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_6)))(0, 1, 2, 3, 4, 5, 6, 7) == 5);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_7)))(0, 1, 2, 3, 4, 5, 6, 7) == 6);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_8)))(0, 1, 2, 3, 4, 5, 6, 7) == 7);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_1)))(0, 1, 2, 3, 4, 5, 6, 7, 8) == 0);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_2)))(0, 1, 2, 3, 4, 5, 6, 7, 8) == 1);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_3)))(0, 1, 2, 3, 4, 5, 6, 7, 8) == 2);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_4)))(0, 1, 2, 3, 4, 5, 6, 7, 8) == 3);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_5)))(0, 1, 2, 3, 4, 5, 6, 7, 8) == 4);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_6)))(0, 1, 2, 3, 4, 5, 6, 7, 8) == 5);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_7)))(0, 1, 2, 3, 4, 5, 6, 7, 8) == 6);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_8)))(0, 1, 2, 3, 4, 5, 6, 7, 8) == 7);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_9)))(0, 1, 2, 3, 4, 5, 6, 7, 8) == 8);
// test mixed perfect forwarding
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_1)))(i[0], 1) == 0);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_2)))(i[0], 1) == 1);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_1)))(0, i[1]) == 0);
BOOST_HOF_TEST_CHECK(constify(boost::hof::protect(boost::hof::lazy(f)(std::placeholders::_2)))(0, i[1]) == 1);
}
BOOST_HOF_TEST_CASE()
{
BOOST_HOF_TEST_CHECK(boost::hof::lazy(boost::hof::apply)(boost::hof::protect(boost::hof::lazy(boost::hof::identity)(boost::hof::_1)), boost::hof::_1)(17) == 17);
BOOST_HOF_TEST_CHECK(boost::hof::lazy(boost::hof::apply)(boost::hof::protect(boost::hof::lazy(boost::hof::identity)(boost::hof::_1)), 17)() == 17);
BOOST_HOF_STATIC_TEST_CHECK(boost::hof::lazy(boost::hof::apply)(boost::hof::protect(boost::hof::lazy(boost::hof::identity)(boost::hof::_1)), boost::hof::_1)(17) == 17);
BOOST_HOF_STATIC_TEST_CHECK(boost::hof::lazy(boost::hof::apply)(boost::hof::protect(boost::hof::lazy(boost::hof::identity)(boost::hof::_1)), 17)() == 17);
}
namespace test1 {
int id(int x)
{
return x;
}
BOOST_HOF_TEST_CASE()
{
BOOST_HOF_TEST_CHECK(boost::hof::lazy(boost::hof::apply)(boost::hof::protect(boost::hof::lazy(id)(std::placeholders::_1)), std::placeholders::_1)(17) == 17);
BOOST_HOF_TEST_CHECK(boost::hof::lazy(boost::hof::apply)(boost::hof::protect(boost::hof::lazy(id)(std::placeholders::_1)), 17)() == 17);
}
}
|
PANBOHE/Humanpose-fight | demo/alphaction/dataset/collate_batch.py | <filename>demo/alphaction/dataset/collate_batch.py
import math
def batch_different_videos(videos, size_divisible=0):
'''
:param videos: a list of video tensors
:param size_divisible: output_size(width and height) should be divisble by this param
:return: batched videos as a single tensor
'''
assert isinstance(videos, (tuple, list))
max_size = tuple(max(s) for s in zip(*[clip.shape for clip in videos]))
if size_divisible > 0:
stride = size_divisible
max_size = list(max_size)
max_size[2] = int(math.ceil(max_size[2] / stride) * stride)
max_size[3] = int(math.ceil(max_size[3] / stride) * stride)
max_size = tuple(max_size)
batch_shape = (len(videos),) + max_size
batched_clips = videos[0].new(*batch_shape).zero_()
for clip, pad_clip in zip(videos, batched_clips):
pad_clip[:clip.shape[0], :clip.shape[1], :clip.shape[2], :clip.shape[3]].copy_(clip)
return batched_clips
class BatchCollator(object):
"""
From a list of samples from the dataset,
returns the batched objectimages and targets.
This should be passed to the DataLoader
"""
def __init__(self, size_divisible=0):
self.divisible = size_divisible
self.size_divisible = self.divisible
def __call__(self, batch):
transposed_batch = list(zip(*batch))
slow_clips = batch_different_videos(transposed_batch[0], self.size_divisible)
fast_clips = batch_different_videos(transposed_batch[1], self.size_divisible)
boxes = transposed_batch[2]
objects = transposed_batch[3]
extras = transposed_batch[4]
clip_ids = transposed_batch[5]
return slow_clips, fast_clips, boxes, objects, extras, clip_ids
|
hedg-r52/job4j | utils/src/main/java/ru/job4j/utils/generators/TextFileGenerator.java | <reponame>hedg-r52/job4j<gh_stars>0
package ru.job4j.utils.generators;
import java.io.FileWriter;
import java.io.IOException;
/**
* @author <NAME> (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class TextFileGenerator {
private final StringGenerator stringGenerator = new StringGenerator();
public void generate(String path, int countLines, int length) throws IOException {
try (FileWriter fw = new FileWriter(path)) {
fw.write(stringGenerator.generate(length));
for (int i = 1; i < countLines; i++) {
fw.write(System.getProperty("line.separator"));
fw.write(stringGenerator.generate(length));
}
}
}
}
|
whitfin/spack | var/spack/repos/builtin/packages/py-guidata/package.py | # Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyGuidata(PythonPackage):
"""Automatic graphical user interfaces generation for easy dataset editing
and display"""
homepage = "https://github.com/PierreRaybaut/guidata"
url = "https://pypi.io/packages/source/g/guidata/guidata-1.7.5.zip"
version('1.7.5', '915188c02ad3c89951ee260db65d84a7')
depends_on('py-setuptools', type='build')
depends_on('py-pyqt@4:', type=('build', 'run'))
depends_on('py-spyder@2.0:2.9.9', type=('build', 'run'))
depends_on('py-h5py', type=('build', 'run'))
|
DingWeizhe/f2-nodejs | test/demos/area.js | const F2 = require('../../index');
describe('area', () => {
describe('area normal', () => {
const canvas = document.createElement('canvas');
canvas.width = 500;
canvas.height = 500;
document.body.appendChild(canvas);
const data = [
{ time: '2016-08-08 00:00:00', tem: 10, city: 'beijing' },
{ time: '2016-08-08 00:10:00', tem: 22, city: 'beijing' },
{ time: '2016-08-08 00:30:00', tem: 16, city: 'beijing' },
{ time: '2016-08-09 00:35:00', tem: 26, city: 'beijing' },
{ time: '2016-08-09 01:00:00', tem: 12, city: 'beijing' },
{ time: '2016-08-09 01:20:00', tem: 26, city: 'beijing' },
{ time: '2016-08-10 01:40:00', tem: 18, city: 'beijing' },
{ time: '2016-08-10 02:00:00', tem: 26, city: 'beijing' },
{ time: '2016-08-10 02:20:00', tem: 12, city: 'beijing' },
{ time: '2016-08-08 00:00:00', tem: 28, city: 'newYork' },
{ time: '2016-08-08 00:10:00', tem: 16, city: 'newYork' },
{ time: '2016-08-08 00:30:00', tem: 26, city: 'newYork' },
{ time: '2016-08-09 00:35:00', tem: 12, city: 'newYork' },
{ time: '2016-08-09 01:00:00', tem: 26, city: 'newYork' },
{ time: '2016-08-09 01:20:00', tem: 20, city: 'newYork' },
{ time: '2016-08-10 01:40:00', tem: 29, city: 'newYork' },
{ time: '2016-08-10 02:00:00', tem: 16, city: 'newYork' },
{ time: '2016-08-10 02:20:00', tem: 22, city: 'newYork' }
];
const chart = new F2.Chart({
el: canvas
});
chart.source(data, {
time: {
type: 'timeCat',
tickCount: 3,
range: [ 0, 1 ]
},
tem: {
tickCount: 5,
min: 0
}
});
// 配置刻度文字大小,供PC端显示用(移动端可以使用默认值20px)
chart.axis('tem', {
label: {
fontSize: 14
}
});
// 配置time刻度文字样式
const label = {
fill: '#979797',
font: '14px san-serif',
offset: 6
};
chart.axis('time', {
label(text, index, total) {
const cfg = label;
// 第一个点左对齐,最后一个点右对齐,其余居中,只有一个点时左对齐
if (index === 0) {
cfg.textAlign = 'start';
}
if (index > 0 && index === total - 1) {
cfg.textAlign = 'end';
}
return cfg;
}
});
chart.area().position('time*tem')
.color('city')
.shape('smooth')
.style({
opacity: 0.6
});
chart.render();
});
describe('area stack', () => {
const canvas = document.createElement('canvas');
canvas.width = 500;
canvas.height = 500;
document.body.appendChild(canvas);
const data = [
{ month: 12, tem: 7, city: 'tokyo' },
{ month: 1, tem: 6.9, city: 'tokyo' },
{ month: 2, tem: 9.5, city: 'tokyo' },
{ month: 3, tem: 14.5, city: 'tokyo' },
{ month: 4, tem: 18.2, city: 'tokyo' },
{ month: 5, tem: 21.5, city: 'tokyo' },
{ month: 6, tem: 25.2, city: 'tokyo' },
{ month: 7, tem: 26.5, city: 'tokyo' },
{ month: 8, tem: 23.3, city: 'tokyo' },
{ month: 9, tem: 18.3, city: 'tokyo' },
{ month: 10, tem: 13.9, city: 'tokyo' },
{ month: 11, tem: 9.6, city: 'tokyo' },
{ month: 12, tem: 0, city: 'newYork' },
{ month: 1, tem: 0.8, city: 'newYork' },
{ month: 2, tem: 5.7, city: 'newYork' },
{ month: 3, tem: 11.3, city: 'newYork' },
{ month: 4, tem: 17, city: 'newYork' },
{ month: 5, tem: 22, city: 'newYork' },
{ month: 6, tem: 24.8, city: 'newYork' },
{ month: 7, tem: 24.1, city: 'newYork' },
{ month: 8, tem: 20.1, city: 'newYork' },
{ month: 9, tem: 14.1, city: 'newYork' },
{ month: 10, tem: 8.6, city: 'newYork' },
{ month: 11, tem: 2.5, city: 'newYork' },
{ month: 12, tem: 2, city: 'berlin' },
{ month: 1, tem: 0.6, city: 'berlin' },
{ month: 2, tem: 3.5, city: 'berlin' },
{ month: 3, tem: 8.4, city: 'berlin' },
{ month: 4, tem: 13.5, city: 'berlin' },
{ month: 5, tem: 17, city: 'berlin' },
{ month: 6, tem: 18.6, city: 'berlin' },
{ month: 7, tem: 17.9, city: 'berlin' },
{ month: 8, tem: 14.3, city: 'berlin' },
{ month: 9, tem: 9, city: 'berlin' },
{ month: 10, tem: 3.9, city: 'berlin' },
{ month: 11, tem: 1, city: 'berlin' }
];
const chart = new F2.Chart({
el: canvas
});
chart.source(data, {
month: {
tickCount: 12
},
tem: {
tickCount: 5
}
});
// 配置刻度文字大小,供PC端显示用(移动端可以使用默认值20px)
chart.axis('tem', {
label: {
fontSize: 14
}
});
chart.axis('time', {
label: {
fontSize: 14
}
});
chart.area().position('month*tem').color('city')
.shape('smooth')
.style({
opacity: 0.6
})
.adjust('stack');
chart.render();
function getPoint(canvas, x, y) {
const bbox = canvas.getBoundingClientRect();
return {
x: x - bbox.left,
y: y - bbox.top
};
}
canvas.onclick = function(e) {
const point = getPoint(e.target, e.clientX, e.clientY);
const data = chart.getSnapRecords(point);
// let html = '';
// data.forEach(function(item) {
// html += 'city:' + item._origin.city + ',tem:' + item._origin.tem + ',month:' + item._origin.month + '\b\n';
// });
console.log(data);
};
});
describe.only('area gradient', () => {
const canvas = document.createElement('canvas');
canvas.width = 500;
canvas.height = 500;
document.body.appendChild(canvas);
const data = [
{ month: 12, tem: 7, city: 'tokyo' },
{ month: 1, tem: 6.9, city: 'tokyo' },
{ month: 2, tem: 9.5, city: 'tokyo' },
{ month: 3, tem: 14.5, city: 'tokyo' },
{ month: 4, tem: 18.2, city: 'tokyo' },
{ month: 5, tem: 21.5, city: 'tokyo' },
{ month: 6, tem: 25.2, city: 'tokyo' },
{ month: 7, tem: 26.5, city: 'tokyo' },
{ month: 8, tem: 23.3, city: 'tokyo' },
{ month: 9, tem: 18.3, city: 'tokyo' },
{ month: 10, tem: 13.9, city: 'tokyo' },
{ month: 11, tem: 9.6, city: 'tokyo' }
/* { month: 12, tem: 0, city: 'newYork' },
{ month: 1, tem: 0.8, city: 'newYork' },
{ month: 2, tem: 5.7, city: 'newYork' },
{ month: 3, tem: 11.3, city: 'newYork' },
{ month: 4, tem: 17, city: 'newYork' },
{ month: 5, tem: 22, city: 'newYork' },
{ month: 6, tem: 24.8, city: 'newYork' },
{ month: 7, tem: 24.1, city: 'newYork' },
{ month: 8, tem: 20.1, city: 'newYork' },
{ month: 9, tem: 14.1, city: 'newYork' },
{ month: 10, tem: 8.6, city: 'newYork' },
{ month: 11, tem: 2.5, city: 'newYork' }
*/
];
const chart = new F2.Chart({
el: canvas
});
chart.source(data, {
month: {
tickCount: 12
},
tem: {
tickCount: 5
}
});
// 配置刻度文字大小,供PC端显示用(移动端可以使用默认值20px)
chart.axis('tem', {
label: {
fontSize: 14
}
});
chart.axis('time', {
label: {
fontSize: 14
}
});
const linear_gradient = canvas.getContext('2d').createLinearGradient(0, 0, 0, 500);
linear_gradient.addColorStop(1, '#fff');
linear_gradient.addColorStop(0, 'rgb(15, 141, 232)');
chart.area().position('month*tem').color(linear_gradient)
.shape('smooth')
.style({
opacity: 0.6
})
.adjust('stack');
chart.render();
});
});
|
fhornain/patternfly-react-seed_1 | node_modules/@patternfly/react-icons/dist/js/icons/inbox-icon.d.js | <reponame>fhornain/patternfly-react-seed_1<gh_stars>0
"use strict";
//# sourceMappingURL=inbox-icon.d.js.map |
astamate/hotel | src/main/java/com/tap5/bootStarter/TapestryApplication.java | <reponame>astamate/hotel
package com.tap5.bootStarter;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by code8 on 11/6/15.
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TapestryApplication {
}
|
ishiura-compiler/CF3 | testsuite/EXP_1/test93.c | <reponame>ishiura-compiler/CF3
/*
CF3
Copyright (c) 2015 ishiura-lab.
Released under the MIT license.
https://github.com/ishiura-compiler/CF3/MIT-LICENSE.md
*/
#include<stdio.h>
#include<stdint.h>
#include<stdlib.h>
#include"test1.h"
int32_t t0 = 0;
static int64_t x12 = INT64_MIN;
int32_t t3 = 181;
uint8_t x25 = 14U;
int64_t x37 = INT64_MIN;
int64_t x38 = INT64_MAX;
int32_t t9 = -1;
static int64_t x43 = INT64_MIN;
static uint64_t x46 = 57307223838078LLU;
int16_t x51 = INT16_MIN;
uint8_t x65 = UINT8_MAX;
int16_t x70 = -4;
uint8_t x74 = 12U;
uint8_t x85 = 23U;
int8_t x86 = 0;
volatile int32_t t19 = 7;
static int16_t x92 = 1;
uint16_t x97 = UINT16_MAX;
int32_t x101 = -1;
int16_t x105 = -1;
volatile int16_t x106 = INT16_MIN;
static volatile int32_t t24 = 3;
volatile uint8_t x110 = 62U;
static uint32_t x112 = UINT32_MAX;
static volatile int32_t t25 = 2011596;
static int64_t x121 = 1LL;
uint16_t x123 = 1U;
uint8_t x124 = 77U;
volatile int8_t x130 = 6;
int64_t x136 = 69317415LL;
int16_t x138 = 6;
volatile int64_t x151 = INT64_MAX;
int32_t t35 = 414325068;
static int32_t x161 = INT32_MAX;
volatile int16_t x162 = INT16_MIN;
int8_t x163 = 14;
uint16_t x169 = UINT16_MAX;
volatile int32_t t38 = -115;
uint64_t x173 = UINT64_MAX;
int32_t t39 = -5227059;
volatile int32_t t41 = 24582;
int32_t t42 = 0;
int64_t x198 = -1LL;
volatile uint8_t x202 = UINT8_MAX;
static volatile int32_t t46 = -56346593;
int32_t t47 = 987495325;
static int8_t x220 = -7;
volatile uint32_t x221 = UINT32_MAX;
volatile int32_t x222 = INT32_MIN;
static int32_t x226 = INT32_MAX;
static uint32_t x228 = 173U;
int8_t x230 = -7;
volatile int32_t t51 = -28829;
static int8_t x236 = 37;
int32_t t53 = 1;
int64_t x241 = INT64_MIN;
uint16_t x243 = 1217U;
volatile int16_t x246 = INT16_MIN;
int64_t x252 = -1994675626LL;
int32_t t57 = 252338669;
int64_t x263 = 44419427935784LL;
int16_t x270 = -1;
int64_t x278 = INT64_MAX;
int32_t x282 = 0;
static volatile uint32_t x283 = 3U;
int64_t x286 = INT64_MIN;
uint32_t x290 = 136314187U;
int32_t x291 = INT32_MAX;
volatile uint64_t x293 = 255082964LLU;
int32_t t66 = -1;
int64_t x303 = -3066975139370LL;
static uint8_t x306 = 1U;
uint32_t x313 = 46248133U;
int16_t x331 = 1587;
volatile int16_t x341 = -1;
static int8_t x342 = INT8_MIN;
uint8_t x346 = 114U;
int16_t x347 = 6;
uint32_t x348 = 971U;
volatile int32_t t79 = 1;
volatile int64_t x357 = 0LL;
static uint32_t x359 = UINT32_MAX;
int32_t t82 = -56429;
int32_t x371 = INT32_MIN;
int32_t x373 = -136136068;
int8_t x380 = -34;
volatile int32_t t87 = -130642526;
int32_t x389 = 2150690;
uint64_t x394 = 109LLU;
int32_t x398 = INT32_MAX;
uint32_t x405 = UINT32_MAX;
static int16_t x406 = INT16_MIN;
static int16_t x407 = INT16_MIN;
static volatile uint8_t x411 = 0U;
static volatile int32_t t94 = 108624;
static int64_t x416 = 110950LL;
static int32_t t96 = -231;
int16_t x421 = -1;
static int8_t x429 = -1;
int64_t x430 = -3942400123LL;
int8_t x436 = INT8_MIN;
int32_t x437 = 0;
int16_t x440 = INT16_MAX;
volatile int8_t x443 = 32;
static int16_t x466 = 3914;
int16_t x477 = 3;
uint16_t x480 = UINT16_MAX;
uint32_t x481 = 5U;
volatile int32_t x503 = -1;
volatile int32_t t114 = 1;
uint32_t x517 = 6U;
int16_t x518 = INT16_MAX;
volatile int8_t x519 = INT8_MIN;
uint64_t x521 = 15574627765131LLU;
uint8_t x531 = UINT8_MAX;
int8_t x542 = INT8_MIN;
static int32_t x544 = 11743;
static int8_t x554 = -9;
int64_t x558 = INT64_MAX;
static uint8_t x561 = 44U;
int16_t x565 = 0;
int8_t x574 = INT8_MIN;
int32_t t131 = 509;
static volatile int32_t t133 = -413705269;
int8_t x599 = INT8_MIN;
uint16_t x605 = UINT16_MAX;
int32_t t136 = 8059;
uint16_t x612 = UINT16_MAX;
static int16_t x615 = -1;
static int32_t t138 = -127;
int64_t x620 = -1LL;
uint32_t x623 = UINT32_MAX;
static uint64_t x628 = 2648548572453LLU;
int16_t x633 = 0;
int16_t x637 = 1;
volatile int16_t x645 = INT16_MIN;
uint16_t x646 = UINT16_MAX;
static volatile uint16_t x647 = UINT16_MAX;
int64_t x648 = -26678861606489LL;
int16_t x657 = INT16_MIN;
static int16_t x658 = -8590;
uint8_t x668 = 29U;
int8_t x670 = 0;
int8_t x680 = INT8_MIN;
uint64_t x683 = 2791398887LLU;
volatile int32_t t155 = 861014391;
int8_t x704 = INT8_MIN;
static uint32_t x706 = UINT32_MAX;
volatile int32_t t159 = 1;
uint64_t x718 = 287253432218291LLU;
int32_t x721 = INT32_MIN;
int32_t t163 = 4159464;
static volatile int32_t t168 = 24367905;
static int8_t x767 = INT8_MAX;
volatile int64_t x768 = INT64_MIN;
uint8_t x770 = UINT8_MAX;
uint32_t x772 = 925133U;
uint8_t x773 = 3U;
int32_t t172 = -6;
uint64_t x779 = UINT64_MAX;
int64_t x780 = -60157319585357409LL;
int16_t x781 = INT16_MIN;
int64_t x783 = INT64_MIN;
static int16_t x785 = 2;
int64_t x795 = INT64_MIN;
volatile uint16_t x796 = 28474U;
volatile int64_t x797 = 1388235545LL;
volatile int32_t t178 = 1;
volatile int16_t x802 = -11;
int16_t x804 = INT16_MAX;
int16_t x805 = 0;
volatile int32_t t180 = 29478;
static volatile uint32_t x821 = UINT32_MAX;
volatile int16_t x827 = INT16_MIN;
uint32_t x832 = 12U;
int8_t x842 = -5;
static int64_t x849 = 38438463878048698LL;
int8_t x852 = -1;
volatile int32_t t189 = -6010277;
int16_t x853 = INT16_MIN;
int64_t x856 = INT64_MIN;
volatile int16_t x867 = -1;
int32_t t192 = -504;
int8_t x869 = INT8_MIN;
static volatile int64_t x871 = INT64_MIN;
int16_t x872 = INT16_MAX;
static int64_t x882 = 558325495869716LL;
int32_t x888 = 7671258;
int64_t x889 = INT64_MIN;
static volatile int64_t x890 = 295708LL;
int32_t x895 = INT32_MIN;
void f0(void) {
volatile int16_t x1 = INT16_MAX;
volatile int8_t x2 = -9;
volatile int16_t x3 = -356;
int32_t x4 = INT32_MAX;
t0 = (((x1+x2)!=x3)>x4);
if (t0 != 0) { NG(); } else { ; }
}
void f1(void) {
uint8_t x5 = 8U;
uint8_t x6 = 7U;
uint16_t x7 = 0U;
volatile uint64_t x8 = 9563705LLU;
volatile int32_t t1 = -647550;
t1 = (((x5+x6)!=x7)>x8);
if (t1 != 0) { NG(); } else { ; }
}
void f2(void) {
int16_t x9 = -1;
static int16_t x10 = -1;
static volatile int16_t x11 = INT16_MIN;
static int32_t t2 = -192210981;
t2 = (((x9+x10)!=x11)>x12);
if (t2 != 1) { NG(); } else { ; }
}
void f3(void) {
static int16_t x13 = -8;
int16_t x14 = -11;
int32_t x15 = -1;
uint64_t x16 = 39251LLU;
t3 = (((x13+x14)!=x15)>x16);
if (t3 != 0) { NG(); } else { ; }
}
void f4(void) {
volatile uint64_t x17 = 325817974372352847LLU;
uint32_t x18 = 5703205U;
static int8_t x19 = -1;
int16_t x20 = 4151;
volatile int32_t t4 = -3859;
t4 = (((x17+x18)!=x19)>x20);
if (t4 != 0) { NG(); } else { ; }
}
void f5(void) {
int32_t x21 = INT32_MIN;
uint32_t x22 = UINT32_MAX;
uint16_t x23 = 3314U;
int8_t x24 = INT8_MAX;
static volatile int32_t t5 = 808;
t5 = (((x21+x22)!=x23)>x24);
if (t5 != 0) { NG(); } else { ; }
}
void f6(void) {
static uint8_t x26 = 0U;
volatile int8_t x27 = INT8_MAX;
int16_t x28 = INT16_MIN;
int32_t t6 = -63356;
t6 = (((x25+x26)!=x27)>x28);
if (t6 != 1) { NG(); } else { ; }
}
void f7(void) {
int16_t x29 = -941;
int8_t x30 = -1;
volatile int16_t x31 = INT16_MAX;
int32_t x32 = -1;
volatile int32_t t7 = -2;
t7 = (((x29+x30)!=x31)>x32);
if (t7 != 1) { NG(); } else { ; }
}
void f8(void) {
int32_t x33 = 84823;
int32_t x34 = INT32_MIN;
volatile uint64_t x35 = 2278LLU;
uint64_t x36 = 164562483139LLU;
volatile int32_t t8 = -276280890;
t8 = (((x33+x34)!=x35)>x36);
if (t8 != 0) { NG(); } else { ; }
}
void f9(void) {
int32_t x39 = INT32_MIN;
static int16_t x40 = INT16_MIN;
t9 = (((x37+x38)!=x39)>x40);
if (t9 != 1) { NG(); } else { ; }
}
void f10(void) {
uint64_t x41 = 289555159367074LLU;
int16_t x42 = 250;
uint8_t x44 = 88U;
int32_t t10 = 15606813;
t10 = (((x41+x42)!=x43)>x44);
if (t10 != 0) { NG(); } else { ; }
}
void f11(void) {
int32_t x45 = -1;
int64_t x47 = -1LL;
static volatile int16_t x48 = 493;
volatile int32_t t11 = 41720558;
t11 = (((x45+x46)!=x47)>x48);
if (t11 != 0) { NG(); } else { ; }
}
void f12(void) {
int64_t x49 = INT64_MAX;
int16_t x50 = -1;
int32_t x52 = -216613353;
volatile int32_t t12 = 938082;
t12 = (((x49+x50)!=x51)>x52);
if (t12 != 1) { NG(); } else { ; }
}
void f13(void) {
uint8_t x57 = 2U;
uint16_t x58 = UINT16_MAX;
uint64_t x59 = 0LLU;
static int8_t x60 = INT8_MAX;
volatile int32_t t13 = -225341194;
t13 = (((x57+x58)!=x59)>x60);
if (t13 != 0) { NG(); } else { ; }
}
void f14(void) {
volatile uint16_t x61 = UINT16_MAX;
static int8_t x62 = INT8_MIN;
static uint32_t x63 = 16032998U;
uint32_t x64 = UINT32_MAX;
volatile int32_t t14 = 25130;
t14 = (((x61+x62)!=x63)>x64);
if (t14 != 0) { NG(); } else { ; }
}
void f15(void) {
int8_t x66 = INT8_MIN;
volatile uint64_t x67 = UINT64_MAX;
int64_t x68 = INT64_MIN;
volatile int32_t t15 = -58877018;
t15 = (((x65+x66)!=x67)>x68);
if (t15 != 1) { NG(); } else { ; }
}
void f16(void) {
int32_t x69 = -3128;
static volatile int8_t x71 = INT8_MAX;
int8_t x72 = INT8_MIN;
int32_t t16 = -229;
t16 = (((x69+x70)!=x71)>x72);
if (t16 != 1) { NG(); } else { ; }
}
void f17(void) {
int16_t x73 = INT16_MIN;
static int16_t x75 = INT16_MIN;
int32_t x76 = INT32_MIN;
volatile int32_t t17 = -6225;
t17 = (((x73+x74)!=x75)>x76);
if (t17 != 1) { NG(); } else { ; }
}
void f18(void) {
static volatile uint16_t x81 = 3125U;
volatile uint64_t x82 = 1734840508340671LLU;
uint16_t x83 = UINT16_MAX;
int32_t x84 = INT32_MAX;
int32_t t18 = -14;
t18 = (((x81+x82)!=x83)>x84);
if (t18 != 0) { NG(); } else { ; }
}
void f19(void) {
static int8_t x87 = -1;
uint16_t x88 = 3445U;
t19 = (((x85+x86)!=x87)>x88);
if (t19 != 0) { NG(); } else { ; }
}
void f20(void) {
uint64_t x89 = UINT64_MAX;
int16_t x90 = 14526;
uint32_t x91 = UINT32_MAX;
int32_t t20 = 47792956;
t20 = (((x89+x90)!=x91)>x92);
if (t20 != 0) { NG(); } else { ; }
}
void f21(void) {
uint32_t x93 = UINT32_MAX;
int64_t x94 = -1LL;
static int16_t x95 = 6;
uint8_t x96 = UINT8_MAX;
int32_t t21 = -725;
t21 = (((x93+x94)!=x95)>x96);
if (t21 != 0) { NG(); } else { ; }
}
void f22(void) {
uint32_t x98 = UINT32_MAX;
int64_t x99 = INT64_MIN;
int8_t x100 = INT8_MIN;
int32_t t22 = -5373;
t22 = (((x97+x98)!=x99)>x100);
if (t22 != 1) { NG(); } else { ; }
}
void f23(void) {
int32_t x102 = 29400;
int16_t x103 = INT16_MIN;
int16_t x104 = -258;
int32_t t23 = 13259;
t23 = (((x101+x102)!=x103)>x104);
if (t23 != 1) { NG(); } else { ; }
}
void f24(void) {
static int8_t x107 = 27;
int8_t x108 = INT8_MIN;
t24 = (((x105+x106)!=x107)>x108);
if (t24 != 1) { NG(); } else { ; }
}
void f25(void) {
static volatile int16_t x109 = INT16_MAX;
static int64_t x111 = -1LL;
t25 = (((x109+x110)!=x111)>x112);
if (t25 != 0) { NG(); } else { ; }
}
void f26(void) {
uint64_t x113 = UINT64_MAX;
volatile int64_t x114 = 1575166667442922LL;
volatile uint32_t x115 = UINT32_MAX;
volatile int32_t x116 = INT32_MIN;
static volatile int32_t t26 = 28423;
t26 = (((x113+x114)!=x115)>x116);
if (t26 != 1) { NG(); } else { ; }
}
void f27(void) {
static uint8_t x122 = 12U;
int32_t t27 = 490415;
t27 = (((x121+x122)!=x123)>x124);
if (t27 != 0) { NG(); } else { ; }
}
void f28(void) {
static uint32_t x125 = UINT32_MAX;
int8_t x126 = INT8_MIN;
int8_t x127 = -31;
static uint64_t x128 = 500438637903LLU;
int32_t t28 = -1;
t28 = (((x125+x126)!=x127)>x128);
if (t28 != 0) { NG(); } else { ; }
}
void f29(void) {
static int8_t x129 = -16;
int16_t x131 = INT16_MIN;
int64_t x132 = -384194LL;
int32_t t29 = 7;
t29 = (((x129+x130)!=x131)>x132);
if (t29 != 1) { NG(); } else { ; }
}
void f30(void) {
int16_t x133 = -3;
int32_t x134 = -1;
static int8_t x135 = -1;
volatile int32_t t30 = -2;
t30 = (((x133+x134)!=x135)>x136);
if (t30 != 0) { NG(); } else { ; }
}
void f31(void) {
uint32_t x137 = UINT32_MAX;
int8_t x139 = INT8_MIN;
uint64_t x140 = UINT64_MAX;
int32_t t31 = -18967122;
t31 = (((x137+x138)!=x139)>x140);
if (t31 != 0) { NG(); } else { ; }
}
void f32(void) {
static uint32_t x141 = UINT32_MAX;
uint64_t x142 = 142508LLU;
static uint64_t x143 = UINT64_MAX;
int32_t x144 = -16132073;
static volatile int32_t t32 = -3743;
t32 = (((x141+x142)!=x143)>x144);
if (t32 != 1) { NG(); } else { ; }
}
void f33(void) {
int32_t x145 = INT32_MIN;
uint64_t x146 = 123333158LLU;
uint8_t x147 = 98U;
int32_t x148 = INT32_MAX;
volatile int32_t t33 = -88;
t33 = (((x145+x146)!=x147)>x148);
if (t33 != 0) { NG(); } else { ; }
}
void f34(void) {
uint64_t x149 = UINT64_MAX;
uint8_t x150 = 0U;
uint8_t x152 = 2U;
int32_t t34 = -2696;
t34 = (((x149+x150)!=x151)>x152);
if (t34 != 0) { NG(); } else { ; }
}
void f35(void) {
uint16_t x153 = 315U;
int64_t x154 = INT64_MIN;
volatile int32_t x155 = -1;
uint32_t x156 = UINT32_MAX;
t35 = (((x153+x154)!=x155)>x156);
if (t35 != 0) { NG(); } else { ; }
}
void f36(void) {
uint16_t x157 = 802U;
static uint32_t x158 = 3797661U;
int64_t x159 = -1LL;
static int64_t x160 = 5294289969008401LL;
static int32_t t36 = 75008;
t36 = (((x157+x158)!=x159)>x160);
if (t36 != 0) { NG(); } else { ; }
}
void f37(void) {
int64_t x164 = -110297915310331363LL;
volatile int32_t t37 = -36;
t37 = (((x161+x162)!=x163)>x164);
if (t37 != 1) { NG(); } else { ; }
}
void f38(void) {
int8_t x170 = 5;
volatile int32_t x171 = INT32_MIN;
int16_t x172 = INT16_MIN;
t38 = (((x169+x170)!=x171)>x172);
if (t38 != 1) { NG(); } else { ; }
}
void f39(void) {
static int32_t x174 = -711477;
int16_t x175 = INT16_MAX;
int16_t x176 = 1;
t39 = (((x173+x174)!=x175)>x176);
if (t39 != 0) { NG(); } else { ; }
}
void f40(void) {
volatile uint8_t x181 = 89U;
int16_t x182 = -1;
uint64_t x183 = UINT64_MAX;
int32_t x184 = INT32_MAX;
int32_t t40 = 4;
t40 = (((x181+x182)!=x183)>x184);
if (t40 != 0) { NG(); } else { ; }
}
void f41(void) {
int64_t x185 = INT64_MIN;
static int16_t x186 = 9;
static int16_t x187 = INT16_MAX;
static int16_t x188 = 7;
t41 = (((x185+x186)!=x187)>x188);
if (t41 != 0) { NG(); } else { ; }
}
void f42(void) {
static uint64_t x193 = 808LLU;
static volatile uint16_t x194 = 3U;
uint32_t x195 = UINT32_MAX;
uint64_t x196 = 188LLU;
t42 = (((x193+x194)!=x195)>x196);
if (t42 != 0) { NG(); } else { ; }
}
void f43(void) {
int16_t x197 = INT16_MIN;
int32_t x199 = -56483358;
static int64_t x200 = -770002346LL;
volatile int32_t t43 = 701148;
t43 = (((x197+x198)!=x199)>x200);
if (t43 != 1) { NG(); } else { ; }
}
void f44(void) {
volatile uint64_t x201 = UINT64_MAX;
int64_t x203 = INT64_MAX;
static int64_t x204 = INT64_MIN;
volatile int32_t t44 = 5;
t44 = (((x201+x202)!=x203)>x204);
if (t44 != 1) { NG(); } else { ; }
}
void f45(void) {
int32_t x205 = 6901;
volatile int32_t x206 = INT32_MIN;
int16_t x207 = -61;
uint64_t x208 = 60055669097208LLU;
volatile int32_t t45 = 15551;
t45 = (((x205+x206)!=x207)>x208);
if (t45 != 0) { NG(); } else { ; }
}
void f46(void) {
static int64_t x209 = INT64_MIN;
uint64_t x210 = 1333LLU;
static int8_t x211 = 1;
volatile uint16_t x212 = UINT16_MAX;
t46 = (((x209+x210)!=x211)>x212);
if (t46 != 0) { NG(); } else { ; }
}
void f47(void) {
volatile uint16_t x213 = 1U;
static uint16_t x214 = 2U;
uint64_t x215 = 166067LLU;
int32_t x216 = INT32_MAX;
t47 = (((x213+x214)!=x215)>x216);
if (t47 != 0) { NG(); } else { ; }
}
void f48(void) {
int8_t x217 = INT8_MIN;
static int32_t x218 = -1;
uint64_t x219 = 450404376247524023LLU;
volatile int32_t t48 = -14195;
t48 = (((x217+x218)!=x219)>x220);
if (t48 != 1) { NG(); } else { ; }
}
void f49(void) {
int16_t x223 = -4;
int8_t x224 = -1;
static volatile int32_t t49 = 36863379;
t49 = (((x221+x222)!=x223)>x224);
if (t49 != 1) { NG(); } else { ; }
}
void f50(void) {
int8_t x225 = -1;
static volatile uint32_t x227 = 34U;
static int32_t t50 = -39702868;
t50 = (((x225+x226)!=x227)>x228);
if (t50 != 0) { NG(); } else { ; }
}
void f51(void) {
int8_t x229 = INT8_MAX;
int32_t x231 = INT32_MAX;
volatile uint64_t x232 = 107664229154166703LLU;
t51 = (((x229+x230)!=x231)>x232);
if (t51 != 0) { NG(); } else { ; }
}
void f52(void) {
int16_t x233 = INT16_MAX;
int64_t x234 = 1293039549LL;
volatile int16_t x235 = INT16_MIN;
volatile int32_t t52 = 148;
t52 = (((x233+x234)!=x235)>x236);
if (t52 != 0) { NG(); } else { ; }
}
void f53(void) {
int16_t x237 = 224;
uint64_t x238 = 23487277LLU;
int16_t x239 = 13657;
int32_t x240 = 89015;
t53 = (((x237+x238)!=x239)>x240);
if (t53 != 0) { NG(); } else { ; }
}
void f54(void) {
uint16_t x242 = 827U;
uint8_t x244 = 0U;
int32_t t54 = -137;
t54 = (((x241+x242)!=x243)>x244);
if (t54 != 1) { NG(); } else { ; }
}
void f55(void) {
static int64_t x245 = 8470623028LL;
int64_t x247 = -7536185LL;
int64_t x248 = -1LL;
static volatile int32_t t55 = 0;
t55 = (((x245+x246)!=x247)>x248);
if (t55 != 1) { NG(); } else { ; }
}
void f56(void) {
int32_t x249 = 1112858;
int8_t x250 = -1;
uint8_t x251 = 1U;
static int32_t t56 = -87;
t56 = (((x249+x250)!=x251)>x252);
if (t56 != 1) { NG(); } else { ; }
}
void f57(void) {
static int8_t x253 = INT8_MIN;
int8_t x254 = INT8_MAX;
static int64_t x255 = INT64_MAX;
volatile uint8_t x256 = UINT8_MAX;
t57 = (((x253+x254)!=x255)>x256);
if (t57 != 0) { NG(); } else { ; }
}
void f58(void) {
int32_t x257 = -6190;
uint64_t x258 = 3929025824642LLU;
volatile uint64_t x259 = UINT64_MAX;
static uint64_t x260 = 2095007424072159LLU;
int32_t t58 = 15834915;
t58 = (((x257+x258)!=x259)>x260);
if (t58 != 0) { NG(); } else { ; }
}
void f59(void) {
int64_t x261 = -2188LL;
uint16_t x262 = 334U;
static int16_t x264 = INT16_MIN;
int32_t t59 = 2485;
t59 = (((x261+x262)!=x263)>x264);
if (t59 != 1) { NG(); } else { ; }
}
void f60(void) {
int16_t x265 = 3717;
uint16_t x266 = 664U;
int16_t x267 = INT16_MIN;
int32_t x268 = 176328489;
int32_t t60 = 55295116;
t60 = (((x265+x266)!=x267)>x268);
if (t60 != 0) { NG(); } else { ; }
}
void f61(void) {
uint16_t x269 = UINT16_MAX;
volatile int8_t x271 = -1;
static int64_t x272 = INT64_MIN;
volatile int32_t t61 = 126203;
t61 = (((x269+x270)!=x271)>x272);
if (t61 != 1) { NG(); } else { ; }
}
void f62(void) {
uint64_t x277 = UINT64_MAX;
uint32_t x279 = UINT32_MAX;
int8_t x280 = -1;
int32_t t62 = -385;
t62 = (((x277+x278)!=x279)>x280);
if (t62 != 1) { NG(); } else { ; }
}
void f63(void) {
uint8_t x281 = 4U;
static int32_t x284 = INT32_MIN;
volatile int32_t t63 = 81383955;
t63 = (((x281+x282)!=x283)>x284);
if (t63 != 1) { NG(); } else { ; }
}
void f64(void) {
uint32_t x285 = UINT32_MAX;
uint32_t x287 = 526654U;
uint8_t x288 = 59U;
volatile int32_t t64 = -12040996;
t64 = (((x285+x286)!=x287)>x288);
if (t64 != 0) { NG(); } else { ; }
}
void f65(void) {
uint64_t x289 = 1869425524LLU;
static int32_t x292 = INT32_MIN;
static volatile int32_t t65 = 1;
t65 = (((x289+x290)!=x291)>x292);
if (t65 != 1) { NG(); } else { ; }
}
void f66(void) {
uint16_t x294 = UINT16_MAX;
int32_t x295 = 118;
static int64_t x296 = INT64_MAX;
t66 = (((x293+x294)!=x295)>x296);
if (t66 != 0) { NG(); } else { ; }
}
void f67(void) {
int16_t x297 = INT16_MAX;
volatile uint64_t x298 = 46552984201206714LLU;
int32_t x299 = -1;
int16_t x300 = INT16_MAX;
int32_t t67 = 462;
t67 = (((x297+x298)!=x299)>x300);
if (t67 != 0) { NG(); } else { ; }
}
void f68(void) {
int32_t x301 = -64965337;
int8_t x302 = -31;
static uint8_t x304 = 1U;
static int32_t t68 = 282200;
t68 = (((x301+x302)!=x303)>x304);
if (t68 != 0) { NG(); } else { ; }
}
void f69(void) {
int64_t x305 = -93069LL;
volatile int32_t x307 = INT32_MAX;
int8_t x308 = INT8_MIN;
static int32_t t69 = 1382;
t69 = (((x305+x306)!=x307)>x308);
if (t69 != 1) { NG(); } else { ; }
}
void f70(void) {
static uint64_t x309 = 14299524910LLU;
static volatile int64_t x310 = INT64_MIN;
int16_t x311 = 2058;
static volatile uint64_t x312 = 3506096132567LLU;
int32_t t70 = -408891;
t70 = (((x309+x310)!=x311)>x312);
if (t70 != 0) { NG(); } else { ; }
}
void f71(void) {
uint16_t x314 = 3207U;
int8_t x315 = -13;
int64_t x316 = 13169526919515692LL;
volatile int32_t t71 = -2000498;
t71 = (((x313+x314)!=x315)>x316);
if (t71 != 0) { NG(); } else { ; }
}
void f72(void) {
int16_t x317 = -72;
static uint8_t x318 = 30U;
int16_t x319 = -1;
int64_t x320 = INT64_MIN;
int32_t t72 = -1798;
t72 = (((x317+x318)!=x319)>x320);
if (t72 != 1) { NG(); } else { ; }
}
void f73(void) {
static int32_t x321 = 10732797;
static uint8_t x322 = UINT8_MAX;
static uint16_t x323 = 2U;
uint8_t x324 = 8U;
int32_t t73 = -1;
t73 = (((x321+x322)!=x323)>x324);
if (t73 != 0) { NG(); } else { ; }
}
void f74(void) {
static volatile int32_t x325 = INT32_MIN;
static volatile uint16_t x326 = 184U;
static uint32_t x327 = 26U;
volatile int16_t x328 = -49;
volatile int32_t t74 = -1013402213;
t74 = (((x325+x326)!=x327)>x328);
if (t74 != 1) { NG(); } else { ; }
}
void f75(void) {
int8_t x329 = -1;
uint64_t x330 = 40346876LLU;
uint32_t x332 = 70818U;
int32_t t75 = 49155;
t75 = (((x329+x330)!=x331)>x332);
if (t75 != 0) { NG(); } else { ; }
}
void f76(void) {
volatile int16_t x333 = 3;
volatile uint32_t x334 = 182U;
int32_t x335 = 88;
static int32_t x336 = 0;
static int32_t t76 = -364;
t76 = (((x333+x334)!=x335)>x336);
if (t76 != 1) { NG(); } else { ; }
}
void f77(void) {
static uint16_t x337 = 63U;
static int16_t x338 = INT16_MIN;
int8_t x339 = INT8_MIN;
uint64_t x340 = 20159044353938924LLU;
int32_t t77 = 44849;
t77 = (((x337+x338)!=x339)>x340);
if (t77 != 0) { NG(); } else { ; }
}
void f78(void) {
uint64_t x343 = 186940408056003LLU;
uint16_t x344 = UINT16_MAX;
int32_t t78 = 33;
t78 = (((x341+x342)!=x343)>x344);
if (t78 != 0) { NG(); } else { ; }
}
void f79(void) {
int64_t x345 = -10735129038472265LL;
t79 = (((x345+x346)!=x347)>x348);
if (t79 != 0) { NG(); } else { ; }
}
void f80(void) {
int64_t x349 = 2686LL;
int16_t x350 = -1;
int32_t x351 = -1;
int32_t x352 = INT32_MIN;
volatile int32_t t80 = 3;
t80 = (((x349+x350)!=x351)>x352);
if (t80 != 1) { NG(); } else { ; }
}
void f81(void) {
volatile int32_t x353 = -75272857;
uint64_t x354 = 146742614LLU;
static int8_t x355 = 26;
volatile int8_t x356 = 3;
volatile int32_t t81 = -218604;
t81 = (((x353+x354)!=x355)>x356);
if (t81 != 0) { NG(); } else { ; }
}
void f82(void) {
uint64_t x358 = 175LLU;
volatile int16_t x360 = INT16_MAX;
t82 = (((x357+x358)!=x359)>x360);
if (t82 != 0) { NG(); } else { ; }
}
void f83(void) {
int16_t x365 = INT16_MIN;
volatile uint32_t x366 = 2025417U;
int32_t x367 = INT32_MIN;
int16_t x368 = -430;
int32_t t83 = -30224898;
t83 = (((x365+x366)!=x367)>x368);
if (t83 != 1) { NG(); } else { ; }
}
void f84(void) {
int8_t x369 = INT8_MIN;
volatile uint8_t x370 = UINT8_MAX;
uint32_t x372 = 3U;
int32_t t84 = 4;
t84 = (((x369+x370)!=x371)>x372);
if (t84 != 0) { NG(); } else { ; }
}
void f85(void) {
uint16_t x374 = 104U;
int8_t x375 = INT8_MAX;
volatile uint32_t x376 = 3852U;
static int32_t t85 = -9;
t85 = (((x373+x374)!=x375)>x376);
if (t85 != 0) { NG(); } else { ; }
}
void f86(void) {
int8_t x377 = INT8_MAX;
int32_t x378 = -1;
volatile uint16_t x379 = 12U;
int32_t t86 = 0;
t86 = (((x377+x378)!=x379)>x380);
if (t86 != 1) { NG(); } else { ; }
}
void f87(void) {
uint16_t x381 = 0U;
int8_t x382 = INT8_MIN;
uint64_t x383 = 664256149633LLU;
volatile uint16_t x384 = 44U;
t87 = (((x381+x382)!=x383)>x384);
if (t87 != 0) { NG(); } else { ; }
}
void f88(void) {
volatile uint64_t x385 = UINT64_MAX;
volatile uint16_t x386 = 20U;
int32_t x387 = INT32_MAX;
uint16_t x388 = 6U;
static volatile int32_t t88 = 1598575;
t88 = (((x385+x386)!=x387)>x388);
if (t88 != 0) { NG(); } else { ; }
}
void f89(void) {
int16_t x390 = 17;
volatile int64_t x391 = INT64_MAX;
int32_t x392 = -1;
int32_t t89 = 104;
t89 = (((x389+x390)!=x391)>x392);
if (t89 != 1) { NG(); } else { ; }
}
void f90(void) {
uint64_t x393 = 0LLU;
int32_t x395 = INT32_MAX;
int16_t x396 = INT16_MIN;
static int32_t t90 = -108423578;
t90 = (((x393+x394)!=x395)>x396);
if (t90 != 1) { NG(); } else { ; }
}
void f91(void) {
int64_t x397 = -5LL;
uint16_t x399 = 3288U;
int16_t x400 = INT16_MIN;
static volatile int32_t t91 = 621453;
t91 = (((x397+x398)!=x399)>x400);
if (t91 != 1) { NG(); } else { ; }
}
void f92(void) {
static uint64_t x401 = 3LLU;
uint64_t x402 = UINT64_MAX;
volatile int16_t x403 = 3761;
volatile int32_t x404 = INT32_MIN;
int32_t t92 = 1;
t92 = (((x401+x402)!=x403)>x404);
if (t92 != 1) { NG(); } else { ; }
}
void f93(void) {
int32_t x408 = 7440985;
volatile int32_t t93 = -800480;
t93 = (((x405+x406)!=x407)>x408);
if (t93 != 0) { NG(); } else { ; }
}
void f94(void) {
int8_t x409 = INT8_MAX;
int64_t x410 = 584LL;
uint64_t x412 = 119954272288LLU;
t94 = (((x409+x410)!=x411)>x412);
if (t94 != 0) { NG(); } else { ; }
}
void f95(void) {
static uint32_t x413 = UINT32_MAX;
static int32_t x414 = -1;
volatile int8_t x415 = INT8_MAX;
volatile int32_t t95 = 8322;
t95 = (((x413+x414)!=x415)>x416);
if (t95 != 0) { NG(); } else { ; }
}
void f96(void) {
int32_t x417 = 257;
int16_t x418 = INT16_MIN;
int8_t x419 = INT8_MIN;
int32_t x420 = 162;
t96 = (((x417+x418)!=x419)>x420);
if (t96 != 0) { NG(); } else { ; }
}
void f97(void) {
int8_t x422 = INT8_MIN;
int16_t x423 = INT16_MIN;
static volatile uint8_t x424 = 25U;
int32_t t97 = 771508;
t97 = (((x421+x422)!=x423)>x424);
if (t97 != 0) { NG(); } else { ; }
}
void f98(void) {
static int32_t x425 = -2668;
int64_t x426 = INT64_MAX;
volatile uint8_t x427 = UINT8_MAX;
volatile int64_t x428 = INT64_MIN;
int32_t t98 = 102520809;
t98 = (((x425+x426)!=x427)>x428);
if (t98 != 1) { NG(); } else { ; }
}
void f99(void) {
int64_t x431 = INT64_MIN;
volatile int64_t x432 = INT64_MIN;
int32_t t99 = 113;
t99 = (((x429+x430)!=x431)>x432);
if (t99 != 1) { NG(); } else { ; }
}
void f100(void) {
uint16_t x433 = 230U;
int64_t x434 = 1098LL;
uint16_t x435 = 25159U;
int32_t t100 = -74518;
t100 = (((x433+x434)!=x435)>x436);
if (t100 != 1) { NG(); } else { ; }
}
void f101(void) {
static volatile uint64_t x438 = 6608LLU;
uint8_t x439 = UINT8_MAX;
static volatile int32_t t101 = 41;
t101 = (((x437+x438)!=x439)>x440);
if (t101 != 0) { NG(); } else { ; }
}
void f102(void) {
static int64_t x441 = 4812124198203284LL;
int64_t x442 = INT64_MIN;
int8_t x444 = -1;
volatile int32_t t102 = -933043;
t102 = (((x441+x442)!=x443)>x444);
if (t102 != 1) { NG(); } else { ; }
}
void f103(void) {
int8_t x449 = 1;
volatile int16_t x450 = -1;
int8_t x451 = INT8_MIN;
int16_t x452 = 7823;
int32_t t103 = 41;
t103 = (((x449+x450)!=x451)>x452);
if (t103 != 0) { NG(); } else { ; }
}
void f104(void) {
volatile int32_t x453 = INT32_MIN;
static int8_t x454 = 22;
volatile int16_t x455 = -1;
int32_t x456 = INT32_MIN;
static volatile int32_t t104 = -1767319;
t104 = (((x453+x454)!=x455)>x456);
if (t104 != 1) { NG(); } else { ; }
}
void f105(void) {
int16_t x457 = -1;
volatile uint8_t x458 = 5U;
static int64_t x459 = INT64_MAX;
uint8_t x460 = 1U;
volatile int32_t t105 = 68307;
t105 = (((x457+x458)!=x459)>x460);
if (t105 != 0) { NG(); } else { ; }
}
void f106(void) {
static volatile int32_t x465 = -1;
int16_t x467 = INT16_MIN;
int8_t x468 = -25;
int32_t t106 = 523444;
t106 = (((x465+x466)!=x467)>x468);
if (t106 != 1) { NG(); } else { ; }
}
void f107(void) {
volatile int8_t x469 = INT8_MAX;
static uint32_t x470 = 23U;
uint64_t x471 = 16590017996784442LLU;
int64_t x472 = 39LL;
static volatile int32_t t107 = 1;
t107 = (((x469+x470)!=x471)>x472);
if (t107 != 0) { NG(); } else { ; }
}
void f108(void) {
int8_t x473 = INT8_MIN;
int8_t x474 = -36;
volatile uint64_t x475 = 7350294073939LLU;
int32_t x476 = -30;
int32_t t108 = -12775391;
t108 = (((x473+x474)!=x475)>x476);
if (t108 != 1) { NG(); } else { ; }
}
void f109(void) {
static int16_t x478 = 10440;
int16_t x479 = 2;
int32_t t109 = 395961796;
t109 = (((x477+x478)!=x479)>x480);
if (t109 != 0) { NG(); } else { ; }
}
void f110(void) {
uint64_t x482 = UINT64_MAX;
static int16_t x483 = INT16_MIN;
uint64_t x484 = UINT64_MAX;
volatile int32_t t110 = 63808;
t110 = (((x481+x482)!=x483)>x484);
if (t110 != 0) { NG(); } else { ; }
}
void f111(void) {
volatile int16_t x485 = INT16_MAX;
uint8_t x486 = 100U;
uint8_t x487 = 3U;
int8_t x488 = -13;
volatile int32_t t111 = 36;
t111 = (((x485+x486)!=x487)>x488);
if (t111 != 1) { NG(); } else { ; }
}
void f112(void) {
int16_t x493 = INT16_MIN;
uint32_t x494 = UINT32_MAX;
int64_t x495 = INT64_MIN;
volatile uint64_t x496 = 294312100385205LLU;
int32_t t112 = 0;
t112 = (((x493+x494)!=x495)>x496);
if (t112 != 0) { NG(); } else { ; }
}
void f113(void) {
volatile uint8_t x497 = 4U;
uint64_t x498 = UINT64_MAX;
int16_t x499 = INT16_MAX;
static int8_t x500 = 0;
int32_t t113 = -100508402;
t113 = (((x497+x498)!=x499)>x500);
if (t113 != 1) { NG(); } else { ; }
}
void f114(void) {
int8_t x501 = 27;
int8_t x502 = -1;
int32_t x504 = 148220;
t114 = (((x501+x502)!=x503)>x504);
if (t114 != 0) { NG(); } else { ; }
}
void f115(void) {
int32_t x505 = INT32_MIN;
uint8_t x506 = 0U;
int64_t x507 = INT64_MIN;
int16_t x508 = INT16_MIN;
int32_t t115 = 482272949;
t115 = (((x505+x506)!=x507)>x508);
if (t115 != 1) { NG(); } else { ; }
}
void f116(void) {
int32_t x509 = INT32_MIN;
volatile int64_t x510 = INT64_MAX;
volatile int64_t x511 = -1937675819317743691LL;
int32_t x512 = INT32_MIN;
static int32_t t116 = -138;
t116 = (((x509+x510)!=x511)>x512);
if (t116 != 1) { NG(); } else { ; }
}
void f117(void) {
static int64_t x520 = INT64_MAX;
volatile int32_t t117 = 759786;
t117 = (((x517+x518)!=x519)>x520);
if (t117 != 0) { NG(); } else { ; }
}
void f118(void) {
volatile uint32_t x522 = UINT32_MAX;
int64_t x523 = -1LL;
static int32_t x524 = 221;
static volatile int32_t t118 = 6114998;
t118 = (((x521+x522)!=x523)>x524);
if (t118 != 0) { NG(); } else { ; }
}
void f119(void) {
int16_t x525 = -1;
static int32_t x526 = INT32_MAX;
volatile uint16_t x527 = 60U;
int64_t x528 = INT64_MIN;
volatile int32_t t119 = -690196;
t119 = (((x525+x526)!=x527)>x528);
if (t119 != 1) { NG(); } else { ; }
}
void f120(void) {
static int64_t x529 = INT64_MIN;
volatile int8_t x530 = INT8_MAX;
int64_t x532 = INT64_MAX;
static volatile int32_t t120 = 971487509;
t120 = (((x529+x530)!=x531)>x532);
if (t120 != 0) { NG(); } else { ; }
}
void f121(void) {
uint64_t x533 = UINT64_MAX;
static uint16_t x534 = UINT16_MAX;
volatile int32_t x535 = INT32_MIN;
static int32_t x536 = 19910512;
int32_t t121 = 5410;
t121 = (((x533+x534)!=x535)>x536);
if (t121 != 0) { NG(); } else { ; }
}
void f122(void) {
uint16_t x537 = UINT16_MAX;
static int16_t x538 = INT16_MIN;
int16_t x539 = INT16_MAX;
uint8_t x540 = UINT8_MAX;
volatile int32_t t122 = 0;
t122 = (((x537+x538)!=x539)>x540);
if (t122 != 0) { NG(); } else { ; }
}
void f123(void) {
uint16_t x541 = 3U;
uint16_t x543 = 9U;
static volatile int32_t t123 = 126;
t123 = (((x541+x542)!=x543)>x544);
if (t123 != 0) { NG(); } else { ; }
}
void f124(void) {
uint32_t x549 = 82963182U;
volatile int32_t x550 = INT32_MIN;
int8_t x551 = INT8_MAX;
int8_t x552 = INT8_MAX;
int32_t t124 = -7446920;
t124 = (((x549+x550)!=x551)>x552);
if (t124 != 0) { NG(); } else { ; }
}
void f125(void) {
uint16_t x553 = 16U;
int16_t x555 = 1;
int32_t x556 = 7923;
int32_t t125 = 87;
t125 = (((x553+x554)!=x555)>x556);
if (t125 != 0) { NG(); } else { ; }
}
void f126(void) {
static int64_t x557 = -33922251294LL;
uint32_t x559 = 77748U;
static uint32_t x560 = 63242249U;
int32_t t126 = -3815894;
t126 = (((x557+x558)!=x559)>x560);
if (t126 != 0) { NG(); } else { ; }
}
void f127(void) {
static int32_t x562 = -316225;
uint64_t x563 = 68898143LLU;
static volatile uint8_t x564 = 61U;
volatile int32_t t127 = 2;
t127 = (((x561+x562)!=x563)>x564);
if (t127 != 0) { NG(); } else { ; }
}
void f128(void) {
int16_t x566 = -3;
uint64_t x567 = 8055060445094121LLU;
int8_t x568 = -6;
int32_t t128 = 13192681;
t128 = (((x565+x566)!=x567)>x568);
if (t128 != 1) { NG(); } else { ; }
}
void f129(void) {
volatile int64_t x573 = 0LL;
int64_t x575 = 3462558635089854LL;
int32_t x576 = 14666;
volatile int32_t t129 = -1;
t129 = (((x573+x574)!=x575)>x576);
if (t129 != 0) { NG(); } else { ; }
}
void f130(void) {
uint16_t x577 = UINT16_MAX;
static int8_t x578 = INT8_MIN;
volatile int16_t x579 = -1;
int64_t x580 = -1LL;
volatile int32_t t130 = 724735;
t130 = (((x577+x578)!=x579)>x580);
if (t130 != 1) { NG(); } else { ; }
}
void f131(void) {
uint32_t x581 = 38764478U;
static volatile uint16_t x582 = 5908U;
static int16_t x583 = 934;
int32_t x584 = -1;
t131 = (((x581+x582)!=x583)>x584);
if (t131 != 1) { NG(); } else { ; }
}
void f132(void) {
uint64_t x585 = 8167632469089790LLU;
uint32_t x586 = 3708478U;
int64_t x587 = 1LL;
static int16_t x588 = INT16_MAX;
int32_t t132 = -4109914;
t132 = (((x585+x586)!=x587)>x588);
if (t132 != 0) { NG(); } else { ; }
}
void f133(void) {
uint32_t x589 = 38U;
static int16_t x590 = -1;
int16_t x591 = -1;
int32_t x592 = INT32_MAX;
t133 = (((x589+x590)!=x591)>x592);
if (t133 != 0) { NG(); } else { ; }
}
void f134(void) {
int8_t x597 = -7;
static int8_t x598 = INT8_MIN;
int32_t x600 = INT32_MIN;
static int32_t t134 = -30;
t134 = (((x597+x598)!=x599)>x600);
if (t134 != 1) { NG(); } else { ; }
}
void f135(void) {
static volatile int16_t x601 = 7;
static int32_t x602 = -3404759;
uint32_t x603 = UINT32_MAX;
int64_t x604 = -29LL;
int32_t t135 = -1008656139;
t135 = (((x601+x602)!=x603)>x604);
if (t135 != 1) { NG(); } else { ; }
}
void f136(void) {
static int16_t x606 = 502;
uint8_t x607 = UINT8_MAX;
int8_t x608 = 48;
t136 = (((x605+x606)!=x607)>x608);
if (t136 != 0) { NG(); } else { ; }
}
void f137(void) {
static volatile uint16_t x609 = 17U;
int16_t x610 = INT16_MIN;
uint16_t x611 = 1U;
volatile int32_t t137 = 1;
t137 = (((x609+x610)!=x611)>x612);
if (t137 != 0) { NG(); } else { ; }
}
void f138(void) {
int16_t x613 = INT16_MIN;
int32_t x614 = INT32_MAX;
uint32_t x616 = 824375460U;
t138 = (((x613+x614)!=x615)>x616);
if (t138 != 0) { NG(); } else { ; }
}
void f139(void) {
int32_t x617 = INT32_MAX;
uint32_t x618 = UINT32_MAX;
uint16_t x619 = 7U;
int32_t t139 = -2894240;
t139 = (((x617+x618)!=x619)>x620);
if (t139 != 1) { NG(); } else { ; }
}
void f140(void) {
volatile uint16_t x621 = 752U;
uint32_t x622 = UINT32_MAX;
volatile int8_t x624 = 0;
int32_t t140 = 38;
t140 = (((x621+x622)!=x623)>x624);
if (t140 != 1) { NG(); } else { ; }
}
void f141(void) {
int64_t x625 = INT64_MIN;
uint64_t x626 = UINT64_MAX;
static volatile int8_t x627 = 1;
static volatile int32_t t141 = 1;
t141 = (((x625+x626)!=x627)>x628);
if (t141 != 0) { NG(); } else { ; }
}
void f142(void) {
int8_t x634 = INT8_MIN;
int8_t x635 = -6;
int32_t x636 = -1;
int32_t t142 = -43;
t142 = (((x633+x634)!=x635)>x636);
if (t142 != 1) { NG(); } else { ; }
}
void f143(void) {
static uint64_t x638 = UINT64_MAX;
static uint16_t x639 = UINT16_MAX;
uint16_t x640 = 18U;
int32_t t143 = -1;
t143 = (((x637+x638)!=x639)>x640);
if (t143 != 0) { NG(); } else { ; }
}
void f144(void) {
uint8_t x641 = 7U;
static int8_t x642 = -58;
int8_t x643 = INT8_MIN;
uint16_t x644 = 23U;
static int32_t t144 = -8850074;
t144 = (((x641+x642)!=x643)>x644);
if (t144 != 0) { NG(); } else { ; }
}
void f145(void) {
volatile int32_t t145 = -234;
t145 = (((x645+x646)!=x647)>x648);
if (t145 != 1) { NG(); } else { ; }
}
void f146(void) {
static uint32_t x649 = 8818U;
volatile uint8_t x650 = 2U;
volatile int32_t x651 = INT32_MAX;
static uint32_t x652 = UINT32_MAX;
volatile int32_t t146 = -1981;
t146 = (((x649+x650)!=x651)>x652);
if (t146 != 0) { NG(); } else { ; }
}
void f147(void) {
static uint8_t x653 = 0U;
int32_t x654 = INT32_MAX;
int8_t x655 = INT8_MIN;
static uint16_t x656 = UINT16_MAX;
int32_t t147 = 994503;
t147 = (((x653+x654)!=x655)>x656);
if (t147 != 0) { NG(); } else { ; }
}
void f148(void) {
uint32_t x659 = 6531020U;
uint64_t x660 = 190135670228068LLU;
int32_t t148 = -113354710;
t148 = (((x657+x658)!=x659)>x660);
if (t148 != 0) { NG(); } else { ; }
}
void f149(void) {
int64_t x661 = 0LL;
int32_t x662 = INT32_MIN;
static int32_t x663 = INT32_MIN;
volatile uint32_t x664 = 1229146007U;
int32_t t149 = 36770;
t149 = (((x661+x662)!=x663)>x664);
if (t149 != 0) { NG(); } else { ; }
}
void f150(void) {
int64_t x665 = 66012337101LL;
uint8_t x666 = UINT8_MAX;
int8_t x667 = INT8_MAX;
int32_t t150 = 1;
t150 = (((x665+x666)!=x667)>x668);
if (t150 != 0) { NG(); } else { ; }
}
void f151(void) {
int32_t x669 = INT32_MIN;
int32_t x671 = INT32_MIN;
static volatile uint64_t x672 = 136862144972475665LLU;
static volatile int32_t t151 = 1;
t151 = (((x669+x670)!=x671)>x672);
if (t151 != 0) { NG(); } else { ; }
}
void f152(void) {
int16_t x677 = -1;
int16_t x678 = -38;
int8_t x679 = -1;
int32_t t152 = -42578293;
t152 = (((x677+x678)!=x679)>x680);
if (t152 != 1) { NG(); } else { ; }
}
void f153(void) {
volatile int32_t x681 = INT32_MAX;
int64_t x682 = INT64_MIN;
static volatile int8_t x684 = INT8_MAX;
volatile int32_t t153 = -293934117;
t153 = (((x681+x682)!=x683)>x684);
if (t153 != 0) { NG(); } else { ; }
}
void f154(void) {
uint8_t x689 = 18U;
uint16_t x690 = 61U;
int32_t x691 = -29;
int64_t x692 = 652LL;
static volatile int32_t t154 = -384348389;
t154 = (((x689+x690)!=x691)>x692);
if (t154 != 0) { NG(); } else { ; }
}
void f155(void) {
int16_t x693 = INT16_MAX;
volatile int32_t x694 = INT32_MIN;
int8_t x695 = INT8_MIN;
volatile int32_t x696 = INT32_MIN;
t155 = (((x693+x694)!=x695)>x696);
if (t155 != 1) { NG(); } else { ; }
}
void f156(void) {
uint32_t x697 = 15150U;
int16_t x698 = -12;
int16_t x699 = 24;
static int64_t x700 = -1LL;
int32_t t156 = 1700;
t156 = (((x697+x698)!=x699)>x700);
if (t156 != 1) { NG(); } else { ; }
}
void f157(void) {
uint16_t x701 = 1233U;
volatile uint16_t x702 = UINT16_MAX;
volatile int8_t x703 = INT8_MIN;
volatile int32_t t157 = -779;
t157 = (((x701+x702)!=x703)>x704);
if (t157 != 1) { NG(); } else { ; }
}
void f158(void) {
uint16_t x705 = 5U;
int16_t x707 = INT16_MIN;
uint32_t x708 = UINT32_MAX;
volatile int32_t t158 = -44;
t158 = (((x705+x706)!=x707)>x708);
if (t158 != 0) { NG(); } else { ; }
}
void f159(void) {
int16_t x713 = -1;
int8_t x714 = -1;
static int32_t x715 = -100343833;
volatile int64_t x716 = INT64_MIN;
t159 = (((x713+x714)!=x715)>x716);
if (t159 != 1) { NG(); } else { ; }
}
void f160(void) {
volatile int64_t x717 = -88124009068872150LL;
static volatile int8_t x719 = INT8_MIN;
volatile int8_t x720 = -1;
volatile int32_t t160 = -402828240;
t160 = (((x717+x718)!=x719)>x720);
if (t160 != 1) { NG(); } else { ; }
}
void f161(void) {
uint8_t x722 = 21U;
volatile int32_t x723 = -1;
uint32_t x724 = 92U;
static volatile int32_t t161 = 235280894;
t161 = (((x721+x722)!=x723)>x724);
if (t161 != 0) { NG(); } else { ; }
}
void f162(void) {
int16_t x725 = 0;
static int16_t x726 = INT16_MAX;
int64_t x727 = -1LL;
uint8_t x728 = 62U;
static int32_t t162 = 6730;
t162 = (((x725+x726)!=x727)>x728);
if (t162 != 0) { NG(); } else { ; }
}
void f163(void) {
uint32_t x733 = 61607524U;
static int64_t x734 = -1LL;
volatile int8_t x735 = INT8_MIN;
int16_t x736 = -1;
t163 = (((x733+x734)!=x735)>x736);
if (t163 != 1) { NG(); } else { ; }
}
void f164(void) {
uint32_t x737 = 9U;
int8_t x738 = 1;
volatile int16_t x739 = INT16_MIN;
int64_t x740 = -1LL;
volatile int32_t t164 = 50408;
t164 = (((x737+x738)!=x739)>x740);
if (t164 != 1) { NG(); } else { ; }
}
void f165(void) {
volatile int16_t x741 = -16289;
int8_t x742 = 0;
int64_t x743 = INT64_MAX;
volatile int32_t x744 = INT32_MAX;
int32_t t165 = -660605062;
t165 = (((x741+x742)!=x743)>x744);
if (t165 != 0) { NG(); } else { ; }
}
void f166(void) {
int8_t x749 = 12;
int64_t x750 = -1LL;
int32_t x751 = -1;
uint64_t x752 = 620282427LLU;
volatile int32_t t166 = -145;
t166 = (((x749+x750)!=x751)>x752);
if (t166 != 0) { NG(); } else { ; }
}
void f167(void) {
int8_t x753 = INT8_MIN;
uint32_t x754 = UINT32_MAX;
int8_t x755 = INT8_MAX;
int8_t x756 = -1;
volatile int32_t t167 = 1;
t167 = (((x753+x754)!=x755)>x756);
if (t167 != 1) { NG(); } else { ; }
}
void f168(void) {
int16_t x757 = -1;
uint16_t x758 = 115U;
volatile uint16_t x759 = 1U;
volatile int64_t x760 = INT64_MAX;
t168 = (((x757+x758)!=x759)>x760);
if (t168 != 0) { NG(); } else { ; }
}
void f169(void) {
volatile int16_t x761 = -1;
uint8_t x762 = UINT8_MAX;
int8_t x763 = 27;
int64_t x764 = INT64_MAX;
static int32_t t169 = -5735;
t169 = (((x761+x762)!=x763)>x764);
if (t169 != 0) { NG(); } else { ; }
}
void f170(void) {
static volatile uint64_t x765 = 277883LLU;
volatile int64_t x766 = INT64_MAX;
int32_t t170 = 3232714;
t170 = (((x765+x766)!=x767)>x768);
if (t170 != 1) { NG(); } else { ; }
}
void f171(void) {
int64_t x769 = INT64_MIN;
uint64_t x771 = 2406366857114LLU;
int32_t t171 = 31;
t171 = (((x769+x770)!=x771)>x772);
if (t171 != 0) { NG(); } else { ; }
}
void f172(void) {
int32_t x774 = INT32_MIN;
volatile uint16_t x775 = UINT16_MAX;
int16_t x776 = 3;
t172 = (((x773+x774)!=x775)>x776);
if (t172 != 0) { NG(); } else { ; }
}
void f173(void) {
uint64_t x777 = 11LLU;
int32_t x778 = INT32_MIN;
static int32_t t173 = -1;
t173 = (((x777+x778)!=x779)>x780);
if (t173 != 1) { NG(); } else { ; }
}
void f174(void) {
volatile uint64_t x782 = 74569601458LLU;
uint16_t x784 = 25982U;
int32_t t174 = -91355304;
t174 = (((x781+x782)!=x783)>x784);
if (t174 != 0) { NG(); } else { ; }
}
void f175(void) {
int16_t x786 = INT16_MIN;
int16_t x787 = 12;
int64_t x788 = INT64_MIN;
int32_t t175 = -1028141235;
t175 = (((x785+x786)!=x787)>x788);
if (t175 != 1) { NG(); } else { ; }
}
void f176(void) {
volatile int16_t x789 = 1;
int32_t x790 = 9;
static volatile uint8_t x791 = UINT8_MAX;
uint64_t x792 = 33588378LLU;
int32_t t176 = 178224221;
t176 = (((x789+x790)!=x791)>x792);
if (t176 != 0) { NG(); } else { ; }
}
void f177(void) {
uint8_t x793 = UINT8_MAX;
int8_t x794 = INT8_MIN;
int32_t t177 = -10;
t177 = (((x793+x794)!=x795)>x796);
if (t177 != 0) { NG(); } else { ; }
}
void f178(void) {
static int8_t x798 = INT8_MIN;
static int8_t x799 = -22;
int32_t x800 = -12731;
t178 = (((x797+x798)!=x799)>x800);
if (t178 != 1) { NG(); } else { ; }
}
void f179(void) {
static volatile int64_t x801 = -61676377119900LL;
volatile uint64_t x803 = 2636018LLU;
volatile int32_t t179 = 311;
t179 = (((x801+x802)!=x803)>x804);
if (t179 != 0) { NG(); } else { ; }
}
void f180(void) {
int64_t x806 = -1LL;
static int64_t x807 = -1LL;
volatile int64_t x808 = 284180248850572426LL;
t180 = (((x805+x806)!=x807)>x808);
if (t180 != 0) { NG(); } else { ; }
}
void f181(void) {
int32_t x813 = 732982691;
int16_t x814 = INT16_MIN;
int64_t x815 = INT64_MIN;
int64_t x816 = 13162LL;
static volatile int32_t t181 = -147;
t181 = (((x813+x814)!=x815)>x816);
if (t181 != 0) { NG(); } else { ; }
}
void f182(void) {
static uint16_t x817 = 4371U;
volatile int32_t x818 = -1;
int32_t x819 = INT32_MIN;
static int64_t x820 = 21110462LL;
int32_t t182 = 928;
t182 = (((x817+x818)!=x819)>x820);
if (t182 != 0) { NG(); } else { ; }
}
void f183(void) {
int8_t x822 = -46;
int8_t x823 = 2;
uint32_t x824 = UINT32_MAX;
int32_t t183 = 89145;
t183 = (((x821+x822)!=x823)>x824);
if (t183 != 0) { NG(); } else { ; }
}
void f184(void) {
static uint8_t x825 = UINT8_MAX;
int64_t x826 = INT64_MIN;
int32_t x828 = INT32_MIN;
int32_t t184 = 408;
t184 = (((x825+x826)!=x827)>x828);
if (t184 != 1) { NG(); } else { ; }
}
void f185(void) {
uint16_t x829 = 1U;
static int64_t x830 = INT64_MIN;
volatile int32_t x831 = INT32_MAX;
int32_t t185 = -7788845;
t185 = (((x829+x830)!=x831)>x832);
if (t185 != 0) { NG(); } else { ; }
}
void f186(void) {
static int8_t x833 = -1;
uint8_t x834 = 19U;
int16_t x835 = INT16_MIN;
static int8_t x836 = -1;
int32_t t186 = 46295;
t186 = (((x833+x834)!=x835)>x836);
if (t186 != 1) { NG(); } else { ; }
}
void f187(void) {
int32_t x841 = -1;
int64_t x843 = INT64_MIN;
int16_t x844 = -1;
volatile int32_t t187 = -5;
t187 = (((x841+x842)!=x843)>x844);
if (t187 != 1) { NG(); } else { ; }
}
void f188(void) {
uint8_t x845 = UINT8_MAX;
int16_t x846 = 12682;
int8_t x847 = INT8_MAX;
uint16_t x848 = 458U;
int32_t t188 = 49253;
t188 = (((x845+x846)!=x847)>x848);
if (t188 != 0) { NG(); } else { ; }
}
void f189(void) {
volatile uint8_t x850 = 21U;
volatile int64_t x851 = -633321LL;
t189 = (((x849+x850)!=x851)>x852);
if (t189 != 1) { NG(); } else { ; }
}
void f190(void) {
int16_t x854 = INT16_MAX;
uint16_t x855 = 851U;
int32_t t190 = -440653;
t190 = (((x853+x854)!=x855)>x856);
if (t190 != 1) { NG(); } else { ; }
}
void f191(void) {
int64_t x857 = INT64_MAX;
uint64_t x858 = 4103772LLU;
int64_t x859 = INT64_MAX;
volatile int64_t x860 = -15740849334LL;
volatile int32_t t191 = 13680;
t191 = (((x857+x858)!=x859)>x860);
if (t191 != 1) { NG(); } else { ; }
}
void f192(void) {
static int64_t x865 = 1444863442166996LL;
static int32_t x866 = INT32_MAX;
uint8_t x868 = UINT8_MAX;
t192 = (((x865+x866)!=x867)>x868);
if (t192 != 0) { NG(); } else { ; }
}
void f193(void) {
int64_t x870 = 0LL;
int32_t t193 = 29;
t193 = (((x869+x870)!=x871)>x872);
if (t193 != 0) { NG(); } else { ; }
}
void f194(void) {
static uint8_t x877 = UINT8_MAX;
static uint16_t x878 = 57U;
static int32_t x879 = -1;
int8_t x880 = 1;
int32_t t194 = -10459;
t194 = (((x877+x878)!=x879)>x880);
if (t194 != 0) { NG(); } else { ; }
}
void f195(void) {
volatile int16_t x881 = INT16_MAX;
uint64_t x883 = UINT64_MAX;
int32_t x884 = INT32_MIN;
volatile int32_t t195 = 920;
t195 = (((x881+x882)!=x883)>x884);
if (t195 != 1) { NG(); } else { ; }
}
void f196(void) {
volatile uint16_t x885 = 2312U;
uint64_t x886 = 84455829715770035LLU;
static uint32_t x887 = UINT32_MAX;
volatile int32_t t196 = 2079731;
t196 = (((x885+x886)!=x887)>x888);
if (t196 != 0) { NG(); } else { ; }
}
void f197(void) {
uint32_t x891 = 50406U;
uint64_t x892 = UINT64_MAX;
volatile int32_t t197 = -11256516;
t197 = (((x889+x890)!=x891)>x892);
if (t197 != 0) { NG(); } else { ; }
}
void f198(void) {
int32_t x893 = INT32_MIN;
uint16_t x894 = 220U;
volatile uint16_t x896 = UINT16_MAX;
volatile int32_t t198 = 524724352;
t198 = (((x893+x894)!=x895)>x896);
if (t198 != 0) { NG(); } else { ; }
}
void f199(void) {
volatile uint64_t x897 = 2235813642965451LLU;
uint8_t x898 = UINT8_MAX;
volatile int16_t x899 = 267;
int32_t x900 = INT32_MIN;
int32_t t199 = 1;
t199 = (((x897+x898)!=x899)>x900);
if (t199 != 1) { NG(); } else { ; }
}
int main(void) {
f0();
f1();
f2();
f3();
f4();
f5();
f6();
f7();
f8();
f9();
f10();
f11();
f12();
f13();
f14();
f15();
f16();
f17();
f18();
f19();
f20();
f21();
f22();
f23();
f24();
f25();
f26();
f27();
f28();
f29();
f30();
f31();
f32();
f33();
f34();
f35();
f36();
f37();
f38();
f39();
f40();
f41();
f42();
f43();
f44();
f45();
f46();
f47();
f48();
f49();
f50();
f51();
f52();
f53();
f54();
f55();
f56();
f57();
f58();
f59();
f60();
f61();
f62();
f63();
f64();
f65();
f66();
f67();
f68();
f69();
f70();
f71();
f72();
f73();
f74();
f75();
f76();
f77();
f78();
f79();
f80();
f81();
f82();
f83();
f84();
f85();
f86();
f87();
f88();
f89();
f90();
f91();
f92();
f93();
f94();
f95();
f96();
f97();
f98();
f99();
f100();
f101();
f102();
f103();
f104();
f105();
f106();
f107();
f108();
f109();
f110();
f111();
f112();
f113();
f114();
f115();
f116();
f117();
f118();
f119();
f120();
f121();
f122();
f123();
f124();
f125();
f126();
f127();
f128();
f129();
f130();
f131();
f132();
f133();
f134();
f135();
f136();
f137();
f138();
f139();
f140();
f141();
f142();
f143();
f144();
f145();
f146();
f147();
f148();
f149();
f150();
f151();
f152();
f153();
f154();
f155();
f156();
f157();
f158();
f159();
f160();
f161();
f162();
f163();
f164();
f165();
f166();
f167();
f168();
f169();
f170();
f171();
f172();
f173();
f174();
f175();
f176();
f177();
f178();
f179();
f180();
f181();
f182();
f183();
f184();
f185();
f186();
f187();
f188();
f189();
f190();
f191();
f192();
f193();
f194();
f195();
f196();
f197();
f198();
f199();
return 0;
}
|
dbtmurray/icu_tournament | lib/icu_tournament/team.rb | module ICU
#
# A team consists of a name and one or more players referenced by numbers.
# Typically the team will be attached to a tournament (ICU::Tournament)
# and the numbers will the unique numbers by which the players in that
# tournament are referenced. To instantiate a team, you must supply a
# name.
#
# team = ICU::Team.new('Wandering Dragons')
#
# Then you simply add player's (numbers) to it.
#
# team.add_player(1)
# team.add_payeer(3)
# team.add_player(7)
#
# To get the current members of a team
#
# team.members # => [1, 3, 7]
#
# You can enquire whether a team contains a given player number.
#
# team.contains?(3) # => true
# team.contains?(4) # => false
#
# Or whether it matches a given name (which ignoring case and removing spurious whitespace)
#
# team.matches(' wandering dragons ') # => true
# team.matches('Blundering Bishops') # => false
#
# Whenever you reset the name of a tournament spurious whitespace is removed but case is not altered.
#
# team.name = ' blundering bishops '
# team.name # => "blundering bishops"
#
# Attempting to add non-numbers or duplicate numbers as new team members results in an exception.
#
# team.add(nil) # exception - not a number
# team.add(3) # exception - already a member
#
class Team
attr_reader :name, :members
# Constructor. Name must be supplied.
def initialize(name)
self.name = name
@members = Array.new
end
# Set name. Must not be blank.
def name=(name)
@name = name.strip.squeeze(' ')
raise "team can't be blank" if @name.length == 0
end
# Add a team member referenced by any integer.
def add_member(number)
pnum = number.to_i
raise "'#{number}' is not a valid as a team member player number" if pnum == 0 && !number.to_s.match(/^[^\d]*0/)
raise "can't add duplicate player number #{pnum} to team '#{@name}'" if @members.include?(pnum)
@members.push(pnum)
end
# Renumber the players according to the supplied hash. Return self.
def renumber(map)
@members.each_with_index do |pnum, index|
raise "player number #{pnum} not found in renumbering hash" unless map[pnum]
@members[index] = map[pnum]
end
self
end
# Detect if a member exists in a team.
def include?(number)
@members.include?(number)
end
# Does the team name match the given string (ignoring case and spurious whitespace).
def matches(name)
self.name.downcase == name.strip.squeeze(' ').downcase
end
end
end |
CI6/gmchain-core | src/network/p2p_networking.h | //
// p2p_networking.h
// gmchain-core
//
// Created by AnonymityMaster on 2019/12/18.
// Copyright © 2019 ci6. All rights reserved.
//
#ifndef p2p_networking_h
#define p2p_networking_h
#include <stdio.h>
typedef struct {
} P2PNetworking;
#endif /* p2p_networking_h */
|
lnkaruturi/JavaPrograms | Selinium/src/mercurytoots/Mercury.java | <gh_stars>0
package mercurytoots;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Mercury {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\<NAME>\\Desktop\\chromedriver_win32\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("http://www.newtours.demoaut.com/");
driver.findElement(By.xpath(".//*[starts-with(@href,'mercuryregister.php')]")).click();
driver.findElement(By.xpath(".//*[contains(@name,'firstName')]")).sendKeys("Lakshmi");
driver.findElement(By.xpath(".//*[contains(@name,'lastName')]")).sendKeys("Karuturi");
driver.findElement(By.xpath(".//*[contains(@name,'phone')]")).sendKeys("7047791898");
driver.findElement(By.xpath(".//*[contains(@id,'userName')]")).sendKeys("<EMAIL>");
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[contains(@name,'address1')]")).sendKeys("4211 Harwin Place");
//driver.findElement(By.name("address1")).sendKeys("4211 Harwin Place");
driver.findElement(By.name("address2")).sendKeys("Apt-309");
driver.findElement(By.xpath(".//*[contains(@name,'city')]")).sendKeys("<NAME>");
//driver.findElement(By.name("city")).sendKeys("Glen Allen");
driver.findElement(By.xpath(".//*[contains(@name,'state')]")).sendKeys("VA");
//driver.findElement(By.name("state")).sendKeys("VA");
driver.findElement(By.name("postalCode")).sendKeys("23060");
driver.findElement(By.name("country")).sendKeys("UNITED STATES");
Thread.sleep(2000);
driver.findElement(By.name("email")).sendKeys("<EMAIL>");
driver.findElement(By.name("password")).sendKeys("<PASSWORD>");
driver.findElement(By.name("confirmPassword")).sendKeys("<PASSWORD>");
}
}
|
CharlesKimMaina/chattie | src/client/components/Loader/Loader.js | <filename>src/client/components/Loader/Loader.js
import React from 'react';
import './Loader.styles.css';
export default function Loader() {
return (
<div className="container">
<div className="canvas">
<div className="hour-glass"> </div>
</div>
</div>
);
}
|
BreakerOfThings/o3de | Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/TranslationManipulators.cpp | <filename>Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/TranslationManipulators.cpp
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include "TranslationManipulators.h"
#include <AzCore/Math/VectorConversions.h>
#include <AzToolsFramework/Manipulators/ManipulatorView.h>
#include <AzToolsFramework/Viewport/ViewportSettings.h>
namespace AzToolsFramework
{
static const AZ::Color LinearManipulatorXAxisColor = AZ::Color(1.0f, 0.0f, 0.0f, 1.0f);
static const AZ::Color LinearManipulatorYAxisColor = AZ::Color(0.0f, 1.0f, 0.0f, 1.0f);
static const AZ::Color LinearManipulatorZAxisColor = AZ::Color(0.0f, 0.0f, 1.0f, 1.0f);
static const AZ::Color SurfaceManipulatorColor = AZ::Color(1.0f, 1.0f, 0.0f, 0.5f);
static TranslationManipulatorsViewCreateInfo DefaultTranslationManipulatorViewCreateInfo()
{
TranslationManipulatorsViewCreateInfo createInfo;
createInfo.axis1Color = LinearManipulatorXAxisColor;
createInfo.axis2Color = LinearManipulatorYAxisColor;
createInfo.axis3Color = LinearManipulatorZAxisColor;
createInfo.surfaceColor = SurfaceManipulatorColor;
createInfo.linearAxisLength = LinearManipulatorAxisLength();
createInfo.linearConeLength = LinearManipulatorConeLength();
createInfo.linearConeRadius = LinearManipulatorConeRadius();
createInfo.planarAxisLength = PlanarManipulatorAxisLength();
createInfo.surfaceRadius = SurfaceManipulatorRadius();
return createInfo;
}
TranslationManipulators::TranslationManipulators(
const Dimensions dimensions, const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale)
: m_dimensions(dimensions)
{
switch (dimensions)
{
case Dimensions::Two:
m_linearManipulators.reserve(2);
for (size_t manipulatorIndex = 0; manipulatorIndex < 2; ++manipulatorIndex)
{
m_linearManipulators.emplace_back(LinearManipulator::MakeShared(worldFromLocal));
}
m_planarManipulators.emplace_back(PlanarManipulator::MakeShared(worldFromLocal));
break;
case Dimensions::Three:
m_linearManipulators.reserve(3);
m_planarManipulators.reserve(3);
for (size_t manipulatorIndex = 0; manipulatorIndex < 3; ++manipulatorIndex)
{
m_linearManipulators.emplace_back(LinearManipulator::MakeShared(worldFromLocal));
m_planarManipulators.emplace_back(PlanarManipulator::MakeShared(worldFromLocal));
}
m_surfaceManipulator = SurfaceManipulator::MakeShared(worldFromLocal);
break;
default:
AZ_Assert(false, "Invalid dimensions provided");
break;
}
m_manipulatorSpaceWithLocalTransform.SetSpace(worldFromLocal);
SetNonUniformScale(nonUniformScale);
}
void TranslationManipulators::InstallLinearManipulatorMouseDownCallback(
const LinearManipulator::MouseActionCallback& onMouseDownCallback)
{
for (AZStd::shared_ptr<LinearManipulator>& manipulator : m_linearManipulators)
{
manipulator->InstallLeftMouseDownCallback(onMouseDownCallback);
}
}
void TranslationManipulators::InstallLinearManipulatorMouseMoveCallback(
const LinearManipulator::MouseActionCallback& onMouseMoveCallback)
{
for (AZStd::shared_ptr<LinearManipulator>& manipulator : m_linearManipulators)
{
manipulator->InstallMouseMoveCallback(onMouseMoveCallback);
}
}
void TranslationManipulators::InstallLinearManipulatorMouseUpCallback(const LinearManipulator::MouseActionCallback& onMouseUpCallback)
{
for (AZStd::shared_ptr<LinearManipulator>& manipulator : m_linearManipulators)
{
manipulator->InstallLeftMouseUpCallback(onMouseUpCallback);
}
}
void TranslationManipulators::InstallPlanarManipulatorMouseDownCallback(
const PlanarManipulator::MouseActionCallback& onMouseDownCallback)
{
for (AZStd::shared_ptr<PlanarManipulator>& manipulator : m_planarManipulators)
{
manipulator->InstallLeftMouseDownCallback(onMouseDownCallback);
}
}
void TranslationManipulators::InstallPlanarManipulatorMouseMoveCallback(
const PlanarManipulator::MouseActionCallback& onMouseMoveCallback)
{
for (AZStd::shared_ptr<PlanarManipulator>& manipulator : m_planarManipulators)
{
manipulator->InstallMouseMoveCallback(onMouseMoveCallback);
}
}
void TranslationManipulators::InstallPlanarManipulatorMouseUpCallback(const PlanarManipulator::MouseActionCallback& onMouseUpCallback)
{
for (AZStd::shared_ptr<PlanarManipulator>& manipulator : m_planarManipulators)
{
manipulator->InstallLeftMouseUpCallback(onMouseUpCallback);
}
}
void TranslationManipulators::InstallSurfaceManipulatorMouseDownCallback(
const SurfaceManipulator::MouseActionCallback& onMouseDownCallback)
{
if (m_surfaceManipulator)
{
m_surfaceManipulator->InstallLeftMouseDownCallback(onMouseDownCallback);
}
}
void TranslationManipulators::InstallSurfaceManipulatorMouseUpCallback(const SurfaceManipulator::MouseActionCallback& onMouseUpCallback)
{
if (m_surfaceManipulator)
{
m_surfaceManipulator->InstallLeftMouseUpCallback(onMouseUpCallback);
}
}
void TranslationManipulators::InstallSurfaceManipulatorMouseMoveCallback(
const SurfaceManipulator::MouseActionCallback& onMouseMoveCallback)
{
if (m_surfaceManipulator)
{
m_surfaceManipulator->InstallMouseMoveCallback(onMouseMoveCallback);
}
}
void TranslationManipulators::InstallSurfaceManipulatorEntityIdsToIgnoreFn(
SurfaceManipulator::EntityIdsToIgnoreFn entityIdsToIgnoreFn)
{
if (m_surfaceManipulator)
{
m_surfaceManipulator->InstallEntityIdsToIgnoreFn(AZStd::move(entityIdsToIgnoreFn));
}
}
void TranslationManipulators::SetLocalTransformImpl(const AZ::Transform& localTransform)
{
for (AZStd::shared_ptr<LinearManipulator>& manipulator : m_linearManipulators)
{
manipulator->SetLocalTransform(localTransform);
}
for (AZStd::shared_ptr<PlanarManipulator>& manipulator : m_planarManipulators)
{
manipulator->SetLocalTransform(localTransform);
}
if (m_surfaceManipulator)
{
m_surfaceManipulator->SetLocalPosition(localTransform.GetTranslation());
}
}
void TranslationManipulators::SetLocalPositionImpl(const AZ::Vector3& localPosition)
{
for (AZStd::shared_ptr<LinearManipulator>& manipulator : m_linearManipulators)
{
manipulator->SetLocalPosition(localPosition);
}
for (AZStd::shared_ptr<PlanarManipulator>& manipulator : m_planarManipulators)
{
manipulator->SetLocalPosition(localPosition);
}
if (m_surfaceManipulator)
{
m_surfaceManipulator->SetLocalPosition(localPosition);
}
}
void TranslationManipulators::SetLocalOrientationImpl(const AZ::Quaternion& localOrientation)
{
for (AZStd::shared_ptr<LinearManipulator>& manipulator : m_linearManipulators)
{
manipulator->SetLocalOrientation(localOrientation);
}
for (AZStd::shared_ptr<PlanarManipulator>& manipulator : m_planarManipulators)
{
manipulator->SetLocalOrientation(localOrientation);
}
}
void TranslationManipulators::SetSpaceImpl(const AZ::Transform& worldFromLocal)
{
for (AZStd::shared_ptr<LinearManipulator>& manipulator : m_linearManipulators)
{
manipulator->SetSpace(worldFromLocal);
}
for (AZStd::shared_ptr<PlanarManipulator>& manipulator : m_planarManipulators)
{
manipulator->SetSpace(worldFromLocal);
}
if (m_surfaceManipulator)
{
m_surfaceManipulator->SetSpace(worldFromLocal);
}
}
void TranslationManipulators::SetNonUniformScaleImpl(const AZ::Vector3& nonUniformScale)
{
for (AZStd::shared_ptr<LinearManipulator>& manipulator : m_linearManipulators)
{
manipulator->SetNonUniformScale(nonUniformScale);
}
for (AZStd::shared_ptr<PlanarManipulator>& manipulator : m_planarManipulators)
{
manipulator->SetNonUniformScale(nonUniformScale);
}
if (m_surfaceManipulator)
{
m_surfaceManipulator->SetNonUniformScale(nonUniformScale);
}
}
void TranslationManipulators::SetAxes(
const AZ::Vector3& axis1, const AZ::Vector3& axis2, const AZ::Vector3& axis3 /*= AZ::Vector3::CreateAxisZ()*/)
{
AZ::Vector3 axes[] = { axis1, axis2, axis3 };
for (size_t manipulatorIndex = 0; manipulatorIndex < m_linearManipulators.size(); ++manipulatorIndex)
{
m_linearManipulators[manipulatorIndex]->SetAxis(axes[manipulatorIndex]);
}
for (size_t manipulatorIndex = 0; manipulatorIndex < m_planarManipulators.size(); ++manipulatorIndex)
{
m_planarManipulators[manipulatorIndex]->SetAxes(axes[manipulatorIndex], axes[(manipulatorIndex + 1) % 3]);
}
}
void TranslationManipulators::ConfigureView2d(const TranslationManipulatorsViewCreateInfo& translationManipulatorViewCreateInfo)
{
ConfigureLinearView(
translationManipulatorViewCreateInfo.linearAxisLength, translationManipulatorViewCreateInfo.linearConeLength,
translationManipulatorViewCreateInfo.linearConeRadius, translationManipulatorViewCreateInfo.axis1Color,
translationManipulatorViewCreateInfo.axis2Color, translationManipulatorViewCreateInfo.axis3Color);
ConfigurePlanarView(
translationManipulatorViewCreateInfo.planarAxisLength, translationManipulatorViewCreateInfo.linearAxisLength,
translationManipulatorViewCreateInfo.linearConeLength, translationManipulatorViewCreateInfo.axis1Color,
translationManipulatorViewCreateInfo.axis2Color, translationManipulatorViewCreateInfo.axis3Color);
}
void TranslationManipulators::ConfigureView3d(const TranslationManipulatorsViewCreateInfo& translationManipulatorViewCreateInfo)
{
ConfigureView2d(translationManipulatorViewCreateInfo);
ConfigureSurfaceView(translationManipulatorViewCreateInfo.surfaceRadius, translationManipulatorViewCreateInfo.surfaceColor);
}
void TranslationManipulators::ConfigureLinearView(
const float axisLength,
const float coneLength,
const float coneRadius,
const AZ::Color& axis1Color,
const AZ::Color& axis2Color,
const AZ::Color& axis3Color /*= AZ::Color(0.0f, 0.0f, 1.0f, 0.5f)*/)
{
const AZ::Color axesColor[] = { axis1Color, axis2Color, axis3Color };
const auto configureLinearView = [lineBoundWidth = m_lineBoundWidth, coneLength, axisLength,
coneRadius](LinearManipulator* linearManipulator, const AZ::Color& color)
{
const auto lineLength = axisLength - coneLength;
ManipulatorViews views;
views.emplace_back(CreateManipulatorViewLine(*linearManipulator, color, axisLength, lineBoundWidth));
views.emplace_back(
CreateManipulatorViewCone(*linearManipulator, color, linearManipulator->GetAxis() * lineLength, coneLength, coneRadius));
linearManipulator->SetViews(AZStd::move(views));
};
for (size_t manipulatorIndex = 0; manipulatorIndex < m_linearManipulators.size(); ++manipulatorIndex)
{
configureLinearView(m_linearManipulators[manipulatorIndex].get(), axesColor[manipulatorIndex]);
}
}
void TranslationManipulators::ConfigurePlanarView(
const float planarAxisLength,
const float linearAxisLength,
const float linearConeLength,
const AZ::Color& plane1Color,
const AZ::Color& plane2Color /*= AZ::Color(0.0f, 1.0f, 0.0f, 0.5f)*/,
const AZ::Color& plane3Color /*= AZ::Color(0.0f, 0.0f, 1.0f, 0.5f)*/)
{
const AZ::Color planesColor[] = { plane1Color, plane2Color, plane3Color };
for (size_t manipulatorIndex = 0; manipulatorIndex < m_planarManipulators.size(); ++manipulatorIndex)
{
const auto& planarManipulator = *m_planarManipulators[manipulatorIndex];
m_planarManipulators[manipulatorIndex]->SetViews(ManipulatorViews{ CreateManipulatorViewQuadForPlanarTranslationManipulator(
planarManipulator.GetAxis1(), planarManipulator.GetAxis2(), planesColor[manipulatorIndex],
planesColor[(manipulatorIndex + 1) % 3], linearAxisLength, linearConeLength, planarAxisLength) });
}
}
void TranslationManipulators::ConfigureSurfaceView(const float radius, const AZ::Color& color)
{
if (m_surfaceManipulator)
{
m_surfaceManipulator->SetView(CreateManipulatorViewSphere(
color, radius,
[]([[maybe_unused]] const ViewportInteraction::MouseInteraction& mouseInteraction, bool mouseOver,
const AZ::Color& defaultColor) -> AZ::Color
{
const AZ::Color color[2] = {
defaultColor, Vector3ToVector4(BaseManipulator::s_defaultMouseOverColor.GetAsVector3(), SurfaceManipulatorOpacity())
};
return color[mouseOver];
}));
}
}
void TranslationManipulators::ProcessManipulators(const AZStd::function<void(BaseManipulator*)>& manipulatorFn)
{
for (AZStd::shared_ptr<LinearManipulator>& manipulator : m_linearManipulators)
{
manipulatorFn(manipulator.get());
}
for (AZStd::shared_ptr<PlanarManipulator>& manipulator : m_planarManipulators)
{
manipulatorFn(manipulator.get());
}
if (m_surfaceManipulator)
{
manipulatorFn(m_surfaceManipulator.get());
}
}
void TranslationManipulators::SetLineBoundWidth(const float lineBoundWidth)
{
m_lineBoundWidth = lineBoundWidth;
}
void ConfigureTranslationManipulatorAppearance3d(TranslationManipulators* translationManipulators)
{
translationManipulators->SetAxes(AZ::Vector3::CreateAxisX(), AZ::Vector3::CreateAxisY(), AZ::Vector3::CreateAxisZ());
translationManipulators->ConfigureView3d(DefaultTranslationManipulatorViewCreateInfo());
}
void ConfigureTranslationManipulatorAppearance2d(TranslationManipulators* translationManipulators)
{
translationManipulators->SetAxes(AZ::Vector3::CreateAxisX(), AZ::Vector3::CreateAxisY());
translationManipulators->ConfigureView2d(DefaultTranslationManipulatorViewCreateInfo());
}
AZStd::shared_ptr<ManipulatorViewQuad> CreateManipulatorViewQuadForPlanarTranslationManipulator(
const AZ::Vector3& axis1,
const AZ::Vector3& axis2,
const AZ::Color& axis1Color,
const AZ::Color& axis2Color,
const float linearAxisLength,
const float linearConeLength,
const float planarAxisLength)
{
const AZ::Vector3 offset = (axis1 + axis2) * (((linearAxisLength - linearConeLength) * 0.5f) - (planarAxisLength * 0.5f));
return CreateManipulatorViewQuad(axis1, axis2, axis1Color, axis2Color, offset, planarAxisLength);
}
} // namespace AzToolsFramework
|
TongqiLiu/leetcode | Algorithms/Java/src/OneEditDistance/OneEditDistance.java | <gh_stars>1-10
package src.OneEditDistance;
/**
* @author mingqiao
* @Date 2020/10/12
*/
public class OneEditDistance {
/**
* 题目地址:https://leetcode-cn.com/problems/one-edit-distance/
* 先通过交换默认让ls<lt,然后就只剩两种情况满足条件了,复杂度O(N)
*
* @param s
* @param t
* @return
*/
public boolean isOneEditDistance(String s, String t) {
int ls = s.length();
int lt = t.length();
if (ls > lt) {
return isOneEditDistance(t, s);
}
if (lt - ls > 1) {
return false;
}
for (int i = 0; i < ls; i++) {
if (s.charAt(i) != t.charAt(i)) {
if (ls == lt) {
//替换当前位置,之后的两子串需要完全一致
return s.substring(i + 1).equals(t.substring(i + 1));
} else {
//删掉t串该字符,剩余两子串需要完全一致
return s.substring(i).equals(t.substring(i + 1));
}
}
}
//两字符串不能完全相同
return ls + 1 == lt;
}
}
|
uk-gov-mirror/ONSdigital.census-worth-self-help | site/src/extra/report.js | <reponame>uk-gov-mirror/ONSdigital.census-worth-self-help
import React from "react"
import { graphql } from "gatsby"
import { css } from "@emotion/core"
import PageTitle from "../components/pagetitle"
import TextBlock from "../components/textblock"
import ReportItem from "../components/admin/reportItem"
import DatePicker from "react-datepicker"
import datePickerCss from "./datePickerCss"
const moment = require("moment")
const NA = "(not set)"
const SET = "(set)"
const DRAFT = "(in draft)"
const INITIAL_STATE = {
author: "",
cconly: "",
contentsource: "",
departments: "",
directory: "",
draftreason: "",
"match-author": "",
"match-title": "",
"match-signedby": "",
"match-tags": "",
optimisedby: "",
"date-from": null,
"date-to": null,
roles: "",
signedby: "",
title: "",
}
export default class Report extends React.Component {
constructor(props) {
super(props)
this.data = props.data
this.state = INITIAL_STATE
this.fieldMatches = this.fieldMatches.bind(this)
this.fieldEquals = this.fieldEquals.bind(this)
this.fieldDateBetween = this.fieldDateBetween.bind(this)
this.getCollectionSelect = this.getCollectionSelect.bind(this)
this.getCollectionOptions = this.getCollectionOptions.bind(this)
this.getFieldMatchInput = this.getFieldMatchInput.bind(this)
this.getFieldDateBetweenSelector = this.getFieldDateBetweenSelector.bind(this)
this.reset = this.reset.bind(this)
}
updateReport(fieldName) {
return (event) => {
this.setState({
[fieldName]: event.target.value
})
}
}
updateReportDate(fieldName) {
return (date) => {
this.setState({
[fieldName]: date
})
}
}
reset() {
this.setState(INITIAL_STATE);
}
fieldMatches(fieldName, node) {
const matchStateAttributeName = "match-" + fieldName
return !this.state[matchStateAttributeName] ||
(node.frontmatter[fieldName] &&
JSON.stringify(node.frontmatter[fieldName]).toLowerCase().includes(this.state[matchStateAttributeName].toLowerCase())
)
}
fieldEquals(fieldName, node) {
const value = this.state[fieldName]
const fieldValue = node.frontmatter[fieldName]
return !value ||
(Array.isArray(fieldValue) && fieldValue.includes(value)) ||
`${node.frontmatter[fieldName]}` === value ||
(value === DRAFT && node.frontmatter[fieldName] !== "Ready for Live Site") ||
(value === NA && !this.isSet(node.frontmatter[fieldName])) ||
(value === SET && this.isSet(node.frontmatter[fieldName]))
}
fieldDateBetween(fieldName, node) {
const from = this.state[fieldName + "-from"]
const to = this.state[fieldName + "-to"]
const date = node.frontmatter[fieldName]
if (!to && !from) {
return true
}
if (!date) {
return false
}
if (!to) {
return moment(date).isAfter(moment(from));
}
if (!from) {
return moment(date).isBefore(moment(to));
}
return moment(date).isAfter(moment(from)) && moment(date).isBefore(moment(to));
}
isSet(value) {
return value !== null && value !== ""
}
getFieldMatchInput(fieldName) {
const matchStateAttributeName = "match-" + fieldName
return (<input
css={css`
margin: 0em 1em;
`}
id={"report-match-" + fieldName}
maxLength="30"
size={30}
type="text"
value={this.state[matchStateAttributeName]}
onChange={this.updateReport(matchStateAttributeName).bind(this)}
/>)
}
getCollectionOptions(fieldName) {
if (fieldName === "cconly")
return (
["true","false"].map(( value ) => (
<option key={value}>{value}</option>
))
)
if (["author","contentsource", "signedby"].includes(fieldName))
return (<option hidden key={fieldName + "-option/hidden"}/>)
return this.data[fieldName].edges.map(({ node }) => (
<option
key={fieldName + "-option/" + node.fields.pagename}
>{node.frontmatter.title}</option>
))
}
getCollectionSelect(fieldName) {
return (<select
id={"report-select-" + fieldName}
value={this.state[fieldName]}
onChange={this.updateReport(fieldName).bind(this)}
css={css`
margin: 0em 1em;
`}
>
<option/>
<option>{NA}</option>
<option>{SET}</option>
{fieldName === "draftreason" && <option>{DRAFT}</option>}
{this.getCollectionOptions(fieldName)}
</select>
)
}
getFieldDateBetweenSelector(fieldName) {
return (<span css={datePickerCss}>
<DatePicker
id={"report-select-" + fieldName + "-from"}
selected={this.state[fieldName + "-from"]}
onChange={this.updateReportDate(fieldName + "-from").bind(this)}
dateFormat={"dd/MM/yyyy"}
/>
<DatePicker
id={"report-select-" + fieldName + "-to"}
selected={this.state[fieldName + "-to"]}
onChange={this.updateReportDate(fieldName + "-to").bind(this)}
dateFormat={"dd/MM/yyyy"}
/>
</span>)
}
render() {
const stateKeys = Object.keys(this.state)
.filter(key => this.state[key])
const fieldNamesSearched = Array.from(new Set(stateKeys.map(key =>
key.startsWith("match-") ? key.substring(6) :
key.startsWith("date-") ? "date" : key
)))
const items = this.data.allItems.edges
.filter(({ node }) => {
return this.fieldEquals("author", node) &&
this.fieldEquals("cconly", node) &&
this.fieldEquals("contentsource", node) &&
this.fieldEquals("departments", node) &&
this.fieldEquals("directory", node) &&
this.fieldEquals("draftreason", node) &&
this.fieldEquals("optimisedby", node) &&
this.fieldEquals("roles", node) &&
this.fieldEquals("signedby", node) &&
this.fieldMatches("author", node) &&
this.fieldMatches("signedby", node) &&
this.fieldMatches("title", node) &&
this.fieldMatches("tags", node) &&
this.fieldDateBetween("date", node)
}).map(({ node }) => (
<ReportItem
key={node.fields.collection + "/" + node.fields.pagename}
node={node}
fieldNames={fieldNamesSearched}/>
))
const filterAsString = stateKeys
.map(key => {
const value = this.state[key]
const valueAsString = key.includes("date") ?
moment(value).format("D MMM YY") : value
return (
<li key={"state/" + key}>{key} = {valueAsString}</li>
)
})
const count = items.length;
return (
<div>
<TextBlock>
<div css={css`
border: 1px solid #555;
padding: 1em;
`}>
<div>
Title{this.getFieldMatchInput("title")}
</div>
Call Centre Only{this.getCollectionSelect("cconly")}
Draft Reasons{this.getCollectionSelect("draftreason")}
<div>Related Team(s){this.getCollectionSelect("departments")}</div>
Content Source{this.getCollectionSelect("contentsource")}
Role(s){this.getCollectionSelect("roles")}
Directory{this.getCollectionSelect("directory")}
<div>
Author{this.getCollectionSelect("author")}
{this.getFieldMatchInput("author")}
</div>
Optimised By{this.getCollectionSelect("optimisedby")}
<div>
Signed By{this.getCollectionSelect("signedby")}
{this.getFieldMatchInput("signedby")}
</div>
<div>
Tags{this.getFieldMatchInput("tags")}
</div>
<div>Between Dates {this.getFieldDateBetweenSelector("date")}</div>
<div css={css`
text-align:right;
`}><button css={css`font-size:1.5em;`} onClick={this.reset}>Reset</button></div>
</div>
<PageTitle>
CMS content report : {count} item{(count !== 1) && <span>s</span>}
</PageTitle>
<div css={css`
text-align:right;
`}>{moment().format("DD MMM YYYY @ hh:mm")}</div>
<ul>{filterAsString}</ul>
{items}
</TextBlock>
</div>
)
}
}
export const query = graphql`
query {
allItems: allMarkdownRemark(
sort: { fields: frontmatter___title }
filter: { fields: { collection: { eq: "articles" } } }
) {
totalCount
edges {
node {
...BaseArticleFields
frontmatter {
author
cconly
contentsource
date
departments
draftreason
optimisedby
roles
signedby
tags
}
}
}
}
roles: allMarkdownRemark(
sort: { fields: frontmatter___title }
filter: { fields: { collection: { eq: "roles" } } }
) {
edges {
node {
fields {
pagename
}
frontmatter {
title
}
}
}
}
draftreason: allMarkdownRemark(
sort: { fields: frontmatter___title }
filter: { fields: { collection: { eq: "draftreason" } } }
) {
edges {
node {
fields {
pagename
}
frontmatter {
title
}
}
}
}
departments : allMarkdownRemark(
sort: { fields: frontmatter___title }
filter: { fields: { collection: { eq: "departments" } } }
) {
edges {
node {
fields {
pagename
}
frontmatter {
title
}
}
}
}
directory : allMarkdownRemark(
sort: { fields: frontmatter___title }
filter: { fields: { collection: { eq: "directories" } } }
) {
edges {
node {
fields {
pagename
}
frontmatter {
title
}
}
}
}
optimisedby : allMarkdownRemark(
sort: { fields: frontmatter___title }
filter: { fields: { collection: { eq: "optimisedby" } } }
) {
edges {
node {
fields {
pagename
}
frontmatter {
title
}
}
}
}
}
`
|
graphcore/poplibs | lib/popsparse/FullyConnectedPlan.cpp | <filename>lib/popsparse/FullyConnectedPlan.cpp
// Copyright (c) 2020 Graphcore Ltd. All rights reserved.
#include "FullyConnectedPlan.hpp"
#include "PerformanceEstimation.hpp"
#include "SparseMetaInfo.hpp"
#include "popsparse/FullyConnectedParams.hpp"
#include "poplibs_support/Algorithm.hpp"
#include "poplibs_support/Compiler.hpp"
#include "poplibs_support/TileHierarchy.hpp"
#include "poplibs_support/VectorUtils.hpp"
#include "poplibs_support/gcd.hpp"
#include "poplibs_support/logging.hpp"
#include "poputil/exceptions.hpp"
#include "popsolver/Model.hpp"
#include "FullyConnectedOptions.hpp"
#include "FullyConnectedUtils.hpp"
#include "PlanningCacheImpl.hpp"
#include "popsparse/FullyConnected.hpp"
#include <map>
#include <utility>
#include <vector>
using namespace poplar;
using namespace poplibs_support;
// TODO: share this across files
using MetaInfoType = unsigned short;
namespace popsparse {
using namespace dynamic;
namespace fullyconnected {
namespace {
using MetaInfoType = unsigned short;
static const auto deviceMetaInfoType =
poplar::equivalent_device_type<MetaInfoType>().value;
using CostBreakdown = std::vector<std::pair<std::string, Cost>>;
using CostVariables = Estimates<popsolver::Variable>;
using CostBreakdownVariables =
std::vector<std::pair<std::string, CostVariables>>;
static Cost highestCost(popsolver::DataType::max(), popsolver::DataType::max());
// TODO: This can easily be shared along with other stuff with the
// (dense) convolution library.
class PlanningObjective {
public:
enum Type { MINIMIZE_CYCLES, MINIMIZE_TILE_TEMP_MEMORY };
private:
Type type;
popsolver::DataType cyclesBound = popsolver::DataType::max();
popsolver::DataType tileTempMemoryBound = popsolver::DataType::max();
PlanningObjective(Type type) : type(type) {}
public:
PlanningObjective() {}
static PlanningObjective minimizeCycles() {
return PlanningObjective(MINIMIZE_CYCLES);
}
static PlanningObjective minimizeTileTempMemory() {
return PlanningObjective(MINIMIZE_TILE_TEMP_MEMORY);
}
PlanningObjective &setCyclesBound(popsolver::DataType bound) {
assert(type != MINIMIZE_CYCLES);
assert(*bound > 0);
cyclesBound = bound;
return *this;
}
PlanningObjective &setTileTempMemoryBound(popsolver::DataType bound) {
assert(type != MINIMIZE_TILE_TEMP_MEMORY);
assert(*bound > 0);
tileTempMemoryBound = bound;
return *this;
}
popsolver::DataType getCyclesBound() const { return cyclesBound; }
popsolver::DataType getTileTempMemoryBound() const {
return tileTempMemoryBound;
}
Type getType() const { return type; }
bool lowerCost(Cost a, Cost b) const {
bool aCyclesOutOfBounds = a.cycles >= cyclesBound;
bool bCyclesOutOfBounds = b.cycles >= cyclesBound;
bool aMemoryOutOfBounds = a.tempBytes >= tileTempMemoryBound;
bool bMemoryOutOfBounds = b.tempBytes >= tileTempMemoryBound;
switch (type) {
case MINIMIZE_CYCLES:
return std::tie(aCyclesOutOfBounds, aMemoryOutOfBounds, a.cycles,
a.tempBytes) < std::tie(bCyclesOutOfBounds,
bMemoryOutOfBounds, b.cycles,
b.tempBytes);
case MINIMIZE_TILE_TEMP_MEMORY:
return std::tie(aMemoryOutOfBounds, aCyclesOutOfBounds, a.tempBytes,
a.cycles) < std::tie(bMemoryOutOfBounds,
bCyclesOutOfBounds, b.tempBytes,
b.cycles);
}
POPLIB_UNREACHABLE();
}
};
// TODO: T41384, share common estimation code between poplibs libraries.
class ExchangeEstimator {
// Exchange bytes per cycle is given as a floating point value but the
// constaint solver only supports unsigned integer variables. To reduce
// quantization error in the calculation of the number of cycles we multiply
// both the divisor (exchange bytes per cycle) and the dividend (the number of
// bytes) by this scaling factor. Larger values of the scaling factor reduce
// the quantization error but reduce the maximum number of bytes that can
// be exchanged before running into the limits of the data type used to store
// it.
constexpr static unsigned exchangeBytesScalingFactor = 16u;
public:
ExchangeEstimator(popsolver::Model &m, const poplar::Target &target,
const std::vector<unsigned> &hierarchy,
const std::vector<double> &perLevelExchangeBytesPerCycle)
: m(m), target(target), levelsOfHierarchy(hierarchy.size()) {
perLevelScaledExchangeBytesPerCycle.reserve(hierarchy.size());
perLevelScaledExchangeBytesPerCycleVar.reserve(hierarchy.size());
for (unsigned level = 0; level != hierarchy.size(); ++level) {
const auto scaledBytesPerCycle = getScaledExchangeBytesPerCycle(
m, perLevelExchangeBytesPerCycle[level], exchangeBytesScalingFactor);
perLevelScaledExchangeBytesPerCycle.push_back(scaledBytesPerCycle);
perLevelScaledExchangeBytesPerCycleVar.push_back(
m.addConstant(scaledBytesPerCycle));
}
}
popsolver::Variable operator()(const popsolver::Variable mNumBytes,
const unsigned level,
const std::string &debugName = "") const {
return getCycles(mNumBytes, level, debugName);
}
popsolver::Variable
operator()(const popsolver::Variable mNumBytes,
const popsolver::Variable mConsecutiveTilesReceivingSameData,
const popsolver::Variable mTotalReceivingTiles,
const unsigned level, const std::string &debugName = "") const {
return getCycles(mNumBytes, mConsecutiveTilesReceivingSameData,
mTotalReceivingTiles, level, debugName);
}
unsigned operator()(unsigned numBytes, unsigned level) const {
assert(level < perLevelScaledExchangeBytesPerCycle.size());
const unsigned scalingFactor = exchangeBytesScalingFactor;
const auto scaledElementBytes = numBytes * scalingFactor;
return ceildiv(scaledElementBytes,
perLevelScaledExchangeBytesPerCycle[level]);
}
private:
popsolver::Variable
getCycles(const popsolver::Variable mNumBytes,
const popsolver::Variable mConsecutiveTilesReceivingSameData,
const popsolver::Variable mTotalReceivingTiles,
const unsigned level, const std::string &debugName = "") const {
assert(level < perLevelScaledExchangeBytesPerCycleVar.size());
auto mScaledBytesPerCycle = perLevelScaledExchangeBytesPerCycleVar[level];
assert(target.getTilesPerSharedExchangeBus() == 2);
if (level == levelsOfHierarchy - 1 && target.supportsExchangeBusSharing() &&
target.getTilesPerSharedExchangeBus() == 2) {
// In general the factor by which we can speed up the exchange by sharing
// the exchange bus is the greatest common divisor of the number of
// consecutive tiles receiving the same data and the number of tiles
// sharing an exchange bus. A separate special case where we can always
// share the exchange bus is when the number of consecutive tiles
// receiving the same data is equal the number of tiles receiving data
// (even if that number shared no common factor with the number of tiles
// sharing the exchange bus > 1).
//
// Because gcd is hard to do in popsolver and because we only ever have
// a maximum of 2 tiles sharing an exchange bus for current architecture
// we assume 2 tiles share an exchange bus at most and the logic below
// reflects this and would not work for more.
const auto tilesSharingBus = target.getTilesPerSharedExchangeBus();
const auto mTilesSharingBus = m.addConstant(tilesSharingBus);
const auto mZeroWhenFullBroadcast =
m.sub(mTotalReceivingTiles, mConsecutiveTilesReceivingSameData);
const auto mZeroWhenCanShareBusAnyway =
m.mod(mConsecutiveTilesReceivingSameData, mTilesSharingBus);
const auto mZeroWhenCanShareBus =
m.product({mZeroWhenFullBroadcast, mZeroWhenCanShareBusAnyway});
const auto mCanShareBus =
m.sub(m.one(), m.min({m.one(), mZeroWhenCanShareBus}));
const auto mShareFactor = m.sum({m.one(), mCanShareBus});
mScaledBytesPerCycle = m.product({mScaledBytesPerCycle, mShareFactor});
}
const auto mScalingFactor = m.addConstant(exchangeBytesScalingFactor);
const auto mScaledBytes = m.product({mNumBytes, mScalingFactor});
return m.ceildiv(mScaledBytes, mScaledBytesPerCycle, debugName);
}
popsolver::Variable getCycles(const popsolver::Variable mNumBytes,
const unsigned level,
const std::string &debugName = "") const {
assert(level < perLevelScaledExchangeBytesPerCycleVar.size());
const auto mScaledBytesPerCycle =
perLevelScaledExchangeBytesPerCycleVar[level];
const auto mScalingFactor = m.addConstant(exchangeBytesScalingFactor);
const auto mScaledBytes = m.product({mNumBytes, mScalingFactor});
return m.ceildiv(mScaledBytes, mScaledBytesPerCycle, debugName);
}
static unsigned getScaledExchangeBytesPerCycle(popsolver::Model &m,
double exchangeBytesPerCycle,
unsigned scaleFactor) {
auto scaledExchangeBytesPerCycle =
std::round(exchangeBytesPerCycle * scaleFactor);
// Ensure scaled bytes per cycle is at least one to avoid divide by zero
// errors.
scaledExchangeBytesPerCycle = std::max(1.0, scaledExchangeBytesPerCycle);
// Saturate to the half the maximum unsigned integer value (we avoid the
// maximum value to avoid range problems with the intermediate variables
// used to implement ceildiv).
scaledExchangeBytesPerCycle =
std::min(scaledExchangeBytesPerCycle,
static_cast<double>(std::numeric_limits<unsigned>::max() / 2));
return static_cast<unsigned>(scaledExchangeBytesPerCycle);
}
popsolver::Model &m;
const poplar::Target ⌖
const unsigned levelsOfHierarchy;
std::vector<unsigned> perLevelScaledExchangeBytesPerCycle;
std::vector<popsolver::Variable> perLevelScaledExchangeBytesPerCycleVar;
};
// Contains variables describing partitions. Only one form canonically describes
// the partitions, but it is useful to be able to store this information in
// redundant forms to avoid recomputing different forms/combinations of
// partitions all over the place.
struct PartitionVariables {
// Partitions in each dimension at each level.
std::vector<Vector<popsolver::Variable>> partition;
// Product of the partitions of each dimension in each level.
std::vector<popsolver::Variable> product;
// Number of tile-level partitions at and below each level.
// i.e. productByLevel[level] * productByLevel[level + 1]
// .. * productByLevel[maxLevels]
std::vector<popsolver::Variable> tile;
// Cumulative product of partitions at each level and all levels
// higher than it.
std::vector<Vector<popsolver::Variable>> cumulative;
PartitionVariables(
popsolver::Model &m,
const std::vector<Vector<popsolver::Variable>> &mPartitions)
: partition(mPartitions), product(mPartitions.size()),
tile(mPartitions.size() + 1), cumulative(mPartitions.size() + 1) {
// Calculate products of partitions
for (unsigned level = 0; level < partition.size(); ++level) {
product[level] = m.product(partition[level].asStdVector());
}
// Calculate no. of tile-level partitions at each level
tile[mPartitions.size()] = m.one();
for (int level = partition.size() - 1; level >= 0; --level) {
tile[level] = m.product({product[level], tile[level + 1]});
}
// Calculate cumulative partitions
cumulative[0] =
Vector<popsolver::Variable>::generate([&] { return m.one(); });
for (unsigned level = 1; level < partition.size() + 1; ++level) {
cumulative[level] = partition[level - 1].binaryOp(
cumulative[level - 1],
[&](const auto &partition, const auto &cumulativePrev) {
return m.product({partition, cumulativePrev});
});
}
}
};
} // end anonymous namespace
static popsolver::Variable getArePartitionsOnConsecutivePNs(
popsolver::Model &m, const PartitionVariables &p,
const PartitionToPNMapping &mapping, unsigned level, const unsigned dim) {
const auto &order = mapping.getLinearisationOrder().asStdVector<unsigned>();
const auto &partition = p.partition[level].asStdVector();
// Inverse order contains the ordering of dimensions as they
// are linearised.
std::vector<unsigned> inverseOrder(order.size());
std::iota(inverseOrder.begin(), inverseOrder.end(), 0);
for (std::size_t i = 0; i < order.size(); ++i) {
inverseOrder[order[i]] = i;
}
// Partitions are on consecutive tiles if the product of all
// partitions of inner dimensions in the ordering is 1.
std::vector<popsolver::Variable> innerPartitions = {m.one()};
for (std::size_t i = order[dim] + 1; i < inverseOrder.size(); ++i) {
innerPartitions.push_back(partition[inverseOrder[i]]);
}
const auto mInnerPartitionsProduct = m.product(innerPartitions);
const auto mInnerPartitionsProductM1 =
m.sub(mInnerPartitionsProduct, m.one());
// Re-ify (mInnerPartitionsProduct == 1) to a boolean represented by 0/1
return m.sub(m.one(), m.min({m.one(), mInnerPartitionsProductM1}));
}
// This cost covers:
// * Pre-distribution exchange i.e. exchange of dense input to the fc layer
// potentially broadcast across partitions of X.
// * Distribution exchange i.e. exchange of buckets required to complete
// computation assuming a perfectly uniform distribution of sparsity.
// In practice this means the exchange cost to broadcast each bucket on
// each PN within a SORG to all PNs within a SORG.
static std::tuple<CostVariables, popsolver::Variable, popsolver::Variable>
addDistributionExchangeCostSparseDense(
popsolver::Model &m, const Target &target, const Type &inputType,
const Type &deviceMetaInfoType, const Options &options,
const std::vector<unsigned> &hierarchy,
const ExchangeEstimator &exchangeEstimator,
const PartitionToPNMapping &mapping,
const std::vector<Vector<popsolver::Variable>> &mGroups,
const Vector<popsolver::Variable> &mGrouping,
const popsolver::Variable &mRBytesPerBucket, const PartitionVariables &p) {
const auto mBytesPerInput = m.addConstant(target.getTypeSize(inputType));
std::vector<popsolver::Variable> mRBytesPerTile(hierarchy.size() + 1),
mSBytesPerTile(hierarchy.size() + 1);
for (unsigned level = 0; level < hierarchy.size() + 1; ++level) {
// Bytes per-tile for the dense input at each level are given by the
// product of number of grains of each dimension of the input, spread
// over the tiles that will eventually compute on those bytes.
mSBytesPerTile[level] =
m.product({m.ceildiv(m.product({mGroups[level].groups, mGroups[level].y,
mGroups[level].z}),
p.tile[level]),
mGrouping.groups, mGrouping.y, mGrouping.z, mBytesPerInput});
// In the initial distribution we broadcast the buckets of the sparse
// operand across partitions processing the same X and Y partitions.
// Buckets are constrained to be of equal size on all tiles so this
// product will not introduce any error in the calculation moving up
// levels of the hierarchy.
mRBytesPerTile[level] =
m.product({p.cumulative[level].z, mRBytesPerBucket});
}
// Estimate exchange for the initial distribution. We exchange input
// operands s and r to the tiles that will process them during the first
// compute step.
//
// Exchange cycles are calculated by finding the critical path for send
// /receive of data. In this case the exchange will multi-cast data from
// each tile within a particular set of partitions to all tiles in that
// particular partition. The critical path then is the sending of each
// chunk of data on each tile in series due to not being able to receive
// on all tiles in parallel.
//
// Exchange temporary memory is more complex as this is dependent on the
// need to gather the input operands into contiguous memory as part of the
// exchange or not.
//
// There are 2 special cases:
//
// The first occurs when there is no broadcast
// of data and we assume that inputs are allocated such that they are
// already resident on each tile. There is no exchange and no temporary
// memory requirement for these inputs in this case.
//
// TODO: The second case occurs when the data is only being
// multi-cast to one other tile and/ we don't need to gather the data
// into one contiguous region. In this case we can simultaneously
// send/receive from both tiles in each set. This doesn't affect
// single-IPU planning.
std::vector<popsolver::Variable> mCyclesPerLevel(hierarchy.size()),
mTempBytesPerLevel(hierarchy.size());
popsolver::Variable mSTempBytesAfterExchange = m.zero(),
mRTempBytesAfterExchange = m.zero();
for (unsigned level = 0; level < hierarchy.size(); ++level) {
// If this is the last level then we need to gather the operand
// S as this needs to be contiguous on-tile. TODO: We don't
// need to gather at other levels so current estimation of temp
// memory is exaggerated.
const auto mSBytesAreExchanged = m.min(
{m.one(), m.sub(mSBytesPerTile[level + 1], mSBytesPerTile[level])});
const auto mSBytesToSendReceivePerTile =
m.product({mSBytesAreExchanged, mSBytesPerTile[level + 1]});
const auto mSTempBytes = mSBytesToSendReceivePerTile;
const auto mSBytesToSendReceive =
m.product({mSBytesToSendReceivePerTile, p.tile[level + 1]});
const auto mRBytesAreExchanged = m.min(
{m.one(), m.sub(mRBytesPerTile[level + 1], mRBytesPerTile[level])});
const auto mRBytesToSendReceive = m.product(
{mRBytesAreExchanged, p.tile[level + 1], mRBytesPerTile[level + 1]});
// Because we never need to gather R temporary memory at any stage is
// just the difference between the bytes for original locations of
// buckets at level 0 and the current level.
const auto mRTempBytes =
m.sub(mRBytesPerTile[level + 1], mRBytesPerTile[0]);
// Using our knowledge of how the source and destination of the exchange
// will be laid out to allow the exchange estimator to account for the
// possibility of exchange bus sharing between tiles during the broadcast
// of information.
//
// We choose a tile to process this partition based on the flattened
// index into a 3D array with shape {y,z,x}. This means that 2
// partitions of x will be on neighbouring tiles and input S could be
// broadcast. Alternatively if there is only 1 partition of x then
// 2 partitions of z will be on neighbouring tiles.
const auto mXPartitionsOnConsecutiveTiles =
getArePartitionsOnConsecutivePNs(m, p, mapping, level, 1 /* X */);
const auto mSConsecutiveTilesReceivingSameData = m.max(
{m.one(),
m.product({mXPartitionsOnConsecutiveTiles, p.partition[level].x})});
const auto mZPartitionsOnConsecutiveTiles =
getArePartitionsOnConsecutivePNs(m, p, mapping, level, 3 /* Z */);
const auto mRConsecutiveTilesReceivingSameData = m.max(
{m.one(),
m.product({mZPartitionsOnConsecutiveTiles, p.partition[level].z})});
const auto mSExchangeCycles = exchangeEstimator(
mSBytesToSendReceive, mSConsecutiveTilesReceivingSameData,
p.product[level], level);
const auto mRExchangeCycles = exchangeEstimator(
mRBytesToSendReceive, mRConsecutiveTilesReceivingSameData,
p.product[level], level);
mCyclesPerLevel[level] = m.sum({mSExchangeCycles, mRExchangeCycles});
mTempBytesPerLevel[level] =
m.sum({mSTempBytesAfterExchange, mSTempBytes, mRTempBytes});
mSTempBytesAfterExchange = mSTempBytes;
mRTempBytesAfterExchange = mRTempBytes;
}
CostVariables mCost(m.sum(mCyclesPerLevel), m.max(mTempBytesPerLevel));
return std::make_tuple(mCost, mSTempBytesAfterExchange,
mRTempBytesAfterExchange);
}
/** Account for the cost of broadcasting/rearranging
* inputs/output gradients
*/
static CostVariables addPreDistributionExchangeCostDenseDense(
popsolver::Model &m, const Options &options,
const std::vector<unsigned> &hierarchy,
const ExchangeEstimator &exchangeEstimator,
const PartitionToPNMapping &mapping,
const std::vector<popsolver::Variable> &mQGradBytesPerTile,
const std::vector<popsolver::Variable> &mSBytesPerTile,
popsolver::Variable &mQGradTempBytesAfterExchange,
popsolver::Variable &mSTempBytesAfterExchange,
const PartitionVariables &p) {
// TODO: Add cost for exchanging meta-info when mapping order
// does not match forward pass
std::vector<popsolver::Variable> mCyclesPerLevel(hierarchy.size()),
mTempBytesPerLevel(hierarchy.size());
// Assuming the temporary memory for these operands first appears here.
mQGradTempBytesAfterExchange = m.zero(), mSTempBytesAfterExchange = m.zero();
for (unsigned level = 0; level < hierarchy.size(); ++level) {
const auto mQGradBytesAreExchanged =
m.min({m.one(), m.sub(mQGradBytesPerTile[level + 1],
mQGradBytesPerTile[level])});
const auto mQGradBytesToSendReceivePerTile =
m.product({mQGradBytesAreExchanged, mQGradBytesPerTile[level + 1]});
const auto mQGradTempBytes = mQGradBytesToSendReceivePerTile;
const auto mQGradBytesToSendReceive =
m.product({mQGradBytesToSendReceivePerTile, p.tile[level + 1]});
const auto mSBytesAreExchanged = m.min(
{m.one(), m.sub(mSBytesPerTile[level + 1], mSBytesPerTile[level])});
const auto mSBytesToSendReceivePerTile =
m.product({mSBytesAreExchanged, mSBytesPerTile[level + 1]});
const auto mSTempBytes = mSBytesToSendReceivePerTile;
const auto mSBytesToSendReceive =
m.product({mSBytesToSendReceivePerTile, p.tile[level + 1]});
const auto mXPartitionsOnConsecutiveTiles =
getArePartitionsOnConsecutivePNs(m, p, mapping, level, 1 /* X */);
const auto mYPartitionsOnConsecutiveTiles =
getArePartitionsOnConsecutivePNs(m, p, mapping, level, 2 /* Y */);
const auto mQGradConsecutiveTilesReceivingSameData = m.max(
{m.one(),
m.product({mYPartitionsOnConsecutiveTiles, p.partition[level].y})});
const auto mSConsecutiveTilesReceivingSameData = m.max(
{m.one(),
m.product({mXPartitionsOnConsecutiveTiles, p.partition[level].x})});
// There should be as much data as the number of z partitions as there
// is no reduction stage following this.
// This assumes we have to move operands on-tile - we only cycle
// operands between tiles z partitions - 1 times.
const auto mQGradExchangeCycles = exchangeEstimator(
mQGradBytesToSendReceive, mQGradConsecutiveTilesReceivingSameData,
p.product[level], level);
const auto mSExchangeCycles = exchangeEstimator(
mSBytesToSendReceive, mSConsecutiveTilesReceivingSameData,
p.product[level], level);
mCyclesPerLevel[level] = m.sum({mQGradExchangeCycles, mSExchangeCycles});
mTempBytesPerLevel[level] =
m.sum({mQGradTempBytesAfterExchange, mSTempBytesAfterExchange,
mQGradTempBytes, mSTempBytes});
mQGradTempBytesAfterExchange = mQGradTempBytes;
mSTempBytesAfterExchange = mSTempBytes;
}
return CostVariables(m.sum(mCyclesPerLevel), m.max(mTempBytesPerLevel));
}
static std::tuple<popsolver::Variable, popsolver::Variable>
addGradWExchangeAndComputeTempBytesCost(
popsolver::Model &m, const Options &options, const Type &inputType,
const bool exchangeBuckets,
const popsolver::Variable &mRGradPartialBytesPerTile,
const popsolver::Variable &mRMetaInfoBytesPerTile,
const popsolver::Variable &mQGradBytesPerTile,
const popsolver::Variable &mSBytesPerTile, const PartitionVariables &p) {
popsolver::Variable mTempBytes;
const auto mNeedsCast =
m.addConstant(inputType != options.partialsType ? 1u : 0u);
const auto mRemainingPartialBytes =
m.product({mNeedsCast, mRGradPartialBytesPerTile});
if (exchangeBuckets) {
// If we exchange buckets, the peak temp memory during exchange and
// compute phases is 2x the size of the partials & meta-info and
// whatever temporary storage is required for the dense operands
// s/q-grad.
const auto mRGradBytesPerTile =
m.sum({mRGradPartialBytesPerTile, mRMetaInfoBytesPerTile});
mTempBytes = m.sum({mQGradBytesPerTile, mSBytesPerTile,
m.product({mRGradBytesPerTile, m.addConstant(2u)})});
} else {
// When exchanging inputs, the temporary memory is given by the memory
// needed for partials (if needed) and 2x the size of the buffers for
// dense operands s/q-grad.
const auto mInputBytes = m.sum({mQGradBytesPerTile, mSBytesPerTile});
mTempBytes = m.sum(
{mRemainingPartialBytes, m.product({mInputBytes, m.addConstant(2u)})});
}
return std::make_tuple(mTempBytes, mRemainingPartialBytes);
}
/** Account for the cost of exchange in the distribution phase.
* The cost of exchange for this phase is any exchange required
* assuming a perfectly uniform sparsity pattern. This boils down
* to the cost of exchange required to complete one full cycle
* around the Z dimension.
*/
static popsolver::Variable addDistributionExchangeCycleCostDenseDense(
popsolver::Model &m, const Options &options,
const std::vector<unsigned> &hierarchy,
const ExchangeEstimator &exchangeEstimator,
const PartitionToPNMapping &mapping, const bool exchangeBuckets,
const popsolver::Variable &mRGradBytesPerTile,
const popsolver::Variable &mQGradBytesPerTile,
const popsolver::Variable &mSBytesPerTile, const PartitionVariables &p) {
std::vector<popsolver::Variable> mCyclesPerLevel(hierarchy.size(), m.zero());
for (unsigned level = 0; level < hierarchy.size(); ++level) {
const auto mZPartitionsM1 = m.sub(p.partition[level].z, m.one());
const auto mNeedsExchange = m.min({mZPartitionsM1, m.one()});
if (exchangeBuckets) {
const auto mBytesToSendReceivePerTile =
mRGradBytesPerTile; // Non-zero value partials and meta-info.
const auto mBytesToSendReceive = m.product(
{mNeedsExchange, mBytesToSendReceivePerTile, p.tile[level + 1]});
// We don't do any broadcasting when exchanging buckets hence no
// calculation of consecutive tiles like below.
const auto mExchangeCycles =
m.product({exchangeEstimator(mBytesToSendReceive, level),
p.partition[level].z});
mCyclesPerLevel[level] = mExchangeCycles;
} else {
const auto mQGradBytesToSendReceivePerTile =
m.product({mNeedsExchange, mQGradBytesPerTile, p.tile[level + 1]});
const auto mSBytesToSendReceivePerTile =
m.product({mNeedsExchange, mSBytesPerTile, p.tile[level + 1]});
const auto mQGradBytesToSendReceive =
m.product({mQGradBytesToSendReceivePerTile, p.tile[level + 1]});
const auto mSBytesToSendReceive =
m.product({mSBytesToSendReceivePerTile, p.tile[level + 1]});
const auto mZPartitionsOnConsecutiveTiles =
getArePartitionsOnConsecutivePNs(m, p, mapping, level, 3 /* Z */);
const auto mConsecutiveTilesReceivingSameData = m.max(
{m.one(),
m.product({mZPartitionsOnConsecutiveTiles, p.partition[level].z})});
const auto mQGradExchangeCycles =
m.product({exchangeEstimator(mQGradBytesToSendReceive,
mConsecutiveTilesReceivingSameData,
p.product[level], level),
p.partition[level].z});
const auto mSExchangeCycles =
m.product({exchangeEstimator(mSBytesToSendReceive,
mConsecutiveTilesReceivingSameData,
p.product[level], level),
p.partition[level].z});
mCyclesPerLevel[level] = m.sum({mQGradExchangeCycles, mSExchangeCycles});
}
}
return m.sum(mCyclesPerLevel);
}
static std::tuple<unsigned, unsigned> getNumGroupsGivenUniformSparsityPattern(
const double nzRatio, const unsigned xGroups, const unsigned yGroups) {
const double pGroupIsZero = 1.0 - nzRatio;
const double pXGroupHasAllZeroGroups = std::pow(pGroupIsZero, yGroups);
const double pXGroupHasNonZeroGroup = 1.0 - pXGroupHasAllZeroGroups;
const unsigned totalNonZeroGroups = std::ceil(xGroups * yGroups * nzRatio);
const unsigned xNonZeroGroups = std::ceil(xGroups * pXGroupHasNonZeroGroup);
const unsigned yNonZeroGroups = ceildiv(totalNonZeroGroups, xNonZeroGroups);
return std::make_tuple(xNonZeroGroups, yNonZeroGroups);
}
static inline unsigned getNumConvUnits(const Target &target,
bool floatActivations,
bool floatPartial) {
if (floatActivations) {
return target.getFp32InFp32OutConvUnitsPerTile();
} else {
return floatPartial ? target.getFp16InFp32OutConvUnitsPerTile()
: target.getFp16InFp16OutConvUnitsPerTile();
}
}
static std::tuple<CostVariables, popsolver::Variable>
addDistributionComputeCostSparseDense(
popsolver::Model &m, const Target &target, const Type &inputType,
const double &nzRatio, const Options &options, const OnTileMethod &method,
const Vector<popsolver::Variable> &mGroups,
const Vector<popsolver::Variable> &mGrouping,
const Vector<popsolver::Variable> &mCumulativePartitions,
const popsolver::Variable &mSTempBytes,
const popsolver::Variable &mRTempBytes) {
// TODO: Padding estimates etc...
const auto mPartialsPerTile =
m.product({mGroups.groups, mGroups.x, mGroups.z, mGrouping.groups,
mGrouping.x, mGrouping.z});
const auto numWorkers = target.getNumWorkerContexts();
const auto partialsType = options.partialsType;
const unsigned numConvUnits =
getNumConvUnits(target, inputType == FLOAT, partialsType == FLOAT);
const auto mBytesPerPartial = m.addConstant(target.getTypeSize(partialsType));
const auto mNumBucketsPerTile = mCumulativePartitions.z;
const auto mCycles = m.call<unsigned>(
{mPartialsPerTile, mNumBucketsPerTile, mGroups.x, mGroups.y, mGroups.z,
mGrouping.x, mGrouping.y, mGrouping.z},
[=](const std::vector<unsigned> &values) -> popsolver::DataType {
const auto partialsPerTile = values[0];
const auto numBuckets = values[1];
const auto xGroups = values[2];
const auto yGroups = values[3];
const auto zGroups = values[4];
const auto xGrouping = values[5];
const auto yGrouping = values[6];
const auto zGrouping = values[7];
const auto partialsPerWorker = ceildiv(partialsPerTile, numWorkers);
std::uint64_t cycles = zeroPartialsCycles(partialsPerWorker, numWorkers,
options.partialsType == FLOAT,
xGrouping * yGrouping > 0);
unsigned xNonZeroGroups, yNonZeroGroups;
std::tie(xNonZeroGroups, yNonZeroGroups) =
getNumGroupsGivenUniformSparsityPattern(nzRatio, xGroups, yGroups);
std::vector<Tile> workerTiles;
switch (method) {
case OnTileMethod::Forward:
case OnTileMethod::GradA:
assert(xGrouping * yGrouping == 1);
workerTiles =
splitTileBetweenWorkers(xNonZeroGroups, zGroups, numWorkers);
break;
case OnTileMethod::Transpose:
assert(xGrouping * yGrouping == 1);
// Transpose vertex does its work split at runtime
workerTiles = splitTileBetweenWorkers(1, 1, numWorkers);
case OnTileMethod::ForwardAMPBlock:
case OnTileMethod::TransposeAMPBlock:
// We may only split Z amongst workers for forward/grad-a AMP
// codelets
workerTiles = splitTileBetweenWorkers(1, zGroups, numWorkers);
break;
default:
throw poputil::poplibs_error("Unhandled OnTileMethod");
}
std::uint64_t maxMulCycles = 0;
for (const auto &workerTile : workerTiles) {
const unsigned workerXGroups = workerTile.getRows().size();
const unsigned workerZGroups = workerTile.getColumns().size();
const unsigned workerZElems = workerZGroups * zGrouping;
const unsigned numY = yNonZeroGroups * yGrouping;
// Because we are assuming best case with perfectly uniform
// distribution of sparsity over the dense sparse of R, there should
// be a perfect distribution of sub-groups over buckets such that each
// bucket only contains elements of 1 sub-group.
constexpr auto numSubGroupsPerBucket = 1u;
std::uint64_t mulCycles = 0;
switch (method) {
case OnTileMethod::Forward:
mulCycles = sparseDenseElementwiseMultiply(
numBuckets, numBuckets, numSubGroupsPerBucket, workerXGroups,
workerZElems,
std::vector<unsigned>({static_cast<unsigned>(numY)}),
inputType == FLOAT, partialsType == FLOAT, numWorkers);
break;
case OnTileMethod::GradA:
mulCycles = sparseDenseGradAElementwiseMultiply(
numBuckets, numBuckets, numSubGroupsPerBucket, workerXGroups,
workerZElems,
std::vector<unsigned>({static_cast<unsigned>(numY)}),
inputType == FLOAT, partialsType == FLOAT, numWorkers);
break;
case OnTileMethod::Transpose:
// The transpose method divides the work along the X-dimension.
mulCycles = sparseDenseTransposeElementwiseMultiply(
numBuckets, numBuckets, numSubGroupsPerBucket, numY,
zGroups * zGrouping, std::vector<unsigned>({xGroups}),
inputType == FLOAT, partialsType == FLOAT, numWorkers);
break;
case OnTileMethod::ForwardAMPBlock: {
constexpr bool retainX = true;
mulCycles = sparseDenseBlockMultiply(
numBuckets, numBuckets, numSubGroupsPerBucket, xNonZeroGroups,
workerZElems, xGrouping, yGrouping, {yNonZeroGroups},
inputType == FLOAT, partialsType == FLOAT, numWorkers,
numConvUnits, retainX);
break;
}
case OnTileMethod::TransposeAMPBlock: {
constexpr bool retainX = false;
mulCycles = sparseDenseBlockMultiply(
numBuckets, numBuckets, numSubGroupsPerBucket, yNonZeroGroups,
workerZElems, yGrouping, xGrouping, {xNonZeroGroups},
inputType == FLOAT, partialsType == FLOAT, numWorkers,
numConvUnits, retainX);
break;
}
default:
throw poputil::poplibs_error("Unhandled method when planning");
}
maxMulCycles = std::max(maxMulCycles, mulCycles);
}
cycles += maxMulCycles;
return popsolver::DataType{cycles};
});
// The temporary memory during this operation is the temporary memory for
// both the inputs, and the memory for partial outputs. Memory for partial
// outputs is only temporary if there is a cast or reduction to be done
// later on.
const auto mNeedsCast = m.addConstant(inputType != partialsType ? 1u : 0u);
const auto mNeedsReduction = m.sub(mCumulativePartitions.z, m.one());
const auto mNeedsCastOrReduction =
m.min({m.one(), m.sum({mNeedsCast, mNeedsReduction})});
const auto mPartialsTempBytes =
m.product({mNeedsCastOrReduction, mPartialsPerTile, mBytesPerPartial});
const auto mTempBytes = m.sum({mSTempBytes, mRTempBytes, mPartialsTempBytes});
return std::make_tuple(CostVariables(mCycles, mTempBytes),
mPartialsTempBytes);
}
static std::pair<popsolver::Variable, popsolver::Variable>
rearrangeDenseCost(popsolver::Model &m, const Target &target,
const Type &dataType, const popsolver::Variable &mXOrYGroups,
const popsolver::Variable mXOrYGrouping,
const popsolver::Variable &mZGroups,
const popsolver::Variable &mZGrouping) {
const auto numWorkers = target.getNumWorkerContexts();
// TODO: add padding cost once we support padding.
const auto calculateRearrangeCycles =
[=](const std::vector<unsigned> &values) {
const auto numXOrYGroups = values[0];
const auto blockSizeXY = values[1];
const auto numZ = values[2];
const auto cycles = getBlockTransposeGradWCycles(
dataType == FLOAT, blockSizeXY, numXOrYGroups, numZ, numWorkers);
return popsolver::DataType{cycles};
};
const auto mCycles = m.call<unsigned>(
{mXOrYGroups, mXOrYGrouping, m.product({mZGroups, mZGrouping})},
calculateRearrangeCycles);
const auto mBytesPerInput = m.addConstant(target.getTypeSize(dataType));
const auto mTransposedBytes = m.product(
{mBytesPerInput, mXOrYGroups, mXOrYGrouping, mZGroups, mZGrouping});
return std::make_pair(mCycles, mTransposedBytes);
}
/** Account for the cost of compute in the distribution phase.
* The cost of compute for this phase is any compute required
* assuming a perfectly uniform sparsity pattern. This boils
* down to the cost of compute in one full partition of X/Y.
*/
static popsolver::Variable addDistributionComputeCycleCostDenseDense(
popsolver::Model &m, const Target &target, const Type &inputType,
const double &nzRatio, const Options &options, const OnTileMethod &method,
const Vector<popsolver::Variable> &mGroups,
const Vector<popsolver::Variable> &mGrouping,
const Vector<popsolver::Variable> &mCumulativePartitions,
const popsolver::Variable &mSparseGroups,
const popsolver::Variable &mElemsPerSparseGroup) {
// TODO: Handle groups for vertex cycle estimates properly
const auto mPartialsPerTile =
m.product({mSparseGroups, mElemsPerSparseGroup});
const auto &partialsType = options.partialsType;
const unsigned numConvUnits =
getNumConvUnits(target, inputType == FLOAT, partialsType == FLOAT);
const auto numWorkers = target.getNumWorkerContexts();
auto mCycles = m.call<unsigned>(
{mPartialsPerTile, mGroups.x, mGroups.y, mGroups.z, mGrouping.x,
mGrouping.y, mGrouping.z, mCumulativePartitions.z},
[=](const std::vector<unsigned> &values) -> popsolver::DataType {
const auto partialsPerTile = values[0];
const auto xGroups = values[1];
const auto yGroups = values[2];
const auto zGroups = values[3];
const auto xGrouping = values[4];
const auto yGrouping = values[5];
const auto zGrouping = values[6];
const auto numZPartitions = values[7];
const auto partialsPerWorker = ceildiv(partialsPerTile, numWorkers);
std::uint64_t cycles = zeroPartialsCycles(partialsPerWorker, numWorkers,
partialsType == FLOAT,
xGrouping * yGrouping > 1);
unsigned xNonZeroGroups, yNonZeroGroups;
// Divide the number of xGroups by Z partition as we always split
// rows first.
const auto xGroupsPerZSplit = ceildiv(xGroups, numZPartitions);
std::tie(xNonZeroGroups, yNonZeroGroups) =
getNumGroupsGivenUniformSparsityPattern(nzRatio, xGroupsPerZSplit,
yGroups);
unsigned nonZeroGroups = xNonZeroGroups * yNonZeroGroups;
const auto groupsPerWorker = ceildiv(nonZeroGroups, numWorkers);
const auto numUsedWorkers =
method == OnTileMethod::GradWAMPBlock
? 1
: ceildiv(nonZeroGroups, groupsPerWorker);
const auto numZ = zGroups * zGrouping;
std::uint64_t maxMulCycles = 0;
for (unsigned worker = 0; worker < numUsedWorkers; ++worker) {
std::vector<unsigned> numYThisWorker;
unsigned numXGroupsThisWorker;
if (method == OnTileMethod::GradWAMPBlock) {
numYThisWorker.push_back(yNonZeroGroups);
numXGroupsThisWorker = xNonZeroGroups;
} else {
auto startGroup = worker * groupsPerWorker;
auto endGroup =
std::min(nonZeroGroups, (worker + 1) * groupsPerWorker);
numXGroupsThisWorker = ceildiv(endGroup, yNonZeroGroups) -
floordiv(startGroup, yNonZeroGroups);
numYThisWorker.reserve(numXGroupsThisWorker);
while (startGroup != endGroup) {
const auto numYGroupsForXGroup =
std::min(endGroup, startGroup + yNonZeroGroups) - startGroup;
numYThisWorker.emplace_back(numYGroupsForXGroup);
startGroup += numYGroupsForXGroup;
}
}
constexpr auto numBuckets = 1u;
constexpr auto numSubGroupsPerBucket = 1u;
const auto numXThisWorker = numXGroupsThisWorker * xGrouping;
std::uint64_t mulCycles = 0;
switch (method) {
case OnTileMethod::GradW:
mulCycles = sparseDenseGradWElementwiseMultiply(
numBuckets, numBuckets, numSubGroupsPerBucket, numXThisWorker,
numZ, numYThisWorker, inputType == FLOAT, partialsType == FLOAT,
numWorkers);
break;
case OnTileMethod::GradWBlock:
mulCycles = sparseDenseBlockMultiplyGradW(
numBuckets, numBuckets, numSubGroupsPerBucket,
numXGroupsThisWorker, numZ, xGrouping, yGrouping,
numYThisWorker, inputType == FLOAT, partialsType == FLOAT,
numWorkers);
break;
case OnTileMethod::GradWAMPBlock:
// Each block is processed by all workers
mulCycles = sparseDenseBlockMultiplyGradWAmp(
numBuckets, numBuckets, numSubGroupsPerBucket,
numXGroupsThisWorker, numZ, xGrouping, yGrouping,
numYThisWorker, inputType == FLOAT, partialsType == FLOAT,
numWorkers, numConvUnits);
break;
default:
throw poputil::poplibs_error("Unhandled method when planning");
}
// Average over different values of Y. TODO: The Y provided aren't
// statistically significant, they just assume a rectangle and
// divide between workers so there is some accounting for overheads.
mulCycles = ceildiv(mulCycles, numYThisWorker.size());
maxMulCycles = std::max(maxMulCycles, mulCycles);
}
cycles += maxMulCycles * numZPartitions;
return popsolver::DataType{cycles};
});
return mCycles;
}
static CostVariables addPropagationCost(
popsolver::Model &m, const Target &target, const Type &inputType,
const std::vector<unsigned> &hierarchy, const Options &options,
const ExchangeEstimator &exchangeEstimator,
const popsolver::Variable &mBytesPerBuffer, const PartitionVariables &p) {
// Estimate temporary memory cost of a single iteration of the dynamically
// executed exchange based on this plan.
//
// During the propagating exchange, we will need space for 2 buckets which
// we will flip flop between to allow simulatenous forwarding and receiving
// of buckets to/from other tiles.
return CostVariables(m.zero(),
m.product({mBytesPerBuffer, m.addConstant(2u)}));
}
static std::tuple<CostVariables, CostVariables> addReductionCost(
popsolver::Model &m, const Target &target, const Type &inputType,
const std::vector<unsigned> &hierarchy, const Options &options,
const ExchangeEstimator &exchangeEstimator,
const popsolver::Variable &mPartialsPerTileToReduce,
const std::vector<popsolver::Variable> &mReductionDepth,
const std::vector<popsolver::Variable> &mReductionDepthCumulative,
const std::vector<popsolver::Variable> &mTileLevelPartitions,
popsolver::Variable mQTempBytesAfterCompute) {
// This is not dependent upon the distribution of the sparsity
// pattern as we are reducing the dense output. This occurs after all other
// steps of exchange and compute are complete.
//
// The cost of reduction is determined by the factor by which we reduce.
//
// There is no on-tile reduction naturally as partials for the same result
// are partitioned between tiles.
const auto mBytesPerPartial =
m.addConstant(target.getTypeSize(options.partialsType));
std::vector<popsolver::Variable> mPartialsPerTile(hierarchy.size() + 1);
std::vector<popsolver::Variable> mExchangeCyclesPerLevel(hierarchy.size()),
mExchangeTempBytesPerLevel(hierarchy.size()),
mComputeCyclesPerLevel(hierarchy.size()),
mComputeTempBytesPerLevel(hierarchy.size());
const auto numWorkers = target.getNumWorkerContexts();
const auto dataPathWidth = target.getDataPathWidth();
for (int level = hierarchy.size(); level >= 0; --level) {
if (static_cast<unsigned>(level) == hierarchy.size()) {
mPartialsPerTile[level] = mPartialsPerTileToReduce;
} else {
// Now estimate compute portion of reduction exchange cost.
const auto reducePartialsType = options.partialsType;
const auto reduceOutputType =
(level == 0) ? inputType : options.partialsType;
bool floatPartials = reducePartialsType == FLOAT;
bool floatOutput = reduceOutputType == FLOAT;
const auto partialsVectorWidth =
target.getVectorWidth(reducePartialsType);
const auto outputVectorWidth = target.getVectorWidth(reduceOutputType);
const auto mBytesPerOutput =
m.addConstant(target.getTypeSize(reduceOutputType));
mPartialsPerTile[level] =
m.ceildiv(mPartialsPerTile[level + 1], mReductionDepth[level]);
const auto mNeedsReduction = m.min(
{m.one(), m.sub(mReductionDepthCumulative[level + 1], m.one())});
// The reduction's exchange cost will be given by each tile needing to
// receive (reductionDepth - 1)/reductionDepth of the partials, and
// send 1/reductionDepth of the partials. > 2 reductionFactor means we
// cannot overlap send/receive of partials so cost is based on full
// partials size. This is an all-to-all exchange.
const auto mPartialsToExchangePerTile = mPartialsPerTile[level + 1];
const auto mBytesToExchangePerTile = m.product(
{mPartialsToExchangePerTile, mBytesPerPartial, mNeedsReduction});
const auto mBytesToExchange =
m.product({mBytesToExchangePerTile, mTileLevelPartitions[level + 1]});
mExchangeCyclesPerLevel[level] =
exchangeEstimator(mBytesToExchange, level);
mExchangeTempBytesPerLevel[level] =
m.sum({mQTempBytesAfterCompute, mBytesToExchangePerTile});
mComputeCyclesPerLevel[level] = m.call<unsigned>(
{mPartialsPerTile[level], mReductionDepth[level]},
[=](const std::vector<unsigned> &values) -> popsolver::DataType {
const auto partialsPerTile = values[0];
const auto reductionDepth = values[1];
if (reductionDepth == 0) {
return popsolver::DataType{0};
}
if (reductionDepth == 1) {
if (floatOutput == floatPartials) {
return popsolver::DataType{0};
} else {
return popsolver::DataType{
getCastCycleEstimate(partialsPerTile, partialsVectorWidth,
outputVectorWidth, numWorkers)};
}
}
return popsolver::DataType{getReduceCycleEstimate(
partialsPerTile, reductionDepth, dataPathWidth, floatOutput,
floatPartials, numWorkers)};
});
const auto mNeedsCast =
m.addConstant(reducePartialsType != inputType ? 1u : 0u);
const auto mNeedsCastOrReduction =
m.min({m.one(), m.sum({mNeedsCast, mNeedsReduction})});
mQTempBytesAfterCompute = m.product(
{mNeedsCastOrReduction, mPartialsPerTile[level], mBytesPerOutput});
mComputeTempBytesPerLevel[level] =
m.sum({mExchangeTempBytesPerLevel[level], mQTempBytesAfterCompute});
}
}
CostVariables mExchangeCost(m.sum(mExchangeCyclesPerLevel),
m.max(mExchangeTempBytesPerLevel));
CostVariables mComputeCost(m.sum(mComputeCyclesPerLevel),
m.max(mComputeTempBytesPerLevel));
return std::make_tuple(mExchangeCost, mComputeCost);
}
static std::tuple<CostVariables, popsolver::Variable>
addTransposeBucketsCost(popsolver::Model &m, const Target &target,
const Type &inputType,
const popsolver::Variable &mGroupsPerBucket,
const Vector<popsolver::Variable> &mGrouping) {
const auto mElemsPerGroup = m.product({mGrouping.x, mGrouping.y});
const auto mGroupingSum = m.sum({mGrouping.x, mGrouping.y});
const auto mNeedsTranspose = m.sub(
m.one(), m.sub(mGroupingSum, m.min({mElemsPerGroup, mGroupingSum})));
const auto mBytesPerInput = m.addConstant(target.getTypeSize(inputType));
const auto numWorkers = target.getNumWorkerContexts();
const auto calculateTransposeCycles =
[=](const std::vector<unsigned> &values) {
const auto numTransposes = values[0];
const auto numSrcRows = values[1];
const auto numSrcColumns = values[2];
if (numSrcRows + numSrcColumns > numSrcRows * numSrcColumns) {
return popsolver::DataType{0};
}
const auto cycles = getTransposeCycleEstimate(
numTransposes, numSrcRows, numSrcColumns, inputType, numWorkers);
return popsolver::DataType{cycles};
};
const auto mCycles =
m.product({mNeedsTranspose,
m.call<unsigned>({mGroupsPerBucket, mGrouping.x, mGrouping.y},
calculateTransposeCycles)});
const auto mTransposedBytes = m.product(
{mNeedsTranspose, mGroupsPerBucket, mElemsPerGroup, mBytesPerInput});
return std::make_tuple(CostVariables(mCycles, mTransposedBytes),
mTransposedBytes);
}
static std::tuple<CostVariables, CostBreakdownVariables>
addEstimates(const Target &target, const Type &inputType,
const Vector<std::size_t> &shape,
const SparsityParams &sparsityParams, const double &nzRatio,
const OnTileMethod &method, const std::vector<unsigned> &hierarchy,
const ExchangeEstimator &exchangeEstimator,
const PartitionToPNMapping &mapping, popsolver::Model &m,
const PartitionVariables &p,
const std::vector<Vector<popsolver::Variable>> &mGroups,
const Vector<popsolver::Variable> &mGrouping,
const popsolver::Variable &mRGroupsPerBucket,
const popsolver::Variable &mRElemsPerGroup,
const popsolver::Variable &mRMetaInfoElemsPerBucket,
const bool transposeBuckets, const Options &options) {
CostBreakdownVariables costBreakdown;
const auto mBytesPerInput = m.addConstant(target.getTypeSize(inputType));
const auto mBytesPerMetaInfoElem =
m.addConstant(target.getTypeSize(deviceMetaInfoType));
const auto &mRNonZeroBytesPerBucket =
m.product({mRGroupsPerBucket, mRElemsPerGroup, mBytesPerInput});
const auto &mRMetaInfoBytesPerBucket =
m.product({mRMetaInfoElemsPerBucket, mBytesPerMetaInfoElem});
const auto mRBytesPerBucket =
m.sum({mRNonZeroBytesPerBucket, mRMetaInfoBytesPerBucket});
CostVariables mTransposeBucketsCost(m.zero(), m.zero());
popsolver::Variable mRTransposedBytes = m.zero();
if (transposeBuckets) {
std::tie(mTransposeBucketsCost, mRTransposedBytes) =
addTransposeBucketsCost(m, target, inputType, mRGroupsPerBucket,
mGrouping);
costBreakdown.emplace_back("Transpose buckets", mTransposeBucketsCost);
}
CostVariables mDistributionExchangeCost;
popsolver::Variable mSTempBytesAfterExchange, mRTempBytesAfterExchange;
std::tie(mDistributionExchangeCost, mSTempBytesAfterExchange,
mRTempBytesAfterExchange) =
addDistributionExchangeCostSparseDense(
m, target, inputType, deviceMetaInfoType, options, hierarchy,
exchangeEstimator, mapping, mGroups, mGrouping, mRBytesPerBucket, p);
mDistributionExchangeCost.tempBytes =
m.sum({mDistributionExchangeCost.tempBytes, mRTransposedBytes});
costBreakdown.emplace_back("Pre-distribution + distribution exchange",
mDistributionExchangeCost);
CostVariables mDistributionComputeCost;
popsolver::Variable mQTempBytesAfterCompute;
std::tie(mDistributionComputeCost, mQTempBytesAfterCompute) =
addDistributionComputeCostSparseDense(
m, target, inputType, nzRatio, options, method, mGroups.back(),
mGrouping, p.cumulative.back(), mSTempBytesAfterExchange,
mRTempBytesAfterExchange);
mDistributionComputeCost.tempBytes =
m.sum({mDistributionComputeCost.tempBytes, mRTransposedBytes});
costBreakdown.emplace_back("Distribution compute", mDistributionComputeCost);
auto mPropagationCost =
addPropagationCost(m, target, inputType, hierarchy, options,
exchangeEstimator, mRBytesPerBucket, p);
mPropagationCost.tempBytes =
m.sum({mPropagationCost.tempBytes, mSTempBytesAfterExchange,
mQTempBytesAfterCompute, mRTransposedBytes});
costBreakdown.emplace_back("Propagation", mPropagationCost);
const popsolver::Variable mPartialsPerTileToReduce =
m.product({mGroups.back().groups, mGroups.back().x, mGroups.back().z,
mGrouping.groups, mGrouping.x, mGrouping.z});
std::vector<popsolver::Variable> mReductionDepth(hierarchy.size()),
mReductionDepthCumulative(hierarchy.size() + 1);
for (unsigned level = 0; level < hierarchy.size() + 1; ++level) {
if (level < hierarchy.size()) {
mReductionDepth[level] = p.partition[level].y;
}
mReductionDepthCumulative[level] = p.cumulative[level].y;
}
const auto &[mReductionExchangeCost, mReductionComputeCost] =
addReductionCost(m, target, inputType, hierarchy, options,
exchangeEstimator, mPartialsPerTileToReduce,
mReductionDepth, mReductionDepthCumulative, p.tile,
mQTempBytesAfterCompute);
costBreakdown.emplace_back("Exchange to reduce", mReductionExchangeCost);
costBreakdown.emplace_back("Reduction or cast", mReductionComputeCost);
CostVariables cost(
m.sum({mTransposeBucketsCost.cycles, mDistributionExchangeCost.cycles,
mDistributionComputeCost.cycles, mPropagationCost.cycles,
mReductionExchangeCost.cycles, mReductionComputeCost.cycles}),
m.max(
{mTransposeBucketsCost.tempBytes, mDistributionExchangeCost.tempBytes,
mDistributionComputeCost.tempBytes, mPropagationCost.tempBytes,
mReductionExchangeCost.tempBytes, mReductionComputeCost.tempBytes}));
costBreakdown.emplace_back("Total", cost);
return std::make_tuple(cost, costBreakdown);
}
static std::tuple<CostVariables, CostBreakdownVariables> addEstimatesGradW(
const Target &target, const Type &inputType,
const Vector<std::size_t> &shape, const SparsityParams &sparsityParams,
const double nzRatio, const OnTileMethod &method,
const std::vector<unsigned> &hierarchy,
const ExchangeEstimator &exchangeEstimator,
const PartitionToPNMapping &mapping, const bool exchangeBuckets,
popsolver::Model &m, const PartitionVariables &p,
const std::vector<Vector<popsolver::Variable>> &mGroups,
const Vector<popsolver::Variable> &mGrouping,
const popsolver::Variable &mRGroupsPerBucket,
const popsolver::Variable &mRElemsPerGroup,
const popsolver::Variable &mRMetaInfoElemsPerBucket,
const Options &options) {
CostBreakdownVariables costBreakdown;
// We pre-calculate certain variables that will be used for different exchange
// costs below.
const auto mBytesPerInput = m.addConstant(target.getTypeSize(inputType));
const auto mBytesPerPartial =
m.addConstant(target.getTypeSize(options.partialsType));
const auto mBytesPerMetaInfoElem =
m.addConstant(target.getTypeSize(UNSIGNED_SHORT));
std::vector<popsolver::Variable> mQGradBytesPerTile(hierarchy.size() + 1),
mSBytesPerTile(hierarchy.size() + 1);
for (unsigned level = 0; level < hierarchy.size() + 1; ++level) {
mQGradBytesPerTile[level] =
m.product({m.ceildiv(m.product({mGroups[level].groups, mGroups[level].x,
mGroups[level].z}),
p.tile[level]),
mGrouping.groups, mGrouping.x, mGrouping.z, mBytesPerInput});
mSBytesPerTile[level] =
m.product({m.ceildiv(m.product({mGroups[level].groups, mGroups[level].y,
mGroups[level].z}),
p.tile[level]),
mGrouping.groups, mGrouping.y, mGrouping.z, mBytesPerInput});
}
const auto mRGradPartialBytesPerTile =
m.product({mRMetaInfoElemsPerBucket, mBytesPerMetaInfoElem});
const auto mRMetaInfoBytesPerTile =
m.product({mRGroupsPerBucket, mRElemsPerGroup, mBytesPerPartial});
const auto mRGradBytesPerTile =
m.sum({mRGradPartialBytesPerTile, mRMetaInfoBytesPerTile});
popsolver::Variable mQGradTempBytes = m.zero(), mSTempBytes = m.zero();
const auto mPreDistributionExchangeCost =
addPreDistributionExchangeCostDenseDense(
m, options, hierarchy, exchangeEstimator, mapping, mQGradBytesPerTile,
mSBytesPerTile, mQGradTempBytes, mSTempBytes, p);
costBreakdown.emplace_back("Pre-distribution exchange",
mPreDistributionExchangeCost);
CostVariables mTransposeCost(m.zero(), m.zero());
if (method == OnTileMethod::GradWAMPBlock) {
// Estimate cycle cost for rearranging both activations and gradients
// wrt output. Transpose and exchange and there need not be done for
// each partition of z.
const auto &[mQGradTransposeCycles, mQGradTransposeBytes] =
rearrangeDenseCost(m, target, inputType, mGroups.back().x, mGrouping.x,
mGroups.back().z, mGrouping.z);
const auto &[mSTransposeCycles, mSTransposeBytes] =
rearrangeDenseCost(m, target, inputType, mGroups.back().y, mGrouping.y,
mGroups.back().z, mGrouping.z);
mTransposeCost.cycles = m.sum({mQGradTransposeCycles, mSTransposeCycles});
// We transpose all in one compute set so temp mem is sum
mTransposeCost.tempBytes = m.sum(
{mQGradTransposeBytes, mQGradTempBytes, mSTransposeBytes, mSTempBytes});
mQGradTempBytes = mQGradTransposeBytes;
mSTempBytes = mSTransposeBytes;
}
costBreakdown.emplace_back("Q-grad/S transpose", mTransposeCost);
const auto mDistributionExchangeCycles =
addDistributionExchangeCycleCostDenseDense(
m, options, hierarchy, exchangeEstimator, mapping, exchangeBuckets,
mRGradBytesPerTile, mQGradBytesPerTile.back(), mSBytesPerTile.back(),
p);
costBreakdown.emplace_back(
"Distribution exchange",
CostVariables(mDistributionExchangeCycles, m.zero()));
const auto mDistributionComputeCycles =
addDistributionComputeCycleCostDenseDense(
m, target, inputType, nzRatio, options, method, mGroups.back(),
mGrouping, p.cumulative.back(), mRGroupsPerBucket, mRElemsPerGroup);
costBreakdown.emplace_back(
"Distribution compute",
CostVariables(mDistributionComputeCycles, m.zero()));
const auto &[mDistributionAndPropagationMaxTempBytes, mRGradTempBytes] =
addGradWExchangeAndComputeTempBytesCost(
m, options, inputType, exchangeBuckets, mRGradPartialBytesPerTile,
mRMetaInfoBytesPerTile, mQGradTempBytes, mSTempBytes, p);
costBreakdown.emplace_back(
"All exchange + compute",
CostVariables(m.zero(), mDistributionAndPropagationMaxTempBytes));
const auto mPartialsPerTileToReduce =
m.product({mRGroupsPerBucket, mRElemsPerGroup});
const std::vector<popsolver::Variable> mReductionDepth(hierarchy.size(),
m.one()),
mReductionDepthCumulative(hierarchy.size() + 1, m.one());
const auto &[mReductionExchangeCost, mReductionComputeCost] =
addReductionCost(m, target, inputType, hierarchy, options,
exchangeEstimator, mPartialsPerTileToReduce,
mReductionDepth, mReductionDepthCumulative, p.tile,
mRGradTempBytes);
costBreakdown.emplace_back("Exchange to reduce", mReductionExchangeCost);
costBreakdown.emplace_back("Reduction or cast", mReductionComputeCost);
CostVariables cost(
m.sum({mPreDistributionExchangeCost.cycles, mTransposeCost.cycles,
mDistributionExchangeCycles, mDistributionComputeCycles,
mReductionExchangeCost.cycles, mReductionComputeCost.cycles}),
m.max({mPreDistributionExchangeCost.tempBytes, mTransposeCost.tempBytes,
mDistributionAndPropagationMaxTempBytes,
mReductionExchangeCost.tempBytes,
mReductionComputeCost.tempBytes}));
costBreakdown.emplace_back("Total", cost);
return std::make_tuple(cost, costBreakdown);
}
// TODO: We could actually get this straight from the parameters. Until
// we've decided how blocks should be represented in FullyConnectedParams
// we'll calculate exactly what we want here.
static popsolver::Variable
addNumNonZeroGroups(popsolver::Model &m, const FullyConnectedParams ¶ms,
const Type &inputType) {
const auto &sparsityParams = params.getSparsityParams();
const auto blockDimensions =
getBlockDimensionsToUse(sparsityParams.blockDimensions, inputType);
const auto outputBlocks =
params.getOutputChannelsPerGroup() / blockDimensions.at(0);
const auto inputBlocks =
params.getInputChannelsPerGroup() / blockDimensions.at(1);
const auto rGroups =
params.getNumGroups() *
unsigned(std::ceil(inputBlocks * outputBlocks * params.getNzRatio()));
return m.addConstant(rGroups);
}
static popsolver::Variable addNumNonZeroGroupsPerBucket(
popsolver::Model &m, const Target &target, const Type &inputType,
const popsolver::Variable &mNonZeroGroups, unsigned nonZeroElemsPerGroup,
const PartitionVariables &p, const Options &options) {
// Find the number of groups per bucket when uniformly distributed.
const auto mPerfectlyUniformGroupsPerBucket =
m.ceildiv(mNonZeroGroups, p.tile.at(0));
// Ensure the number of elements guarantees the size in bytes of the bucket
// is a multiple of the exchange atom size.
const unsigned bytesPerNonZeroElem = target.getTypeSize(inputType);
const auto bytesPerGroup = nonZeroElemsPerGroup * bytesPerNonZeroElem;
const unsigned exchangeAtomSize = target.getExchangeBytesPerCycle();
const auto grainSizeInGroups =
lcm(bytesPerGroup, exchangeAtomSize) / bytesPerGroup;
return m.call<unsigned>(
{mPerfectlyUniformGroupsPerBucket},
[=](const std::vector<unsigned> &values) -> popsolver::DataType {
// Number of groups when perfectly distributed is multiplied by some
// factor given as an option to allow room for imbalance.
const unsigned groups = std::round(
values[0] * (1.0 + options.metaInfoBucketOversizeProportion));
return popsolver::DataType{roundUp(groups, grainSizeInGroups)};
});
}
// Given the meta-info is often shared between passes in some way, these
// are calculated and returned jointly.
static popsolver::Variable addMetaInfoElemsPerBucket(
popsolver::Model &m, const Target &target, const Type &deviceMetaInfoType,
const double &nzRatio, const OnTileMethod &method,
const Vector<popsolver::Variable> &mGroupsPerTile, const Options &options) {
const unsigned bytesPerMetaInfoElem = target.getTypeSize(deviceMetaInfoType);
const unsigned exchangeAtomSize = target.getExchangeBytesPerCycle();
const auto atomSizeInMetaInfoElems =
lcm(bytesPerMetaInfoElem, exchangeAtomSize);
// A chosen number of sub-groups per bucket just for memory planning.
constexpr unsigned numSubgroupsPerBucket = 2U;
auto calcFwdBucketSizeElemwise =
[=](const std::vector<unsigned> &values) -> popsolver::DataType {
const auto xGroups = values[0];
const auto yGroups = values[1];
unsigned xNonZeroGroups, yNonZeroGroups;
std::tie(xNonZeroGroups, yNonZeroGroups) =
getNumGroupsGivenUniformSparsityPattern(nzRatio, xGroups, yGroups);
// Knowing that we use a CSR based format we can calculate the
// number of elements of meta-info that would be required to
// store this in a perfect world.
const auto outputEntryElems =
sizeof(MetaInfo<MetaInfoType>::OutputEntry) / sizeof(MetaInfoType);
const auto subGroupElems =
sizeof(MetaInfo<MetaInfoType>::SubGroupEntry) / sizeof(MetaInfoType);
const auto workerEntryElems =
sizeof(MetaInfo<MetaInfoType>::WorkerEntry) / sizeof(MetaInfoType);
const auto numElemsPerfectlyUniform =
xNonZeroGroups * (outputEntryElems + yNonZeroGroups);
const auto gradWWorkerEntryElems =
options.doGradWPass
? (1 + sizeof(MetaInfo<MetaInfoType>::GradWWorkerEntry) /
sizeof(MetaInfoType))
: 0;
const unsigned elems =
(subGroupElems + target.getNumWorkerContexts() *
(workerEntryElems + gradWWorkerEntryElems)) *
numSubgroupsPerBucket +
std::ceil(numElemsPerfectlyUniform *
(1.0 + options.metaInfoBucketOversizeProportion));
return popsolver::DataType{roundUp(elems, atomSizeInMetaInfoElems)};
};
const auto calcFwdBucketSizeAMPBlock =
[=](const std::vector<unsigned> &values) -> popsolver::DataType {
const auto xGroups = values[0];
const auto yGroups = values[1];
unsigned xNonZeroGroups, yNonZeroGroups;
std::tie(xNonZeroGroups, yNonZeroGroups) =
getNumGroupsGivenUniformSparsityPattern(nzRatio, xGroups, yGroups);
const auto outputEntryElems =
sizeof(BlockMetaInfo<MetaInfoType>::OutputEntry) / sizeof(MetaInfoType);
const auto subGroupElems =
sizeof(BlockMetaInfo<MetaInfoType>::SubGroupEntry) /
sizeof(MetaInfoType);
const auto gradWWorkerEntryElems =
options.doGradWPass
? sizeof(BlockMetaInfo<MetaInfoType>::GradWWorkerEntry) /
sizeof(MetaInfoType)
: 0;
const auto numElemsPerfectlyUniform =
xNonZeroGroups * (outputEntryElems + yNonZeroGroups);
const unsigned elems =
((subGroupElems +
target.getNumWorkerContexts() * gradWWorkerEntryElems) *
numSubgroupsPerBucket +
std::ceil(numElemsPerfectlyUniform *
(1.0 + options.metaInfoBucketOversizeProportion)));
return popsolver::DataType{roundUp(elems, atomSizeInMetaInfoElems)};
};
switch (method) {
case OnTileMethod::Forward: {
return m.call<unsigned>({mGroupsPerTile.x, mGroupsPerTile.y},
calcFwdBucketSizeElemwise);
}
case OnTileMethod::GradA: {
auto calcGradABucketSizeElemwise =
[=](const std::vector<unsigned> &values) -> popsolver::DataType {
const auto xGroups = values[0];
const auto yGroups = values[1];
unsigned xNonZeroGroups, yNonZeroGroups;
std::tie(xNonZeroGroups, yNonZeroGroups) =
getNumGroupsGivenUniformSparsityPattern(nzRatio, xGroups, yGroups);
// Knowing that we use a CSR based format we can calculate the
// number of elements of meta-info that would be required to
// store this in a perfect world.
const auto outputEntryElems =
sizeof(MetaInfo<MetaInfoType>::OutputEntry) / sizeof(MetaInfoType);
const auto subGroupElems =
sizeof(MetaInfo<MetaInfoType>::SubGroupEntry) / sizeof(MetaInfoType);
const auto workerEntryElems =
sizeof(MetaInfo<MetaInfoType>::WorkerEntry) / sizeof(MetaInfoType);
// yNonZeroGroups * 2 because we encode information to transpose
// weights along with offsets for inputs if GradA method is selected
// other wise the same bucket as forward is used
constexpr unsigned elementsPerY = 2;
const auto numElemsPerfectlyUniform =
xNonZeroGroups * (outputEntryElems + yNonZeroGroups * elementsPerY);
const unsigned elems =
(subGroupElems + target.getNumWorkerContexts() * workerEntryElems) *
numSubgroupsPerBucket +
std::ceil(numElemsPerfectlyUniform *
(1.0 + options.metaInfoBucketOversizeProportion));
return popsolver::DataType{roundUp(elems, atomSizeInMetaInfoElems)};
};
return m.call<unsigned>({mGroupsPerTile.x, mGroupsPerTile.y},
calcGradABucketSizeElemwise);
}
case OnTileMethod::Transpose: {
// We actually use the same buckets as forward and for a joint plan
// the split should just be the tranpose of the forward.
return m.call<unsigned>({mGroupsPerTile.y, mGroupsPerTile.x},
calcFwdBucketSizeElemwise);
}
case OnTileMethod::ForwardAMPBlock: {
return m.call<unsigned>({mGroupsPerTile.x, mGroupsPerTile.y},
calcFwdBucketSizeAMPBlock);
}
case OnTileMethod::TransposeAMPBlock: {
return m.call<unsigned>({mGroupsPerTile.y, mGroupsPerTile.x},
calcFwdBucketSizeAMPBlock);
}
default:
throw poputil::poplibs_error("Unhandled OnTileMethod");
}
}
static void
applyPartitionPlanConstraint(popsolver::Model &m, const Options &options,
unsigned level,
const Vector<popsolver::Variable> &partition) {
assert(level == 0);
const auto &planConstraints = options.planConstraints;
const auto &thisPartition = planConstraints.get_child_optional("partition");
if (thisPartition) {
const auto constrainVar = [&](const std::string &pathSuffix,
const popsolver::Variable &var) {
const auto constraint =
thisPartition.get().get_optional<popsolver::DataType>(pathSuffix);
if (constraint) {
m.equal(var, *constraint);
}
};
constrainVar("x", partition.x);
constrainVar("y", partition.y);
constrainVar("z", partition.z);
}
}
// Add limits in the model to account for the range limit of meta-info
template <typename MetaInfoT>
static void addMetaInfoRangeLimits(popsolver::Model &m,
const Vector<popsolver::Variable> &mGroups,
const Vector<popsolver::Variable> &mGrouping,
MetaInfoT, const Type &inputType,
bool isBlockMetaInfoFormat,
const Options &options) {
// TODO: This should really live alongside the meta-info, but currently use
// of the model prohibits this. We could add a wrapper for popsolver
// variables that provides operator overloads such that we can just template
// the calculation of the max value given the grouping etc.
// TODO: This is not complete and only accounts for the offsets encoded in
// meta-info for element-wise sparsity as these are the most likely to exceed
// the range of the encoding type for the meta-info.
//
if (!isBlockMetaInfoFormat) {
const auto mYOffsetFactor =
m.addConstant(getYOffsetTypeScaleFactor(inputType == FLOAT));
// Max offset Y in S on this tile is (Y - 1)
const auto mMaxYOffset =
m.sub(m.product({mGroups.y, mGrouping.y}), m.one());
const auto mMaxYOffsetEncoded =
m.product({mMaxYOffset, mGroups.z, mGrouping.z, mYOffsetFactor});
const auto mMaxXOffsetEncoded =
m.sub(m.product({mGroups.x, mGrouping.x}), m.one());
const auto mMaxOffset = m.max({mMaxYOffsetEncoded, mMaxXOffsetEncoded});
const auto mMaxEncodableValue =
m.addConstant(std::numeric_limits<MetaInfoT>::max());
m.lessOrEqual(mMaxOffset, mMaxEncodableValue);
}
}
// For now just make this such that it never gets picked. In future
// will change this so that the planner will pick this variable
// based on the plan returned for the dense operation
static popsolver::Variable
addUseDenseVariable(popsolver::Model &m,
const poplibs_support::PlanConstraints &constraints) {
const auto denseConstraint = constraints.get_optional<bool>("useDense");
unsigned useDenseValue = 0;
if (denseConstraint) {
useDenseValue = static_cast<unsigned>(*denseConstraint);
}
return m.addConstant(useDenseValue);
}
static std::tuple<Plan, Cost, CostBreakdown>
createPlan(const PlanningObjective &objective, const Target &target,
const Type &inputType, const FullyConnectedParams ¶ms,
const Method &method, const ExchangeAndMappingPlan &exchangePlan,
const Cost &bestCost, const Options &options) {
const auto hierarchy = poplibs::getTileHierarchy(target);
const auto perLevelExchangeBytesPerCycle =
poplibs::getPerLevelExchangeBytesPerCycle(target);
// For now we just handle single-IPU for simplicity. Handling further
// levels should not be significantly harder functionally however.
assert(hierarchy.size() == 1);
Vector<unsigned> size = {
static_cast<unsigned>(params.getNumGroups()), // groups
static_cast<unsigned>(params.getOutputChannelsPerGroup()), // x
static_cast<unsigned>(params.getInputChannelsPerGroup()), // y
static_cast<unsigned>(params.getBatchSize()), // z
};
Vector<unsigned> groups =
size.binaryOp(method.grouping, [&](const auto size, const auto grouping) {
return ceildiv(size, grouping);
});
popsolver::Model m;
// Create partitions variables
const PartitionVariables fwdPartition = [&] {
std::vector<Vector<popsolver::Variable>> mPartitions(hierarchy.size());
for (unsigned level = 0; level < hierarchy.size(); ++level) {
mPartitions[level] = Vector<popsolver::Variable>::generate(
[&] { return m.addVariable(1, hierarchy[level]); });
applyPartitionPlanConstraint(m, options, level, mPartitions[level]);
}
auto partitionPrioGrp = m.addPriorityGroup();
for (const auto &levelPartition : mPartitions) {
for (const auto &var : levelPartition.asStdVector()) {
m.setPriorityGroup(var, partitionPrioGrp);
}
}
m.prioritiseOver(partitionPrioGrp, m.getDefaultPriorityGroup());
return PartitionVariables(m, mPartitions);
}();
// Calculate grains, add constraints on partitions
std::vector<Vector<popsolver::Variable>> mFwdGroups(hierarchy.size() + 1);
mFwdGroups[0] = groups.transform<popsolver::Variable>(
[&](const auto groups) { return m.addConstant(groups); });
for (unsigned level = 0; level < hierarchy.size(); ++level) {
m.lessOrEqual(fwdPartition.product[level],
popsolver::DataType{hierarchy[level]});
mFwdGroups[level + 1] = mFwdGroups[level].binaryOp(
fwdPartition.partition[level],
[&](const auto &groups, const auto &partition) {
return m.ceildivConstrainDivisor(groups, partition);
});
// Partitions of Z must be of equal size on every tile.
m.factorOf(mFwdGroups[level].z, fwdPartition.partition[level].z);
// Our vertex doesn't handle groups at all.
if (level == hierarchy.size() - 1) {
m.equal(mFwdGroups[level + 1].groups, popsolver::DataType{1});
}
}
const auto mFwdGrouping = method.grouping.transform<popsolver::Variable>(
[&](const auto grouping) { return m.addConstant(grouping); });
const bool isBlockMetaInfoFormat =
params.getSparsityParams().type == SparsityType::Block;
addMetaInfoRangeLimits(m, mFwdGroups.back(), mFwdGrouping, MetaInfoType(),
inputType, isBlockMetaInfoFormat, options);
// Calculate size of buckets.
const auto mRGroups = addNumNonZeroGroups(m, params, inputType);
const auto rElemsPerGroup =
method.grouping.groups * method.grouping.x * method.grouping.y;
const auto mRGroupsPerBucket = addNumNonZeroGroupsPerBucket(
m, target, inputType, mRGroups, rElemsPerGroup, fwdPartition, options);
const auto mRElemsPerGroup = m.addConstant(rElemsPerGroup);
const auto mRFwdMetaInfoElemsPerBucket = addMetaInfoElemsPerBucket(
m, target, deviceMetaInfoType, params.getNzRatio(), method.fwd,
mFwdGroups.back(), options);
CostVariables fwdCost;
CostBreakdownVariables fwdCostBreakdown;
const Vector<std::size_t> fwdShape = {
params.getNumGroups(),
params.getOutputChannelsPerGroup(),
params.getInputChannelsPerGroup(),
params.getBatchSize(),
};
const ExchangeEstimator exchangeEstimator(m, target, hierarchy,
perLevelExchangeBytesPerCycle);
std::tie(fwdCost, fwdCostBreakdown) =
addEstimates(target, inputType, fwdShape, params.getSparsityParams(),
params.getNzRatio(), method.fwd, hierarchy,
exchangeEstimator, exchangePlan.fwdMapping, m, fwdPartition,
mFwdGroups, mFwdGrouping, mRGroupsPerBucket, mRElemsPerGroup,
mRFwdMetaInfoElemsPerBucket, false, options);
CostVariables gradACost(m.zero(), m.zero());
CostBreakdownVariables gradACostBreakdown;
popsolver::Variable mRGradAMetaInfoElemsPerBucket = m.zero();
if (options.doGradAPass) {
// TODO: Encapsulate this translation to GradA pass better.
// This is just a swizzle applied to all vectors in 'planning
// space'.
const auto toGradA = [](const auto fwdV) {
return decltype(fwdV){
fwdV.groups,
fwdV.y,
fwdV.x,
fwdV.z,
};
};
const auto gradAShape = toGradA(fwdShape);
const auto gradAPartition = [&] {
auto gradA = fwdPartition;
for (auto &p : gradA.partition) {
p = toGradA(p);
}
for (auto &p : gradA.cumulative) {
p = toGradA(p);
}
return gradA;
}();
const auto mGradAGroups = [&] {
auto v = mFwdGroups;
for (auto &g : v) {
g = toGradA(g);
}
return v;
}();
const auto mGradAGrouping = toGradA(mFwdGrouping);
if (!options.sharedBuckets) {
addMetaInfoRangeLimits(m, mGradAGroups.back(), mGradAGrouping,
MetaInfoType(), inputType, isBlockMetaInfoFormat,
options);
}
mRGradAMetaInfoElemsPerBucket = addMetaInfoElemsPerBucket(
m, target, deviceMetaInfoType, params.getNzRatio(), method.gradA,
mGradAGroups.back(), options);
std::tie(gradACost, gradACostBreakdown) = addEstimates(
target, inputType, gradAShape, params.getSparsityParams(),
params.getNzRatio(), method.gradA, hierarchy, exchangeEstimator,
exchangePlan.gradAMapping, m, gradAPartition, mGradAGroups,
mGradAGrouping, mRGroupsPerBucket, mRElemsPerGroup,
mRGradAMetaInfoElemsPerBucket, true, options);
}
CostVariables gradWCost(m.zero(), m.zero());
CostBreakdownVariables gradWCostBreakdown;
if (options.doGradWPass) {
std::tie(gradWCost, gradWCostBreakdown) = addEstimatesGradW(
target, inputType, fwdShape, params.getSparsityParams(),
params.getNzRatio(), method.gradW, hierarchy, exchangeEstimator,
exchangePlan.gradWMapping, exchangePlan.gradWExchangeBuckets, m,
fwdPartition, mFwdGroups, mFwdGrouping, mRGroupsPerBucket,
mRElemsPerGroup, mRFwdMetaInfoElemsPerBucket, options);
}
const auto useDense = addUseDenseVariable(m, options.planConstraints);
const CostVariables mCost(
m.sum({fwdCost.cycles, gradACost.cycles, gradWCost.cycles}),
m.max({fwdCost.tempBytes, gradACost.tempBytes, gradWCost.tempBytes}));
CostBreakdownVariables mCostBreakdown;
for (auto &entry : fwdCostBreakdown) {
mCostBreakdown.emplace_back("Fwd: " + std::move(entry.first),
std::move(entry.second));
}
for (auto &entry : gradACostBreakdown) {
mCostBreakdown.emplace_back("GradA: " + std::move(entry.first),
std::move(entry.second));
}
for (auto &entry : gradWCostBreakdown) {
mCostBreakdown.emplace_back("GradW: " + std::move(entry.first),
std::move(entry.second));
}
popsolver::Solution solution;
switch (objective.getType()) {
case PlanningObjective::MINIMIZE_CYCLES:
m.lessOrEqual(mCost.cycles, bestCost.cycles);
m.lessOrEqual(mCost.tempBytes, objective.getTileTempMemoryBound());
solution = m.minimize({mCost.cycles, mCost.tempBytes});
break;
case PlanningObjective::MINIMIZE_TILE_TEMP_MEMORY:
m.lessOrEqual(mCost.tempBytes, bestCost.tempBytes);
m.lessOrEqual(mCost.cycles, objective.getCyclesBound());
solution = m.minimize({mCost.tempBytes, mCost.cycles});
break;
}
if (!solution.validSolution()) {
return {Plan(), highestCost, {}};
}
Plan plan;
plan.partition = fwdPartition.partition[0].transform<unsigned>(
[&](popsolver::Variable partitionVar) {
return solution[partitionVar].getAs<unsigned>();
});
// For now these are hard-coded but we could plan for it further
// down the road if memory or something else did not allow this.
plan.initialDistributionPartitions = Vector<unsigned>(1);
plan.initialDistributionPartitions.z = plan.partition.z;
// We round up the number of nz values per bucket to a multiple of
// 64-bits when used as partials in the GradW pass.
assert(8 % target.getTypeSize(options.partialsType) == 0);
const auto nzElemGrainSize =
options.doGradWPass ? 8 / target.getTypeSize(options.partialsType) : 1;
plan.nzElemsPerBucket =
roundUp(solution[mRGroupsPerBucket].getAs<unsigned>() * rElemsPerGroup,
nzElemGrainSize);
plan.fwdMetaInfoElemsPerBucket =
solution[mRFwdMetaInfoElemsPerBucket].getAs<unsigned>();
plan.gradAMetaInfoElemsPerBucket =
solution[mRGradAMetaInfoElemsPerBucket].getAs<unsigned>();
plan.method = method;
// We currently plan the gradW pass with dimensions ordered for the
// forward pass but the implementation wants a different ordering so
// do the switch here until such a time as planning/implementation agree
// on dimension ordering for gradW pass.
plan.exchangePlan = exchangePlan;
const auto oldGradWMapping =
exchangePlan.gradWMapping.getLinearisationOrder();
plan.exchangePlan.gradWMapping =
PartitionToPNMapping({oldGradWMapping.groups, oldGradWMapping.x,
oldGradWMapping.z, oldGradWMapping.y});
plan.useDense = solution[useDense].getAs<unsigned>();
Cost cost;
cost.cycles = solution[mCost.cycles];
cost.tempBytes = solution[mCost.tempBytes];
CostBreakdown costBreakdown;
costBreakdown.reserve(mCostBreakdown.size());
for (const auto &entry : mCostBreakdown) {
costBreakdown.emplace_back(
std::move(entry.first),
Cost(solution[entry.second.cycles], solution[entry.second.tempBytes]));
}
return std::make_tuple(std::move(plan), std::move(cost),
std::move(costBreakdown));
}
static std::vector<Method>
getCandidateMethods(const Target &target, const Type &inputType,
const FullyConnectedParams ¶ms,
const Options &options) {
std::vector<Method> methods;
const auto &sparsityParams = params.getSparsityParams();
const auto blockDimensions =
getBlockDimensionsToUse(sparsityParams.blockDimensions, inputType);
const unsigned xElemsPerBlock = blockDimensions.at(0);
const unsigned yElemsPerBlock = blockDimensions.at(1);
const unsigned elemsPerBlock = xElemsPerBlock * yElemsPerBlock;
if (elemsPerBlock == 1) {
// Element-wise methods
Vector<unsigned> grouping = {
1, // groups
1, // x
1, // y
target.getVectorWidth(inputType), // z
};
methods.emplace_back(Method{
grouping, OnTileMethod::Forward,
// TODO: This could eventually be based on a memory/cycle tradeoff
options.sharedBuckets ? OnTileMethod::Transpose : OnTileMethod::GradA,
OnTileMethod::GradW});
} else {
// AMP-based block methods
Vector<unsigned> grouping = {
1,
xElemsPerBlock,
yElemsPerBlock,
1,
};
methods.emplace_back(Method{grouping, OnTileMethod::ForwardAMPBlock,
OnTileMethod::TransposeAMPBlock,
OnTileMethod::GradWBlock});
// Batch size restriction on AMP based GradW method
const auto zGrouping = inputType == FLOAT ? 8U : 16U;
const auto addGradWAmpMethod = (params.getBatchSize() % zGrouping == 0) &&
(xElemsPerBlock % 4 == 0) &&
(yElemsPerBlock % 4 == 0);
if (addGradWAmpMethod) {
// AMP-based block methods
Vector<unsigned> groupingAmp = {
1,
xElemsPerBlock,
yElemsPerBlock,
zGrouping,
};
methods.emplace_back(Method{groupingAmp, OnTileMethod::ForwardAMPBlock,
OnTileMethod::TransposeAMPBlock,
OnTileMethod::GradWAMPBlock});
}
}
return methods;
}
static std::vector<ExchangeAndMappingPlan>
getCandidateExchangePlans(const Options &options) {
std::vector<ExchangeAndMappingPlan> candidates;
const auto &planConstraints = options.planConstraints;
const auto &exchangePlanConstraints =
planConstraints.get_child_optional("exchange");
std::vector<bool> validGradWExchangeBucketsOptions = {false, true};
if (exchangePlanConstraints) {
const auto &constraint = exchangePlanConstraints.get().get_optional<bool>(
"gradWExchangeBuckets");
if (constraint) {
validGradWExchangeBucketsOptions = {*constraint};
}
}
// Only leave one of the 2 possibilities if we aren't doing a
// GradW pass anyway as gradWExchangeBuckets will have no effect
// on a plan without a GradW pass.
if (!options.doGradWPass && validGradWExchangeBucketsOptions.size() > 1) {
validGradWExchangeBucketsOptions = {validGradWExchangeBucketsOptions[0]};
}
ExchangeAndMappingPlan basePlan;
basePlan.fwdMapping = PartitionToPNMapping({0, 3, 1, 2});
basePlan.gradAMapping = PartitionToPNMapping({0, 1, 3, 2});
for (const auto &gradWExchangeBuckets : validGradWExchangeBucketsOptions) {
basePlan.gradWExchangeBuckets = gradWExchangeBuckets;
if (gradWExchangeBuckets) {
// Note this is a conscious choice of re-use of the forward
// pass mapping for the candidate where buckets are
// exchanged.
basePlan.gradWMapping = PartitionToPNMapping({0, 3, 1, 2});
} else {
basePlan.gradWMapping = PartitionToPNMapping({0, 1, 2, 3});
}
candidates.emplace_back(basePlan);
}
return candidates;
}
static std::tuple<Plan, Cost, CostBreakdown>
createPlan(const PlanningObjective &objective, const Target &target,
const Type &inputType, const FullyConnectedParams ¶ms,
const Options &options) {
const auto candidateMethods =
getCandidateMethods(target, inputType, params, options);
const auto candidateExchangePlans = getCandidateExchangePlans(options);
assert(!candidateMethods.empty());
assert(!candidateExchangePlans.empty());
Plan best;
Cost bestCost = highestCost;
CostBreakdown bestCostBreakdown;
for (const auto &candidateMethod : candidateMethods) {
for (const auto &candidateExchangePlan : candidateExchangePlans) {
Plan candidate;
Cost candidateCost;
CostBreakdown candidateCostBreakdown;
std::tie(candidate, candidateCost, candidateCostBreakdown) =
createPlan(objective, target, inputType, params, candidateMethod,
candidateExchangePlan, bestCost, options);
if (candidateCost == highestCost) {
continue;
}
if (objective.lowerCost(candidateCost, bestCost)) {
best = std::move(candidate);
bestCost = std::move(candidateCost);
bestCostBreakdown = std::move(candidateCostBreakdown);
}
}
}
return std::make_tuple(best, bestCost, bestCostBreakdown);
}
static std::tuple<Plan, Cost> runPlanner(const Target &target,
const Type &inputType,
const FullyConnectedParams ¶ms,
const Options &options) {
Plan plan;
auto cost = highestCost;
CostBreakdown costBreakdown;
const unsigned availableTileMem =
target.getBytesPerTile() * options.availableMemoryProportion;
if (availableTileMem != 0) {
auto objective = PlanningObjective::minimizeCycles();
auto stepMemBound = availableTileMem;
objective.setTileTempMemoryBound(popsolver::DataType{stepMemBound});
logging::popsparse::debug(
"Planning sparse-dense matrix multiply with a per-tile "
"memory limit of {} bytes.",
stepMemBound);
do {
std::tie(plan, cost, costBreakdown) =
createPlan(objective, target, inputType, params, options);
if (cost != highestCost) {
break;
}
stepMemBound *= 2;
logging::popsparse::warn(
"Unable to meet memory target. Retrying with a per-tile "
"memory limit of {} bytes.",
stepMemBound);
objective.setTileTempMemoryBound(popsolver::DataType{stepMemBound});
} while (stepMemBound < target.getBytesPerTile() * 2);
// If the above did not succeed, try again without any memory limit to
// get a valid plan of some sort.
if (cost == highestCost) {
objective = PlanningObjective::minimizeCycles();
logging::popsparse::warn(
"Unable to meet memory target. Retrying with no per-tile "
"memory limit.");
std::tie(plan, cost, costBreakdown) =
createPlan(objective, target, inputType, params, options);
}
} else {
logging::popsparse::debug(
"Planning sparse-dense matrix multiply with unlimited memory usage.");
}
logging::popsparse::debug("Found best plan: {}.", cost);
if (logging::popsparse::shouldLog(logging::Level::Debug)) {
logging::popsparse::debug(" Cost breakdown:");
for (const auto &entry : costBreakdown) {
logging::popsparse::debug(" {}: {}", entry.first, entry.second);
}
}
logging::popsparse::debug(" for params:\n{}", params);
logging::popsparse::debug(" and input type: {}", inputType);
logging::popsparse::debug(" with options:\n{}", options);
logging::popsparse::debug("{}", plan);
return std::make_tuple(std::move(plan), std::move(cost));
}
std::ostream &operator<<(std::ostream &os, const Cost &c) {
os << "Cost{";
bool needComma = false;
if (*c.cycles != 0) {
os << "cycles=" << c.cycles;
needComma = true;
}
if (*c.tempBytes != 0) {
if (needComma) {
os << ", ";
}
os << "memory=" << c.tempBytes;
}
os << "}";
return os;
}
std::ostream &operator<<(std::ostream &os, const OnTileMethod &m) {
switch (m) {
case OnTileMethod::Forward:
os << "Forward";
break;
case OnTileMethod::GradA:
os << "GradA";
break;
case OnTileMethod::GradW:
os << "GradW";
break;
case OnTileMethod::Transpose:
os << "Transpose";
break;
case OnTileMethod::ForwardAMPBlock:
os << "ForwardAMPBlock";
break;
case OnTileMethod::TransposeAMPBlock:
os << "TransposeAMPBlock";
break;
case OnTileMethod::GradWAMPBlock:
os << "GradWAMPBlock";
break;
case OnTileMethod::GradWBlock:
os << "GradWBlock";
break;
default:
throw poputil::poplibs_error("Unrecognised on-tile method");
}
return os;
}
std::ostream &operator<<(std::ostream &os, const Method &m) {
os << "{ grouping: " << m.grouping << ", forward pass: " << m.fwd
<< ", grad-a pass: " << m.gradA << ", grad-w pass: " << m.gradW << " }";
return os;
}
std::ostream &operator<<(std::ostream &os, const ExchangeAndMappingPlan &p) {
os << "{ forward pass: " << p.fwdMapping
<< ", grad-a pass: " << p.gradAMapping
<< ", grad-w pass: " << p.gradWMapping << ", grad-w pass exchanges "
<< (p.gradWExchangeBuckets ? "buckets" : "inputs") << "}";
return os;
}
std::ostream &operator<<(std::ostream &os, const Plan &p) {
os << "Plan:\n method: " << p.method << "\n partition: " << p.partition
<< "\n initial distribution partitions: "
<< p.initialDistributionPartitions
<< "\n used tiles: " << product(p.partition.asStdVector())
<< "\n exchange plan: " << p.exchangePlan
<< "\n no. of non-zero elements per bucket: " << p.nzElemsPerBucket
<< "\n no. of meta-info elements per bucket (forward): "
<< p.fwdMetaInfoElemsPerBucket
<< "\n no. of meta-info elements per bucket (grad-a): "
<< p.gradAMetaInfoElemsPerBucket << "\n use dense operation:" << p.useDense
<< "\n";
return os;
}
std::array<std::vector<std::size_t>, 3>
getPartitionStartIndices(const popsparse::dynamic::FullyConnectedParams ¶ms,
const Plan &plan) {
auto createSplit = [](unsigned size, unsigned partitionSize,
unsigned grainSize) {
auto grains = poplibs_support::ceildiv(size, grainSize);
std::vector<std::size_t> split;
const auto grainsPerPartition = ceildiv(grains, partitionSize);
for (unsigned i = 0; i != partitionSize; ++i) {
const auto tileBegin = i * grainsPerPartition * grainSize;
split.push_back(tileBegin);
}
return split;
};
auto xSplits = createSplit(params.getOutputChannelsPerGroup(),
plan.partition.x, plan.method.grouping.x);
auto ySplits = createSplit(params.getInputChannelsPerGroup(),
plan.partition.y, plan.method.grouping.y);
auto zSplits = createSplit(params.getBatchSize(), plan.partition.z,
plan.method.grouping.z);
return {xSplits, ySplits, zSplits};
}
std::tuple<Plan, Cost> getPlan(const Target &target, const Type &inputType,
const FullyConnectedParams ¶ms,
const OptionFlags &optionFlags,
PlanningCache *cache) {
// TODO: Verify some basic things about the input.
const auto &options = parseOptionFlags(optionFlags);
auto cacheImpl = cache ? cache->impl.get() : nullptr;
PlanningCacheImpl::Key key(params, options);
if (cacheImpl) {
auto &plans = cacheImpl->plans;
auto match = plans.find(key);
if (match != plans.end()) {
return match->second;
}
}
auto planAndCost = runPlanner(target, inputType, params, options);
if (cacheImpl) {
cacheImpl->plans.emplace(key, planAndCost);
}
return planAndCost;
}
unsigned int getTotalMetaInfoElemsPerBuckets(const Plan &plan) {
return plan.fwdMetaInfoElemsPerBucket +
(plan.sharedBuckets() ? 0 : plan.gradAMetaInfoElemsPerBucket);
}
} // end namespace fullyconnected
} // end namespace popsparse
|
alibaba/FederatedScope | federatedscope/core/message.py | import sys
import json
import numpy as np
from federatedscope.core.proto import gRPC_comm_manager_pb2
class Message(object):
"""
The data exchanged during an FL course are abstracted as 'Message' in FederatedScope.
A message object includes:
msg_type: The type of message, which is used to trigger the corresponding handlers of server/client
sender: The sender's ID
receiver: The receiver's ID
state: The training round of the message, which is determined by the sender and used to filter out the outdated messages.
strategy: redundant attribute
"""
def __init__(self,
msg_type=None,
sender=0,
receiver=0,
state=0,
content=None,
strategy=None):
self._msg_type = msg_type
self._sender = sender
self._receiver = receiver
self._state = state
self._content = content
self._strategy = strategy
@property
def msg_type(self):
return self._msg_type
@msg_type.setter
def msg_type(self, value):
self._msg_type = value
@property
def sender(self):
return self._sender
@sender.setter
def sender(self, value):
self._sender = value
@property
def receiver(self):
return self._receiver
@receiver.setter
def receiver(self, value):
self._receiver = value
@property
def state(self):
return self._state
@state.setter
def state(self, value):
self._state = value
@property
def content(self):
return self._content
@content.setter
def content(self, value):
self._content = value
@property
def strategy(self):
return self._strategy
@strategy.setter
def strategy(self, value):
self._strategy = value
def transform_to_list(self, x):
if isinstance(x, list) or isinstance(x, tuple):
return [self.transform_to_list(each_x) for each_x in x]
elif isinstance(x, dict):
for key in x.keys():
x[key] = self.transform_to_list(x[key])
return x
else:
if hasattr(x, 'tolist'):
return x.tolist()
else:
return x
def msg_to_json(self, to_list=False):
if to_list:
self.content = self.transform_to_list(self.content)
json_msg = {
'msg_type': self.msg_type,
'sender': self.sender,
'receiver': self.receiver,
'state': self.state,
'content': self.content,
'strategy': self.strategy,
}
return json.dumps(json_msg)
def json_to_msg(self, json_string):
json_msg = json.loads(json_string)
self.msg_type = json_msg['msg_type']
self.sender = json_msg['sender']
self.receiver = json_msg['receiver']
self.state = json_msg['state']
self.content = json_msg['content']
self.strategy = json_msg['strategy']
def create_by_type(self, value, nested=False):
if isinstance(value, dict):
m_dict = gRPC_comm_manager_pb2.mDict()
for key in value.keys():
m_dict.dict_value[key].MergeFrom(
self.create_by_type(value[key], nested=True))
if nested:
msg_value = gRPC_comm_manager_pb2.MsgValue()
msg_value.dict_msg.MergeFrom(m_dict)
return msg_value
else:
return m_dict
elif isinstance(value, list) or isinstance(value, tuple):
m_list = gRPC_comm_manager_pb2.mList()
for each in value:
m_list.list_value.append(self.create_by_type(each,
nested=True))
if nested:
msg_value = gRPC_comm_manager_pb2.MsgValue()
msg_value.list_msg.MergeFrom(m_list)
return msg_value
else:
return m_list
else:
m_single = gRPC_comm_manager_pb2.mSingle()
if type(value) in [int, np.int32]:
m_single.int_value = value
elif type(value) in [str]:
m_single.str_value = value
elif type(value) in [float, np.float32]:
m_single.float_value = value
else:
raise ValueError(
'The data type {} has not been supported.'.format(
type(value)))
if nested:
msg_value = gRPC_comm_manager_pb2.MsgValue()
msg_value.single_msg.MergeFrom(m_single)
return msg_value
else:
return m_single
def build_msg_value(self, value):
msg_value = gRPC_comm_manager_pb2.MsgValue()
if isinstance(value, list) or isinstance(value, tuple):
msg_value.list_msg.MergeFrom(self.create_by_type(value))
elif isinstance(value, dict):
msg_value.dict_msg.MergeFrom(self.create_by_type(value))
else:
msg_value.single_msg.MergeFrom(self.create_by_type(value))
return msg_value
def transform(self, to_list=False):
if to_list:
self.content = self.transform_to_list(self.content)
splited_msg = gRPC_comm_manager_pb2.MessageRequest() # map/dict
splited_msg.msg['sender'].MergeFrom(self.build_msg_value(self.sender))
splited_msg.msg['receiver'].MergeFrom(
self.build_msg_value(self.receiver))
splited_msg.msg['state'].MergeFrom(self.build_msg_value(self.state))
splited_msg.msg['msg_type'].MergeFrom(
self.build_msg_value(self.msg_type))
splited_msg.msg['content'].MergeFrom(self.build_msg_value(
self.content))
return splited_msg
def _parse_msg(self, value):
if isinstance(value, gRPC_comm_manager_pb2.MsgValue) or isinstance(
value, gRPC_comm_manager_pb2.mSingle):
return self._parse_msg(getattr(value, value.WhichOneof("type")))
elif isinstance(value, gRPC_comm_manager_pb2.mList):
return [self._parse_msg(each) for each in value.list_value]
elif isinstance(value, gRPC_comm_manager_pb2.mDict):
return {
k: self._parse_msg(value.dict_value[k])
for k in value.dict_value
}
else:
return value
def parse(self, received_msg):
self.sender = self._parse_msg(received_msg['sender'])
self.receiver = self._parse_msg(received_msg['receiver'])
self.msg_type = self._parse_msg(received_msg['msg_type'])
self.state = self._parse_msg(received_msg['state'])
self.content = self._parse_msg(received_msg['content'])
def count_bytes(self):
"""
calculate the message bytes to be sent/received
:return: tuple of bytes of the message to be sent and received
"""
from pympler import asizeof
download_bytes = asizeof.asizeof(self.content)
upload_cnt = len(self.receiver) if isinstance(self.receiver,
list) else 1
upload_bytes = download_bytes * upload_cnt
return download_bytes, upload_bytes
|
NASARace/race | race-swing/src/main/scala/gov/nasa/race/swing/FileSelectionPanel.scala | /*
* Copyright (c) 2016, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The RACE - Runtime for Airspace Concept Evaluation platform is 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.
*/
package gov.nasa.race.swing
import java.io.File
import javax.swing.filechooser.FileFilter
import Style._
import gov.nasa.race.swing.GBPanel.{Anchor, Fill}
import scala.swing._
import scala.swing.event.{EditDone, SelectionChanged}
object FileSelectionPanel extends SimpleSwingApplication {
val top = new MainFrame {
title = "FSP Test"
contents = new FileSelectionPanel("config:")( f =>
println(s"@@ selected file: $f")
).styled()
}
}
/**
* a panel that allows selection of files either through a
* text ComboBox or a button that triggers a FileChooser dialog
*/
class FileSelectionPanel(labelText: String, optDir: Option[String]=None, optExt: Option[String]=None)
(var action: (File)=>Any = f=>{}) extends GBPanel {
var history = List.empty[String]
var fileSelection: Option[File] = None
val label = new Label(labelText).styled("labelFor")
val textField = new TextField(20).styled("stringField")
val dir = new File(if (optDir.isDefined) optDir.get else System.getProperty("user.dir"))
val chooser = new FileChooser(dir)
if (optExt.isDefined){
chooser.fileFilter = new FileFilter {
override def getDescription: String = "HOCON, JSON or Java properties file"
override def accept(f: File): Boolean = f.getPath.endsWith(optExt.get)
}
}
val openButton = new Button( Action("Open"){
chooser.showOpenDialog(FileSelectionPanel.this) match {
case FileChooser.Result.Approve =>
val f = chooser.selectedFile
textField.text = f.getPath
action(f)
case FileChooser.Result.Cancel => // ignore
}
}).styled()
val c = new Constraints( gridy=0, fill=Fill.Horizontal, anchor=Anchor.West, ipadx=10, insets=(5,5,5,5))
layout(label) = c.weightx(0)
layout(textField) = c.weightx(1.0f)
layout(openButton) = c.weightx(0)
reactions += {
case EditDone(`textField`) =>
val path = textField.text
val f = new File(path)
if (f.isFile) {
fileSelection = Some(f)
history = path :: history
action(f)
} else {
// report error
println(s"@@ not a file: $path")
}
}
def onSelect(a: (File)=>Any) = action = a
}
|
yjx0003/UBUGrades | src/main/java/es/ubu/lsi/ubumonitor/view/chart/risk/RiskBar.java | package es.ubu.lsi.ubumonitor.view.chart.risk;
import java.io.IOException;
import java.text.MessageFormat;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import es.ubu.lsi.ubumonitor.controllers.Controller;
import es.ubu.lsi.ubumonitor.controllers.MainController;
import es.ubu.lsi.ubumonitor.model.EnrolledUser;
import es.ubu.lsi.ubumonitor.model.LastActivity;
import es.ubu.lsi.ubumonitor.model.LastActivityFactory;
import es.ubu.lsi.ubumonitor.util.I18n;
import es.ubu.lsi.ubumonitor.util.JSArray;
import es.ubu.lsi.ubumonitor.util.JSObject;
import es.ubu.lsi.ubumonitor.view.chart.ChartType;
import es.ubu.lsi.ubumonitor.view.chart.Plotly;
public class RiskBar extends Plotly {
public RiskBar(MainController mainController) {
this(mainController, ChartType.RISK_BAR);
}
public RiskBar(MainController mainController, ChartType chartType) {
super(mainController, chartType);
useGeneralButton = false;
useLegend = true;
useGroupButton = false;
}
@Override
public String getOnClickFunction() {
return Plotly.MULTIPLE_USER_ON_CLICK_FUNCTION;
}
@Override
public void createData(JSArray data) {
List<EnrolledUser> selectedEnrolledUser = getSelectedEnrolledUser();
ZonedDateTime lastUpdate = Controller.getInstance()
.getUpdatedCourseData();
Map<LastActivity, List<EnrolledUser>> lastCourseAccess = new TreeMap<>(
Comparator.comparing(LastActivity::getIndex));
Map<LastActivity, List<EnrolledUser>> lastAccess = new TreeMap<>(Comparator.comparing(LastActivity::getIndex));
for (EnrolledUser user : selectedEnrolledUser) {
lastCourseAccess
.computeIfAbsent(LastActivityFactory.DEFAULT.getActivity(user.getLastcourseaccess(), lastUpdate),
k -> new ArrayList<>())
.add(user);
lastAccess
.computeIfAbsent(LastActivityFactory.DEFAULT.getActivity(user.getLastaccess(), lastUpdate),
k -> new ArrayList<>())
.add(user);
}
List<LastActivity> lastActivities = LastActivityFactory.DEFAULT.getAllLastActivity();
data.add(createTrace(I18n.get("label.lastcourseaccess"), selectedEnrolledUser.size(), lastCourseAccess,
lastActivities, 0.2));
data.add(createTrace(I18n.get("label.lastaccess"), selectedEnrolledUser.size(), lastAccess, lastActivities,
0.5));
}
public JSObject createTrace(String name, int nUsers, Map<LastActivity, List<EnrolledUser>> lastAccess,
List<LastActivity> lastActivities, double opacity) {
JSObject trace = new JSObject();
JSArray color = new JSArray();
JSArray y = new JSArray();
JSArray x = new JSArray();
x.addAllWithQuote(lastActivities);
JSArray usersArray = new JSArray();
JSArray usersIdArray = new JSArray();
JSArray text = new JSArray();
for (LastActivity lastActivity : lastActivities) {
color.add(colorToRGB(lastActivity.getColor(), opacity));
StringBuilder users = new StringBuilder();
JSArray usersId = new JSArray();
List<EnrolledUser> listUsers = lastAccess.computeIfAbsent(lastActivity, k -> Collections.emptyList());
y.add(listUsers.size());
listUsers.forEach(e -> {
usersId.add(e.getId());
users.append(e.getFullName());
users.append("<br>");
});
usersArray.addWithQuote(users);
usersIdArray.add(usersId);
text.add("'<b>'+toPercentage(" + listUsers.size() + "," + nUsers + ")+'</b>'");
}
trace.put("type", "'bar'");
trace.putWithQuote("name", name);
trace.put("x", x);
trace.put("y", y);
JSObject marker = new JSObject();
marker.put("color", color);
trace.put("marker", marker);
trace.put("userids", usersIdArray);
trace.put("customdata", usersArray);
trace.put("text", text);
trace.put("textposition", "'auto'");
trace.put("hovertemplate", "'<b>%{x}<br>%{data.name}:</b> %{y}<br><br>%{customdata}<extra></extra>'");
return trace;
}
@Override
public void createLayout(JSObject layout) {
boolean horizontalMode = getConfigValue("horizontalMode", false);
JSObject axis = new JSObject();
axis.put("showgrid", true);
axis.put("tickmode", "'array'");
axis.put("type", "'category'");
axis.put("tickson", "'boundaries'");
JSObject xaxis = horizontalMode ? new JSObject() : axis;
JSObject yaxis = horizontalMode ? axis : new JSObject();
if (horizontalMode) {
Plotly.defaultAxisValues(xaxis, getYAxisTitle(), "");
Plotly.defaultAxisValues(yaxis, getXAxisTitle(), null);
yaxis.putAll(axis);
layout.put("xaxis", yaxis);
layout.put("yaxis", xaxis);
} else {
Plotly.defaultAxisValues(xaxis, getXAxisTitle(), null);
Plotly.defaultAxisValues(yaxis, getYAxisTitle(), "");
xaxis.putAll(axis);
layout.put("xaxis", xaxis);
layout.put("yaxis", yaxis);
}
layout.put("barmode", "'group'");
layout.put("hovermode", "'closest'");
}
@Override
public void exportCSV(String path) throws IOException {
ZonedDateTime updateTime = Controller.getInstance()
.getUpdatedCourseData();
try (CSVPrinter printer = new CSVPrinter(getWritter(path), CSVFormat.DEFAULT.withHeader("userid", "fullname",
"lastCourseAccess", "lastMoodleAcess", "diffCourseAccess", "diffMoodleAccess"))) {
for (EnrolledUser enrolledUser : getSelectedEnrolledUser()) {
printer.printRecord(enrolledUser.getId(), enrolledUser.getFullName(),
Controller.DATE_TIME_FORMATTER.format(enrolledUser.getLastcourseaccess()
.atZone(ZoneId.systemDefault())),
Controller.DATE_TIME_FORMATTER.format(enrolledUser.getLastaccess()
.atZone(ZoneId.systemDefault())),
ChronoUnit.DAYS.between(enrolledUser.getLastcourseaccess(), updateTime),
ChronoUnit.DAYS.between(enrolledUser.getLastaccess(), updateTime));
}
}
}
@Override
public String getXAxisTitle() {
return MessageFormat.format(super.getXAxisTitle(), Controller.getInstance()
.getUpdatedCourseData()
.format(Controller.DATE_TIME_FORMATTER));
}
}
|
Icohedron/Alexandria | app/src/main/java/ca/ualberta/CMPUT3012019T02/alexandria/model/holder/BookViewHolder.java | <reponame>Icohedron/Alexandria
package ca.ualberta.CMPUT3012019T02.alexandria.model.holder;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import ca.ualberta.CMPUT3012019T02.alexandria.R;
/**
* Sets up item ID for RecyclerViews
*/
public class BookViewHolder extends RecyclerView.ViewHolder{
public RelativeLayout itemBook;
public ImageView ivCover;
public TextView tvTitle;
public TextView tvAuthor;
public TextView tvISBN;
public ImageView ivStatus;
/**
* Instantiates a new Book view holder.
*
* @param itemView the list view for the books
*/
public BookViewHolder(@NonNull View itemView) {
super(itemView);
itemBook = itemView.findViewById(R.id.item_book);
ivCover = itemView.findViewById(R.id.item_book_cover);
tvTitle = itemView.findViewById(R.id.item_book_title);
tvAuthor = itemView.findViewById(R.id.item_book_author);
tvISBN = itemView.findViewById(R.id.item_book_isbn);
ivStatus = itemView.findViewById(R.id.item_book_status);
}
}
|
neilneil0/bcstack-core | bluetooth/include/hci.h | <filename>bluetooth/include/hci.h
/*
Copyright 2013-2014 bcstack.org
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.
*/
#ifndef _HCI_H_
#define _HCI_H_
#define BT_COMMAND_CHANNEL 1
#define BT_EVENT_CHANNEL 2
#define BT_ACL_IN_CHANNEL 3
#define BT_ACL_OUT_CHANNEL 4
void hci_setup(void);
void hci_shutdown(void);
void hci_write_later(u8 channel);
void hci_write(u8 channel, u16 size);
void hci_loop(void);
void hci_handle_transport_event(u8 channel, u8* buffer, u16 size);
void bt_uart_tx(const u8* buffer, u16 len);
void bt_uart_rx(u8* buffer, u16 len);
void bt_uart_tx_done();
void bt_uart_rx_done();
#endif //_HCI_H_
|